text
stringlengths
64
81.1k
meta
dict
Q: 木兰辞 original poem I was trying to read the original 木兰辞 poem. But I found two versions of it on the internet. One line reads: 愿借明驼千里足,送儿还故乡。 In the other version it's: 愿驰千里足,送儿还故乡。 Which one is the original one? Thanks! A: Both are correct, you might have noticed in many ancient poems, some characters or even an entire sentence could have different versions, which are both or all correct. Some readers may favour one version while other may favour another. There are many reasons for this to happen. First, in ancient times, there is no easy way of copying and pasting, reproduction is thus relayed on people if you do not happen to have the original printing template, which could introduce flaws. Moreover, the author could have made adjustment to his or her work many times, therefore different versions could be in circulating contemporarily. There could be many other reasons, please see this post. By the way, in case if you are curious, please refer to this webpage for the meaning of 明驼。
{ "pile_set_name": "StackExchange" }
Q: MySql Query Help needed I have a table with comments. These comments are related to another table of questions, through 1-to-many relation, i.e. 1 question to many comments. Now, I want a list of 5 questions with the maximum number of comment counts (in succession of course). So, my query should return something like: Question Id:4 with 30 comments Question Id:2 with 27 comments Question Id:11 with 22 comments Question Id:5 with 15 comments Question Id:14 with 10 comments Can I achieve this through 1 query or multiple ones? And how? A: This query gets the data you need. You can handle the output formatting as desired. select questionid, count(commentid) as commentcount from question q inner join comment c on q.questionid = c.questionid group by questionid order by commentcount desc limit 5;
{ "pile_set_name": "StackExchange" }
Q: Using amsthm to number examples - how do I account for altered examples (i.e. 1', 1'', etc.) I have sought long and hard for a solution to this and experimented with a combination of https://tex.stackexchange.com/a/43351 and https://tex.stackexchange.com/a/443, but could not get it to work. I would like the following to happen: I define an example somewhere in the text like this \begin{shortex}\label{Example1} lorem ipsum \end{shortex} Later in the document, I introduce an altered version of the example (Example 1'), if possible using cleveref Here's my code before any of that happens: \documentclass[letterpaper,12pt]{article} %Math symbol packages \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} %Add several formatting packages \usepackage{paralist} \usepackage[colorlinks=true,hidelinks]{hyperref} \usepackage{cleveref} \crefdefaultlabelformat{[#2#1#3]} %Add theorem support \usepackage{amsthm} %Define example \theoremstyle{definition} \newtheorem{ex}{Example} \renewcommand{\theex}{\arabic{ex}} %Access package-internal code that uses @ \makeatletter % Define examples without linebreaks \newenvironment{shortex} {\refstepcounter{ex}\textsc{Example~}\theex:\normalfont}%\begin{shortex} {}%\end{shortex} \makeatother %Define cref for Examples \crefname{ex}{}{examples} \creflabelformat{ex}{(#2#1#3)} \begin{document} \begin{shortex}\label{ex1} This is example 1 \end{shortex} \end{document} I have tried getting rid of shortex and simply using {ex}, but this still wouldn't work. Thanks for any help y'all can give! EDIT (djupp): I also found David Carlisle's https://tex.stackexchange.com/a/69918/27148 now, which would probably work great if I could incorporate the suggested use of \ref (or \cref) to refer back to an older example. (I.e., it's possible that I would want to restate example 1 after I've already stated 2,3,4,5,etc.) A: I don't know if this is what you're looking for; I define a varex environment for stating a variant of an example, computing its number via the label of the original one and a suffix that is, by default, a prime, but another one can be specified as optional argument. \documentclass[letterpaper,12pt]{article} %Math symbol packages \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} %Add theorem support \usepackage{amsthm} %Expanded references \usepackage{refcount} %Add several formatting packages \usepackage{paralist} \usepackage[colorlinks=true,hidelinks]{hyperref} \usepackage{cleveref} \crefdefaultlabelformat{[#2#1#3]} %Define example \theoremstyle{definition} \newtheorem{ex}{Example} \newcounter{Hex} % a new counter for hyperref %Access package-internal code that uses @ \makeatletter \g@addto@macro\ex{\stepcounter{Hex}} % use Hex for making anchors % Define examples without linebreaks \newenvironment{varex}[2][$'$] {\edef\theex{\getrefnumber{#2}#1}% \addtocounter{ex}{-1} \ex} {\endex} \makeatother %Define cref for Examples \crefname{ex}{example}{examples} \creflabelformat{ex}{(#2#1#3)} \begin{document} \begin{ex}\label{first} An example. \end{ex} \begin{ex}\label{second} Another one. \end{ex} \begin{varex}{first}\label{first'} This is example 1$'$. \end{varex} \begin{varex}[$''$]{first}\label{first''} This is example 1$''$. \end{varex} References: \cref{first} \cref{second} \cref{first'} \cref{first''} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Polymer animation get Keyframes error I have created a simple animation for my elements, but instead of cool effects I get Uncaught TypeError: Keyframes must be null or an array of keyframes. <script> Polymer({ is: 'marvin-user-entrance', behaviors: [ Polymer.NeonAnimationRunnerBehavior ], properties: { animationConfig: { value: function() { return { 'fade-in':[{name: 'fade-in-animation', node: this}], 'fade-out':[{name: 'fade-out-animation', node: this}] } } } }, animate: function () { this.playAnimation('fade-out'); }, ready: function () { this.$.auth.animate(); } }); </script> It seems that it's not a problem of Polymer itself, but it is somewhere in my code or web animation node... A: You should be calling this.animate() instead of this.$.auth.animate() as the animate function is defined inside this Polymer element. If you want to animate the auth element only, change the node to point to this.$.auth instead of the whole element, like below - node: this.$.auth
{ "pile_set_name": "StackExchange" }
Q: How to escape UNICODE string in python (to javascript escape) I have the following string "◣⛭◣◃✺▲♢" and I want to make that string into "\u25E3\u26ED\u25E3\u25C3\u273A\u25B2\u2662". Exactly the same as this site does https://mothereff.in/js-escapes I was wondering if this is possible in python. I have tried allot of stuff from the unicode docs for python but failed miserably. Example of what I tried before: #!/usr/bin/env python # -*- coding: latin-1 -*- f = open('js.js', 'r').read() print(ord(f[:1])) help would be appreciated! A: Considering you're using Python 3: unicode_string="◣⛭◣◃✺▲♢" byte_string= unicode_string.encode('ascii', 'backslashreplace') print(byte_string) See codecs module documentation for more infotmation. However, to work with JavaScript notation, there's a special module json, and then you could achieve the same thing: import json unicode_string="◣⛭◣◃✺▲♢" json_string=json.dumps(unicode_string) print(json_string) A: If you're in python 2, then I'd suspect you're getting something like this: >>> s = "◣⛭◣◃✺▲♢" >>> s[0] '\xe2' To get to the unicode code points in a UTF-8 encoded file (or buffer), you'll need to decode it into a python unicode object first (otherwise you'll see the bytes that make up the UTF-8 encoding). >>> s_utf8 = s.decode('utf-8') >>> s_utf8[0] u'\u25e3' >>> ord(s_utf8[0]) 9699 >>> hex(ord(s_utf8[0])) '0x25e3' In your case, you can go straight from the ord() to a literal unicode escape with something like this: >>> "\\u\x" % (ord(s_utf8[0])) '\\u25e3' Or convert the entire string in one go with a list comprehension: >>> ''.join(["\\u%04x" % (ord(c)) for c in s_utf8]) '\\u25e3\\u26ed\\u25e3\\u25c3\\u273a\\u25b2\\u2662' Of course, when you're doing the conversion this way, you're going to display the code points for all the characters in the string. You'll have to decide which code points to show, or the ABCs will be escaped too: >>> ''.join(["\\u%04x" % (ord(c)) for c in u"ABCD"]) '\\u0041\\u0042\\u0043\\u0044' Or, just use georg's suggestion to let python figure all that out for you.
{ "pile_set_name": "StackExchange" }
Q: Play a Track Using Spotify Web API I have the artist, track, and album from LastFM API stored in a widget. I would like to play a 30 second snippet of the song from Spotify when a user clicks play. Is it possible to do this? I'm struggling to find a way.. Especially without user authentication / permissions. Spotify App API: Play specific track from album This looks promising, but I'm not sure if it's what I'm talking about... If someone could point me in the right direction (what API calls to use), that would be great! I can figure out the rest from there. A: In the Spotify API documentation I found a link to this github repo that uses the 30-sec API calls to build a web player you can check out here. I believe you want the track API: preview_url      string      A link to a 30 second preview (MP3 format) of the track.
{ "pile_set_name": "StackExchange" }
Q: I have a question about the \displaystyle command I have a question about the \displaystyle command. So every time I write a quiz or test, in order to make a fraction, limit, integral, etc. look decent, I have to do something like, $\displaystyle\frac{2}{3}$ or $\displaystyle\int_{0}^{\infty} e^{-5x}dx$. If I do not input this command, the text is absurdly small. Is there a package or command I can put in my template so that it just automatically assumes to do the \displaystyle command? I run MiKTeX on a Windows computer. I have decent LaTeX knowledge, but am foggy in templates. A: Christian has already shown examples of better markup, but I thought I'd answer your "absurdly small" comment. $ is designed for inline math, that is, mathematics set within a paragraph of text. It attempts (not always successfully) to fit within the standard baseline spacing of a paragraph. As the example shows, sometimes even the default settings are not cramped enough and the paragraph baseline is affected, but displaystyle opens up the paragraph with wildly inconsistent spacing making it more or less unreadable as a block of text. \documentclass{article} \usepackage{amsmath} \begin{document} A paragraph of text with $x^2+y^2=z^2$ some math(s). Other examples might be $\frac{1}{2}\int_0^nx dx$ and $\sqrt{x}$. A paragraph of text with $x^2+y^2=z^2$ some math(s). Other examples might be $\frac{1}{2}\int_0^nx dx$ and $\sqrt{x}$. A paragraph of text with $x^2+y^2=z^2$ some math(s). Other examples might be $\frac{1}{2}\int_0^nx dx$ and $\sqrt{x}$. \bigskip \hrule \bigskip \everymath{\displaystyle} A paragraph of text with $x^2+y^2=z^2$ some math(s). Other examples might be $\frac{1}{2}\int_0^nx dx$ and $\sqrt{x}$. A paragraph of text with $x^2+y^2=z^2$ some math(s). Other examples might be $\frac{1}{2}\int_0^nx dx$ and $\sqrt{x}$. A paragraph of text with $x^2+y^2=z^2$ some math(s). Other examples might be $\frac{1}{2}\int_0^nx dx$ and $\sqrt{x}$. \end{document} A: I don't really recommend this, but \everymath{\displaystyle} is a way to achieve the display style for math content, i.e. for inline math content as well. In my opinion the usage of the various align like environments should be preferred or \[...\]. Please consider also \dfrac{2}{3} for example as a 'nicer' way of displaying fractions. As Zarko stated in comment: Using \displaystyle all the way will increase the spacing between the lines and leaves a disrupted look of the page. Again: Don't do it. \documentclass{book} \usepackage{mathtools} \begin{document} $E=mc^2 = \frac{mc^2}{1}$ $\frac{2}{3}$ or $\int_{0}^{\infty} e^{-5x}dx$. or \[ \frac{2}{3} \] or \[ \int_{0}^{\infty} e^{-5x}dx \] \everymath{\displaystyle} $\frac{2}{3}$ or $\int_{0}^{\infty} e^{-5x}dx$. \begin{align*} \int_{0}^{\infty} e^{-5x}\mathrm{d}x &= \dots \end{align*} $\dfrac{2}{3}$ \end{document}
{ "pile_set_name": "StackExchange" }
Q: Did "Where the really hard problems are" hold up? What are current ideas on the subject? I found this paper to be very interesting. To summarize: it discusses why in practice you rarely find a worst-case instance of a NP-complete problem. The idea in the article is that instances usually are either very under- or very overconstrained, both of which are relatively easy to solve. It then proposes for a few problems a measure of 'constrainedness'. Those problems appear to have a 'phase transition' from 0 likelihood of a solution to 100% likelihood. It then hypothesizes: That all NP-complete (or even all NP-problems) problems have a measure of 'constrainedness'. That for each NP-complete problem, you can create a graph of the probability of a solution existing as a function of the 'constrainedness'. Moreover, that graph will contain a phase-transition where that probability quickly and dramatically increases. The worst case examples of the NP-complete problems lie in that phase-transition. The fact whether a problem lies on that phase-transition remains invariant under transformation of one NP-complete problem to another. This paper was published in 1991. My question is was there any follow-up research on these ideas the last 25 years? And if so, what is the current mainstream thinking on them? Were they found correct, incorrect, irrelevant? A: Here is a rough summary of the status based on a presentation given by Vardi at a Workshop on Finite and Algorithmic Model Theory (2012): It was observed that hard instances lie at the phase transition from under- to over-constrained region. The fundamental conjecture is that there is strong connection between phase-transitions and computational complexity of NP problems. Achlioptas–Coja-Oghlan, found that there is a density in the satisfiabe region where the solution space shatters into exponentially many small clusters. Vinay Deolalikar based his famous attempt to proof $P \ne NP$ on the assumption that shattering implies computational hardness. Deolalikar’s Proof was refuted by the fact that XOR-SAT is in $P$ and it shatters. Therefore, shattering can not be used to prove computational hardness. The current mainstream thinking seems to be (as stated by Vardi) that phase-transitions are not intrinsically connected to computational complexity. Finally, Here is an article published in Nature which investigates the connection between phase-transitions and computational hardness of K-SAT. A: Yes, there has been a lot of work since Cheeseman, Kanefsky and Taylor's 1991 paper. Doing a search for reviews of phase transitions of NP-Complete problems will give you plenty of results. One such review is Hartmann and Weigt [1]. For a higher level introduciton, see Brian Hayes American Scientist articles [2] [3]. Cheesemen, Kanefsky and Taylor's 1991 paper is an unfortunate case of computer scientists not paying attention to the mathematics literature. In Cheeseman, Kanefsky and Taylor's paper, they identified the Hamiltonian Cycle as having a phase transition with a pickup in search cost near the critical threshold. The random graph model they used was Erdos-Renyi random graph (fixed edge probability or equivalently Gaussian degree distribution). This case was well studied before Cheeseman et all's 1991 paper with known almost sure polynomial time algorithms for this class of graph, even at or near the critical threshold. Bollobas's "Random Graphs" [4] is a good reference. The original proof I believe was presented by Angliun and Valiant [5] with further improvements by Bollobas, Fenner and Frieze [6]. After Cheeseman, Kanefsky and Taylor, Culberson and Vandegriend [7] published a paper giving an algorithm that in practice performed extremely well for all Erdos-Renyi random graphs, even near the critical threshold. The phase transition for Hamiltonian Cycles in random Erdos-Renyi random graphs exists in the sense that there is a rapid transition of the probability of finding a solution but this does not translate to an increase in "intrinsic" complexity of finding Hamiltonian Cycles. There are almost sure polynomial time algorithms for finding Hamiltonian Cycles in Erdos-Renyi random graphs, even at the critical transition, both in theory and in practice. Survey propagation [8] has had good success in finding satisfiable instances for random 3-SAT very near the critical threshold. My current knowledge is a little rusty so I'm not sure if there's been any large progress of finding "efficient" algorithms for unsatisfiable cases near the critical threshold. 3-SAT, as far as I know, is one of the cases where it's "easy" to solve if it's satisfiable and near the critical threshold but unknown (or hard?) in the unsatisfiable case near the critical threshold. My knowledge is a bit dated now but the last time I looked at this subject in depth, there were a few things that stood out to me: Hamiltonian Cycle is "easy" for Erdos-Renyi random graphs. Where are the hard problems for it? Number Partition should be solvable when very far in the almost sure probability 0 or 1 region but no efficient algorithms (to my knowledge) exist for even moderate instance sizes (1000 numbers of 500 bits each is, as far as I know, completely intractable with state of the art algorithms). [9] [10] 3-SAT is "easy" for satisfiable instances near the critical threshold, even for huge instance sizes (millions of variables) but hard for unsatisfiable instances near the critical threshold. I hesitate to include it here as I have not published any peer reviewed papers from it but I did write my thesis on the subject. The main idea is that a possible class of random ensembles (Hamiltonian Cycles, Number Partition Problem, etc.) that are "intrinsically hard" are ones that have a "scale invariance" property. Levy-stable distributions are one of the more natural distributions with this quality, having power law tails, and one can choose random instances from NP-Complete ensembles that somehow incorporate the Levy-stable distribution. I gave some weak evidence that intrinsically difficult Hamiltonian Cycle instances can be found if random graphs are chosen with a Levy-stable degree distribution instead of a Normal distribution (i.e. Erdos-Renyi). If nothing else it will at least give you a starting point for some literature review. [1] A. K. Hartmann and M. Weigt. Phase Transitions in Combinatorial Optimization Problems: Basics, Algorithms and Statistical Mechanics. Wiley-VCH, 2005. [2] B. Hayes. The easiest hard problem. American Scientist, 90(2), 2002. [3] B. Hayes. On the threshold. American Scientist, 91(1), 2003. [4] B. Bollobás. Random Graphs, Second Edition. Cambridge University Press, New York, 2001. [5] D. Angluin and L. G. Valiant. Fast probabilistic algorithms for Hamilton circuits and matchings. J. Computer, Syst. Sci., 18:155–193, 1979. [6] B. Bollobás, T. I. Fenner, and A. M. Frieze. An algorithm for finding Hamilton paths and cycles in random graphs. Combinatorica, 7:327–341, 1987. [7] B. Vandegriend and J. Culberson. The G n,m phase transition is not hard for the Hamiltonian cycle problem. J. of AI Research, 9:219–245, 1998. [8] A. Braunstein, M. Mézard, and R. Zecchina. Survey propagation: an algorithm for satisfiability. Random Structures and Algorithms, 27:201–226, 2005. [9] I. Gent and T. Walsh. Analysis of heuristics for number partitioning. Computational Intelligence, 14:430–451, 1998. [10] C. P. Schnorr and M. Euchner. Lattice basis reduction: Improved practical algorithms and solving subset sum problems. In Proceedings of Fundamentals of Computation Theory ’91, L. Budach, ed., Lecture Notes in Computer Science, volume 529, pages 68–85, 1991.
{ "pile_set_name": "StackExchange" }
Q: JQuery Validation is not working, I disabled the html form validation manually I have the below page, I was trying to use JQuery validation to validate a registration form, but it didn't work, I appreciate your input. <div id="left"> <div id="Welcome"> <h1 class="pageHeading">Eurotech Course Registeration</h1> <div class="bg"></div> <div id="form_block"> <form name="frmFindProgram" id="frmFindProgram" method="post" novalidate="novalidate" action="do-register.php?lang="> <div class="field_box"> <div class="field_lbl">Course Title</div> <div class="field_element"> <input type="text" required id="coursetitle" name="coursetitle" value="" /> <input type="hidden" id="coursecategory" name="coursecategory" value="" /> </div> </div> <div class="field_box"> <div class="field_lbl">Course Date</div> <div class="field_element"> <input type="text" required id="coursedate" name="coursedate" value="" /> </div> </div> <div class="field_box"> <div class="field_lbl">Course Place</div> <input type="radio" name="coursecity" id="coursecity" value="" />&nbsp; <input type="radio" name="coursecity" id="coursecity" value="" /> </div> <div class="field_box"> <div class="field_lbl">First Name</div> <div class="field_element"> <input type="text" required id="firstname" name="firstname" value=""/> </div> </div> <div class="field_box"> <div class="field_lbl">Last Name</div> <div class="field_element"> <input type="text" id="lastname" name="lastname" value=""/> </div> </div> <div class="field_box"> <div class="field_lbl">Position</div> <div class="field_element"> <input type="text" id="position" name="position" value=""/> </div> </div> <div class="field_box"> <div class="field_lbl">Department</div> <div class="field_element"> <input type="text" id="department" name="department" value=""/> </div> </div> <div class="field_box"> <div class="field_lbl">Company</div> <div class="field_element"> <input type="text" id="company" name="company" value=""/> </div> </div> <div class="field_box"> <div class="field_lbl">Mobile</div> <div class="field_element"> <input type="text" required id="mobile" name="mobile" value=""/> </div> </div> <div class="field_box"> <div class="field_lbl">Email</div> <div class="field_element"> <input type="email" required id="email" name="email" value=""/> </div> </div> <div class="field_box"> <div class="field_lbl">P.O Box</div> <div class="field_element"> <input type="text" id="pobox" name="pobox" value=""/> </div> </div> <div class="field_box"> <div class="field_lbl">Country</div> <div class="field_element"> <select id="country" name="country" /> <option value="Choose a country">Choose a country</option> <option value=" United States"> United States</option> <option value=" Uruguay"> Uruguay</option> <option value=" US Minor Outlying Islands"> US Minor Outlying Islands</option> <option value=" USSR (former)"> USSR (former)</option> <option value=" Uzbekistan"> Uzbekistan</option> <option value=" Vanuatu"> Vanuatu</option> <option value=" Vatican City State (Holy Sea)"> Vatican City State (Holy Sea)</option> <option value=" Venezuela"> Venezuela</option> <option value=" Viet Nam"> Viet Nam</option> <option value=" Virgin Islands (British)"> Virgin Islands (British)</option> <option value=" Virgin Islands (U.S.)"> Virgin Islands (U.S.)</option> <option value=" Wallis and Futuna Islands"> Wallis and Futuna Islands</option> <option value=" Western Sahara"> Western Sahara</option> <option value=" Yemen"> Yemen</option> <option value=" Yugoslavia"> Yugoslavia</option> <option value=" Zaire"> Zaire</option> <option value=" Zambia"> Zambia</option> <option value=" Zimbabwe"> Zimbabwe</option> </select> </div> </div> <div class="field_box"> <div class="field_lbl">&nbsp;</div> <div class="field_element"> <input type="submit" id="submitFormBtn" name="submit" value="" /> <input type="reset" id="resetFormBtn" name="reset" value="" /> </div> </div> </form> <script type="text/javascript"> $("#frmFindProgram").validate(); </script> Thanks A: Your page is broken because the code is nothing like what you've posted in your OP. On your page, you have input elements outside of the relevant form container and you should fix the broken HTML. The code in your OP is working as expected: http://jsfiddle.net/XZaA6/
{ "pile_set_name": "StackExchange" }
Q: Powershell - LIKE against an array For every file being processed, its name is being checked to satisfy the condition. For example, given the following list of filters: $excludeFiles = @" aaa.bbb ccccc.* ddddd???.exe "@ | SplitAndTrim; It should exclude a file from processing if it matches any of the lines. Trying to avoid match/regex, because this script needs to be modifiable by someone who does not know it, and there are several places where it needs to implemented. $excludedFiles and similar are defined as a here-string on purpose. It allows the end user/operator to paste a bunch of file names right from the CMD/Powershell window. It appears that Powershell does not accept -like against an array, so I cannot write like this: "ddddd000.exe" -like @("aaa.bbb", "ccccc.*", "ddddd???.exe") Did I miss an option? If it's not natively supported by Powershell, what's the easiest way to implement it? A: Here is a short version of the pattern in the accepted answer: ($your_array | %{"your_string" -like $_}) -contains $true Applied to the case in the OP one obtains PS C:\> ("aaa.bbb", "ccccc.*", "ddddd???.exe" | %{"ddddd000.exe" -like $_}) -contains $true True A: You can perform a pattern match against a collection of names, but not against a list of patterns. Try this: foreach($pattern in $excludeFiles) { if($fileName -like $pattern) {break} } Here is how it can be wrapped into a function: function like($str,$patterns){ foreach($pattern in $patterns) { if($str -like $pattern) { return $true; } } return $false; }
{ "pile_set_name": "StackExchange" }
Q: How to add a GPG key to the apt sources keyring? Ubuntu Doc page says this: It is advisable that you add the Opera GPG key. wget -qO - http://deb.opera.com/archive.key | sudo apt-key add - Where do I add that? I want to take the advice but I don't know what part of software center to add gpg keys to. A: This a a one line command to enter in terminal. See What is a terminal and how do I open and use it? To use it, you would paste the entire command in the terminal (remember to use https): wget -qO - https://deb.opera.com/archive.key | sudo apt-key add - But of course, it is daunting just copying and pasting commands without knowing what they are doing, and having no instructions on how to undo their actions, so here is a basic breakdown of the commands: wget downloads something from a server. See wget manual for Ubuntu 16.04. | is a pipline, which takes the output of one command and runs it into the input of another apt-key add adds a package key So it basically downloads the key and then adds it in one command. I tested the command and it should work. Now to verify that it worked, run this command (from this answer): apt-key list This will list the keys added and the key from Opera should be listed on the bottom like this: pub 1024D/30C18A2B 2012-10-29 [expires: 2014-10-29] uid Opera Software Archive Automatic Signing Key 2013 <packager@opera.com> sub 4096g/C528FCA9 2012-10-29 [expires: 2014-10-29] The linked answer also shows that you can remove the key if needed, using: sudo apt-key del 30C18A2B with 30C18A2B being the key-id from the list. After performing that command, and setting up the sources exactly like in your screen-shot, do: sudo apt-get update sudo apt-get install opera (note there are some random warnings, but nothing that affects the install or software center operations) And for the removal (just in case): What is the correct way to completely remove an application? So in summary: Add repository Add key with apt-key Install in terminal with apt-get Search in dash A: If you are manually adding a key from a PPA, use sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 00000000 Replacing the 00000000 with the second part of the key informed in the PPA website that you want to add. For example, if you find this line: 4096R/7BF576066 Use only the second part (no matter its size), which in this example is 7BF576066 A: Newer versions of apt also support the following: apt-key adv --fetch-keys http://deb.opera.com/archive.key This method also provides more detailed feedback as well, e.g.: gpg: key 7BD9BF62: public key "signing key <username@domain.com>" imported gpg: Total number processed: 1 gpg: imported: 1 (RSA: 1) This also has the added bonus of removing the need for additional dependencies like wget or curl.
{ "pile_set_name": "StackExchange" }
Q: Regular Expression for Special Characters in Rails I need the regex method in rails for the european language special characters like eg. é, ä, ö, ü, ß. Kindly help me. A: Regular expressions will work just fine with "special" characters. If you're wanting to match a set of special characters, you'll need to tell the expression exactly what those characters are. Your definition of "special" might not match the next guy's. For instance, if you wanted to see if a string contains any of the characters you listed above, you can do this: irb(main):001:0> word = "resumé" => "resum\303\251" irb(main):002:0> word =~ /[éäöüß]/ => 5 irb(main):003:0> word.gsub(/é/, 'e') => "resume" I hope this helps!
{ "pile_set_name": "StackExchange" }
Q: extracting words from dictionary-python I have some words and its meaning in a dictionary.I need to extract the meaning alone if I give the word.(For example,herd certain animals of the same species). How can I extract the meaning for a particular word?please help living_thing animate_thing pigfishes animal if i give pigfishes it should print animal A: with open('file.txt') as myfile: d = dict(line.rstrip().split(None, 1) for line in myfile)
{ "pile_set_name": "StackExchange" }
Q: Lie Algebra: Optimal system of one-dimensional sub-algebras of the heat equation This is a follow up question to Invariants of a PDE by Lie Symmetries, as I tried to follow the reasoning from the book Applications of Lie Groups to Differential Equations (Peter J. Olver, Example 3.13 on page 204-207). As one can show the heat equation $u_t=u_{xx}$ has the following symmetries (infinitesimal transformations): $$ v_1 = \partial_x \quad v_2 = \partial_t \quad v_3 = u\partial_u \quad v_4 = x\partial_x +2t\partial_t$$ $$ v_5 = 2t\partial_x-xu\partial_u \quad v_6 = 4tx\partial_x+4t^2\partial_t-(x^2+2t)u\partial_u$$ $$ v_{\alpha} = \alpha(x,t)\partial_u$$ Where $\alpha(x,t)$ is a solution of the heat equation. In example 3.13 the author wants to derive the optimal system of sub-algebras of the heat equation. Getting the commutator table and adjoint table is not a problem. But from there on everything is not clear to me. The author starts with the general vector $$v=a_1v_1+a_2v_2+a_3v_3+a_4v_4+a_5v_5+a_6v_6$$ and directly concludes that $\eta(v)=a_4^2-4a_2a_6$ is an invariant of the full adjoint action: $\eta(Ad g(v))=\eta(v), v \in g, g \in G$ My first question: How am I supposed to find this invariant? EDIT: I found out that this has to do with the killing form of the lie algebra. Then it is stated that: $$\tilde{v}=\sum_{i=1}^6\tilde{a}_iv_i=Ad(\exp(\alpha v_6))\circ Ad(\exp(\beta v_2))v.$$ My second question: Where does this come from? He then continues to simplify and finally gets to the set of optimal subalgebras of the heat equation $$My last question: Can someone explain what he does? Thank you alot for reading my question :). A: The invariant of full adjoint action or formally called killing form is actually solution of set of linear partial differential equations of first order. I can suggest you well written article on this topic where author has described procedure for construction of such killing form. Please see article, this article is also available on arxiv.org. The set of partial differential equations I am talking about are given by equation (13) on pp.053504-5 and their solution is killing form you are asking for. If you fully understood this paper you can definitely master the construction of optimal system.
{ "pile_set_name": "StackExchange" }
Q: MySQL WHERE Array I have been reading through, testing, and coming up short from understanding how to create a MySQL statement that matches a column against an array of values... Here's what I have... <form id="form" action="index.php" method="post"> <? $query = "SELECT Interest FROM Interests"; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)) { echo '<input type="checkbox" name="Interest[]" value="' . $row['Interest'] . '" /> ' . $row['Interest'] . '<br />'; } ?> <input id="Search" name="Search" type="submit" value="Search" /> </form> <? if (isset($_POST['Search'])) { $InterestMatches = implode(',', $_POST['Interest']); $query = "SELECT MemberID FROM MemberInterests WHERE Interest IN ( $InterestMatches )"; $result = mysql_query($query) or die(mysql_error()); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message); } while ($row = mysql_fetch_assoc($result)) { $ResultingMemberIDs[] += $row['MemberID']; } } ?> And what I always get is the same error... Unknown column 'WhateverInterest' in 'where clause' Can someone please tell me what I am doing wrong, what I need to do to correct this? A: I suggest echoing out your query, it'll help with debugging. Your query currently looks like: SELECT MemberID FROM MemberInterests WHERE Interest IN (WhateverInterest,Testing) As you can see, in the IN the values are unquoted, so they're interpreted as field names. You need to add quotes around each value in the IN. You can fix it by looping, and adding quotes around each value: foreach($_POST['Interest'] as &$intrest){ $intrest = "'$intrest'"; } $InterestMatches = implode(',', $_POST['Interest']); Or by imploding with "','", and then adding quotes before and after: $InterestMatches = "'" . implode("','", $_POST['Interest']) . "'"; P.S. You should mysql_real_escape_string each value in $_POST['Interest'] to avoid SQL injections.
{ "pile_set_name": "StackExchange" }
Q: Customize users' capabilities to change a custom post's post status I've got a somewhat unique scenario that I would appreciate some assistance with. I have a custom post type, coin, for content that is automatically created by an custom import process. I would like to restrict all users from performing certain actions on any coin posts. Specifically, I want to prevent any user from deleting a coin, changing the published status, or changing the visibility. I have registered a post type: function my_post_type() { register_post_type('coin', array( 'labels' => array( 'name' => __( 'Coins' ), 'singular_name' => __( 'Coin' ), 'view_item' => __( 'View Coin' ), 'edit_item' => __( 'Edit Coin' ), ), 'public' => true, 'menu_position' => 5, 'capability_type' => 'coin', ) ); } add_action('init', 'my_post_type'); I have specified how to handle the capabilities: function my_map_meta_cap( $caps, $cap, $user_id, $args ) { if (preg_match('/_coins?$/', $cap) == 1){ $post = get_post( $args[0] ); $post_type = get_post_type_object( $post->post_type ); $caps = array(); $disallowed = array( 'delete_coin', 'publish_coins', ); if (in_array($cap, $disallowed)){ $caps[] = 'do_not_allow'; } } return $caps; } add_filter( 'map_meta_cap', 'my_map_meta_cap', 10, 4 ); This does prevent the deletion of coin posts. This does prevent the adjustment of the visibility of a coin post. This does prevent users from publishing a coin post. However, it does not prevent users from changing a coin post status to draft or pending review. Additionally, I would like to prevent users from being able to add new coin posts as coin posts should only be created by the import routine. I have not found any information about how I could do this. Can anyone help me or am I asking too much of wordpress? A: There's not a good way to do this as the code for this section is pretty rigid. You can simply remove the elements via JavaScript. By removing (and not just hiding) the elements, you disable the functionality. You can customize the following to your needs I'm sure. Use CSS to hide the post actions inner box so the prohibited buttons never display to the screen. Without this, you will see the buttons for a moment and then they disappear. Removals of the elements Show the post publishing actions inner box again. Example: add_action('admin_head-post.php', 'remove_publishing_actions'); add_action('admin_head-post-new.php', 'remove_publishing_actions'); function remove_publishing_actions(){ global $post; if($post->post_type == 'post'){ //check user capabilities here echo "<style type='text/css'> /* hide the publishing box until we remove the elements */ #submitpost{display:none;} </style>"; echo " <script type='text/javascript'> jQuery(document).ready(function($){ //Remove whatever elements you don't want $('#misc-publishing-actions, #save-action, #delete-action').remove(); //Show the publish actions $('#submitpost').show(); }); </script> "; } } You should probably check for your custom user cap before echoing the style and script tags. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: proof that $\lim \sup (a_n · b_n) = \lim \sup a_n · \lim \sup b_n $ With $a_n, b_n \geq 0$ or non-negative for all $n$ in $\mathbb N$. Proof that for $n \to \infty $ $\lim \sup (a_n · b_n) = \lim \sup a_n · \lim \sup b_n $ , if $a_n$ and $b_n $converge. My start would be: Since $a_n$ converges and $\lim a_n = a$, so is $\lim \sup a_n = a$ and since $b_n$ converges and $\lim b_n = b$, so is $\lim \sup b_n = b$. So that, $\lim \sup (a_n · b_n) = a · b$. A: I't not correct ! take $a_n=\boldsymbol 1_{2\mathbb N}(n)$ and $b_n=\boldsymbol 1_{2\mathbb N+1}(n)$. Then $$\limsup (a_nb_n)=0$$ whereas $$\limsup(a_n)\limsup(b_n)=1.$$
{ "pile_set_name": "StackExchange" }
Q: QStringList of quazip::getFileNameList casts error by destruction in Qt Creator (qt 4.8, winxp) I wrote QuaZip* zipfile = new QuaZip; zipfile->setZipName("myzipfile.zip"); zipfile->open(QuaZip::mdUnzip); if(zipfile->isOpen()){ QStringList files = zipfile->getFileNameList(); } // here the error occurs when files is destroyed, a messagebox says Debug Assertion Failed! Expression: _CrtIsValidHeapPointer(pUserData) In the debugger I have the following function stack: 0 DbgBreakPoint ntdll 0x7c90120e 1 RtlpBreakPointHeap ntdll 0x7c96c201 2 RtlpValidateHeapEntry ntdll 0x7c96c63e 3 RtlValidateHeap ntdll 0x7c9603b0 4 HeapValidate kernel32 0x7c85f8d7 5 _CrtIsValidHeapPointer dbgheap.c 2103 0x102d1ac9 6 _free_dbg_nolock dbgheap.c 1317 0x102d0b3a 7 _free_dbg dbgheap.c 1258 0x102d09e0 8 free dbgfree.c 49 0x102d8990 9 qFree qmalloc.cpp 60 0x5e2f1d 10 QString::free qstring.cpp 1235 0x65dd22 11 QString::~QString qstring.h 880 0x5ac0d3 12 QString::`scalar deleting destructor' QuizSet 0x4120e0 13 QList<QString>::node_destruct qlist.h 433 0x412180 14 QList<QString>::free qlist.h 759 0x4115fb 15 QList<QString>::~QList<QString> qlist.h 733 0x410967 16 QStringList::~QStringList MyApp 0x414d9f 17 MyApp::myFunction myapp.cpp 561 0x420e1c ... line 433 in qlist.h is where the debugger stops: while (from != to) --to, reinterpret_cast<T*>(to)->~T(); the error occurs only if I call ::getFileNameList(), if I fill the list manual it works fine. Other operations with quazip work, I can unzip and zip data, only the getFileNameList makes trouble. EDIT: I found the cause: the quazip1.dll I used was the release version of it, only in debug-running this problem arised. So if I use the debug quazip.dll, it works fine. Annoying they're called the same, so I have to rename everytime I switch from debug to release. Anybody knows a workaround to this? A: This means that you are mixing release mode Qt DLLs with Debug ones. You have to create 2 sets of Quazip DLLs one for Release mode and one for Debug mode. You cannot mix Qt Debug DLLs with Release DLLs.
{ "pile_set_name": "StackExchange" }
Q: How do you guys feel about organization specific frameworks? I know that there should be a kind of standard for developing software but in the organization where I work for (30,000+ employees), we have a very strict framework for Java development. In my opinion such a framework is prehistoric as we are therefor running at least 10 years behind (Standard is Java 1.5 but with support 'til java 1.2). Further the framework slows down performance, user satisfaction drops and I'm writing more boilerplate code than is good for my health :-). Any suggestions on the advantages of such a framework? What are good practices for such a framework for not running behind the facts? A: What frameworks are meant to do is to simplify, or organize software development in some way that has benefit. Unfortunately, unless the framework evolves with new advances in the language, those advantages it affords are probably overtaken by events. For example, 10 years ago there were a few Java frameworks, but the one that has the widest acceptance is currently Spring. Anecdotedly, I remember hearing about Spring and thinking to myself it'll never get anywhere. I was wrong. It's important to understand what problem(s) the framework was intended to address. If your organization has to support 10 year old installs of Java for whatever reason, and the framework ensures that new code will run on old VMs--that's an important advantage to the company. However, if there are no advantages whatsoever to the old (and possibly aging) framework, then you will probably need to take some statistics. Nothing speaks to managers more than numbers. When you show them how much of your work is due to feeding the framework vs. how much time it would take to do it another way. Perhaps it would be much less political if you were to address a specific portion of the framework that if changed would buy you another x hours of productivity during the day. Frameworks need to evolve over time just as all software does. As new features come out in a language, the framework needs to be adapted to take advantage of them. The Spring of today is hardly the Spring when it was originally introduced.
{ "pile_set_name": "StackExchange" }
Q: UIAlertController conflicts with UICollectionViewFlowLayout Hey, and Merry New Year! I have a strange problem, where my extension of UICollectionViewFlowLayout conflicts with a UIAlertController, and removes its button. My app has a uicollectionviewcontroller with paging enabled, and my uicollectionviewflowlayout extension makes sure a single cell fills the whole screen // Extension to make a UICollectionViewCell fill the whole screen extension UICollectionViewFlowLayout { public override func prepareLayout() { let ratio : CGFloat = 5.6 / 8.7 let cardHeight = collectionView!.frame.height * 0.7 let cardWidth = cardHeight * ratio let spacing = (collectionView!.frame.height - cardHeight) / 2 itemSize = CGSize(width: cardWidth, height: cardHeight) minimumLineSpacing = spacing*2 sectionInset = UIEdgeInsets(top: spacing, left: 0, bottom: spacing, right: 0) } } and whenever i call a UIAlertController let alertController = UIAlertController(title: "Error", message: "Error", preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Cancel) { (action) in }) self.presentViewController(alertController, animated: true) {} i get the following message in the console 2016-01-01 21:04:48.924 Jeg Har Aldrig[10912:3649777] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x15f6c4e80 h=--& v=--& H:[_UIAlertControllerActionView:0x15f53d9e0(19.8253)]>", "<NSLayoutConstraint:0x15f67b370 H:|-(>=12)-[UIView:0x15f53e0c0] (Names: '|':_UIAlertControllerActionView:0x15f53d9e0 )>", "<NSLayoutConstraint:0x15f67b3c0 UIView:0x15f53e0c0.trailing <= _UIAlertControllerActionView:0x15f53d9e0.trailing - 12>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x15f67b3c0 UIView:0x15f53e0c0.trailing <= _UIAlertControllerActionView:0x15f53d9e0.trailing - 12> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 2016-01-01 21:04:48.926 Jeg Har Aldrig[10912:3649777] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x15f6c62a0 h=--& v=--& V:[_UIAlertControllerActionView:0x15f53d9e0(30.8)]>", "<NSLayoutConstraint:0x15f67bd50 V:[_UIAlertControllerActionView:0x15f53d9e0(>=44)]>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x15f67bd50 V:[_UIAlertControllerActionView:0x15f53d9e0(>=44)]> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 2016-01-01 21:04:48.927 Jeg Har Aldrig[10912:3649777] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x15f6c4e80 h=--& v=--& H:[_UIAlertControllerActionView:0x15f53d9e0(19.8253)]>", "<NSLayoutConstraint:0x15f67b370 H:|-(>=12)-[UIView:0x15f53e0c0] (Names: '|':_UIAlertControllerActionView:0x15f53d9e0 )>", "<NSLayoutConstraint:0x15f67b3c0 UIView:0x15f53e0c0.trailing <= _UIAlertControllerActionView:0x15f53d9e0.trailing - 12>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x15f67b3c0 UIView:0x15f53e0c0.trailing <= _UIAlertControllerActionView:0x15f53d9e0.trailing - 12> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 2016-01-01 21:04:48.927 Jeg Har Aldrig[10912:3649777] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x15f6c62a0 h=--& v=--& V:[_UIAlertControllerActionView:0x15f53d9e0(30.8)]>", "<NSLayoutConstraint:0x15f67bd50 V:[_UIAlertControllerActionView:0x15f53d9e0(>=44)]>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x15f67bd50 V:[_UIAlertControllerActionView:0x15f53d9e0(>=44)]> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 2016-01-01 21:04:48.938 Jeg Har Aldrig[10912:3649777] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x15f6c4e80 h=--& v=--& H:[_UIAlertControllerActionView:0x15f53d9e0(19.8253)]>", "<NSLayoutConstraint:0x15f67b370 H:|-(>=12)-[UIView:0x15f53e0c0] (Names: '|':_UIAlertControllerActionView:0x15f53d9e0 )>", "<NSLayoutConstraint:0x15f67b3c0 UIView:0x15f53e0c0.trailing <= _UIAlertControllerActionView:0x15f53d9e0.trailing - 12>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x15f67b3c0 UIView:0x15f53e0c0.trailing <= _UIAlertControllerActionView:0x15f53d9e0.trailing - 12> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 2016-01-01 21:04:48.940 Jeg Har Aldrig[10912:3649777] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x15f6c62a0 h=--& v=--& V:[_UIAlertControllerActionView:0x15f53d9e0(30.8)]>", "<NSLayoutConstraint:0x15f67bd50 V:[_UIAlertControllerActionView:0x15f53d9e0(>=44)]>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x15f67bd50 V:[_UIAlertControllerActionView:0x15f53d9e0(>=44)]> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. while the button on my UIAlertControllers dont appear, see the image Any suggestiens? Solution based on Mattvens answer Instead of making a extension i made a subclass: class FullCellLayout: UICollectionViewFlowLayout { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let ratio : CGFloat = 5.6 / 8.7 let cardHeight = UIScreen.mainScreen().bounds.height * 0.7 let cardWidth = cardHeight * ratio let spacing = (UIScreen.mainScreen().bounds.height - cardHeight) / 2 itemSize = CGSize(width: cardWidth, height: cardHeight) minimumLineSpacing = spacing*2 sectionInset = UIEdgeInsets(top: spacing, left: 0, bottom: spacing, right: 0) } } A: Short answer: Don't use an extension for this. Extensions in Swift are global, so your extension to UICollectionViewLayout is affecting all UICollectionViewLayout classes. Judging from the error you are getting, UIAlertController is internally using UICollectionView to layout buttons, and your extension is breaking that functionality. You should use a subclass, if you really need it, but there's no reason (that I know of) you can't initialize UICollectionViewFlowLayout, assign it to a var and use that.
{ "pile_set_name": "StackExchange" }
Q: Google Script OAuth for multiple users I've created a Google App Script that handle 2 different OAuth connections. 1- Google itself to send mail on behalf of the user and access google docs (google api console used to get keys, secret) 2- gtraxapp wich is a timesheet cloud-based app. (Script is registered, got a key/secret, etc.) The script is published as a web app. It works perfectly for my user. When logged on a different user name, I can authorize Google OAuth without providing different key/secret, and emails will be sent from the actual user. Problem happens with the 2nd app (gTrax). Authorization seems to work. Running the function inside the script to authorize lead to a screen asking for permission, gtrax then appears in the account as a registered app (could revoke access if needed). But, when running the app, I get a message saying I need permission to do this action (UrlFetchApp / simple get) My question is : Is this possible that I need to register each user to get a key/secret for everyone (and dealing with that in the script)... Or do OAuth can be registered with 1 key/secret ? In other word, are (should) key/secret linked to a single user or are they only a kind of RSA-like key pairs that, when verified, can be used to authorize any user. A: My understanding is this. When you use built-in Apps Script functions, like MailApp.sendEmail, the Google Apps Script "environment" takes care for you to ask authorization for the user (1st time he access your app) and save and manage the oAuth tokens for you, so it all runs smoothly. When you call an external service using UrlFetchApp, Apps Script oAuth authorization process works differently. The authorization is just a strange popup you get on the script editor, when you actually make the fetch call. It is not processed at "compile time" and asked before you run anything like the other services. But you also do this step only once. The "gotcha" is that this different authorization process does not work when a user is running the app as a webapp. AFAIK it only works from the script editor itself or running directly from a spreadsheet. If your users are just a known few, you could advise everybody to open the script editor (or a spreadsheet that contains it) and run an specific function that will just attempt the UrlFetchApp.fetch call so the popup shows up and they authorize it. Once this step is done, they can use the webapp normally. Apps Script will do the magic for you after that. But if you plan to share this broadly, say at the Chrome Web Store, and don't want to ask every user to do this somewhat strange step, then you'll need to manage all the authorization process yourself. It means, you'll have to register your app with the third party service (if it's Google's, it's at the API Console), where you will receive a client id and a client secret. With those you'll have to place a "Authorize" submit button on your app html that will redirect the users to the 3rd party authorization url, providing the correct scope, etc. When they authorize it, the 3rd party will redirect the user back to your app providing a code token as URL parameter. You'll use this code to call the 3rd party oAuth service to get the real access and possibly refresh tokens that you'll have to use on your UrlFetch calls. You'll be responsible to save these tokens, refresh them when they expire and so on. Not a very simple procedure :-/ Oh, and although your app have only one id and secret, the tokens are per user. Which makes sense, since each call you do must be on behalf of a specific user and he *must* have authorized it. I hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Dynamic type-hint in Laravel for Form Request I've created a Base Controller and I want to dynamically type-hint the store method to use the proper Form Request class. How can I do that? Here's my base controller (simplified): class BaseController extends Controller { protected $baseClass; protected $baseResourceClass; protected $baseStoreRequestClass; public function index() { $items = $baseClass::paginate(10); return $baseResourceClass::collection($items); } // the $baseStoreRequestClass doesn't work, and that's what I'm trying to figure it out public function store(**$baseStoreRequestClass** $request) { $validatedFields = $request->validated(); $newItem = $baseClass::create($validatedFields); return new $baseResourceClass($newItem); } } Then, from the controller that will extend, I would have just to declare the 3 variables. Example: class UserController extends BaseController { protected $baseClass = '\App\User'; protected $baseResourceClass = '\App\Http\Resources\UserResource'; protected $baseStoreRequestClass = '\App\Http\Requests\StoreUser'; } class ProductController extends BaseController { protected $baseClass = '\App\Product'; protected $baseResourceClass = '\App\Http\Resources\roductResource'; protected $baseStoreRequestClass = '\App\Http\Requests\StoreProduct'; } How could I make the $baseStoreRequestClass works? A: You can't specify a dynamic type as a function parameter. It's just not valid PHP syntax. Here's what I suggest. Your base class would be the boilerplate: class BaseController extends Controller { protected $baseClass; protected $baseResourceClass; public function index() { $items = $baseClass::paginate(10); return $baseResourceClass::collection($items); } public function store(FormRequest $request) // Or other base request object you might create { $validatedFields = $request->validated(); $newItem = $baseClass::create($validatedFields); return new $baseResourceClass($newItem); } } Then each subclassed controller would need an explicit request type: class UserController extends BaseController { protected $baseClass = '\App\User'; protected $baseResourceClass = '\App\Http\Resources\UserResource'; public function store(StoreUser $request) { return parent::store($request); } }
{ "pile_set_name": "StackExchange" }
Q: Unable to install GitHub for Windows I'm trying to install github for windows when I received this error: Application cannot be started. Contact the application vendor. The error log produced this: PLATFORM VERSION INFO Windows : 6.2.9200.0 (Win32NT) Common Language Runtime : 4.0.30319.34014 System.Deployment.dll : 4.0.30319.33440 built by: FX45W81RTMREL clr.dll : 4.0.30319.34014 built by: FX45W81RTMGDR dfdll.dll : 4.0.30319.33440 built by: FX45W81RTMREL dfshim.dll : 6.3.9600.16384 (winblue_rtm.130821-1623) SOURCES Deployment url : http://github-windows.s3.amazonaws.com/GitHub.application ERROR SUMMARY Below is a summary of the errors, details of these errors are listed later in the log. * Activation of http://github-windows.s3.amazonaws.com/GitHub.application resulted in exception. Following failure messages were detected: + The referenced assembly is not installed on your system. (Exception from HRESULT: 0x800736B3) COMPONENT STORE TRANSACTION FAILURE SUMMARY No transaction error was detected. WARNINGS There were no warnings during this operation. OPERATION PROGRESS STATUS * [8/22/2014 12:51:27 AM] : Activation of http://github-windows.s3.amazonaws.com/GitHub.application has started. ERROR DETAILS Following errors were detected during this operation. * [8/22/2014 12:51:28 AM] System.Runtime.InteropServices.COMException - The referenced assembly is not installed on your system. (Exception from HRESULT: 0x800736B3) - Source: System.Deployment - Stack trace: at System.Deployment.Internal.Isolation.IStore.GetAssemblyInformation(UInt32 Flags, IDefinitionIdentity DefinitionIdentity, Guid& riid) at System.Deployment.Application.ComponentStore.GetSubscriptionStateInternal(DefinitionIdentity subId) at System.Deployment.Application.SubscriptionStore.GetSubscriptionStateInternal(SubscriptionState subState) at System.Deployment.Application.SubscriptionState.Validate() at System.Deployment.Application.SubscriptionStore.CheckAndReferenceApplication(SubscriptionState subState, DefinitionAppId appId, Int64 transactionId) at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestDirectBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options, ServerInformation& serverInformation) at System.Deployment.Application.DownloadManager.DownloadDeploymentManifestBypass(SubscriptionStore subStore, Uri& sourceUri, TempFile& tempFile, SubscriptionState& subState, IDownloadNotification notification, DownloadOptions options) at System.Deployment.Application.ApplicationActivator.PerformDeploymentActivation(Uri activationUri, Boolean isShortcut, String textualSubId, String deploymentProviderUrlFromExtension, BrowserSettings browserSettings, String& errorPageUrl) at System.Deployment.Application.ApplicationActivator.ActivateDeploymentWorker(Object state) COMPONENT STORE TRANSACTION DETAILS No transaction information is available. According to https://status.github.com/messages , there are no issues currently with the servers. I am on a personal computer so there shouldn't be any issues with the connection. I tried downloading the application directly from http://github-windows.s3.amazonaws.com/GitHub.application , but the result was the same. I am running Windows 8.1 Pro x64. Edit 1: Currently I'm working around being unable to install GitHub for Windows by first installing it on another system, then taking the newly installed files from %appdata%\Local\Apps\2.0, and moving them to the system that is having trouble installing. (The full directory is %appdata%\Local\Apps\2.0\EWG9HYRR.BKG\2XKOJCRD.XRD\gith..tion_317444273a93ac29_0002.0002_f44dcb2e9d4cde94). One of the major caveats of this workaround is that on the problem system, GitHub for Windows will report "This isn't a networked deployed app." and therefor not automatically update. A: After contacting support, they emailed me and helped me work through the problem preventing GitHub for windows from installing. This is a problem with the ClickOnce Application Cache. Before proceeding make sure that you have connectivity. Sometimes Firewall may be blocking this *.application So turn off you firewall for private and public profile and then retry. If the issue persists, you can use the process specified below. Hold down the Windows key and type R. Type in rundll32 %SystemRoot%\system32\dfshim.dll CleanOnlineAppCache in the run dialog and hit Enter. Then try installing the application. If that doesn't work, there's a more manual approach to ensuring the cache is cleared - you can delete the ClickOnce Application folder directly. On Windows Vista or higher, this will be the %LocalAppData%\Apps\2.0 directory. Simply delete the %LocalAppData%\Apps\2.0 directory and restart github for windows. If nothing seems to happen after running the installer, you may need to restart Windows, or explorer.exe (if using the .msi installer, the app may be in: %LocalAppData%\GitHubDesktop) A: I had this issue as well installing github on Windows 8 x64, I tried all suggestions above related to removing the 2.0 directory but with no luck. Later I found a blog saying that one guy solved this issue by downloading the installer using Internet Explorer (weird right?) Surprisingly for me, it worked! Hre is the link https://github-windows.s3.amazonaws.com/GitHub.application So I recommend you to do the same, at least IE is worth for something :) Best A: For Windows 8.1 64-Bit, Go to file Explorer (Shortcut: windows key + E). Paste this " %LocalAppData%\Apps" (without inverted commas) in you file explorer panel (which displays your current location in file explorer. Press Enter key. Delete the folder named 2.0 . In my case, this worked without a glitch. I Hope this helps you
{ "pile_set_name": "StackExchange" }
Q: linking .dylib via LDFLAGS using clang/LLVM I am getting an error. One of the source files references: #include <libxml/parser.h> I am working with a Makefile below, trying to link: LDFLAGS =-l../../usr/local/sys/usr/lib/libxml2.dylib Path appears to be correct, and the file is there. Error details from IDE: http://clip2net.com/clip/m0/1333837472-clip-29kb.png http://clip2net.com/clip/m0/1333837744-clip-32kb.png What am I doing wrong? ############################################################################# # Makefile for iPhone application (X) ############################################################################# # Define here the name of your project's main executable, and the name of the # build directory where the generated binaries and resources will go. NAME = X OUTDIR = X.app # Define here the minimal iOS version's MAJOR number (iOS3, iOS4 or iOS5) IOSMINVER = 5 # List here your project's resource files. They can be files or directories. RES = Info.plist icon.png # Define here the compile options and the linker options for your project. CFLAGS = -W -Wall -O2 -Icocos2dx/include -Icocos2dx/platform -Icocos2dx/platform/ios -Icocos2dx/effects -Icocos2dx/cocoa -Icocos2dx/support -Icocos2dx/support/image_support -Icocos2dx/support/data_support -Icocos2dx/support/zip_support -Icocos2dx/extensions -Icocos2dx LDFLAGS =-l../../usr/local/sys/usr/lib/libxml2.2.dylib ############################################################################# # Except for specific projects, you shouldn't need to change anything below ############################################################################# # Define which compiler to use and what are the mandatory compiler and linker # options to build stuff for iOS. Here, use the ARM cross-compiler for iOS, # define IPHONE globally and link against all available frameworks. CC = clang LD = link CFLAGS += -ccc-host-triple arm-apple-darwin -march=armv6 --sysroot ../../usr/local/sys -integrated-as -fdiagnostics-format=msvc -fconstant-cfstrings -DIPHONE -D__IPHONE_OS_VERSION_MIN_REQUIRED=$(IOSMINVER)0000 LDFLAGS += -lstdc++ $(addprefix -framework , $(notdir $(basename $(wildcard /Frameworks/iOS$(IOSMINVER)/*)))) # List here your source files. The current rule means: ask the shell to build # a one-liner list of all files in the current directory and its subdirectories # ending with either .c, .cc, .cpp, .cxx, .m, .mm, .mx or .mxx. SRC = $(shell find . \( -name "*.c" -o -name "*.cc" -o -name "*.cpp" -o -name "*.cxx" -o -name "*.m" -o -name "*.mm" -o -name "*.mx" -o -name "*.mxx" \) -printf '%p ') # Define where the object files should go - currently, just aside the source # files themselves. We take the source file's basename and just append .o. OBJ = $(addsuffix .o, $(basename $(SRC))) ################### # Rules definitions # This rule is the default rule that is called when you type "make". It runs # the specified other rules in that order: removing generated output from # previous builds, compiling all source files into object files, linking them # all together, codesigning the generated file, copying resources in place # and then displaying a success message. all: prune $(OBJ) link codesign resources checksum ipa deb end # The following rule removes the generated output from any previous builds prune: @echo " + Pruning compilation results..." @rm -f $(OUTDIR)/$(NAME) # The following rules compile any .c/.cc/.cpp/.cxx/.m/.mm/.mx/.mxx file it # finds in object files (.o). This is to handle source files in different # languages: C/C++ (with .c* extension), and Objective-C (.m*). %.o: %.c @echo " + Compiling $<..."; $(CC) $(CFLAGS) -o $@ -c $< %.o: %.cc @echo " + Compiling $<..."; $(CC) $(CFLAGS) -o $@ -c $< %.o: %.cpp @echo " + Compiling $<..."; $(CC) $(CFLAGS) -o $@ -c $< %.o: %.cxx @echo " + Compiling $<..."; $(CC) $(CFLAGS) -o $@ -c $< %.o: %.m @echo " + Compiling $<..."; $(CC) $(CFLAGS) -o $@ -c $< %.o: %.mm @echo " + Compiling $<..."; $(CC) $(CFLAGS) -o $@ -c $< %.o: %.mx @echo " + Compiling $<..."; $(CC) $(CFLAGS) -o $@ -c $< %.o: %.mxx @echo " + Compiling $<..."; $(CC) $(CFLAGS) -o $@ -c $< # The following rule first ensures the output directory exists, creates it if # necessary, then links the compiled .o files together in that directory link: @echo " + Linking project files..." @test -d $(OUTDIR) || mkdir -p $(OUTDIR) @$(LD) $(LDFLAGS) -o $(OUTDIR)/$(NAME) $(OBJ) # The following rule calls Saurik's ldid code pseudo-signing tool to generate # the SHA checksums needed for the generated binary to run on jailbroken iOS. codesign: @echo " + Pseudo-signing code..." @ldid -S $(OUTDIR)/$(NAME) @rm -f $(OUTDIR)/.$(NAME).cs # The following rule takes all the specified resource items one after the # other (whether they are files or directories) ; files are copied in place # and directories are recursively copied only if they don't exist already. resources: @echo " + Copying resources..." @for item in $(RES); do \ if [ -d $$item ]; then test -d $(OUTDIR)/$$item || cp -r $$item $(OUTDIR)/; chmod +r $(OUTDIR)/$$item; \ else cp $$item $(OUTDIR)/; chmod +r $(OUTDIR)/$$item; \ fi; \ done @chmod +x $(OUTDIR) @chmod -R +r $(OUTDIR) @chmod +x $(OUTDIR)/$(NAME) # The following rule takes all files in the target directory and builds the # _CodeSignature/CodeResource XML file with their SHA1 hashes. checksum: @echo " + Generating _CodeSignature directory..." @echo -n APPL???? > $(OUTDIR)/PkgInfo @codesigner $(OUTDIR) > .CodeResources.$(NAME) @test -d $(OUTDIR)/_CodeSignature || mkdir -p $(OUTDIR)/_CodeSignature @mv .CodeResources.$(NAME) $(OUTDIR)/_CodeSignature/CodeResources @test -L $(OUTDIR)/CodeResources || ln -s _CodeSignature/CodeResources $(OUTDIR)/CodeResources # The following rule builds an IPA file out of the compiled app directory. ipa: @echo " + Building iTunes package..." @test -d Packages || mkdir Packages @rm -f Packages/$(NAME).ipa @test -d Payload || mkdir Payload @mv -f $(OUTDIR) Payload @cp -f iTunesArtwork.jpg iTunesArtwork @chmod +r iTunesArtwork @zip -y -r Packages/$(NAME).ipa Payload iTunesArtwork -x \*.log \*.lastbuildstate \*successfulbuild > /dev/null @rm -f iTunesArtwork @mv -f Payload/$(OUTDIR) . @rmdir Payload # The following rule builds a Cydia package out of the compiled app directory. deb: @echo " + Building Cydia package..." @test -d Packages || mkdir Packages @rm -f Packages/$(NAME).deb @test -d $(NAME) || mkdir $(NAME) @test -d $(NAME)/Applications || mkdir $(NAME)/Applications @mv -f $(OUTDIR) $(NAME)/Applications @test -d $(NAME)/DEBIAN || mkdir $(NAME)/DEBIAN @cp -f cydia-package.cfg $(NAME)/DEBIAN/control @chmod +r $(NAME)/DEBIAN/control @echo "#!/bin/bash" > $(NAME)/DEBIAN/postinst @echo "rm -f /Applications/$(OUTDIR)/*.log /Applications/$(OUTDIR)/*.lastbuildstate /Applications/$(OUTDIR)/*.successfulbuild" >> $(NAME)/DEBIAN/postinst @echo "chown -R root:admin \"/Applications/$(OUTDIR)\"" >> $(NAME)/DEBIAN/postinst @echo "find \"/Applications/$(OUTDIR)\"|while read ITEM; do if [ -d \"\$$ITEM\" ]; then chmod 755 \"\$$ITEM\"; else chmod 644 \"\$$ITEM\"; fi; done" >> $(NAME)/DEBIAN/postinst @echo "chmod +x \"/Applications/$(OUTDIR)/$(NAME)\"" >> $(NAME)/DEBIAN/postinst @echo "su -c /usr/bin/uicache mobile 2> /dev/null" >> $(NAME)/DEBIAN/postinst @echo "exit 0" >> $(NAME)/DEBIAN/postinst @chmod +r+x $(NAME)/DEBIAN/postinst @dpkg-deb -b $(NAME) > /dev/null 2>&1 @mv -f $(NAME).deb Packages @mv -f $(NAME)/Applications/$(OUTDIR) . @rm -rf $(NAME) # This simple rule displays the success message after a successful build end: @echo " + Done. Output directory is \"$(OUTDIR)\", iTunes package is \"Packages\$(NAME).ipa\", Cydia package is \"Packages\$(NAME).deb\"." # This rule removes generated object files from the project and also temporary # files ending with ~ or #. clean: @echo " + Cleaning project intermediate files..." @rm -f $(OBJ) *~ *\# @echo " + Done." # This rule removes all generated output from any previous builds so as to # leave an intact source tree (useful for generating source tree releases). distclean: clean @echo " + Cleaning project output files..." @rm -rf $(OUTDIR) @echo " + Done." A: You actually may have two problems. I suggest you try: Add -I../../usr/local/sys/usr/include to your CFLAGS to make it find the header. Change the LDFLAGS to -L../../usr/local/sys/usr/lib, add LIBS=-lxml2 and change the linker invocation to $(LD) $(LDFLAGS) -o $(OUTDIR)/$(NAME) $(OBJ) $(LIBS) (i.e. add the -l at the end, the -L at the beginning of the linker command line). A: -l is for specifying the library name only. Use -L to add directories where libraries will also be looked for: LDFLAGS += -L../../usr/local/sys/usr/lib -lxml2 Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: How to save the date and time when a Core Data object is created I want to save & retrive current time (if today) or date of the note created in Core Data Please guide me on how I can do this. A: You can have your custom NSManagedObject subclass set an attribute as soon as it's inserted in a context by overriding the -awakeFromInsert method: @interface Person : NSManagedObject @property (nonatomic, copy) NSDate *creationDate; // modeled property @end @implementation Person @dynamic creationDate; // modeled property - (void)awakeFromInsert { [super awakeFromInsert]; self.creationDate = [NSDate date]; } @end Note that creationDate above is a modeled property of Core Data attribute type "date", so its accessor methods are generated automatically. Be sure to set your entity's custom NSManagedObject class name appropriately as well. A: Make a Core Data entity called Note, give it an attribute called timeStamp Set it to type Date. When creating a new Note assign it the current time: [note setTimeStamp:[NSDate date]]; Persist the Note, that is it. A: Just to keep this question up-to-date with Swift, in the xcdatamodelid click the entity you wish to create a default date. Under the Data Model Inspector change Codegen from "Class Definition" to "Manual/None": Then from the menu bar click Editor -> Create NSManagedObject Subclass... and create the two Swift classes: Note+CoreDataClass.swift and Note+CoreDataProperties.swift Open the Note+CoreDataClass.swift file and add the following code: import Foundation import CoreData @objc(Note) public class Note: NSManagedObject { override public func awakeFromInsert() { super.awakeFromInsert() self.creationDate = Date() as NSDate } } Now the creationalDate will get a default date of the current date/time.
{ "pile_set_name": "StackExchange" }
Q: How to clear all markers when bounds changed I am playing with Google map and loading markers from database table with jQuery Ajax. Now everything is working perfect for me but two things are, i don't know how to implement Google map: Clear all previous markers when bounds_changed. Close others infowindow and display current one. For point 2: I have tried with this code but no luck. You can see I have added in my code. var infowindow = new google.maps.InfoWindow({}); infowindow.close(); I am getting json data with latitude & longitude: [ {"latitude":"23.046100780353495","longitude":"72.56860542227514"}, {"latitude":"23.088427701737665","longitude":"72.49273109366186"}, {"latitude":"23.061264193197644","longitude":"72.68224525381811"}, {"latitude":"22.977212139977677","longitude":"72.52191352774389"}, {"latitude":"23.002180435752084","longitude":"72.47590827872045"}, {"latitude":"23.108638843843046","longitude":"72.49444770743139"} ] Google Code with Ajax: google.maps.event.addListener(map, 'bounds_changed', function() { var bounds = map.getBounds(); var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); $.ajax({ type: "POST", url: 'get-locations.php', data: 'ne='+ne+'&sw='+sw, success:function(data){ var infowindow = new google.maps.InfoWindow({}); var objects_array = JSON.parse(data); // This is an array of objects. var totalLocations = objects_array.length; for (var i = 0; i < totalLocations; i++) { var obj = objects_array[i]; // This is one object from the array. // Init markers var marker = new google.maps.Marker({ position: new google.maps.LatLng(obj.latitude, obj.longitude), map: map, icon: 'http://localhost/google/marker.png', // Default icon title: obj.title }); // Process multiple info windows (function(marker, i) { // Add click event google.maps.event.addListener(marker, 'click', function() { //console.log(objects_array[i].info_data); //infowindow.close(); infowindow = new google.maps.InfoWindow({ content: '<div class="MarkerPopUp"><div class = "MarkerContext">'+objects_array[i].info_data+'</div></div>' }); infowindow.open(map, this); }); })(marker, i); } } }); }); Any Idea how to do both points. I will thankful, If you guide me with my example :). Thanks. A: Use below code to clear all marker. see google help for marker var markers = []; var infowindow = null; // Sets the map on all markers in the array. function setAllMap(map) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } } // Removes the markers from the map, but keeps them in the array. function clearMarkers() { setAllMap(null); } google.maps.event.addListener(map, 'bounds_changed', function() { var bounds = map.getBounds(); var ne = bounds.getNorthEast(); var sw = bounds.getSouthWest(); $.ajax({ type: "POST", url: 'get-locations.php', data: 'ne='+ne+'&sw='+sw, success:function(data){ var infowindow = new google.maps.InfoWindow({}); var objects_array = JSON.parse(data); // This is an array of objects. var totalLocations = objects_array.length; clearMarkers(); // clear all markers before addd new markers for (var i = 0; i < totalLocations; i++) { var obj = objects_array[i]; // This is one object from the array. // Init markers var marker = new google.maps.Marker({ position: new google.maps.LatLng(obj.latitude, obj.longitude), map: map, icon: 'http://localhost/google/marker.png', // Default icon title: obj.title }); //// Add marker object to array . markers.push(marker); // Process multiple info windows (function(marker, i) { // Add click event google.maps.event.addListener(marker, 'click', function() { if (infowindow) { infowindow.close(); } infowindow = new google.maps.InfoWindow({ content: '<div class="MarkerPopUp"><div class = "MarkerContext">'+objects_array[i].info_data+'</div></div>' }); infowindow.open(map, this); }); })(marker, i); } } }); });
{ "pile_set_name": "StackExchange" }
Q: PHP-activerecord - relation has_many (users, groups, users_groups) I want to do this on my view but it´s not working: <?php echo $user->group->name;?> I have 3 tables - users (id, name) - groups (id, name) - users_groups (id, user_id, group_id) I have 2 models class User extends ActiveRecord\Model { static $belongs_to = array( array('group', 'through' => 'users_groups') ); } class Group extends ActiveRecord\Model { static $has_many = array( array('users' , 'through' => 'users_groups') ); } My models are wrong or miss something? I need another model users_groups? If is yes, how would be called? I need help, i don´t find the correct way. Thanks! A: The solution is: class User extends ActiveRecord\Model { static $has_many = array( array('groups', 'through' => 'usersgroups', 'order'=>'id asc'), array('usersgroups') ); } class Group extends ActiveRecord\Model { static $has_many = array( array('users' , 'through' => 'usersgroups'), array('usersgroups') ); } class UsersGroup extends ActiveRecord\Model { static $table_name = 'users_groups'; static $belongs_to = array( array('user'), array('group') ); } The problem was with the name of the of third model (UsersGroup in singular)
{ "pile_set_name": "StackExchange" }
Q: Grails: mapping column names of a field and a belongsTo of the same type I'm trying to map the column names of this class: class Amount{ String total //Total amount of something String type //Type of amount, Dollars, %, Times something Bonification bonificationRate //the amount can be "x times another bonification" static belongsTo = [parentBonification: Bonification] static mapping = { table "AMOUNTS" total column: "AMOU_TTOTAL" type column: "AMOU_TTYPE" parentBonification column: "BONI_CID" bonificationRate column: "BONI_TRATE_CID" } } class Bonification { //among other things: Amount amount } The thing is none of the field with the Bonification class are created in the DB, not with the name I give them and neither with the default suppossed names. Comment Edit: Both are Domain Classes; Datasource is on dbCreate = "update" I dropped the Table in Oracle and let Grails create it again. Still no Bonification columns. I can not dbCreate = "create-drop" because there is data that I can't delete for now. I mounted a new local Derby Database with dbCreate = create-drop. Still no luck. (PD: All other fields are persisted and mapped with the right column names, only those two Bonification fields are the problem) Is there another way of doing this? Grails: 1.3.9 BD: Oracle 9 Edit for asked DataSource.groovy (External file accessed from Config.groovy grails.config.locations = [ "file:${extConfig}/${appName}Config.groovy"]) package xx.xxx.xxxx.xxxXxxx dataSource { pooled = true dialect = "org.hibernate.dialect.Oracle10gDialect" driverClassName = "oracle.jdbc.OracleDriver" username = "XXX" password = "XXX" properties { maxActive = 100 maxIdle = 25 minIdle = 5 initialSize = 5 minEvictableIdleTimeMillis = 60000 timeBetweenEvictionRunsMillis = 60000 maxWait = 10000 validationQuery = "select 1 from dual" } } hibernate { cache.use_second_level_cache = true cache.use_query_cache = true cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider' } // environment specific settings environments { development { println "Including external DataSource" dataSource { dbCreate = "update" url = "jdbc:oracle:thin:@xxx.xxx.xx:xxxx:XXXX" } } } A: Ok, finally I got it. I used the "mappedBy" property. http://grails.org/doc/2.1.0/ref/Domain%20Classes/mappedBy.html The documentation (6.2.1.2 One-to-many) said that is for use in the "hasMany" side. That confused me because I didn't have a hasMany but rather two field of the same type in Class Amount. And what I really had to do was to use the mappedBy property, not in the Amount Class, but in the Bonification Class that has just one reference to Amount. And with that I tell to the Amount Class, wich Bonification he has to back reference so "he" doesn't get confused, and take the bonificationRate field just as a field and not as a reference as I think he was doing before. class Amount{ String total //Total amount of something String type //Type of amount, Dollars, %, Times something Bonification bonificationRate //the amount can be "x times another bonification" static belongsTo = [parentBonification: Bonification] static mapping = { table "AMOUNTS" total column: "AMOU_TTOTAL" type column: "AMOU_TTYPE" parentBonification column: "BONI_CID" bonificationRate column: "BONI_TRATE_CID" } } class Bonification { //among other things: Amount amount static mappedBy = [amount: "parentBonification"] } That didn't created the parentBonification "BONI_CID" column but it Did created the bonificationRate "BONI_TRATE_CID" wich I needed. Sorry if it's too messy. Thanks for the time and help anyway.
{ "pile_set_name": "StackExchange" }
Q: Why is R reading numeric data as character? I'm trying to load a file that contains integers and float data. I'm at a loss as to why R will read one of the columns as a character field. > df <- read.table( 'C:\\temp\\test.tab' , + sep = '\t' , header = TRUE , stringsAsFactors = FALSE , dec="." ) > str(df) 'data.frame': 7 obs. of 5 variables: $ A: int 0 0 0 0 1 0 0 $ B: int 1431 2097 2712 24821 27359 41165 49221 $ C: int 0 0 0 0 0 0 0 $ D: chr "7" "26.950000762939453" "57.95000076293945" "21" ... $ E: int 1 2 3 4 5 6 7 File Content: A B C D E 0 1431 0 7 1 0 2097 0 26.950000762939453 2 0 2712 0 57.95000076293945 3 0 24821 0 21 4 1 27359 0 57.900001525878906 5 0 41165 0 33.95000076293945 6 0 49221 0 28.950000762939453 7 > R.version _ platform x86_64-w64-mingw32 arch x86_64 os mingw32 system x86_64, mingw32 status major 3 minor 1.0 year 2014 month 04 day 10 svn rev 65387 language R version.string R version 3.1.0 (2014-04-10) nickname Spring Dance A: This probably deserves a genuine answer that we can point to, so.... The behavior of type.convert was altered in R 3.1.0 (and, read below, will be largely reverted to its pre-3.1.0 behavior in R 3.1.1): As from R 3.1.0, where converting inputs to numeric or complex would result in loss of accuracy they are returned as strings (for as.is = TRUE) or factors. This created a fairly significant ruckus on the r-devel mailing list. The beginning of the relevant (and long) thread is here. As Ben mentioned above, one of the results of that discussion is that the default behavior was restored in the development version for a subsequent release. In the short term if you know which columns will be affected you can always use colClasses. Otherwise you'd have to modify your code to check the results of read.table and convert things yourself, I guess.
{ "pile_set_name": "StackExchange" }
Q: How to get the right source code with Python from the URLs using my web crawler? I'm trying to use python to write a web crawler. I'm using re and requests module. I want to get urls from the first page (it's a forum) and get information from every url. My problem now is, I already store the URLs in a List. But I can't get further to get the RIGHT source code of these URLs. Here is my code: import re import requests url = 'http://bbs.skykiwi.com/forum.php?mod=forumdisplay&fid=55&typeid=470&sortid=231&filter=typeid&pageNum=1&page=1' sourceCode = getsourse(url) # source code of the url page allLinksinPage = getallLinksinPage(sourceCode) #a List of the urls in current page for eachLink in allLinksinPage: url = 'http://bbs.skykiwi.com/' + eachLink.encode('utf-8') html = getsourse(url) #THIS IS WHERE I CAN'T GET THE RIGHT SOURCE CODE #To get the source code of current url def getsourse(url): header = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 10.0; WOW64; Trident/8.0; Touch)'} html = requests.get(url, headers=header) return html.text #To get all the links in current page def getallLinksinPage(sourceCode): bigClasses = re.findall('<th class="new">(.*?)</th>', sourceCode, re.S) allLinks = [] for each in bigClasses: everylink = re.findall('</em><a href="(.*?)" onclick', each, re.S)[0] allLinks.append(everylink) return allLinks A: You define your functions after you use them so your code will error. You should also not be using re to parse html, use a parser like beautifulsoup as below. Also use urlparse.urljoin to join the base url to the the links, what you actually want is the hrefs in the anchor tags inside the the div with the id threadlist: import requests from bs4 import BeautifulSoup from urlparse import urljoin url = 'http://bbs.skykiwi.com/forum.php?mod=forumdisplay&fid=55&typeid=470&sortid=231&filter=typeid&pageNum=1&page=1' def getsourse(url): header = {'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 10.0; WOW64; Trident/8.0; Touch)'} html = requests.get(url, headers=header) return html.content #To get all the links in current page def getallLinksinPage(sourceCode): soup = BeautifulSoup(sourceCode) return [a["href"] for a in soup.select("#threadlist a.xst")] sourceCode = getsourse(url) # source code of the url page allLinksinPage = getallLinksinPage(sourceCode) #a List of the urls in current page for eachLink in allLinksinPage: url = 'http://bbs.skykiwi.com/' html = getsourse(urljoin(url, eachLink)) print(html) If you print urljoin(url, eachLink) in the loop you see you get all the correct links for the table and the correct source code returned, below is a snippet of the links returned: http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3177846&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3197510&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3201399&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3170748&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3152747&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3168498&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3176639&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3203657&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3190138&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3140191&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3199154&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3156814&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3203435&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3089967&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3199384&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3173489&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 http://bbs.skykiwi.com/forum.php?mod=viewthread&tid=3204107&extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 If you visit the links above in your browser you will see it get the correct page, using http://bbs.skykiwi.com/forum.php?mod=viewthread&amp;tid=3187289&amp;extra=page%3D1%26filter%3Dtypeid%26typeid%3D470%26sortid%3D231%26typeid%3D470%26sortid%3D231 from your results you will see : Sorry, specified thread does not exist or has been deleted or is being reviewed [New Zealand day-dimensional network Community Home] You can see clearly the difference in the url's. If you wanted yours to work you would need to do a replace in your regex: everylink = re.findall('</em><a href="(.*?)" onclick', each.replace("&","%26"), re.S)[0] But really don't parse html will a regex.
{ "pile_set_name": "StackExchange" }
Q: Why can't I target an image in a table with jQuery? The idea is to show some extra content in TDs on hover, as well as increase the size of images in the rest of the row at the same time without breaking image proportions. I'm using this JS: $('tr.therow').hover(function() { $(this).find('img.theimage').css("height", "100px"); }); See: http://jsfiddle.net/J2YAj/ What am I doing wrong here? Thanks in advance! A: You can use $('td > img.theimage', this) to target the images in the row that you're currently hovering over. Instead of using .css(), you can simply set the height with .height(). However, there is no change back because you did not include that in your original code, it would be relatively easy to add though. You can see the changes here: http://jsfiddle.net/J2YAj/3/
{ "pile_set_name": "StackExchange" }
Q: Why isn't Haskell's Data.Vector an instance of Traversable? Don't understand, if Data.Map is and [] is. I found this out while wondering why I need Data.Vector.mapM for vectors and Data.Traversable.mapM for maps. A: There are orphan instances on hackage.
{ "pile_set_name": "StackExchange" }
Q: Does a number matrix have its invariant factors?? I'm just confused by the following statement in my advanced algebra textbook: Frobenius Form: Let $A$ be an $n$th order square matrix over a number field $K$, whose invariant factors are: $$1,\cdots ,1, d_1(\lambda),\cdots,d_k(\lambda)$$ Then we can obtain its Frobenius form as: $$\cdots$$ Proof: Note that $(\lambda I-A)$'s $n$th determinant factor is exactly $A$'s characteristic polynomial $|\lambda I-A|$. Because of the invariability of determinant factors under elementary transformations, we have $$|\lambda I-A|=\prod_{i=1}^{k}d_i(\lambda)$$ $$\cdots$$ I don't understand why a number matrix should have something like invariant factors or determinant factors since all of its minors are pure numbers instead of polynomials? In fact, I strongly suspected that the author originally intended to mean "$(\lambda I-A)$'s invariant factors" rather than $A$'s invariant factors, which led me to believe that it was just a typo. But later in an exercise, it appeared again: The matrix $$A=\begin{pmatrix} 0&0&0&0\\0&0&0&0\\0&0&0&1\\0&0&0&0\end{pmatrix}$$ has the invariant factors: $1,\lambda,\lambda,\lambda^2$. $$\cdots$$ I got a shock. After calculation I found out that the invariant factors of $(\lambda I-A)$ "coincided" to be $1,\lambda,\lambda,\lambda^2$. This left me even more puzzled. Apparently that's not a typo, but why on earth did the author say "$A$'s" rather than "$(\lambda I-A)$"'s invariant factors? Or more probably, I'm just misunderstanding the use of this terminology? If so then can you point out where I'm wrong? Thanks in advance. A: All this stems from the fact that if you're given a finite dimensional vector space $E$ over any field $k$ and an endomorphism $f$, $E$ can be seen as a $k[x]$-module through $x\cdot v=f(v)$. This module is a finitely generated torsion module since $\chi_f(x)\cdot v=0$ (because of Cayley-Hamilton theorem). Hence by the structure theorem for finitely generated modules over a PID, it has a sequence of invariant factors. What is most important is that two matrices are similar if and only if they have the same invariant factors – which are also known as similarity invariants. To the difference of the computation of Jordan form, the computation of similarity invariants is entirely effective, as it doesn't require knowing the eigenvalues of the endomorphism.
{ "pile_set_name": "StackExchange" }
Q: How to display a result passed to a function in a textbox i have a function the retrieves data from a database and returns it to a function.i am trying to get the Income value from the result to be displayed in the text box. this is what i tried. function Display(result) // result gets passed { var income= $('#Income'); //getting the textbox; income.value=result.Income // when i try this result.Income,Income comes back as undefined. } How do i display the value from my result into the textbox? this is how my "result" looks thats passed into the Display function.So ideally the value for Income is "Salary" so salary should be displayed in the textbox. { ID: 0 Number: 520 OtherIncome: "Private" Income: "Salary" } This is my HTML <input type="text" name="Income" id="Income" class="text ui-widget-content ui-corner-all" value=""> A: var json = { ID: 0, Number: 520, OtherIncome: "Private", Income: "Salary", } function Display(result) // result gets passed { var income = $('#Income'); //getting the textbox; income.val(result.Income) // when i try this result.Income,Income comes back as undefined. } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="Income" id="Income" class="text ui-widget-content ui-corner-all" value=""> <button onClick="Display(json)">Click</button><br> Click the button to set the textbox value. Try using income.val(result.Income) to set the value of the text box. Here I have used a button click event to generate the example.
{ "pile_set_name": "StackExchange" }
Q: Dropping foreign keys in Alembic downgrade? So I have created a number of tables in my database using an Alembic migration, each has an index and one or two foreign keys. My upgrade method works fine, executes and creates the tables. My downgrade method fails, after I drop my indexes and then drop my tables. I believe I also have to drop my foreign keys first? However I can't figure out how to drop foreign keys from the Alembic Documentation. Downgrade method: def downgrade(): # Drop Indexes op.drop_index('ix_charge_id') op.drop_index('ix_statutory_provision_id') op.drop_index('ix_originating_authority_id') # Drop Tables op.drop_table('charge') op.drop_table('statutory_provision') op.drop_table('originating_authority') Each of these three tables has a foreign key, so how do I go about dropping these first? TYIA. A: You just need to call drop constrain. So in your upgrade method you might have the following: op.create_foreign_key(u'my_fkey', 'table1', 'table2', ['table2_id'], ['id']) Then in your downgrade method you just need to have op.drop_constraint(u'my_fkey', 'table1', type_='foreignkey') One thing to watch for is that you assign a name when you create the foreign key, or known exactly the naming convention that will be used by the database. When you drop the constraint you need to specify the exact name being used. One last thing which might help and save you time is to use the auto revision function of alembic. I find this saves a lot of the heavy lifting, and then I can just tweak the scripts if I need to. alembic revision --autogenerate -m <message> Check out http://alembic.zzzcomputing.com/en/latest/autogenerate.html for more information about the autogenerate, but it really is a time saver.
{ "pile_set_name": "StackExchange" }
Q: How to handle an ASP.NET MVC ActionResult Exception? I have a custom ActionResult which is more deeply encountering System.Web.HttpException when the remote host closes the connection. I've already overridden the Controller's OnException method but it's not getting caught there. The ASP.NET MVC pipeline is already done executing my Controller's Action and is now executing the returned ActionResult when it encounters this exception. Presently, it's bubbling up and being cluttering my log as an ERROR. I'd rather not filter these out at logging time, because I don't consider a remote host aborting the download of the content to be an error. I'd rather handle this error directly, but I can't tell where. Controller.OnException doesn't work, and so I doubt the IExceptionFilter would either. I could use Application_OnError but I fear that is too high up. Isn't there a more MVC'ish way? A: There are no other points to catch exceptions between Controller.OnException and Application_OnError. Be Brave and use Application_OnError
{ "pile_set_name": "StackExchange" }
Q: Sizing an entire backlog using story points I'm a PM on a large multi-year project with a sizable backlog of work implementing Scrum in 4 week release cycles. I hold weekly backlog grooming sessions with the project team and key business owners to review the user stories in the backlog, break down larger user stories (epics) into smaller ones that the project team can begin implementing in the sprint and size these smaller user stories using story points. The use of story points associated to a user story is a fairly new concept to the team and has only been implemented in the past 6 months of the project (that started 1.5 years ago). So, the entire backlog is not sized in story points. My goal initially was to introduce the team to story points and to establish a regular meeting for the team to size user stories in the backlog so that they get used to it and thereby become more efficient (read faster) at sizing. However, the team has plateaued in terms of the speed at which user stories are sized and at the current rate I estimate it would take upwards to another year to size the entire backlog. Is this a good approach to sizing an entire backlog (that is very large) with the project team? How can I move forward with this in a manner that will speed up the process? If not a good idea, what is the better approach to this process? A: Usually, it is not a good idea to frequently check the whole backlog with the whole team. The last 2/3 part of the backlog is going to change in the future and checking these items just waste the time of the team and generate unnecessary discussions about future issues which may not be implemented at all. The recommended approach is that the Product Owner checks the whole backlog and keeps it in shape, and prepares as much user stories that the team can handle in 2-3 sprints. The rest remains in a kind of unknown or draft state. The Product Owner can call for a regular meeting where the whole backlog is discussed where the team gives a rough estimation on the whole backlog. If the sprint is 2 weeks long than this meeting shall be called once in two months. This meeting gives an overall view on the whole progress and provides. Running this meeting is a bit different from a Sprint Planning Meeting, because it is longer, because of the number of user stories, and there is no task break down. If impediments or issues come up, the Product Owner shall sort them out. This meeting is often called as Release Planning Meeting (there might be some good articles about it on the Scrum Alliance site). A: Stories to be worked on in the upcoming sprint should be estimated much more rigorously than stories scheduled for many months' time. Some people call this "Rolling Wave" planning. This is how I've estimated the whole backlog in the past: Product Owner identifies stories and prioritises them. Before a project starts, the PO and 1 or 2 technical guys spend 10 secs per story on estimation. Literally just a buest guess from the headline of the story. Not very accurate, but accurate enough given that most stories will get changed in some way before development, and many will not even get scheduled in. At the start of the project the whole team estimates the candidate stories for the first sprint, and possibly the following (if there's time). During a sprint, take some time out for the whole team to estimate the next batch of candidate stories for the following sprint in more detail. (This meeting is timeboxed to 1 hour). Re-estimate stories if necessary during sprint planning. Remember that Scrum is adaptive rather than predictive -- you shouldn't expect highly accurate estimates for work which is more than a sprint or two in the future. The type of accuracy you get from the above approach still lets you draw product backlog burndown (or burnup) charts to give an idea of release date. A: I truly believe that story point estimation should be limited to tasks you plan on putting into the next two-three sprints. Attempting more than that is just going to waste your team's time. The further into the future you're trying to predict, the more uncertainty there will be. This is just the way it is, whether using Scrum or any other methodology. So what do I do? Default new user stories to the average effort point value of completed user stories. You'd actually be quite amazed at how accurate predictions made with this value are, especially if you're good at breaking your epics into the right sized chunks. Just make sure that you don't fall into the habit of leaving this value. Estimate effort points with the team during sprint planning (or whenever you normally do it), but concentrate their efforts on the top of the backlog.
{ "pile_set_name": "StackExchange" }
Q: An increasing smooth map $f:(0,1)\rightarrow(0,1)$ which does not extend to any smooth function on a larger domain Although I'm not sure it's related, I have found a smooth map $f:(0,1)\rightarrow(0,1)$ which does not extend to any continuous function on a larger domain, namely $f(x)=\frac{1}{4}+\frac{1}{2}\sin^2\big{(}\frac{1}{x(x-1)}\big{)}$. This behaves like $\sin(\frac{1}{x})$ at $x=0$ and $x=1$, and all other adjustments are made to ensure the image is contained in $(0,1)$. Now I'm after a function as in the question - the 'increasing' restriction means I can't use any tricks like $\sin(\frac{1}{x})$ as above. I imagine there exists a continuous extension of such map, even if there is not a smooth one. Any suggestions would be welcome! A: If $f: (0,1) \to (0,1)$ is smooth and does not extend continuously to $[0,1]$ (because it does not have limits as $x \to 0+$ or $1-$), then $$g(x) = \dfrac{\int_0^x f(t)\; dt}{\int_0^1 f(t)\; dt}$$ is smooth and increasing and does not extend to a $C^1$ function on a larger domain.
{ "pile_set_name": "StackExchange" }
Q: how to add a custom theme in jquery mobile from theme roller site? I am trying to add a custom theme in my jquery mobile site. I visited the theme roller site , i designed a theme and then i downloaded a zip file. Inside there is a themes folder and an index.html . Inside the themes folder there is an images folder and 2 CSS files : 1) customTheme.css 2) customTheme.min.css I copy-pasted the 2) in my project folder. Then in my project i do : <head> <meta charset="utf-8"> <title>CEID</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="customTheme.min.css" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile.structure-1.3.1.min.css" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> <link rel="stylesheet" href="custom.css" /> </head> It should work right? What am i doing wrong here? The theme doesnt work.. What i am designing looks like this : What i get looks like this : My html looks like this : <head> <meta charset="utf-8"> <title>CEID</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="themes/CustomTheme.min.css" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile.structure-1.3.1.min.css" /> <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> </head> The custom CSS i was using : /* Home page banner */ h2#banner { background:transparent url(images/banner.png) no-repeat left 10px; width:220px; height:250px; margin:-10px auto -150px auto; text-indent:-9999px; } /* Home page banner landscape */ .landscape h2#banner { background:transparent url(../img/banner/banner-landscape.jpg) no-repeat left 10px; width:480px; height:290px; margin:-10px auto -175px auto; text-indent:-9999px; } .ui-listview .ui-li-icon { max-height: 32px !important; max-width: 32px !important; } /* Home page icons */ .ui-li-icon { top:0.4em !important; } /* Make room for icons */ .ui-li-has-icon .ui-btn-inner a.ui-link-inherit, .ui-li-static.ui-li-has-icon { padding-left:47px; } The body of my html: <body> <div data-role="page" id="home"> <div data-role="header"> </div> <div data-role="content"> <h2 id="banner">CEID Mobile</h2> <div class="menu_list"> <ul data-inset="true" data-role="listview"> <li><a href="information.html"><img src="images/info.png" alt="Information" class="ui-li-icon">Πληροφορίες</a></li> <li><a href="staff.html"><img src="images/staff.png" alt="Staff" class="ui-li-icon">Προσωπικό</a></li> <li><a href="research.html"><img src="images/research.png" alt="Research" class="ui-li-icon">Έρευνα</a></li> <li><a href="undergraduates.html"><img src="images/undergraduates.png" alt="undergraduates" class="ui-li-icon">Προπτυχιακά</a></li> <li><a href="metaptyxiaka.html"><img src="images/graduates.png" alt="Graduates" class="ui-li-icon">Μεταπτυχιακά</a></li> <li><a href="students.html"><img src="images/students.png" alt="Students" class="ui-li-icon">Φοιτητές</a></li> <li><a href="news.html"><img src="images/news.png" alt="News" class="ui-li-icon">Ανακοινώσεις</a></li> </ul> </div> <div class="menu_list"> <ul data-inset="true" data-role="listview"> <li><a href="http://www.ceid.upatras.gr"><img src="images/info.png" alt="Information" class="ui-li-icon">Μεταφορά στον Ιστότοπο</a></li> </ul> </div> </div> </div> </body> A: Your example won't work, take a look what you have : <link rel="stylesheet" href="customTheme.min.css" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile.structure-1.3.1.min.css" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" /> There are 3 different css files. First one is your custom theme, second one is only structure css file (everything else), and last one is complete jQuery Mobile css file. Currently your last css file (complete one) is overriding custom css theme. To solve your problem change everything to: <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" /> <link rel="stylesheet" href="customTheme.min.css" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile.structure-1.3.1.min.css" /> Or even better remove jquery.mobile-1.3.1.min.css and use only: <link rel="stylesheet" href="customTheme.min.css" /> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile.structure-1.3.1.min.css" /> What you need to understand, jQuery Mobile have 3 available css files. jquery.mobile-1.3.1.min.css should be used alone because it hase css for themes and structure. If you have custom themes then you only need to use custom theme css file and jquery.mobile.structure-1.3.1.min.css. EDIT : Don't forget that you also need to add data-theme to your page DIV container: <div data-role="page" id="home" data-theme="b"> or you can add it only to your header, content and footer DIV's but I would advise you to add it to page DIV.
{ "pile_set_name": "StackExchange" }
Q: LibreOffice Calc Cell Texts Is it possible in LibreOffice Calc to have a cell equal what another cell has including some extra text in the new cell. For example: Cell H4 contains "Hi". Cell J4 would have "=H4 + Bob". Bob would be the extra manually entered text. So the new J4 cell would read "Hi Bob". A: You should use function Concatenate in text area ( Name could be a little diffrent because I don't use English version ). If you want use manually entered text put it in double quote. =concatenate(H4;" Bob") Here you have more about: https://help.libreoffice.org/Calc/Text_Functions#CONCATENATE
{ "pile_set_name": "StackExchange" }
Q: Flex - Change position of scrollbar to the top of a HorizontalList component By default, the Horizontal ScrollBar of a HorizontalList component will be at the bottom. Is there a way to reposition it so it is at the top? Just for clarity, I do not mean moving the scroll position using either scrollToIndex or horizontalScrollPosition or similar, but the actual physical position of the scrollbar component. Any suggestions would be very appreciated! A: I was looking for something similar myself a while ago and found this post. I eventually ended up solving my problem in another way, so didn't use that solution, however it might work for what you want.
{ "pile_set_name": "StackExchange" }
Q: Iterating worksheets and cells, copying data to summary sheet I have been working on this particular sub for a while and it was very very slow from the beginning. Compared to my other subs that go through a lot more data the task of this one is almost minuscule. All it has to do is to go through about ~15 sheets and parse through a couple hundred cells. Since this is a fairly complicated task I need to test it a lot which becomes almost unbearable with how long it takes. I am not sure if there is anything I can do or if there even is a solution. I am open to all kinds of suggestions. Private Sub CommandButton24_Click() Dim xSheet As Worksheet Dim DestSh As Worksheet Dim Last As Long Dim copyRng As Range Dim destRng As Range Dim cRange As Range Dim c As Range Dim uniqueVal() As Variant Dim x As Long With Application .ScreenUpdating = False .EnableEvents = False End With 'Delete the summary worksheet if it exists. Application.DisplayAlerts = False On Error Resume Next ActiveWorkbook.Worksheets("Summary").Delete On Error GoTo 0 Application.DisplayAlerts = True ' Add a worksheet with the name "Summary" Set DestSh = ActiveWorkbook.Worksheets.Add DestSh.Name = "Summary" DestSh.Range("A1").Value = "Account" DestSh.Range("B1").Value = "Exchange" DestSh.Range("C1").Value = "Quarter" DestSh.Range("D1").Value = "Year" Set destRng = DestSh.Range("E1") 'Define inital array values uniqueVal = Array("Account by Type", "Total", "lv_nsac_ACCOUNT", "ams_ACCOUNT", "bru_ACCOUNT", "lsem_ACCOUNT", "mse_ACCOUNT", "par_ACCOUNT", "swx_ACCOUNT", "us_ACCOUNT", "wbag_ACCOUNT", "xetra_ACCOUNT", "europe_ACCOUNT", "lv_ACCOUNT", "lv_apac_ACCOUNT") ' This first part subtracts all the relevant column names, just running this 'already took excel about 3-5 minutes ' Loop through all worksheets and copy the data to the ' summary worksheet. For Each xSheet In ActiveWorkbook.Worksheets If InStr(1, xSheet.Name, "ACCOUNT") And xSheet.Range("B1") <> "No Summary Available" Then _ Set copyRng = xSheet.Range("A:A") For Each c In copyRng.SpecialCells(xlCellTypeVisible) If Len(c) <> 0 And Not ISIN(c, uniqueVal) Then _ 'Copy to destination Range c.Copy destRng 'move destination Range Set destRng = destRng.Offset(0, 1) 'change / adjust the size of array ReDim Preserve uniqueVal(0 To UBound(uniqueVal) + 1) As Variant 'add value on the end of the array uniqueVal(UBound(uniqueVal)) = c.Value End If Next c End If Next xSheet 'This second part is supposed to capture account names from the sheets and 'and put them in the first column. The command has been running for 20 'minutes with the program being completely non responsive. 'Loop through all worksheets and copy the data to the 'summary worksheet. For Each xSheet In ActiveWorkbook.Worksheets If InStr(1, xSheet.Name, "ACCOUNT") And xSheet.Range("B1") <> "No Summary Available" Then _ Set copyRng = xSheet.Cells For Each c In copyRng.SpecialCells(xlCellTypeVisible) If Len(c) <> 0 And Not ISIN(c, uniqueVal) Then _ If InStr(1, c.Value, "C-") Then _ 'Set destination Set destRng = xSheet.Range("A2:A").Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues) 'Copy to destination Range c.Copy destRng End If End If Next c End If Next xSheet ExitTheSub: Application.Goto DestSh.Cells(1) With Application .ScreenUpdating = True .EnableEvents = True End With End Sub Sorry for the massive block of code. A: I have found the answer. What seems to have cause the issue is these lines of code: Set copyRng = xSheet.Range("A:A") Set copyRng = xSheet.Cells All I wanted was to access the entire sheet with all of its non-empty cells. This seems to have been the wrong way of doing that since the code does in fact only take mere fractions of a second if I give it a clear defined range such as "A1:A100" in case of the first instance.
{ "pile_set_name": "StackExchange" }
Q: Json Decode returning NULL I am trying to decode json into array in PHP.But My json is like string(307) " string(290) "{"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"}" " string within a string!! How to convert it into array. A: This looks like you're trying to decode (or trying to output) the data with var_dump(). That isn't the function you require; what you require is json_decode(): $data = json_decode($json); If that isn't the issue, and you're actually receiving the data as above then you'll have to strip it out - most likely using a regex like the following: $s = 'string(307) " string(290) "{"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"}" "'; preg_match('/\{(.*)\}/', $s, $matches); print_r($matches); Which would return your json: Array ( [0] => {"id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05"} [1] => "id":"1","name":"test name","rowno":"0","note":"test notes","created_date":"2016-05-01","updated_date":"2016-05-12 05:08:05" ) Thus allowing you to decode it properly within $matches. Regex is a beast to me so I'll try explain as best as possible what the expression is doing: \{ matches the first open { (.*) matches any character inbetween \} matches the closing }
{ "pile_set_name": "StackExchange" }
Q: How to create a SESSION variable without giving it a value? [php] Basicaly my problem is the following: I'm trying to create a session variable so that something like this can happen if(username == false) { $_SESSION['error messages'] = 'username missing'; } The problem is that, while there are no errors, I want $_SESSION['error messages'] to be empty. But if I dont do something like this: $_SESSION['error messages'] = 'garbage'; if(username == false) { $_SESSION['error messages'] = 'username missing'; } It says that $_SESSION['error messages'] is not defined How can I have this variable empty until I need it? Thank you A: First, in order to save an error message, use the following: if (empty($username)) { $_SESSION['error messages'][] = 'username missing'; } It is nicer to keep an array of error messages. That way, if you have multiple errors, you can easily loop trough them, count them, ect. Then, when you want to display the error messages, do the following. if (isset($_SESSION['error messages']) && is_array($_SESSION['error messages'])) { foreach ($_SESSION['error messages'] as $errorMessage) { // Do something with the error message, for instance: printf ("The following error occured: <em>%s</em><br>", $errorMessage); } // Next, clear the error messages so that they do not pop up on the next page request. unset($_SESSION['error messages']); } Wrap the code that uses $_SESSION['error messages'] in isset() makes sure you won't get the error message about the index not being defined.
{ "pile_set_name": "StackExchange" }
Q: Write data.table syntax as its dplyr equivalent to fix 9218868437227407266's integer64 I have the integer64 issue that instead of NA it shows 9218868437227407266 as it's described here: fread() fails with missing values in integer64 columns I have loaded bit64 package that with data.table 1.9.5 or greater supposedly displays NAs instead of 9218868437227407266s but it doesn't work. The issue is described here and is a bit64 issue: https://github.com/Rdatatable/data.table/issues/488 I wrote this as a "solution": dt[as.character(my_col) == "9218868437227407266", my_col := as.integer64(NA)] It works but I wonder how I can write that in dplyr syntax to use the %>% without unexpected crashes. Many thanks in advance ! A: We can use replace library(dplyr) dt %>% mutate(my_col = replace(my_col, as.character(my_col) == "9218868437227407266", as.integer64(NA))
{ "pile_set_name": "StackExchange" }
Q: HtmlWebpackPlugin load bundle.[hash].js/css into base twig file I have two entries in my webpack.config.js. One for the JS and one for the SCSS. I can run in development and product mode. If i create a production build I get the following files: index.html, main[hash].js, main[hash].css. In the index.html i have the link and script tag with the src to the files. How do i load these link & script tags in my base.twig file that get loaded when deploying the application? In development it loads the main.js from the base.twig and in that file everything is included. base.twig <script src="assets/main.js"></script> Folder structure: index.html <html> <head> <meta charset="UTF-8"> <title>Webpack App</title> <link href="main.7a67bd4eae959f87c9bc.css" rel="stylesheet"></head> <body> <script type="text/javascript" src="main.7a67bd4eae959f87c9bc.js"></script></body> </html> webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const BrowserSyncPlugin = require('browser-sync-webpack-plugin'); const CopyPlugin = require('copy-webpack-plugin'); module.exports = (env, options) => { const devMode = options.mode === 'development'; return { mode: (devMode) ? 'development' : 'production', watch: devMode, devtool: "source-map", entry: [ './resources/javascript/index.js', './resources/sass/app.scss' ], output: { path: path.resolve(__dirname, 'public/assets'), filename: devMode ? '[name].js' : '[name].[hash].js' }, module: { rules: [ { test: /\.twig/, loader: 'twig-loader' }, { test: /\.js$/, exclude: /(node_modules)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } }, { test: /\.(sa|sc|c)ss$/, use: [ { loader: devMode ? 'style-loader' : MiniCssExtractPlugin.loader, }, { loader: "css-loader", }, { loader: "postcss-loader" }, { loader: "sass-loader", options: { implementation: require("sass") } } ] }, { test: /\.(png|jpe?g|gif|svg)$/, use: [ { loader: "file-loader", options: { outputPath: 'images' } } ] }, { test: /\.(woff|woff2|ttf|otf|eot)$/, use: [ { loader: "file-loader", options: { outputPath: 'fonts' } } ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: devMode ? '[name].css' : '[name].[hash].css', }), new BrowserSyncPlugin({ proxy: 'https://dev.identity/oauth/authorize?response_type=code&client_id=1c9e2b58-2d01-4c92-a603-c934dfa9bc78&redirect_uri=https://localhost/hooray&state=aaaaa&code_challenge=12345678901234567890123456789012345678901123&code_challenge_method=plain&resource=https://cloud.ctdxapis.io&scope=cloud:my-profile' }), new CopyPlugin([ { from: './resources/images', to: './images' } ]), new HtmlWebpackPlugin({ }), ] }; }; Updated structure: A: You can provide templateContent config property of HTMLWebpackPlugin in-order to generate your assets.twig file new HtmlWebpackPlugin({ templateContent: function(params) { return ` {% block jsAssets %} ${params.htmlWebpackPlugin.files.js.map( file => `<script src="${file}"></script>`, )} {% endblock %} {% block cssAssets %} ${params.htmlWebpackPlugin.files.css.map( file => `<link rel="stylesheet" type="text/css" href="${file}">`, )} {% endblock %}`; }, filename: '../../resources/templates/assets.twig', inject: false, // prevents from the plugin to auto-inject html tags }); Then in your base.twig just use the blocks method to specify where to render your assets. {{ block("jsAssets", "assets.twig") }} {{ block("cssAssets", "assets.twig") }}
{ "pile_set_name": "StackExchange" }
Q: fosuserbundle and user in security token I'm using fosuserbundle with a custom authentication provider and mongodb persisted user. User class has a property persisted as a collection of reference to another mongodb collection, but this and other fields are not serialized in security token. In another project of mine, the user as a plain old php object is correctly saved in and fetched from the token, so I don't understand if the problem is due to mongodb hydration overhaed. A: Usually, in the token are persisted the user information that needs to be serialized. The fosuserbundle will serialize the properties: /** * Serializes the user. * * The serialized data have to contain the fields used by the equals method and the username. * * @return string */ public function serialize() { return serialize(array( $this->password, $this->salt, $this->usernameCanonical, $this->username, $this->expired, $this->locked, $this->credentialsExpired, $this->enabled, $this->id, )); } that are defined in the "serialize" method. If you want to serialize other properties you need to implement in your User class the methods serialize/unserialize. It's not a good practice, because when you retrieve the user from the token, normally he's refreshed. Have you implemented the method "refreshToken" in your UserProvider?
{ "pile_set_name": "StackExchange" }
Q: How to add sessionDelegate option on SocketManager's config Swift I'm tryng to connect to a self signed SSL URL. But when I add sessionDelegate as option it's not working. import Foundation import SocketIO import UIKit class SocketM: NSObject, URLSessionDelegate { static var manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config: [.log(true), .secure(true), .selfSigned(true), .sessionDelegate(self)]) func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let protectionSpace = challenge.protectionSpace guard protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, protectionSpace.host.contains(Services_Routes.host) else { completionHandler(.performDefaultHandling, nil) return } guard let serverTrust = protectionSpace.serverTrust else { completionHandler(.performDefaultHandling, nil) return } let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } It returns me Type 'Any' has no member 'sessionDelegate' When I try : SocketIOClientOption.sessionDelegate(self) Type '(SocketM) -> () -> SocketM' does not conform to protocol 'URLSessionDelegate' Can someone explain me the problem? Thanks ! A: You are creating static variable and passing delegate as "self", you can't use self before initialising object. If you don't need static object of manager then you can write code as class SocketM: NSObject, URLSessionDelegate { var manager: SocketManager? override init() { super.init() manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config: [.log(true), .reconnects(true), .selfSigned(true), .sessionDelegate(self)]) } } And If you want static manager the class SocketM: NSObject, URLSessionDelegate { static var manager = SocketManager(socketURL: URL(string:"https://localhost:8000")!, config: [.log(true), .reconnects(true), .selfSigned(true)]) override init() { super.init() SocketM.manager.config.insert(.sessionDelegate(self)) } }
{ "pile_set_name": "StackExchange" }
Q: SQL open failure leads to systematic TransactionAbortedException (due to timeout) until application pool is recycled We have a Worker Role that is hosted in Azure and uses SQL Azure for its database. Occasionally, there will be an SQL connection error: System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: Session Provider, error: 19 - Physical connection is not usable) Once this error has occurred, all following attempts to create a connection/transaction will fail with the following error: System.Transactions.TransactionAbortedException: The transaction has aborted. ---> System.TimeoutException: Transaction Timeout essentially rendering our entire service unusable (since all of our services require database access). The only solution we've found is to manually recycle the application pool. Obviously, this is causing issues since whenever this happens, our instance becomes unable to service requests until somebody manually recycles the application pool. Obviously, we're looking for another solution, either a fix to the issue altogether or a workaround that we can put into place to automate the application pool recycle (or something that can achieve a similar result). One thing to note, we are using Entity Framework 4 (old project, it works as-is and we've found no reason to upgrade yet). As such, since EF4 will open/close the database connection for each query or SaveChanges call, our code forces the connection to open when the transaction is created using ObjectContext.Connection.Open() to avoid having the transaction promoted to a MSDTC if there are multiple queries or updates within the same transaction. It is during this initial open that the exception occurs. For the TransactionScope we are using TransactionScopeOption.Required and IsolationLevel.ReadCommitted. A: A solution has been found! The issue is that we were using an object EFTransaction to wrap both the TransactionScope as well as the ObjectContext in order to automate the creation of the scope and the opening of the connection. This code was found in the constructor of this type: this._transactionScope = new TransactionScope(transactionScopeOption, transactionOptions); this.OpenConnection(); While the class itself is IDisposable, the exception is happening within the constructor. As such, the reference to the object never gets assigned and the Dispose() never gets called. Therefore, the _transactionScope field never gets Disposed and the transaction is stuck in limbo, which causes following transaction requests to timeout. The solution is two-fold: first, implement a finalizer on the class. While the time of finalization execution is undefined, it's still preferable to leaving a pending transaction in limbo. At least at some point the object will get GC'd and the transaction disposed and other transactions will resume. Second, wrap this.OpenConnection() in a try/catch and Dispose() the transaction if the open fails: this._transactionScope = new TransactionScope(transactionScopeOption, transactionOptions); try { this.OpenConnection(); } catch { this._transactionScope.Dispose(); throw; } This handles the exception case and leaves no pending "zombie" transactions.
{ "pile_set_name": "StackExchange" }
Q: TensorFlow XOR code works fine with two dimensional target but not without? Trying to implement a very basic XOR FFNN in TensorFlow. I may just be misunderstanding the code but can anyone see an obvious reason why this won't work-- blows up to NaNs and starts with loss of $0$. Toggles are on works/ doesn't work if you want to mess around with it. Thanks! import math import tensorflow as tf import numpy as np HIDDEN_NODES = 10 x = tf.placeholder(tf.float32, [None, 2]) W_hidden = tf.Variable(tf.truncated_normal([2, HIDDEN_NODES])) b_hidden = tf.Variable(tf.zeros([HIDDEN_NODES])) hidden = tf.nn.relu(tf.matmul(x, W_hidden) + b_hidden) #----------------- #DOESN"T WORK W_logits = tf.Variable(tf.truncated_normal([HIDDEN_NODES, 1])) b_logits = tf.Variable(tf.zeros([1])) logits = tf.add(tf.matmul(hidden, W_logits),b_logits) #WORKS # W_logits = tf.Variable(tf.truncated_normal([HIDDEN_NODES, 2])) # b_logits = tf.Variable(tf.zeros([2])) # logits = tf.add(tf.matmul(hidden, W_logits),b_logits) #----------------- y = tf.nn.softmax(logits) #----------------- #DOESN"T WORK y_input = tf.placeholder(tf.float32, [None, 1]) #WORKS #y_input = tf.placeholder(tf.float32, [None, 2]) #----------------- cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, y_input) loss = tf.reduce_mean(cross_entropy) loss = cross_entropy train_op = tf.train.GradientDescentOptimizer(0.1).minimize(loss) init_op = tf.initialize_all_variables() sess = tf.Session() sess.run(init_op) xTrain = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) #----------------- #DOESN"T WORK yTrain = np.array([[0], [1], [1], [0]]) # WORKS #yTrain = np.array([[1, 0], [0, 1], [0, 1], [1, 0]]) #----------------- for i in xrange(500): _, loss_val,logitsval = sess.run([train_op, loss,logits], feed_dict={x: xTrain, y_input: yTrain}) if i % 10 == 0: print "Step:", i, "Current loss:", loss_val,"logits",logitsval print sess.run(y,feed_dict={x: xTrain}) A: TL;DR: For this to work, you should use loss = tf.nn.l2_loss(logits - y_input) ...instead of tf.nn.softmax_cross_entropy_with_logits. The tf.nn.softmax_cross_entropy_with_logits operator expects the logits and labels inputs to be a matrix of size batch_size by num_classes. Each row of logits is an unscaled probability distribution across the classes; and each row of labels is a one-hot encoding of the true class for each example in the batch. If the inputs do not match these assumptions, the training process may diverge. In this code, the logits are batch_size by 1, which means that there is only a single class, and the softmax outputs a prediction of class 0 for all of the examples; the labels are not one-hot. If you look at the implementation of the operator, the backprop value for tf.nn.softmax_cross_entropy_with_logits is: // backprop: prob - labels, where // prob = exp(logits - max_logits) / sum(exp(logits - max_logits)) This will be [[1], [1], [1], [1]] - [[0], [1], [1], [0]] in every step, which clearly does not converge.
{ "pile_set_name": "StackExchange" }
Q: Is it true that the US president can execute anyone without a trial? Sorry if this is a stupid question. I am not an American (i.e. Canadian) and I was speaking to a friend today and he told me that apparently Obama passed a law last year that gives the president the power to execute any American citizen without having an actual trial? Now please tell me this isn't true. Thanks. A: In a roundabout way, there's some truth to that statement, though it's a bit more nuanced than that. It refers to the administration's claims that they have the power to go after high-level terrorist organizations--including targeting individuals (who could be citizens of the US). It's an interesting, but also complex issue that's really about how we define war and enemy combatants in the modern era. There's been plenty of coverage on it over the past year, so plenty to search on. Here's a more recent article that talks about the aspect of US soil, which eventually led to the recent Rand Paul filibuster this past week: http://www.guardian.co.uk/commentisfree/2013/feb/22/obama-brennan-paul-assassinations-filibuster A: Short version: No and yes. Not "anyone" (see DA's answer for more detail, but, but yes, some people without trial, when "an informed, high-level official of the U.S. government" determines the target is an imminent threat, when capture would be infeasible and when the operation is "conducted consistent with applicable law of war principles." (src) However, this is not new or unique to USA - heads of state always had ability to have enemy combatants killed outside judicial system - it's called "waging war". The only difference is that in this case, the definition of what specifically constitutes an enemy combatant is shifting away from early-20th-century idea of a uniformed member of an official state army, to include asymmetric warfare guerrilla fighters and their leaders despite not being associated with a specific officially recognized state. This is supposedly based on standard "self defense" war doctrine which is recognized by United Nations, although specific legal issues are subject to much debating and frequently are more a matter of opinion than law. A: No, not anyone. US citizens on US soil, not posing an imminent threat may not be executed. What your friend told you likely stems from comments made by our current Attorney Genrral, Eric Holder. In response to a question about using drone strikes against US citizens, here in the United States, Holder wrote: [...] The question you have posed is therefore entirely hypothetical, unlikely to occur, and one we hope no president will ever have to confront. It is possible, I suppose, to imagine an extraordinary circumstance in which it would be necessary and appropriate under the Constitution and applicable laws of the United States for the President to authorize the military to use lethal force within the territory of the United States. For example, the president could conceivably have no choice but to authorize the military to use such force if necessary to protect the homeland in the circumstances like a catastrophic attack like the ones suffered on December 7, 1941, and September 11, 2001. [...] After Rand Paul filibustered the nomination of John Brennan for CIA director, Holder clarified his remarks. "Does the president have the authority to use a weaponized drone to kill an American not engaged in combat on an American soil?" The answer to that question is no." Under questioning by Senator Ted Cruz, Eric Holder seemed to be hung up on using the word appropriate, when asked if using a drone strike on a US citizen in the US who was not an imminent threat was constitutional. It is important to note that the US Justice Department does believe that they have the authority to execute US citizens that are not in the United States, that would be infeasible to capture, and that are not currently posing an immenent threat. This legal analysis, a 50-page internal memo, was performed a year before Anwar al-Awlaki was killed in Yemen, along with another US Citizen who wasn't the target of the attack. A white-paper version of the 50-page memo was released to the public, the Justice Department removing parts it considered protected due to attorney client privilege.
{ "pile_set_name": "StackExchange" }
Q: How to write multiple cron expression Execute the job on Monday until Saturday from 7pm until 9am and the whole day for Sunday. I try to input multiple expressions of cron, but it's not working. Can anyone get me the solution for this? 1. " * * 19-8 ? * MON,TUE,WED,THU,FRI,SAT " 2. " * * * ? * SUN " A: Since you are using Quartz, you can create several different CronTriggers, and schedule all of them to your required job. E.g.(change the cron expressions to the expressions that you need) SchedulerFactory sf = new StdSchedulerFactory(); Scheduler sched = sf.getScheduler(); JobDetail job = newJob(SimpleJob.class) .withIdentity("job1", "group1") .build(); Set<Trigger> triggers = new HashSet<>(); CronTrigger trigger = newTrigger() .withIdentity("trigger1", "group1") .withSchedule(cronSchedule("0/20 * * * * ?")) .build(); triggers.add(trigger1); CronTrigger trigger2 = newTrigger() .withIdentity("trigger2", "group1") .withSchedule(cronSchedule("15 0/2 * * * ?")) .build(); triggers.add(trigger2); CronTrigger trigger3 = newTrigger() .withIdentity("trigger3", "group1") .withSchedule(cronSchedule("0 0/2 8-17 * * ?")) .build(); triggers.add(trigger3); scheduler.scheduleJob(job, triggers, false); You can't create one trigger with multiple CronExpressions. A: CronMaker is a utility which helps you to build cron expressions. CronMaker uses Quartz open source scheduler. Generated expressions are based on Quartz cron format. This expressions defines the start of a task. It does not define its duration (it belongs to the task). - used to specify ranges. For example, "10-12" in the hour field means "the hours 10, 11 and 12" CronTrigger Tutorial
{ "pile_set_name": "StackExchange" }
Q: Remove Repeated Pages in iReport I am using List component iReport the data is populating but the pdf has two pages. The data in 2nd page is same as first page. I have 25 records in db and I want to populate in one page. The table data keep repeating in pdf pages. Is there any setting in list to avoid it? I will appreciate for your great help. <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="test" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20"> <property name="ireport.zoom" value="1.0"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <subDataset name="dataset1"> <parameter name="ID" class="java.lang.Integer"/> <queryString> <![CDATA[select * from CALENDAR WHERE REGION=$P{ID} ]]> </queryString> <field name="ID" class="java.lang.Integer"/> <field name="NAME" class="java.lang.String"/> <field name="REGION" class="java.lang.Integer"/> <field name="YEAR" class="java.lang.Integer"/> <field name="HOLIDAY_NAME" class="java.lang.String"/> <field name="DATE_PICKER" class="java.sql.Date"/> <field name="APPLICABLE_FROM" class="java.sql.Date"/> <field name="APPLICABLE_TO" class="java.sql.Date"/> </subDataset> <parameter name="ID" class="java.lang.Integer"/> <queryString> <![CDATA[select * from USERS]]> </queryString> <field name="ID" class="java.lang.Integer"/> <field name="EMP_ID" class="java.lang.Integer"/> <field name="LEVEL_ID" class="java.lang.Integer"/> <field name="REG_DIV_ID" class="java.lang.Integer"/> <field name="PROFILE_ID" class="java.lang.Integer"/> <field name="FINANCE_ID" class="java.lang.Integer"/> <field name="NOMINEE_ID" class="java.lang.Integer"/> <field name="PASSPORT_ID" class="java.lang.Integer"/> <field name="PERSONAL_ID" class="java.lang.Integer"/> <field name="SALARY_ID" class="java.lang.Integer"/> <field name="STATUS" class="java.lang.Boolean"/> <field name="CREATE_DATE" class="java.sql.Timestamp"/> <background> <band splitType="Stretch"/> </background> <pageHeader> <band height="87"> <image> <reportElement positionType="Float" x="52" y="38" width="123" height="47"/> <imageExpression class="java.lang.String"><![CDATA["/home/user/Desktop/image003.jpg"]]></imageExpression> </image> <image> <reportElement positionType="Float" x="453" y="30" width="62" height="55"/> <imageExpression class="java.lang.String"><![CDATA["/home/user/Desktop/image002.jpg"]]></imageExpression> </image> </band> </pageHeader> <columnHeader> <band splitType="Stretch"/> </columnHeader> <detail> <band height="89" splitType="Stretch"> <componentElement> <reportElement positionType="Float" stretchType="RelativeToTallestObject" x="52" y="53" width="464" height="29"/> <jr:list xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" printOrder="Vertical"> <datasetRun subDataset="dataset1"> <datasetParameter name="ID"> <datasetParameterExpression><![CDATA[$P{ID}]]></datasetParameterExpression> </datasetParameter> <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression> </datasetRun> <jr:listContents height="29" width="464"> <textField> <reportElement positionType="Float" stretchType="RelativeToBandHeight" x="28" y="5" width="197" height="20"/> <textElement/> <textFieldExpression class="java.lang.String"><![CDATA[$F{HOLIDAY_NAME}+" "]]></textFieldExpression> </textField> <line> <reportElement x="0" y="27" width="464" height="1"/> </line> <line> <reportElement x="0" y="1" width="1" height="28"/> </line> <line> <reportElement x="463" y="0" width="1" height="28"/> </line> <line> <reportElement x="225" y="0" width="1" height="28"/> </line> <textField> <reportElement positionType="Float" stretchType="RelativeToBandHeight" x="301" y="6" width="100" height="20"/> <textElement/> <textFieldExpression class="java.lang.String"><![CDATA[$F{DATE_PICKER}]]></textFieldExpression> </textField> </jr:listContents> </jr:list> </componentElement> <rectangle> <reportElement x="52" y="30" width="464" height="23" backcolor="#DD6626"/> </rectangle> <textField> <reportElement x="80" y="35" width="181" height="23"/> <textElement> <font size="12" isBold="true"/> </textElement> <textFieldExpression class="java.lang.String"><![CDATA["HOLIDAYS LIST"]]></textFieldExpression> </textField> <textField> <reportElement x="353" y="35" width="124" height="23"/> <textElement> <font size="12" isBold="true"/> </textElement> <textFieldExpression class="java.lang.String"><![CDATA["DATE"]]></textFieldExpression> </textField> </band> </detail> <columnFooter> <band splitType="Stretch"/> </columnFooter> <pageFooter> <band height="35" splitType="Stretch"/> </pageFooter> <summary> <band splitType="Stretch"/> </summary> </jasperReport> A: Your report is designed so the List repeats for every user. If that's not what you want then you need to either change the main query select * from USERS to something that returns only a single row, or you need to move the List into a band that does not repeat (like the Title or the Summary band).
{ "pile_set_name": "StackExchange" }
Q: How to set "type" in controller using Single Table Inheritance in Rails? I am new to rails and trying to set the "type" of a subclass in my create controller. How do I go about this? Here is my code: Post.rb class Post < ActiveRecord::Base attr_accessible :body, :name, :song_id, :user_id, :artist_id, :type belongs_to :song belongs_to :user belongs_to :artist end Picture.rb class Picture < Post end And finally the controller: def create @picture = Post.new(params[:picture]) @picture.type = "Picture" if @picture.save redirect_to @artist, :notice => "Successfully posted picture." else render :action => 'new' end end A: Although I don't see why the code you have wouldn't work, it would be better to do @picture = Picture.new(params[:picture]) :type will be automatically set to "Picture" if you do this.
{ "pile_set_name": "StackExchange" }
Q: Algorithm on interview Recently I was asked the following interview question: You have two sets of numbers of the same length N, for example A = [3, 5, 9] and B = [7, 5, 1]. Next, for each position i in range 0..N-1, you can pick either number A[i] or B[i], so at the end you will have another array C of length N which consists in elements from A and B. If sum of all elements in C is less than or equal to K, then such array is good. Please write an algorithm to figure out the total number of good arrays by given arrays A, B and number K. The only solution I've come up is Dynamic Programming approach, when we have a matrix of size NxK and M[i][j] represents how many combinations could we have for number X[i] if current sum is equal to j. But looks like they expected me to come up with a formula. Could you please help me with that? At least what direction should I look for? Will appreciate any help. Thanks. A: After some consideration, I believe this is an NP-complete problem. Consider: A = [0, 0, 0, ..., 0] B = [b1, b2, b3, ..., bn] Note that every construction of the third set C = ( A[i] or B[i] for i = 0..n ) is is just the union of some subset of A and some subset of B. In this case, since every subset of A sums to 0, the sum of C is the same as the sum of some subset of B. Now your question "How many ways can we construct C with a sum less than K?" can be restated as "How many subsets of B sum to less than K?". Solving this problem for K = 1 and K = 0 yields the solution to the subset sum problem for B (the difference between the two solutions is the number of subsets that sum to 0). By similar argument, even in the general case where A contains nonzero elements, we can construct an array S = [b1-a1, b2-a2, b3-a3, ..., bn-an], and the question becomes "How many subsets of S sum to less than K - sum(A)?" Since the subset sum problem is NP-complete, this problem must be also. So with that in mind, I would venture that the dynamic programming solution you proposed is the best you can do, and certainly no magic formula exists.
{ "pile_set_name": "StackExchange" }
Q: Regarding Oracle Error I am getting the below oracle error. I checked the test scheme for any constraint name CMF_CMP using toad. But i am unable to find it. How do i detect the reason for failure and how to resolve it. ERROR at line 1: ORA-20001: -2298: ORA-02298: cannot validate (TEST.FMF_CMP) - parent keys not found ORA-06512: at test.test_SYN", line 46 A: Sounds like you have an orphan! You'll need to track it down and give it a parent or drop the orphan http://www.techonthenet.com/oracle/errors/ora02298.php select * from test_SYN ts where PARENTID not EXISTS( select NULL from test_PARENT tp where tp.ID = ts.ParentID) Are you trying to enable the constraint or am I just missing the mark?
{ "pile_set_name": "StackExchange" }
Q: Rename language after item is created I'm using sitecore 6.5 with two languages installed, en (default) and fr-CA. There are items in the tree with content in both en and fr-CA. The problem is that the French url has 'fr-CA' in it and we want that to be 'fr', for example: http://website.com/fr/page.aspx instead of http://website.com/fr-CA/page.aspx I tried renaming the language from 'fr-CA' to 'fr' and that fixed the url but the content still points to the old language 'fr-CA', so the item shows three languages: en, fr and fr-CA. It's not recognizing the name change. Any suggestions are much appreciated. Thanks, Tarek A: The problem is you have created fr-CA versions of your items which cannot be fixed by renaming the language .. you can now make a fr version but, like you are seeing, this means there are now 3 possible versions. One suggestion is to leave the languages in Sitecore alone and alter how links are served and processed instead. You would probably need to look at adding your own method into the httpRequestBegin pipeline in Sitecore. This would follow the LanguageResolver entry. You can then parse the RawUrl and set Sitecore.Context.Langauge' to French if the first element in it matched/fr/`. Extremely quick & dirty example: public class MyLanguageResolver : HttpRequestProcessor { public override void Process(HttpRequestArgs args) { string languageText = WebUtil.ExtractLanguageName(args.Context.Request.RawUrl); if(languageText == "fr") { Sitecore.Context.Language = LanguageManager.GetLanguage("fr-CA"); } } } You would probably also have to override the LinkProvider in the <linkManager> section of the web.config to format your URLs when they are resolved by Sitecore. Another extremely quick & dirty example: public class MyLinkProvider : LinkProvider { public override string GetItemUrl(Sitecore.Data.Items.Item item, UrlOptions options) { var url = base.GetItemUrl(item, options); url = url.Replace("/fr-CA/", "/fr/"); return url; } } Another way (slightly more long-winded as it will need to be executed via a script) is to copy the data from the fr-CA version to the fr version and then delete the fr-CA version of each item. Rough helper method that encompasses what you're trying to do private void CopyLanguage(ID id, Language sourceLanguage, Language destinationLanguage) { var master = Database.GetDatabase("master"); var sourceLanguageItem = master.GetItem(id, sourceLanguage); var destinationLanguageItem = master.GetItem(id, destinationLanguage); using (new SecurityDisabler()) { destinationLanguageItem.Editing.BeginEdit(); //for each field in source, create in destination if it does not exist foreach (Field sf in sourceLanguageItem.Fields) { if (sf.Name.Contains("_")) continue; destinationLanguageItem.Fields[sf.Name].Value = sf.Value; } destinationLanguageItem.Editing.AcceptChanges(); ////Remove the source language version ItemManager.RemoveVersions(sourceLanguageItem,sourceLanguage, SecurityCheck.Disable); } } Another way to update the languages on your content items is: Export the fr-CA language to a .xml file (Using the Control Panel) In the .xml file replace all and tags with the and Rename fr-CA language in the master database to the fr Import language from the .xml file Run Clean Up Databases task (from the Control Panel) Also you can create a sql script that will change fr-CA language with the fr for all records in the UnversionedFields and VersionedFields tables. If you need any more information or examples please let me know. :)
{ "pile_set_name": "StackExchange" }
Q: Does $AB+BA=0$ imply $AB=BA=0$ when $A$ is real semidefinite matrix? This is a general question that came to my mind while listening to a lecture(although its framing may make it look like a textbook question). Suppose that $A$ and $B$ be real matrices. $A$ is symmetric and positive semi-definite$(x^tAx\ge0\ \ \forall x\in \mathbb{R}^n)$. Let $AB+BA=0$. Does this imply $AB=BA=0$? If yes can you give me some example? A: Let $v$ be an eigenvector of $A$ with eigenvalue $\lambda$. Then $$ 0 = A(Bv) + B(Av) = A(Bv)+\lambda Bv\Longrightarrow A(Bv) = -\lambda Bv $$ what this means is that $Bv$ is also an eigenvector of $A$ with eigenvalue $-\lambda$. But since $A$ is positive semi-definite all eigenvalues of $A$ are $\geq 0$. If $\lambda=0$, so we have two possiblities: Either $v$ is an eigenvector with eigenvalue zero, in which case $A(Bv) = 0$, This means $ABv = BAv = 0$ for all eigenvectors corresponding to eigenvalue zero. Or $v$ is an eigenvector with eigenvalue $\lambda>0$. Suppose $Bv\neq 0$, then $Bv$, by above observation is an eigenvector of $A$ with negative eigenvalue! This is impossible, so $Bv=0$. Therefore no only $ABv = 0$, we also have $BAv = \lambda Bv = 0$. Since all vectors can be written as a linear composition of these eigenvectors, we have $AB=BA = 0$ in these circumstances. Extra: If you are also interested in what this $B$ can actually be if $AB+BA = 0$, note that if $w$ is any vector, and $P_0$ is the porjection linear transformation which sends $w$ to the subspace of vectors with eigenvalue zero. Then we know the following: Write $w = P_0w + (1-P_0)w$, then by second observation above $B(1-P_0)w = 0$. So in the basis in which $A$ is diagonal (since $A$ is symmetric it is diagonalizable), $B$ is necessarily of the form $$ B=\begin{pmatrix} B_0 & 0\\ 0 & 0 \end{pmatrix} $$ In other words $B$ satisfies $AB+BA=0$ if and only if $P_0BP_0=B$.
{ "pile_set_name": "StackExchange" }
Q: HTTPS Link Wrapping Regex I have this regular expression which matches all http:// links (http:\/\/[a-z0-9\.\/]+)/i How do i modify it to include https:// links? A: You need to add s after the string http and also add ? after s to make it optional /(https?:\/\/[a-z0-9\.\/]+)/i
{ "pile_set_name": "StackExchange" }
Q: Julian to gregorian date with OutOfBoundsDatetime I'm working with a pandas dataframe and I have a DATE column that contains a julian date. I want to convert every value of that column to a gregorian date. To achieve that I used the following code: df[['DATE']] = df[['DATE']].apply(lambda x: pd.to_datetime(x - pd.Timestamp(0).to_julian_date(), unit='D')) Unfortunately, I get an error that looks like this: OutOfBoundsDatetime: ("cannot convert input 381088.5 with the unit 'D'", u'occurred at index MXPLD_DATE') When I look for the input value that causing problem in the dataframe, it doesn't exist at all, I don't know where 381088.5 come from. Can you tell me what I'm doing wrong? Thank you. EDIT 1 I tried @jezrael solution but I still got a similar error. df['DATE'] = pd.to_datetime(df['DATE'], unit='D', origin='julian') Error: --------------------------------------------------------------------------- OutOfBoundsDatetime Traceback (most recent call last) <ipython-input-18-4353e2be1ced> in <module>() ----> 1 df['DATE'] = pd.to_datetime(df['DATE'], unit='D', origin='julian') /opt/anaconda2/lib/python2.7/site-packages/pandas/core/tools/datetimes.pyc in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin) 469 raise tslib.OutOfBoundsDatetime( 470 "{original} is Out of Bounds for " --> 471 "origin='julian'".format(original=original)) 472 473 elif origin not in ['unix', 'julian']: OutOfBoundsDatetime: 0 2457184 1 2457155 2 2457155 3 2457155 4 2457155 5 2457155 6 2457155 7 2457155 8 2457155 9 2457155 10 2457155 11 2457155 12 2457155 13 2457155 14 2457155 15 2457155 16 2457155 17 2457155 18 2457155 19 2457155 20 2457155 21 2457155 22 2457155 23 2457155 24 2457155 25 2457155 26 2457155 27 2457155 28 2457701 29 2457701 ... 4597928 2457724 4597929 2457724 4597930 2457724 4597931 2457724 4597932 2457724 4597933 2457724 4597934 2457724 4597935 2457724 4597936 2457724 4597937 2457724 4597938 2457724 4597939 2457724 4597940 2457724 4597941 2457724 4597942 2457724 4597943 2457724 4597944 2457724 4597945 2457724 4597946 2457724 4597947 2457724 4597948 2457724 4597949 2457724 4597950 2457724 4597951 2457724 4597952 2457724 4597953 2457724 4597954 2457724 4597955 2457724 4597956 2457724 4597957 2457724 Name: DATE, Length: 4597958, dtype: int64 is Out of Bounds for origin='julian' A: I believe you need to_datetime with parameter origin: df = pd.DataFrame({'julian':[2458072.5, 2458073.5]}) df['date'] = pd.to_datetime(df['julian'], unit='D', origin='julian') print (df) julian date 0 2458072.5 2017-11-15 1 2458073.5 2017-11-16 EDIT: There is problem some datetime OutOfBounds. So first checked timestamp limitations: In [66]: pd.Timestamp.min Out[66]: Timestamp('1677-09-21 00:12:43.145225') In [67]: pd.Timestamp.max Out[67]: Timestamp('2262-04-11 23:47:16.854775807') And then get minimal julian datetimes (by convertin online, e.g. here): maxdate = 2547338 mindate = 2333836 Then add NaN for dates out of range, e.g. by where: df = pd.DataFrame({'julian':[2821676, 2547338, 1, 2333836]}) maxdate = 2547338 mindate = 2333836 clean_dates = df['julian'].where(df['julian'].between(mindate, maxdate)) print (clean_dates) 0 NaN 1 2547338.0 2 NaN 3 2333836.0 df['date'] = pd.to_datetime(clean_dates, unit='D', origin='julian') print (df) julian date 0 2821676 NaT 1 2547338 2262-04-10 12:00:00 2 1 NaT 3 2333836 1677-09-21 12:00:00 And last apply solution to your data - there are 2 values converted to NaT: print (df['MXPLD_DATE'][~df['MXPLD_DATE'].between(mindate, maxdate)]) 1217806 2821676 3167148 2821676 Name: MXPLD_DATE, dtype: int64 clean_dates = df['MXPLD_DATE'].where(df['MXPLD_DATE'].between(mindate, maxdate)) df['MXPLD_DATE'] = pd.to_datetime(clean_dates, unit='D', origin='julian') print (df['MXPLD_DATE']) 0 2015-06-10 12:00:00 1 2015-05-12 12:00:00 2 2015-05-12 12:00:00 3 2015-05-12 12:00:00 4 2015-05-12 12:00:00 5 2015-05-12 12:00:00 6 2015-05-12 12:00:00 7 2015-05-12 12:00:00 8 2015-05-12 12:00:00 9 2015-05-12 12:00:00 10 2015-05-12 12:00:00
{ "pile_set_name": "StackExchange" }
Q: How to wait for for loop with async requests to finish in node.js? I want to make multiple requests in node.js to get a couple of external API responses, to combine them into one array. I'm using a for loop to achieve this. Here's my code: res.setHeader('Content-Type', 'application/json'); const sub = req.query.days_subtract; const enddate = req.query.end_date; var array = []; for (var i = 0; i < sub; i++) { request("https://api.nasa.gov/planetary/apod?date=" + subtractDate(enddate, i) + "&api_key=DEMO_KEY", function(error, response, body) { array.push(body); // console.log(body); }); } res.send(array); but this piece of code returns [] all the time. I know it's because the for loop only starts these async requests, but it doesn't wait for them to finish. I tried to use async/await but that didn't work either. So how to wait for this loop to finish getting requests and to finish pushing them to the array so it can be shown to users? A: For your use case, using await with Promise.all is probably the most performant way to go about it. Your code should look something like this: res.setHeader('Content-Type', 'application/json'); const sub = req.query.days_subtract; const enddate = req.query.end_date; var promiseArray = []; for (var i = 0; i < sub; i++) { promiseArray.push(new Promise((resolve, reject) => { request("https://api.nasa.gov/planetary/apod?date=" + subtractDate(enddate, i) + "&api_key=DEMO_KEY", function(error, response, body) { if (error) reject(error); else resolve(body) }) })) } res.send(await Promise.all(promiseArray)); A: Use something like request-promise. If you await each request in the for loop, then all requests are done in series. If each request is independent and doesn't need to be done one after the other, this is inefficient. The best way to handle something like this is to do them all in parallel and then wait for them all to complete. This is done by creating an array of request promises and then using await Promise.all(promiseArray) to wait for all promises to resolve. var promises = []; for (var i = 0; i < sub; i++) { const promise = request("https://api.nasa.gov/planetary/apod?date=" + subtractDate(enddate, i) + "&api_key=DEMO_KEY"); promises.push(promise); } const array = await Promise.all(promises);
{ "pile_set_name": "StackExchange" }
Q: Why does Entity Framework not return a trimmed string for a nvarchar(MAX) field? I'm currently working on a Silverlight application connected to a SQL Server 2008 Express database that is largely based on a demo on Brad Abrams' blog. (NOTE: The demo file at the specified link is actually a different solution that the one he shows on the live running application. The demo in the blog post uses Entity Framework, while the live application uses POCO). I am trying to figure out why Entity framework is returning a fixed width string for fields that are set up as nvarchar(MAX). (By "Fixed Width," I mean something like "DC ", where there's white space at the end of the content of the string). In the demo file, which is connected to an included MDF file, the Name field is a nvarchar(max) field, and entity framework correctly returns the trimmed string. However, in my personal application, which is connected to a SQLEXPRESS database, a nvarchar(max) field is still returned with the white space at the end, fixed width, and untrimmed. When I hover over the return this._itemPrefix; line of Entity Model C# file at runtime, it shows the item with the white space, untrimmed. I can't figure out why it works in his demo but not in my file. Is there something I can do other than alter the code in the entityModel.Designer.cs to have it return a trimmed string? Has anyone else ran into this issue? A: How many spaces? The only reason I can think of, is because you stored the string that way.Working as intended. You should trim your strings with Trim() or TrimEnd() before you store them if you're using Entity Framework.
{ "pile_set_name": "StackExchange" }
Q: Limiting External Access to AWS SQL Server Instance I have a SQL Server instance on AWS that I have opened to external access by altering my security group to allow access from “Everywhere". +-------------+----------+------------+--------------------------+ | Type | Protocol | Port Range | Source | +-------------+----------+------------+--------------------------+ | MSSQL | TCP | 1433 | Custom 0.0.0.0/0 | | MSSQL | TCP | 1433 | Custom ::/0 | † +-------------+----------+------------+--------------------------+ I would like to restrict this access to this database, though not via IP addresses since the service I will use to access it has no static IP. How can I tighten inbound access to this database for use with an external service (eg Firebase function or NodeJS application)? † AWS security group rule that is generated when "Everywhere" and "MSSQL" are selected in the Security Group inbound rules section A: AFAIK, there is no direct way to achieve this without knowing the static IP or the IP range from where you need to access your EC2 instance (Where you host your SQL Server). But... You can include your instance behind an API Gateway and then enable IAM authentication for the API method in the API Gateway. Then use IAM policies (along with resource policies) to designate permissions for your API's users. More: https://aws.amazon.com/premiumsupport/knowledge-center/iam-authentication-api-gateway/ A: There is no direct way to restrict. AWS Cloud - solution (all services / instance in AWS) If your NodeJS application is running on AWS or you are using AWS Lambda service you can allow access across security groups alone within same VPC. (If multiple accounts used - VPC peering can be done)
{ "pile_set_name": "StackExchange" }
Q: Is there a generic way of coding a get; set; in C# My code has very many of these constructs: ParamViewModel[] _btns; public ParamViewModel[] Btns { get => _btns; set => SetProperty(ref _btns, value); } Is there any way to do this with a generic to enable me to cut down of the lines of code as they are all the same but with just a different data type, string, int, Color etc. For reference here's what SetProperty does: public class ObservableObject : INotifyPropertyChanged { protected virtual bool SetProperty<T>( ref T backingStore, T value, [CallerMemberName]string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return false; backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); return true; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } A: the simple, idiomatic get and set is this ParamViewModel[] Btns {get;set;} You cant get much tighter than that
{ "pile_set_name": "StackExchange" }
Q: unable to get this class working in java on client code - no compilation errors but runtime I have pasted my code here. below the code I give descriptin of what I am trying to do import java.util.*; import java.io.*; //given a string, gives letters counts etc public class LetterDatabase{ private String word; private int[] charCounts; public static final int TOTAL_LETTERS=26; //constructor public LetterDatabase(String word) { this.word=word; int[] charCounts= new int[TOTAL_LETTERS]; //this function fillup charCounts with no of occurances //more below fillupcharArray(); } /*Returns a count of letters. public int get(char letter) { return charCounts[Character.getNumericValue(letter)-10]; } /*Sets the count for the given letter to the given value. public void set(char letter,int value) { int index=Character.getNumericValue(letter-'a'); charCounts[index]=value; } /* converts string to Array of chars containing only alphabets private char[] convertToArray() { String str = word.replaceAll("[^a-zA-Z]+", ""); char[] charArr=new char[str.length()]; for (int i = 0; i < str.length(); i++) { charArr[i] = str.charAt(i); } return charArr; } private void fillupcharArray(){ char[] charArr=convertToArray(); for(int i=0;i<charArr.length;i++) { for(int j=0;j<26;j++) { if (Character.toLowerCase(charArr[i])==Character.toLowerCase((char)('a'+j))) { charCounts[j]+=1; } } } } } my client code that I used to test is below import java.util.*; import java.io.*; public class Testdatabase{ public static void main(String args[]) { String str="my name is Dummy!!!:..,"; LetterDatabase first= new LetterInventory(str); System.out.println(first.get('a')); System.out.println(first.set('a')); System.out.println(first.get('a')); } } Explanation: I define a LetterDatabase class which computes the count of letters--only alphabets (type char) in given string. I have a get method, that returns the occurance of particular letter and a set method, that sets the value of letter to a set value. in my constructor, I am calling a function that fills the array(charCounts), so that I can easily lookup for occurrence of a given char. Firstly my constructor does not work. my class code compiles and my client code above compiles. when I run the clientcode, commenting out the getter and setter calls, i get the following error. Exception in thread "main" java.lang.NullPointerException at LetterDatabase.fillupcharArray(LetterInventory.java:55) at LetterDatabase.<init>(LetterInventory.java:17) at Testdatabase.main(hw1test.java:7) I am unable to figure what is going wrong. the fillupcharArray seems to work fine when I test it individually. I am not pasting that here. secondly, the way I define get and set method in my class is not very good. it would be nice if I dont have to use Character.getNumericValue I am open to hear on any other improvements. Thanks for your time A: In your constructor, you've defined a local variable charCounts: int[] charCounts= new int[TOTAL_LETTERS]; This shadows the instance variable charCounts, to which I think you meant to assign it. Assign it to the instance variable charCounts like this: charCounts = new int[TOTAL_LETTERS]; This means that, in your code, the instance variable charCounts remains null until you access and a NullPointerException results. A: You are shadowing the array charCounts in the constructor of LetterDatabase. Replace int[] charCounts = new int[TOTAL_LETTERS]; with charCounts = new int[TOTAL_LETTERS]; Inside a class method, when a local variable has the same name as an instance variable, the local variable shadows the instance variable inside the method block. In this case the local variable charCounts is shadowing the instance variable charCounts. From wikipedia In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope
{ "pile_set_name": "StackExchange" }
Q: How do I save the new Logging configuration on Laravel? I want to configure Logging for Slack on Laravel 5.7, I modified the relevant files to do so but the logs keep being stored in the 'daily' logs (which is the default). Relevant code: logging.php 'default' => env('LOG_CHANNEL', 'stack'), 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['slack'], ], 'slack' => [ 'driver' => 'slack', 'url' => env('LOG_SLACK_WEBHOOK_URL'), 'username' => 'Logs', 'level' => 'debug', ], .env LOG_CHANNEL=stack LOG_SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...(omitted) Then I want to use it like so: web.php Route::get('/', function () { Log::info('Hello World!'); return view('home'); }) I think I'm missing something fundamental about modifying config files but I can't figure out what. A: when using the slack log.after you make some modifications make sure you run php artisan config:cache(to be on a much safer side do php artisan config:clear) so the application will be notify that you have make some changes to the logging.php file
{ "pile_set_name": "StackExchange" }
Q: This inclusion is continuous Let $H$ be the real space of all absolute continous functions $F$ from $[0,1]$ to the reals such that $f(0)=0$. I'd like to prove that there is $K>0$ such that for all $f\in H$ $\int_0^1f(x)^2dx\leq K\int_0^1f'(x)^2dx$ Any hint is welcome. A: Write $$f(x) = \int_0^x f'(t)\,dt,$$ apply the Cauchy-Schwarz inequality to the inner integral, change the order of integration. Without any tricky estimates, you can achieve $K \leqslant \frac12$.
{ "pile_set_name": "StackExchange" }
Q: Where's the Strangedupe blog post? Previously, in order to explain the benefits of (certain limited kinds of) duplication on Stack Exchange sites, I've seen a blog.stackoverflow blogpost with the words "Dr. Strangedupe" in the title. The post comes up in a search on the new blog, but "can't find the page I'm looking for." Can we please bring this post back? I'd love to link to it when commenting on duplicates, to reassure the questioner that there is value in not deleting their question because of search terms, but the blog post explained it a lot better than I could in a comment. A: It's back now. That and lots of other old posts like to disappear when the blog does partial builds. That'll be investigated further.
{ "pile_set_name": "StackExchange" }
Q: C# math statement not working while doing it in parts works I am wondering if this could be some kind of associativity problem, because when I do the problem on paper, I get the correct answer, but when I run the code I keep getting 4 over and over. Here is the code. Why aren't these equal? What am I missing? The whole problem (returns 4 on every iteration): for (int x = 1; x <= stackCount; x++) { temp = ((x - 1) / stackCount * uBound) + lBound + 1; Base[x] = Top[x] = Convert.ToInt32(Math.Floor(temp)); } Broken into pieces (runs correctly): double temp, temp1, temp2, temp3, temp4; for (int x = 1; x <= stackCount; x++) { temp1 = (x - 1); temp2 = temp1 / stackCount; temp3 = temp2 * uBound; temp4 = temp3 + lBound + 1; Base[x] = Top[x] = Convert.ToInt32(Math.Floor(temp4)); } Added: Yes, I am sorry, I forgot about that declarations: //the main memory for the application private string[] Memory; //arrays to keep track of the bottom and top of stacks private int[] Base; private int[] Top; //keep track of the upper and lower bounds and usable size private int LowerBound; private int UpperBound; private int usableSize; I also think I had that backwards. I thought that if you used a double in a division operation with integers that the result would be a double, but it appears that is not the case. That makes sense! Thank you all! A: Speculation: stackCount, uBound, and lBound are all integers or longs. Result: The entire expression is computed as though you're doing integer arithmetic. Solution: temp = ((double)(x -1) / stackCount * uBound) + lBound + 1;
{ "pile_set_name": "StackExchange" }
Q: Two conjugated verbs in a row? In this sentence there are two conjugated verbs in a row but I don't understand it. When I started learning Spanish I was taught that it should always be verb + infinitive. qué debería considera la gente cuando toma este tipo de decisiones Can someone explain this to me please? Why don't we say "qué debería considerar" instead? A: You are right about the rule you were taught, the sentence should be: qué debería considerar la gente cuando toma este tipo de decisiones Most probably it was a typo, since the sentence you received doesn't make sense otherwise.
{ "pile_set_name": "StackExchange" }
Q: How to get a specific XML node with Nokogiri and XPath I have this structure in XML: <resource id="2023984310000103605" name="Rebelezza"> <prices> <price datefrom="2019-10-31" dateto="2019-12-31" price="2690.0" currency="EUR" /> <price datefrom="2020-01-01" dateto="2020-03-31" price="2690.0" currency="EUR" /> <price datefrom="2020-03-31" dateto="2020-04-30" price="3200.0" currency="EUR" /> </prices> <products> <product name="specific-product1"> <prices> <price datefrom="2019-10-31" dateto="2019-12-31" price="2690.0" currency="EUR" /> <price datefrom="2020-01-01" dateto="2020-03-31" price="2690.0" currency="EUR" /> <price datefrom="2020-03-31" dateto="2020-04-30" price="3200.0" currency="EUR" /> </prices> </product> </products> </resource> How can I get only the prices under resources without getting the prices inside products using an XPath selector. At the moment, I have something like: resources = resourcesParsed.xpath("//resource") for resource in resources do prices = resource.xpath(".//prices/price[number(translate(@dateto, '-', '')) >= 20190101]") end However, I am getting both, the prices directly under resource element and also under products. I'm not interested in the prices under products. A: 2 options with XPath : .//price[parent::prices[parent::resource]] .//price[ancestor::*[2][name()="resource"]] Output : 3 nodes And to add a date condition, you can use what you did : .//price[parent::prices[parent::resource]][translate(@dateto, '-', '') >= 20200101]
{ "pile_set_name": "StackExchange" }
Q: ili9341 Not Working on STM32f4 discovery I am testing IlI9341 3.2 TFT LCD on stm32F4-discovery. I wired based on Discovery datasheet. I also read ILI9341 datasheet and went through all registers. However I get nothing. Also, the LD7, LD5 and LD6 keep on indicating overflow of current. Compiled using Coocox IDE. The functions SETCURSORPOSITION and FILL are further down. Here is my code if someone can help me. Thank you. #include "stm32f4xx.h" #include "stm32f4xx_rcc.h" #include "stm32f4xx_gpio.h" #include "stm32f4xx_fsmc.h" #include "LCD.h" #define LCD_REG (*((volatile unsigned short *) 0x60000000))//address #define LCD_RAM (*((volatile unsigned short *) 0x60020000))//data #define MAX_X 320//landscape mode #define MAX_Y 240//landscape mode #define ILI9341_PIXEL 76800 #define Green 0x07E0 void LCD_PinsConfiguration(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD,ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOD,&GPIO_InitStructure); GPIO_ResetBits(GPIOD,GPIO_Pin_7); RCC_AHB3PeriphClockCmd(RCC_AHB3Periph_FSMC,ENABLE); GPIO_PinAFConfig(GPIOD,GPIO_PinSource0,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource1,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource4,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource5,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource8,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource9,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource10,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource11,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource14,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOD,GPIO_PinSource15,GPIO_AF_FSMC); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1|GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_8|GPIO_Pin_9|GPIO_Pin_10|GPIO_Pin_11|GPIO_Pin_14|GPIO_Pin_15; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOD,&GPIO_InitStructure); RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE,ENABLE); GPIO_PinAFConfig(GPIOE,GPIO_PinSource2,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource7,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource8,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource9,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource10,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource11,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource12,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource13,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource14,GPIO_AF_FSMC); GPIO_PinAFConfig(GPIOE,GPIO_PinSource15,GPIO_AF_FSMC); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2|GPIO_Pin_7|GPIO_Pin_8|GPIO_Pin_9|GPIO_Pin_10|GPIO_Pin_11|GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_14|GPIO_Pin_15; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_Init(GPIOD,&GPIO_InitStructure); Delay(5000); RCC_AHB3PeriphClockCmd(RCC_AHB3Periph_FSMC,ENABLE); FSMC_NORSRAMInitTypeDef FSMC_NORSRAMInitStructure; FSMC_NORSRAMTimingInitTypeDef FSMC_NORSRAMTimingInitStructure; FSMC_NORSRAMTimingInitStructure.FSMC_AddressSetupTime = 0x0F; FSMC_NORSRAMTimingInitStructure.FSMC_AddressHoldTime = 0; FSMC_NORSRAMTimingInitStructure.FSMC_AddressSetupTime = 5; FSMC_NORSRAMTimingInitStructure.FSMC_BusTurnAroundDuration =0; FSMC_NORSRAMTimingInitStructure.FSMC_CLKDivision = 0; FSMC_NORSRAMTimingInitStructure.FSMC_DataLatency =0; FSMC_NORSRAMTimingInitStructure.FSMC_AccessMode = FSMC_AccessMode_A; FSMC_NORSRAMInitStructure.FSMC_Bank = FSMC_Bank1_NORSRAM1; FSMC_NORSRAMInitStructure.FSMC_DataAddressMux = FSMC_DataAddressMux_Disable; FSMC_NORSRAMInitStructure.FSMC_MemoryType = FSMC_MemoryType_SRAM; FSMC_NORSRAMInitStructure.FSMC_MemoryDataWidth = FSMC_MemoryDataWidth_16b; FSMC_NORSRAMInitStructure.FSMC_BurstAccessMode = FSMC_BurstAccessMode_Disable; FSMC_NORSRAMInitStructure.FSMC_WaitSignalPolarity = FSMC_WaitSignalPolarity_Low; FSMC_NORSRAMInitStructure.FSMC_WrapMode = FSMC_WrapMode_Disable; FSMC_NORSRAMInitStructure.FSMC_WaitSignalActive = FSMC_WaitSignalActive_BeforeWaitState; FSMC_NORSRAMInitStructure.FSMC_WriteOperation = FSMC_WriteOperation_Enable; FSMC_NORSRAMInitStructure.FSMC_AsynchronousWait = FSMC_AsynchronousWait_Disable; FSMC_NORSRAMInitStructure.FSMC_ExtendedMode = FSMC_ExtendedMode_Disable; FSMC_NORSRAMInitStructure.FSMC_WriteBurst = FSMC_WriteBurst_Disable; FSMC_NORSRAMInitStructure.FSMC_ReadWriteTimingStruct = &FSMC_NORSRAMTimingInitStructure; FSMC_NORSRAMInit(&FSMC_NORSRAMInitStructure); FSMC_NORSRAMCmd(FSMC_Bank1_NORSRAM1,ENABLE); } void LCD_Initialization(void) { LCD_PinsConfiguration(); LCD_ILI9341_SendCommand(0x01); Delay(50000); LCD_ILI9341_SendCommand(0xcb); LCD_ILI9341_SendData(0x39); LCD_ILI9341_SendData(0x2C); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x34); LCD_ILI9341_SendData(0x02); LCD_ILI9341_SendCommand(0xcf); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0xC1); LCD_ILI9341_SendData(0x30); LCD_ILI9341_SendCommand(0xe8); LCD_ILI9341_SendData(0x85); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x78); LCD_ILI9341_SendCommand(0xea); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendCommand(0xed); LCD_ILI9341_SendData(0x64); LCD_ILI9341_SendData(0x03); LCD_ILI9341_SendData(0x12); LCD_ILI9341_SendData(0x81); LCD_ILI9341_SendCommand(0xf7); LCD_ILI9341_SendData(0x20); LCD_ILI9341_SendCommand(0xc0); LCD_ILI9341_SendData(0x23); LCD_ILI9341_SendCommand(0xc1); LCD_ILI9341_SendData(0x10); LCD_ILI9341_SendCommand(0xc5); LCD_ILI9341_SendData(0x3E); LCD_ILI9341_SendData(0x28); LCD_ILI9341_SendCommand(0xc7); LCD_ILI9341_SendData(0x86); LCD_ILI9341_SendCommand(0x36); LCD_ILI9341_SendData(0x48); LCD_ILI9341_SendCommand(0x3a); LCD_ILI9341_SendData(0x55); LCD_ILI9341_SendCommand(0xb1); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x18); LCD_ILI9341_SendCommand(0xb6); LCD_ILI9341_SendData(0x08); LCD_ILI9341_SendData(0x82); LCD_ILI9341_SendData(0x27); LCD_ILI9341_SendCommand(0xf2); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendCommand(0x2a); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0xEF); LCD_ILI9341_SendCommand(0x2b); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x01); LCD_ILI9341_SendData(0x3F); LCD_ILI9341_SendCommand(0x26); LCD_ILI9341_SendData(0x01); LCD_ILI9341_SendCommand(0xe0); LCD_ILI9341_SendData(0x0F); LCD_ILI9341_SendData(0x31); LCD_ILI9341_SendData(0x2B); LCD_ILI9341_SendData(0x0C); LCD_ILI9341_SendData(0x0E); LCD_ILI9341_SendData(0x08); LCD_ILI9341_SendData(0x4E); LCD_ILI9341_SendData(0xF1); LCD_ILI9341_SendData(0x37); LCD_ILI9341_SendData(0x07); LCD_ILI9341_SendData(0x10); LCD_ILI9341_SendData(0x03); LCD_ILI9341_SendData(0x0E); LCD_ILI9341_SendData(0x09); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendCommand(0xe1); LCD_ILI9341_SendData(0x00); LCD_ILI9341_SendData(0x0E); LCD_ILI9341_SendData(0x14); LCD_ILI9341_SendData(0x03); LCD_ILI9341_SendData(0x11); LCD_ILI9341_SendData(0x07); LCD_ILI9341_SendData(0x31); LCD_ILI9341_SendData(0xC1); LCD_ILI9341_SendData(0x48); LCD_ILI9341_SendData(0x08); LCD_ILI9341_SendData(0x0F); LCD_ILI9341_SendData(0x0C); LCD_ILI9341_SendData(0x31); LCD_ILI9341_SendData(0x36); LCD_ILI9341_SendData(0x0F); LCD_ILI9341_SendCommand(0x11); Delay(50000); LCD_ILI9341_SendCommand(0x29); LCD_ILI9341_SendCommand(0x22); } void LCD_ILI9341_SendCommand(uint16_t index) { LCD_REG = index; } void LCD_ILI9341_SendData(uint16_t data) { LCD_RAM = data; } void LCD_ILI9341_SetCursorPosition(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2) { LCD_ILI9341_SendCommand(0x2A); LCD_ILI9341_SendData(x1 >> 8); LCD_ILI9341_SendData(x1 & 0xFF); LCD_ILI9341_SendData(x2 >> 8); LCD_ILI9341_SendData(x2 & 0xFF); LCD_ILI9341_SendCommand(0x2B); LCD_ILI9341_SendData(y1 >> 8); LCD_ILI9341_SendData(y1 & 0xFF); LCD_ILI9341_SendData(y2 >> 8); LCD_ILI9341_SendData(y2 & 0xFF); } void LCD_ILI9341_Fill(uint16_t color) { unsigned int n, i, j; i = color >> 8; j = color & 0xFF; LCD_ILI9341_SetCursorPosition(0, 0, MAX_Y - 1, MAX_X - 1); LCD_ILI9341_SendCommand(0x0022); for (n = 0; n < ILI9341_PIXEL; n++) { LCD_ILI9341_SendData(i); LCD_ILI9341_SendData(j); } } void Delay(__IO uint32_t nCount) { while(nCount--) { } } A: I am going to answer my own question to make it clear things got solved. But I want to thank the community. Actually I did few things: I removed GPIOE 2 from configuration block, because it was not being used. I replaced GPIOD to GPIOE in the same block. Inside "LCD_ILI9341_Fill" I changed "LCD_ILI9341_SendCommand(0x0022)" to "LCD_ILI9341_SendCommand(0x002C)". 0x002C is the actual Memory Write address to where you write the data on ili9341. I also connected the LCD RESET pin to the stm32f4 NRST pin. 3V power was connected to LCD LED_A. Now everything works, I still get wrong colors but I need to make few changes on registers, such as register 36h.
{ "pile_set_name": "StackExchange" }
Q: Как переносить текст на новую строчку? пробовал shift+enter, переносят в редакторе, но на входе оно переносится только с более чем двойным shift+enter: текст с двойным shift+enter; текст с одинарным shift+enter; A: Для перевода текста на новую строку нужно закончить предыдущую двумя пробелами. Ссылка на страницу справки по форматированию есть в редакторе, открывается через иконку вопросика: Далее — «расширенная справка» https://ru.stackoverflow.com/editing-help
{ "pile_set_name": "StackExchange" }
Q: CAN communication questions I started down this path, because I've got a CAN driver in uCLinux that I'm reviewing. I'm new to CAN in general, so I was doing a little research about it, and I've stumbled upon a question that I haven't found an answer to. If CAN is a serial interface, and CANopen doesn't have a "bus master", then how does the CAN protocol handle inevitable collisions of data on the bus? If there's no one governing when you can send, given enough devices and time there will have to be sends that collide. It's a pretty basic question, so it's possible I found an answer and just didn't understand it... If anyone can provide an answer/example that would be great. A: It's done through CSMA/CD.The signal of CAN is wire AND logic. So the smaller message id can have higher priority based competing with wire AND logic.
{ "pile_set_name": "StackExchange" }
Q: Ambiguous column name and I need it in he answer I've written a program with 2 views. but, I'm getting the error msg: Ambiguous column name 'b_id'. And, I need the b_id in the result. What can I do? The code is as follows: --view for all store managers with b_id and jobtitle CREATE VIEW storemanagers AS SELECT b_id, jobTitle,e_firstname,e_middlename,e_lastname FROM Employee WHERE jobTitle='Store Manager' ----view for employee in each branch CREATE VIEW employee_perbranch AS SELECT b_id, COUNT(*) AS 'Employee_count' FROM Employee GROUP BY b_id --Procedure for listing store managers who manage a branch with more than 8 employees SELECT* FROM employee_perbranch SELECT e_firstname, e_middlename, e_lastname, Employee_count,b_id FROM storemanagers sm, employee_perbranch eb, Branch b WHERE b.b_id=sm.b_id AND eb.b_id=b.b_id AND eb.Employee_Count >8 A: You should specify an alias for b_id column from SELECT e_firstname, e_middlename, e_lastname, Employee_count,b_id, either b.b_id or sm.b_id as it's present in both views.
{ "pile_set_name": "StackExchange" }
Q: mmap: can't attach to existing region without knowing its size (Windows) I'm trying to attach to an existing shared memory region created by another application, not written in Python (this is how its plugin modules intercommunicate). On Windows, it uses named kernel objects rather than files in the filesystem; Python's mmap module supports this, via the tagname parameter. The problem is that I have no way of knowing in advance what the size of the shared region is - this is a configuration parameter of the other application, which is adjusted based on the expected volume of data. For file-based shared regions, passing zero for the size uses the existing size of the file, but this apparently doesn't work for tagged regions. Here's a simplified version of what I'm trying: import mmap, random TAGNAME = 'SHM_1001' # This is a simulation of what the other application does. # The size isn't actually random, I simply don't know in advance what it is. m1 = mmap.mmap(-1, random.randint(1e3, 1e6), TAGNAME) # This is what I'm trying to do in my application, to attach to the same region. m2 = mmap.mmap(-1, 0, TAGNAME) # WindowsError: [Error 87] The parameter is incorrect If I specify a small nonzero size, then I can successfully attach to the region - but of course I can then only access that many bytes at the start of the region. If I specify a size larger than the actual size of the region (perhaps equal to the largest size it can ever have), I get an access error. The problem exists in both Python 2.7 and 3.4. The approach of passing zero for the size definitely works at the system call level - that is exactly how every existing C/C++ plugin for this application works - so the problem is apparently in Python's wrapper for the mmap() call. Any ideas on how I can get this to work? A: The parameter validation in CreateFileMapping is erroring out before the system service NtCreateSection gets called, which if called would find the existing section. Using 0 size when hFile is INVALID_HANDLE_VALUE (-1) is invalid because CreateFileMapping presumes (wrongly in this case) that the section needs to be allocated from the paging file. I assume C plugins are instead calling OpenFileMapping (i.e. NtOpenSection). You can use ctypes, or PyWin32, or a C extension module. After calling OpenFileMappingW, call MapViewOfFile and then call VirtualQuery to get the mapped region size, rounded up to a page boundary. Here's an example using ctypes. from ctypes import * from ctypes.wintypes import * kernel32 = WinDLL('kernel32', use_last_error=True) FILE_MAP_COPY = 0x0001 FILE_MAP_WRITE = 0x0002 FILE_MAP_READ = 0x0004 FILE_MAP_ALL_ACCESS = 0x001f FILE_MAP_EXECUTE = 0x0020 PVOID = LPVOID SIZE_T = c_size_t class MEMORY_BASIC_INFORMATION(Structure): _fields_ = (('BaseAddress', PVOID), ('AllocationBase', PVOID), ('AllocationProtect', DWORD), ('RegionSize', SIZE_T), ('State', DWORD), ('Protect', DWORD), ('Type', DWORD)) PMEMORY_BASIC_INFORMATION = POINTER(MEMORY_BASIC_INFORMATION) def errcheck_bool(result, func, args): if not result: raise WinError(get_last_error()) return args kernel32.VirtualQuery.errcheck = errcheck_bool kernel32.VirtualQuery.restype = SIZE_T kernel32.VirtualQuery.argtypes = ( LPCVOID, # _In_opt_ lpAddress PMEMORY_BASIC_INFORMATION, # _Out_ lpBuffer SIZE_T) # _In_ dwLength kernel32.OpenFileMappingW.errcheck = errcheck_bool kernel32.OpenFileMappingW.restype = HANDLE kernel32.OpenFileMappingW.argtypes = ( DWORD, # _In_ dwDesiredAccess BOOL, # _In_ bInheritHandle LPCWSTR) # _In_ lpName kernel32.MapViewOfFile.errcheck = errcheck_bool kernel32.MapViewOfFile.restype = LPVOID kernel32.MapViewOfFile.argtypes = ( HANDLE, # _In_ hFileMappingObject DWORD, # _In_ dwDesiredAccess DWORD, # _In_ dwFileOffsetHigh DWORD, # _In_ dwFileOffsetLow SIZE_T) # _In_ dwNumberOfBytesToMap kernel32.CloseHandle.errcheck = errcheck_bool kernel32.CloseHandle.argtypes = (HANDLE,) if __name__ == '__main__': import mmap NPAGES = 9 PAGE_SIZE = 4096 TAGNAME = 'SHM_1001' mm1 = mmap.mmap(-1, PAGE_SIZE * NPAGES, TAGNAME) hMap = kernel32.OpenFileMappingW(FILE_MAP_ALL_ACCESS, False, TAGNAME) pBuf = kernel32.MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0) kernel32.CloseHandle(hMap) mbi = MEMORY_BASIC_INFORMATION() kernel32.VirtualQuery(pBuf, byref(mbi), PAGE_SIZE) assert divmod(mbi.RegionSize, PAGE_SIZE) == (NPAGES, 0) mm2 = (c_char * mbi.RegionSize).from_address(pBuf) # write using the mmap object mm1.seek(100) mm1.write(b'Windows') # read using the ctypes array assert mm2[100:107] == b'Windows'
{ "pile_set_name": "StackExchange" }
Q: Trace $A$ is an integer. If $A$ is a square matrix of order $n$ with real entries and $A^3 + I =0$. Then $\operatorname{trace}(A)$ is an integer. My attempt: Here $|A| = -1$. And $\operatorname{trace}(A^3) = -n$. Then I tried to draw a contradiction assuming that $\operatorname{trace}(A)$ isn't an integer (using definition of determinant). But nowhere near the solution. A: Hint From the equation we conclude that the eigenvalues ($k$) will fit the equation: $$k^3=-1$$ So, $k=-1$ or $k=\frac{1}{2}\pm \frac{\sqrt{3}}{2}i$ are the candidates for eigenvalues. 1) We know that the trace is the sum of the eigenvalues. 2) We also know that once we have a real matrix if we have a complex number as an eigenvalue then his conjugate will also be an eigenvalue. Can you finish?
{ "pile_set_name": "StackExchange" }
Q: How to complete a Job when user closes Eclipse application I use org.eclipse.core.runtime.jobs.Job to execute stored procedure which deletes data and to update user interface according to the new data. Thus it is important that this job will be completed even if user closes eclipse application. final Job execStoredProcJob = new Job(taskName) { protected IStatus run(IProgressMonitor monitor) { monitor.beginTask(taskName, // execute stored procedure // update user interface monitor.done(); return Status.OK_STATUS; } }; execStoredProcJob.schedule(); When I close eclipse app while the Job still running it seems to kill the Job. How to complete the job after user has closed eclipse app? Is it possible? A: I think you might want to take a look at scheduling rules http://www.eclipse.org/articles/Article-Concurrency/jobs-api.html execStoredProcJob.setRule([Workspace root]); execStoredProcJob.schedule(); [Workspace root] can be attained like project.getWorkspace().getRoot() if you have a reference to your project. That will block all jobs that require the same rule. The shutdown job is one of them.. It's also possible to: IWorkspace myWorkspace = org.eclipse.core.resources.ResourcesPlugin.getWorkspace(); Then use: myWorkspace.getRoot();
{ "pile_set_name": "StackExchange" }
Q: Play Framework 2.3.x how to run the sample applications? I have Play 2.3.7 installed, and I have the activator command working with other play apps I have created locally. However, when I try to clone the Play Framework from github and run one of the 2.3.x sample applications , the activator command fails with a Null Pointer Exception. Similarly, if I try to import the project into IntelliJ and build from the .sbt file, I get the same error: Is there something I need to change in the build.sbt file to get it to load properly? I'm guessing that it is something very simple that I am overlooking. TL;DR: How do I run a Play 2.3.x sample application when cloned from github? A: Specify the exact play version that you have in plugins.sbt From addSbtPlugin("com.typesafe.play" % "sbt-plugin" % System.getProperty("play.version")) To(Assuming you are using play 2.3.1) addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.3.1") Then activator clean then run again. Source
{ "pile_set_name": "StackExchange" }
Q: Using EJBs with regular java classes. Trying to instantiate a stateless EJB I have a large web project in Java EE 6 so far everything is working great. Now I'm adding a new class that takes twitter information and returns a string. So far the strings have been extracted from the JSON file from twitter and are ready to be persisted in my database. My problem is I'm not sure how to pass information from the EJB that normally handles all of my database calls. I'm using JPA and have a DAO class that managers all database access. I already have a method there for updateDatabase(String). I'd like to be able to call updateDatabase(String) from the class that has the strings to add but I don't know if it's good form to instantiate a stateless bean like that. Normally you inject beans and then call just their class name to access their methods. I could also maybe try and reference the twitter string generating class from inside of the EJB but then I'd have to instantiate it there and mess with main() method calls for execution. I'm not really sure how to do this. Right now my Twitter consuming class is just a POJO with a main method. For some reason some of the library methods did not work outside of main in face IOUtils() API directly says "Instances should NOT be constructed in standard programming". So on a higher level bottom line, I'm just asking how POJO's are normally "mixed" into a Java EE project where most of your classes are EJBs and servlets. Edit: the above seems confusing to me after rereading so I'll try to simplify it. basically I have a class with a main method. I'd like to call my EJB class that handles database access and call it's updateDatabase(String) method and just pass in the string. How should I do this? Edit: So it looks like a JNDI lookup and subsequence reference is the preferred way to do this rather than instantiating the EJB directly? Edit: these classes are all in the same web project. In the same package. I could inject one or convert the POJO to an EJB. However the POJO does have a main method and some of the library files do not like to be instantiated so running it in main seems like the best option. My main code: public class Driver { @EJB static RSSbean rssbean; public static void main(String[] args) throws Exception { System.setProperty("http.proxyHost", "proxya..com"); System.setProperty("http.proxyPort", "8080"); /////////////auth code///////////////auth code///////////////// String username = System.getProperty("proxy.authentication.username"); String password = System.getProperty("proxy.authentication.password"); if (username == null) { Authenticator.setDefault(new ProxyAuthenticator("", "")); } ///////////////end auth code/////////////////////////////////end URL twitterSource = new URL("http://search.twitter.com/search.json?q=google"); ByteArrayOutputStream urlOutputStream = new ByteArrayOutputStream(); IOUtils.copy(twitterSource.openStream(), urlOutputStream); String urlContents = urlOutputStream.toString(); JSONObject thisobject = new JSONObject(urlContents); JSONArray names = thisobject.names(); JSONArray asArray = thisobject.toJSONArray(names); JSONArray resultsArray = thisobject.getJSONArray("results"); JSONObject(urlContents.substring(urlContents.indexOf('s'))); JSONObject jsonObject = resultsArray.getJSONObject(0); String twitterText = jsonObject.getString("text"); rssbean.updateDatabase("twitterText"); } } I'm also getting a java.lang.NullPointerException somewhere around rssbean.updateDatabase("twitterText"); A: You should use InitialContext#lookup method to obtain EJB reference from an application server. For example: @Stateless(name="myEJB") public class MyEJB { public void ejbMethod() { // business logic } } public class TestEJB { public static void main() { MyEJB ejbRef = (MyEJB) new InitialContext().lookup("java:comp/env/myEJB"); ejbRef.ejbMethod(); } } However, note that the ejb name used for lookup may be vendor-specific. Also, EJB 3.1 introduces the idea of portable JNDI names which should work for every application server. A: Use the POJO as a stateless EJB, there's nothing wrong with that approach. From the wikipedia: EJB is a server-side model that encapsulates the business logic of an application. Your POJO class consumes a web service, so it performs a business logic for you. EDIT > Upon reading your comment, are you trying to access an EJB from outside of the Java EE container? Because if not, then you can inject your EJB into another EJB (they HAVE to be Stateless, both of them)
{ "pile_set_name": "StackExchange" }
Q: is there a way to change the menu text colour when at the top of a website I am using a menu that has a background which is seethrough at the top and when you scroll down the background color of the menu changes to black. In one of my pages the background of the whole website is white so when the user scrolls to the top, the menu background is white which makes it impossible to read the menu text. I was wondering if there is a code that can change the color of the text of the menu when the menu bar is at the top of the website the menu text changes black so it is readable. here is a picture when the menu bar is at the top of the website and not at the top. I'll add the code that codes for the menu bar. HTML & Script: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Croydon Cycles</title> <link rel="stylesheet" href="shop-style.css"> <link rel="shortcut icon" type="image/png" href="images/favicon.png"> <link href="https://fonts.googleapis.com/css?family=Karla" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="parallax.min.js"></script> </head> <body> <div class="wrapper"> <header> <nav> <div class="menu-icon"> <i class="fa fa-bars fa-2x"></i> </div> <div class="logo"> Croydon Cycles </div> <div class="menu"> <ul> <li><a href="index.html">Home</a></li> <li><a href="location.html">Location</a></li> <li><a href="shop.html">Shop</a></li> <li><a href="contact.html">Contact</a></li> </ul> </div> </nav> </header> <script type="text/javascript"> // Menu-toggle button $(document).ready(function() { $(".menu-icon").on("click", function() { $("nav ul").toggleClass("showing"); }); // add this instruction ! setTimeout(function() {plusSlides(1) }, 1000) }) // Scrolling Effect $(window).on("scroll", function() { if($(window).scrollTop()) { $('nav').addClass('black'); } else { $('nav').removeClass('black'); } }) </script> </body> </html> CSS: html, body { margin: 0; padding: 0; width: 100%; font-family: verdana,sans-serif; margin: 0; font-family: "Helvetica Neue",sans-serif; font-weight: lighter; box-sizing: border-box; } header { width: 100%; height: 60px; background: url(hero.jpg) no-repeat 50% 50%; background-size: cover; } .content { width: 94%; margin: 4em auto; font-size: 20px; line-height: 30px; text-align: justify; } .logo { line-height: 60px; position: fixed; float: left; margin: 16px 46px; color: #fff; font-weight: bold; font-size: 20px; letter-spacing: 2px; } nav { position: fixed; width: 100%; line-height: 60px; z-index:2; } nav ul { line-height: 60px; list-style: none; background: rgba(0, 0, 0, 0); overflow: hidden; color: #fff; padding: 0; text-align: right; margin: 0; padding-right: 40px; transition: 1s; } nav.black ul { background: #000; } nav ul li { display: inline-block; padding: 16px 40px;; } nav ul li a { text-decoration: none; color: #fff; font-size: 16px; } .menu-icon { line-height: 60px; width: 100%; background: #000; text-align: right; box-sizing: border-box; padding: 15px 24px; cursor: pointer; color: #fff; display: none; } @media(max-width: 786px) { .logo { position: fixed; top: 0; margin-top: 16px; } nav ul { max-height: 0px; background: #000; } nav.black ul { background: #000; } .showing { max-height: 34em; } nav ul li { box-sizing: border-box; width: 100%; padding: 24px; text-align: center; } .menu-icon { display: block; } } A: You need to add the correct colors for .black class. Before run the snippet click and Expand Snippet, because I added for large resolutions only, you can add in @media(max-width: 786px) for small resolutions (mobile devices). I added <div style="height:1500px" class="only-for-scroll"></div> to force scroll. I commented with //add this to you identify the changes that I did. html, body { margin: 0; padding: 0; width: 100%; font-family: verdana,sans-serif; margin: 0; font-family: "Helvetica Neue",sans-serif; font-weight: lighter; box-sizing: border-box; } header { width: 100%; height: 60px; background: url(hero.jpg) no-repeat 50% 50%; background-size: cover; } .content { width: 94%; margin: 4em auto; font-size: 20px; line-height: 30px; text-align: justify; } /*add this lines*/ nav.black .logo { color: #fff; } nav.black ul li a { color: #fff; } /*END*/ nav .logo { line-height: 60px; position: fixed; float: left; margin: 16px 46px; color: #000; font-weight: bold; font-size: 20px; letter-spacing: 2px; } nav { position: fixed; width: 100%; line-height: 60px; z-index:2; } nav ul { line-height: 60px; list-style: none; background: rgba(0, 0, 0, 0); overflow: hidden; color: #000; padding: 0; text-align: right; margin: 0; padding-right: 40px; transition: 1s; } nav.black ul { background: #000; } nav ul li { display: inline-block; padding: 16px 40px;; } nav ul li a { text-decoration: none; color: #000; font-size: 16px; } .menu-icon { line-height: 60px; width: 100%; background: #000; text-align: right; box-sizing: border-box; padding: 15px 24px; cursor: pointer; color: #fff; display: none; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="https://code.jquery.com/jquery-3.3.1.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="parallax.min.js"></script> <body> <div class="wrapper"> <header> <nav> <div class="menu-icon"> <i class="fa fa-bars fa-2x"></i> </div> <div class="logo"> Croydon Cycles </div> <div class="menu"> <ul> <li><a href="index.html">Home</a></li> <li><a href="location.html">Location</a></li> <li><a href="shop.html">Shop</a></li> <li><a href="contact.html">Contact</a></li> </ul> </div> </nav> </header> <div style="height:1500px" class="only-for-scroll"></div> <script type="text/javascript"> // Menu-toggle button $(document).ready(function() { $(".menu-icon").on("click", function() { $("nav ul").toggleClass("showing"); }); // add this instruction ! //setTimeout(function() {plusSlides(1) }, 1000) }) // Scrolling Effect $(window).on("scroll", function() { if($(window).scrollTop()) { $('nav').addClass('black'); } else { $('nav').removeClass('black'); } }) </script>
{ "pile_set_name": "StackExchange" }
Q: Opa match pattern OR I am writing my first Opa application. I am trying to set up a match for url handling. Code is as follows: function start(url) { match (url) { case {path:[] ...}: Resource.page("Home", home()) case {...}: Resource.page("nofindy", nofindy()) } } Server.start(Server.http, { dispatch: start }) It works like a charm, but now I want to be able to do synonymous mappings. For example, I would like to be able to not only have / go to the home page, but also /home. Is there a concise way to do this, perhaps with an OR operator, or do I need to set up separate cases that both trigger the same resource? tl;dr: is there a better way to write the following snippet: case {path:[] ...}: Resource.page("Home", home()) case {path:["home"] ...}: Resource.page("Home", home()) A: You should use a custom instead of a dispatch: function start(v){ Resource.page(v, <h1>{v}</h1>) } urls = parser { case ("/" | "/home") : start("home") case .* : start("other") } Server.start(Server.http, {custom: urls}) Learn more about the parser here: http://doc.opalang.org/manual/The-core-language/Parser
{ "pile_set_name": "StackExchange" }
Q: Annotate Boolean field if item is in a python list I have an app for a Restaurant. And I have this model: class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField() I have a list called TopSelled like this: ['Beer', 'Burger', ...] I want to aggregate a boolean field called 'Hot', depending if product item is "top-sell" or not. So my annotation should be something like this: Product.objects.all().annotate(if Product.Name in List: HOT = True ELSE Hot = False) How can I achieve this? Thx! A: Try annotating with Case: from django.db.models import BooleanField from django.db.models.expressions import Case, When Product.objects.annotate(hot=Case( When(name__in=hot_list, then=True), output_field=BooleanField()) ).filter(hot=True)
{ "pile_set_name": "StackExchange" }
Q: "Poil au menton"? I encountered this while reading Astérix. The conversation goes as follows: Roman Commander : Après quoi, nous nous débarrasserons de ces deux gaulois ! Ce sera pour eux une leçon ! Roman Lieutenant : Poil au menton ! While I know the literal meaning is along the lines of hair on your chin, what does that mean in this context? A: In French, it is a very common (and no so funny) joke to said "poil au {part of the body}" where the part of the body rhymes with the last sentence. - Je vais aller manger. - Poil au nez ! - Il s'agit d'un lapin. - Poil aux mains ! - Ce n'est pas tout à fait pareil. - Poil aux oreilles Well, I think you get it...
{ "pile_set_name": "StackExchange" }
Q: SF novel that takes place on a planet called Ragnarok? In my youth I read and enjoyed a SF novel that took place largely on a planet called Ragnarok. I'd like to rediscover it, if I could. Some details I remember: Humans are fighting a war with a humanoid non-human species. The planet is earth-like, and has seasons. The human colonists of the planet arrived there more-or-less accidentally, their ship having been attacked by the antagonists, who were either unaware of their survival or did not care at the time. The story takes place on Ragnarok over several generations of descendants of the original colonists; the bulk of the story is how they survived and eventually prospered The humans do not have any advanced technology due to the destruction or disablement of their ship; they gradually recreate some basic technology. An important weapon is the semi-automatic crossbow. The humans have a hard time surviving -- they can live off the land, but initially not very well Eventually the non-human antagonists return to the planet and the colonists' descendants fight them -- and win! And thus acquire the means to leave the planet using the starship of their enemies ETA: It's a duplicate in the sense that both questions are answered with the same story -- but it's not a duplicate exactly. I'm happy, nevertheless, although marking this a dupe after well over a year seems a tad delayed. No problem. A: The Survivors (1958) by Tom Godwin? From Wikipedia: A ship heading from Earth to Athena, a planet 500 light years away, is suddenly attacked by the Gerns, an alien empire in its expansion phase. People aboard are divided by the invaders into Acceptables and Rejects. The Acceptables would become slave labor for the Gerns on Athena, and the Rejects are forced ashore on the nearest 'Earth-like' planet, called Ragnarok. The Gerns say they will return for the Rejects, but the Rejects quickly realise that that isn't going to happen. Ragnarok has a gravity 1.5 times that of Earth, and is populated by deadly, aggressive creatures and it contains little in the way of usable metal ores. This, combined with a terrible deadly fever that kills in hours, more than decimates the population. The novels follows the stranded humans through several generations as they try to survive there, and their unswerving goal to repay the Gerns for their cruelty.
{ "pile_set_name": "StackExchange" }
Q: Bootstrap 3 Popover with function for content Bootstrap 3 provides a Popover that I'm trying to use. The docs say that the data-content may be either a string or a function. However, I seem unable to set the content to a function: <button type="button" class="btn btn-lg btn-danger" data-toggle="popover" title="Popover title" data-content="my_function();"> Click to toggle popover </button> And here's the JavaScript: $(function () { $('[data-toggle="popover"]').popover() }) function my_function(){ return "This is my popover's content"; } You can try the JSFiddle. I've also tried variations like data-content="javascript:my_function();". I'm not sure if my syntax is just a little off, or if you can't use data-content this way. Is it possible to specify a function for a Popover's content using the data-content attribute? Or am I misunderstanding the docs? A: It is not possible to specify a function for a Popover's content using the data-content attribute.
{ "pile_set_name": "StackExchange" }
Q: Meal Premiums in California I've worked at several companies that have not been paying the 1-hour of regular pay to employees if they miss their lunch period. During the transition from not taking break to taking breaks and changing the policies, we're trying to figure out how to position this to employees. It's been a struggle to just have employees take breaks and how will be continue to have them take breaks if they find out that they will get paid for not taking a break. We're trying to find a way to position this to employees so that: They do not ask for compensation for all the missed breaks up until now They continue to take their meal breaks A: As for #1, there may be no way around it without breaking a few labor laws. As for #2, start writing them up for missing their breaks and send them home early if they do. Do both or people will game the system (Hey! I get to leave early if I skip lunch) or (Hey, I worked through lunch, I should get paid, it's not fair that you right me up and don't pay me, I still worked the hours) A: You have two options. First if the labor law requires they be paid, then you must pay them for the past instances. Let them know how paying this impacts things you will be no longer be able to pay for such as conferences, new equipment, etc. Be very transparent on where the money to pay this came from. Going forward, you can budget the money to pay this as part of their normal salary. Let them know there will be no salary increases next year (or whatever budget items you have to cut to make this work for your company) as you have to absorb this major change to your budget. Show them the budget calculation. Assume a low figure for the salary calc (and make sure they know you are low balling) but say 100 people who get paid an extra hour 5 days a week every week is a lot of money even if you lowball the per hour salary. Or you can tell them specifically and in writing that the policy is that breaks will be taken unless approved in writing in advance by a manager. Then the first time after that someone works through a break without written approval, you write them up for insubordination and let them know that three strikes and they are out (i.e. fired). If you have an HR team, have them draft the policy as they should be aware of the legal requirements. If not have labor lawyer draft the policy. Do not write this policy without consultation with someone who is up on labor laws. It is tough to have to be harsh, but this is a huge budgetary issue for you and it is something that warrants firing when they disregard your specific workplace rules on breaks. But don't make the threat unless you take action when someone defies the policy just as you would if they deliberately smashed some equipment or stole from the company. This is that level of serious. (It is stealing from the company to get unauthorized payments.) You will lose some people because they don't want to be adults. Fine, good riddance. Further not taking breaks is counterproductive just like working overtime is. They actually get less work done over time because they are tired. Remind them of that.
{ "pile_set_name": "StackExchange" }
Q: How to loop through lowercase characters without casting? I want to loop throught my lowercase alphabet without casting. I could loop through every character, but if I cast the result, I only get the first character. How can I fix this? main.c #include "common.h" #include <iostream> #pragma comment(lib,"ws2_32") Common common; int main() { std::cout << common.ascii_uppercase(); std::cin.get(); } common.c #include "common.h" #include <iostream> char Common::ascii_uppercase(){ for (int c = 97; c <= 122; ++c) return (char)c; } A: When you return, the function execution ends, even if it is in a loop. So your loop will only run once. That's not because of the cast. If you want to return more than one char, you can return an std::string instead, like this: std::string ascii_lowercase() { std::string result; for (char c = 'a'; c <= 'z'; ++c) result += c; return result; } Note how the return isn't in the loop anymore, instead it only returns after it is done looping from a to z. This will print abcdefghijklmnopqrstuvwxyz.
{ "pile_set_name": "StackExchange" }
Q: Using destination-over to save background and actual sketch I've read this and a few other questions, and it is clear I need to use destination-over to save the background and the sketch by display the new image over the old one. I'm using Sketch.JS with my code as such: var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); $('#myCanvas').sketch({ defaultColor: "red" }); $('#download').click(function() { ctx.globalCompositeOperation = "destination-over"; img = new Image(); img.setAttribute('crossOrigin', 'anonymous'); img.src = 'http://lorempixel.com/400/200/'; ctx.drawImage(img, 0, 0); $('#url').text(c.toDataURL('/image/png')); window.open(c.toDataURL('/image/png')); }); #myCanvas { background: url(http://lorempixel.com/400/200/); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://rawgit.com/intridea/sketch.js/gh-pages/lib/sketch.js"></script> <canvas id="myCanvas"></canvas> <input type='button' id='download' value='download'> <span id='url'></span> Fiddle But that doesn't help. Clicking 'download' still only produces the sketch. Now, it seems I don't understand how I need to use destination-over properly. W3Schools doesn't seem to help. Could anyone point me in the right direction please? A: Assume you have a SketchJS canvas on top of an image containing a background: #wrapper{positon:relative;} #bk,#myCanvas{position:absolute;} <div id='wrapper'> <img crossOrigin='anonymous' id=bk src='yourImage.png'> <canvas id="myCanvas" width=500 height=300></canvas> </div> Then when you want to combine the Sketch with the background and save it as an image you can use destination-over compositing to draw the background "under" the existing Sketch. ctx.globalCompositeOperation='destination-over'; ctx.drawImage(bk, 0, 0); Here's example code: <!doctype html> <html> <head> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://rawgit.com/intridea/sketch.js/gh-pages/lib/sketch.js"></script> <style> body{ background-color: ivory; } #wrapper{positon:relative;} #bk,#myCanvas{position:absolute;} </style> <script> $(function(){ var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); $('#myCanvas').sketch({ defaultColor: "red" }); $('#download').click(function() { var img=document.getElementById('bk'); ctx.globalCompositeOperation='destination-over'; ctx.drawImage(bk, 0, 0); ctx.globalCompositeOperation='source-over'; var html="<p>Right-click on image below and Save-Picture-As</p>"; html+="<img src='"+c.toDataURL()+"' alt='from canvas'/>"; var tab=window.open(); tab.document.write(html); }); }); // end $(function(){}); </script> </head> <body> <h4>Drag to sketch on the map.</h4> <button id=download>Download</button> <div id='wrapper'> <img crossOrigin='anonymous' id=bk src='https://dl.dropboxusercontent.com/u/139992952/multple/googlemap1.png'> <canvas id="myCanvas" width=459 height=459></canvas> </div> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: What's Happening on my Vacation? I'm on vacation right now! I left on the 13th in celebration of my birthday! It was a long flight so I brought along some reading material: Faulkner, William. The Sound and the Fury. Published by Voyager Company in 1992. D8.46 -A4.1C Hemingway, Ernest. The Old Man and the Sea. Published by Scribner in 1995. D5.22 D.CB Lee, Harper. To Kill a Mockingbird. Published by Grand Central Publishing in 1988. 59.24 56.C4 ****Not part of the puzzle: Let me know if you can't find any of these books. **** I can't recall what those strange codes I wrote down were. Probably to help me remember where I am! I'm so absentminded... Anyways, I love it here. I thought I would be out in the middle of nowhere, but it seems I'm always in the centre of the hustle and bustle. For some reason, I'm worried about where I currently am. Can you figure out where I am, and tell me why I shouldn't be so worried? $$\_\_,\_\_,\_\_,\_\_,\_\_,\_\_,\_\_,\_\_$$ Meta: Again, the answer to this puzzle is a single word that fits into the blanks above. Moved from previous hint: the answer should not only describe the location but simultaneously also alleviate my worries. This puzzle should be more straightforward than my first one. Hint 1 (read if you think this puzzle will be tedious, because it's not): How absentminded am I? Before I left the US, I entered my PIN number wrong so many times at the ATM machine it locked me out! I'm so forgetful... wait, when did I leave for this trip again? That's such an important date, you'd think I'd remember it... Hint 2 (read this if a certain thing is ambiguous): If you're wondering, yes, it is the center of gravity. Also, high school physics classes used two decimal places, so it'll work for us too. Hint 3 (spoilers): Think you're on the edge of the getting the answer? Yes, yes you are. Think you've triangulated my position? Make sure it's got something in common with the first letter of every sentence. A: Final answer! You are in: the district of Chomutov in the Czech Republic near the border with Germany. The eight-letter word is: Schengen which alleviates your worries because the two countries are part of the Schengen Agreement and crossing the border should be easy. The decoding starts with: the codes below each book. They look like geodetic coordinates (latitude and longitude). As the date is the 13th and the coordinates use digits from 1-9-A-D, it seems that each book's ISBN-13 is needed. The following coordinates result from a 13 digit substitution key of 123456789ABCD: First ISBN 9781559402736 with (D8.46,-A4.1C) $\Rightarrow$ (64.15,-21.93) at Reykjavik, Iceland Second ISBN 9780684801223 with (D5.22,D.CB) $\Rightarrow$ (36.77,3.22) at Algiers, Algeria Third ISBN 9780446310789 with (59.24,56.C4) $\Rightarrow$ (41.70,44.80) at Tbilisi, Georgia Each of these locations are capital cities. A capital is "common with the first letter of every sentence". Using geomidpoint.com, the center of gravity of these three coordinates is (50.54,13.25) which is located in the Czech Republic near the border with Germany.
{ "pile_set_name": "StackExchange" }
Q: Is there such thing as a Lazy observable? I have the following observable exposed by an object through property. IObservable<HumidityLevel> humidity; But the above observable is not created until after a method of that object is called. But subscribers have to subscribe at the time of construction of that object that is exposing the above observable. One way I could think of is to create an empty observable so subscribers can subscribe IObservable<HumidityLevel> humidity = Observable.Empty<HumidityLevel>(); And later on in the object's lifetime when the actual observable is ready, merge that into the above existing ones. humidity = humidity.Concat(actualHumidityObservable) Now the above line obviously modifies the humidity reference that the Subscribers are not subscribed to so they will never hear from this object. How do I achieve what I am trying to do ? Is there any extension in Rx that can Merge into an existing observable so subscribers are preserved ? A: Subjects are the key here, they act as both observers and observables. As well as manually invoking events on a subject via it's On... methods, you can also just subscribe them to a source observable directly - either before or after the subjects own subscribers subscribe. Here's one way you might do this: public class HumidityLevel { public int Value; } public class Monitor { private Subject<HumidityLevel> _humidityLevel = new Subject<HumidityLevel>(); public IObservable<HumidityLevel> HumidityLevel { get { return _humidityLevel.AsObservable(); } } public void StartMonitoring(IObservable<HumidityLevel> source) { source.Subscribe(_humidityLevel); } } Note the use of AsObservable() in the getter - this is a means to protect the origin of the observable as an underlying Subject and thus from being abused! Then use it like this: var monitor = new Monitor(); // a subscriber is free to subscribe at any time var subscriber = monitor.HumidityLevel .Subscribe(level => Console.WriteLine(level.Value)); // now create an example source var source = Observable.Interval(TimeSpan.FromSeconds(1)) .Select(i => new HumidityLevel { Value = (int)i }); // and pass it to monitor and the subscriber will start getting events monitor.StartMonitoring(source); Note I am not doing any clean up here, like unsubscribing from the source when you are done with it. Whether you need to do this, and how you do it will be dependent on your scenario. It may not matter, or you might want to track the subscription and release it on reassignment of a fresh source. In this case you might be interested in storing the subscription to the source in a SerialDisposable. There are lot of options here.
{ "pile_set_name": "StackExchange" }
Q: add string in each line at the begining of column I digged many threads, but neither of them adresses this question as it stands. I am interested in addind string chr to the begining of column in each line. File is tab delimited, looks sth like: re1 1 AGT re2 1 AGT re3 2 ACGTCA re12 3 ACGTACT what I need is: re1 chr1 AGT re2 chr1 AGT re3 chr2 ACGTCA re12 chr3 ACGTACT Can be in bash oneliner many thanks for any help, cheers, Irek A: What about this? $ awk '$2="chr"$2' file re1 chr1 AGT re2 chr1 AGT re3 chr2 ACGTCA re12 chr3 ACGTACT Explanation With $2="chr"$2 we add chr to the 2nd field. Then we do not need any other command to get the desired output, as the default behaviour of awk is print $0. To make sure the OFS (output field separator) is a tab, you can do the following: $ awk 'BEGIN{OFS="\t"}$2="chr"$2' file re1 chr1 AGT re2 chr1 AGT re3 chr2 ACGTCA re12 chr3 ACGTACT A: Awk one-liner do? $ awk -v OFS=$'\t' '{ $2="chr" $2; print}' so.txt re1 chr1 AGT re2 chr1 AGT re3 chr2 ACGTCA re12 chr3 ACGTACT
{ "pile_set_name": "StackExchange" }
Q: CSS triangular cutout with border and transparent gap I need to draw the following pattern with CSS as a separator between sections of my page: Using the skewX() technique from this answer, I was able to mimic the triangular cutout accurately (two pseudo-elements are appended to the top of the lower section, one skewed left and one skewed right, so that the background of the upper section shows through): But I can't figure out how to then add the border, as shown in the first image. The problem is that the gap between the border and the lower section has to be transparent, because the background of the upper section can be a gradient, an image, etc. Therefore, I can't simply use an image for the triangular cutout, because I can't know what content will be behind it. Is there any possible way to do this with CSS? A: It is possible to do this with CSS but the only approach that I could find is a very complex one using a fair amount of gradients to mimic the borders. This couldn't be done with normal borders because that resulted in either the borders extending beyond their meeting point or the inner area never meeting. It couldn't be done with box shadow's also because the gap between the border and the filled area need to be transparent. (Not saying it cannot be done with those but just that I couldn't get it to work, maybe there is a way with those too). The below is how I've managed to achieve the border: Four linear gradients were used to create the borders that are required. The 1st and 2nd are actually solid colors (that is, there is no change from 1 color to another) but I had used gradients because that allows us to control the background-size. These two produce a solid horizontal line where one is positioned on the left and another is positioned on the right a bit above the transparent cut that was produced using the pseudo-elements. The 3rd and 4th produce the angled lines with the same thickness as required for the border. The size and position of all the four gradients are set such that they produce the border effect. The output - as you can see by hovering the element - is responsive too. div { position: relative; height: 200px; width: 300px; background: linear-gradient(#DDD, #DDD), /* horizontal border line on left */ linear-gradient(#DDD, #DDD), /* horizontal border line on right */ linear-gradient(to top right, transparent calc(50% - 2px), #DDD calc(50% - 2px), #DDD calc(50% + 2px), transparent calc(50% + 2px)), /* angled border on left of center */ linear-gradient(to top left, transparent calc(50% - 2px), #DDD calc(50% - 2px), #DDD calc(50% + 2px), transparent calc(50% + 2px)), /* angled border on right of center */ radial-gradient(circle, #3F9CBA 0%, #153346 100%) /* actual background */; background-size: calc(50% - 38px) 4px, calc(50% - 38px) 4px, 40px 40px, /* size of one half of the triangle */ 40px 40px, /* size of one half of the triangle */ auto auto /* size of actual bg */; background-position: 0% calc(100% - 44px), 100% calc(100% - 44px), calc(50% - 18px) calc(100% - 8px), calc(50% + 18px) calc(100% - 8px), 0px 0px; background-repeat: no-repeat; overflow: hidden; border-bottom: 20px solid #DDD; } div:before, div:after { position: absolute; content: ''; height: 40px; width: 50%; bottom: 0; background: #DDD; backface-visibility: hidden; } div:before { left: 0; transform-origin: left bottom; transform: skewX(45deg); } div:after { right: 0; transform-origin: right bottom; transform: skewX(-45deg); } /* Just for demo */ div { transition: all 1s; } div:hover { height: 250px; width: 550px; } <div></div> The following is how the background properties need to be set based on the required border color and width (all calculations for 45 degree skew angle, different angle will need different calculations): The colors used within the gradient is the same as the border color. So, if border color needs to be red instead of #DDD then all color values should be changed to red. The thickness of the border will be determined using background-size for the first two gradients and using the gradient's color-stop points for the next two gradients. For the first two, the background-size in Y-axis is nothing but the border thickness. Change it to suit the needed thickness. The background-size in X-axis is nothing but 50% minus the height of the pseudo minus half of border thickness For the next two, the color stop points of the gradient should be set such that the color starts (and transparent ends) at 50% - half the border thickness and color ends (transparnet starts) and 50% + half the border thickness (so that it produces a stroke of required thickness). The background-position should be set such that the required gap is there between the colored area and the border. For the first two, the background-position in X-axis should be left edge (0%) and right edge (100%) respectively. Their position in Y-axis should be above the pseudo-element and so it should be 100% minus pseudo-element's height minus the spacing. For the next two, the background-position involves more complex calculation involving the border spacing, thickness and pseudo-element's height. The logic is present below. background: linear-gradient([color, [color]), linear-gradient([color], [color]), linear-gradient(to top right, transparent calc(50% - [border-thickness/2]), [color] calc(50% - [border-thickness/2]), [color] calc(50% + [border-thickness/2]), transparent calc(50% + [border-thickness/2])), linear-gradient(to top left, transparent calc(50% - [border-thickness/2]), [color] calc(50% - [border-thickness/2]), [color] calc(50% + [border-thickness/2]), transparent calc(50% + [border-thickness/2])), radial-gradient(circle, #3F9CBA 0%, #153346 100%) /* actual background */; background-size: calc(50% - [pseudo-height - border-thickness/2]) [border-thickness], calc(50% - [pseudo-height - border-thickness/2]) [border-thickness], [pseudo-height] [pseudo-height], [pseudo-height] [pseudo-height], auto auto /* size of actual bg */; background-position: 0% calc(100% - [pseudo-height + border-space]), 100% calc(100% - [pseudo-height + border-space]), calc(50% - [(pseudo-height - border-space)/2]) calc(100% - [border-space + border-thickness/2]), calc(50% + [(pseudo-height - border-space)/2]) calc(100% - [border-space + border-thickness/2]), 0px 0px; If you need the transparent cut with border on the top part of the lower div then you could achieve it like in the below snippet. div { height: 200px; width: 300px; } div:nth-child(1) { background: radial-gradient(circle, #3F9CBA 0%, #153346 100%); background-repeat: no-repeat; } div:nth-child(2) { position: relative; margin-top: -48px; padding-top: 48px; background: linear-gradient(#DDD, #DDD), linear-gradient(#DDD, #DDD), linear-gradient(to top right, transparent calc(50% - 2px), #DDD calc(50% - 2px), #DDD calc(50% + 2px), transparent calc(50% + 2px)), linear-gradient(to top left, transparent calc(50% - 2px), #DDD calc(50% - 2px), #DDD calc(50% + 2px), transparent calc(50% + 2px)), linear-gradient(#DDD, #DDD); background-size: calc(50% - 38px) 4px, calc(50% - 38px) 4px, 40px 40px, 40px 40px, auto auto; background-position: 0% 0px, 100% 0px, calc(50% - 18px) 0px, calc(50% + 18px) 0px, 0px 0px; background-repeat: no-repeat; background-clip: border-box, border-box, border-box, border-box, content-box; overflow: hidden; } div:nth-child(2):before, div:nth-child(2):after { position: absolute; content: ''; height: 40px; width: 50%; top: 8px; background: #DDD; backface-visibility: hidden; } div:before { left: 0; transform-origin: left bottom; transform: skewX(45deg); } div:after { right: 0; transform-origin: right bottom; transform: skewX(-45deg); } /* Just for demo */ div { transition: all 1s; } body:hover > div { height: 250px; width: 550px; } <div></div> <div></div> A: here anoter approach with gradient and (@Harry )borders & shadow : A known width helps much, else, you need to adjust some shadows offset values with calc(). div.bdr { padding-bottom: 5px;/* to be used to draw a transparent line */ background: #1B4046; background-clip: content-box;/* here comes the 5 transparent pixel line */ box-shadow: -273px 5px 0 #1B4046, 274px 5px 0 #1B4046; /* move shadow far away to only draw them by bits Notice, wrapper must be hidding overflow */ margin-bottom:2em; } .bdr.bg-color{ background-color:tomato; background-image:linear-gradient(to top, transparent 5px, #1B4046 5px); background-clip:border-box; } div.bdr:after { content: ''; height: 30px; width: 30px; padding: 5px; display: block; margin: auto; z-index: -1; transform: rotate(45deg); margin: -20px auto -20px; background: #1B4046; background-clip: content-box;/* again, keep some parts transparent */ box-shadow:6px 6px 0 -1px #1B4046; } .bdr.bg-color:after { z-index:0; padding:5px 0 0 5px; border:5px solid transparent; border-left:0; border-top:0; box-shadow:6px 6px 0 -1px #1B4046; background:linear-gradient(to bottom right, transparent 50%, #1B4046 50%) no-repeat , linear-gradient(to bottom right, transparent 50%, tomato 50%) 5px 5px no-repeat; } article { width:500px; margin:auto; color:white; } h1 { text-align:center; } div.shapebdr { padding-bottom: 40px; margin: 32px 0; background: linear-gradient(to top, transparent 30px, #1B4046 30px, #1B4046 35px, transparent 35px) bottom left, linear-gradient(to top, transparent 30px, #1B4046 30px, #1B4046 35px, transparent 35px) bottom right, linear-gradient(to top, transparent 40px, #1B4046 40px) bottom; ; background-repeat: no-repeat; background-size: 230px 100%, 230px 100%, 100% 100%; position: relative; } div.shapebdr:after { content: ''; height: 40px; width: 40px; padding: 10px; display: block; margin: auto; z-index: -1; background: inherit; transform: rotate(45deg); margin: -40px auto -20px; background: linear-gradient(to top, #1B4046, #1B4046) no-repeat, linear-gradient(to top, #1B4046 0, #1B4046 5px, transparent 5px) no-repeat right, linear-gradient(to left, #1B4046 0, #1B4046 5px, transparent 5px) no-repeat bottom right; background-clip: content-box, border-box, border-box; background-size: auto auto, 57% 100%, 100% 57%; } div.br:after { margin: auto; margin-bottom: -40px; } article { overflow: hidden; padding-bottom: 40px; } html { min-height: 100%; background: linear-gradient(30deg, gray, yellow, purple, lime, tomato, turquoise, gray); } p { padding:0.25em; margin:0.25em; position:relative;/* make sure text shows over the pseudo element */ } <article> <h1>border and shadow approach </h1> <div class="bdr"> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. facilisis luctus, metus</p> </div> <h1>gradient approach</h1> <div class="shapebdr"> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p> </div> <h1>shadow + gradient approach to fill translucide line</h1> <div class="bdr bg-color"> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p> </div> </article> pen to play with
{ "pile_set_name": "StackExchange" }
Q: dlopen failed: cannot locate symbol "__cxa_finalize" referenced by "/system/lib/libdl.so" Up until Android 6, we had a working version of application, which was written using Qt Android, starting from Android 6 in Nexus device we are seeing strange error dlopen failed: cannot locate symbol "__cxa_finalize" referenced by "/system/lib/libdl.so" and application crashes. objdump -T ourlibrary.so ... 00000000 DF *UND* 00000000 __cxa_finalize ... tested with -lc flag in order to link libc.so, couldn't help, without it same problem. other dependant libraries while building: libgnustl_shared.so in order to cheat compiler we have added extern "C" int __cxa_finalize(void*); // { empty body somewhere in .cpp file } didn't help, could someone point into the problem? Note: this was fully working until Android 6 (Marshmallow) UPD1: api version android-9, architecture arm, qt android compilation armv5, toolchain version 4.9 UPD2: some other libraries are showing glibc version 00000000 w DF *UND* 00000000 GLIBC_2.2.5 __cxa_finalize A: I saw the same error when running my application. Do you have: System.loadLibrary("dl"); Located in your code somewhere? If so, what I did to make my code run on 6 and <6 was to catch and ignore the UnsatisfiedLinkError exception thrown by 6 when trying to load the library.
{ "pile_set_name": "StackExchange" }
Q: PyCharm 2017.3.3 hangs There is PyCharm, an IDE for programming Python. It's available in a Community edition for Linux as well. The problem affects (at least) version 2017.3.3. I installed it as a normal user with wget https://download.jetbrains.com/python/pycharm-community-2017.3.3.tar.gz tar -xzf pycharm-community-2017.3.3.tar.gz mv pycharm-community-2017.3.3 pycharm rm pycharm-community-2017.3.3.tar.gz cd pycharm/bin ./pycharm.sh The remaining installation steps are guided by a wizard: do not import settings accept license Darcula theme create a startup script install Markdown support confirm warning about granted permissions create a new project, create virtual environment wait for installation of setuptools, pip, wheels etc. close startup tips wait until indexing is done wait until skeletons are built wait until packages are scanned So far, everything is fine. However, even when all those steps have completed successfully, PyCharm hangs in several situations, e.g. when loading a project (sometimes) when typing code into a .py file (sometimes) when running the project (always) What is the cause and how can I fix it? I have installed the Rasbian IMG file from 2017-11-29 and performed sudo apt-get update and sudo apt-get upgrade prior to the PyCharm installation. A: The problem is related to the Java version. In my case, the Java version is $ java -version java version "1.8.0_65" Java(TM) SE Runtime Environment (build 1.8.0_65-b17) Java HotSpot(TM) Client VM (build 25.65-b01, mixed mode) The same version is also mentioned in the PyCharm about dialog. You may not have noticed it, but PyCharm displays a message in the event log. IDE's Java runtime (1.8u65), which may cause instability. Update to version 1.8.0u144 or higher. The solution is to be to update to a newer Java version. However, sudo apt-get update sudo apt-get upgrade will not install a new version. However, sudo apt-get purge oracle* sudo apt-get update sudo apt-get upgrade sudo apt-get remove oracle* reboot solved the problem and OpenJDK was installed. You should confirm that with a Java version check: $ java -version openjdk version "1.8.0_151 OpenJDK Runtime Environment (build 1.8.0_151-8u151-b12-1-deb9u1-b12) OpenJDK Client VM (build 25.151-b12, mixed mode) Since then, PyCharm operated totally fine for us. You could also download and install a Java version manually, but since we are teaching kids, we wanted to have a simple OS-supported solution.
{ "pile_set_name": "StackExchange" }
Q: Understanding Logarithms I’m currently in my senior year of high school and we just started on the topic of logs, when doing textbook work I encountered a problem and I am confused on where I’m going wrong. Could any body help? $$2^x+1 = 3^x-1 \implies x\log2 + \log2 = x\log3 - \log3$$ After this I don’t know where to go. A: Remember, the values $\log 2$ and $\log 3$ are just real numbers, so you're now trying to solve the equation $ax + a = bx - b$, where $a=\log 2$ and $b = \log 3$.
{ "pile_set_name": "StackExchange" }
Q: How to view the log rows in group/session in Kibana's Discover UI? I'm using elasticsearch + kibana + logstash + filebeat latest 6.4.1 to collect and analyze web logs. The columns of my log are like: timestamp, http_method, request_uri, http_status, host, user_agent, client_ip, client_port I have configured ELK to show my logs in Kibana. But now I want to see my logs in sessions. I hope the log lines can be grouped by session and shown in Kibana's Discover page. In my scenario, the log lines with the same (host, client_ip) belong to the same session. I hope the Discover with session/grouping UI can show all the sessions. And I can still see the log lines inside one session when I click it. Is it possible to do it? Or what's the best way to do it? Thanks. A: Discover shows you the log entries as raw documents as they are stored, you can save the search on Discover, even without filtering anything. Through Vizualize you can create widgets, these can aggregate data like sessions. I usually make one or two "visual builder" for timelines and a data table for (request_uri, host, user_agent, client_ip) and a pie for http_status. With these visuals you can create a Dashboard and include the search result from discover. On this dashboard you can search and filter and if you add the search from discover, the dashboard will show the raw data for each will still show. I only use discover after adding new indices. https://www.elastic.co/guide/en/kibana/current/visualize.html https://www.elastic.co/guide/en/kibana/current/dashboard.html If you really want the index contain the host/client_ip as a aggregate you have to group the data before you store it in elasticsearch. A Dashboard sounds like a better idea. EDIT: As Waleed Ali described, the visualize could look like this
{ "pile_set_name": "StackExchange" }
Q: Creating / Modifying Enums at Runtime I'm creating a program where the user has the option of creating their own custom properties that will ultimately be displayed in a PropertyGrid. Right now I don't want to mess with custom editors, so I'm only allowing primitive type properties (string, int, double, DateTime, bool etc.) that the PropertyGrid already has built in editors for. However, I also want to give the user the option to create multiple choice properties where they can defined a list of possible values which in turn will show up as a drop down list in the PropertyGrid. When I hard code an Enum in my code the property grid automatically shows properties of that enum as a drop down list. But can I create and or modify an enumeration at runtime so the user could add another property option, and go back to the PropertyGrid and see their new option in a drop down? Update Considering Patricks comment, I'm thinking that Enums are not the right way to go in this case. So instead how can I use a list of strings to populate a drop down in a PropertyGrid item? Would that require a custom editor? A: The answer is in a simple class: TypeConverter. (and yes, enums are not suitable here). Since I have not a lot of details, I will assume that you have a PropertyGrid "linked" to a target instance by the SelectedObject property and that your target instance implements ICustomTypeDescriptor so that you can add properties (i.e. PropertyDescriptors) at runtime. I don't know your design but if you are not doing like this, I advise you to have a look at it. Now let's say that you add a string property and that you want to let your user specify a set of constraints for this property. Your UI let's the user enter a set of strings and you get a list of strings as a result. Maybe you keep a dictionary of properties in your target instance so let's assume this new list is stored there too. Now, just write a new converter derived from TypeConverter (or StringConverter maybe in this example). You will have to override GetStandardValuesSupported to return true and GetStandardValues to return the list of strings (use the context parameter to access the Instance property and its list of strings). This converter will be published by your PropertyDescriptor with the PropertyDescriptor.Converter property. I hope this is not too nebulous. If you have a specific question on this process, just let me know. A: The typical engineering solution to your problem is to use to maintain the list as reference data in your database. In general enums are intended to be constants defined at compile time, and their modification in later released of code is discouraged (let alone runtime), as it can cause side effects in switch statements.
{ "pile_set_name": "StackExchange" }
Q: Repositioning GridLayout in Swing I've created a board game with 8x8 GridLayout where in each grid, there is a button which is opaque. I've created to show in the form of a 8x8 table and when user clicks on any cell, it should do some action. Right now, the grid looks like : I want it to re-position this through animation at an angle to look like this: Is it possible to do this in Swing using repaint? If not, is there a better toolkit to use other than Swing so that I can animate this? A: Changing the state of a live component requires more then just painting... For example, based on Boann's example... Painting in Swing is a complex and optimised process, which isn't always done in a linear fashion. Having said that, there is a way, but you are going to need to work for it. This is based on the JXLayer API and pbjar examples import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.GridBagLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.jdesktop.jxlayer.JXLayer; import org.pbjar.jxlayer.demo.TransformUtils; import org.pbjar.jxlayer.plaf.ext.transform.DefaultTransformModel; public class Twister02 { public static void main(String[] args) { new Twister02(); } public Twister02() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new ExamplePane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class ExamplePane extends JPanel { private JSlider slider; private FieldPane fieldPane; private DefaultTransformModel transformModel; public ExamplePane() { setLayout(new BorderLayout()); slider = new JSlider(0, 360); slider.setValue(0); slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { transformModel.setRotation(Math.toRadians(slider.getValue())); } }); fieldPane = new FieldPane(); transformModel = new DefaultTransformModel(); transformModel.setRotation(Math.toRadians(0)); transformModel.setScaleToPreferredSize(true); JXLayer<JComponent> rotatePane = TransformUtils.createTransformJXLayer(fieldPane, transformModel); add(slider, BorderLayout.NORTH); add(rotatePane); } } public class FieldPane extends JPanel { public FieldPane() { setLayout(new GridLayout(8, 8)); for (int i = 0; i < 64; i++) { add(new JButton("" + i)); } } } } Now, the problem is, the pbjar examples seem to have vanished off the face of the internet, to our great disappointment. However, you can grab a copy from here Add because it's fun... import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.GridBagLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import org.jdesktop.jxlayer.JXLayer; import org.pbjar.jxlayer.demo.TransformUtils; import org.pbjar.jxlayer.plaf.ext.transform.DefaultTransformModel; public class Twister02 { public static void main(String[] args) { new Twister02(); } public Twister02() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new BorderLayout()); frame.add(new ExamplePane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class ExamplePane extends JPanel { private JSlider rotateSlider; private JSlider shearXSlider; private JSlider shearYSlider; private FieldPane fieldPane; private DefaultTransformModel transformModel; public ExamplePane() { setLayout(new BorderLayout()); rotateSlider = new JSlider(0, 180); rotateSlider.setValue(0); rotateSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { transformModel.setRotation(Math.toRadians(rotateSlider.getValue())); } }); shearXSlider = new JSlider(-100, 100); shearXSlider.setValue(0); shearXSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { double value = shearXSlider.getValue() / 200d; transformModel.setShearX(value); } }); shearYSlider = new JSlider(-100, 100); shearYSlider.setValue(0); shearYSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { double value = shearYSlider.getValue() / 200d; transformModel.setShearY(value); } }); fieldPane = new FieldPane(); transformModel = new DefaultTransformModel(); transformModel.setRotation(Math.toRadians(0)); transformModel.setScaleToPreferredSize(true); JXLayer<JComponent> rotatePane = TransformUtils.createTransformJXLayer(fieldPane, transformModel); JPanel sliders = new JPanel(new GridLayout(3, 0)); sliders.add(rotateSlider); sliders.add(shearXSlider); sliders.add(shearYSlider); add(sliders, BorderLayout.NORTH); add(rotatePane); } } public class FieldPane extends JPanel { public FieldPane() { setLayout(new GridLayout(8, 8)); for (int i = 0; i < 64; i++) { add(new JButton("" + i)); } } } }
{ "pile_set_name": "StackExchange" }
Q: Regarding Analysis for CO2 Absorption in NaOH Background Lab experiment, packed glass column (random packing of metal/ceramic material), countercurrent gas absorption, flowrates measured using rotameters, $rt \approx 27^\circ C$. 2 N NaOH flows downwards at 10-30 mL/s; Air + $\ce{CO2}$ (~10% $\ce{CO2}$ (v/v)) flows upwards at total rate of ~350-500 mL/s. Samples were collected as (I) 10 mL + (II) 10 mL from the bottom of the column. An excess of $\ce{BaCl2}$ was added to (II). Both are titrated against 0.5 N HCl with phenolphthalein ($\ce{HPh}$) as indicator. Expected Reactions $$\ce{2NaOH + CO2 \to Na2CO3}$$ $$\ce{Na2CO3 + BaCl2 \to BaCO3 + 2NaCl}$$ Colour changes: $$\ce{HPh + HO- \to Ph- + H2O}$$ $\ce{HPh}$ is colourless and $\ce{Ph-}$ is pink The Problem The first few readings were as expected and no irregularities were observed. The volumes of HCl added were $<$ 15 mL. Later On adding indicator and waiting for some time, the colour disappeared (pink $\to$ colourless) for both (I) and (II). Shaking sped up the colour change process. On adding indicator and starting titration immediately, the colour lightened (did not fade away completely) for a considerable volume of HCl added, then darkened considerably, and after a few more drops, suddenly became colourless (white in case of (II)). The volume of HCl added was $>$ 40 mL. Such a great change is not expected. One Possibility: $\ce{CO2}$ from the atmosphere reacts with the sample to increase the acidic nature of the solution and causes the disappearance of colour. This would explain speeding up of colour change by shaking. But, is the rate of absorption of CO2 into a still sample of $\ce{NaOH + Na2CO3}$ this fast? Other possibilities Formation of buffer: $\ce{Na+}$, $\ce{CO3^{2-}}$, $\ce{HO-}$ ions are present in (I). (II) additionally contains $\ce{Ba^{2+}}$, $\ce{Cl-}$. The tap water used might be a source of $\ce{Cl-}$ as well. $\ce{HCO3-}$ formation during titration (?) The packing material might have reacted into the system somehow. This seems unlikely, and the packings did not show signs of fouling. The chemicals used contain impurities causing these weird effects, in which case, which type of impurites could cause this? Note: Do comment if you more information is needed. A: Phenolphthalein becomes colorless again (from pink) in strongly basic medium with time. It is a known phenomenon called the alkaline fading of phenolphthalein. https://scholar.google.com/scholar?hl=en&as_sdt=0%2C44&q=fading+of+phenolphthalein+in+alkaline+solution&btnG= It is not a good choice to use phenolphthalein in the presence of sodium carbonate or bicarbonate. Methyl orange is typically used when NaOH and Na2CO3 are present together. Please consult the classic Vogel's "Quantitative Inorganic Analysis" for more details. Alternatively, you may try a potentiometeric titration (pH vs. volume of titrant). Measure the pH after every 0.5 mL addition of titrant and construct a titration curve. The reaction of CO2 with NaOH is very fast.
{ "pile_set_name": "StackExchange" }