prompt
stringlengths
66
13.6k
chosen
stringlengths
40
27.8k
rejected
stringlengths
16
13.3k
I want to disable cash on delivery payment method option for some specific products. I want to show cash on delivery method only for specific products and need to hide other payment options. How can I do this? I read [this other question](https://stackoverflow.com/questions/14011348/disable-payment-options-only-cash-on-delivery-for-particular-product-magento) but it did not solve my problem.
Using payment\_method\_is\_active observer you could load the current checkout session quote and check what city the order is be shipped to. ``` $checkout = Mage::getSingleton('checkout/session')->getQuote(); $shipping = $checkout->getShippingAddress(); $cashOnDeliveryCities = array('city name 1','city name 2',..) if(in_array($shipping->getCity(), $cashOnDeliveryCities)){ $result->isAvailable = true; }else{ $result->isAvailable = false; } ```
Here's how to do it without an extension. Just go to admin > per motions > Shopping Cart Price Rule and create rules for this "cash on delivery payment method option for some specific products". First in conditions select payment method "COD" in options. After that in "Action" add product SKU, for multiple using add SKU by comma. Activate the rule and check your payment method for those products to ensure it's working.
I'm developing an eclipse plugin and I'm starting to have performance problems, so I's like to start using a profiler. Since it's an eclipse plugin and not an ordinary java program, what tool should I use to profile it?
You don't need the `@`, since this is not a `razor` view (MVC 3). In MVC 2 you do: ``` <div id="leftcolumn"> <%= Html.ActionLink("Home", "Home", "Home") %> <%= Html.ActionLink("About", "About", "Home") %> <%= Html.ActionLink("Sermon", "Sermon", "Home") %> </div> ```
Your mixing Razor syntax (MVC3) with MVC2 code, for MVC2 you want to do: ``` <%= Html.ActionLink("Home", "Home", "Home") %> ... ```
I'm a .NET guy originally, working in Java recently, and finding I'm really missing LINQ to Objects, specifically for performing filtering against collections. A few people here on Stack Overflow have answered the "LINQ for Java?" question with a single word : > > [Quaere](http://quaere.codehaus.org/) > > > However, on the site it clearly states "Pre-Beta", and there's been no commits to their code for over a year, so I'm guessing the project is pretty much dead. Is anyone actually using this, and / or have any experience with it? The second most common answer appears to be "use Google Collections". Is this the most appropriate Java way? Cheers Marty
Quaere is in a pioneer position with LINQ in Java, but is not typesafe, which is one of the main points of LINQ. [Querydsl](http://www.querydsl.com) is type-safe and supports filtering, sorting and projecting Collections. It supports operations on JPA/Hibernate, JDO and SQL backends as well. The syntax is similar to SQL with the difference that the basic order is from-where-list. I am the maintainer of Querydsl, so this answer is biased.
There is the [extra166y addendum to JSR166y](http://g.oswego.edu/dl/concurrency-interest/) with the [ParallelArray](http://gee.cs.oswego.edu/dl/jsr166/dist/extra166ydocs/extra166y/ParallelArray.html) construct. Basically a PLINQ for object arrays.
I have some fresh peaches that have been peeled and sliced and mixed with some sugar and a little lemon (approx 1/2 a bushel). All the recipes I can find only call for "8 peaches" or similar values. But my peaches are already cut up. Does anyone have a suggestion as to how many cups of peaches is equivalent to 8 peaches?
I've found that 2 medium size peaches is a cup, give or take, and this works in a recipe I like that calls for 8 peaches.
8 peaches equal five and a half to 6 cups of sliced peaches
I've done some algebra tricks in this derivation and I'm not sure if it's okay to do those things. $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = \cos^2\theta + \sin^2\theta$$ Can I really do this next step? $$\frac{x^2}{a^2} = \cos^2\theta\quad\text{and}\quad\frac{y^2}{b^2} = \sin^2\theta$$ $$x^2 = a^2\cos^2\theta\quad\text{and}\quad y^2 = b^2\sin^2\theta$$ Ignoring the negative numbers: $$x = a\cos\theta\quad\text{and}\quad y = b\sin\theta$$
The idea behind your argument is absolutely fine. Any two non-negative numbers $u$ and $v$ such that $u+v=1$ can be expressed as $u=\cos^2\theta$, $v=\sin^2\theta$ for some $\theta$. This is so obvious that it probably does not require proof. Set $u=\cos^2\theta$. Then $v=1-\cos^2\theta=\sin^2\theta$. The second displayed formula muddies things somewhat. You intended to say that if $x^2/a^2+y^2/b^2=1$, then there **exists** a $\theta$ such that $x^2/a^2=\cos^2\theta$ and $y^2/b^2=\sin^2\theta$. You did not mean that for **any** $\theta$, if $x^2/a^2+y^2/b^2=1$ then $x^2/a^2=\cos^2\theta$! But the transition from the second displayed equation to the third could be interpreted as asserting what you clearly did not intend to say. It would be better to do exactly what you did, but to use more geometric language, as follows. $$\frac{x^2}{a^2}+\frac{y^2}{b^2}=1 \quad\text{iff}\quad \left(\frac{x}{a}\right)^2 + \left(\frac{y}{b}\right)^2=1.$$ But the equation on the right holds iff the point $(x/a, y/b)$ lies on the unit circle. The points on the unit circle are parametrized by $(\cos \theta,\sin\theta)$, with $\theta$ ranging over $[0,2\pi)$, so the points on our ellipse are given by $x=a\cos\theta$, $y=a\sin\theta$.
Which kind of "okay" do you aim for here -- it is usually "okay" to use dodgy steps to find an answer if only you can prove it's correct once you know what it is. Doing mathematics has two parts: (1) you need to figure out what to prove, and (2) you need to actually prove it. The latter part is an exact science; it has clear and strict rules for what is allowed and what is not, and it's the one that usually gets all the press. However, the first one is no less important. It is sometimes easier and sometimes harder, but its rules are quite different, namely this: anything goes! Yes, really. No matter how you got the idea to prove such-and-such, the only thing that matters is that you can deliver in phase 2 (and that what you proved then turns out to be useful in the context of whichever problem you had originally, but that's a different matter). Sometimes, the process by which you arrive at the-thing-to-prove is so straightforward that you can read a proof directly off it with essentially no effort. Teachers love these cases (and sometimes give the impression they are all there is), because they make things look nice and orderly, and they're easy to grade. But in real mathematics, there is *no shame at all* in using less direct methods to find the answer you prove correct later. It doesn't matter if you divided by zero in order to find it, or if an angel appeared in a dream and told you -- if you can deliver a proof that the answer is right at the end of the day, then that is "correct", no matter how you found it. So it's not really meaningful to ask for a "correct" way to arrive at the parameterization. The important thing, once you have made the leap of faith to separate the two sums, is to prove that the result is right, i.e., that image of your parametric curve is exactly the set of solutions to the original equation. One side of this is simple. If we substitute your expressions for $x$ and $y$ into the equation, we get $$\frac{(a\cos\theta)^2}{a^2} + \frac{(b\sin\theta)^2}{b^2} = 1$$ and it is then a simple matter of rigorous but uninspired rewriting to prove that this is indeed an identity. (This kind of verification is what is typically meant by "by inspection"). Now we have proved that the image of your curve is a *subset* of the set of solutions. It then remains to prove that the set of solutions is a subset of the image of the curve. To do we assume that some given $x$ and $y$ satisfy the equation, and then aim to prove that there must exist a $\theta$ such that $x=a\cos\theta$ and $y=b\sin\theta$. How do we do this? Well, at this time of the night the best I can think of would be some horribly messy case analysis on the various combinations of signs for $x$ and $y$, with special cases if one of them is 0 and otherwise something like $\arctan(\frac{ay}{bx})$ turning up somewhere -- possibly a lemma proving that $(tx,ty)$ can only be a solution if $|t|=1$ will be necessary along the way. If would work out eventually, but it wouldn't be pretty. I'm not even going to try to get all of the details right just now. Perhaps you can find a slicker argument. Perhaps there is none. Perhaps your audience will be happy with a more handwavy argument than the one I'm imagining.
I have a following method: ``` def a(b='default_b', c='default_c', d='default_d'): # … pass ``` And I have some command-line interface that allows either to provide variables `user_b`, `user_c`, `user_d` or to set them to `None` - i.e. the simple Python `argparse` module. I want to make a call like: ``` a(b=user_b if user_b is not None, c=user_c if user_c is not None, d=user_d if user_d is not None) ``` If the variable is `None` I want to use a default value from the method's argument. The only way I found is to check all the combinations of the user variables: ``` if not user_b and not user_c and not user_d: a() elif not user_b and not user_c and user_d: a(d) … elif user_b and user_c and user_d: a(b, c, d) ``` What is more efficient, fancy and Pythonic way to solve my problem?
You could write a function that filters out unwanted values then use it to scrub the target function call. ``` def scrub_params(**kw): return {k:v for k,v in kw.items() if v is not None} some_function(**scrub_params(foo=args.foo, bar=args.bar)) ```
You can define a class with your data and pass the object as argument. ``` class Args: def __init__(self, user_b, user_c, user_d): self.b = user_b self.c = user_c self.d = user_d ```
I am currently tasked with finding a solution for a serious PHP bottleneck which is apparently caused by server-side minification of CSS and JS when our sites are under high load. Some details and what I have found out so far ============================================= I inherited a web application running on Wordpress and which uses a complex constellation of Doctrine, Memcached and W3 Total Cache for minification and caching. When under heavy load our application begins to slow down rapidly. So far we have narrowed part of the problem down to the server-side minification process. Preliminary analysis has shown that the number PHP processes start to stack up under load, and when reaching the process limit of 500 processes, start to slow everything down. Something which is also mentioned [by the author of the minify library](https://github.com/mrclay/minify#warnings). Solutions I have evaluated so far ================================= **Pre-minification** The most logical solution would be to **pre-minify any of the files** before going live. Unfortunately our workflow demands that non-developers should be able to edit said files on our production servers (i.e. after the web app has gone live). Therefore I *think* that pre-processing is out of the question, as it limits the editability of minified files. **Serving unminified files** 75% of our users are accessing our web application with their mobile devices, especially smartphones. Unminified JS and CSS amounts to 432KB and is reduced by 60-80% in size when minified. Therefore serving unminified files, while solving the performance and editability problem, is for the sake of mobile users out of the question. I understand that this is as much a technical problem as it is a workflow problem and I guess we are open to working on both as long as we end up with a better overall performance. My questions ============ 1. Is there a reasonable compromise which solves the PHP bottleneck problem, allows for non-devs to make changes to live CSS/JS and still serves reasonably sized files to clients. 2. If there is no such one-size-fits-all solution, what can I do to better our workflow and / or server-side behaviour? EDIT: Because there were some questions / comments regarding the server configuration, our servers run Debian and are equipped with 32GB of RAM and 24 core CPUs.
You can run a css/javascript compilation service like `Gulp` or `Grunt` via `Node.js` that minifies all your js and css assets on change. This service can run in production but that is not recommended without some architectural setup ( having multiple versioned compiled files and auto-checking them via gulp or another extension ). > > I emphasize that patching features into production and directly > editing it is strongly discouraged as it can present live issues to > your visitors reducing your credibility. > > > <http://gulpjs.com/> Using `Gulp/Grunt` would require you to change how you write your css/javascript files.
I like the idea of using [GulpJS](http://gulpjs.com). One thing you might consider is to have a wp-cron or even just a system cron that runs every 5 minutes or so and then runs a gulp task to minify and concatenate your css and js files. Another option that doesn't require scheduling but is based off of watching the file system for changes and then triggering a Gulp build to happen is to use incron (inotify cron). Check out the [incron man page](http://manpages.ubuntu.com/manpages/natty/en/man8/incrond.8.html). Incron is great in that it triggers actions based on file system events such as file changes. You could use this to trigger a gulp build when any css file changes on the file system. One caveat is that this is a Linux solution so if you're hosting on Windows you might have to look for something similar. Edit: [Incron Documentation](http://inotify.aiken.cz/?section=incron&page=doc&lang=en)
I have a namespace in the following format allowing for public and private members: ``` function A() { return('a'); } namespace1 = (function () { // private namespace2 = (function() { // private prC = function () { return(namespace1.puB() + 'c'); }; puC = function () { return(prC()); }; // public return({ puC: puC }); })(); prB = function () { return(A() + 'b'); }; puB = function () { return(prB()); }; // public return({ puB: puB, namespace2: namespace2 }); })(); document.write('A() = '); try { document.write(A()); } catch (ex) { document.write('inaccessible'); } document.write('<BR />'); document.write('namespace1.prB() = '); try { document.write(namespace1.prB()); } catch (ex) { document.write('inaccessible'); } document.write('<BR />'); document.write('namespace1.puB() = '); try { document.write(namespace1.puB()); } catch (ex) { document.write('inaccessible'); } document.write('<BR />'); document.write('namespace1.namespace2.prC() = '); try { document.write(namespace1.namespace2.prC()); } catch (ex) { document.write('inaccessible'); } document.write('<BR />'); document.write('namespace1.namespace2.puC() = '); try { document.write(namespace1.namespace2.puC()); } catch (ex) { document.write('inaccessible'); } ``` Output: ``` A() = a namespace1.prB() = inaccessible namespace1.puB() = ab namespace1.namespace2.prC() = inaccessible namespace1.namespace2.puC() = abc ``` How might I go about appending both public and private members to such a namespace (IE: from different files)? [Here's a JSFiddle](http://jsfiddle.net/CoryG/AagXJ/).
Any variable declared without the **`var`** keyword will be in the **global scope**. So your `puB()` function is NOT inaccessible or private, it is just not a member of the object returned by the `namespace1` function. Try `window.prB()` for example, you'll see that method exists within the global scope of the `window` object. ``` <head> <script type="text/javascript"> obj1 = {}; //in global scope var obj2 = {}; //in global scope. Although used the var keyword, this line itself is in the global scope; so the variable. function someFunc() { obj3 = {}; //in global scope var obj4 = {}; //'so-called' private (inaccessible from global scope) } </script> </head> ``` For combining two different JS files under the same 'namespace' (or let's say object): **File-1**.js ``` var namespace1 = (function() { // some code... var namespace2 = (function() { // some code... return { obj2: 'value2' }; })(); return { obj1: 'value1' }; })(); ``` **File-2**.js ``` namespace1.namespace3 = (function() { // some code... var ns4 = (function() { // some code... return { obj4: 'value4' }; })(); return { obj3: 'value3', namespace4: ns4 }; })(); ``` What is what: * `namespace1` is declared inside the global scope; so it is accessible from anywhere and it is our main object. * `namespace2` is inaccessible (private). * `namespace3` is inaccessible in the global scope but accessible as a member of `namespace1`; e.g.: `namespace1.namespace3`. * `namespace4` is accessible as a member of `namespace1`. e.g.: `namespace1.namespace4`. So; the members of our main object **`namespace1`** is: ``` namespace1 = { obj1: String, namespace3: { obj3: String, namespace4: { obj4: String } } }; ```
You are a long way from Kansas, here. You can't "declare" things as public or private. As long as you define things inside of function, and then choose to return specific things, or append them to an object/array which you passed in as an argument, then you will have "public" (outer) access to those things, after the function returns. In order to have "private" access, you return a function which references something on the inside. ``` var Wallet = function (amount, overdraft_limit) { var balance = 0, overdraft = overdraft_limit || 0, deposit_funds = function (funds) { balance += funds; return true; }, withdraw_funds = function (request) { var funds = 0; balance -= request; funds = request; return funds; }, validate_request = function (pin) { /* ... */ }, sufficient_funds = function (val) { return val <= (balance + overdraft); }, add = function (pin, deposit) { if (!validate_request(pin) || deposit <= 0) { return false; } var result = deposit_funds(deposit); return result; }, deduct = function (pin, withdrawl) { if (!validate_request(pin) || withdrawl <= 0) { return false; } if (!sufficient_funds(withdrawl)) { return false; } var funds = withdraw_funds(withdrawl); return funds; }, check = function () { return balance; }, public_interface = { deduct : deduct, add : add, check : check }; return public_interface; }; var myWallet = Wallet(30, 20); var cash = myWallet.deduct(40); cash; // 40 myWallet.check(); // -10 myWallet.balance = 40000000000; cash = myWallet.deduct(4000); cash; // === false ``` By building functions inside of my "constructor", which have access to `balance`, the variable that I return that "public" object to can call methods to interact with the "private" data, but can't access it or modify it through any method but to use those "public" functions. Nesting this stuff 8-layers deep, using IIFEs uses the exact-same concept of closure which I just demonstrated. Explicitly decide what you're going to return and what you are not. The functions which you send into the world are `public`. The functions/etc inside of the function, which weren't returned or attached to an object are private. They have been closed over, by the "constructor" function which returned, and now they are 100% inaccessible, except by using the functions which were built inside of the constructor, which reference the private vars, and were returned as public methods.
I am building a page that will display a PDF file on the page. When viewing this page in Chrome, the zoom level is set by default so that the document is wider and taller than the allotted space. Safari seems to have a preferable default of fitting the page to the available space, just FYI. I would like to know if there are any parameters that can be set in `<object>` to force the initial zoom level of the document. It might be name=initZoom with values like "fitToPage" or "fitToWidth" or "70" (for 70% zoom). It might look something like this: ``` <object data="/path/to/file.pdf" type="application/pdf"> <param name="initZoom" value="fitToPage" /> </object> ```
Does Adobe's document [**'Parameters for opening PDF files'**](http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf) help you? According to that document, something like ``` <object data="/path/to/file.pdf" type="application/pdf"> <param name="view" value="Fit" /> </object> ``` could work, or even ``` <object data="/path/to/file.pdf#toolbar=1&amp;navpanes=0&amp;scrollbar=1&amp;page=3&amp;view=FitV" type="application/pdf"> <p>It appears you don't have a PDF plugin for this browser. No problem though... You can <a href="/path/to/file.pdf">click here to download the PDF</a>. </p> </object> ```
Another late answer (looks like we're on a 2-year cycle...) I found that setting the parameter `#zoom=Fit` finally did the trick. This is only in FF so far. Chrome is laughing at every parameter I feed it. **Note** that the [documentation](https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf) states that `view` gets the `Fit` values, but `zoom` is the one that seems to do anything with them. I hope this helps someone down the line.
I've been trying to make this shape in CSS, but unfortunately could not find a way how to. It's half pipe like shaped: [![enter image description here](https://i.stack.imgur.com/BZuXP.png)](https://i.stack.imgur.com/BZuXP.png) The pixelated corner should be smooth (it's a zoomed in image). Anyone knows how to create this? Or can get me on the right tracks?
You will need to use pseudo element `:after` for the inner block and then apply `border-radius` for curved corner. ```css div { height: 60px; width: 60px; border: solid red; position: relative; background: red; border-width: 0 10px 10px 0; box-sizing: border-box; } div:after { content: ""; position: absolute; top: 0; left: 0; right: 0; bottom: 0; border-bottom-right-radius: 10px; background: #fff; } ``` ```html <div></div> ```
You can do this with one element and with transparency like this: ```css .box { width:80px; height:100px; border-right:20px solid grey; border-bottom:20px solid grey; box-sizing:border-box; background: radial-gradient(farthest-side at top left,transparent 98%,grey ) bottom right/20px 20px no-repeat; } body { background:pink; } ``` ```html <div class="box"> </div> ```
I've been animating a character and everything's been fine until I tried to move the "Belly" bone's location. At first, I wouldn't get any errors, and when keyframed, the belly wouldn't move. It would just stay in the last position I moved it in. Rotation's fine, and every other bone is fine, but this one's not. Even in the properties, the rotation and scale values were yellow, showing a keyframe, but I couldn't keyframe the location values - they just stayed green. Then I tried fixing it and I think I made it worse, not sure what I did. Now it won't let me keyframe it at all - location OR rotation. [![enter image description here](https://i.stack.imgur.com/zKhGG.png)](https://i.stack.imgur.com/zKhGG.png) I need to be able to animate at least the belly's rotation and location. Here is my .blend file - [![](https://blend-exchange.giantcowfilms.com/embedImage.png?bid=1972)](https://blend-exchange.giantcowfilms.com/b/1972/)
As the error message hints, your animation channels are locked: [![enter image description here](https://i.stack.imgur.com/fQcUi.png)](https://i.stack.imgur.com/fQcUi.png) You need to click the padlock icon next to the bone name in the *Dopesheet Editor* to unlock them all. You probably just clicked it by accident. This solves being able to insert new keyframes, but the bone still doesn't move when animated. This is because the location channels are also *muted*: [![enter image description here](https://i.stack.imgur.com/q9p1A.png)](https://i.stack.imgur.com/q9p1A.png) *Locking* protects the animation channels from being edited (inserting/deleting keyframes) and *muting* temporarily disables them (hides their effects).
Make sure to keyframe the frozen original moment twice, then after a few seconds of frames, make a movement. To keyframe type `i` and select *Loc, Rot, Scale*.
I know that libgdx has this `Button` class that seems so easy to use, but I wonder why the `draw` method is set protected? In that case, how should I draw the button? [Scene2d Button](http://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/scenes/scene2d/ui/Button.html)
I'm writing a libgdx tutorial for beginners. This post might be useful to you: [libgdx Tutorial: scene2d](http://steigert.blogspot.com/2012/02/3-libgdx-tutorial-scene2d.html)
Button is an Actor, so it is used with Stage. There is [official documentation](https://code.google.com/p/libgdx/wiki/scene2d) for scene2d. Button is in scene2d.ui, which is a UI framework on top Stage, which is a general purpose 2D scene graph. There is no official documentation for scene2d.ui yet. You can see [UITest](https://code.google.com/p/libgdx/source/browse/trunk/tests/gdx-tests/src/com/badlogic/gdx/tests/UITest.java) though.
In *A New Hope*, when Darth Vader and Obi Wan engaged in a fight, Obi Wan was killed. At that time, his lightsaber fell there and Luke didn't retrieve it. So, what happened to it? Was it destroyed?
In **movie canon**, the last time we see it is after the dramatic conclusion of the duel between Darth Vader and Obi-Wan Kenobi. As Darth Vader strikes his final blow, Obi-Wan turns into a Force ghost, leaving his clothes and weapon behind. We see the lightsaber last among his robes, as an unbelieving Darth Vader examines it by kicking it with his foot. We don't see it afterwards, unlike Luke's first / Anakin's old lightsaber that seemed lost on Bespin but turns up at Maz Kanata's. We may *speculate* that Darth Vader picked it up, but there's no evidence that it survived the destruction of the Death Star.
I am pretty sure that Vader took it and left it inside some safe or in his quarters.I do not believe he had it with him when he boarded his tie fighter, prior to the Death Star being blown to bits. If the light-saber was not destroyed by the explosion and is still out there, it is floating in space somewhere in the outer rim by now.
When I run website in browser, following server error occured - ``` Server Error in '/FinalHVA' Application. -------------------------------------------------------------------------------- Cannot open database "HVAdb" requested by the login. The login failed. Login failed for user 'COMP1\ASPNET'. ```
Geektool runs all the commands from / so relative path names will not work when trying to run growlnotify. ``` puts Dir.pwd #outputs "/" ``` You will need to pass the absolute paths of the images to growlnotify. The current path can be retrieved with ``` File.dirname(__FILE__) ``` So you would use ``` theAuthorImage = File.dirname(__FILE__) case theAuthor when 'James' : theAuthorImage += '/images/me32.png' when 'Zuzu' : theAuthorImage += '/images/Zuzu32.png' end cmd = "/usr/local/bin/growlnotify '#{theAuthor} says' -m '#{theMessage}' -n 'Laurens Notes' --image '#{theAuthorImage}'" puts cmd system cmd ```
Have you checked if GeekTool spews any output to console.log or system.log? Also, if it never gets past 'File is opened', it might be an issue with gems and requiring Hpricot?
The other day I found this little piece of software - WARI. It stands for Web Application REsource Inspector. Apparently it checks dependencies between css, html, js and images and reports unused and duplicated css styles, javascript functions and images. Link: [WARI is released!](http://blog.konem.net/java//index.php?blog=1) What do you use? Any alternatives?
Conceptually such a tool would be very handy as it is typically a very awkward task to find stray files and safely remove them. I'm not sure if this is the case... but from the wording of this question it looks like this might be a self-promotion question which isn't an endorsed activity. If you wanted to follow up to the generic question "what tools are out there to do x,y, & z" with your own answer that would be fine. For the record, I use 2 tools called CheckWeb and Xenu that will follow all links and report back what was found. This finds me any 404's, and I then compare the list of referenced files against my directory listing to see what files were not used. (Its rough, but works)
As Stat1124 has mentioned Firebug is invaluable. The net panel is great for this purpose as it shows the time required to load all the assets associated with a page - and if a resource is unavailable it also shows the HTTP response code. When trying to optimise a site, yslow (<http://developer.yahoo.com/yslow/>) is a great addition to firebug - as it provides specific implementation tips to achieve a more responsive page load. There's also a great utility called smush.it (<http://developer.yahoo.com/yslow/smushit/>) - which has recently been added to the yslow tool-kit - which produces optimisations to reduce image size.
I am coding a small program in Python3 that calculates the network availability. According to my Data Communications class, you determine your network availability by multiplying the availability of each device in your network. **For example:** There are 3 devices in your network. Device 1 has an availability of .67. Device 2 has an availability of .94. Device 3 has an availability of .79. Then you multiply the availabilities: .67 \* .94 \* .79 = .498 network availability. **Here is my code so far:** ``` # Network Availability # by Nicholas Zachariah numDev = int(input("How many devices do you have? ")) # number of devices print(f"There are {numDev} devices.") devList = list(range(1, numDev+1)) # device list for device in devList: ava = input(f"What is the availability of device number {device}? ") # availability ``` From here, I would like to store each availability input, and then multiply each device's availability and print the overall network's availability, but I am having trouble fulfilling this task as I cannot figure out how to individually store each device's availability. Can anyone help? **PS** In simple terms, I am looking for the network's Total Availability.
From what I can understand (not what everyone else has inferred) you want to find the *total* network availability, in other words the product of all availabilities. In order to individually store the availability you can use one of the many iterable objects in python, the simplest one is a [list](https://docs.python.org/3/tutorial/datastructures.html). A list is a data structure that holds multiple elements (not necessarily of the same type). In order to achieve what you want to accomplish you need the following: ``` # Network Availability # by Nicholas Zachariah numDev = int(input("How many devices do you have? ")) # number of devices print(f"There are {numDev} devices.") devList = list(range(1, numDev+1)) # device list availability_list = list() for device in devList: ava = input(f"What is the availability of device number {device}? ") # availability availability_list.append(ava) curr_avail = availability_list.pop() for avail in availability_list: curr_avail = curr_avail*avail ``` For example, when you enter 0.8, 0.7, and 0.6 ``` availability_list = [0.8, 0.7, 0.6] curr_avail = availability_list.pop() for avail in availability_list: curr_avail = curr_avail*avail curr_avail >>> 0.33599999999999997 ```
Michael King had a great answer, and I marked it as correct. Here is my new code based on his answer. I just kind of organized it a little more and used a round function so the final result doesn't have ten decimal places. ``` netAva = 1 # Network Availability ava = [] # List of each device's availability numDev = int(input("How many devices do you have? ")) # number of devices print(f"There are {numDev} devices.") devList = list(range(1, numDev+1)) # device list for device in devList: ava.append(float(input(f"What is the availability of device number {device}? "))) # availability for device in ava: netAva *= device netAva = round(netAva, 3) print(f"{netAva} is your network's availability.") ```
I have the following problem: I append the div: ``` $(".class").click(function() { $(this).append("<div class='click'></div>"); $("div.click").show(); }); ``` Then i remove it with a click on another button but the div is still there. ``` $(".button").on("click", function(e){ e.preventDefault(); ... $("div.click").hide(); }); ```
you can dynamically add and remove div with javaScript like this Check this example [Add and Remove Div dynamically](http://jsfiddle.net/Faheem66/mCa5X/) in this example the default remove button remove the most recent added div or you can say the last div in the container But if you want to remove particular div with div place number you can enter the div number . Code example HTML ``` <div class="Main"> <div>div1</div> </div> <button id="ok">add</button> <button id="del">remove</button> <label>Enter div number to remove</label> <input id="V"/> <button id="Vok">ok</button> ``` JS ``` var counter=0; $("#ok").click(function(){ $('.Main').append('<div> new div'+counter+'</div>'); counter++; }) $("#del").click(function(){ $('.Main div').remove(':last-child'); }) $("#Vok").click(function(){ var Val=$('#V').val(); $('.Main div:nth-child('+Val+')').remove(); }) ```
remove "on" from ``` $(".button").on("click", function(e){ e.preventDefault(); ... $("div.click").hide(); }); ```
I'm currently working on a project that uses an API to retrieve, update and delete data. The API i'm using is the [prestashop API](http://doc.prestashop.com/display/PS16/Using+the+PrestaShop+Web+Service). So after being able to retrieve data and update some items i stumbled upon an issue. As told in the documentation all data sent and retrieved through the API is with `json` and `xml` Since some data of the API has different levels in the json return like the @attributes and @associations levels i came up with this question. The thing is I would like to access this data and, in combination with [angularjs](https://angularjs.org/) I would like to show this data. So let me show you a quick example of what I'm trying to achieve. First of all the `JSON` return would be something like this. ``` {"products":{"product":[{"id":"1","id_manufacturer":"1","id_supplier":"1","id_category_default":"5","new":{},"cache_default_attribute":"1","id_default_image":"1","id_default_combination":"1","id_tax_rules_group":"1","position_in_category":"0","manufacturer_name":"Fashion Manufacturer","quantity":"0","type":"simple","id_shop_default":"1","reference":"demo_1","supplier_reference":{},"location":{},"width":"0.000000","height":"0.000000","depth":"0.000000","weight":"0.000000","quantity_discount":"0","ean13":"333456789111","isbn":{},"upc":{},"cache_is_pack":"0","cache_has_attachments":"0","is_virtual":"0","state":"1","on_sale":"0","online_only":"0","ecotax":"0.000000","minimal_quantity":"1","price":"16.510000","wholesale_price":"4.950000","unity":{},"unit_price_ratio":"0.000000","additional_shipping_cost":"0.00","customizable":"0","text_fields":"0","uploadable_files":"0","active":"1","redirect_type":"404","id_type_redirected":"0","available_for_order":"1","available_date":"0000-00-00","show_condition":"0","condition":"new","show_price":"1","indexed":"1","visibility":"both","advanced_stock_management":"0","date_add":"2017-03-16 14:36:24","date_upd":"2017-12-01 13:01:13","pack_stock_type":"3","meta_description":{"language":{"@attributes":{"id":"1"}}},"meta_keywords":{"language":{"@attributes":{"id":"1"}}},"meta_title":{"language":{"@attributes":{"id":"1"}}},"link_rewrite":{"language":"gebleekte-T-shirts-met-korte-mouwen"},"name":{"language":"Gebleekte T-shirts met Korte Mouwen"},"description":{"language":" Fashion maakt goed ontworpen collecties sinds 2010. Het merk biedt vrouwelijke combineerbare kleding en statement dresses en heeft een pr\u00eat-\u00e0-porter collectie ontwikkeld met kledingstukken die niet in een garderobe mogen ontbreken. Het resultaat? Cool, gemakkelijk, easy, chique met jeugdige elegantie en een duidelijk herkenbare stijl. Alle prachtige kledingstukken worden met de grootste zorg gemaakt in Itali\u00eb. Fashion breidt zijn aanbod uit met accessoires zoals schoenen, hoeden, riemen!<\/p>"},"description_short":{"language":" Gebleekt T-shirt met korte mouwen en hoge halslijn. Zacht en elastisch materiaal zorgt voor een comfortabele pasvorm. Maak het af met een strooien hoed en u bent klaar voor de zomer!<\/p>"},"available_now":{"language":"Op voorraad"},"available_later":{"language":{"@attributes":{"id":"1"}}},"associations":{"categories":{"@attributes":{"nodeType":"category","api":"categories"},"category":[{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"}]},"images":{"@attributes":{"nodeType":"image","api":"images"},"image":[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"}]},"combinations":{"@attributes":{"nodeType":"combination","api":"combinations"},"combination":[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"},{"id":"6"}]},"product_option_values":{"@attributes":{"nodeType":"product_option_value","api":"product_option_values"},"product_option_value":[{"id":"1"},{"id":"13"},{"id":"14"},{"id":"2"},{"id":"3"}]},"product_features":{"@attributes":{"nodeType":"product_feature","api":"product_features"},"product_feature":[{"id":"5","id_feature_value":"5"},{"id":"6","id_feature_value":"11"},{"id":"7","id_feature_value":"17"}]},"tags":{"@attributes":{"nodeType":"tag","api":"tags"}},"stock_availables":{"@attributes":{"nodeType":"stock_available","api":"stock_availables"},"stock_available":[{"id":"1","id_product_attribute":"0"},{"id":"11","id_product_attribute":"1"},{"id":"12","id_product_attribute":"2"},{"id":"13","id_product_attribute":"3"},{"id":"22","id_product_attribute":"4"},{"id":"23","id_product_attribute":"5"},{"id":"24","id_product_attribute":"6"}]},"accessories":{"@attributes":{"nodeType":"product","api":"products"}},"product_bundle":{"@attributes":{"nodeType":"product","api":"products"}}}}, ``` The structure simplified ``` products { product { id: name: category: ... @attributes { id: language: ... } @attributes { {"nodeType":"product_option_value","api":"product_option_values"},"product_option_value":[ {"id":"1"}, {"id":"11"}, {"id":"8"}, {"id":"2"}, {"id":"3"} ] }, } } } ``` Using the `$http.get()` function in Angularjs I'm able to retrieve the data and use an ng-repeat and bind combination to show the product\_names. Now I would like to access the @attribute values and so on. But how would I be able to access them? Is there a specific way to do this? or is it purely done by accessing the depth level of the JSON object? The AngularJS function for the products: ``` $http.get('config/get/getProducts.php', {cache: true}).then(function (response) { $scope.products = response.data.products.product }); ``` Then in the `<html>` I can simply use: ``` <div ng-if="product.active == 1" class="productimg col-4" ng-repeat="product in products | filter : {id_category_default: catFilter.id}: true | filter:productSearch | filter:product.name | orderBy: 'name'"> <p ng-bind="product.name.language"></p> </div> ``` **UPDATE: 01/02/2018** So after reading and testing some of the comments i've come up with a reasonable solution. I'm able to access the @attributes and associations values but i've stumbled upon a new problem. The return i'm getting for each filter are multiple "id" values. Take a look at the example below. ``` <div class="col-lg-3" ng-repeat="value in products"> <p ng-bind="value.associations.categories.category"></p> </div> ``` Returns: ``` [{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"}] [{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"}] [{"id":"2"},{"id":"3"},{"id":"4"},{"id":"7"}] ``` Where each row of [ .. .. ] stands for a different product. Now i need to get these values as only the numbers that they are so that i can compare them with corresponsding id values from different tables. A good result would be: ``` 2, 3, 4, 5 ``` The question is how would i be able to get to this solution? If anyone is interested in why and how. I'm trying to retrieve the `option_values` id's and `category` id's from the products from a prestashop installation, and all that through the prestashop webservice.
As I understand you would like to use ng-repeat with nested JSON objects. You will need to use more than one repeater because a single repeated item can contain multiple items of its own which you would like to display. So as far as I can see something like this should work: ``` <div ng-if="product.active == 1" class="productimg col-4" ng-repeat="product in products | filter : {id_category_default: catFilter.id}: true | filter:productSearch | filter:product.name | orderBy: 'name'"> <p ng-bind="product.name.language"></p> <table ng-repeat="cat in product.associations.categories"> <tr ng-repeat="attr in cat.@attributes"> <td >{{attr.nodeType}}</td> <td >{{attr.api}}</td> </tr> </table> </div> ``` Have a look here: <https://www.aspsnippets.com/Articles/AngularJS-Using-ng-repeat-with-Complex-Nested-JSON-objects.aspx>
You have clearly two options for solving this problems of yours: 1. Preformatting the response object so that all the keys in JSON are JS accepted identifiers. But that would be futile work in your scenario. 2. Second is using `Object[fieldName]` notation instead of `Object.fieldName`, because a key in the json can also be a number. Mind you an array in JS is indexed object.
I need to convert a lat/long coordinates to a address. I could use the Google Maps API but I would need a XML Response. I have looked at [Convert Lat Long to address Google Maps ApiV2](https://stackoverflow.com/questions/15700845/convert-lat-long-to-address-google-maps-apiv2) but I need to be able to do this in JavaScript. **My Question is: How To Convert a Lat/Long coordinate to an address?**
You can use GeoNames' [FindNearestAddress](http://www.geonames.org/maps/us-reverse-geocoder.html#findNearestAddress). It takes a latitude and longitude parameter and returns the nearest address in XML format. From the example: ``` http://api.geonames.org/findNearestAddress?lat=37.451&lng=-122.18&username=demo ``` ``` <address> <street>Roble Ave</street> <mtfcc>S1400</mtfcc> <streetNumber>649</streetNumber> <lat>37.45127</lat> <lng>-122.18032</lng> <distance>0.04</distance> <postalcode>94025</postalcode> <placename>Menlo Park</placename> <adminCode2>081</adminCode2> <adminName2>San Mateo</adminName2> <adminCode1>CA</adminCode1> <adminName1>California</adminName1> <countryCode>US</countryCode> </address> </geonames> ```
``` var geocoder = new google.maps.Geocoder(); // create a geocoder object var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); // turn coordinates into an object geocoder.geocode({'latLng': location}, function (results, status) { if(status == google.maps.GeocoderStatus.OK) { // if geocode success var add=results[0].formatted_address; // if address found, pass to processing function document.write(add); ``` source from <https://gist.github.com/marchawkins/9406213/download#> it works me
In the Java/C world, people often use enums. If I'm using a Java library which using enums, I can convert between them and keywords, for example, using `(. java.lang.Enum valueOf e..., (aget ^"[Ljava.lang.Enum;" (. e (getEnumConstants)) i)`, and some reflection. But in the Clojure world, do people ever need anything like an enum (a named integer) ? If not, how is their code structured that they don't need them ? If yes, what's the equivalent ? I sense I'm really asking about indices (for looping), which are rarely used in functional programming (I've used map-indexed only once so far).
For almost all the Clojure code I have seen **keywords tend to be used instead of Enums** they are name-spaced and have all the other useful properties of keywords while being much easier to write. They are not an exact standin because they are more dynamic (as in dynamic typing) than Java enums as for indexing and looping I find it more idiomatic to map over a sequence of keywords: ``` (map do-stuff [:a :b :c :d] (range)) ``` than to loop over the values in an enumeration, which I have yet to find an example of in Clojure code, though an example very likely exists ;-)
Yes, use keywords in most places where Java programmers would use enums. In the rare case that you need a number for each of them, you can simply define a map for converting: `{:dog 0, :rabbit 1, ...}`. On the other hand, one of the first Clojure libraries I wrote was just this: a `defenum` macro that assigned numbers to symbols and created conversion systems back and forth. It's a terrible idea implemented reasonably well, so feel free to [have a look](https://github.com/amalloy/enum/blob/master/src/enum/core.clj) but I don't recommend you use it.
I have noticed that I find it far easier to write down mathematical proofs without making any mistakes, than to write down a computer program without bugs. It seems that this is something more widespread than just my experience. Most people make software bugs all the time in their programming, and they have the compiler to tell them what the mistake is all the time. I've never heard of someone who wrote a big computer program with no mistakes in it in one go, and had full confidence that it would be bugless. (In fact, hardly any programs are bugless, even many highly debugged ones). Yet people can write entire papers or books of mathematical proofs without any compiler ever giving them feedback that they made a mistake, and sometimes without even getting feedback from others. Let me be clear. this is not to say that people don't make mistakes in mathematical proofs, but for even mildly experienced mathematicians, the mistakes are usually not that problematic, and can be solved without the help of some "external oracle" like a compiler pointing to your mistake. In fact, if this wasn't the case, then mathematics would scarcely be possible it seems to me. **So this led me to ask the question: What is so different about writing faultless mathematical proofs and writing faultless computer code that makes it so that the former is so much more tractable than the latter?** One could say that it is simply the fact that people have the "external oracle" of a compiler pointing them to their mistakes that makes programmers lazy, preventing them from doing what's necessary to write code rigorously. This view would mean that if they didn't have a compiler, they would be able to be as faultless as mathematicians. You might find this persuasive, but based on my experience programming and writing down mathematical proofs, it seems intuitively to me that this is really not explanation. There seems to be something more fundamentally different about the two endeavours. My initial thought is, that what might be the difference, is that for a mathematician, a correct proof only requires every single logical step to be correct. If every step is correct, the entire proof is correct. On the other hand, for a program to be bugless, not only every line of code has to be correct, but its relation to every other line of code in the program has to work as well. In other words, if step $X$ in a proof is correct, then making a mistake in step $Y$ will not mess up step $X$ ever. But if a line of code $X$ is correctly written down, then making a mistake in line $Y$ will influence the working of line $X$, so that whenever we write line $X$ we have to take into account its relation to all other lines. We can use encapsulation and all those things to kind of limit this, but it cannot be removed completely. This means that the procedure for checking for errors in a mathematical proof is essentially linear in the number of proof-steps, but the procedure for checking for errors in computer code is essentially exponential in the number of lines of code. What do you think? **Note: This question has a large number of answers that explore a large variety of facts and viewpoints. Before you answer, please read *all of them* and answer only if you have something new to add.** Redundant answers, or answers that don't back up opinions with facts, may be deleted.
> > What is so different about writing faultless mathematical proofs and writing faultless computer code that makes it so that the former is so much more tractable than the latter? > > > I believe that the primary reasons are **idempotency** (gives the same results for the same inputs) and **immutability** (doesn't change). *What if a mathematical proof could give different results if it was read on a Tuesday or when the year advanced to 2000 from 1999? What if part of a mathematical proof was to go back a few pages, re-write a few lines, and then start again from that point?* I'm sure that such a proof would be nearly as prone to bugs as a normal segment of computer code. I see other secondary factors as well: 1. Mathematicians are usually far more educated before attempting to write a significant/publishable proof. 1/4 of self-titled professional developers started coding less than 6 years ago (see [SO survey 2017](https://insights.stackoverflow.com/survey/2017#developer-profile-experience-professional-developers)), but I assume most mathematicians have over a decade of formal math education. 2. Mathematical proofs are rarely held to the same level of scrutiny as computer code. A single typo can/will break a program, but dozens of typos may not be sufficient to destroy a proof's value (just its readability). 3. The devil's in the details, and computer code cannot skip details. Proofs are free to skip steps which are deemed simple/routine. There are some nice syntactic sugars available in modern languages, but these are hard-coded and quite limited in comparison. 4. Mathematics is older and has a more solid foundation/core. There certainly is a plethora of new and shiny subfields in math, but most of the core principles have been in use for decades. This leads to stability. On the other side, programmers still disagree on basic coding methodology (just ask about Agile development and its adoption rate).
I think that your reasoning is valid, but your input is not. Mathematical proofs simply aren't more fault-tolerant than programs, if both are written by humans. Dijkstra was already quoted here, but I will offer an additional quote. > > Yet we must organize the computations in such a way that our limited powers are sufficient to guarantee that the computation will establish the desired effect. This organizing includes the composition of the program and there we are faced with the next problem of size, viz. the length of the program text, and we should give this problem also explicit recognition. We should remain aware of the fact that the extent to which we can read or write a text is very much dependent on its size. [...] > > > It is in the same mood that I should like to draw the reader's attention to the fact that "clarity" has pronounced quantitative aspects, a fact many mathematicians, curiously enough, seem to be unaware of. A theorem stating the validity of a conclusion when ten pages full of conditions are satisfied is hardly a convenient tool, as all conditions have to be verified whenever the theorem is appealed to. In Euclidean geometry, Pythagoras' Theorem holds for any three points A, B and C such that through A and C a straight line can be drawn orthogonal to a straight line through B and C. How many mathematicians appreciate that the theorem remains applicable when some or all of the points A, B and C coincide? yet this seems largely responsible for the convenience with which Pythagoras Theorem can be used. > > > Summarizing: as a slow-witted human being I have a very small head and I had better learn to live with it and to respect my limitations and give them full credit, rather than to try to ignore them, for the latter vain effort will be punished by failure. > > > This is slightly edited last three paragraphs from first chapter of Dijkstra's Structured Programming. To perhaps rephrase this, to apply better to your question: correctness is largely a function of size of your proof. Correctness of long mathematical proofs is very difficult to establish (lots of published "proofs" live in the limbo of uncertainty since nobody actually verified them). But, if you compare correctness of trivial programs to trivial proofs, there's likely no noticeable difference. However, automated proof assistants (in a broader sense, your Java compiler is also a proof assistant), let programs win by automating a lot of groundwork.
Having a syntax error that I can not find I think. e.CmsData is showing error along with e.Message. Error states: only assignment, call, decrement, and the new object expressions can be used as a statement. What am I missing? ``` private static void OnMessageReceived (object sender, MessageReceivedEventArgs e) { try { if (e == null) return; if (e.CmsData != null) e.CmsData; if (!String.IsNullOrEmpty(e.Message)) (e.Message); } catch (Exception ex) { } { // logger.Error(" Exception " + ex); // throw ex; } } ```
``` e.CmsData; ``` is not a valid statement, you need to do something with it, like ``` var x = e.CmsData; ``` The same goes for ``` (e.Message); ```
Accessing a property like you did is invalid ``` e.Cmsdata; // Invalid ``` Properties are just like variables but encapsulated.
I'm interested in deriving the solution for $y$ in terms of $x$ given $x^y = y^x$ using the Lambert $W$ function. [Wolfram Alpha states](http://www.wolframalpha.com/input/?i=x%5Ey%20%3D%20y%5Ex): $$y = - \frac{x\ W\left(-\frac{\log(x)}{x}\right)}{\log(x)}$$ So far I have done the following: \begin{align\*} x^y & = y^x\\ y \log(x) & = x \log(y)\\ \log(y)/y & = \log(x)/x\\ \log(y)/y & = \alpha && (\alpha=\log(x)/x) \end{align\*} The rest of it is proving the solution for $y$ in the last equation is $y = - W(-\alpha)/\alpha$. I can easily verify the solution but I'm unsure how to derive it. Thanks in advance.
$$\langle w,w\rangle = 1$$ leads to $$\langle -u-v,-u-v\rangle =1.$$ Expand and simplify and you're done.
\begin{align\*} \langle u+v+w, u+v-w\rangle&=0\\ \|u\|^2+\|v\|^2+2\langle u, v\rangle-\|w\|^2=0\\ 2\langle u, v\rangle+1&=0\\ \langle u, v\rangle&=-\frac{1}{2} \end{align\*}
I have 3 angles a b c a=315 b=20 c=45 ok so would like to know giving all three if b is in between a and c i have the long way of doing this adding and subtracting that's seems to work. I would just like to get something smaller and maybe more efficient. thanks EDIT Here is a picture what i am trying to say. ![enter image description here](https://i.stack.imgur.com/KWV9H.png) Ok I have angle L(currently 0) i add 45(or any angle) and subtract 45(or any angle) to get a and b (my view angle). Now i need to know if the green dot is between a and b (g> a || g > 0) && (g < b) so in this picture only the top green dot will be true.. Sorry if I am not making my self clear my first language is not English
1st off, every angle is between 2 other angles, what you're really asking is: For given angles: *a*, *b*, and *g*, is *g* outside the reflex angle between *a* and *b*? ========================================================================================= You can just go ahead and define *a* as the leftmost angle and *b* as the rightmost angle or you can solve for that, for example if either of these statements are true *a* is your leftmost angle: 1. *a ≤ b ∧ b - a ≤ π* 2. *a > b ∧ a - b ≥ π* For simplicity let's say that your leftmost angle is *l* and your rightmost angle is *r* and you're trying to find if *g* is between them. The problem here is the seem. There are essentially 3 positive cases that we're looking for: 1. *l ≤ g ≤ r* 2. *l ≤ g ∧ r < l* 3. *g ≤ r ∧ r < l* If you're just defining *a* to be leftmost and *b* to be rightmost you're done here and your condition will look like: ``` a <= g && g <= b || a <= g && b < a || g <= b && b < a ``` If however you calculated the *l* and *r* you'll notice there is an optimization opportunity here in doing both processes at once. Your function will look like: ``` if(a <= b) { if(b - a <= PI) { return a <= g && g <= b; } else { return b <= g || g <= a; } } else { if(a - b <= PI) { return b <= g && g <= a; } else { return a <= g || g <= b; } } ``` Or if you need it you could expand into this nightmare condition: ``` a <= b ? (b - a <= PI && a <= g && g <= b) || (b - a > PI && (b <= g || g <= a)) : (a - b <= PI && b <= g && g <= a) || (a - b > PI && (a <= g || g <= b)) ``` Note that all this math presumes that your input is in radians and in the range [0 : 2π]. [`Live Example`](http://ideone.com/iwbMqZ)
There is an issue with the suggested solutions when handling negative angles (e.g. from=30 to=-29) **The suggested (kotlin) fix should be:** ``` fun isBetween(from:Float,to:Float,check:Float,inclusive:Boolean = true):Boolean{ var a1 = to - from a1 = (a1 + 180f).mod(360f) - 180f if(a1<0f) a1+=360f var a2 = check - from a2 = (a2 + 180f).mod(360f) - 180f if(a2<0f) a2+=360f val between = if(inclusive) a2<=a1 else a2<a1 && a2>0f println("$from->$to, $check, $between ($a1,$a2)") return between } ```
I have an autocomplete textview with the following layout for the items (Textview) ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="@dimen/activity_horizontal_margin" android:gravity="center_vertical" android:orientation="vertical"> <TextView android:id="@+id/suggestion" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center_vertical" android:minHeight="?android:attr/listPreferredItemHeightSmall" android:paddingEnd="?android:attr/listPreferredItemPaddingEnd" android:paddingLeft="?android:attr/listPreferredItemPaddingLeft" android:paddingRight="?android:attr/listPreferredItemPaddingRight" android:paddingStart="?android:attr/listPreferredItemPaddingStart" android:textAppearance="?android:attr/textAppearanceListItemSmall" android:textColor="@color/black"/> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="?android:attr/listDivider"/> </LinearLayout> ``` When the dropdown list shows, the background is grey and when I click and hold on an item there is ripple effect showing. To have the ripple effect as default is great, but how can I set the background to white while keeping the ripple effect?
console.log( data ); instead of console.log(value.id);
I finally got it working. I had to then simply get the value inside the object. This is how I got it to work: $.get("/"+vendor\_id+"/events/"+event\_id +"/"+caldate, function( data ) { ``` console.log(data); window.location.href="/"+vendor_id+"/events/"+event_id +"/"+data.spotid.id; }); ```
I've got the following formula, but it does not work as when I add the *California* around the name it just fails so it just tells me that everything is UK. How can I fix this? ``` =IF(OR(N10776="*California*",N10776="*San Francisco*",N10776="*New York*"),"USA","UK") ```
1. Ensure your VSCode uses the arm64 version. (it can use a different go version from the system) 2. Run Go: install/update tools. It will rebuild all tools with the arm64 go version.
Writing this so that anyone facing same problem while migrating to M1 mac can get all the required information at one place. I faced this issue after migrating data from my intel mac to M1(using Apple Migration Assistant). So basically, the go binaries and vscode for amd64 were copied to M1 mac(arm64) Hence, i had to uninstall (removed all go related files i.e located at `/home/<my_user>/go` and go executables located at `/usr/local/go`) and reinstall go and vscode for arm64. Post that, i was getting the error `could not launch process: EOF` while running the debugger in vscode using delve, to solve that i referred to this github thread - <https://github.com/go-delve/delve/issues/2794> and performed below steps: ``` sudo rm -rf /Library/Developer/CommandLineTools xcode-select --install ``` After that, i was able to use delve to debug code in vscode
``` mysql> Select Emp_B AS Total -> From (Select Sum(mines.NoOfWorkers) AS Emp_B from mines); ERROR 1248 (42000): Every derived table must have its own alias mysql> Select Emp_B AS Total -> From (Select Sum(mines.NoOfWorkers) from mines) AS Emp_B; ERROR 1054 (42S22): Unknown column 'Emp_B' in 'field list' ``` I am having some problem with this SQL statement. Any assistance will be mose appreciated
``` Select Emp_B AS Total From (Select Sum(mines.NoOfWorkers) AS Emp_B from mines) x; ``` As the error states *`Every derived table must have its own alias`* Just give it an alias, like `x` above. OR `AS x`, but the `AS` word is optional. Or why alias it twice... ``` Select Total From (Select Sum(mines.NoOfWorkers) AS Total from mines) x; ``` But since SUM gives you exactly one value, unless you have simplified the query from some larger one, this gives exactly the same result?? ``` Select Sum(mines.NoOfWorkers) AS Total from mines; ```
``` Select temp.total From ( Select Sum(mines.NoOfWorkers) AS total from mines ) AS temp ; ```
I'm reading some papers in CF and noticed that most state-of-the-art methods are based on different factorization methods on the rating matrix only. I'd like to know if there are some representative works on combining content information (e.g. user features and item features) into factorization. Any ideas?
I am a researcher in the field of recommender systems, and did some work on exactly that. Here are some papers on that topic: 1. Aditya Krishna Menon, Charles Elkan: A log-linear model with latent features for dyadic prediction, ICDM 2010 2. David Stern, Ralf Herbrich, and Thore Graepel: Matchbox: Large Scale Bayesian Recommendations, WWW 2009 3. Chong Wang, David Blei: Collaborative topic modeling for recommending scientific articles, KDD 2011 4. Zeno Gantner, Lucas Drumond, Christoph Freudenthaler, Steffen Rendle, Lars Schmidt-Thieme: Learning Attribute-to-Feature Mappings for Cold-Start Recommendations, ICDM 2010 5. D. Agarwal and B.-C. Chen. Regression-based latent factor models, KDD 2009 6. D. Agarwal and B.-C. Chen. fLDA: Matrix factorization through latent dirichlet allocation, WSDM 2010 Please note that (4) is a paper by me, so this is also some kind of advertisement ;-) Also, the KDD Cup 2011 involved an item taxonomy, and there has been some interesting work on combining such taxonomy information with latent factor models at the workshop: <http://kddcup.yahoo.com/workshop.php>
See for example "*5. Hybrid Collaborative Filtering Techniques*" in > > X. Su, T. M. Khoshgoftaar, A Survey of Collaborative Filtering Techniques, > Advances in Artificial Intelligence (2009). [PDF](http://downloads.hindawi.com/journals/aai/2009/421425.pdf) > > >
I know that the Brew Potion feat can be used to make these items, but can I also use skills? The [Paizo site](http://paizo.com/prd/magicItems/magicItemCreation.html) states that potions can be crafted with the Brew Potion feat, Spellcraft skill, and Craft (alchemy) skill. Does this mean I can just have Craft (alchemy) and not take the feat Brew Potion and still be able to make potions and oils? Or do I still need the feat?
<http://paizo.com/prd/magicItems/magicItemCreation.html> > > create magic items, spellcasters use special feats which allow them to > invest time and money in an item's creation. **At the end of this > process, the spellcaster must make a single skill check (usually > Spellcraft, but sometimes another skill) to finish the item**. If an > item type has multiple possible skills, you choose which skill to make > the check with. The DC to create a magic item is 5 + the caster level > for the item. Failing this check means that the item does not function > and the materials and time are wasted. Failing this check by 5 or more > results in a cursed item (see Cursed Items for more information). > > > Note that all items have prerequisites in their descriptions. These > prerequisites must be met for the item to be created. Most of the > time, they take the form of spells that must be known by the item's > creator (although access through another magic item or spellcaster is > allowed). The DC to create a magic item increases by +5 for each > prerequisite the caster does not meet. **The only exception to this is > the requisite item creation feat, which is mandatory.** In addition, > you cannot create potions, spell-trigger, or spell-completion magic > items without meeting their spell prerequisites. > > > You can use *spellcraft* or *craft(alchemy)* for the final check to create the potion/oil, but the *brew potion* feat is still required.
The link you cite doesn't quite say that. What the [Creating Potions section](http://paizo.com/prd/magicItems/magicItemCreation.html#creating-potions) says is that *Brew Potion* is **required**, plus either *Spellcraft* or *Craft (alchemy)*. So yes, you still need the feat.
In the last battle of DoFP, future Magneto and Storm create a massive explosion (by electrically charging and blowing up the future Blackbird) and destroy a vast amount of Sentinel ships. This results in a massive amount of shrapnel and debris headed straight towards the mutants which Magneto is able to stop using his powers. However, Trask mentioned that the sentinels were made out of a special polymer, "no metal". Why would these Sentinels then build their ships out of metal? Why not the same polymer?
### Short answer: The adaptability power used by the Sentinels is being driven by a computerized interface with their exoskeleton. The mechanics of how the polymer and its ability to mimic Mystique's power are not explained, but it make sense there would be a need to use a computer to control the mimetic properties of the polymer. * It means the special polymer needs an interface acting to control the mechanized version of Mystique's power. The Sentinels are already using a sophisticated AI to control their powers. * Giving this power to an aircraft is an unnecessary expense when all the plane is doing is delivering the Sentinels to the field of battle faster than the Sentinels can fly there on their own. ### Longer Answer: 1. Sentinels can fly under their own power. But they fly slowly in comparison to a decent aircraft. Putting them in aircraft increases their mobility. 2. Ordinary airplanes are used to get them to the battle and then the Sentinels fly the rest of the way to their targets and fight once they arrive. 3. Their airplanes being made of metal won't mean much to them even if a mutant can weaponize the material against them because the Sentinels are very tough. 4. The Sentinel are also depending on their numbers and their engineered mutability to overcome the mutants in the end. Given the desperate plight of the mutants when the movie begins, Trask's methods were simple and efficient.
I don't think this is ever said onscreen, but my understanding was that it was a function of the later Sentinels' adaptability. In Trask's day they needed to be non-magnetic so mutants like Magneto couldn't easily destroy them, but in the future they could simply adapt to become a different material (or create opposing magnetic fields, or counter Magneto's power in a dozen other ways), so their base construction parameters became less important. They were then built with whatever material was best, in this case something that happened to be magnetic, safe in the knowledge that on the battlefield it wouldn't be an issue.
So, we all know that CS50 is a big class and lots to learn. Here's another issue I'm having with Python now. The syntax took a little while to get right with all the indentation changes but the logic seems to be very similar. The code works up until you put in .99 or even 1.20. BUT, and it's a big but, I can't debug in the cloud9 ide with Python.....? Idk. I just started Python this week so I'm sure it's a language oriented issue and I just need to figure that out. Hope you can help me. Thanks. ``` #Greedy algorithm converted to python import sys import os c = float(input("How much change is owed? ")) i = 0 while (c<0 or c==0): print("Please input a positive amount...") while (c>.24): i += 1 c=(c-.25) while (c>.1 or c==.1): i += 1 c=(c-.1) while (c>.05 or c==.05): i += 1 c=(c-.05) while (c>.01 or c==.01): i += 1 c=(c-.01) print("%i coin(s) needed to make the change." % i) ```
What you are asking for is not possible right now with React, you want to use what is known as web components. <https://webdesign.tutsplus.com/articles/how-to-create-your-own-html-elements-with-web-components--cms-21524> Read this to learn how to. The other method is obviously ``` ReactDOM.render(<MyComponent />, document.getElementById('id')); ``` If you have to stick with React.
There are couple of options which can be explored here 1. parcel bundle <https://javascriptpros.com/creating-react-widgets-embedded-anywhere/> 2. direflow bundle <https://jhinter.medium.com/using-react-based-web-components-in-wordpress-f0d4097aca38>
I have a text file1 and I wish to extract lines (which don't exist in file2)in a new file3 example : file1: ``` /** * Gets the total volume. * * @return the total volume */ public int getTotalVolume() {return totalVolume;} ``` file2: ``` * Gets the total volume. * * @return the total volume ``` file3: ``` /** */ public int getTotalVolume() {return totalVolume;} ``` my function: ``` public void Traitv2(string file1, string file2, string file3) { StreamReader monStreamReaderfile1 = new StreamReader(file1); StreamWriter monStreamWriterfile3 = new StreamWriter(file3); string ligne = monStreamReaderfile1.ReadLine(); while (ligne != null) { StreamReader monStreamReaderfile2 = new StreamReader(file2); string ligne1 = monStreamReaderfile2.ReadLine(); while (ligne1 != null) { if (!ligne.Equals(ligne1)) { Console.WriteLine(ligne); monStreamWriterfile3.WriteLine(ligne); } ligne1 = monStreamReaderfile2.ReadLine(); ligne = monStreamReaderfile1.ReadLine(); } ligne = monStreamReaderfile1.ReadLine(); monStreamReaderfile2.Close(); } monStreamWriterfile3.Close(); monStreamReaderfile1.Close(); } ``` When I run this function, the result is false and an error occurs: error Object reference not set to an instance of an object
Simple solution using Linq: ``` var file1 = File.ReadAllLines("file1name"); var file2 = File.ReadAllLines("file2name"); var file3 = file1.Except(file2); File.WriteAllLines("fileName3", file3); ```
you should check for null at the `strings` you get to the function and more impotently `StreamReader` and the line you read you are getting null because of the line: ``` ligne = monStreamReaderfile1.ReadLine(); ``` inside the while loop. the file got to the end and you try to read. check null before your line ``` if (!ligne.Equals(ligne1)) ``` here is the full answer code ``` public void Traitv2(string file1, string file2, string file3) { StreamReader monStreamReaderfile1 = new StreamReader(file1); StreamWriter monStreamWriterfile3 = new StreamWriter(file3); string ligne = monStreamReaderfile1.ReadLine(); while (ligne != null) { StreamReader monStreamReaderfile2 = new StreamReader(file2); string ligne1 = monStreamReaderfile2.ReadLine(); while (ligne1 != null) { if (ligne != null && !ligne.Equals(ligne1)) { Console.WriteLine(ligne); monStreamWriterfile3.WriteLine(ligne); } ligne1 = monStreamReaderfile2.ReadLine(); ligne = monStreamReaderfile1.ReadLine(); } ligne = monStreamReaderfile1.ReadLine(); monStreamReaderfile2.Close(); } monStreamWriterfile3.Close(); monStreamReaderfile1.Close(); } ```
I am trying to set up a connection and transfer files using putty on a windows 10 platform. I have verified that the default port in putty is 22. When I run the command in the command line to connect and transfer files though I get the above error. Any idea why this is or what I should do?
I had the same error and ended up at this page. The `-P 22` did not solve my problem. I use Putty saved sessions and double checked my command line and had the same error as the OP. I was using: `pscp -l SESSION_NAME_IN_PUTTY ip:/remote_path local_path` I reviewed the [command line options](https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter5.html#pscp-usage) for pscp and changed the `-l` to `-load` and it worked. The final command looked like: `pscp -load SESSION_NAME_IN_PUTTY ip:/remote_path local_path` **Note**: If you still have the error, please review your spelling of `SESSION_NAME_IN_PUTTY` and ensure it is an exact match. One letter off, can cause the same error.
In my case I had created a shortened "session name" in Putty -- that is, a shorter representation of the full hostname. This worked for most Putty functions -- but when I tried to use pscp I found that I needed to have a session name that was identical to the hostname.
In the sense of why the Barber in the [Barber Paradox](http://en.wikipedia.org/wiki/Barber_paradox) doesn't go mad or enter an infinite decision loop. What makes our minds paradox proof? Can an artificial intelligence be made paradox proof? I know that the exact functioning of mind is not known yet, but I'd appreciate any insight scratching the surface.
The human brain does not go through every logical option when making a decision. Doing so takes too long and results in sub-optimal decisions. Neuroeconomics suggests that (1) our decision making process follows a diffusion approach, where data accumulates until one option passes a threshold, and that option is taken. It also suggests that we rely on emotions as a heuristic. Because if that, we might make what appear to be paradoxical decisions, but because we don't parse through every option until we find the right one, our brain doesn't fall into the infinite loop issue. That being said, it is possible that the universe itself is not logically consistent. While inconsistent mathematics may seem like a purely academic line of thinking, it is possible that the universe itself has actual paradoxical conditions. Take relativity and quantum mechanics. They are incompatible, and we are trying to find a grand unification theory. But maybe there isn't one. Maybe the universe obeys both, and we just live in a logically inconsistent universe where both of these theories, or something very close to them, are indeed true.
The barber paradox is easily resolved: Assuming the initial claim (the statement about the barber) to be true leads to a contradiction, therefore the statement is not true (that is, it is not true that the barber shaves all those and only those who are not shaving themselves). Of course that's not the only way to resolve the paradox; another resolution would be to declare that there's no barber (that's essentially how ZFC resolves Russell's paradox), therefore any statement about the barber is vacuous. Indeed, quite a few paradoxes can be resolved by simply assuming some information given when telling the paradox is false. There are a few paradoxes which cannot be resolved that way (like the "distilled" version of the liar paradox, "this sentence is wrong"). Such paradoxes are "resolved" by understanding that there are no resolutions, and then simply ignoring them, as they are not relevant for our decisions anyway (remember, our rational thinking ability did not evolve to think about logic puzzles, but to make decisions in the real world which help us to survive).
I have a function that does something like this: ``` function my_function() { if ($('#footer').outerHeight() > 100) { $('#footer').height(...) ; $('#footer').css(....) ; } ``` That function is called everytime I scroll, so I wonder if it's that bad to do this $('#footer') so many times. If so, what would be a good way to solve this?
You should chain your functions and cache your selector like so: ``` function my_function() { var footer = $('#footer'); if (footer.outerHeight() > 100) { footer.height(...).css(....); } } ``` You could even move the `var footer = $('#footer');` outside of the function making it global to further improve it.
The other answers are good, but if you don't want your if statement evaluated at all (past the first time), try the following: ``` var $footer; var footerEvaled = false; function my_function() { if(footerEvaled == false) { $footer = $footer || $('#footer'); if ( $footer.outerHeight() > 100) { $footer.height(...) ; $footer.css(....) ; footerEvaled = true; } } } ```
i have a simple uitableview with tableHeaderView. i have more than one section. i set the headerview's height 30. but i want to use 40 pixel height uiview in my header (from 0,0 to 320,30 not transparent. from 30,10 to 320,40 is transparent). i put a picture in it. there is a small icon on point(0x30). its height=10. i just want to show my headerview just a little bit over on the first tablecell. you will see below that i set header's height to 30, but i create 40 pixel height view in viewForHeaderInSection. ``` - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 30; } - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)]; sectionView.backgroundColor = [UIColor redColor]; [sectionView autorelease]; return sectionView; } ``` is it possible?
The feature you're looking for is called a "placeholder". (if nothing else, just knowing this term will help you search for more info in Google) In modern browsers which support HTML5, this is a built-in feature which you can use very easily, as follows: ``` <input type='text' name='username' size='15' placeholder='User name' /> ``` However, this method only works with up-to-date browsers which support this feature. Older browsers will need to have some Javascript code to do it. Fortunately, there are a number of scripts you can use, including some written as JQuery plug-ins. The ones I'd recommend are those which tie into the `placeholder` attribute on the input field, so that you can support it natively in the browsers which have this feature and fall-back to Javascript for those that don't. Try this one: <http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html>
I wrote a custom one because I wanted to have a specific behaviour. <https://90dayjobmatch.com/js/jquery.wf.formvaluelabel.js> Usage: ``` $('#signup_job_title').formvaluelabel({text:'eg. Graphic Artist'}); ``` Let me know if you have any questions about it. HTH
Just wondering if Drush is capable of deleting nodes of a given content type. Something like: `$ drush delete-node --type=MyContentType` If not possible, can I create a **method** like that?
VBO has Drush integration. Create a VBO view of nodes, execute it via Drush (using `drush vbo-execute`), pass the node type as an argument.
Updating the answer provided by @kenorb. In Drupal 8 ``` drush eval '$nids = \Drupal::entityQuery('node')->execute(); $storage = Drupal::entityTypeManager()->getStorage('node'); $e = $storage->loadMultiple($nids); $storage->delete($e);' ```
I have this code: ``` __asm jno no_oflow overflow = 1; __asm no_oflow: ``` It produces this nice warning: > > error C4235: nonstandard extension used : '\_\_asm' keyword not supported on this architecture > > > What would be an equivalent/acceptable replacement for this code to check the overflow of a subtraction operation that happened before it?
First define the following: ``` #ifdef _M_IX86 typedef unsigned int READETYPE; #else typedef unsigned __int64 READETYPE; #endif extern "C" { READETYPE __readeflags(); } #pragma intrinsic(__readeflags) ``` You can then check the eflags register as follows: ``` if ( (__readeflags() & 0x800)) { overflow = 1; } ```
I assume that the code above is trying to catch some sort of integer overflow/underflow? Maybe the answers to this question will help: [How to detect integer overflow?](https://stackoverflow.com/questions/199333/best-way-to-detect-integer-overflow-in-c-c)
As a programmer I have an inherent nagging annoyance at my tools, other peoples code, my code, the world in general. I always want to improve it. So I refactor, I stay on top of the latest techniques. I try and learn patterns, I try to use frameworks so as not to reinvent the wheel. I can write a tech spec that will blow your socks off with the amount of patterns I can squeeze in. However, lately I feel I actually know more about the tools I use than how to actually implement successful software. I feel like I'm lacking in the human factors skill set and I believe that to be a successful software engineer takes more than knowing the coolest framework. I think it needs some of the following skillsets too. * Interaction design * User experience * Marketing I've got a bit of this that I've learned from people I've worked with and great projects I've worked on but I don't feel like I "own" these skills. Am I right? Should I be trying to develop these skills further, or should these be left to the people who do these for a career? How do you make sure you don't get too tied up in how you're doing something and make sure you "make your users awesome"? Does anyone know of good resources for learning these skills from a programming point of view?
**For every line of code you write you introduce the chance of a bug.** So, the best designs minimise the amount of introduced code - perhaps through the DRY (Don't Repeat Yourself) principle. However, startups favour the **YAGNI** (You Ain't Gonna Need It) approach which leads to the MVP (Minimum Viable Product) much quicker. If your objective is to create a clean, easy to use product that does exactly what your users want, then YAGNI is your ultimate design pattern. Throw everything out that does not directly contribute to working code. That includes purist build processes and obsessive use of patterns. **Some reading material** You may want to read "[Don't make me think](http://rads.stackoverflow.com/amzn/click/0321344758)" which is an excellent book on user interface design. Also, any of the Gitomer series of books (particularly [The Little Green Book](http://rads.stackoverflow.com/amzn/click/0131576070)) will help you with your sales, networking and marketing skills.
While you may never be responsible for every aspect of your company's software, having a wide range of knowledge across a lot of subjects can be extremely valuable. If nothing else, it's more stuff you can drop in an interview, so you can keep your career moving forward. If you're not getting challenged enough in some areas on your job, start your own project at home to do something that you find interesting. Or get involved with an open source project.
I have a class like this: ``` public class Item { [XmlAttribute("Name")] public string Name { get; set; } [XmlAttribute("Id")] public int Id { get; set; } [XmlAttribute("Entry")] public int Entry { get { return this.Id; } set { this.Id = value; } } } ``` And I don't want to serialize the `Entry` attribute but still want to be able to deserialize it from files that have said attribute. If I either set `XmlIgnore` it will not read during deserialization and if I don't it will write both `Entry` and `Id` to my serialized file which I don't want. **I know I could generate a secondary class with excludes Entry altogether and use that specific one for serializing, but I grew curious if there is a way to make so it will not serialize the Id or it will deserialize the `Entry` into the `Id` attribute instead?** *I am open to other suggestions as well...* EDIT: Also tried using `XmlIgnoreAttribute` as explained here: <http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore%28v=vs.110%29.aspx> With true on my serialization and false on my deserialization, but didn't work. --- Just to further clarify the issue, how the XML's are formatted is not something I control and what I am doing is merely a 3rd party application that will read those files and save them back. To me the `Entry` attribute is redundant and unneeded hence why I save it to the Id as they are the same, however there are many elements with no `Id` and instead they have the `Entry`, once my application is used to read and re-save the file it removes the `Entry` and saves it as `Id` instead. Also to serialize and deserialize it I have to inject the root element name: ``` XmlSerializer serializer = new XmlSerializer(typeof(T), new XmlRootAttribute(root)); using (XmlReader reader = XmlReader.Create(file)) { return (T)serializer.Deserialize(reader); } ``` Because the root name will differ from file to file I have to inject it.
You've misplaced your `valueUpdate` parameter. It's inside the `css` parameter - you need to move it outside the `}`: ``` <input id="firstName" type="text" placeholder="First name" data-bind="value: Registration.FirstName, css: { CircleErrors: Registration.FirstName().length == 0 && Registration.FirstNameValidation() }, valueUpdate: 'afterkeydown'"> ``` [Here's a demo with it working](http://jsfiddle.net/rqk4kckc/1/)
[Demo](http://jsfiddle.net/rqk4kckc/4/) this is what you looking for ` var reg = new (function() { var self = this; this.FirstName = ko.observable(''); this.checkifEmpty = ko.observable(false); ``` this.check=function(){ if(this.FirstName()!=null&&this.FirstName()!=undefined && this.FirstName() !=''){ this.checkifEmpty(true); }else{ this.checkifEmpty(false); } } this.FirstNameValidation = function() { return true; } ``` })(); ko.applyBindings(reg); `
An article claiming to solve a great long-standing mathematical open problem was published in a conference proceedings, and was refereed on MathSciNet positively, i.e. the reviewer makes an impression that the proof is valid. However, some details hint that this may not be the case: 1. the result of this caliber should go to a top-tier journal and get a significant resonance in the mathematical community; 2. the preprint has been available on [arXiv](https://en.wikipedia.org/wiki/ArXiv) for 15 years before its final publication and underwent eight redactions (with the last redaction about eight years before the publication); 3. I talked to an expert in this area around 10 years ago and their opinion about one of the earlier drafts of the preprint was that it is erroneous and the author doesn't want to admit his mistakes. Now some other articles (published in first-tier journals) use this questionable result. And many other people are still working on solving this long-standing problem, and may have doubts about the status of the problem, in view of this publication. So my question is: how much of the responsibility lies on the MathSciNet reviewer who "validated" the proof? My understanding is that it is their duty to reveal the mistakes in the published article, so that the other authors do not base their work on it. Is there a way to "nudge" the reviewer to make amends to the review?
> > how much of the responsibility lies on the MathSciNet reviewer who "validated" the proof? > > > None. The [instructions for reviewers](https://mathscinet.ams.org/mresubs/guide-reviewers.html) don't ask the reviewer to check the validity of the proofs; by a time a paper gets to MathSciNet it has been peer reviewed already. The purpose of a MathSciNet review is to explain what's in the paper and why someone might want to read it. It is fine to write to [contact AMS](http://www.ams.org/about-us/contact/reach) and ask them to retract a review, if (1) you are a well-known expert in the field, capable of speaking (to a reasonable extent) for the field as a whole; or (2) you are able to conclusively demonstrate that the paper has an error. If neither of these is the case, while your desire to do something is admirable, realistically there is probably not any effective action available to you.
You state, without qualification, that the paper is erroneous. Actually, that may be true or not. And even if it contains errors, it is also possible that they are immaterial to the main result. You blame it on the reviewer. But the reviewer may simply be mistaken in their analysis - especially if the result is deep and subtle. People make mistakes. Authors do. Reviewers also. It isn't evil intent. And it certainly isn't the job of a review writer, after publication, to make a claim without evidence that a paper is flawed. It is the responsibility of the reviewer to try to give a valid report on the paper as best they can analyze it. If they are wrong, they have made a mistake, but I doubt that any reviewer would "cover up" for an author, stating that something was true, when they knew it was not. But it is also the responsibility of the reviewer to include in any report that they can't follow the argument to its end, if that is the case. But that is about all that they can do and all you can ask for. But, the proper response to an erroneous paper is to publish a correct one. That can be done by anyone. If you are sure the paper has errors, publish your own analysis. But in the end, mathematics can be just *hard*. I'll note that some papers have errors that haven't been noticed after fifty years or more. No one really doubts the result, though a thorough analysis might prove them wrong. Automated theorem provers/checkers can catch some of that, but not all. But the human mind has limitations in how much detail it can manage and some proofs go beyond the natural limits.
Consider,We are Creating a Two-body system in free space,Where no other mass exists,Let's Take First Mass M1 and hold it,Now bring Second Mass M2,hold it up,Now we are giving a suddenly impulse To M1 causing its initial Velocity to be V1 and then releasing M2,now here,How do we derive that These bodies will perform Circular motion About (Barycentre/Centre of masses),What will happen between The the time When Impulse is given and time When They become steady rotating about Centre Of mass(in COM frame). The Gravitational force is only considered here,So my Question is Centrepetal Force Acts on both which varies inversely to $r^2$,So How are they set into circular motion?
Kinematic equations, one of which is $v=u+at$, are derived making the assumption that the acceleration $a$ is a constant. Why this is so can be seen by inspecting a graph of velocity against time for constant acceleration (gradient of the straight line). [![enter image description here](https://i.stack.imgur.com/kA20X.jpg)](https://i.stack.imgur.com/kA20X.jpg) Gradient, $a= \frac {v-u}{t} \Rightarrow v = u+at$ If the acceleration varied the gradient of the graph would not be constant and then this derivation would be invalid. The area under a velocity time graph is equal to the displacement $s = \left (\frac{v+u}{2}\right ) t$ (area of a trapezium) and from these two equation one can generate the other two constant acceleration kinematic equations. Because the gradient is constant it is not necessary in this case to use the calculus notation , $a = \frac {dv}{dt}$ and $s = \int ^t\_0 v \,dt$ which you would need to use if the acceleration depended on time.
It's pretty simple. The formal definition of velocity is the derivative of position with respect to time. So in one dimension: $v = \frac{dx}{dt}$ And therefore $x(t) = \int\_{0}^{t}v(t')dt'$ If you assume $v(t)$ is constant, then that equation becomes $x = vt$ (hence the kinematic equation). If $v(t)$ isn't constant, then $x=vt$ is almost certainly not correct. **Edit**: As @hft pointed out, the more central assumption to kinematics is that $a(t)$ is constant, so that: $v(t) = \int\_{0}^{t}a(t')dt' = at$ Now if we substitute $at$ in for $v(t)$, we get: $x(t) = \int\_{0}^{t}v(t')dt' = \int\_{0}^{t}at' + v\_0dt' = \frac{1}{2}at^2 + v\_0t$ Which should look like the form we know and love.
In SQL server 2008: Suppose I have two tables. Table1 has 3 fields: Name, Date1 and Date2. Currently, all the Date2 entries are NULL. (Name, Date1) form a unique key. Table2 has 2 fields: Name and Date2. (Name, Date2) form a unique key. Every "Name" in Table1 has at least one corresponding entry in Table2. Now, I want to update all the Date2 entries in Table1 (remember they are all NULL right now) to the Date2 entry in Table2 that is the **closest** to Date1 in Table1. I.e. the date that would give the result of: > > > ``` > min(datediff(dd,Table1.Date1,Table2.Date2)) > > ``` > > So to be clear, if I have the following entries: **Table1:** *[Name]: Karl, [Date1]: 1/1/2009, [Date2]: NULL* **Table2:** *[Name]: Karl, [Date2]: 1/1/2000* *[Name]: Karl, [Date2]: 1/7/2009* *[Name]: Karl, [Date2]: 1/1/2010* Then I want to update Table1.Date2 to '1/7/2009' since that is the closest date to '1/1/2009'. Thanks a lot Karl
AS is matrix. This will return the largest elements of AS in its 2nd dimension (i.e. its columns)
This function is taking AS and producing the maximum value along the second dimension of AS. It returns the max value 'Y' and the index of it 'I'.
I am writing a dirty little extension method for HtmlHelper so that I can say something like HtmlHelper.WysiwygFor(lambda) and display the CKEditor. I have this working currently but it seems a bit more cumbersome than I would prefer. I am hoping that there is a more straight forward way of doing this. Here is what I have so far. ``` public static MvcHtmlString WysiwygFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { return MvcHtmlString.Create(string.Concat("<textarea class=\"ckeditor\" cols=\"80\" id=\"", expression.MemberName(), "\" name=\"editor1\" rows=\"10\">", GetValue(helper, expression), "</textarea>")); } private static string GetValue<TModel, TProperty>(HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { MemberExpression body = (MemberExpression)expression.Body; string propertyName = body.Member.Name; TModel model = helper.ViewData.Model; string value = typeof(TModel).GetProperty(propertyName).GetValue(model, null).ToString(); return value; } private static string MemberName<T, V>(this Expression<Func<T, V>> expression) { var memberExpression = expression.Body as MemberExpression; if (memberExpression == null) throw new InvalidOperationException("Expression must be a member expression"); return memberExpression.Member.Name; } ``` Thanks!
Try like this: ``` public static MvcHtmlString Try<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression ) { var builder = new TagBuilder("textarea"); builder.AddCssClass("ckeditor"); builder.MergeAttribute("cols", "80"); builder.MergeAttribute("name", "editor1"); builder.MergeAttribute("id", expression.Name); // not sure about the id - verify var value = ModelMetadata.FromLambdaExpression( expression, htmlHelper.ViewData ).Model; builder.SetInnerText(value.ToString()); return MvcHtmlString.Create(builder.ToString()); } ```
[ASP.NET MVC 3 Futures](http://weblogs.asp.net/imranbaloch/archive/2011/07/26/using-the-features-of-asp-net-mvc-3-futures.aspx) includes a helper for that.
I'm looking for a method that will allow the content of the emails sent by a given EmailOperator task to be set dynamically. Ideally I would like to make the email contents dependent on the results of an xcom call, preferably through the html\_content argument. ``` alert = EmailOperator( task_id=alertTaskID, to='please@dontreply.com', subject='Airflow processing report', html_content='raw content #2', dag=dag ) ``` I notice that the Airflow docs say that xcom calls can be embedded in templates. Perhaps there is a way to formulate an xcom pull using a template on a specified task ID then pass the result in as html\_content? Thanks
Use `PythonOperator` + `send_email` instead: ``` from airflow.operators import PythonOperator from airflow.utils.email import send_email def email_callback(**kwargs): with open('/path/to.html') as f: content = f.read() send_email( to=[ # emails ], subject='subject', html_content=content, ) email_task = PythonOperator( task_id='task_id', python_callable=email_callback, provide_context=True, dag=dag, ) ```
might as well answer this myself. Turns out it's fairly straight forward using the template+xcom route. This code snippet works in the context of an already defined dag. It uses the BashOperator instead of EmailOperator because it's easier to test. ``` def pushparam(param, ds, **kwargs): kwargs['ti'].xcom_push(key='specificKey', value=param) return loadxcom = PythonOperator( task_id='loadxcom', python_callable=pushparam, provide_context=True, op_args=['your_message_here'], dag=dag) template2 = """ echo "{{ params.my_param }}" echo "{{ task_instance.xcom_pull(task_ids='loadxcom', key='specificKey') }}" """ t5 = BashOperator( task_id='tt2', bash_command=template2, params={'my_param': 'PARAMETER1'}, dag=dag) ``` can be tested on commandline using something like this: ``` airflow test dag_name loadxcom 2015-12-31 airflow test dag_name tt2 2015-12-31 ``` I will eventually test with EmailOperator and add something here if it doesn't work...
I want to serialize a `HashMap` with structs as keys: ``` use serde::{Deserialize, Serialize}; // 1.0.68 use std::collections::HashMap; fn main() { #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash)] struct Foo { x: u64, } #[derive(Serialize, Deserialize, Debug)] struct Bar { x: HashMap<Foo, f64>, } let mut p = Bar { x: HashMap::new() }; p.x.insert(Foo { x: 0 }, 0.0); let serialized = serde_json::to_string(&p).unwrap(); } ``` This code compiles, but when I run it I get an error: ```none Error("key must be a string", line: 0, column: 0)' ``` I changed the code: ``` #[derive(Serialize, Deserialize, Debug)] struct Bar { x: HashMap<u64, f64>, } let mut p = Bar { x: HashMap::new() }; p.x.insert(0, 0.0); let serialized = serde_json::to_string(&p).unwrap(); ``` The key in the `HashMap` is now a `u64` instead of a string. Why does the first code give an error?
You can use `serde_as` from the [`serde_with` crate](https://crates.io/crates/serde_with) to encode the `HashMap` as a sequence of key-value pairs: ``` use serde_with::serde_as; // 1.5.1 #[serde_as] #[derive(Serialize, Deserialize, Debug)] struct Bar { #[serde_as(as = "Vec<(_, _)>")] x: HashMap<Foo, f64>, } ``` Which will serialize to (and deserialize from) this: ``` { "x":[ [{"x": 0}, 0.0], [{"x": 1}, 0.0], [{"x": 2}, 0.0] ] } ``` There is likely some overhead from converting the `HashMap` to `Vec`, but this can be very convenient.
While all provided answers will fulfill the goal of serializing your `HashMap` to json they are ad hoc or hard to maintain. One correct way to allow a specific data structure to be serialized with `serde` as keys in a map, is the same way `serde` handles integer keys in `HashMap`s (which works): They serialize the value to `String`. This has a few advantages; namely 1. Intermediate data-structure omitted, 2. no need to clone the entire `HashMap`, 3. easier maintained by applying OOP concepts, and 4. serialization usable in more complex structures such as `MultiMap`. This can be done by manually implementing `Serialize` and `Deserialize` for your data-type. I use composite ids for maps. ```rust #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Proj { pub value: u64, } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Doc { pub proj: Proj, pub value: u32, } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub struct Sec { pub doc: Doc, pub value: u32, } ``` So now manually implementing `serde` serialization for them is kind of a hassle, so instead we delegate the implementation to the `FromStr` and `From<Self> for String` (`Into<String>` blanket) traits. ```rust impl From<Doc> for String { fn from(val: Doc) -> Self { format!("{}{:08X}", val.proj, val.value) } } impl FromStr for Doc { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match parse_doc(s) { Ok((_, p)) => Ok(p), Err(e) => Err(e.to_string()), } } } ``` In order to parse the `Doc` we make use of [`nom`](https://crates.io/crates/nom). The parse functionality below is explained in their examples. ```rust fn is_hex_digit(c: char) -> bool { c.is_digit(16) } fn from_hex8(input: &str) -> Result<u32, std::num::ParseIntError> { u32::from_str_radix(input, 16) } fn parse_hex8(input: &str) -> IResult<&str, u32> { map_res(take_while_m_n(8, 8, is_hex_digit), from_hex8)(input) } fn parse_doc(input: &str) -> IResult<&str, Doc> { let (input, proj) = parse_proj(input)?; let (input, value) = parse_hex8(input)?; Ok((input, Doc { value, proj })) } ``` Now we need to hook up `self.to_string()` and `str::parse(&str)` to `serde` we can do this using a simple macro. ```rust macro_rules! serde_str { ($type:ty) => { impl Serialize for $type { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let s: String = self.clone().into(); serializer.serialize_str(&s) } } impl<'de> Deserialize<'de> for $type { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { paste! {deserializer.deserialize_string( [<$type Visitor>] {})} } } paste! {struct [<$type Visitor>] {}} impl<'de> Visitor<'de> for paste! {[<$type Visitor>]} { type Value = $type; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("\"") } fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error, { match str::parse(v) { Ok(id) => Ok(id), Err(_) => Err(serde::de::Error::custom("invalid format")), } } } }; } ``` Here we are using [`paste`](https://crates.io/crates/paste) to interpolate the names. Beware that now the struct will always serialize as defined above. Never as a struct, always as a string. It is important to implement `fn visit_str` instead of `fn visit_string` because `visit_string` defers to `visit_str`. Finally, we have to call the macro for our custom `struct`s ```rust serde_str!(Sec); serde_str!(Doc); serde_str!(Proj); ``` Now the specified types can be serialized to and from string with serde.
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example: If the elements are: `1 2 3 4 5 6` It should print: `1 2 3 6 5 4` But it's printing: `1 2 3 5 4` Why isn't it printing the last element? How can this be solved? ``` void reverse() { int c=1; node *current,*prev,*temp; current=head; prev=NULL; std::stack<int>s; while(current->next!=NULL) { c++; s.push(current->data); current=current->next; } int mid=0; if((c%2)==0) { mid=c/2; } else { mid=(c+1)/2; } current=head; for(int i=0;i<mid;i++) { cout<<current->data<<"\t"; current=current->next; } for(int i=mid;i>1;i--) { std::cout<<s.top()<<"\t"; s.pop(); } std::cout << '\n'; } ```
Let's assume that the list contains only one element. In this case this loop ``` while(current->next!=NULL) { c++; s.push(current->data); current=current->next; } ``` will be executed never and as result the stack will be empty. Moreover the function initially has undefined behavior when the list in turn is empty and hence `head` is equal to NULL and you may not access `current->next` data member. Well now let's assume that the list contains exactly two elements. The loop will be executed only once and the variable `c` gets value 2. The calculated value of the variable `mid` will be equal to 1. So this loop ``` for(int i=0;i<mid;i++) { cout<<current->data<<"\t"; current=current->next; } ``` executes only one iteration and the first element is outputted. However the next loop ``` for(int i=mid;i>1;i--) { std::cout<<s.top()<<"\t"; s.pop(); } ``` will; be executed never because its condition `i > 1` yields `false` because mid is equal to 1. So the program has two wrong loops that should be rewritten. Below is a demonstrative program that shows how the function can be implemented. ``` #include <iostream> #include <stack> struct node { int data; node *next; } *head = nullptr; void append( int data ) { node **current = &head; while ( *current ) current = &( *current )->next; *current = new node { data, nullptr }; } void clear() { while ( head ) { node *tmp = head; head = head->next; delete tmp; } } void reverse() { std::stack<int> s; for ( node *current = head; current; current = current->next ) { s.push( current->data ); } std::stack<int>::size_type middle = ( s.size() + 1 ) / 2; std::stack<int>::size_type i = 0; for ( node *current = head; i < middle; i++ ) { std::cout << current->data << '\t'; current = current->next; } for ( i = s.size() - i; i != 0; i-- ) { std::cout << s.top() << '\t'; s.pop(); } std::cout << std::endl; } int main() { const int N = 10; for ( int i = 0; i < N; i++ ) { for ( int j = 0; j <= i; j++ ) append( j ); reverse(); clear(); std::cout << std::endl; } return 0; } ``` The program output is ``` 0 0 1 0 1 2 0 1 3 2 0 1 2 4 3 0 1 2 5 4 3 0 1 2 3 6 5 4 0 1 2 3 7 6 5 4 0 1 2 3 4 8 7 6 5 0 1 2 3 4 9 8 7 6 5 ```
It's not quite going to compile, but this is somewhat fewer lines: ``` // assert myList is sorted before called // if it's not, add // std::sort(myList.begin(), myList.end()); // as the first line of the function void reverseLatterHalf(std::vector& myList) { auto it = myList.begin() + myList.size() / 2; std::reverse(it, myList.end()); } ```
someone could please tell why this code does not work? it does not create data.txt. and the file does not save anything. ``` <?php $txt = "data.txt"; if(isset($_POST['info1']) && isset($_POST['info2']) && isset($_POST['info3']) && isset($_POST['info4']) && isset($_POST['info5']) && isset($_POST['info6'])) { // check if both fields are set //open file in read mode to get number of lines $handle = fopen($txt, 'r'); //check file opened if($handle) { //get number of lines $count = 1; while(fgets($handle) !== false) { $count++; } fclose($handle); //open in append mode. $handle = fopen($txt, 'a'); //prepare data to be writen $txt = $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n"; //write data to file fwrite($handle,$txt); fclose($handle); } } ?> ```
You are first trying to open the file read only, and if that succeeds you close it and open it again with write access. This will only work if the file already exists. If the file doesn't exist, your text will not get written to it. Move the closing bracket if `if ($handle) {` in front of the second `fopen` call. ``` if($handle) { //get number of lines $count = 1; while(fgets($handle) !== false) { $count++; } fclose($handle); } //open in append mode. $handle = fopen($txt, 'a'); //prepare data to be writen $txt = $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n"; //write data to file fwrite($handle,$txt); fclose($handle); ``` by the way, you can reduce this to three lines of code. ``` $lines = file($txt); $count = sizeof($lines); file_put_contents($txt, $count . ' ' . $_POST['info1'].'/'.$_POST['info2'].'/'.$_POST['info3'].'/'.$_POST['info4'].'/'.$_POST['info5'].'/'.$_POST['info6']. "\r\n", FILE_APPEND); ```
to check for multiple variables in `isset` create only one `isset` to check all veriables change this ``` if(isset($_POST['info1']) && isset($_POST['info2']) && isset($_POST['info3']) && isset($_POST['info4']) && isset($_POST['info5']) && isset($_POST['info6'])) ``` to ``` if(isset($_POST['info1'],$_POST['info2'],$_POST['info3'],$_POST['info4'],$_POST['info5'],$_POST['info6'])) ```
I want to create an alias that can handle parameters (`$1`), and can fall back to a default value if a parameter is not provided.  For example, ``` $ alias foo='NUM=${1:-42}; echo $NUM' ``` Invoked without params it works as I want: ``` $ foo 42 ``` But invoked with a param, it prints both my value and default value: ``` $ foo 69 42 69 ``` I don't understand why it's this way. How should it be done properly?  How can I debug this kind of problem myself?
aliases are just text replacement before another round of shell syntax interpretation, they don't take arguments, so after: ``` foo 69 ``` The `foo` text is replaced with `NUM=${1:-42}; echo $NUM` and then the shell interprets the resulting text: ``` NUM=${1:-42}; echo $NUM 69 ``` `$1` is still not set, so that's `NUM=42; echo 42 69` For an inline script interpreted in the current shell and that take arguments, use *functions* instead: ``` foo() { NUM=${1-42} printf '%s\n' "$NUM" } ``` Here using `${1-42}` instead of `${1:-42}`, as if the user calls `foo ''`, I would assume they want `$NUM` being assigned the empty string.
Use a function inside alias: ``` $ alias foo='function foo { NUM=${1:-42}; echo $NUM; }; foo' $ foo 42 $ foo 69 69 ```
I am in search.php and I get, for a certain query, a set of results (pages and posts). Now, within the loop I am using to display such results, I need to figure out if the current item is actually a post or a page. How do I do that? Is there a conditional tag to do it? I couldn't find it :( Thanks
You can use `is_page( $post->ID )` for pages and `is_single( $post->ID )` for posts.
The right answer is the following (sorry guys): ``` <?php while (have_posts()) : the_post(); ?> <?php if ($post->post_type === "post"): ?> it's a post! <?php endif; ?> <?php endwhile; ?> ```
I want to extract the words which have both alphabetical and numerical characters/ for example the function returns ac64fc in text below: foo ac64fc bar 4544 ``` preg_match('/^[0-9A-Z]*([0-9][A-Z]|[A-Z][0-9])[0-9A-Z]*$/', $subject); ``` I wrote this regulareexpression to find if there is any but I don't know how can I extract the word (ac64fc )
You are forcing input string to be only in the given format by `^` and `$` anchors. Replace them with `\b` (word boundary token) **and you are done** (also don't forget to enable `i` flag which makes it case-insensitive). Also to simplify, you could use the following version which obviously doesn't invoke lookarounds: ``` \b(?:[a-z]+\d|\d+[a-z])[a-z\d]*\b ``` See [live demo here](https://regex101.com/r/qAa8JL/1) PHP code: ``` preg_match('/\b(?:[a-z]+\d|\d+[a-z])[a-z\d]*\b/i', $subject); ```
Try Regex: `(?=\w*\d)(?=\w*[a-zA-Z])[A-Za-z\d]+` [Demo](https://regex101.com/r/cRAu9c/1)
when running * phpunit I get error ``` Warning: require(PHPUnit/Autoload.php): failed to open stream: No such file or directory in /usr/local/bin/phpunit on line 42 Fatal error: require(): Failed opening required 'PHPUnit/Autoload.php' (include_path='.:') in /usr/local/bin/phpunit on line 42 ``` /usr/local/bin/phpunit displays the following on line 42: ``` require 'PHPUnit/Autoload.php'; ``` any suggestions how to fix this? **Update (1):** I was missing php.ini in /etc/, so I symlinked it to read the MAMP php.ini. Now I get ``` php -r 'foreach (explode(":", get_include_path()) as $path) echo $path . PHP_EOL;' . /Applications/MAMP/bin/php/php5.3.6/lib/php /usr/local/bin/pear /usr/local/share/pear/PHPUnit ``` running * phpunit is running but provides no output. Any suggestions what to check next? **Update (2):** probably the root cause of this issue is related to question * [MAMP PEAR configuration is pointing to local directories](https://stackoverflow.com/questions/8482265/mamp-pear-configuration-is-pointing-to-local-directories).
I hit a similar issue on MAC OSX Lion. I installed phpunit with the PEAR package manager, and when I try to run it I got the error as described by udo. I was able to resolve it with the following simple steps: 1. Get the latest php archive of pear `curl http://pear.php.net/go-pear.phar > go-pear.php` 2. Install the archive with `sudo php -q go-pear.php` During installation, it detects if the include\_path in your php.ini does not contain the PEAR PHP directory. You can choose to let it fix it for you automatically when given the option.
It should be noted that most users who face the problem faced here must be running the command **$ phpunit** from the command prompt. when they get the above error. What Most of us fail to understand about the real issue is that the PHP used on the command prompt will mostly be very different from the one running things for you in your webserver. Personally i use lampp and even though i had correctly installed phpunit using pear successfully,i failed to realised this essential part for hours. **Remedy** - for anytime you need to run a PHP script that requires resources in the include\_path, make sure that php.ini for the respective PHP binary your using is adequately furnished. case and point in my ubuntu 12.04 installation with xampp my two php binaries include * the command line one i.e php5-cli found in /etc/php5/cli/ directory * the xampp one i.e php that is used by apache to serve my pages found in /opt/lampp/etc/php.ini Both the php.ini files must have your desirable and correct include\_path declaration for you to correctly bootstrap any command line scripts and serverside(apache served scripts). **Back to our matter at hand after correctly configuring the php.ini remember to** * Restart Apache so that the web server pick your changes * Restart you terminal/commandline session so that the cli prompt picks your changes **Common Mistakes that get you problems when Changing Files in Linux/\*nix Systems** * remember to run chwon to own the php.ini file or else you wont even manage to edit them * remember to run chmod and change the values to allow you to save your changes after which you can return everything (access control on file i.e chwon and chmod to the previous state) to the way they were and it should be ok after restarting the terminal and apache. Good Luck
Yeah basically the title, I want to do that things from a app that can run Linux scripts per SSH. I only want to run these three and not ALL from systemctl with my basic user. So thanks.
this line in my script got me the current (which as you now realise can change) xinput numbers from the names, in this case anything with ELAN0732. my results here is 14 and 15. xinput --list | sed -n 's/.\*ELAN0732:00.*id=([0-9]*).\*/\1/p' so you can set result as a variable and setpprop from that most likely using the first one to come up, 14 for me there.
Never mind. The xinput props setting numbers have changed once again and it turns out I had a set of ~/.profile settings that was overwriting them with funny values, which was the spanner in the works. FYI here is what I have set now as of Ubuntu 19.04 ``` xinput set-prop 11 313 20.0 50000.0 # more or less disable inertial scrolling because it just keeps sending scroll events which can lead to unwanted zooming if ctrl is pressed immediately after) xinput set-prop 11 311 1 # palm detection on xinput set-prop 11 312 1, 1 # set it to the smallest area possible (dunno if this is actually effective) ```
I have this `magit` configuration which automatically sets the magit commit message buffer to `evil` `INSERT` mode, but it assumes that `evil` is installed and active which may not be the case. How can I configure it so that it will only apply if `evil` is installed and active? ``` (use-package magit :ensure t :bind (("C-x g" . magit-status)) :config (setq magit-ediff-dwim-show-on-hunks t) (add-hook 'git-commit-setup-hook #'evil-insert-state) ) ```
If you only want the evil-related section to load if/when evil is loaded, you could wrap it with `with-eval-after-load 'evil`, like so: ``` (use-package magit :ensure t :bind (("C-x g" . magit-status)) :config (setq magit-ediff-dwim-show-on-hunks t) (with-eval-after-load 'evil (add-hook 'git-commit-setup-hook #'evil-insert-state))) ``` If you want the whole magit config to only load if evil is loaded, you could use the `:after` keyword like so: ``` (use-package magit :ensure t :after evil :bind (("C-x g" . magit-status)) :config (setq magit-ediff-dwim-show-on-hunks t) (add-hook 'git-commit-setup-hook #'evil-insert-state)) ```
Use package has a `:if` directive that will > > Initialize and load only if EXPR evaluates to a non-nil value. > > > Adding that to your config will stop magit from being loaded if evil is not already loaded. ``` (use-package magit :if (featurep 'evil-mode) :ensure t :bind (("C-x g" . magit-status)) :config (setq magit-ediff-dwim-show-on-hunks t) (add-hook 'git-commit-setup-hook #'evil-insert-state) ) ```
We have a [RichEdit](http://blogs.msdn.com/murrays/archive/2006/10/14/richedit-versions.aspx) control into which we allow the user to insert an [Office MathML](http://en.wikipedia.org/wiki/Office_MathML) equation object. Basically the logic goes like this: the user click on insert math equation, we allow them to use an external MathML editor, then we will paste an image to represent the equation into the RichEdit control: ``` ' Paste the picture into the RichTextBox. SendMessage ctlLastFocus.hwnd, WM_PASTE, 0, 0 ``` Find its position and lock it down using: ``` With ctlLastFocus 'lock the image .SelStart = .SelStart - 1 .SelLength = 1 .SelProtected = True ``` It's all nice and good in the beautiful world of ANSI, but we also allow [Unicode](http://en.wikipedia.org/wiki/Unicode) characters, and what I've noticed is that when you use Chinese characters, the position of the insertion is wrong by half the total position, i.e if it's supposed to be the 7th position now it's inserted at the third. Basically divided by two, I guess because Unicode takes two bytes as compared to ANSI which requires just one. So because I'm a dummy with no experience with the [RTF](http://en.wikipedia.org/wiki/Rich_Text_Format), RichEdit and Visual Basic 6. So my question is: can I change the position of the image when I paste it using the sendMessage line? Or via some other way to control the position of the image inserted into the RichEdit box?
What exactly are you trying to accomplish by doing this? LOLcat-style image captioning? I'd use Gd2 and modify the image directly. Simplified web-page layout? Probably quicker to cache the div's source code. I'd also suggest creating a few manually and comparing the resulting file-transfer sizes, I'd bet in almost all circumstances (original HTML+image) is smaller than (resulting image).
If you're determined to render an image, you must 1. call a stand-alone web browser, or 2. embed an (X)HTML rendering engine, or 3. restrict the input options such that you can write a (greatly simplified) custom renderer, or 4. delegate the work to an external service All of these depend on the server's operating system, what software is available on it, and what access privs you have. 1. on Windows: call IE using COM automation; on Linux: see <http://www.chimeric.de/blog/2007/1018_automated_screenshots_using_bash_firefox_and_imagemagick> 2. on Windows: see <http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx> ; on Linux, see <http://webkit.org/building/build.html> or <http://khtml2png.sourceforge.net/> You might also consider the PHP-Qt or PHP-GTK bindings. Hope that helps.
Im looking for a way to detect if the user is using **Opera Mini on iPad**. The reason why I want to do that is because Opera Mini on iPad does not support HTML5's "video" tag or Flash. I need to be able to have a static image loading in my video container in that specific case. Is there any way of detecting this?? Im already using the ipad detection like: ``` var isiPad = navigator.userAgent.match(/iPad/i) != null; if (isiPad){ ... } ``` Now, can I get that specific browser?
You could check for `<video>` support directly using [Modernizr](http://www.modernizr.com/docs/#features-html5).
I think this will answer your question. <https://www.handsetdetection.com/features/mobile-browser-detection> I hope this helps.
First of all, I'm using Andorid and Java only for a week and I'm a total newbie. I need to know which button user clicked and then compare it with good or bad answer. Here is the code ``` protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.questions); Integer[] flags = { R.drawable.flag_albania, R.drawable.flag_andorra, R.drawable.flag_angola, R.drawable.flag_avganistan, }; String[] questions = { "What is the flag of Albania", "What is the flag of Andorra", "What is the flag of Angola", "What is the flag of Avganistan", }; TextView tv = (TextView) findViewById(R.id.textView1); int arraySize = flags.length; Random rand = new Random(); ImageButton button1 = (ImageButton) findViewById(R.id.imageButton1); int index = rand.nextInt(arraySize); int questionIndex1 = index; button1.setImageResource(flags[index]); flags[index] = flags[--arraySize]; ImageButton button2 = (ImageButton) findViewById(R.id.imageButton2); index = rand.nextInt(arraySize); int questionIndex2 = index; button2.setImageResource(flags[index]); flags[index] = flags[--arraySize]; ImageButton button3 = (ImageButton) findViewById(R.id.imageButton3); index = rand.nextInt(arraySize); int questionIndex3 = index; button3.setImageResource(flags[index]); flags[index] = flags[--arraySize]; ImageButton button4 = (ImageButton) findViewById(R.id.imageButton4); index = rand.nextInt(arraySize); int questionIndex4 = index; button4.setImageResource(flags[index]); flags[index] = flags[--arraySize]; Integer[] question = { questionIndex1, questionIndex2, questionIndex3, questionIndex4 }; int questionArraySize = question.length; int questionArray = rand.nextInt(questionArraySize); tv.setText(questions[question[questionArray]]); ``` My idea is to compare questionIndex that is randomly selected to a button id but I really don't know how to implement it. Every help is appreciated.
Try out this way: > > > ``` > button1.setOnClickListener(onClickListener); > button2.setOnClickListener(onClickListener); > /** > * Common click listener > */ > OnClickListener onClickListener = new OnClickListener() > { > @Override > public void onClick(View p_v) > { > switch (p_v.getId()) > { > case R.id.imageButton1: > //Your logic here. > break; > case R.id.imageButton2: > //Your logic here. > break; > } > } > > ``` > > } > > >
You can do the it this way also. You have to use some int variables to keep the tag value of the button. And also you have to create a onClickListner for the button actions. Coding is as follow ``` public class MyActivity extends Activity{ //Define the Tag values for image buttons. private static final int TAG_IMAGE_BTN_1 = 0; private static final int TAG_IMAGE_BTN_2 = 1; private static final int TAG_IMAGE_BTN_3 = 2; private static final int TAG_IMAGE_BTN_4 = 3; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); initActivity(); } private void initActivity(){ //Initialize the image buttons via xml or from the code itself. //Add the onClickListner_BTN_CLICK and the corresponding tag to the image button imageBtn1.setTag(TAG_IMAGE_BTN_1); imageBtn1.setOnClickListener(onClickListner_BTN_CLICK); imageBtn2.setTag(TAG_IMAGE_BTN_2); imageBtn2.setOnClickListener(onClickListner_BTN_CLICK); ....................................................... ....................................................... } OnClickListener onClickListner_BTN_CLICK = new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub int iTag = (Integer)v.getTag(); switch (iTag) { case TAG_IMAGE_BTN_1: break; case TAG_IMAGE_BTN_2: break; case TAG_IMAGE_BTN_3: break; case TAG_IMAGE_BTN_4: break; } } }; } ``` The advantages of using the tag values for capture the action, 1)If we use R.id....... then we have to change the value in switch case if we change it in the xml file 2)We can use only one onClickListner for every action in an activity.
I have a spreadsheet with multiple columns and over 4000 rows. I need to sort, then alphabetize my report and everytime I do, there are 43 rows that do not sort with the rest of the report; they go to the top or bottom of the report and are alphabetized as a separate group. I've tried deleting them and re-entering them and trying all over to get them to alphabetize with the rest of the report but they continue to stay separate. Why is this happening? Any help will be appreciated.
The most common reason for data not sorting correctly is due to the leading space ahead of the text. Many people using encounter this problem. The text with leading space is sorted at the top in ascending and at the bottom in descending order sort. Try correcting this, and it will work.
My solution: I was sorting by date, and found that some of my dates didn't make sense (ie: February 31st) Perhaps some of your values are similarly nonsensical.
> > **Possible Duplicate:** > > [How to find web hosting that meets my requirements?](https://webmasters.stackexchange.com/questions/20838/how-to-find-web-hosting-that-meets-my-requirements) > > > I have spent weeks trying to find information on hosting sites for my site. I currently use 1&1 but I need to have support for add-on DLLs (iTextsharp) and they have told me for security reasons they can't do that. I use .NET, C# and MSSQL.. I'm in the UK but not bothered where I host. So off I went researching on the web, and every time I thought I had found a good one, I would read reviews and they would be bad! I am down to the following list. Does anyone have any views on them or point me to a *good* site which has proper reviews from lots of users or **even better** a reliable .NET host which would support my needs. DiscountASP, U2-Web, 000webHost, HeartInternet, Somee, Arvixe, Daily.co.uk, GoldPuma, TitanInternet, Aspnethosting, IXWebHosting
It depends upon how far you want to stretch your budget - Shared servers will always be incredibly cheap, but of course you will always trade off cheapness for many restrictions upon your code and deployment options. Have you considered a VPS solution rather than shared hosting? I've been using UK company [Memset](http://www.memset.com) and I've found that they are pretty good. You can get your own virtual Windows 2008 server for £11.95 per month (if you choose the year contract, they do a 1 month minimum term and you can cancel any time). The only problem you'd have with choosing a VPS solution is MS SQL Server. Clearly the licence costs are prohibitive for an individual, but if it's a greenfield project, installing PostgreSQL or MySQL is trivial, so perhaps you could develop against that. I've been using the PostgreSQL ADO.NET libs for years and they are really good - you shouldn't have any problems. If you decide to try a VPS - use the Web Platform Installer to set things up. It's really smooth, quick and easy. P.S. Before anybody asks... I don't work for Memset!
You may want to give WinHost (http://winhost.com) a look. We support everything you're looking for starting at $4.95/month. If you have any questions about us feel free to drop us a line.
In computer programming, there is a classic first program for learning/teaching a new language or system, called "hello, world". <http://en.wikipedia.org/wiki/Hello_world_program> Is there a classic first data visualization for using a graphing package? If so, what is it? And if not, what would good candidates be?
Two thoughts: A. When I try to get at the essence of "Hello World", it's the minimum that must be done in the programming language to generate a valid program that prints a single line of text. That suggests to me that your "Hello World" should be a univariate data set, the most basic thing you could plug into a statistical or graphics program. B. I'm unaware of any graphing "Hello World". The closest I can come is typical datasets that are included in various statistical packages, such as R's AirPassengers. In R, a Hello World graphing statement would be: ``` plot (AirPassengers) # Base graphics, prints line graph ``` or ``` qplot (AirPassengers) # ggplot2, prints a bar chart ``` or ``` xyplot (AirPassengers) # lattice, which doesn't have a generic plot ``` Personally, I think the simplest graph is a line graph where you have N items in Y and X ranges from 1:N. But that's not a standard.
The histogram of a sample of a normally distributed random variable.
Like many others I was excited to hear that [Mockito now works with Android](http://corner.squareup.com/2012/10/mockito-android.html) and followed [this tutorial](http://www.paulbutcher.com/2012/05/mockito-on-android-step-by-step) to see it with my own eyes. Everything seemed fan-flapping-tastic and I got underway incorporating the mocking solution into my Android Test Project... ### The error However, on setting up my application's test project to leverage the `mockito-all-1.9.5`, `dexmaker-1.0` and `dexmaker-mockito-1.0` jars I encountered a problem with my very first test case. Precisely [this problem](http://code.google.com/p/dexmaker/issues/detail?id=16) in fact. The part that I would like assistance on is; ``` Caused by: java.lang.VerifyError: org/mockito/cglib/core/ReflectUtils at org.mockito.cglib.core.KeyFactory$Generator.generateClass(KeyFactory.java:167) at org.mockito.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25) at org.mockito.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:217) at org.mockito.cglib.core.KeyFactory$Generator.create(KeyFactory.java:145) at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:117) at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:109) at org.mockito.cglib.core.KeyFactory.create(KeyFactory.java:105) at org.mockito.cglib.proxy.Enhancer.<clinit>(Enhancer.java:70) ``` I have been informed that this "simply doesn't quite work yet" since the stack trace implies that the DexMaker jar is not being used - reference [this response](http://code.google.com/p/dexmaker/issues/detail?id=16#c3). However, I am suspicious that I am doing something wrong with respect to my project set-up so I'm looking to draw from the collective knowledge base here to see if indeed this is user error or a beta-bug. ### My Android Test Project set-up Please find below a screenshot of my test project's configuration. The project was created via the Android Wizard and shares no special features other than the inclusion of the Mockito and DexMaker jars (mentioned above) under the `libs` directory. ![Test Project Configuration](https://i.stack.imgur.com/O6VqW.png) ### The Test Never mind the content of the test (the test fails before the unit test is executed) the set-up is as described below; ``` public class TestSpotRatingCalculator extends InstrumentationTestCase { @Mock private AService aService; // Changed the service names being used here - not important. @Mock private BService bService; @Mock private CService cService; @Mock private DService dService; /** * @see android.test.AndroidTestCase#setUp() */ @Override protected void setUp() throws Exception { super.setUp(); MockitoAnnotations.initMocks(this); // Failure here with aforementioned stacktrace... } ``` If anyone out there has an idea what is wrong then please sound-off here.
Hi I had the same problem and I found this article really usefull! <http://corner.squareup.com/2012/10/mockito-android.html> The key piece of information is: > > To use Mockito on a device or emulator, you’ll need to add three .jar > files to your test project’s libs directory: [mockito-all-1.9.5.jar](https://mockito.googlecode.com/files/mockito-all-1.9.5.jar), > [dexmaker-1.0.jar](http://dexmaker.googlecode.com/files/dexmaker-1.0.jar), and [dexmaker-mockito-1.0.jar](http://dexmaker.googlecode.com/files/dexmaker-mockito-1.0.jar). > > >
Just add this in your gradle: ``` androidTestCompile 'org.mockito:mockito-core:1.10.8' androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.1' ```
[This recent question](https://cooking.stackexchange.com/questions/75148/is-there-any-way-to-bring-an-egg-to-its-natural-state-not-boiled-after-you-coo) about a person who wanted to bake a cake but only had a cooked egg left suggested me an even stupider one: **is it possible to bake a cake with a cooked egg instead of a raw one?** After all, the egg is going to end up cooked inside the cake anyway. I imagine that it's going to be tricky to mix it with the dough, but with a hand mixer and a sufficient amount of violence everything is possible. Or are the chemical processes of boiling an egg and cooking it inside the dough fundamentally different?
It is possible, but only if you do not want it to act as glue. > > are the chemical processes of boiling an egg and cooking it inside the dough fundamentally different? > > > As mentioned in earlier answers - no, but the point is that you need these processes during baking. One notable exception is shortcrust pastry ========================================== You can use boiled egg to bake it. It is meant to be crusty, fragile. That's why you mix flour with fat first - to prevent gluing. When you use a boiled egg yolk instead of raw one, you have one less factor for gluing. It's easy to make pastry too delicate that way, but it is doable. I did it with success.
In Italy we go as far as cooking salty cakes with boiled eggs, they are decorative but can be peeled and eaten. We indeed put them in the oven with all the shell. The recipe is from Naples, and is called Casatiello Napoletano Salato (Casatiello stays for little house, don't ask me why, the other two words mean neapolitan and salty). Cfr.: <http://www.lucianopignataro.it/a/ricetta-casatiello-napoli/70835>
The increase in the character limit of comments has led them to become as important as the questions and answers that spawn them. On several occasions (especially on meta) I've found reason to want to link to a comment directly. I'd imagine something as simple as making the date / time stamp an anchored link which mimics the behavior of the question link.
This appears to be officially supported now: ![permalink to comments](https://i.stack.imgur.com/t0076.png) Right clicking on the timestamp gives what looks like a stable URL: [`https://meta.stackexchange.com/questions/5436/direct-link-to-a-comment#comment1232412_5436`](https://meta.stackexchange.com/questions/5436/direct-link-to-a-comment#comment1232412_5436)
This would actually be really helpful for people who flag comments - being able to move directly to the item flagged.
Lately my garage door has been stopping when it gets about 2ft from the closed position and then returns to the original position. Nothing is blocking the sensors and the tracks don't seem to have any bends or anything that would prevent the door from moving freely. I also tried checking the cycle with the door disengaged (by pulling the emergency handle and letting the door sit in the closed position not connected to the chain), and the chain moves, stops, and returns at the same location as it does when the door is attached. So, I assume it's something in the actual opening unit. I haven't tried to adjust the downward force yet, but I'll give that a try when I get home tonight. Don't think that's the issue though. Has anyone had this issue before?
I had this happen to one of my garage doors. The sensor "eyes" are attached to the rails. Over time the bottom of one of the rails worked itself a little loose and I found that the vibration of the door coming down would rattle the rail and disturb or misalign the sensor to the point that it would read an interruption and the door would reopen. I found other rails could be tightened as well. Tightened everything up, realigned the sensors and no problems since.
I posted an answer on a [similar question](https://diy.stackexchange.com/a/141675/35238) Basically I determined that the wiring from the sensor to the circuit board was loose. I unscrewed and reconnected it. Second I realized that the chain was vibrating a lot while opening/closing, which is what caused the loose wiring to flicker. I tightened the chain a bit (not too tight - it is supposed to sag a little bit) and straightened it since it was very slightly twisted. Now the garage door closes and opens without any vibration, and the wiring is secure, so it has stopped reversing.
I am learning `Android` concepts `Activity` and `BroadCastReceiver`. I want to update the content of `Activity` from the `BroadtCastReceiver` both are in different java class. It is something like `MyActivity.java` and `MyBroadtCastReceiver.java` Is this possible to do this in Android ?
[Squonk](https://stackoverflow.com/users/488241/squonk)-s answer only works, if the Activity is active currently. If you dont want to declare / define your BroadcastReceiver (BR) in an other Activity, or if you want to make some changes even if the app is not foreground, than your solution would look something like this. First, you declare the BR, and save, or override the data needed to show in Acitvity. ``` public class MyBR extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // override the data. Eg: save to SharedPref } } ``` Then in Activity, you show the data ``` TextView tv = findViewById(R.id.tv); tv.setText(/*get the data Eg: from SharedPref*/); ``` And you should use a Timer to refresh the tv as well: ``` Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { TextView tv = findViewById(R.id.tv); tv.setText(/*get the data Eg: from SharedPref*/); } }); } }, REFRESH_RATE, REFRESH_RATE); ``` REFRESH\_RATE could be something like 1 second, but you decide.
try like this it may help you. Define this method in activity's oncreate method in which you want to update ui, ``` BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //your code to update ui } }; LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("giveyourappname")); ``` Define this action at place from where you want to update ui, ``` try{ ActivityManager am = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE); List<RunningTaskInfo> taskInfo = am.getRunningTasks(1); ComponentName componentInfo = taskInfo.get(0).topActivity; Log.d("Activity", "Current Activity ::" + taskInfo.get(0).topActivity.getClassName()); Log.d("Package", "Package Name : "+ componentInfo.getPackageName()); if(componentInfo.getPackageName().equals("your application package name")){ Intent intent = new Intent("giveyourappname"); //add data you wnat to pass in intent LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } }catch(Throwable e){ e.printStackTrace(); } ```
Whenever Ubuntu boots up, a dialogue pops up asking me to unlock my default keyring. Is there some way this can unlock automatically through PAM or some other magical way? [![unlock login keyring](https://i.stack.imgur.com/SeF1u.png)](https://i.stack.imgur.com/SeF1u.png)
### For versions up to 12.04: (for 12.10 onwards, see [this](https://askubuntu.com/a/224777/2405) answer) The method is similar to previous Ubuntu versions, but I also include a command-line alternative at the end. ### 1. Using the Gnome Keyring Manager (*Seahorse*) * Press `Alt`+`F2`, type *seahorse* and press Enter to start the Gnome Keyring Manager: ![enter image description here](https://i.stack.imgur.com/P7WYq.png) * Alternately, open a terminal with `Ctrl`+`F2`+`T`, type `seahorse &` and press Enter. * The "Passwords and Keys" window should come up as shown below. Under the *Passwords* tab, select *login*, right-click on it, and then click on *Change Password*: ![enter image description here](https://i.stack.imgur.com/QpfPB.png) * The "Change Keyring Password" box will come up. Type your old password, and then *leave the new/confirm password fields **blank***. Then press OK, and the information box shown below will pop-up; read it, and then click on *Use Unsafe Storage* to not have to enter your password at each login: ![enter image description here](https://i.stack.imgur.com/OFoGF.png) * Close the keyring manager. After you log out/reboot, you won't be asked for your password any more. ### 2. Disable the login keyring password from the command-line As an alternative to all the above steps, simply open a terminal, and type/paste the below, changing `MYPASSWORD` to whatever your current password is; that's it! ``` python -c "import gnomekeyring;gnomekeyring.change_password_sync('login', 'MYPASSWORD', '');" ```
open passwords and keys then ![enter image description here](https://i.stack.imgur.com/eKIQ5.png) ![enter image description here](https://i.stack.imgur.com/QpfPB.png) Then you need to enter your current password (old password). Don't enter any password for your new one, or leave it blank. You need to confirm that you will store unencrypted password. If you are sure that it is what you want, then just click "Use Unsafe Storage" button.
There was a small [discussion](https://stackoverflow.com/questions/4299418/why-do-you-use-git-over-mercurial-or-vice-versa/4300055#4300055) about what git does and doesn't do by default for the user. By default, colour is disabled (generally set up with `git config`), yet it sends its output to a pager application for certain commands (such as in `git log`). One side to this would be that no flags should be enabled since it gives the user full control of the application. The contrary would state that when releasing a new application, one should try and win users over as quickly as possible with as many bells and whistles as possible. This is probably a very subjective question, but in the year 2010 should terminal applications start making usability decisions by default or force its users to customize it.
``` $ rm file.txt </dev/null Do you want to remove file.txt [y/n] tty not connected, guessing "no" ``` So no; please avoid any assumptions because they can turn out to be the exact opposite of what is expected. Color in git diff is disabled by default, because pagers may not support it — this is the case even for less, which needs to be explicitly invoked with the `-R` option to turn on escape sequence support.
if there are conditions when something acts differently like in the case of color when the output is a tty vs a pipe it should be clear what this condition is but `git log` doesn't check for this but some other programs do like `ls` in it's `--color=auto` mode in the case of `git log` with `--color` it uses less with color escape code pass though on if you want to override it give them a like a `--color[=WHEH]` option like `ls` has which can force color on regardless of the type of the output ``` --color[=WHEN] control whether color is used to distinguish file types. WHEN may be `never', `always', or `auto' ``` the auto mode is what i describe in the first paragraph the default should be the one useful to the users of the program, if there are cases where that default isn't what is wanted that's what options are for
I have an expression consisting of a few pure functions added together like so: ``` f+g+h ``` I want to add the bodies of these functions together and make that a pure function. Usually I would do this by finding the maximum number of arguments (`maxArgs`) required to fill the functions `f`, `g` and `h`, and then create my added function like so: ``` newFunc = Evaluate[Through[(f+g+h)@@Slot/@Range@maxArgs]] &; ``` The `Evaluate` here is important for a couple of reasons impertinent to this question. Just know that it is **necessary to evaluate the function body**. The problem with this method is that in general, I won't always know what `maxArgs` will be. Technically, I could find this value by using [this answer](https://mathematica.stackexchange.com/a/56672/14593), but I'm worried about the performance and robustness of this method. I thought that I might circumvent the need to specify a number of slots by doing this: ``` newFunc = Evaluate[Through[(f+g+h)[##]]]& ``` But *Mathematica*'s output at this point throws an error, saying that the slots of the functions *f*, *g* and *h* cannot be filled from `##`. I understand that this is because `##` appears as just one symbol to *Mathematica*. So how might I evaluate `Through` without specifying the number of slots I will need? **Example:** Given: ``` f = #&; g = Function[{a,b,c}, a^3 - b]; h = - #1^2 + #2 &; ``` My desired output is produced by: ``` myFunc = Evaluate[Through[(f+g+h)[#1,#2,#3]]&; ``` The important bit here is the `Evaluate`. I want to evaluate the function body completely before creating the function. The problem with the code above is that I had to explicitly enter the maximum number of slots required by the pure functions. In this case, three slots were required. In general, I may be using functions that take 3 arguments, or 5, or 72, etc. In my notebook, I will not know ahead of time how many slots will be used by these functions.
Reading your question and comments again, and assuming that none of your pure functions contain SlotSequence, I think maybe this will work for you: ``` combine[expr_] := Max[ Cases[expr, Slot[n_] :> n, {-2}], Cases[expr, Verbatim[Function][x_List, __] :> Length@Unevaluated@x, {1}] ] // Function @@ {Through[expr @@ Array[Slot, #]]} & ``` Test: ``` f = # &; g = Function[{a}, a^2]; h = (-2 #1 + #3) &; combine[f + g + h] ``` > > > ``` > -#1 + #1^2 + #3 & > > ``` > > And now also: ``` f = Function[{a}, a]; g = Function[{a}, a^2]; h = Function[{a, b, c}, (-2 a + c)]; combine[f + g + h] ``` > > > ``` > -#1 + #1^2 + #3 & > > ``` > > Of course as rasher/ciao points out this doesn't work with e.g. `combine[f+g+h+f+g+h]` but that is because `f + f` evaluates to `2 f` and `Through` only works on the level one head. If something besides `Through` behavior is desired that will need to be specified.
Is this near to what you are looking for? ``` ClearAll[f, g, h] f1[s__] := Total@Take[{s}, 3]; f2[s__] := Times @@ Take[{s}, 2]; f3[s__] := {s}[[1]] {s}[[3]] - {s}[[2]] {s}[[4]]; expr = Through[(f + g + h)[##]] & w = expr /. {f -> f1, g -> f2, h -> f3}; w[5, 6, 7, 8] (* 35 *) ```
my images are structured like this: ``` /uploads/middle/ex.png /uploads/thumb/ex.png ``` i will change it to: `/images/trees/ex_middle.png` and `/images/trees/ex_thumb.png` it would be nice if i can get also access to them like this: `/images/ex_middle.png` and `/images/ex_thumb.png` is this possible ? i tried: ``` RewriteRule ^images/(.+)$ uploads/middle/$1 [NC,L] RewriteRule ^images/trees/(.+)$ uploads/middle/$1 [NC,L] ``` but this only works with one path, and i dont know how the rewrite the file name - any suggestions ? greets
I like <https://github.com/brianc/node-postgres>. It's actively developed, and just a nice thin layer. To use the json types in a prepared query, just `JSON.stringify` whatever you are trying to store as json (that's how postgres wants it anyway).
[Any-db](https://github.com/grncdr/node-any-db) with the pg extension is working great for me.
I have three original points $pt\_1, pt\_2, pt\_3$ which if transformed by an unknown matrix $M$ turn into points $gd\_1, gd\_2, gd\_3$ respectively. How can I find the matrix $M$ (all points are in 3-dimensional space)? I understand that for original points holds $M\cdot pt\_i = gd\_i$, so combining all $pt\_i$ into matrix $PT$ and all $gd\_i$ into $GD$ I'd get a matrix equation $M\cdot PT=GD$ with unknown $M$. However, many math packages solve matrix equations in form of $A\cdot x=B$, where $x$ is unknown. Is my idea of combining points into matrices correct and if so how can I solve my matrix equation?
Form matrices whose rows are $pt\_k$ and $gd\_k$. Then $$ \begin{bmatrix}pt\_1\\pt\_2\\pt\_3\end{bmatrix}M=\begin{bmatrix}gd\_1\\gd\_2\\gd\_3\end{bmatrix} $$ Then we have $$ M=\begin{bmatrix}pt\_1\\pt\_2\\pt\_3\end{bmatrix}^{-1}\begin{bmatrix}gd\_1\\gd\_2\\gd\_3\end{bmatrix} $$ So your idea is correct.
I don't believe the accepted answer works for translations. If we have a three-dimensional point and a 3x3 transformation matrix, the zero point will always map to the zero point. A general affine transformation requires a four-dimensional matrix. It may be possible to use a four-dimensional point with the fourth component of the point equal to 1.
I want to make a `Booking` class to book concert tickets. A `ConcertHall` class has 2 different seats, namely VIP and Regular. I've chosen `Seat[][]` as my data structure, where a `Seat` class contains `seat_number:String` and `preference:String`. Now, the VIP and Regular seats have a different capacity. Let's say the VIP's capacity is 10x5 seats and the Regular's capacity is 50x100 seats. The seats corresponding to both VIP and Regular also have Left, Center, and Right preferences. The problem with my current design is I have so many redundant code . Let's say a user wants to book a concert ticket, he/she will call the method: `book("VIP", "Mary", "Center")`. This is what my design and book method look like: ``` class Booking { private ConcertHall A; public Booking(String name) { A = new ConcertHall(name); } public boolean book(String serviceClass, String name, String preference) { Seat seat = find(serviceClass, preference) if(seat != null) { assignSeat(seat, name); return true; } return false; } } class ConcertHall { private Seat[][] VIP; private Seat[][] Regular; public Seat findSeat(String serviceClass, String preference) { if(serviceClass.equals("VIP")) { // query VIP array } else if(serviceClass.equals("Regular")) { // query Regular array } } public boolean assignSeat(Seat seat, String name) { if(serviceClass.equals("VIP")) { // query VIP array } else if(serviceClass.equals("Regular")) { // query Regular array } } } ``` There's already a problem here, namely for almost every method in `ConcertHall`, I have to do 2 identical checking for the VIP class and Regular class. Now I'm stuck. My code looks long and stupid because of the 2 identical checking. ===================================update=================================== I forgot to mention, there's an additional requirement. I have to keep track of the seats' position. Let's say a group of people want to book concert tickets, we have to find available seats in the same row. So, a HashMap wouldn't work here I think.
Because `event.target.responseText` isn't an array, it's a string. The length of a string object refers to the amount of characters in a string. You will need to call a `JSON.parse` on your response to get it in the correct format you want. ``` var responseText = '["4.wav","2.wav","3.wav","6.mp3","1.mp3","5.wav"]'; responseText.length //49 at this point, the length of the string var responseArray = JSON.parse(responseText); responseArray.length //6, because it's an array ```
You have to use Javascript function `JSON.parse()` with your given response. ``` var a = '["4.wav","2.wav","3.wav","6.mp3","1.mp3","5.wav"]'; alert(JSON.parse(a).length); ``` **[Demo](http://jsfiddle.net/2p6yve9d/)**
**Answer [here](https://stackoverflow.com/a/62116110/13651848).** 1.First I created variables `POWER`, `gandalf` and `saruman` as seen above in the code then a variable called `spells` to store the number of spells that the sorcerers cast. **code** ``` POWER = { 'Fireball': 50, 'Lightning bolt': 40, 'Magic arrow': 10, 'Black Tentacles': 25, 'Contagion': 45 } gandalf = ['Fireball', 'Lightning bolt', 'Lightning bolt', 'Magic arrow', 'Fireball', 'Magic arrow', 'Lightning bolt', 'Fireball', 'Fireball', 'Fireball'] saruman = ['Contagion', 'Contagion', 'Black Tentacles', 'Fireball', 'Black Tentacles', 'Lightning bolt', 'Magic arrow', 'Contagion', 'Magic arrow', 'Magic arrow'] spells=10 ``` 2. Then created two variables called gandalf\_wins and saruman\_wins. Set both of them to 0. ``` gandalf_wins=0 saruman_wins=0 ``` 3. And Lastly two variables called gandalf\_power and saruman\_power to store the list of spell powers of each sorcerer. ``` gandalf_power=[] saruman_power=[] ``` 4. The battle starts! Using the variables you've created above, code the execution of spell clashes. Remember that a sorcerer wins if he succeeds in winning 3 spell clashes in a row. If a clash ends up in a tie, the counter of wins in a row is not restarted to 0. Remember to print who is the winner of the battle. I am stucked here because I don't know how to create a dictionary for each with the spells and the power of this spells. Then, how should I compare them? Thanks in advance!
I have managed to solve this after doing some research into character encodings. MySQL UTF8 is more centred around linux and UNIX, Windows UTF8 support is very limited so UTF8 collations are likely to cause issues. However Windows does support UTF16... It still isn't straight forward though. In MySQL there are character sets UTF16 and UTF16LE. The LE stands for little endian. UTF16 uses big endian which in short will order by the most significant value in a sequence as opposed to little endian which orders by the least significant value in a sequence. For more info read the below. [<https://searchnetworking.techtarget.com/definition/big-endian-and-little-endian][1]> The encoding used by Windows Servers will mainly use little endian because as explained in the above article, it is determined by the CPUs of the servers (Intel processors are an example that use little endian). With this in mind I collated the Join/Sort column (nvarchar(55)) in the SQL Server Source to Latin1\_General\_Bin which in theory should be UTF16 little endian Encoding. I then converted the Join/Sort Columns in the MySQL source to UTF16LE character set and in the Order By Collated to UTF16LE\_Bin ``` SELECT CONVERT(UPPER(CONCAT_WS('-', Column1, Column2, Column3, 'AAA BBB CCC')) USING UTF16LE) AS DerivedColumn, ... ... ORDER BY DerivedColumn COLLATE UTF16LE_bin; ``` This Sorted the data correctly without need for using the Sort Transformation.
If you trust the sorting from both sources, you can just set the "Is Sorted" property in the Advanced Edit section for outputs from your data source. You then set a position for any column that the sort is applied to. If there's only one column that it's sorted on, just put a 1 against that column. Be careful though as it will barf if it isn't in the same order. If it's a number, you'r probably fine, or that format you've mentioned is also probably fine. But strings in general, I wouldn't trust.
What is the best practice? I am making a `ASP.NET` site where the user can input text data to be stored at a SQL database. I am using `HttpUtility.HTNLEncode()` to store the data and `HTMLDecode` to display it. This works well, but it does searching (selecting or free text) a lot more difficult. The user should be able to enter text containing <, ", ' and any other problematic character. What is the best practice? To store the data un-encoded? How can I mitigate the risks of injection then?
There are a few areas to cover here, so I'll do my best to cover the points. The points are: * Submitting potentially unsafe text * Storing unsafe text * Displaying unsafe text ASP.NET has a validation mechanism (as pointed out by @Candie) to be a first line defence against an attack. If you have an app that needs to submit HTML, XML, JS etc, you'll have to override the validation to allow it through. Once the data is through, I would say it is safe to store. The best way to store this data is through the use of Stored Procedures, and not dynamic T-SQL, as it can lead to [SQL Injection attacks](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx). The only problem left now comes from displaying that data verbatim in HTML. If you literally dump content onto the screen, this is where your problems may begin to become more apparent. So this is where your `HTMLEncode` comes into play. Characters are converted to HTML equivelant codes, so as not to be a danger. The Literal control offers a [.Mode](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.literal.mode.aspx) property so the control can handle this for you. Finally, there is an article on MSDN around [How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings](http://msdn.microsoft.com/en-us/library/a2a4yykt.aspx), which may also be of use.
The question you need to ask yourself is, why are you encoding the data? If you are trying to avoid SQL injection, then you should validate the data before putting it into the database. For example, if you only want alphanumeric characters in the input, then you would check that before inserting it into the database. If they are entering HTML, which makes it harder to check the text, then I would recommend using stored procedures. If you're using MsSQL then [this may help.](https://web.archive.org/web/20210513004137/http://www.4guysfromrolla.com/webtech/111499-1.shtml). If you're using MySQL then I *think* [this may refer to them](http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html). Remember, always sanitize your inputs!
I have an activity that has one element that is rooted to the top, and another element that should take the rest of the space available. The first element's content will change over time and require different amounts of space, and the second element needs to change size with it. This is a simplified version of what I have already: ``` <android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textview_A" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textview_B" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintTop_toBottomOf="@+id/textview_A" app:layout_constraintBottom_toBottomOf="parent" /> </android.support.constraint.ConstraintLayout> ``` The way it is currently, the top element is correct, but the second element isn't. It will adjust its position to be halfway the bottom of the top element and the bottom of the parent element, but its height is the same as its content, not all available space. How can I achieve this?
Set layout weight = 1 android: layout="1"
Please search before posting a question like this. Some of the previous answers on this * [Set width to match constraints in ConstraintLayout](https://stackoverflow.com/questions/37603751/set-width-to-match-constraints-in-constraintlayout) * [Restrict width in ConstraintLayout by another view](https://stackoverflow.com/questions/44409421/restrict-width-in-constraintlayout-by-another-view) Change `android:layout_height` of `@id/testview_B` to `0dp`. Something like `<TextView android:id="@+id/textview_B" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintTop_toBottomOf="@id/textview_A" app:layout_constraintBottom_toBottomOf="parent" />`
I have a delete link that makes a remote call: ``` <%= link_to image_tag("trash.png"), [current_user, bookcase], method: :delete, :remote => true, confirm: "You sure?", title: bookcase.image %> ``` In my controller, I end the delete function with a redirect: ``` def destroy @bookcase.destroy redirect_to current_user end ``` This works, except it's redirecting the user to the 'user/show.html.erb' file instead of the 'user/show.js.erb' file. How can I redirect the user, specifying which format to use?
Don't know if this is answering this specific question, but some might find the following helpful: ``` module AjaxHelper def ajax_redirect_to(redirect_uri) { js: "window.location.replace('#{redirect_uri}');" } end end class SomeController < ApplicationController include AjaxHelper def some_action respond_to do |format| format.js { render ajax_redirect_to(some_path) } end end end ```
I am pretty sure this code will work. ``` render :js => "window.location = '/jobs/index' ``` You can use this code in action /controller\_name/action name/
I can not seem to get sql server to recognize my credentials. Asp.net recognizes me when I login but when I execute a sql command I get a login failed message. The IIS server and SQL server are on different machines. There are other applications the IIS server which are able to authenticate to the sql server. I believe the Active Directory settings are correct. I am investigating what I am doing differently. I must be missing something. * I check the IIS settings * The web config is set to impersonate. Below is the relevant information. If anyone has any idea as to what I missed or am doing wrong I would appreciate some help. IIS Settings: * 'Integrated Windows authentication' is checked * 'Enable anonymous access" is not checked Web Config ``` <authentication mode="Windows"/> <identity impersonate="true"/> <authorization> <deny users="?" /> </authorization> ``` Page\_Load Code: ``` Dim winId As IIdentity = HttpContext.Current.User.Identity TextBoxMessage.Text = winId.Name + Environment.NewLine Dim cnn As SqlClient.SqlConnection Try Dim sql As String = "*****" cnn = New SqlClient.SqlConnection("Data Source=*****;Initial Catalog=****;Integrated Security=True") cnn.Open() Dim cmd As New SqlClient.SqlCommand(sql, cnn) cmd.ExecuteNonQuery() cnn.Close() Catch ex As Exception TextBoxMessage.Text += ex.Message cnn.Close() End Try ``` Output: Domain\UserName Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
You also need to enable constrained delegation: * [Enabling Constrained Delegation](http://technet.microsoft.com/en-us/library/cc756940(WS.10).aspx) * [How To: Use Protocol Transition and Constrained Delegation in ASP.NET 2.0](http://msdn.microsoft.com/en-us/library/ms998355.aspx) * [Windows Server 2003 Constrained Delegation (IIS 6.0)](http://technet.microsoft.com/en-us/library/dd296652(WS.10).aspx)
You need to set you credentials in Application Pool. - Open IIS - Select Application Pools - Enter the name, select .Net framework version and click OK - Select the new added application pool and click on Advanced Settings.. - In the Process Model section click on Identity - choose custom account and enter the AD username, password, confirm password and click OK - Select your application and in the Basic settings choose your application pool just created. Hope this helps
I have a notebook HP Pavilion dm4 running Ubuntu 12.04 and I'm trying to determine the model number (like HP Pavilion dm4-2015dx or HP Pavilion dm4-2033cl, etc). There's no such information on notebook's body as suggested [on HP's website](http://h10025.www1.hp.com/ewfrf/wc/document?lc=en&cc=us&docname=c00033108&dlc=en&product=1842189) on **Option 1**. I tried to use `lshw` and `dmidecode`, but couldn't find. Maybe I should use an especific option but all the information I found is for Windows, nothing for linux. There is a way to show this information on linux? --- `sudo dmidecode |grep Version` shows `Version: Intel(R) Core(TM) i5 CPU M 460 @ 2.53GHz` --- Here's the `System Information` part of `sudo dmidecode | less` ``` System Information Manufacturer: Hewlett-Packard Product Name: HP Pavilion dm4 Notebook PC Version: 058A120000242B10000020100 Serial Number: 5CA1062FYJ UUID: E4BD398B-4D9E-BC63-1A03-099330BF5443 Wake-up Type: Power Switch SKU Number: XZ299UAR#ABA Family: 103C_5335KV G=N L=CON B=HP S=PAV : ```
To see your model number, open a **Terminal** with `Ctrl` + `Alt` + `T` and type: `sudo dmidecode | grep Version | sed -n '2p'` or alternatively type: `sudo dmidecode | grep 'SKU Number' | head -1` to see your SKU Number. --- If you want to see a more detailed view of your System information type: `sudo dmidecode | grep -A 9 "System Information"` or `sudo dmidecode | less` and use the `**↓**` key to go to the section *System Information*. ![enter image description here](https://i.stack.imgur.com/yY9V2.png)
On my T430 I have to take out the battery and there is this little sticker that tells me exactly what I want to know. It's not where Lenovo says it is (on top of the battery), but there it is. Might be easier than doing it from the command line if in fact you have such a sticker.
I've never understood why $\int\_{-a}^{a}\frac{1}{t}dt$ isn't $0$. The function $\frac1t$ is odd so the area under the curve on the $t=(0,a]$ interval should cancel out with the area on the $t=[-a,0)$ interval. It shouldn't matter whether it's infinite area though right?
This is called the [Cauchy principal value,](https://en.wikipedia.org/wiki/Cauchy_principal_value) and it has its uses, as long as you understand its drawbacks. The big thing you lose is the change of variables. Let $f(x)=\frac{1}{x}$ and $$g(x)=\begin{cases}\frac{1}{x}&x<0\\\frac{n}{x}&x>0\end{cases}$$ If you want $\int\_{-1}^{1} g(x)\,dx$, you might let $u=x^n$ and $du=nx^{n-1}$ You might try the substitution $$u=\begin{cases}x^n&x>0\\x&x<0\end{cases}$$. So $\frac{du}{u}=\frac{n\,dx}{x}$ for all $x$, but you the Cauchy principal value for our integral is not the same (the value is infinite for the CPV of $\int\_{-1}^1 g(x)\,dx$.) --- A similar risk can be seen if you say it is "obvious" that $$\int\_{-\infty}^{\infty} x\,dx=0,$$ but also, it is "obvious" that: $$\int\_{-\infty}^{\infty} (x+1)\,dx = \int\_{-\infty}^{\infty} x\,dx$$
The integral $\int\_{-a}^{a}\frac{1}{t}dt$ is convergent $ \iff$ the integrals $\int\_{-a}^{0}\frac{1}{t}dt$ and $\int\_{0}^{a}\frac{1}{t}dt$ are both convergent. But the integrals $\int\_{-a}^{0}\frac{1}{t}dt$ and $\int\_{0}^{a}\frac{1}{t}dt$ are both divergent !
I'm trying to optimize web service calls with RxJava by executing batch requests when appropriate but without introducing too much delay to the response. For that I'm using `buffer(closingSelector)` operator with `debounce()` as closing selector like this: ```java Observable<BaseCall<T, R>> burstyMulticast = requestStream.share(); Observable<BaseCall<T, R>> burstyDeBounced = burstyMulticast.debounce(windowSize, windowUnit); burstyMulticast.buffer(burstyDeBounced).subscribe(/* call external WS with batches */); ``` It works fine, except that if `requestStream` produces too fast it emits huge batches, too big for the WS to handle at once, so I'd like to limit the batch size somehow. So I need a `closingSelector` that emits a close event either if there are X items in the buffer or Y amount of time passed since the last item arrived from the upstream. I can't seem to find a good solution other than implementing a custom `Operator` which is similar to `OperatorDebounceWithTime` but with an internal buffer which returns all elements in the buffer rather than the last one. Is there an easier way to achieve this e.g. by combining some ops? **Edit:** After posting the question I realised that the code piece above has another problem: if requests flowing continuously faster than debounce timeout (`requestStream` is producing faster than `windowSize`) then `burstyDeBounced` won't emit anything so all requests will be buffered until there is a long enough pause in the incoming stream.
use `pip3 install scapy-python3` and you will get it
Scapy supports Python 3.3 to 3.6 (and 2.7) but, so far, no release has been made. For now, you have to get the current development version from <https://github.com/secdev/scapy> and install it. **Update**: you can now install a 2.4.0 release candidate using `pip3 install --pre scapy` (`--pre` means you accept non-stable release). **Update**: Scapy 2.4.0 has been released. You can now use `pip3 install scapy`!
I have a series that contains NaN and True as a value. I want another series to generate a sequence of number, such that whenever NaN comes put that series value as 0 and In between of Two NaN rows I need to perform cumcount. i.e., Input: ``` colA NaN True True True True NaN True NaN NaN True True True True True ``` Output ``` ColA Sequence NaN 0 True 0 True 1 True 2 True 3 NaN 0 True 0 NaN 0 NaN 0 True 0 True 1 True 2 True 3 True 4 ``` How to perform this in pandas?
If performace is important better is not use `groupby` for count consecutive `True`s: ``` a = df['colA'].notnull() b = a.cumsum() df['Sequence'] = (b-b.mask(a).add(1).ffill().fillna(0).astype(int)).where(a, 0) print (df) colA Sequence 0 NaN 0 1 True 0 2 True 1 3 True 2 4 True 3 5 NaN 0 6 True 0 7 NaN 0 8 NaN 0 9 True 0 10 True 1 11 True 2 12 True 3 13 True 4 ``` **Explanation**: ``` df = pd.DataFrame({'colA':[np.nan,True,True,True,True,np.nan, True,np.nan,np.nan,True,True,True,True,True]}) a = df['colA'].notnull() #cumulative sum, Trues are processes like 1 b = a.cumsum() #replace Trues from a to NaNs c = b.mask(a) #add 1 for count from 0 d = b.mask(a).add(1) #forward fill NaNs, replace possible first NaNs to 0 and cast to int e = b.mask(a).add(1).ffill().fillna(0).astype(int) #substract b for counts f = b-b.mask(a).add(1).ffill().fillna(0).astype(int) #replace -1 to 0 by mask a g = (b-b.mask(a).add(1).ffill().fillna(0).astype(int)).where(a, 0) #all together df = pd.concat([a,b,c,d,e,f,g], axis=1, keys=list('abcdefg')) print (df) a b c d e f g 0 False 0 0.0 1.0 1 -1 0 1 True 1 NaN NaN 1 0 0 2 True 2 NaN NaN 1 1 1 3 True 3 NaN NaN 1 2 2 4 True 4 NaN NaN 1 3 3 5 False 4 4.0 5.0 5 -1 0 6 True 5 NaN NaN 5 0 0 7 False 5 5.0 6.0 6 -1 0 8 False 5 5.0 6.0 6 -1 0 9 True 6 NaN NaN 6 0 0 10 True 7 NaN NaN 6 1 1 11 True 8 NaN NaN 6 2 2 12 True 9 NaN NaN 6 3 3 13 True 10 NaN NaN 6 4 4 ```
Try this: ``` df['Sequence']=df.groupby((df['colA'] != df['colA'].shift(1)).cumsum()).cumcount() ``` Full example: ``` >>> df = pd.DataFrame({'colA':[np.NaN,True,True,True,True,np.NaN,True,np.NaN,np.NaN,True,True,True,True,True]}) >>> df['Sequence']=df.groupby((df['colA'] != df['colA'].shift(1)).cumsum()).cumcount() >>> df colA Sequence 0 NaN 0 1 True 0 2 True 1 3 True 2 4 True 3 5 NaN 0 6 True 0 7 NaN 0 8 NaN 0 9 True 0 10 True 1 11 True 2 12 True 3 13 True 4 ```
I'm getting the following error while installing one of a joomla component. Function : bcmod is not available. Please ask your hosts how you can enable this function in your PHP installation.
you need your PHP to be compiled with bcmath support (--enable-bcmath configure option). If you're on shared hosting it is unlikely they will enable it for you. So you can try a solution from PHP manual from this page: <http://ru.php.net/manual/en/function.bcmod.php> I haven't tried it , but you can test it: ``` /** * my_bcmod - get modulus (substitute for bcmod) * string my_bcmod ( string left_operand, int modulus ) * left_operand can be really big, but be carefull with modulus :( * by Andrius Baranauskas and Laurynas Butkus :) Vilnius, Lithuania **/ function my_bcmod( $x, $y ) { // how many numbers to take at once? carefull not to exceed (int) $take = 5; $mod = ''; do { $a = (int)$mod.substr( $x, 0, $take ); $x = substr( $x, $take ); $mod = $a % $y; } while ( strlen($x) ); return (int)$mod; } // example echo my_bcmod( "7044060001970316212900", 150 ); ```
If you have a dedicated server, try the solution given here <https://stackoverflow.com/a/25229386/8015825>. > > Before recompiling, check the php.ini file and search for "bcmath". > You may find bcmath.scale=0. If so, change the 0 to a 2. > > > And then restart your http server
I'm new to Laravel and I'm building a blog app in 7.7. I've got most of it working and the application has worked fine up until I've hit one bump. I've defined a "show" function in the controller, added the route, created the blade.php file and added the view yet it's giving me the an error. Code: **web.php** ``` Route::name('blog_path')->get('/blogs/{id}', 'Blogs@show'); ``` **Blogs.php** ``` public function show($id){ $blog = Blog::find($id); return view('blogs.show', ['blog' => $blog]); } ``` **index.blade.php** ``` <h5 class="card-title"><a href="{{ route('blog_path', ['blog' => $blog->id]) }}">{{ $blog->title }}</a></h5> ``` **Error:** ``` Missing required parameters for [Route: blog_path] [URI: blogs/{id}]. (View: D:\xxamp\htdocs\laravel\blog\resources\views\blogs\index.blade.php) ``` Thanks.
I needed to replace ['blog' => $blog->id] with ['id' => $ blog->id] Thanks Aslam.
Replace ``` <h5 class="card-title"><a href="{{ route('blog_path', ['blog' => $blog->id]) }}">{{ $blog->title }}</a></h5> ``` by ``` <h5 class="card-title"><a href="{{ route('blog_path', ['id' => $blog->id]) }}">{{ $blog->title }}</a></h5> ```
I am trying to parse out the patterns from a file and search the files for those strings then group them. Here is the code and the error I am getting ``` PS D:\Shared_With_Pai\Testing> Get-Content C:\\events.txt | Select-String -pattern $_ * |Select-Object LineNumber,FileName|Format-Table -GroupBy FileName Select-String : Cannot bind argument to parameter 'Pattern' because it is null. At line:1 char:52 + Get-Content C:\\events.txt | Select-String -pattern <<<< $_ * |Select-Object LineNumber,FileName|Format-Table -GroupBy FileName + CategoryInfo : InvalidData: (:) [Select-String], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.SelectStrin gCommand ``` Can anybody say where I am making the mistake? **EDIT:** The contents of events.txt is something like ``` 8,coilevent,networkchange 8,coilevent,malfunction 8,coilevent,conflictwithpc ``` I am searching some csv files for these lines.
The current object variable `$_` isn't populated with objects from the pipeline if you use it that way. As [@Kayasax](https://stackoverflow.com/a/22606549/1630171) suggested, you need to put the statement in a loop if you want it to work like that: ``` Get-Content C:\events.txt | % { Select-String -Pattern $_ * } | ... ``` However, there's no need to read the input from a pipeline in the first place. `-Pattern` accepts a string array, so you can simply read the file with the patterns in a subexpression: ``` Select-String -Pattern (Get-Content 'C:\events.txt') * | ... ```
Select-String is expecting a regular expression argument for a pattern. This: ``` Get-Content C:\\events.txt | Select-String -pattern $_ * ``` Is getting the content of the file, and using it as both the pipeline data and the match argument - Each line is being matched to itself. This makes no sense. Then the trailing \* after is going to be read as an argument to a positional parameter. Read the help on select-string, and see ``` get-help about_regular_expressions ``` After considering @Ansgar's comments, you might be able to use this: ``` gci | sls -Pattern (gc c:\temp\events.txt) -SimpleMatch ``` The -Pattern parameter will not take pipeline input, but it will take an array of pattern arguments, and will return a match on any pattern in the array, so you don't need to use foreach-object to iterate through that array.
I'm using this to write to a text file. Works fine while program is open but when I close and reopen and start saving again it completely over writes the previous numbers. ``` private void writeNumbers(ArrayList<String> nums) { try { PrintStream oFile = new PrintStream("lottoNumbers.txt"); oFile.print(nums); oFile.close(); } catch(IOException ioe) { System.out.println("I/O Error" + ioe); } } ```
``` pgClient.query('INSERT INTO my_table (my_json_column) VALUES ($1)', [JSON.stringify(myArrayObj)], cb) ```
Apparently, the expression "req.body.questions" only returns the array object which is not a valid JSON. Try creating a temporary JSON such that temJSON = {qInfo:req.body.questions} Then pass the temporary JSON to store into DB. Hope this helps. -Nith -- ps -- Note the error statement as it says colon character is missing in the input where it expects something like `<KEY>:<VALUE_OBJ>`
I am interested to know if, for some, there is a subtle difference between the two phrases in the title. I am equally interested in knowing if there is a subtle difference.
There is definitely a difference to me. They do not mean the same thing. Being *interested in* something describes a general interest that you hold—something that you tend to find interesting and devote some part of your time doing or at least thinking about. Being *interested to do* something, on the other hand, implies that right at this moment, you find the thing in question interesting and would like to [do whatever it is]; but it does not speak to your general interests. With the verb *know*, the latter tends to be a more accurate description of what’s going on: *knowing* is not something that we often need to talk about as one of our interests in life. For me personally, I frequently use it in the conditional: > > I’d be interested to know how much of our recycled waste is actually recycled. > > > In other words, it just struck me now that that particular piece of information would be an interesting one to have; I don’t count knowing how much of our waste is recycled among my general interests, though. If I *do* count something as a general interest, I would use the gerund form: > > I’m interested in knowing everything I can find out about the mating rituals of grasshoppers. > > > This implies two things: 1. That one of my general interests is the mating rituals of grasshoppers, and I therefore spend lots of time in learning everything I can about them (similar to “I’m interested in art”, except with an action as the interest instead of just a broad concept). 2. I have very little to no social life. This is not really a hard-and-fast distinction, but it’s a good rule of thumb. There are many cases where a gerund construction can, from context, be shoehorned into the sense of ‘current, fleeting interest’ rather than ‘permanent, general interest’: > > Would you be interested in going out for dinner tonight? > > Would you be interested in cooking for me tonight? > > > This is partly to do with the conditional, which tends to reinforce the ‘currently’ sense of *interested*; if you describe general interests, you would usually just use a straightforward present: > > Are you interested in going out to restaurants? > > Are you interested in cooking? > > > These last two are definitely ungrammatical to me with the infinitive construction: > > \*Are you interested to go out to restaurants? > > \*Are you interested to cook? > > >
Based on my intuition and the time I've spent trying to understand Jean Yate's *The Ins and Outs of Prepositions* I would suggest that 'in' gives a more detailed interest in learning, perhaps a specific detail or for a specific goal' whereas 'interested to know' is perhaps a general interest, but maybe nothing more.
I'm making a script which, automatically ads target="\_blank" to all external links. The problem is that, the script also makes the internal absolute links open in a new tab. You can check the problem on this test link: <http://www.fairfood.org/testtest/> ``` $("a").filter(function () { return this.hostname && this.hostname !== location.hostname; }).each(function () { $(this).attr({ target: "_blank", title: "Visit " + this.href + " (click to open in a new window)" }); }); ``` Does anybody know how to fix this? Any help is much appreciated.
`www.yourhost.com` is not the same as `yourhost.com`, so when your links don't match, this isn't working. You can just take out the `www.` if you know that this will always lead to a valid URI. (Also, your use of `.each` is *almost* redundant, as jQuery is already knowledgeable about element sets; however, you need it for `this.href`. Just something to be aware of.) ``` $("a").filter(function() { return this.hostname && this.hostname.replace(/^www\./, '') !== location.hostname.replace(/^www\./, ''); }).each(function() { $(this).attr({ target: "_blank", title: "Visit " + this.href + " (click to open in a new window)" }); }); ``` [Live example.](http://jsfiddle.net/5bWs6/)
You can use a single jQuery selector to do this: ``` $('a').not('a[href*="fairfood.org/"]').each(function(){ $(this).attr({target: "_blank", title: "Visit " + $(this).href + " (click to open in a new window)"}); }); ```
Some pages of my website were vulnerable to SQL injection. The injection worked only when the user was logged in. I have now fixed this problem, and now I want to make sure that no similar problems remain. I have tried scanning with [sqlninja](http://sqlninja.sourceforge.net) and [sqlmap](http://sqlmap.org/) but neither program has a provision to give website login details. Are there any tools that can scan for injection vulnerabilities with a logged in session?
There is a cookie option in sqlmap : > > --cookie=COOKIE HTTP Cookie header > > > So you just need to paste your cookie and you will be able to use sqlmap as if you were logged. If you need the list of all the options : <https://github.com/sqlmapproject/sqlmap/wiki/Usage>
You don't "fix" SQL injection problems. Well, people do, but that's wrong. What you must do is *not to allow them to happen* in the first place. The main tool for that is, as @TerryChia points out, [parameterized SQL statements](http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html). Parameterized SQL statements are very effective at preventing SQL injection attacks, by being a generic and thorough solution; this is *much* better, incomparably better, than any kind of "input data sanitation". SQL injection attacks occur because the Web site is trying to interpret user-provided data (field contents) as code (SQL is a programming language, after all). This implementation strategy is doomed. It cannot be really "fixed"; see [this answer](https://security.stackexchange.com/questions/20939/does-sql-have-any-inherant-weaknesses/20960#20960) for some conceptual discussion on this subject. "When the only tool you have is a hammer, then all problems have better be nails, because you're gonna hit them repeatedly on the head." Be aware that parameterized SQL statements, though widely applicable *and* efficient (more than traditional "dynamic" SQL statements), cannot do *everything*; there are very rare and specific contexts where dynamically building up SQL statements is the only solution. But this is not your situation -- you would already know it, and also all that I write in this answer. --- SQL injection "testing tools" are not satisfactory in any way: they are not meant for ensuring security, but for attacking the "low-hanging fruit". They will miss the overwhelming majority of possible SQL injections. Their purpose is to allow a non-technical attacker to nevertheless believe he is some kind of elite-level hacker; or to automate attack attempts on thousands of distinct sites. What these tools will tell you is one-way: if they *succeed* in breaking into your site, then you *know* that the site is extremely vulnerable; however, if they *fail*, then you know nothing. **Nevertheless**, if you want to get a tool past a "login session" system (despite all that I have explained above), then it depends on how the login is managed. Most Web sites will use a "login page" which results in setting a [cookie value](http://en.wikipedia.org/wiki/HTTP_cookie) in the client; that cookie represents the "logged in" state and it suffices to send it back to the server to be considered as part of the "session". SQL injection test tools allow you to include arbitrary cookie values in the request, which is what you are asking for. See, for instance, the [sqlninja documentation](http://sqlninja.sourceforge.net/sqlninja-howto.html) (search for the second occurrence of the "cookie" word in that page).
In particular, can the tmux session data be written to a file, and reloaded on reboot? I'm thinking of something similar to Vim's `mksession` command.
Assuming you could save the output of all panes to a file after the fact, you still have to restore the state of all processes in those panes. There was [something like that](http://cryopid.berlios.de/) at one point but it still has quite a few limitations. There is no such built-in functionality in tmux. This isn't like Vim which just has to remember which files you opened, whether you saved your work or not, where the cursor was, the history of inputs, etc. Edit: cryopid is down. See <https://criu.org/Main_Page>, which is what's officially in mainline.
You can write a script manually that recreates your desired tmux configuration. <https://github.com/chicks-net/chicks-home/blob/master/bin/start_tmux> is an example that has saved me a lot of time. I think that's easier to maintain than something automatically built like <http://brainscraps.wikia.com/wiki/Resurrecting_tmux_Sessions_After_Reboot> seems to do.
Getting Segmentation fault when executing any of the vespa-model-inspect commands. Vespa version 7.22.18 * log\_debug\_message 'Starting vespa-model-inspect with : ' env LD\_PRELOAD=/opt/vespa/lib64/vespa/malloc/libvespamalloc.so vespa-model-inspect-bin hosts * '[' '' ']' * exec env LD\_PRELOAD=/opt/vespa/lib64/vespa/malloc/libvespamalloc.so vespa-model-inspect-bin hosts Segmentation fault (core dumped) yum list | grep vespa vespa.x86\_64 7.22.18-1.el7 @group\_vespa-vespa .....
Trying to reproduce, how did you install Vespa in this environment? I was able to run vespa-model-inspect after installing Vespa 7.22.18 on RHEL 7.6 following the guide on <https://docs.vespa.ai/documentation/vespa-quick-start-multinode-aws.html>
The VESPA\_HOSTNAME property value in the /opt/vespa/var/jdisc\_core/configserver.properties was wrong as the node was cloned from another server. Once this config was fixed the commands are returning expected result.
I have following code, which should print an output of `k` numbers around `n` number, and instead the `n` number the code should replace by `*`: ```py def numbers_around(n, k): for cislo in range(n-k, n+k+1): if cislo == n: print("*", end=" ") else: print(cislo, end=" ") numbers_around(8, 3) numbers_around(10, 2) ``` The output should be: ```none 5 6 7 * 9 10 11 8 9 * 11 12 ``` But my output is all in one line: ```none 5 6 7 * 9 10 11 8 9 * 11 12 ```
As we have discussed in comment section I have mentioned that to check any object and processes in Kubernetes you have to use kubectl - see: [kubernetes.io/docs/reference/kubectl/overview](https://kubernetes.io/docs/reference/kubectl/overview/). Take a look how to execute proper command to gain required information - [kubectl-rollout](https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#rollout). If you want to check how rollout process looks from backgroud look at the source code - [src-code-rollout-kubernetes](https://github.com/kubernetes/kubectl/blob/master/pkg/cmd/rollout/rollout.go). Pay attention on that if you are using `node-api`: > > The node-api group was migrated to a built-in API in the > [k8s.io/api](https://github.com/kubernetes/api) repo with the v1.14 > release. This repo is no longer maintained, and no longer synced > with core kubernetes as of the v1.18 release. > > >
I often use 2 following command for check out deployment status ``` kubectl describe deployment <your-deployment-name> kubectl get deployment <your-deployment-name> -oyaml ``` The first will show you some events about process of schedule a deployment. The second is more detailed. It contains all of your deployment's resource info as yaml format. Is that enough for your need ?
I'd like clarification of the meaning of $W\_\text{max}$ in the following equations (and thus in the combined result in the third equation): \begin{align} W\_\text{max} &= \Delta G\\ W\_\text{max} &= -nF\varepsilon\\ \Delta G &= -nF\varepsilon\\ \end{align} In the first equation, we somehow come to the conclusion that the maximum useful work available from a process is that process' change in Gibbs Free Energy. I ask now what work that means - does it mean work done on the surroundings by release of energy from the system? Does it mean the maximum work done on the system via a chemical process (this makes more sense because it doesn't make sense that an increase in Gibbs Free Energy of a system would do work on anything but the system)? Secondly, in the electrochemical definition of $W\_\text{max}$, we have the point of view of the system; that is, positive work is done on the system and negative by the system. Therefore, we add the negative sign because when cell potential is positive the work done on the system is negative (it does work on the surroundings). The only logical conclusion I can come to is that the two $W\_\text{max}$ definitions must be both with respect to the system's point of view, which means that $W\_\text{max} = \Delta G$ refers to the maximum amount of work done on a system during a chemical process (the intuitive interpretation that I posed). However, it still makes me uncomfortable to define "useful work" as work done on the system. How can we harness work from putting energy into something?
"Maximum Additional Work that can be extracted at constant pressure and temperature" to be precise, which may include electrical work, etc. It means the work besides the expansion work. The negative sign signifies the sign of the charge of the electron, since electrical work is proportional to the charge.
> > Therefore, we add the negative sign because when cell potential is > positive the work done on the system is negative (it does work on the > surroundings). > > > That's correct. This is merely a convention, though. We could define positive and negative work the other way around as long as we also flipped the sign in all the equations that *use* work: $\Delta G = w$ becomes $\Delta G = -w$; $\Delta U = q + w$ becomes $\Delta U = q - w$; etc. > > How can we harness work from putting energy into something? > > > You can't, you harness the work when you take the energy out; you "store" the work when you put energy in. If, for example, you connect a battery to a DC motor and then have the motor raise a weight, you're doing ("harnassing") work by the cell on the surroundings, and a convention among chemists is to consider this negative work.
I am running an instance of Ubuntu 15.10. I need to install the latest kernel used by Ubuntu 14.10, which I think is 3.16.0-28-generic. Entering `sudo apt-get install linux-image-3.16.0-28-generic` returns an error message stating that it's not available and may have been obsoleted or whatever. I think if I add something to `sources.list` it will be able to get it. But what do I add to it? And before anyone goes on about the troubles this may produce, it doesn't matter to me.
In Ubuntu, use browser to navigate to > [http://kernel.ubuntu.com/~kernel-ppa/mainline/](http://kernel.ubuntu.com/%7Ekernel-ppa/mainline/) Scroll to the bottom of the list; choose your kernel. Download the following files (xxxxxx will be replaced with numbers indicating the kernel version. Assuming you have a 64bit OS): > > linux-headers-xxxxxx-generic-xxxxxx\_amd64.deb > > > linux-headers-xxxxxx\_all.deb > > > linux-image-xxxxxx-generic-xxxxxx\_amd64.deb > > > Move all these files to a folder. cd into it. Install all these packages by running ``` sudo dpkg -i *.deb ``` Choose new kernel from grub menu. **Update**: Since its an ubuntu instance you can manually get the links and and use wget to download the packages
If you know the exact version you want, e.g. 5.4.0-26-generic, just run ``` sudo apt install linux-image-5.4.0-26-generic ``` The dependencies will be installed automatically. Then in the next boot, select it in the grub menu.
The *Mortal Engines* series by Philip Reeve is set in a long-distant post-apocalyptic future known as the Traction Era, in which cities have become massive mobile structures that move around hunting each other, following the theory of Municipal Darwinism (except in the lands controlled by the Anti-Traction League). **Can we work out when the Traction Era is relative to the present day?** Clues given in the books include a reference to 35th-century ceramics being studied by Historians in the first chapter of the first book, and a given year of the Traction Era (roughly 1000, if memory serves) being specified in the last chapter of the last book. But is there enough to work out the time period from now, through the Sixty Minute War and the advent of Quirke, to the time in which the books are set?
At least several millenia ------------------------- The series is clearly set at least several centuries after the modern period, since the Stalkers were destroyed (and presumably created) "hundreds of years ago." > > "I thought they all died **hundreds of years ago**! I thought they were > all destroyed in battles, or went mad and tore themselves apart..." > > > —*Mortal Engines* > > > Of course, we can do better than that. The series is set around a millenium after the beginning of the Traction Era. > > Zagwa > > > 25th April 1027 TE > > > —*A Darkling Plain* > > > This is supported by Ermene Khan's thoughts on the Shield Wall: > > For **a thousand years** his family had helped to man the Shield-Wall, and > he seemed dazed by the news that all his guns and rockets were > suddenly useless. > > > —*Mortal Engines* > > > We further know that it must have been at least 1400 years after the 21st century, > > Two black-robed Guildsmen hurried past, and Tom heard the reedy voice of old Dr Arkengarth whine, "Vibrations! Vibrations! It's playing merry hell with my 35th Century ceramics.. > ."He waited until they had vanished around a bend in the corridor, > then slipped quickly out and down the nearest stairway. He cut through > the 21st Century gallery, past the big plastic statues of Pluto and > Mickey, animal-headed gods of lost America. > > > —*Mortal Engines* > > > That makes the modern period at least 1400 years before the time of the series. The dating of the ceramics is probably pretty accurate, since Pluto and Mickey were (fairly) correctly placed in the 21st Century gallery. Indeed, it seems likely that the 35th Century was before the Traction Era, since the use of TE to represent the Traction Era seems to be standard. This would place the time of the series at no less than 2400 years after the modern period (21st Century). **This is consistent with Hester and Pomeroy's comments, which indicate that the modern period was at least *several* millenia before the time of the series.** Hester says of satellites: > > "Except for the ones that aren't really stars at all. Some of the > really bright ones are mechanical moons that the Ancients put up into > orbit **thousands of years ago**, still circling and circling the poor old > Earth." > > > —*Mortal Engines* > > > Similarly, Pomeroy says, speaking of St. Paul's Cathedral: > > **Thousands of years old**, that cathedral, and they go and turn it into > a... into whatever they've turned it into, without so much as a > by-your-leave..." > > > —*Mortal Engines* > > > St. Paul's Cathedral was constructed starting in 1675. As such, we can suppose that the series is set *no more* than a few thousand years after the modern era, since even a stone building would degrade heavily after a while. That's about the best we can do.
I asked my good friend [Philip Reeve](https://twitter.com/philipreeve1/status/727608074618417152?lang=en) when his novel/s were set. Suffice to say, the answer he gave was somewhat nebulous. > > **Q:** *What year is Mortal Engines set in?* > > > **Philip Reeve:** *I have no idea! It's just The Future.* > > > So there you go. Clear as mud. Hope that helped.
I have a lot of TextBoxes in my single winform application. I am looking for a way to bind a single event method to all those textboxes when the form loads or in its constructor, so I dont add the event to every single textbox in designer. In the event, I want to detect the ENTER key and then programmatically click on a button: ``` private void ApplyFilterOnEnterKey(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { btnApplyFilters_Click(this, null); } } ``` Now the problem is how can I loop over all textboxes in my form and bind them to the above method? My textboxes are everywhere, inside nested tablelayoutpanels or nested normal pannels. How this loop will look like and where should I put it? In form constructor or in load event?!
Instead of subscribing to every TextBox's KeyDown event, you have two other options that I think are better: 1. Set your button as the default button of the form by setting `AcceptButton` property of the form to the button you want to be clicked by pressing Enter key. 2. Override [ProcessDialogKey](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.processdialogkey.aspx) on your form and check for pressing the Enter key: ``` protected override bool ProcessDialogKey(Keys keyData) { if (keyData == Keys.Enter) { // ... do what you want return true; } else return base.ProcessDialogKey(keyData); } ```
Just use the Controls collection and look if the control is a textbox then append the event
I've been thinking about this far too long and haven't gotten any idea, maybe some of you can help. I have a folder of python scripts, all of which have the same surrounding body (literally, I generated it from a shell script), but have one chunk that's different than all of them. In other words: ``` Top piece of code (always the same) Middle piece of code (changes from file to file) Bottom piece of code (always the same) ``` And I realized today that this is a bad idea, for example, if I want to change something from the top or bottom sections, I need to write a shell script to do it. (Not that that's hard, it just seems like it's very bad code wise). So what I want to do, is have one outer python script that is like this: ``` Top piece of code Dynamic function that calls the middle piece of code (based on a parameter) Bottom piece of code ``` And then every other python file in the folder can simply be the middle piece of code. However, normal module wouldn't work here (unless I'm mistaken), because I would get the code I need to execute from the arguement, which would be a string, and thus I wouldn't know which function to run until runtime. So I thought up two more solutions: 1. I could write up a bunch of if statements, one to run each script based on a certain parameter. I rejected this, as it's even worse than the previous design. 2. I could use: os.command(sys.argv[0] scriptName.py) which would run the script, but calling python to call python doesn't seem very elegant to me. So does anyone have any other ideas? Thank you.
In addition to the several answers already posted, consider the [Template Method](http://books.google.com/books?id=Q0s6Vgb98CQC&pg=PT267&lpg=PT267&dq=martelli+template+method&source=bl&ots=hc5X54RluF&sig=Szn0KupOXlKH4P7DqCcr2N9odOI&hl=en&ei=ThdeTN7aNJD4sAOmt92rCw&sa=X&oi=book_result&ct=result&resnum=2&ved=0CBcQ6AEwAQ#v=onepage&q=martelli%20template%20method&f=false) design pattern: make an abstract class such as ``` class Base(object): def top(self): ... def bottom(self): ... def middle(self): raise NotImplementedError def doit(self): self.top() self.middle() self.bottom() ``` Every pluggable module then makes a class which inherits from this `Base` and must override `middle` with the relevant code. Perhaps not warranted for this simple case (you do still have to import the right module in order to instantiate its class and call `doit` on it), but still worth keeping in mind (together with its many Pythonic variations, which I have amply explained in many tech talks now available on youtube) for cases where the number or complexity of "pluggable pieces" keeps growing -- Template Method (despite its horrid name;-) is a solid, well-proven and highly scalable pattern [[sometimes a tad too rigid, but that's exactly what I address in those many tech talks -- and that problem doesn't apply to this specific use case]].
Importing a module (as explained in other answers) is definitely the cleaner way to do this, but if for some reason that doesn't work, as long as you're not doing anything too weird you can use [`exec`](http://docs.python.org/py3k/library/functions.html#exec). It basically runs the content of another file as if it were included in the current file at the point where `exec` is called. It's the closest thing Python has to a `source` statement of the kind included in many shells. As a bare minimum, something like this should work: ``` exec(open(filename).read(None)) ```
I am trying to use the Stripe SDK in my iOS App but there seems to be a problem. Whenever I try to import it like this: ``` #import "Stripe.h" ``` I get the following error: ``` Stripe.h file not found ``` But I have the file right here: ![enter image description here](https://i.stack.imgur.com/3ihrd.png) Thanks in advance, Abdullah Shafique
The folders are blue in Xcode, indicating that the folders themselves have been added as resources, rather than the source files within them. You should remove the stripe-ios folder from your project, and re-add it, ensuring that you choose the option to "Make groups for any added folders"; this will ensure each source file is added to your project, rather than the folder being added to your resources.
I can only speculate what the problem is, but I guess the .h file is just in the wrong directory... So, find a .h file in your project that you CAN import. In which directory is this file? In which directory is the Stripe.h file? Is it even in a subdirectory of the project root?
I have been unemployed for a year. Over the last ~10 years I have worked as a software developer, then a mathematical modeller, then back to software developer. These were all fixed term contracts, except for my very first job. My last contract ended March 2020 and by the end of it I absolutely loathed software development and definitely do not want to go back to it. Since then I have been applying for *mathematical modeller* / *data scientist* type roles at getting nowhere. Most of the time I don't get an interview and when I do I'm rejected. The feedback I get is usually along the lines of *"you were a strong candidate, but we went with someone with more experience"*. On a couple of occasions they have asked if would like to re-interview for a backend software developer type position. I politely decline. Over the last year, I've done a lot of online courses on data analysis, statistics, scientific computing *etc.*. But I'm not sure how legitimate employers think they are versus more traditional qualifications. I am in the UK, so quite a lot of my applications go through recruitment agencies, who, as far as I can tell, do not send my applications forward (probably with good reason). I have been more successful when applying to companies directly, in those cases I usually get interviews, or at least feedback explaining why I was rejected. I am applying for entry-to-mid level positions, since I have worked in this field before and have transferable skills from my time a software developer. I am 37, have a PhD in STEM subject. I know my CV looks terrible, but is there anything I can do to improve my chances?
> > **Over the last ~10 years** I have worked as a software developer, **then a mathematical modeller**, then back to software developer. > > > Now, it is obviously important how much time out of the ~10 years you were a mathematical modeller. Seven years is one thing, three months is another. Even if I went to the extremes a bit, you get my point. If the time you spent actually being a mathematical modeller was closer to the "irrelevant" side, then you need to analyze your options from that point of view. Everything is NOT lost, just a bit more difficult. --- > > **I know my CV looks terrible**, but is there anything I can do to improve my chances? > > > Well, that is the excellent attitude to make you undesirable for pretty much any job. You do not even need to say that during the interview. Just think it. Just store it in the hidden parts of your memory. The interviewer (especially if they are experienced) will read that low self-evaluation, and treat you accordingly. Example from my own life: my experience is mostly about software engineering for automotive. I have done may things around that subject, there was a long time. However, once I wanted to switch jobs, and I found a position as a software "guy" to work (employed) on improving and maintaining some open-source compiler for some processor, under Linux. Obviously, a job very far from my experience. I went to the interview knowing very well my value and my abilities, and my willingness to get involved and learn and improve. When I knew some answer, I went ahead and provided it. Because my specific experience was practically zero, I did not know several answers, and I openly admitted to that. At the end, I pretty much got the job. I did not accept it, simply because I moved to another job, more compatible with my personal needs and priorities at that time. So, the conclusion: know yourself, do not let your limits define who you are. Redefine yourself, push your limits. "Boldly go where no-one has gone before!" --- > > On a couple of occasions they have asked if would like to re-interview for a back-end software developer type position. **I politely decline.** > > > That is another thing you can improve. Do not let opportunities fly by you. There are not many companies who need a mathematical modeller. If such a company wants to hire you, then find a way to turn the situation in your favor. Try an approach along these lines: > > *Being a (back-end developer) is not my first priority. However, I am willing to make a gradual transition, in a way that covers both our needs, to end-up with a win-win situation. I propose that I start doing (80% ?) a back-end job, and (20% ?) mathematical modelling. We evaluate my performance as a mathematical modeller in (one ?) year, and if it is satisfactory, then we review my work allocation, targeting 100% work as a mathematical modeller.* > > > This approach gives you the huge benefit of accumulating experience as a mathematical modeller - something that is in your target. Even if this job is not very good, the next one might be a lot better - you will start from a different (better) starting point. --- > > Most of the time I don't get an interview **and when I do I'm rejected**. > > > Again, you concentrate on the failure. What you need to see from this is that actually **you were accepted for an interview**. That is already a big win. It means that the company already sees potential in you. You just need to convince them. I will not repeat the good advice from **@Old\_Lamplighter**. But I will give you another example which actually helped me in my personal life (although not really in the direct way). Watch the movie "Hitch" (2005) with Will Smith and understand all the advice "The Doctor" gives to his customers. Once "she" said "yes", you move forward. Do not make efforts to improve a "yes". Of course, you will understand that in your case the love (or the woman) is actually the job you are targeting. Not really everything will apply ;) --- > > **have a PhD** in STEM subject > > > While some companies are happy to have people with degrees, many companies treat such people with a cold shoulder. Search for the subject of "over-qualification". When I first heard about it, I thought it was a joke, but in time I understood that it was actually a thing. What you might want to try is to not advertise your PhD. See what happens. If they require a PhD and they are on the verge to reject you for not having the title, just then show them that you have the needed qualification. If asked why you kept the information hidden, just say that you did not keep it hidden. You just did not consider the title very important for the job - and admit that you were a bit wrong, using a smile. --- Sometimes it will help if you study the company before the interview. See what they do, what they advertise. See where you might have a contribution. If they have people which appeared in the media or in scientific journals, study what they did. Analyze yourself and see if you fit in their projects. See where they are stuck with their work (this information is often written in plain words, both in the media, and in the scientific articles). If you have an idea to help, contact these people and see if they are willing to listen. If yes, your chances for a job are dramatically increased. --- Other than these, I wish you good luck and success.
Full disclosure, I taught classes on this subject, and experienced it personally. First of, as you've found there is no substitution for experience. The best way to get that experience when you're not working is to do volunteer work, or independent, or freelance work, or any combination thereof. Also, bring your CV to a friend who is IN the field you are wanting to transition into and see if they can tell you what you are doing right and what you are doing wrong. Buy (and read) tools on closing sales, they can do wonders for helping you interviewing. To start getting your foot in the door, ask friends, family, acquaintances for HELP (not a job, HELP) in learning about the field. It is important that you use the words "help" and "learning" as opposed to needing or finding a job. People are willing to help you learn, but floating your CV, not so much. Also, you can ask your contacts if they know anyone who would be willing to sit down and tell you a bit about the field. This helps you to make professional contacts in the field, and getting your name and face out there. For those extended contacts, you want to ask for **advice** not a job. Again, this is a psychological game. You're getting face-to-face meetings and you are showing them your resume and expressing your interest. Worse case scenario, this new contact will be able to advise you, best case scenario, you could get a job lead. You need to be very creative and driven to be able to make a career change, but steps like these will demonstrate your ambition. People naturally want to help someone who is trying.
I have a registration form and I want to validate an email in simple and shorter way. Right now I am doing email validation as like below with long regex. ``` import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; const emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; export default class Register extends Component { constructor(props) { super(props); this.state = { emailError: '', email: '' }; } handleTouchTap = () => { if(this.state.email == '' || this.state.email == null){ this.setState({ emailError: "Email cannot be empty" }); } else if (!emailPattern.test(this.state.email) && this.state.email.length > 0) { this.setState({ emailError: "Enter a valid email" }); } }else{ let data = {}; data.email = this.state.email; // this.props.registerUser(data); } }; changeEmail = (evt) => { this.setState({ email: evt.target.value }); } render() { return ( <div> <div className="module row" style={{display: 'flex'}}> <section className="section"> <h1>Create an account</h1> <h3>It's free and always will be!</h3> <imports.TextField errorText={this.state.emailError} floatingLabelText="Email" hintText="Enter your email" value={this.state.email} onChange={this.changeEmail} name="email" /> </section> <section className="section"> <div className="feature-link-carousel-cell"> <a href="https://www.glassdoor.com/blog/do-race-gender-play-a-role-in-salary-negotiations/" data-ga-category="homepage" data-ga-lbl="marketing-whatsnew" data-ga-action="whats-new-click"> <img width="960" data-original="https://media.glassdoor.com/home/feature-link/reviews/iStock_81884597_MEDIUM.jpg" className="lazy lazy-loaded" src="https://media.glassdoor.com/home/feature-link/reviews/iStock_81884597_MEDIUM.jpg" alt="Do Race &amp; Gender Play a Role in Salary Negotiations? A New Study Says Yes" style={{opacity: 1}}> </img> </a> </div> </section> </div> </div> ); } } ``` * Is there any simplest and shortest way of validating an email in React? * Are there any shorter ways with **ES6**?
I use this simple util function in my own projects: ``` function validateEmail (email) { const regexp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return regexp.test(email); } ``` This is done with [Regular Expression](https://regexr.com/) and will return `true` if the input is constructed like this: `username@domain.com`
This really is the simplest way to validate email <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email> But, since you are using material ui component, regex should do the trick
I am trying to write a test for ensuring that an invalid instantiation I am doing produces an exception. The test is as follows: ``` describe('Dialog Spec', function () { "use strict"; it("should throw an exception if called without a container element", function () { expect(function() { new Dialog({}); }).toThrow(new Exception("InvalidArgumentException", "Expected container element missing")); }); }); ``` The Dialog() class: ``` function Dialog(args) { if (undefined === args.containerElement) throw new Exception("InvalidArgumentException", "Expected container element missing"); this.containerElement = args.containerElement; } } ``` I'm getting the following failure in jasmine. ``` Expected function to throw Exception InvalidArgumentException: Expected container element missing , but it threw Exception InvalidArgumentException: Expected container element missing ``` My Exception class: ``` function Exception(exceptionName, exceptionMessage) { var name = exceptionName; var message = exceptionMessage; this.toString = function () { return "Exception " + name + ": "+ message; }; } ``` What am I doing wrong?
The assertion for exception only works with when used with the Javascript in-built Error class instance. I was using my own defined Exception() class and that was the cause of the issue.
I would split this into multiple tests. ``` describe("creating a new `Dialog` without a container element", function() { it("should throw an exception", function () { expect(function() { new Dialog({}); }).toThrow(new Exception("InvalidArgumentException", "Expected container element missing")); }); describe("the thrown exception", function() { it("should give a `InvalidArgumentException: Expected container element missing` message", function () { try { new Dialog({}); expect(false).toBe(true); // force the text to fail if an exception isn't thrown. } catch(e) { expect(e.toString()).toEqual("InvalidArgumentException: Expected container element missing"); } }); }); }); ```
As mentioned in opamp datasheets, like [this](http://www.ti.com/product/opa656) one. I would think stability is a problem at higher gains, due to oscillation. What are the problems with unity-gain?
Stability doesn't only depend on gain, but also phase. If an inverting amplifier has a 180° phase shift total phase shift is 360°, and one of the *Barkhausen criteria* for oscillation is met. > > Amplifiers differ in their ability to be stable even if the external > circuitry is optimum. To evaluate the stability potential for a > particular amplifier type, graphic data is required for both "gain vs > frequency" and "phase vs frequency" of the open loop amplifier. If > the phase response exhibits !180E at a frequency where the gain is > above unity, the negative feedback will become positive feedback > and the amplifier will actually sustain an oscillation. Even if the > phase lag is less than !180E and there is no sustained oscillation, > there will be overshoot and the possibility of oscillation bursts > triggered by external noise sources, if the phase response is not > "sufficiently less" than -180° for all frequencies where the gain is > above unity. The "sufficiently less" term is more properly called > **phase margin**. If the phase response is -135°, then the phase > margin is 45° (the amount "less than" -180°). Actually, the phase > margin of interest to evaluate stability potential must also include the > phase response of the *feedback circuit*. When this combined phase > margin is 45° or more, the amplifier is quite stable. The 45° number > is a "rule of thumb" value and greater phase margin will yield even > better stability and less overshoot. > > > Often, but not always, the *lowest* phase margin is at the *highest* > frequency which has gain above unity; because there is always some > delay independent of frequency which represents more degrees at > higher frequencies. An amplifier with 45E phase margin at the higher > frequency of unity open loop gain is said to be "unity gain stable". > Optionally, most amplifier types can be compensated for unity gain > stability at some sacrifice in slew rate or high frequency noise. If > stability is considered to be of high priority, the tradeoff must be > made. Unity gain stable means stable operation at the lowest closed > loop gain where stability is usually worst. > > > *(from [here](http://www.jensen-transformers.com/resources/some-tips-on-stabilizing-op-amps/an001/#main))* **Further reading** [Why Unity Feedback is Most Difficult for Stability?](https://web.archive.org/web/20110414133216/http://seit.unsw.adfa.edu.au/staff/sites/hrp/research/helpfulnotes/whyUnityMostDifficult.html)
Negative feedback stabalises amplifiers while positive feedback destabalises them. Due to parasitic resistance and capacitance an amplifier inevitablly ends up acting as a lowpass filter. This means that in addition to attenuation there is a phase shift. The more stages an amplifier has the more potential there is for phase shifts. The frequency response of an amplifier with two or more stages (i.e. pretty much all op-amps) will contain multiple break frequencies. Arround each break frequency the phase shift increases. After the first break frequency there is about 90 degrees of phase shift, after the second break frequency there is about 180 degrees of phase shift (and so-on but we really only care about the first two). A 180 degree phase shift turns negative feedback into positive feedback. That's a problem. If the "loop gain" of the feedback path at that point is one or more than the amplfier will oscilate. So we have to engineer our amplifiers so the gain in the feedback loop drops to less than one before the second break frequency is reached. OP-AMP manufacturers do this by deliberately adding capacitance (known as "compensation") to thier amplifiers to reduce the frequency of the first breakpoint and hence reduce the gain at the second breakpoint. Of course this reduces the bandwidth of our amplifier. But the gain in the feedback loop depends not only on the amplifier but also on the feedback divider. The higher closed loop gain of your amplifier the lower the gain in the feedback loop. The non-inverting unity gain amplifier is the worst case as it feeds back 100% of the output to the input. So low gain amplifiers need a large compensation capacitance than high gain ones. So makers of high speed op-amps give you the choice. Sometimes this is done by having different models of amplifer for low and high gain applications. Sometimes (for example on the AD8021) this is done by fitting the compensation capacitor externally.