INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Vim Join opened Html tags to same line So I've started using snippets with vim, now sometimes I like the closing tag to be put on a newline but other times I like the closing tag to be on the same line. After typing a html tag and pressing the autocomplete key it's formatted as shown below, with the cursor position shown by the caret symbol <td> ^ </td> Currently, if I want both tags on the same line I have to move the cursor up a line and repeatedly hit Shift+J to join the lines, but this takes multiple key strokes Is there a fast way (without moving the cursor from it's current position), to join the two lines together to look like, from the above code snippet <td>^</td>
You can utilize Vim's built-in _inner tag_ text object to delete (`dit`) or change (`cit`) the whitespace / text inside the tags. (This assumes the tags are indented; without indent, you still need a `J` to join the end tag to the current line.)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "html, vim, code snippets" }
Windows Phone 7- Set an Image source to a stream in memory Is it possible to set the source of an image in WP7 to a stream? Normally I'd use BitmapImage to do this in Silverlight but I don't see that option in WP7. Here's my code: var request = WebRequest.CreateHttp(" request.Credentials = new NetworkCredential("user", "password"); request.BeginGetResponse(result => { var response = request.EndGetResponse(result); var stream = response.GetResponseStream(); // myImage.Source = ?? }, null); The reason I ask is because I need to provide credentials to get the image - if there's another way to approach the problem I'm open to suggestions.
Yes, use this code: var bi = new BitmapImage(); bi.SetSource(stream); myImage.Source = bi;
stackexchange-stackoverflow
{ "answer_score": 21, "question_score": 3, "tags": "c#, image, windows phone 7, stream" }
Computing derivative of parametric equation This is probably a silly question but I am just not sure if I understand what to do. So I have the parametric equations: $x=6\cos (t)-2\\\ y=5\sin (t)+3$ I am asked to compute $\dfrac{dy}{dx}$ at the point $(3\sqrt{2}-2, 3-\frac{5}{\sqrt{2}})$ So $$\frac{dy}{dx}=\frac{\frac{dy}{dt}}{\frac{dx}{dt}}\implies\frac{dy}{dx}=-\frac{5\cos(t)}{6\sin(t)}$$ Now where do I plug the above numbers in to find $\dfrac{dy}{dx}$? Am I on the right track?
**Hint:** $\cos t = \dfrac{x+2}{6}$, and $\sin t = \dfrac{y-3}{5}$
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "derivatives, parametric" }
Maximum value in 2D array (Processing) I would like to find the maximum value within an array of integers (in Processing). I am familiar with the max() command, but it appears to only work for one-dimensional arrays. Does anybody have suggestions as to how I could efficiently find the maximum for a two-dimensional array?
No idea what language you're using, but you could translate this to your language: function findMaxOfArr(arr) { var rowMax=[]; for (var i=0; i<arr.length; i++) { rowMax.push(max(arr[i])); } return max(rowMax); } It first finds the maximum value of each row and stores it in a new array, then it finds the maximum value of that and returns it. You get the idea.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "arrays" }
Nested IFF query in MSAccess returning wrong number of arguments I am trying to write a nested IFF query in MSAccess, but on running the error returned is "Wrong number of arguments" My two fields Paper1 and Paper2 are of datatype True/False The Query I wrote in DesignView is Feedback: IIf([Paper1],"No comment","", Iff([Paper2],"No comment","")) If Either Paper1 or Paper2 is True then I would like to return "No Comment" otherwise show nothing
The correct condition: `Iif (paper1 or paper2,"no comment","")`
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "microsoft access, sql, query" }
Is there a way to view the register contents of one thread from another thread within the same process? Let's say I have a process that contains three threads: A, B, and C. I want to use thread A to pause thread B, examine thread B's register values/stack contents, and then feed some of that information from thread B into thread C (via thread A). According to this post from Linus Torvalds, the `ptrace` syscall won't work here because the threads are within the same process. Is there another way of accomplishing this? Update: this question discusses _why_ it doesn't work; I'd like to know if a work-around exists that doesn't involve creating a child process.
You might be able to work around this using a signal. Pick an otherwise unused signal, eg `SIGUSR1` and install a signal handler for it using the `sa_sigaction` member of `struct sigaction` and specifying the `SA_SIGINFO` flag. Block the signal in every thread except the thread of interest (thread B). When you want to examine thread B, send a thread-directed signal to it using `pthread_kill()`. The signal handler will then fire, and its third argument will be a pointer to a `ucontext_t` structure. The `uc_mcontext` member of this structure is a machine-dependent `mcontext_t` structure, which will contain the register values at the point that the thread was interrupted. You then just need to devise a safe way to pass these values back to thread A.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "c, linux, multithreading, pthreads, ptrace" }
Pixel based Correlation for 2 Rasters I was working with Pollution data from OMI i.e. NO2 & O3. I need to find the correlation between the two rasters. I need pixel-based correlation, but in ArcGIS Pro, I could only find point-based correlation. How do I do pixel-based correlation for the rasters?
Download and install latest QGIS with GRASS GIS. The tool is r.covar under the GRASS tools. It outputs the covariance/correlation matrix.
stackexchange-gis
{ "answer_score": 0, "question_score": 0, "tags": "raster, arcgis pro, correlation" }
Extract text from light text on withe background image I have an image like the following: ![Image to be processed]( and I would want to extract the text from it, that should be `ws35`, I've tried with **pytesseract** library using the method : pytesseract.image_to_string(Image.open(path)) but it returns nothing... Am I doing something wrong? How can I get back the text using the OCR ? Do I need to apply some filter on it ?
Similar to @SilverMonkey's suggestion: Gaussian blur followed by Otsu thresholding. ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, image processing, tesseract, python tesseract" }
How do I save a specific set of class of images in JavaScript? There's a class called "original-image", which are img elements. I want to know how to save the src value of ALL of the "original-image" class elements locally. This is the code: <img title="Pirate Queen" alt="Pirate Queen" class="original-image " src=" I'm trying to save the src of this element onto my hard drive, but for all of the elements of the "original-image" class on the page. How do I do this?
Be happy with your hacking and buy my a beer.... We are going to use "download" attribute from html5 and make an autoclick, image by image $(".original-image").each(function(){ //Current image tag $this = $(this); //Current url $current_url = $this.attr('src'); //Dynamic anchor $shadow_anchor = $('<a id="super_shadow_anchor" download href=' + $current_url +'></a>'); $('body').append($shadow_anchor); setTimeout(function(){ //Native click, jquery's click do not work $("#super_shadow_anchor").get(0).click(); //remove the anchor`enter code here` $("#super_shadow_anchor").remove(); }, 500); }); Edit: try it in HTML5 browser
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, image, save" }
Excel formula: Reduce vector to unique values Excel 2013. I have a column-vector of several values, some are unique, others not, for example `A1:A7`: 981 981 19018 8313 8842 8842 8314 I'm looking for a formula that I can paste down another column that results in: 981 19018 8313 8842 8314 I've found a similar question How to filter unique values in a column using excel formula, but the solution didn't work for me (and I didn't really understand the formula)
First of all `Data>Remove Duplicates` works as a charm. However, if you want something that will be in formula form (given that your values are in range `A1:A7`) use this formula in `B2`: =IFERROR(INDEX($A$1:$A$7,MATCH(0,COUNTIF(B$1:B1,$A$1:$A$7),0)),"") This is an array formula that is applied with `Ctrl` \+ `Shift` \+ `Enter` instead of usual `Enter`. Now you can drag this formula until you get empty values. This will, basically, return the value from range `A1:A7` if it hasn't returned it already, and once it has exhausted all the values it returns blank cells.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "excel, excel formula" }
Как нарисовать линию в андроид? У меня есть несколько TextView, после каждого из них нужно нарисовать черную линию горизонтальную?
Горизонтальная линия: <View android:layout_width="match_parent" android:background="@color/colorLine" android:layout_height="1sp"/> Вертикальная линия: <View android:layout_width="1sp" android:background="@color/colorLine" android:layout_height="match_parent"/>
stackexchange-ru_stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "android" }
Pointer function confusion C++ I'm working my way through Jumping into C++ and I just reached the sections on pointers and consequently, my first wall. I'm trying to solve this problem: **Problem 13.4** Write a function that takes two input arguments and provides two separate results to the caller, one that is the result of multiplying the two arguments, the other the result of adding them. Since you can directly return only one value from a function, you'll need the second value to be returned through a pointer or reference parameter. I just don't understand the question really. I need to write a function, for example: int function(int x, int y){ int addition = x + y; int multi = x * y; } But I since I don't fully understand the question I don't know how to fit in pointers. If anyone can dumb it down for me I would be grateful. Thanks for your time!
You can try int functionPtr(int x, int y int* addition) { // As JustSid mentioned in the comment, it would be good to check the pointer first if (addition) { *addition = x + y; } return x * y; } Or int functionRef(int x, int y int& addition){ addition = x + y; return x * y; } And when you want to call them int x = 1; int y = 2; int addition1 = 0; int multi = functionPtr(x, y, &addition1); int addition2 = 0; int multi = functionRef(x, y, addition2);
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c++, pointers" }
Perspective Raytracing Given the up and focal vector of the perspective camera, the position of the camera and the vertical and horizontal opening angle of the FOV. How can I calculate a ray for given screen space coordinates (x, y) where x, y are between -1 and 1 (inclusive). I tried this: 1) Calculate the vectors sx, sy that span the image plane sy = -norm(up) sx = norm(cross(focal, sy)) 2) Calculate the focal length f f = 1 * sin(90 - vertical) / sin(vertical) 3) Create the ray dir = (center + x * sx + y * sy + f * forward) - center r(t) = center + t * norm(dir) But the resulting image does not turn out like the reference image. Someone know what I am doing wrong?
Let the horizontal FOV be given as theta (in radians), and the vertical FOV be given as phi (in radians). The we know that: $$\tan\frac{\theta}{2}=\frac{w}{f}, \tan\frac{\phi}{2}=\frac{h}{f}$$ Let us pick $f = 1$, then $w = \tan\frac{\theta}{2}, h = \tan\frac{\phi}{2}$. Now your ray generation direction generation formula looks like: $$\pmb{d} = x w\pmb{u} + yh\pmb{v} + \pmb{w}$$ Where $\pmb{u},\pmb{v}, \pmb{w}$ are your sx,sy, forward vectors. Essentially, I found the extent of the smallest/largest x and y respectively ($1w = w, -1w=-w$, etc.). You can premultiply $\pmb{u}, \pmb{v}$ with $w, h$ respectively, if you don't want to perform the multiplication per ray.
stackexchange-computergraphics
{ "answer_score": 1, "question_score": 0, "tags": "raytracing, camera" }
keySet field in HashMap is null I am trying to loop over a `HashMap` with the `keySet()` method as below: for (String key : bundle.keySet()) { String value = bundle.get(key); ... } I use a lot of for-each loops on HashMaps in other parts of my code, but this one as a weird behavior: its size is 7 (what's normal) but `keySet`, `entrySet` and `values` are `null` (according to the Eclipse debugger)! The "bundle" variable is instantiated and populated as follows (nothing original...): Map <String, String> privVar; Constructor(){ privVar = new HashMap<String, String>(); } public void add(String key, String value) { this.privVar.put(key, value); }
What do you mean by `keySet`, `entrySet` and `values`? If you mean the internal fields of `HashMap`, then you should not look at them and need not care about them. They are used for caching. For example in the Java 6 VM that I use `keySet()` is implemented like this: public Set<K> keySet() { Set<K> ks = keySet; return (ks != null ? ks : (keySet = new KeySet())); } So the fact that `keySet` is `null` is irrelevant. `keySet()` (the method) will never return `null`. The same is true for `entrySet()` and `values()`.
stackexchange-stackoverflow
{ "answer_score": 20, "question_score": 9, "tags": "java, collections, dictionary, hashmap" }
Visual Studio 2015 Error 500.19 I have problem with opening project in VS 2015. In VS 2012, and VS 2013 is everythink ok. But when I start web application in VS 2015, I got error 500.19 while loding css and js files. I know, that it shoud be because of permissions, so I set NETWORK, NETWORK SERVICE and IIS_IUSRS to read, write, modify on my project folder, but it did not help. Have anyone idea?
Finally I can handle with it. I just need to remove from my web.Config <staticContent> <mimeMap fileExtension=".less" mimeType="text/css" /> </staticContent >
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 5, "tags": "iis 7, visual studio 2015" }
Piecewise from Rational Absolute Value Function How would one separate a function like the following into piecewise? $$f(x)={\left|4-x\right|\over{\left|x-4\right|}}$$ I've been taught that with a rational function with an absolute value in the numerator only, one does the following: $$g(x)={{\left|4-x\right|\over{x-4}} = \begin{cases}{4-x\over{x-4}} & x<4 \\\ {-(4-x)\over{x-4}} & x>4 \end{cases}}$$ Eventually, of course, the pieces would be simplified, but I'll leave it like that for simplicity's sake. Meanwhile, with an absolute value over an absolute value, I can't find the correct piecewise. When I take the limit of the function, I should get the answer $1$, but I can't do so without graphing the problem. Is there any way to create a correct piecewise version of this function?
You’re making it much too complicated. No matter what $x$ is, $4-x=-(x-4)$, so as long as $x\ne 4$, $$\frac{4-x}{x-4}=-1\;,$$ and therefore $$\left|\frac{4-x}{x-4}\right|=|-1|=1\;.$$ Of course the expression is undefined when $x=4$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "algebra precalculus, absolute value, rational functions" }
Does QC convergence mode in Gaussian make a difference? I have been using Gaussian16 por metal complexes SCF single-point calculations involving triplets to investigate phosphorescence. I have actually run into trouble (very long computational time, even with 36 processors and quite a lot of memory) when using the regular SCF convergence criterion as default in the code. As a result from that, I thought of using the QC keyword, which made the calculations much faster and successfully converged. However, I am not sure if there is evidence on the effect of such an approximation or the lack of accuracy that might be obtained. I have also thought of using XQC keyword, which would make me able to run regular SCF procedure up to a number of cycles and then switch to QC. How safe am I when using QC? Am I losing a lot of accuracy, in general, when compared to the regular SCF procedure?
The **SCF=QC** keyword in Gaussian actually pertains to the choice of algorithm on how find the solution in the SCF procedure while **SCF=Tight** is an option related to SCF cycle convergence. Gaussian SCF criterion depends on density matrix changes, consequently in energy. So using QC algorithm should not cost accuracy if the convergence criterion is the same. If you refer to Gaussian website, you will see **SCF=TightLinEq**. They described this option as having 'tight' convergence throughout QC algorithm which I think makes this a safe choice. I am also sharing the link to Gaussian SCF page for future reference.
stackexchange-materials
{ "answer_score": 5, "question_score": 7, "tags": "gaussian, convergence test" }
Should I use "at soonest" or "as soonest"? My sentence goes like this: "Please let us know **at soonest** if you can help us." Is it correct? And, if yes, is "as soonest" a possible alternative? Thanks in advance.
Soonest is used to say 'as quickly as is reasonable', it is the superlative form of the word of soon. (soon -> sooner -> soonest). "As soon as possible" is what you should use: > Please let us know **as soon as possible** (or as early as possible) if you can help us. Usage in a response: > I don't know for sure, the **soonest** I can know is later this evening. OR > The **soonest** possible time I can let you know is at 5 pm. You may hear someone say to someone else **"see you soonest"** but it's colloquial and what they mean is **"see you in a flash"** or **"see you as soon as I can"** or **"see you very soon"**.
stackexchange-english
{ "answer_score": 3, "question_score": 2, "tags": "phrases" }
General transformation matrix I am currently working through some of my maths assignment, and i have this question, and i can't work out what it means, and i am sure there is something to missing which would make this question make more sense, here is the question: > What is the general transformation matrix for a rotation of angle $\theta$ about the origin? That is all the questions says, any one able to help me out, who may understand it better then me?
The map which rotates any vector in the plane an angle $\theta$ around the origin is a linear map. Hence it can be given by multiplication by a matrix. What is this matrix?
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "matrices, transformation" }
method_missing Within instance_eval Full code: < class Options def method_missing(method, *args, &block) p method end end options = Options.new options.instance_eval do foo foo = "It aint easy being cheesy!" end puts "#===---" options.foo options.foo = "It still aint easy being cheesy!" This returns: :foo #===--- :foo :foo= Because it is treating `foo = ""` as a local variable within instance_eval, it's not recognize it as a method. How would I make instance_eval treat it as a method?
The expression `foo = ""` will never be a method call. It is a local variable assignment. This is a fact of Ruby's syntax. In order to call a setter, you have to specify a receiver explicitly. This is why most Ruby pseudo-DSLs use the Dwemthy-style: class Dragon < Creature life 1340 # tough scales strength 451 # bristling veins charisma 1020 # toothy smile weapon 939 # fire breath end That avoids the equals sign problem.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "ruby" }
Partial match fetch I want to perform `partial match` like the clause `LIKE` do in `SQL`. In Magical Record, to look for values for a specified field, we use `findByAttribute`: NSArray *productsFoundByTitle = [Product MR_findByAttribute:@"product_title" withValue:@"bags"]; The problem is that this will return only `exact matches` of `bags` in `product_title`. I want to return also `partial matches` so a value like : `mail bags` would also be returned. How can I do that in MagicalRecord?
Best solution I came with so far is the following: Grap all data, and find all `Partial matches` with `rangeOfString` function: NSArray *allResults = [Product MR_findAll]; for (id element in allResults) { if ([[element valueForKey:@"product_title"] rangeOfString:@"bags" options:NSCaseInsensitiveSearch].location != NSNotFound) { //I got a partial match, save this instance for later use } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "magicalrecord" }
Prove the following statement - Show that in an abelian group the product of two elements of finite order is itself an element of finite order. I need some hint to start with, I am familiar with the basic
$(ab)^n = a^nb^n$, so take $n = lcm(|a|,|b|)$
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "group theory" }
How do I deal with Warrior stuns? Warriors (hammer-using Warriors in particular) seem capable of greatly turning the tables in their favor when they land a Stun on me, typically resulting in me losing about half of my health or more throughout the duration of the Stun. * What should I look out for to prevent being stunned? * If I get stunned, how should I react to avoid their burst? If it matters, I am an Elementalist, which means that my stun break (Armor of Earth) is also my primary source of Stability.
There are three things you can do : * dodge when you see it coming * stability to prevent its effect * stun-breaker when you didn't react in time or have no other options The best way to find out how it looks like is to try it yourself, this way you will know exactly how it looks like. You can create a new character warrior and go to the PvP zone and try it out. If you don't want to go through that, go on youtube ! The main stuns of a warrior are : * a big swing with hammer : Backbreaker * a shoulder dash : Bull's charge * a hit with a shield : Shield bash As an Elementalist you have a number of skills which can break stun : (Credit to DavidYell for adding the elementalist skills) * Arcane Shield * Armor of Earth * Mist Form * Glyph of Elemental Power * Signet of Air P.S. : For PvP I really recommend trying out every class to better understand its mechanics, reading information and guides on it is great, but experience is key!
stackexchange-gaming
{ "answer_score": 5, "question_score": 1, "tags": "guild wars 2" }
jQuery error hander throw is not catched So I have the following ajax query which fails. ajaxError is called and it throws an exception. But unfortunately the exception is not catched. Any ideas how to catch it? try { function ajaxError(request, type, message) { throw 'ajaxerror ' + type + ' ' + message; } jQuery.ajax({ url: ' error: ajaxError, }); } catch (error) { alert('This: ' + error); }
It's because of ajax is asynchronous and when your ajaxError func actually gets called catch block has been already passed. If you want to catch your errors trowed during ajax call you can do something like this: function ajaxError(request, type, message) { try { throw 'ajaxerror ' + type + ' ' + message; } catch (error) { alert('This: ' + error); } } jQuery.ajax({ url: ' error: ajaxError, }); Or you can apply a pub/sub pattern to catch your async errors
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, exception" }
How to hide a checkboxlist based on a dropdown selection using JQuery? I have a form with a dropdownlist. Based on the selected item in the dropdown respective chekbox list appears and other checkboxlist disappears. How can you accomplish this using JQuery?
Here's Javascript that you should be able to easily adapt to your specific elements: $('#dropdownlist').on('change', function () { if ($(this).val()) { if($(this).val() === "some value") { $('#somecheckboxgroup').show(); $('#someothercheckboxgroup').hide(); } else if($(this).val() === "some other value") { $('#somecheckboxgroup').hide(); $('#someothercheckboxgroup').show(); } } }); Essentially, you just want to run a function every time the dropdownlist changes, and in it, check the currently selected value and then run your desired code based on the observed value.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, javascript, jquery, drop down menu, checkboxlist" }
GET min over multiple columns Can someone give me some advice on how I can get the min of values over multiple colums? I'd like to do this without using a subquery if possible. Thanks in advance! something like the function 'least'.
`least` seems to be exactly what you need: SELECT LEAST(MIN(col1), MIN(col2), MIN(col3)) AS minium_of_three_columns FROM my_table
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "database, oracle, plsql" }
what exactly does it mean to not do work in the database if we can do it elsewhere? < > Don't do work in the database if you can do it elsewhere I must say I don't quite understand this statement. Can someone elaborate on it? Does it mean the we should enforce integrity on the application level instead of at the database level? Or does it mean something else completely?
We have no way of knowing. The only person who knows what he meant by that is the author, Baron Schwartz. A quick scan of his slides suggests he isn't an idiot, so I'm pretty sure he doesn't mean enforce integrity in the application not the database. He probably means don't overload the database with other processing that can be done more efficiently elsewhere.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "mysql, sql server, database, offloading" }
Using tf.tile to replicate a tensor N times My current tensor has shape of (3, 2), e.g., `[[ 1. 2.] [ 2. 1.] [-2. -1.]]` I would like to expand to a shape of (1, 3, 2) with each second dimension a replica of the entire tensor, e.g., [[[ 1. 2.] [ 2. 1.] [ -2. -1.]] [[ 1. 2.] [ 2. 1.] [ -2. -1.]] [[ 1. 2.] [ 2. 1.] [ -2. -1.]]] I tried the folllowing code but it only replicate each row instead. tiled_vecs = tf.tile(tf.expand_dims(input_vecs, 1), [1, 3, 1]) Results in [[[ 1. 2.] [ 1. 2.] [ 1. 2.]] [[ 2. 1.] [ 2. 1.] [ 2. 1.]] [[-2. -1.] [-2. -1.] [-2. -1.]]]
This should work, > tf.ones([tf.shape(A)[0], 1, 1]) * A # Achieved by creating a 3d matrix as shown below # and multiplying it with A, which is `broadcast` to obtain the desired result. [[[1.]], [[1.]], * A [[1.]]] Code Sample: #input A = tf.constant([[ 1., 2.], [ 2. , 1.],[-2., -1.]]) B = tf.ones([tf.shape(A)[0], 1, 1]) * A #output array([[[ 1., 2.], [ 2., 1.], [-2., -1.]], [[ 1., 2.], [ 2., 1.], [-2., -1.]], [[ 1., 2.], [ 2., 1.], [-2., -1.]]], dtype=float32) Also using `tf.tile`, we can obtain the same: > tf.tile(tf.expand_dims(A,0), [tf.shape(A)[0], 1, 1])
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 9, "tags": "tensorflow" }
How does Mask R-CNN automatically output a different number of objects on the image? Recently, I was reading Pytorch's official tutorial about Mask R-CNN. When I run the code on colab, it turned out that it automatically outputs a different number of channels during prediction. If the image has 2 people on it, it would output a mask with the shape `2xHxW`. If the image has 3 people on it, it would output the mask with the shape `3xHxW`. How does Mask R-CNN change the channels? Does it have a `for` loop inside it? My guess is that it has region proposals and it outputs masks based on those regions, and then it thresholds them (it removes masks that have low probability prediction). Is this right?
Object detection models usually generate multiple detections per object. Duplicates are removed in a post-processing step called Non-Maximum Suppression (NMS). The `Pytorch` code that performs this post-processing is called here in the `RegionProposalNetwork` class. The filtering loop you've mentioned performs the NMS and applies the `score_thresh` threshold (although it seems to be zero by default).
stackexchange-ai
{ "answer_score": 0, "question_score": 0, "tags": "object detection, semantic segmentation, mask rcnn, non max suppression" }
Filtering on content type gives error No valid values found I was creating a View and found this issue: Filtering on content type gives error No valid values found Even if adding content type in filter correctly.
The issue was: While adding `Content Type` filter, I accidentally selected `All Displays` and as other blocks are also getting the same configuration, the View was throwing error. **Solution:** Gone to other View Displays and removed the Filter unnecessary for them.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, drupal 8" }
calculate each table values using if else condition i have a table value something like this: sellingprice result 51 ? 49 ? if the sellingprice value is greater than 50 this will be the calculation: **sellingprice - 50 * 0.05 + 3.5** and if the sellingprice value is less than 50 the calculation will be: **sellingprice * 0.07;** I am a little bit confused on how to do it in jquery. hope to guide me through this.
$('table tr').each(function() { var sellingPrice = parseInt($(this).find('.sellingprice').val()); var result; if (sellingPrice > 50) { result = sellingPrice - 50 * 0.05 + 3.5; } else { result = sellingPrice * 0.07; } $(this).find('.result').val(result); }); Code: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "jquery, if statement" }
Rails nested resources with pretty URLs for users The data for my application is structured as: * Organizations have users * Organizations have messages * Organizations have sites I would normally use nested resources to do this RESTfully: resources :organizations do resources :users resources :messages resources :sites end Which gives me URLs like: /organizations/12/messages /organizations/12/sites These wordy URLs are excellent for when an admin needs to create a message for an organization because the URL contains the organization ID. **However** , I would like to show normal users pretty URLs such as: /messages /sites Is there a way to alias these pretty URLs to /organizations/{current_user.organization.id}/* ?
You need a way to pass organization id. For example, if you have a user who belongs to organization and the user is signed in, You can get organization id via current_user as following: class MessageController < ApplicationController before_filter :get_organization # ... private def get_organization @organization = current_user.organization end end And, in your routes you can add: resources :messages resources :organizations do resources :messages end There are other solutions but it depends on how you can get organization id.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails, ruby on rails 3" }
pdal truncating values when writing ply When using pdal to either translate to ply file or split a ply file in smaller chunks, it appears to be truncating values so I end up with point clouds with stripping. This does not occur with other formats - but I need .ply in particular. E.g. when splitting up a bigger file.... pdal split --capacity 1000000 in.ply out.ply ... I end up with the result below for the subsets. Are there parameters that may stop this from happening? (See the below pic) ![point cloud with missing values/strips](
This is actually a precision problem where PDAL trim automatically some decimals. You need to control that with this option : `--writers.ply.precision=6f` (it say to the ply writers to have 6 decimals)
stackexchange-gis
{ "answer_score": 1, "question_score": 3, "tags": "point cloud, pdal" }
In django, why get_or_create doesn't work if the items contain ForeignKey The models defines like the following, Cases has multi Keyword as ForeignKeyword, from django.db import models class Keyword(models.Model): name = models.CharField(max_length=32) def __unicode__(self): return self.name class Case(models.Model): name = models.CharField(max_length=32) keywords = models.ForeignKey(Keyword) def __unicode__(self): return self.name If I want to use create get_or_create, it will show that I missed a Keyword_id, like this: case, flag = Case.objects.get_or_create(name = 'case_name', keywords__name = 'keyword_name') got a message: django.db.utils.IntegrityError: dbtest_case.keywords_id may not be NULL
You need to instantiate/get_or_create `Keyword` first: keyword, _ = Keyword.objects.get_or_create(name='keyword_name') case, flag = Case.objects.get_or_create(name='case_name', keywords=keyword) Hope that works for you.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, django, django models, orm, django orm" }
Create a new column and update it with the results of a calculation in Carto My dataset in Carto has columns with subtotals and a column with total - I would like to create a new column with the calculated percentage in Carto - is there a way to do this?
You can use SQL to do this, using the UPDATE function. From either the DATA tab on the layer that uses the dataset you want to change, or from the dataset itself, switch into SQL mode. If you don't already have a column for your results, you can add a new column using either the UI or this SQL: ALTER TABLE <table> ADD <newColumn> float(5) < Then use the UPDATE function like so: UPDATE <table> SET <newColumn>=subtotal/total <
stackexchange-gis
{ "answer_score": 1, "question_score": 0, "tags": "carto, calculate values" }
Render a scene twice but once it renders with an extra object Hi i have a scene with a kitchen and i am using the sky texture and a large volume to create godrays, except to make the scene less noisy i am rendering it twice with two identical scenes but one has this volumetric effect and i am using the compositer to blend the two renders, but i am trying to reduce file size and want to find a way to get rid of the duplicate scene and simply render twice but once have this volume, i believe it is possible as the vfx setup can do this but i have no idea how this works, any help would be perfect
Ok i figured it out, in blender 2.79 they had something called render layers, in 2.8, and 2.9 they use view layers, to do this you will see ticks in the outliner, and unticking them will make them not be rendered, and in the top right there is a section called view layers, if you duplicate them with the same settings you can tick or untick each one and then composite them together
stackexchange-blender
{ "answer_score": 2, "question_score": 2, "tags": "rendering, scene, render layers, compositing nodes" }
How can I elongate the content of table to be justified in the whole page in LaTeX? I am trying to use the `exam` class for preparation of a question paper. At the top of first page, there is a necessity to provide the time, date and max marks. For this, I have created a `tabular` section while centering it as shown in the MWE below. However, I would like the line to be spread throughout the page with even spacing between the columns. How can I achieve this? \documentclass[12pt,a4paper,addpoints,answers]{exam} \begin{document} \begin{center} \Large \textbf{XXX}\\ \large \textbf{XXX}\\ \textbf{XXX}\\ \textbf{XXX} \end{center} \begin{center} \begin{tabular}{ c c c } \textbf{Time: 3 Hours} & \textbf{Date: 07.12.2019} & \textbf{Max. Marks: 100} \end{tabular} \end{center} \end{document}
Do you want something like this? \documentclass[12pt,a4paper,addpoints,answers]{exam} \begin{document} \begin{center} \Large \textbf{XXX}\\ \large \textbf{XXX}\\ \textbf{XXX}\\ \textbf{XXX} \end{center} \textbf{Time: 3 Hours} \hfill \textbf{Date: 07.12.2019} \hfill \textbf{Max. Marks: 100}\\ \hrule % or \hrulefill if necessary. \end{document} I don't think using tabular is necessary for what you want to achieve.
stackexchange-tex
{ "answer_score": 2, "question_score": 2, "tags": "tables" }
QGIS 3.8 not running GRASS I am having trouble initializing the GRASS plugin.I've tried un-installing and re-installing QGIS already. But the following message keeps appearing. GRASS init error : GRASS was not found in '/usr/local/opt/osgeo-grass/grass-base' (GISBASE), provider and plugin will not work.
You need to change the path to a previous working installation. You can use indifferently 3.6 or 3.8 version, GRASS works. QGIS 3.10 does not install GRASS correctly. ![Custom your path]( ![Select GRASS Mapset](
stackexchange-gis
{ "answer_score": 1, "question_score": 3, "tags": "qgis, grass gis" }
How to string Concatenate with 'ENTER' value in php I need a method that concatenate string with enter. As an example my string `"Apple", "Box"`. That string needs to be as: $mynewstring = "Apple Box" Not as: `$mynewstring ="Apple "."\n"."Box"` or `$mynewstring ="Apple "."<br>"."Box"` Please tell how to do this.
Just do like this.. <?php $mynewstring = "Apple,Box"; $arr=explode(",",$mynewstring); echo(implode(PHP_EOL,$arr)); **`OUTPUT :`** Apple Box
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php" }
2 Content Types: Same column name, different choices. Possible? I am trying to set up a number of different content types and have come across a road block. I am trying to create a "Policy Document" content type and a "Training Document" content type. Within each of these I want a column called "Category is", with the input type "Choice". However in each of these content types I need the choices to be different. For example within "Policy Document" I want Internet, Vehicle, Expenses; and within "Training Document", I want Word, Excel, and Powerpoint. Is this possible?
You need to create your columns and your content type declaratively (through xml in a feature) or programatically (console app, event receiver). Like @thantos said both columns can have the same Display name, yet the Internal Name, the Name and the GUID need to be different
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 1, "tags": "2010, content type" }
Integration TortoiseSVN and FogBugz I have read this tutorial Integration SVN and setuped BugzID for the my project. So, Currently I have another problem, My project is in development and may be added new files or modules, how do automatically add BugzID to the new files or modules ? Thanks.
New files and folders below the folder that you ran the script from, will automatically use the same BugzID property. So, it should just work. If you create a new folder that is not a sub-folder of the original folder, then you'd have to run the script on that folder too. Here's an excerpt from the link: "Tortoise will search up your folder path on a checkout looking for this property, so if you checkout from other folders in your tree, be sure to do the same procedure for those folders also."
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "svn, tortoisesvn, integration, fogbugz" }
View a dependency tree in Maven? I'd like to make sure I'm not including duplicate libraries in my Maven project. I'm pulling in quite a few dependencies from a few different repositories including main, Spring's repo, and JBoss' repository. How can I see a graph of the dependencies so I can make sure I'm not depending on multiple versions of a single library? It would be kind of a bummer if I was including something like `org.springframework:spring-core:3.0.1.RELEASE` **and** `org.springframework:org.springframework.spring-core:3.0.5.RELEASE` which actually do show up as different dependencies, as weird as it sounds, because Spring's repository names things weirdly. What can I do to make sure I don't have duplicate dependencies?
The `dependency:tree` maven plugin should do what you want and show the tree. Alternatively force Maven2 to copy dependencies into target/lib to copy the the artifacts in the `target/lib` directory which should also show duplicates but you would still need to grep all the POMs in the `~/.m2/repository` to see which library is pulling in which version manually and that would be time consuming for large local repositories.
stackexchange-stackoverflow
{ "answer_score": 42, "question_score": 26, "tags": "maven" }
Basic Python Code: Turning a phrase into corresponding acronym This is my first post and I would be happy if someone could please explain to me why we need the `result = ""` section in the following Python code. It is a basic piece of code that turns a phrase such as World Wide Web into WWW. def initials(phrase): words = phrase.split() result = "" for word in words: result += word[0].upper() return result
The `result` needs to be initialised because you're adding something to it every iteration of the loop. Consider this bit: for word in words: result += word[0].upper() The `+=` operator takes `result`, adds something on, and assigns it back to `result`. So in your example what's happening every loop is: # Before loop 1 result = "" # After loop 1 result = "W" # After loop 2 result = "WW" If you don't initialise `result`, then the `+=` operator makes so sense on the first iteration.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "python" }
Command not found $ (dollar sign) Any command that starts with `$` returns command not found How can I fix this? I am using 16.10 Ubuntu.
Presumably you are copying and pasting commands from somewhere that look like this: $ sudo apt update The `$` sign is not part of the command at all - it is a commonly used way to indicate that the text following it is a command. Typically here on Ask Ubuntu we use it when we want to indicate "I entered this command, and the output was this". It is an abbreviation of the full prompt we actually see: zanna@monster:~$ $ sudo apt update $: command not found It can also be used to mean (on Ubuntu Forums for example) "run the command as a normal user", not root, because when you switch to root the prompt changes: zanna@monster:~$ sudo -i [sudo] password for zanna: root@monster:~# The `$` is not meant to be entered. The actual command would be sudo apt update
stackexchange-askubuntu
{ "answer_score": 15, "question_score": 3, "tags": "command line" }
Position button in Bootstrap Panel Hi guys i am using bootstrap panel on a page and i want to align button in the `panel-heading` I tried using `padding` but it doesnt work it just stretched the `button` Here is the image of the `panel-group` and in that you can see that the `checkin` button is not aligned properly Let me know which property i can use Thank you ![enter image description here]( And here is the `html` elements of the `panel` ![enter image description here](
Try using `margin` instead `padding`. Update :- Try set your property position to absolute and use Margin. It will work . Regards. it is not advisable to use position absolute. Depends, more info can check here. Is it considered bad practice to use absolute positioning? This is just an example DEMO
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery, html, css, twitter bootstrap" }
Finding the application support directory on OSX in java I would like to store some files in the application support directory is there some system call to retrieve this directory?
I think you will need to use something like this: String applicationSupportDirectory = System.getProperty("user.home") + "/Library/Application Support";
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "java, macos" }
How can I remove line shadows on Live Chart line chart? ![enter image description here]( I created a line chart using a live chart. But I cannot eliminate the shadows (shaded areas in the image) under these lines. LineSeries yeni = new LineSeries(); yeni.PointGeometrySize = 20; yeni.LineSmoothness = 0; // yeni.BitmapEffect. // yeni.PointForeground = System.Windows.Media.Brushes.Transparent; yeni.Title = kisiler[i].ToString(); yeni.Values = new ChartValues<double>(allValues); cartesianChart1.Series.Add(yeni);
This way I solved the problem: yeni.Fill = System.Windows.Media.Brushes.Transparent;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c#, winforms, livecharts" }
Найти элементы на странице и взять их value jquery Подскажите пожалуйста, как я могу найти все `input` в `div` и вывести их значения? <div> <input type="hidden" value="1"> <input type="hidden" value="2"> <input type="hidden" value="3"> </div>
Если с jQuery: $('div input').each(function() { console.log($(this).val()); }); <script src=" <div> <input type="hidden" value="1"> <input type="hidden" value="2"> <input type="hidden" value="3"> </div>
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "html, jquery" }
returning lower number in binary search if value cannot be found I have a list of sorted numbers. `[1,2,4,6,10,12]` I want to find a number within the list. If I cannot find it, I want to return the next lowest number. For instance, `n = 8`. I search for 8 but cannot find it. I will then return 6 because it is the next lowest number. I have some code but I can't seem to get the indexing correct: def search_val(data, n): low = 0 high = len(data) - 1 if data[-1] <= n: return data[-1] if data[0] >= time: return while low < high: mid = (low + high) / 2 if data[mid] == n: return data[n] if data[mid] > n: high = mid -1 if data[mid] < n: low = mid + 1 if data[low] < n: return data[low] else: return data[low - 1]
This will fix all your problems, and should be a little faster: def search_val(data, n): low = 0 high = len(data) - 1 while low <= high: mid = (low + high) // 2 if data[mid] > n: high = mid -1 elif data[mid] < n: low = mid + 1 else: return data[mid] # Now low > high if high >= 0: return data[high] # All values are > n. Just return the first. Could # be changed to return None. return data[0] Note that, in the case where all values are `> n`, it returns the first value. You could of course change it to return `None` instead if desired. Also note that it assumes `len(data)` is `>= 1`. If that isn't always the case, you could add a check at the top and return `None` if `data` is the empty list.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, binary search" }
Is " finished with status: 'crash' " normal for Cloud Functions? I tried Google Cloud Functions with Python and there was a problem with running it. It said: `Error: could not handle the request` I checked the logs, but there was no error, just a log message: Function execution took 16 ms, finished with status: 'crash' When I simplified the function to a printout then it worked properly. Then I added `raise Exception('test')` before the printout to see if the exception is going to Stackdriver Errors, but it didn't, I got the `finished with status: 'crash'` message again only in the log. Is this normal behavior? Or is it a bug and instead of crash I should see the exception as an error in the log?
Quite rightly, as alluded to in the Comments, the crash seems buggy about Google Cloud Functions with Python. The issue was reported to the Internal Google Cloud Functions engineers and evaluation is still ongoing. You can monitor this link for fixes
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 12, "tags": "python, google cloud functions" }
Remove extra quotation marks in the grep output TUNNEL_TCP=$(grep -Po 'http:\/\/([\S]*?)"' ./tunnel_info.json ) the above cammand is used to get an http link example: **www.224.ngrok.io** but the output is say **www.224.ngrok.io"** How can I remove the extra " at the end? I tried editing the " from the grep command but it doesn't work.
You can use positive lookahead: grep -Po 'http:\/\/([\S]*?)(?=")' `(?=")`matches the `"` without making it part of the match.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "regex, linux, bash" }
Owncloud 7 Migration from Ubuntu 12.04 to 16.04 folks, I have a Ubuntu 12.04. Server with Owncloud 7.0.4.2 on it. I want to migrate to a 16.04 machine and then upgrade to oc 9. Updating the old owncloud 7 before migration does not work on ubuntu 12.04. Since I need the same version for migration, I need to install oc 7 on the ubuntu 16.04 server. Unfortunately, this is not possible either because Owncloud 7 needs php5 and there are no installation candidates available on ubuntu 16.04. How can I do this in a proper way? Do I need to migrate it to an ubuntu 14.04 first, then update and then migrate to ubuntu 16.04? Best Greetings **_Update (27.3.17):_** The solution for me was to install php5.6 on the ubuntu 16.04 machine with the ondrej repo (sudo add-apt-repository ppa:ondrej/php).
In short, yes. You should upgrade to Ubuntu 14.04 first, then upgrade again to 16.04. This is the proper way to do things. If you have physical access to the server, you could load 16.04 on a USB drive, boot from it, and then upgrade directly.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "12.04, 16.04, php, migration, owncloud server" }
Is it possible to study solid state from Kittel after taking only one course in quantum mechanics? I have taken only QM I, which is the 1st half of Griffiths including the chapter on identical particles, will that be enough to understand Kittel's solid state? Should one have also taken a course in statistical mechanics before studying Kittel? I have seen in some universities in the states that the prerequisite of an introductory course in solid state physics sometimes are QM I, II, SM, and other times are QM I only (or with SM and QM II are corequisite)
If I recall correctly, most of the material in Kittel (or a solid state introductory lecture) is about new concepts, e.g. lattices, reciprocal space, band structure, and doesn't build heavily on quantum mechanics. Of course, there is QM beneath it, but you don't need much rigorous QM. Basically just the wave mechanics part - solving differential equations, finding a wave function for a given potential, etc., and a basic understanding of how quantum particles behave. For the later chapters, the advanced maths of a QM II course could be helpful if you want to follow the derivations, e.g. calculating complex integrals, residue theorem and so on. But I'm not sure how much of that is actually in the book and how much was in the lectures I heard. The best would be to just grab the book from a library (or an ebook) and browse through it - you'll notice pretty soon if there are any new concepts/notations you have to learn about first.
stackexchange-physics
{ "answer_score": 2, "question_score": 0, "tags": "statistical mechanics, condensed matter, solid state physics, education" }
Why fopen return invalid handle when server returns error When server return any error (401, 405, etc.), fopen return invalid. Is there a way to receive the body of the response?
Use a context (via stream_context_create) and the ignore_errors context option, that " _Fetch the content even on failure status codes._ ": $options = array( 'http' => array( 'ignore_errors' => true, ), ); $context = stream_context_create($options); $handle = fopen(' 'r', false, $context);
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "php, http" }
Variable Width Tilde I wish to define a new macro, `\vartilde` say, so that `\vartilde{a}` produces the following: * `\tilde{a}` while in inline maths mode, ie using `$ ... $`; * `\widetilde{a}` while in display maths mode, eg using `\[ ... \]`. Put another way, I'd like > `$\vartilde{a} = \tilde{a}$` and `\[ \vartilde{a} = \widetilde{a} \]`. One could think of this as a variable width tilde.
I'm not sure it's a good idea. \documentclass{article} \usepackage{amsmath} \newcommand{\vartilde}[1]{\mathpalette\dovartilde{#1}} \newcommand{\dovartilde}[2]{% \ifx#1\displaystyle\widetilde{#2}\else\tilde{#2}\fi } \begin{document} \begin{center}% just to get it above the other one $\vartilde{a}$ \end{center} \[ \vartilde{a} \] \end{document} ![enter image description here]( See The mysteries of \mathpalette for more information about `\mathpalette`.
stackexchange-tex
{ "answer_score": 5, "question_score": 4, "tags": "macros, accents, variable" }
Plugin EditorConfig - Pra que serve? Acessei o site oficial do plugin EditorConfig, não sou muito bom de inglês então tentei traduzir pra ler e não deu muito certo, então não entendi muito bem a funcionalidade dele, ai gostaria de saber: * Pra que ele serve? * Como é usado? * Qual as vantagens que eu ganho utilizando-o?
Ele serve para definir os padrões de edição do seu projeto. Um grande exemplo disso é a forma como seu código é identação. Vamos exemplificar com um caso onde você usa um editor que insere 4 caracteres para identar o código. Você então resolve editar o seu projeto na casa de um amigo, e o editor dele insere 6 caracteres de espaço. O seu código ficaria algo como: //parte feita na sua casa: function codigoFeitoNoSeuEditor(){ console.log("Fiz isso na minha casa maluca."); } //parte feita na casa do seu amigo: function codigoFeitoNoEditorDoMeuAmigo(){ console.log('Fiz isso na casa do meu amigo alienígena'); } Como você pode perceber, houve uma quebra de padrão ao editar na casa do seu amigo. Para podermos fazer essa padronização que serve o editorconfig, nele você define as propriedades de edição que você utilizou, e em qualquer editor que você abra o seu projeto, teremos o mesmo comportamento.
stackexchange-pt_stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "plugin, ide" }
métodos de inyección de DLL en C# Hola estoy aprendiendo sobre patrones de diseño orientado a objetos y uno de los temas que mas me intrigan son los metodos de inyeccion de dependencias. Pero hasta el momento no se exactamente cuales son los metodos mas usados para esta inyeccion. > Cuales son los metodos mas recomendables? Por otra parte, > cuando se hace una inyeccion de una depedencia como se hace para llamar funciones de la misma. Ya que la inyeccion de dependencia no es mas que incluir extensiones a nuestros programas determinados pero no llamadas al mismo.
Buen día, > En informática, inyección de dependencias (en inglés Dependency Injection, DI) es un patrón de diseño orientado a objetos, en el que se suministran objetos a una clase en lugar de ser la propia clase quien cree el objeto. El término fue acuñado por primera vez por Martin Fowler. Después, aquí te dejo un poco de información desde MSDN, la estrategia para desarrollar en C# inyección de dependencia y finalmente unos ejemplos. Es un tema muy amplio la verdad y abarcarlo todo sería muy complejo, pero espero y te ayude la información que te brindo
stackexchange-es_stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, dependencias" }
Getting mouseposition in longitude and latitude in cartopy (python) I am trying to get the mouse position's longitude and latitude using cartopy via the standard matplotlib event handling. But when my button_press_event fires, event.x just gives the pixel position in the figure (as usual) and event.xdata some arbitrary numbers I cant really define, but definately nothing between 180°W and 180°E. So how could I get the longitude/latitude position of the mousecursor in Mercator projection?
Basically this answers the question: Obtaining coordinates in projected map using Cartopy Cartopy apparently does use some other coordinate system when using the Mercator projection. When transforming back to the PlateCarree projection, it transforms the "arbitrary numbers" back into lat/lon pairs.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, matplotlib, event handling, cartopy" }
Python writing urls to a file with BeautifulSoup I am trying to save scraped urls to a text file but the results I find in the file are different from the printed ones. I only find the last set in the file. urls = [" for url in urls: for number in range(1,10): conn = urllib2.urlopen(url+str(number)) html = conn.read() soup = BeautifulSoup(html) links = soup.find_all('a') file= open("file.txt","w") for tag in links: link = tag.get('href') print>>file, link print link file.close()
As you have opened the file in `'w'` (write) mode, the file gets overwritten every time. Open the file in append mode: file = open("file.txt", "a")
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, beautifulsoup" }
SSL connection with CURL (PHP) working on Linux, same code fails on Windows I wrote a script that uses our banks WSDL service, using Nusoap. Requests are signed with certificate. This script works fine on Ubuntu, Apache 2.2, PHP 5.4. When trying to achieve same thing on Windows 7 (64-bit, Apache 2.2, PHP 5.4), I get this error thrown by Curl: **SSL read: error:140940E5:SSL routines:SSL3_READ_BYTES:ssl handshake failure, errno 0** I have disabled firewall and antivirus. I can provide Curl option details, or any other piece of code or info. Thank you! **SOLUTION:** curl_setopt($this->ch, CURLOPT_SSLVERSION, 3);
To work with a SSL connections you have to enable the `php_openssl.dll` in your **php.ini** And when you work with curl a common problem is that the openssl module work with a wrong SSL version as default. Most times you should set the SSL version to 3. curl_setopt($curl, CURLOPT_SSLVERSION,3); I had the same problem before a few days.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "php, windows, curl, ssl, nusoap" }
Неправильно отображается язык на сайте Скопировал я сайт _curren1.best-gooods.ru_ через _teleport pro_. Залил на хостинг (адрес — < а он отображается неправильно. Я в этом деле новичок, подскажите, пожалуйста, как исправить. Отсюда же вытекает вопрос: как мне сделать, чтобы заказы приходили на мой e-mail адрес, а не на адрес создателя сайта?
У вас проблема с кодировкой. Исправьте строку в вашем файле "<meta charset=utf-8"utf-8">" на <meta charset="utf-8"></meta> Плюс сами файлы сайта тоже должны быть сохранены в utf-8 кодировке перед заливкой на сайт.
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "веб программирование" }
Which UILabel method is invoked when I set text, and it resizes itself to fit? I have an UILabel, created in Universal storyboard, and I have mentioned all required **constraints** for its position **OTHER THAN WIDTH**. So it resizes itself as per the text set. Fantastic! Exactly what I want. **Problem starts here :** It has background color as green color, but that color is wrapping my text tightly. I thus believe that making it a little wider can help me. But to do that, I need to know which method of my UILabel subclass is invoked. So that I can override and add additional width of 10 points. **BottomLine:** Which UILabel method is invoked for resizing the label automatically after I assign it the text? The way it currently looks : !enter image description here
Unfortunately, we don't have any `contentEdgeInsets` property we can set on a `UILabel` (as we do have on a `UIButton`). If you want auto layout to continue to make the height and width constraints itself, you could make a subclass of `UILabel` and override the `intrinsicContentSize` and `sizeThatFits` to achieve what you want. So, something like: - (CGSize) intrinsicContentSize { return [self addHorizontalPadding:[super intrinsicContentSize]]; } - (CGSize)sizeThatFits:(CGSize)size { return [self addHorizontalPadding:[super intrinsicContentSize]]; } - (CGSize)addHorizontalPadding:(CGSize)size { return CGSizeMake(size.width + (2*kSomeHorizontalPaddingValue), size.height); } Note that this only touches the horizontal padding, but can obviously be modified to add vertical padding as well.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "ios, storyboard, uilabel, nslayoutconstraint" }
Getting the line number in the source code for an equation? I have a long file (about 5000 lines, the pdf is about 100 pages) and I want to find an equation with a specific number (for example: 11.5) in the source code. Of course, I have access to all the `.aux`, `.log` files etc. Is there a way to locate the equation in the source code? I don't want to use inverse-search from DVI, because I'll have to do this for a large number of equations.
if you have a `\label` in the source then you can look in the aux and find the label for a particular number then just search for that label in the source document. Alternatively you could modify `\label` to output the line number as a comment in the aux (or in the log) but that has a bigger chance of breaking something.
stackexchange-tex
{ "answer_score": 3, "question_score": 3, "tags": "sourcecode, forward inverse search" }
How to get size of resized image? In UWP I have this Image <Image Source="{Binding Bitmap}" Stretch="Uniform"/> I want to get size of the resized Bitmap _inside_ Image element in code behind, so I have this Image img = ...; var width = img.Width; // this gives size of Image element not the bitmap resized // inside the Image. So the original Bitmap could have size of 1920x1080 but Image element size is 300x200, so the bitmap inside it would have size of 300x112.5 given `Stretch=Uniform`. I want to get 300x112.5
Use the ActualWidth/ActualHeight properties.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, image, uwp, bitmap, image size" }
Why does grep -P on binary files sometimes match wrong bytes? I'm trying to use `grep -P` to find specific byte sequences in potentially large binary files. However, it sometimes matches where it shouldn't - for example, here's a golfed-down case where it appears to simply "match over" a wrong `\xc2` byte: alias bin2hex='xargs echo -n | od -An -tx1' echo -e '\x3e\x1f\xc2\x9d\xa0' > test.bin cat test.bin | bin2hex 3e 1f c2 9d a0 grep -P '\x1f\x9d' test.bin Binary file test.bin matches grep -Pao '\x1f\x9d' test.bin | bin2hex 1f c2 9d Why does this happen? And can it be avoided?
This command: grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0') | xargs echo -n | od -An -tx1 prints nothing with `grep` versions: * GNU grep 2.5.1 * GNU grep 2.6.3 * GNU grep 2.21 Are you sure your `grep` is not aliased to anything wrong (`type grep`)? * * * _UPDATE: converting comments into answer_ I can reproduce your problem with a different `LANG` value: LANG=en_US.UTF-8; grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0') Binary file (standard input) matches The problem is not reproduced with: LANG=en_US; grep -P '\x1f\x9d' <<< $(echo -e '\x3e\x1f\xc2\x9d\xa0')
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "regex, shell, grep, binary, byte" }
How to show data from pipe in template? I have an array: let arr = [{id: 1, name: "G"...}, {id: 2, name: "H"...}, {id: 3, name: "O"...}]; Also there is a template HTML where I need to apply pipe `getTopUser`: <ng-container getTopUser as user> <div class="top_user"> <div class="name">{{user.name}}</div> <div class="age">{{user.age}}</div> </div> <div class="top_user_additional"> <div class="remark">{{user.remark}}</div> </div> </ng-container> So I need to apply pipe to block, how to do that properly? Pipe is: @Pipe({ name: 'applicanttypename', }) export class TopUserPipe implements PipeTransform { transform(user: User[]): string { return user[0]; }
Combining it with an `ngIf` directive, you can assign a local variable to use inside the container: <ng-container *ngIf="users | getTopUser; let user"> <div class="top_user"> <div class="name">{{user.name}}</div> <div class="age">{{user.age}}</div> </div> <div class="top_user_additional"> <div class="remark">{{user.remark}}</div> </div> </ng-container> `users` is the array with users defined in your component. Also note that the name of your pipe is currently `applicanttypename` and not `getTopUser`. And make sure your pipe will handle the case when the input array is undefined or empty. As @yash mentioned you can also use `users | getTopUser as user`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "angular" }
Is it possible to create a C# 'pointer' to a DateTime object? Is it possible to create a C# pointer to a DateTime object? I'm trying to do this: DateTime Event1 = DateTime.Now; DateTime Event2 = DateTime.Now.AddYears(10); DateTime EventPointer; // A Pointer? if (something) { EventPointer = Event1; } else { EventPointer = Event2; } EventPointer.DoSomething? // Something that would change the value of Event1/2 variable.
Not directly, but you can wrap it around a class: Wrapper w1 = new Wrapper { TheDate = DateTime.Now }; Wrapper w2 = new Wrapper { TheDate = DateTime.Now.AddYears(10) }; Wrapper w; if (something) { w = w1; } else { w = w2; } w.DoSomething(); class Wrapper { public DateTime TheDate { get; set; } public void DoSomething() { } }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c#" }
IPC2221 vs IPC2152 for PCB manufacturing I'm designing an hot plate made of an aluminum PCB capable to heat up to ~50°C. Having the area I want to heat up and thus the trace length to cover most of it, to determine the track width that I need I used a couple of common online tools (1, 2), which gave me different results. Then I noticed that one was using IPC2221 (older) and the other was using IPC2152 (newer) as the standard to calculate the result. Reading about it online I found out that IPC2221 was based on 50-years old measurement, and so it would make sense to use the newer IPC2152, but what troubles me is that the Trace Width for external layers (which is what I'm gonna be using) is 1.29 mm for IPC2221 and 3.36 mm for IPC2152: a difference of more than 2x! How is it possible that they differ by so much? Have people been making inaccurate PCB's the whole time because of IPC2221? Should I use IPC2152 results? Thanks ![enter image description here](
The temperature rise is for the copper trace itself sitting on piece of (fairly thermally insulating) FR4. That's why the numbers are different for internal and external layer. I don't think you can directly apply it in your application. I suggest determining the required power experimentally (find a piece of aluminum of the same thickness and overall dimensions, mount it similarly, and heat it with one or more power resistors bolted to it). Then you can use the tools to calculate the required trace width for the required **resistance** at the operating temperature (copper has a positive tempco so you'll need a bit lower resistance at room temperature). There's also a correction for the corners that you may need to apply since current crowds in corners. Incidentally, 50 year old measurements may well be done better than more current ones. I've often had to look up much older papers to find work done to high standards (for example for magnetic shielding).
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "pcb" }
How can I delegate to a member in Scala? Is it possible in Scala to write something like: trait Road { ... } class BridgeCauseway extends Road { // implements method in Road } class Bridge extends Road { val roadway = new BridgeCauseway() // delegate all Bridge methods to the `roadway` member } or do I need to implement each of `Road`'s methods, one by one, and call the corresponding method on `roadway`?
The easiest way to accomplish this is with an implicit conversion instead of a class extension: class Bridge { ... } implicit def bridge2road(b: Bridge) = b.roadway as long as you don't need the original `Bridge` to be carried along for the ride (e.g. you're going to store `Bridge` in a collection of `Road`). If you do need to get the `Bridge` back again, you can add an `owner` method in `Road` which returns an `Any`, set it using a constructor parameter for `BridgeCauseway`, and then pattern-match to get your bridge: trait Road { def owner: Any ... } class BridgeCauseway(val owner: Bridge) extends Road { . . . } class Bridge extends Road { val roadway = new BridgeCauseway(this) ... } myBridgeCauseway.owner match { case b: Bridge => // Do bridge-specific stuff ... }
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 17, "tags": "scala, proxy" }
Why do new towels dry better after a few uses? Most of you will be familiar with the phenomenon: you have bought a new towel and you first have to wash it or use it a couple of times before it starts to work properly, i.e. dry your body after taking a shower instead of smearing out the water . My simple question is: why is this the case? Why do new towels dry better after a few uses? Do the pores in the towel somehow have to be 'opened' after the production process which reduces capillary action in the first couple of uses? Or is it perhaps because of some coating the new towels have to protect them while kept in stores, which causes lower wettability? Or is it perhaps related to the way in which the towel dries after it has been wet?
In the west the vast majority of towels are made from cotton, and cotton is basically cellulose. The surface of cellulose is fairly reactive (the bulk isn't unless you're a termite!) and will react with water to produce surface hydroxyl groups and negatively charged groups. Both of these lower the contact angle of water on the fibres and hence increase capillary forces and wicking. Towels from the factory with have been treated with materials not unlike fabric conditioner. This makes the towel feel nice and soft, but it make the surface more hydrophobic and therefore less able to absorb water by wicking. It takes a few uses for this surface treatment to wear off. You can do the experiment for yourself simply by using fabric conditioner when you wash the towel. If you compare two towels, one laundered with fabric conditioner and one not, then it will be immediately obvious that (a) the conditioned towel feels softer and nicer but (b) the unconditioned towel dries you better.
stackexchange-physics
{ "answer_score": 5, "question_score": 2, "tags": "everyday life, surface tension, capillary action" }
dynamic keyword affects return type I'm not entirley sure why the following code compiles namespace ConsoleApp13 { public class Person { } class Program { static void Main(string[] args) { dynamic expand = new ExpandoObject(); List<Person> people = GetPerson(expand); } public static Person GetPerson(int item) { return new Person(); } } } Why does the `dynamic` keyword impact the return type. It's like the compiler give's up on type checking as soon as `dynamic` is introduced. Is this expected behavior?
> Is this expected behavior? Yes. Almost _anything_ you do that involves a dynamic value ends up with a compile-time type of `dynamic`. Note that binding is performed dynamically, so even though in this specific case you've only got one `GetPerson` method, in the more _general_ case of method invocation, overloads could be present at execution time that aren't present at compile-time, with different return types. There are a few operations which _don't_ end up with a dynamic type: * Casting (e.g. `(string) dynamicValue`) * The `is` operator (e.g. `dynamicValue is string`) * The `as` operator (e.g. `dynamicValue as string` * Constructor calls (e.g. `new Foo(dynamicValue)`)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, .net, dynamic, .net core" }
How to remove all styles for certain page template? I know how to create child themes and page templates. I have a child theme of Salient called Salient-Child, and I have a page template called blankPage.php. For all pages that use this template, I want there to be no CSS loaded at all. I'm aware of `wp_register_script, wp_deregister_script, wp_deregister_style, wp_dequeue_style`, etc, but I'm not sure where/how to use them. I've tried typing some of those functions within blankPage.php itself, and I've also tried editing functions.php. I've tried using a conditional with `if(is_page_template('blankPage.php')){...}`. Any guidance would be appreciated. Thanks!
I seemed to solve the problem, and it was so simple that I'm shocked I've never seen this mentioned by anyone before. First, I deleted my entire child theme so that I could start over from a fresh place. Then, I used < to create a brand new child theme of Salient. Then, in the **Appearance > Editor** menu, I viewed the `functions.php` file and noticed that it had pregenerated `add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );` and `function theme_enqueue_styles()` for me. So I simply wrapped the contents of the function within `if ( !is_page_template( 'rawHtmlPage.php' ) ) { ...}`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 5, "tags": "page template, css" }
How can I retain geotagging information on my iPhone pictures? Most of my phone's memory (almost 11 GB's of it) resides in my pictures and videos. I want to clear most of it but not even my completely empty iCloud storage can handle all of it. Anyways, when you're looking at your photos and you zoom out into "years" and you click one of those years, a big map will pop out and you'll literally see every single place you've taken these pictures at. I think that's really cool since I went to a lot of places last summer and in general think it's a cool feature. Back to the point, is there any way I could save that location information when I _export_ these pictures to my laptop? Would a copy/paste just be sufficient? I don't have a Mac either, so I don't know if it will be harder or impossible. And if it is possible, is there some sort of app that you can use on your laptop to pull up that same view you have on your iPhone and see everywhere you took your pictures?
You can just copy those images. Those location information is coded into EXIF data. It will not be deleted upon transfer.
stackexchange-apple
{ "answer_score": 1, "question_score": 0, "tags": "photos, iphone" }
Meaning of dt/dx when deriving the law of reflection One way to derive the law of reflection, you can use the principle of least action to minimize the action path of motion of light. They key concept while doing this is to take the derivative of the time the light takes to go from one point to the another, then setting this derivative to zero. Say the notation is dt/dx, this means that the infinitesimal change in time over the infinitesimal change in position is equal to zero. What is the meaning of dt/dx in non-mathematical terms? Thanks.
It means that while trying a continuous family of pathes parameterized by a scalar u (works also for 2 or 3 coordinates) and measuring their length and duration T, the solution corresponds to the minimum duration, which is find at dT/du=0.
stackexchange-physics
{ "answer_score": 1, "question_score": 1, "tags": "action, differentiation" }
Evaluating for loops in python, containing an array with an embedded for loop I was looking at the following code in python: for ob in [ob for ob in context.scene.objects if ob.is_visible()]: pass Obviously, it's a for each loop, saying for each object in foo array. However, I'm having a bit of trouble reading the array. If it just had: [for ob in context.scene.objects if ob.is_visible()] that would make some sense, granted the use of different objects with the same name ob seems odd to me, but it looks readable enough, saying that the array consists of every element in that loop. However, the use of 'ob', before the for loop makes little sense, is there some syntax that isn't in what I've seen in the documentation? Thank you
That is the syntax for list comprehension.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, arrays, list, foreach" }
why allow extension methods on null objects? what is the point of allowing invocation of extension methods on null objects? this is making me unnecessarily check for a null object in the extension method. AFAIK,i can't understand this? Please explain.
Extension methods are syntactic sugar of the C# language, they get compiled to normal static method calls in ILCode. A static method doesn't know anything about the parameters at compile time.
stackexchange-stackoverflow
{ "answer_score": 31, "question_score": 16, "tags": "c#, extension methods" }
Java Checkbox List in Netbeans I have to design an application which handles customer orders. The GUI has tabs, one for the customer and one for the admin. In the customer tab, he has the possibility of submitting an order, by chosing the products from the product list, each having a checkbox in front of them and a text field in which the quantity will be specified. I am using the netbeans gui editor for the design and I am a bit stuck as the code cannot be modified. I cannot create the product list dynamically (so to create a line for each product in the product array list, and on each line to put the checkbox and the textfield) or at least I don't know how to. My question is - is there any way of dynamically creating such a list (checkbox + label with the product name + textfield which waits for the quantity) or is there an alternative to my idea ?
Sounds like you need to use a `JTable` for your list of Products and Quantities. In the NetBeans GUI editor you will only be able to place the `JTable` on the panel you are designing. After that you need to define a 'Model' for your table which will hold the data you are entering. See the official Oracle Java tutorial on How to Use Tables. Of course there are lots of other use cases that would fit your requirements, but your design sounds fine. The checkbox is probably superfluous though, as entering a quantity against a product should be enough to indicate that the customer has chosen that Product. If your list of Products gets too long, though, you might want to re-visit this design. Perhaps the table could have 2 coulmns, the first one being a combo-box list of Products, and the second column has the quantity.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, user interface, netbeans, checkbox, arraylist" }
What is the syntax of Spring Boot "application.properties" file? I've seen different delimeters for properties : = Can't find reference about it.
In `application.properties` you can specify properties in either of these forms: * Using `=`: > key=value * Using `:` > key: value All examples in the Spring docs for `application.properties` use `=` as the delimiter. But Java properties also supports `:` so by extension Spring (which is utilising `java.util.Properties` under the hood also supports `:`. Here's the relevant extract from the `java.util.Properties` Javadoc ... > The key contains all of the characters in the line starting with the first non-white space character and up to, but not including, the first unescaped '=', ':', or white space character other than a line terminator.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 7, "tags": "spring boot, application.properties" }
Is it not correct to do api call without useEffect? I want to do an api call after a button is clicked in react.But I have read that to do async tasks, we use useEffect. So is it okay to not use useEffect and do an api call without it? I think that without using useEffect an api call would block the render. useEffect runs depending on deps Array. It is used to do async tasks. But I want to do a api call onClick.So its not possible to use useEffect. So,What is the correct way to do an api call if it has to be done on Click?
You can do api call with and w/o the `useEffect`, both are fine. And no, you won't block the api call if you don't use `useEffect`. const App = () => { const makeApiCall = async () => { // the execution of this function stops // at this await call, but rest of the App component // is still executes const res = await fetch("../"); } ... };
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, reactjs, asynchronous, use effect" }
Map vertex id to vertex coordinate I want to map vertex labels to vertex coordinates stored in two variables. vl = {6, 9, 12} vd = {{1011, 1127, 420}, {950, 1052, 404}, {780, 1033, 470}} I tried, coords = {vl -> vd} but this didn't work. May I know what's the right way to do this? Expected output: {6 -> {1011, 1127, 420}, 9 -> {950, 1052, 404}, 12 -> {780, 1033, 470}}
Thread[vl -> vd] > > {6 -> {1011, 1127, 420}, 9 -> {950, 1052, 404}, 12 -> {780, 1033, 470}} > Also MapThread[Rule] @ {vl, vd} > > {6 -> {1011, 1127, 420}, 9 -> {950, 1052, 404}, 12 -> {780, 1033, 470}} >
stackexchange-mathematica
{ "answer_score": 3, "question_score": 3, "tags": "map, coordinate" }
Add private method in JavaScript? I'm trying to make a basic game to strengthen my JavaScript knowledge. But I need some help with trying to add private methods to an object. The reason for this is that I want to the user to be able to access certain moves once they reach a certain condition, but not before. I also don't want to have to add the methods each time the character levels up. Here is some code: function Character(name, type, sex) { this.name = name; this.type = type; this.sex = sex; //Ignore this part as well this.punch = function() { //Ignore this. Will work on later } }; var rock = new Character('Stoner', 'Rock', 'Male');
> I don't think this is what the OP is looking for... It seems like the OP wants them "private" until the user hits a certain level and then public Assuming this comment is right... It doesn't need to be a private method, have it be a public method and then use an if/else statement to handle if they don't have enough "levels". function Character(name, type, sex) { this.name = name; this.type = type; this.sex = sex; this.level = 10; this.punch = (function(){ if (this.level > 5) { /* Punch functionality goes here. */ } else { /* They don't have enough levels, tell them that! */ } }).bind(this) } I'm only assuming you're using levels. If you have some other system, you can simply adapt it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, methods, private" }
Rederiving the series formula for cot(z) So I am re-deriving the laurent series for $\cot(z)$ and I have the following, but am stuck. First, I look at $\frac{1}{\sin(z)}:$ $$ =\frac{1}{z-\frac{z^3}{3!}+\frac{z^5}{5!}-\dots}=\frac{1}{z(1-\frac{z^2}{3!}+\frac{z^4}{5!}-\dots)}=\frac{1}{z}(1+\left(\frac{z^2}{3!}-\frac{z^4}{5!}+\dots\right)+\left(\frac{z^2}{3!}-\frac{z^4}{5!}+\dots\right)^2+\dots)=\frac{1}{z}+\frac{z}{3!}+\frac{7z^3}{360}+ O(z^4). $$ I think I have this much correct. Then, I recall that $\cos(z)=1-\frac{z^2}{2!}+\frac{z^4}{4!}-\dots$ If I try the naive thing and multiply these series together, term by term, I get: $$ \frac{1}{z}-\frac{z}{6}+\frac{z^3}{45}+O(z^4). $$ However, I understand that the second term is supposed to by $-\frac{z}{3}.$ Is there something I am overlooking?
There is a $z$ term that results from multiplying $\dfrac z{3!}$ by $1$ and one that results from multiplying $\dfrac1z$ by $\dfrac {z^2}{2!}$: $\left(\dfrac{1}{z}+\dfrac{z}{3!}+\dfrac{7z^3}{360}+ O(z^4)\right)\left(1-\dfrac{z^2}{2!}+\dfrac{z^4}{4!}-\dots\right)$ $=\dfrac1z+\dfrac z{3!}-\dfrac z{2!}+O(z^2)=\dfrac1z-\dfrac z3+O(z^2).$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "sequences and series, complex analysis, laurent series" }
Uploading images to S3 with React and Elixir/Phoenix I'm trying to scheme how I'm going to accomplish this and so far I have the following: I grab a file in the front end and on submit send the file name and type to the back end where it generates a presigned URL. I send that to the FE. I then send the file on the front end. The issue here is that when I generate the presign, I want to commit my UUID filename going to S3 in my database via the back end. I don't know if the front end will successfully complete this task. I can think of some janky ways to garbage collect this - but I'm wondering, is there a typically prescribed way to do this that doesn't introduce the possibility of failures the BE isn't aware of?
Yes there's an alternate way. You can configure your bucket so that it sends an event whenever an object is created/updated. You can either send this event to a SNS topic or AWS Lambda. From there you can make a request to your Phoenix app webhook, that can insert it into the database. The advantage is that the event will come only when the file has been created. For more info, you can read the following: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "reactjs, amazon web services, amazon s3, elixir, phoenix framework" }
Ending Python if-then using triple double quote gives EOL while scanning string literal I keep getting the same error, I think it's because of how I end my if-then statement. It basically looks like this, except it's much longer (like, 300 lines long). myIfThenVariable="""def myIfThen(field, fieldB): if field=="Thing One": return "T1" elif field=="Thing Two": return "T2" elif field=="Something else": return fieldB else: return field """" The error I keep getting is: SyntaxError: EOL while scanning string literal (MyRhubarb.py, line 374) * I have my if-then book-ended with triple quotes. * I tried adding a backslash after the word field (` field\"""`). * I copied and pasted the same code into the field calculator in ArcMap and was able to run it without issue.
Instead of ending with three quotes, you have four. Technically this is closing the triple-quoted string and starting a new one, and since there is no closing for the new one you get the `EOL` error.
stackexchange-gis
{ "answer_score": 4, "question_score": 0, "tags": "python, arcmap, field calculator, syntaxerror" }
How does recursion work in the Alloy Analyzer? I see there is an option in the Alloy Analyzer to allow recursion up to a certain depth (1-3). But what happens when a counterexample cannot be found because of the limited recursion depth? Will there be an error or a warning, or are such counterexamples silently ignored?
Alloy basically does not support recursion. When it encounters recursion, it _unrolls_ the code the max number of times. Therefore, if it cannot found a solution, it just, well, cannot find a solution. If it could only generate an error if it knew there was a potential solution, which would solve the original problem. This is, imho, one of the weakest spots in Alloy. Recursion is extremely important in almost all specifications.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "recursion, alloy" }
jQuery - Traversing the DOM Here is my HTML: <li> <div class="menu_inner"> <a href="#"> <div class="button"><img class="486" src="images/portalbutton.png" /></div> <div class="prod_description">&nbsp;</div> </a> </div> </li> I want to add a .click() function to .prod_description, the click event should take the background colour applied in CSS from the li element. Using this code: $(".prod_description").mousedown(function() { $('#toolbar').css('background-color', $(this).parent().css('background-color')) }) I dont seem to be able to get the correct `$(this).parent()` combination....
You can do that like this: $(".prod_description").mousedown(function() { $('#toolbar').css('background-color', $(this).closest('li').css('background-color')) }); `.parent()` gets the immediate parent, you want to go up a few levels (`<a>`, `<div>`, `<li>`). `.closest('li')` climbs the parents and gets the first one that's an `<li>`. In this case, `.parent('li')` would also work :)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "jquery" }
if I got from anyone reference like #!foo=32 what I would recieve if Ia got JS on/off Guyz! I couldn't find the answer to the question what if I got from anyone reference like ..#!foo=32 from <a href=..?foo=32 onClick=" navigate(..#!foo=32); return false;">click</a> what I would receive if I got my **JS** : 1. On 2. Off I'm trying to connect it with SEO. It seems to me that if everyone who goes to link like ..#!foo=32 will develop this link that robots don't see, but not link like href=...?foo=32 which is actually needed for **SEO**. I'm very sorry If I repeat someone's question, but really couldn't find a clear answer.
The hashbang (#!) is a system Google proposed to solve the issue of Ajax based dynamic pages. Google and Bing currently support it. I'm sure Googling hashbang will get you to the details.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, seo, href" }
How to use LIKE and OR in the same query I would like to pull out 3 types of data registred in one day. I want to extract every row where toll, park or expence has been recorded. I can get this to work: $sqlq = "Select * from mydata WHERE logdate LIKE '$myDato' AND park<>'' "; But how do i exted it to this: $sqlq = "Select * from mydata WHERE logdate LIKE '$myDato' AND toll <>'' OR park <>'' OR expence <>'' ";
The `AND` operator takes precedence over the `OR` operator. In your case you want the presence of multiple `OR` clauses to do this you need parentheses to change the evaluation rules based on the precedence of the logical operators So you should use `(` and `)`: $sqlq = "Select * from mydata WHERE logdate LIKE '$myDato' AND ( toll <>'' OR park <>'' OR expence <>'') ";
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "mysql" }
What is Google's Stance on Keeping the Android Market Open to the General Public (And by "General Public" I mean, people who aren't paying $30 a month for data transfers, and just using wifi instead.)
You can download applications over a wifi connection without _any_ phone plan. For example, I recently removed an HTC Hero from my phone plan and was able to download applications to the phone over Wifi with no problem.... even though I could not make calls. Since Android is not limited to phones or devices with wireless data plans, requiring a phone plan would not be possible for all Android devices. Additionally, with competion in the works like Amazon's upcoming Android applications market, there will be too much disincentive for Google to require a monthly fee for market access.
stackexchange-android
{ "answer_score": 5, "question_score": 4, "tags": "google play store" }
Перевести числа, разделенные пробелами из строки в массив целых чисел #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char s[100+1]; int i; int num[20]; fgets(s, 20, stdin); for(i=0;i<20;i++) { num[i]= atoi(s); } puts(s); printf("%d",num[i]); return 0; } Я пытался что-то сделать, но я не понимаю как использовать atoi для обработки всех символов строки, а не только символов до пробела.
Ну, если нужна именно строка, я бы делал примерно так: #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char s[100+1],*e,*b = s; int d,i = 0; int num[20]; fgets(s, 101, stdin); for(d = strtol(b,&e,10); e != b && errno == 0;d = strtol(b = e,&e,10)) { num[i++]= d; } puts(s); for(int j = 0; j < i; ++j) printf("%d ",num[j]); }
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c, массивы, строки, ввод" }
Spring Boot @Scheduled cron Is there a way to call a getter (or even a variable) from a propertyClass in Spring's `@Scheduled` `cron` configuration? The following doesn't compile: `@Scheduled(cron = propertyClass.getCronProperty())` or `@Scheduled(cron = variable)` I would like to avoid grabbing the property directly: @Scheduled(cron = "${cron.scheduling}")
Short answer - it's not possible out of the box. The value passed as the "cron expression" in the `@Scheduled` annotation is processed in `ScheduledAnnotationBeanPostProcessor` class using an instance of the `StringValueResolver` interface. `StringValueResolver` has 3 implementations out of the box - for `Placeholder` (e.g. ${}), for `Embedded` values and for `Static` Strings - none of which can achieve what you're looking for. If you have to avoid at all costs using the properties placeholder in the annotation, get rid of the annotation and construct everything programmatically. You can register tasks using `ScheduledTaskRegistrar`, which is what the `@Scheduled` annotation actually does. I will suggest to use whatever is the simplest solution that works and passes the tests.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 14, "tags": "spring, cron, spring boot, schedule" }
Web development burnout I want to get out of web development and my current job. The company has a culture of learning the latest bleeding edge framework for each new project and it is very tiring keeping on track of everything. We are a very small team. I have spoken to my boss about this and he ensures that I am to work my set hours. The boss is clearly very smart and he is personable. I'm probably what you consider an average/pretty good developer - not rockstar but hardworking and with a sound enough computer science background. But there is a ridiculous amount of things to learn. I'm just not into it anymore. My question is: how can I scope out companies that avoid this, and find a good fit for me? I'm well aware there is no such thing as the perfect job, but I like to think I can influence things to make myself happier.
Ask them during the job interview? For instance: > How often do you switch web frameworks?
stackexchange-workplace
{ "answer_score": 6, "question_score": 5, "tags": "careers" }
Textfield client side validation How can I implement a validator that won't allow a use to type angled-brackets on the client side. This, of course, only allows the use to type numbers: { xtype: 'numberfield', hideTrigger: true, name: 'tsId', width: 120 } But how would I have a textfield that allows a user to type anything other than angled-brackets. < >
Regex is your friend - here's the expression you'll need to test against /<|>/g You can use it as a function like so: var str; function evaluate() { str = $('#evaluationText').val(); var evalTest = str.match(/<|>/g); // test for '<' or '>' if(evalTest){ alert('illegal chars..'); }else { alert('all good'); } } $('#evalText').click(function() { evaluate(); }); Fiddle here - <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, extjs" }
JavaScript: Create event with current mouse coordinates I was looking on this post but it doesn't really help me. What I'm trying to do is to create event, or what would be even better, access current mouse screen coordinates. I have a function with setTimeout inside it, where number of different checks on attributes are performed. In my program some of the elements are changing position and what I want to do is check whether mouse is still over some elements or not. Many thanks, Artur
This solves the problem: // Mouse coordinates for event.clientX, event.clientY respectively. var myClientX, myClientY; // This call makes sure that global variables myClientX, myClientY are up to date window.document.addEventListener("mousemove", function(event) { myClientX = event.clientX; myClientY = event.clientY; }, false); Making coordinates global let's me access them whenever I want :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, events" }
Word "切り開く" / "きりひらく" I'm translating a song and I have a problem with one part. I know that means "open up" or "clear", but what is the object here? Or maybe it has different meaning in this situation? Full song lyrics if more context is needed: < And here's the fragment: > > **** !!
(or sometimes ) often takes objects like , , , , , , , and such. is a set phrase that means something like "to carve one's destiny". In this case, the whole lyrics are filled with words like , and , so even without an explicit object, people can safely feel the positive nuance of the verb. I think "move forward" or something similar will do the job.
stackexchange-japanese
{ "answer_score": 1, "question_score": 1, "tags": "translation, meaning, words, song lyrics" }
How to create this button shape CSS only? I'm stumped for an answer how to do this button with CSS. The easiest way was using an :after with a background image for the right part but this isn't nice and clean when it comes to hover effects. I've been able to solve it by myself with just the blue arrow on the right but this "double arrow" makes me crazy. ![enter image description here](
background gradient maybe ? button { margin:1em; border:none; padding:0.25em 3em 0.25em 1em; text-align:left; background: linear-gradient(-120deg, transparent 1em, #0099C3 1.05em , #0099C3 1.5em, transparent 1.45em, transparent 2em, #0099C3 2.05em) top no-repeat, linear-gradient(300deg, transparent 1em, #0099C3 1.05em , #0099C3 1.5em, transparent 1.45em, transparent 2em, #0099C3 2.05em) bottom no-repeat ; background-size: 100% 50%; color:white } <button>button button <br/> button</button>
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "css, button" }
About deprecation and unit testing in Pharo sometimes, it is better to temporarily use a deprecated method than to create several branches of a project to support several versions of Pharo. At least, that's what I sometimes do. However, calling a deprecated method makes my unit-tests fail in Pharo 3.0. Is there anything I can do?
Shouldn't it be sufficient to switch off deprecation warnings? I think the reason is that opening the deprecation warning is based on an exception that the test case catches.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "pharo" }
Automated network capture and analysis? I was curious to know if anyone has done any work on automated network analysis such as starting network traffic capture (to file) before executing some test, perform some test, then stop capture, then parse capture file for known patterns to look for (expected data, errors that should not appear, etc.). Using pcap libraries for whatever programming/scripting language, using tshark, tcpdump, etc. I had planned to do some work in this area for SIP/VoIP testing but never got the time at work to look into it. But it should be theoretically possible, so just wanted to see if there were real life implementations of it by others (whether made open source or not).
There are a few different solutions off the top of my head. There are several proxies that others have already mentioned that have APIs that can be made to listen on whatever port you need. They may not get granular enough though for what you need. If I were looking in this area I'd maybe take a look at Python's socket module.: < This even gives an example of sniffing and then parsing: <
stackexchange-sqa
{ "answer_score": 2, "question_score": 1, "tags": "automated testing, action recording, data analysis" }
Why doesn't BindingList<T> have to fully implement its interfaces? `BindingList<T>` implements `IBindingList`. One of the methods on `IBindingList` is void ApplySort(PropertyDescriptor property, ListSortDirection direction); But `BindingList<T>` doesn't implement this method. Instead it implements protected virtual void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction); Obviously `ApplySortCore` has a different name and is not public, so I don't see how it could satisfy the requirement of the `IBindingList` interface yet this is the closest thing to what `IBindingList` actually calls for. So how is it possible for this class to get away with not fully implementing its interfaces?
I guess `BindingList` uses explicit interface implementation to hide interface members. Try this interface IX { public string Var {get;} } public class X : IX { string IX.Var { get { return "x"; } } } public class Y { public Y() { X x = new X(); string s = x.Var; // Var is not visible and gives a compilation error. string s2 = ((IX)x).Var; // this works. Var is not hidden when using interface directly. } }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, .net, oop, interface" }
Defining lex include files for (f)lexers When having multiple lexers one sees that, especially, in the pattern part some definitions are repeated in each lexer (e.g. `whiteSpace [ \t]+` ), this is not nice that one has to do define it each time and especially with more complex patterns a bit error prone. So far I have not been able to fine anything, but is there a way to have a file with (e.g.) patterns included in a lexer?
You are free to write your own preprocessor, and I suspect many people have done so. But as far as I know, no popular lex derivative includes such a feature. Certainly, neither flex nor the original AT&T lex have one.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "flex lexer, lex" }