INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Do you know any video tutorials focused purely on Closures in JavaScript? I am having a problem to really get the point when it comes to 'closures' in JavaScript. Do you know any video tutorials focused purely on defining closures in JavaScript with simple and clear examples? Thanks!
Have you tried: Stuart Langridge: Secrets of JavaScript Closures: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, closures" }
Is there a directory for txt files just like drawable for images? In Android Studio, If we want to use an image in our Anroid app, we move this image to `res/drawable` file. And we use it. But if we want to use contents of a `.txt` file (e.g reading text from file at the first launch the app), which directory should we move this file?
You can put it on `res/raw` or in `assets/` directory.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "android, assets" }
Homework Problem: Finding the Covariance and the correlation ![enter image description here]( * I have an idea on how to start the problem and that's with finding the expectation of X and Y and then apply the formula of Covariance but I'm not sure since it is a biased coin. Any help would be appreciated, thank you in advance!
You can also go directly for covariance. * * * Let $Z$ have Bernoulli distribution with parameter $p$. For $i=1,\dots,15$ let $Z_{i}$ take value $1$ if the $i$-th toss results in heads on let it take value $0$ otherwise. Observe that the $Z_{i}$ are iid and have the same distribution as $Z$. Then: $$\mathsf{Cov}\left(X,Y\right)=\mathsf{Cov}\left(\sum_{i=1}^{10}Z_{i},\sum_{j=6}^{15}Z_{j}\right)=\sum_{i=1}^{10}\sum_{j=6}^{15}\mathsf{Cov}\left(Z_{i},Z_{j}\right)=5\mathsf{Var}Z=5p\left(1-p\right)$$ This because the terms where $i\neq j$ take value $0$ because of independence.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "statistics, covariance, correlation" }
Radio stream using just audio package? I have used just audio package for all the urls with ending .mp3 data from apis but i want to stream radio url also can i use the same player for playing the acc format urls from api or i need to add another package for the player.
The audio file was not playing because the url starts with http flutter by default does not support the http urls it only allows https urls so play them i have added the below code to the android manifest file: <application .... android:usesCleartextTraffic="true" .... />
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "flutter" }
Hibernate validation: validate PI I'm in need to apply a validation on a double value which needs to match with PI. I'm thinking to use a **@Pattern(regex="3.14159265359")**. Is it the best way I can apply such a constraint using Hibernate Validation Constraints? Thanks
`@Pattern` is only defined for string type (`CharSequence` really). If your data type is a double you cannot use it, unless you write a custom `ConstraintValidator`. You could use `DecimalMin` in combination with `DecimalMax` potentially allowing for some imprecision. Alternatively, you could write your own constraint `@Pi` which for example allows to specify a delta. `@Pi` is probably the best solution, provided you really need this validation.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "bean validation, hibernate validator" }
Использование открытых интерфейсов Delphi Возникла необходимость внести изменения в среду программирования Delphi. Это достаточно редкая необходимость, поэтому и информации по ней мало. Я нашёл только отрывочную документацию в справке и одну (!) статью в интернете. Однако при попытке установить второй пример из этой статьи, я получаю ошибку доступа: > Registration procedure, Unit1.Register in package C:\Users\Public\Documents\Rad Studio\8.0\Bpl\Expert2try.bpl raised exception class EAccessViolation: Access violation at address 164B18F8 in module 'expert2try.bpl'. Read of address 00000000. Вообще, из-за чего в процедуре Register может быть Access Violaiton? Что с этим делать? Может быть, существуют какие нибудь более подробные статьи? Можно на английском. Использую Delphi XE.
На официальном сайте их есть: * Extending Delphi 2009 With OpenTools API: Getting Started * Creating a Live Templates Scripting Engine * Extending the Project Manager Context menu Кроме того: * Erik's Open Tools API FAQ * Creating a OTA IDE Extension * Сustom syntax highlighting in Delphi 7 Вообще, копайте на тему _Delphi Open Tools API (OTA)_.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "delphi, ide" }
Could not connect to my sql using php ,undefined function mysql_connect() i want to open a connection to `mysql` database using php with following code: `$connection= mysql_connect("localhost","m****","******");` but I've got `undefined function mysql_connect()` i checked out my `phpinfo()` and got this: ![phpinfo\(\)]( so i tried to turn on `mysqli.allow_local_infile` so i do following in `php.ini` file: `mysqli.allow_local_infile = On` and tried to restart `apache2` and `mysql` services but does not effect. what should i do? thanks in advance, I'm using `Ubuntu 18.4` with `php 7.2.24` and `mysql Ver 14.14 Distrib 5.7.28`
You need to change your function name from `mysql_connect` to `mysqli_connect` as `mysql_` is not supported in PHP7.x further, you need to use all functions having `mysqli_` instead of `mysql_` For more guidance: <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "mysql, load data infile, php ini, php" }
Batch script to update hosts file on boot-up using curl I am trying to get a .bat script to run on boot-up and purge the hosts file with a new one. I have this working on Windows Server 2008 Standard X86 and it has been working consistently for over a year. I installed 'curl', hard linked it to System32 and schedule the following .bat script using local group policy: curl x.x.x.x/latest/hosts > C:\Windows\System32\drivers\etc\hosts Now I want to get the same script working on windows server 2008 R2. I have the same thing setup and it works if I double-click the .bat file. However, when the script runs on startup via GPO, it simply wipes the hosts file completely and I have to login manually and double-click the .bat script. Any idea what's causing this? Is it a difference between Server 2008 R2 and Server 2008 STD?
Try curl.exe x.x.x.x/latest/hosts > C:\Windows\System32\drivers\etc\hosts.tmp move C:\Windows\System32\drivers\etc\hosts.tmp C:\Windows\System32\drivers\etc\hosts
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "windows, curl, batch file, hosts" }
Creating order in a settlement What one concept/ideology is most important in a group of people to encourage them to stop acting as individuals and begin acting in the interest of the whole settlement?
There really isn't _one_ concept that will work for all groups in all times. It is highly dependent on the society/culture and the settlement age for example. There really is two concepts that are the root of all the others - internal motivation and extrinsic motivation. Pretty much all methods are rooted in fear or desire. Some methods would be: * Stringent punishment: This will obviously work much better in a fairly hierarchal society since otherwise punishment is much harder to effectively wield. Moral issues can be brought up by this to great effect. * Exclusion from the benefits of the settlement unless they are helping the settlement. You can also use this for moral discussion. * Capitalism: basically a communally created exclusion if there isn't output. Has all the risks and benefits of capitalism in the real world. * Religious teaching/orders: In a highly religious society orders from religious elders are often akin to law or even greater than law.
stackexchange-worldbuilding
{ "answer_score": 3, "question_score": 7, "tags": "law" }
Converting strings separated by commas to arrays and merging arrays that are contained within one variable The following code is used to get some primary keys from various database entries and merging the unique values into a single array for downstream applications. $query = "SELECT * FROM samples_database WHERE order_id=$order_id;"; $result = mysqli_query($conn, $query); $results = ''; while ($input = mysqli_fetch_array($result)) { $results .= $input['micro_analysis']; } $rows = explode(',', $results); $final_rows = array_unique(array_merge($rows)); The problem I have is that each row from the database has a string, for example `1,4` and `2,3`. When the strings are merged they become `1,42,3` which is a problem, because this code then produces a array like this: `Array ( [0] => 1 [1] => 42 [2] => 3 )` instead of this: `Array ( [0] => 1 [1] => 4 [2] => 3 [3] => 2 )`. Anybody have a solution to this?
When you append to the end of your `$result` variable you can add a comma to it. Giving you: "1,4,2,3," as your `$results` string once your `while` loop is complete. You can then remove the trailing comma using `substr()`: substr($results, 0, -1); Combing all of these ideas your code should look like: $query = "SELECT * FROM samples_database WHERE order_id=$order_id;"; $result = mysqli_query($conn, $query); $results = ''; while ($input = mysqli_fetch_array($result)) { $results .= $input['micro_analysis'] . ','; } $results = substr($results, 0, -1); $rows = explode(',', $results); $final_rows = array_unique(array_merge($rows));
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, arrays" }
Rulers and Grids relationships I know that a similar questions were asked, but I did not see any answer that solves the issue - Can we reset the rulers to show us ticks values every 10 point and not those that can be divided by 6? I failed to adjust rulers to grid no matter what I performed (double click in the left upper corner or zeroing via dragging to any desired point. Sometimes I need the rulers and grid to match... The main part of question - Can we match grid lines and rulers perfectly as grids are just continues of rulers ticks? Illustrator CS6. Any new solution? What I miss? !enter image description here UPDATE after the answer by Scott - now it is near to be perfect !enter image description here
Try setting the rulers to something metric, which is based on increments of 10, such as centimeters, millimeters, etc. Or, alter your grid settings to be divisible by 6. Pixels (or points) will never divide well by 10 since they use increments of 6 as the base. (Even though pixels technically have _no size_ )
stackexchange-graphicdesign
{ "answer_score": 1, "question_score": 1, "tags": "adobe illustrator" }
Deriving the real and imaginary parts of the complex refractive index in a dielectric medium I have been trying to demonstrate that for a refractive index $n=n_R+in_I$ we have $$n_I=-\frac{Ne^2\gamma\omega}{2m\epsilon_0[(\omega_0^2-\omega^2)^2+\gamma^2\omega^2]},$$ $$n_R=1+\frac{Ne^2(\omega_0^2-\omega^2)}{2m\epsilon_0[(\omega_0^2-\omega^2)^2+\gamma^2\omega^2]}.$$ I start by using the fact that the susceptibility is given by $$\chi=\frac{Ne^2}{m\epsilon_0(\omega_0^2-\omega^2+i\gamma\omega)}.$$ Considering the polarisation of the dielectric as $\vec{P}=\epsilon_0\chi\vec{E}$ and $n^2=1+\chi$ $\implies n\approx1+\frac{\chi}{2}$, we get $$n=1+\frac{Ne^2}{2m\epsilon_0(\omega_0^2-\omega^2+i\gamma\omega)}.$$ Can anyone see where to go from here?
You are almost done, you just have to separate the real and the imaginary part of $n$. In general, $$ \frac{a + ib}{c + id} = \frac{ac + bd}{c^2+d^2} + i \frac{bc - ad}{c^2+d^2} \;. $$ In your case, $b=0$. If you use this formula, you will get the correct results almost immediately.
stackexchange-physics
{ "answer_score": 2, "question_score": 0, "tags": "electromagnetism, refraction, dielectric" }
XPages view control link manipulation I have a view control and at least one column has the option "Display as link" set. The link is generated manually. What I want to achieve is to add a url parameter which is added to a view column link. The usual link would like this " What I would like to have is: " There must be a (presumably easy) way to achieve this - unfortunately I don't know how... Any help or hint is appreciated. Many thanks in advance. Michael
Follow the below steps: 1\. go to All Properties of view Column which displays column values as link. 2\. Compute the PageUrl with the below Code. var col:com.ibm.xsp.component.xp.XspViewColumn = getComponent("viewColumn1"); col.getDocumentUrl()+"&param1=value1"
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "xpages" }
Android screen too wide? I am trying to create a small web app for my android device, I am testing it and there is a scrollbar on my screen (horizontal) no matter what i set the body width, I get the scrollbar. I noticed m.facebook.com doesn't have it. Do I just simply hide the scrollbar?
Try : webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR); ^_^,pls check your AndroidManifest.xml <uses-sdk android:minSdkVersion="4" /><supports-screens android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:anyDensity="true" /> you must set android:anyDensity="true".
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, css" }
How to relevel the levels of a factor variable without transforming it to integer in R? I want to transform the four categories below to two new categories: `zona_a `contains` (north_east & nothern_central)` and `zone_b` contains the other two categories. Is there a way to achieve that without going through the hassle of transforming the variable to integer and using the `ifelse` function? library(plm) data("Males") table(Males$residence) rural_area north_east nothern_central south 85 733 964 1333
Here you have one `tidyverse` solution, hope that helps: library(tidyverse) Males <- Males %>% mutate(residence = factor(case_when(residence %in% c("north_east", "nothern_central") ~ "zone_a", residence %in% c("rural_area", "south") ~ "zone_b")))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "r, dplyr" }
What does 'share squat' mean in this context? I came across the sentence in a comment from this news story. > The investigators are **sharing squat**. But I bet they know a whole a lot. What does 'sharing squat' mean here?
"Squat" is slang for "absolutely nothing." It's presumably a euphemism for "shit." It's commonly heard in the expression "doesn't know squat," meaning "doesn't know anything [about this issue]." "Doesn't know shit" is equally or more common, and means the same thing more emphatically. (And is vulgar, obviously.)
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "phrase usage, negation, slang" }
Is "hedon" an adjecitve? I heard this line in a film's audio description: > As Nick plays his guitar, he looks out into the audience and sees Tris is among the hedon throng. This scene shows Nick playing guitar onstage and Tris standing in the an audience that is enjoying and bobbing to the music. From what I heard, I can't think of another word that might be what precedes "throng". But as far as I know, "hedon" is a rare word and not an adjective. I am not sure if I heard it wrong. I am putting a recording clyp here for context.
> Trish is amongst the _heaving_ throng. Heaving is an informal way of saying "very crowded" and a throng is a tightly packed crowd of people. These two words are often used together. It is a cliché meaning a large and dense crowd.
stackexchange-ell
{ "answer_score": 2, "question_score": 0, "tags": "meaning, meaning in context" }
Rollback is not working if the storedproce call another storedproc Is it intended behavior that if I call a `stored procedure` inside a `stored procedure` will automatically commit? example: pseudo procedure proc1 create procedure proc1(in var1 int, out var2 int) begin start transaction; -- some code here commit; end pseudo procedure proc2, the one will call the proc1 create procedure proc2() lbl_begin: begin start transaction; -- modify some data here call proc1(0, var2); if var != 0 then rollback; leave lbl_begin; end; commit; end; Even the rollback on proc2 is executed, the data modified before the call of the proc1 is still committed. Is it a bug or its an intended behavior?
> Beginning a transaction causes any pending transaction to be committed. See Section 13.3.3, “Statements That Cause an Implicit Commit”, for more information. \-- < and > Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms. \-- < That is, proc1's `START` closed proc2's `START`. The first `ROLLBACK` closes the only open transaction, hence the second `ROLLBACK` has nothing to "roll back".
stackexchange-dba
{ "answer_score": 1, "question_score": 2, "tags": "mysql, mariadb, stored procedures, transaction, rollback" }
How to serve Angular App with Spring? I am currently learning Spring. So I did one or two of the getting started guides (which are awesome btw) and Set Up a little REST Server. I tested it by building a little AngularApp consuming the REST endpoint, which worked fine. Now the next step is to let the server serve the Angular App. But how do I accomplish that in the most simple way? It should only be loosely coupled and communicate via REST. Is that possible with pure Java (without XML, I haven't really dug into that yet)? Best regards!
Yes it is possible with pure Java. Start with spring-boot. The quick start example is good enough. Use the standard maven folder structure. The static resources including angular can go into the folder `src/main/resources/static`. The resources/static folder gets mapped to the root of the context. So `src/main/resources/static/index.html` gets mapped to `<webcontext>/index.html`. And no need for the HelloController in the example. This is a simple setup. For a more complete one, you might need a dependency and build system for the client code as well - various combination of bower, grunt, gulp..
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "angularjs, spring" }
How to prevent posting duplicate comments on Wordpress? I have looked everywhere, here and on the web, and couldn't find the solution. Basically, I'm trying to prevent posting duplicate comments on WordPress. I have read somewhere that it's not that simple, and first WordPress needs to compare already posted comments. Maybe someone has a quick and easy solution, or have done/implemented something similar on their own Wordpress blog. Maybe a simple code for functions.php? Any help would be greatly appreciated.
Although what you ask seems reasonable, in reality it has a design flow: ensuring that every comment, ever, is unique is expensive as it depends linearly on all your comment base. This means that every time a user posts a comment, that operation will take more and more to complete. Beside this, defeating this expensive validation is trivial and involves just adding some padding characters: suddenly, you must implement more custom checks for every comment posted, thus slowing down your site more. The more your site slows down, the more resources (and money) and money you need. Assuming you are fighting spam, there are plugins designed for that purpose (like Akismet cited in the comments). A spam filter plugin doesn't scan all your comments, but uses more advanced techniques to evaluate different aspect of the text to be analyzed, and then decide whether or not to filter it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, wordpress" }
Get image attachment to a post outside the loop? What's the best way to display the URL to an image that's attached to a post and is outside the loop? This is the code I'm using to display the results: <?php foreach($duplicates as $postID) { ?> <?php $postData = get_post( $postID );?> <?php if(esc_html(get_the_category($postID)[0]->slug) == 'group-a-first'):?> group a first (only) - <?php print $postData->post_title;?><br> <?php endif;?> <?php } ?> I was able get results using `<?php print wp_get_attachment_image_src( get_post_thumbnail_id( $postID ), 'thumbnail' )[0];?>` but it works only if a post has a featured image.
try using get_attached_media function and your current `$postID` $images = get_attached_media( 'image', $postID ); this will return a WP_Post object. If you want to get the url, it's located in the `guid` key of the object. Use a foreach loop to retrieve them all. foreach( $images as $image ){ $src[] = $image->guid; } To use a different size image, try foreach( $images as $image ){ $src[] = wp_get_attachment_image_src( $image->ID, 'thumbnail' )[0]; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "attachments, images" }
Regression evaluation in R Are there any utilities/packages for showing various performance metrics of a regression model on some labeled test data? Basic stuff I can easily write like RMSE, R-squared, etc., but maybe with some extra utilities for visualization, or reporting the distribution of prediction confidence/variance, or other things I haven't thought of. This is usually reported in most training utilities (like caret's train), but only over the training data (AFAICT). Thanks in advance.
Bootstrap confidence intervals for parameters of models can be computed using the recommended package **boot**. It is a very general package requiring you to write a simple wrapper function to return the parameter of interest, say fit the model with some supplied data and return one of the model coefficients, whilst it takes care of the rest, doing the sampling and computation of intervals etc. Consider also the **caret** package, which is a wrapper around a large number of modelling functions, but also provides facilities to compare model performance using a range of metrics using an independent test set or a resampling of the training data ( _k_ -fold, bootstrap). **caret** is well documented and quite easy to use, though to get the best out of it, you do need to be familiar with the modelling function you want to employ.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "r" }
Spring integration project with spring MVC I am trying to integrate spring MVC(REST) layer with Spring Integration Layer, there would be to and fro traffic. I want the spring integration layer to be used by several other services too. So, the spring integration code has to be a independent jar. How should I be implementing it. 1) Create Pom dependency for SI project in the MVC project. 2) SI project to be running on the server. The SI and MVC can be on same server or different servers.(http calls) Would prefer to do the 1) way. Where the SI project jar is created as a dependency. How can this be achieved.
That's a very common pattern; just add the SI dependencies to the POM and invoke the SI flow from your controller using a Messaging Gateway.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "spring integration" }
altering height of rows produced by grid.arrange when nrow=1 Apologies if this question has already been answered but I cant seem to find what I need. I have produced two plots in ggplot2 which I am combining into the same grid using grid.arrange as follows: grid.arrange(p1,p2,main="Title", ncol=2) which gives me the plots side by side like so: !Side by side plots (Sorry I don't understand how to get this to show my image within the post, if you anyone could help me with that as an aside that would be great! I don't want to annoy people by using links.) How can I alter this code so that the graphs are still side by side but they are not elongated the entire length of the object? I would like them to be square. I know that I can add an argument "heights" but not sure if this is what I need and haven't seen anything on here applying it in this situation. Thanks!
You can also specify relative heights and widths using the `heights` and `widths` arguments to grid.arrange like so: grid.arrange(p1 , p2 , widths = unit(0.5, "npc") , heights=unit(0.5, "npc") , main="Title", ncol=2) !enter image description here
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 8, "tags": "r, ggplot2" }
Scheduling local notifications from the background (Ionic + ngCordova) I am using the ngCordova LocalNotification plugin in my Ionic app to schedule the notifications on the device and deliver them locally. My app requires to schedule a new notification every time the previous one is delivered. I am using the $cordovaLocalNotification:trigger method to schedule another notification upon receiving the last one. Everything works fine as long as I respond to the received notification and click on it. If I simply clear or ignore the notification, no new notification is scheduled and subsequently delivered. So far I managed to figure out that the problem is that the call is registered only when the app is brought to the foreground. So I am wondering how to execute my code when the app is in the background? Obviously, I cannot expect every user to reply to every notification in order to schedule the new one. Thanks a lot.
There at least two different cordova plugins to do this: * Cordova background mode * Cordova background app The first allow you to execute code while the application is in background, while the second transform your app in a service. Look at this example of the first plugin to know how to execute code in background. In your specific case, you should listen for the trigger event in the background code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "android, ios, cordova, notifications, ionic framework" }
CakePHP: How to pass url with anchor through Ajax I want to pass a certain url with anchor to cakephp as parameter. my ajax is as follows: var next_url = 'www.domain.com/search#!query=blah%20secondBlah&times=5'; $.ajax({ url : '/users/login/?next='+next_url, success: function(res) { // do something } }); In my controller, I run debug($this->request->query['next']); and it gets me only `www.domain.com/search` without the anchor part. What to do? CakePHP 2.3
I would send `next_url` in the data option of `$.ajax` so it is properly URL encoded. Try this: $.ajax({ url : '/users/login/', data: {next: next_url}, success: function(res) { // do something } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, ajax, cakephp" }
Clustered and non-clustered index Is it possible to create a non clustered index which is not unique? What data structure is used to implement non clustered indexes.
Assuming you are talking about SQL Server then simply don't specify `UNIQUE` when creating the index. CREATE /*UNIQUE*/ NONCLUSTERED INDEX IX ON T(C) As `UNIQUE` is commented out above this does not enforce uniqueness on the `C` column. But in fact it will still be made unique behind the scenes by adding the (unique) row locator in to the non clustered index key. Regarding data structure both clustered and non clustered indexes are B+ trees.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "sql server, indexing, non clustered index" }
Will the James Webb Space Telescope need re-alignment of primary mirror segments? I couldn't find an answer to this question. James Webb Space Telescope will align primary mirror segments and secondary mirror in space. Question is whether these will need re-alignment during the course of operation? And how often if so?
Each of James Webb's mirror segments are adjustable through seven small motors, called _actuators_. Due to thermal variations, the segments do indeed need to be re-adjusted occasionally. Exactly how often is a compromise between desired image quality and valuable science observation time, as argued by Park et al. (2017) who develop a thermal model, but don't seem to actually recommend any interval between re-adjustments. An older proceeding by Mather (2010) says that > it is […] expected the JWST primary mirror may be readjusted on the order of every two weeks. which is backed up by this recent SPIE article.
stackexchange-astronomy
{ "answer_score": 6, "question_score": 6, "tags": "telescope, space telescope, james webb space telescope" }
efficient way of printing lists to a table in a .txt file using python I want to create a text file which contains a table, created from lists. But, I don't want to have to do something like this: import string print >> textfile, string.rjust(listname[0],3), string.rjust(listname[1],3), The following code demonstrates the idea of what I would like to do, but doesn't work: import string listname = ['test1','test2','test3'] i=0 for i in range(0,3): print >> textfile, string.rjust(listname[i],5) I would like the output to look exactly like this: test1 test2 test3 That's what I'm trying to do and how it makes sense in my head, but obviously that won't (and isn't) working. I've used the `join()` function to print the lists nicely, but I can't get the spacing right for the table. Any ideas?
If I'm understanding the problem correctly, you could just do this... >>> def print_table(): ... headers = ['One', 'Two', 'Three'] ... table = [['test1', 2, 3.0], ... ['test4', 5, 6.0], ... ['test7', 8, 9.0], ... ] ... print ''.join(column.rjust(10) for column in headers) ... for row in table: ... print ''.join(str(column).rjust(10) for column in row) ... >>> >>> print_table() One Two Three test1 2 3.0 test4 5 6.0 test7 8 9.0 >>> No need for the `string` module or integers to index into the table. I've printed to standard out for clarity, but you can write to a file just as easily.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, list, printing" }
How to get last child *ngFor list of components I got a component that is called users-list. Inside this component there is *ngFor of directory-user component. <directory-user-card *ngFor="let directoryUser of directoryUsers" [directoryUser]="directoryUser"> I need the last directory-user-card component to have different style. So I tries to use last-child at the parent component but with no success. directory-user-card :last-child{ border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; } Any ideas?
You can use `*ngFor` \- `last` variable to check whether the element is the last element or not. if it's a last element of the loop then `last` variable will become true, so we can use `[ngClass]` to add/remove the class. Angular Docs Github Issue, where this is discussed as the correct way to handle this. <directory-user-card *ngFor="let directoryUser of directoryUsers; let last = last" [directoryUser]="directoryUser" [ngClass]="{'last-child': last}"> .last-child{ border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; }
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 12, "tags": "css, angular" }
Split a list into sublists in java using if possible flatMap here is my list: List<Integer> mylist = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12); Assuming my list is always even, then i would like to split it in 6 equal parts. List as a Sketch: [1,2,3,4,5,6,7,8,9,10,11,12] Output Sketch: [[1,2][3,4],[5,6],[7,8],[9,10],[11,12]] I would prefer a solution if possible with Java 8 stream `flatMap`
Given that the "sublists" are all of equal size and that you can divide the list into exact sublists of the same size, you could calculate the desired size and then map an `IntStream` to the starting indexes of each sublist and use that to extract them: List<Integer> mylist = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12); int size = mylist.size(); int parts = 6; int partSize = size / parts; List<List<Integer>> result = IntStream.range(0, parts) .mapToObj(i -> mylist.subList(i * partSize, (i + 1) * partSize))) .collect(Collectors.toList()); **EDIT:** IdeOne demo graciously provided by @Turing85
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "java, list, split, functional programming, java stream" }
Using IS operator to identify the type of Form I would like to write a common method which would check if a form is already open. If it is open then just activate it. Otherwise show it. Now my challenge is what type of parameter do I pass to the Test method? private void Test(?? ??) { bool isFormOpen = false; foreach (Form form in Application.OpenForms) { if (form is ??) { isFormOpen = true; form.Activate(); } } if (!isFormOpen) { } } Thanks Nishant
the way your code is written you need to pass `Type` of the respective Form class... if (form.GetType() == theTypeParam) { isFormOpen = true; form.Activate(); } An alternative is to use generice - see the answer from Heinzi for that.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "c#, reflection" }
How to create a plot based on a grouped value in R? So I have an assignment where I am supposed to create a simple plot based on some values: Species Weight Avg Cornea Diameter Great Grey 971 19.50 Great Grey 1209 19.00 Great Grey 1793 21.00 Snowy 1572 22.50 Snowy 1500 23.50 Snowy 1490 22.00 How do I create a plot of the Great Grey species only and the Snowy species only? As the assignment is supposed to be simple I'm not sure how to go back this. I want to be able to plot the Great Grey species using `plot(Weight~CorneaAvg)` but when I do that there is data for all of the species not each individual one. Any help would be appreciated!
df1 = subset(df, Species == "GreatGrey") df2 = subset(df, Species == "Snowy") with(df1, plot(Weight ~ Avg_Cornea_Diameter)) with(df2, plot(Weight ~ Avg_Cornea_Diameter)) Or you can try: library(dplyr) df %>% split(df$Species) %>% lapply(function(x){ with(x, plot(Weight ~ Avg_Cornea_Diameter)) }) **Data:** df = read.table(text="Species Weight Avg_Cornea_Diameter GreatGrey 971 19.50 GreatGrey 1209 19.00 GreatGrey 1793 21.00 Snowy 1572 22.50 Snowy 1500 23.50 Snowy 1490 22.00", header = TRUE)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "r, statistics" }
Каким боком подключить один файл js в другой? Начал с недавнего времени работать с библиотеки `anime.js`, но я не хочу засорять код html поэтому хочу созать файл `mine.js` подключить туда `anime.min.js` и потом в html просто подключить файл: <script src ="mine.js"><script> пробовал: function include(url) { var script = document.createElement('script'); script.src = url; document.getElementsByTagName('head')[0].appendChild(script); } не получилось, пробовал через `jQuery` \- не работает, помогите!
И так ответ я нашел сам, спасибо всем но ответ который я выбрал рабатал не так как я хотел, решение такое, в конце тега мы подключаем библиотеку, и потом наш скрипт файл, вот как это выглядит <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TEST STACK OVE FLOW RU</title> </head> <body> <div> <h2>Что то</h2> </div> <script type="text/javascript" src="Ваш скрипт"></script> <script type="text/javascript" src="Библиотека"></script>> </body> </html> еще раз повторяю обязательно в низ тега body !
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, anime.js" }
Loop and process multiple HDFS files in spark/scala I have multiple files in my HDFS folder and I want to loop and run my scala transformation logic on it. I am using below script which is working fine in my development environment using local files but it is failing when I run on my HDFS environment. Any idea where am I doing wrong please? val files = new File("hdfs://172.X.X.X:8020/landing/").listFiles.map(_.getName).toList files.foreach { file => print(file) val event = spark.read.option("multiline", "true").json("hdfs://172.X.X.X:8020/landing/" + file) event.show(false) } Can someone correct it or suggest alternative solution please.
You should use Hadoop IO library to handle hadoop files. code: import java.net.URI import org.apache.hadoop.fs.{FileSystem, Path} import org.apache.spark.sql.SparkSession val spark=SparkSession.builder().master("local[*]").getOrCreate() val fs=FileSystem.get(new URI("hdfs://172.X.X.X:8020/"),spark.sparkContext.hadoopConfiguration) fs.globStatus(new Path("/landing/*")).toList.foreach{ f=> val event = spark.read.option("multiline", "true").json("hdfs://172.X.X.X:8020/landing/" + f.getPath.getName) event.show(false) }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "scala, apache spark, spark streaming" }
What is the cause of the 'not found' error in my user-defined function? df <- tibble(wspid = c("text","text",1:9,NA), PID = c("text","text",1:10)) #Function to export a single column inputted in the function argument export_ids <- function(var) { export_df <- df %>% filter(!is.na(var)) %>% select(var) write_csv(export_df, "~/Downloads/final_ids.csv") } #Calling the function export_ids(wspid) I keep getting the same error: Error: Problem with `filter()` input `..1`. ℹ Input `..1` is `!is.na(var)`. x object 'wspid' not found I suspect there's some issue with the scoping of the function but no matter what combinations I try-- such as defining the tibble within the function or referencing the tibble directly within the function (as in, df$var) I still get an error.
As we pass unquoted variable, use `{{}}` (curly-curly opertor) for evaluation export_ids <- function(var) { export_df <- df %>% filter(!is.na({{var}})) %>% select({{var}}) write_csv(export_df, "~/Downloads/final_ids.csv") } -testing export_ids(wspid)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "r, tidyverse" }
Looking for a c++ compression library/libraries that can decompress rar, 7z, bz2, zip etc Not sure if a unified library like this exist or if the algorithms are even open-sourced. I Need to be able to decompress as many types as possible without having to install any other applications.
`7zip` has all its required functions to handle archives in a separate library and it can be found at < It will handle > 7z, XZ, BZIP2, GZIP, TAR, ZIP, WIM, ARJ, CAB, CHM, CPIO, CramFS, DEB, DMG, FAT, HFS, ISO, LZH, LZMA, MBR, MSI, NSIS, NTFS, RAR, RPM, SquashFS, UDF, VHD, WIM, XAR, Z .
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c++, 7zip, compression, rar" }
Why is water vapor released when an empty water bottle is squeezed? I recently came across this tutorial and wondered why vapor will come out when the cap comes off. Heres the Tutorial !enter image description here
When the cap bursts off the bottle the air inside it will expand rapidly and adiabatically, so its temperature will fall. If there is enough water vapour in the air inside the bottle, and if the temperature reduction takes the temperature below the dew point, the water vapour will condense giving the fine mist that you see. In this case it looks to me (it's hard to tell for sure) as if there were droplets of water left inside the water bottle, in which case the air inside was saturated with water vapour. Under those circumstances even a modest temperature reduction will cause condensation of the water vapour.
stackexchange-physics
{ "answer_score": 3, "question_score": 3, "tags": "everyday life, pressure" }
Is it possible/advisable to run multiple sites app pools using the same domain account I've got a rather unwieldy legacy intranet app that does a lot of file manipulations across multiple network shares (file reads, moves, deletes, creates directories, etc) and I want to set up a preproduction instance. Currently the app pool is running under a domain account that has been granted access to all these scattered directories. I'm wondering if running a second instance of the site (different server) using the same domain account would be an issue. This doesn't seem to be an easy question to formulate in a way to get a useful answer out of google. Anyone have any experience doing this? I would rather not have to create more accounts and track down all the locations that would require added permissions if I don't have to.
The aim to set different application pool identity for different application pools is to restrict the limit for application pool. Independent application pool will isolation NTFS permission from accessing the files that the web app shouldn't reach. Just in case the server are under vulnerability attack. Of course, if you are hosting your web apps in a isolated network environment, you could share your domain account for multiple application pools. As Lex said, consult your network administrator would get more practical answer.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iis, windowsdomainaccount" }
eclipse key bindings everywhere I want to assign an eclipse key shortcut. Say, `Ctrl`+`Shift`+`F` = "File Search". I can assign this in Window -> Preferences -> General -> Keys -> File Search -> Binding: `Ctrl`+`Shift`+`F` I also need to select "When". I can select one of "Editing Java Source", "Editing Java Script Source" etc. Is it possible to assign this key shortcut to be effective everywhere? What I mean is I can be doing anything in eclipse - editing Java, js, xml, etc or I could be in Console window looking at the logs. I will highlight a word I want to search and press `Ctrl`+`Shift`+`F` and eclipse just has to bring up the "File Search" dialog. How can we do this without have to assign the binding to every item in the "When" drop-down list?
Try setting "When" to "In Windows". I just checked, and the key binding worked everywhere I tested it...
stackexchange-stackoverflow
{ "answer_score": 22, "question_score": 16, "tags": "eclipse, keyboard shortcuts" }
Vasodilation decreases blood pressure Okay it should make sense intuitively, but Bernoulli's principle says that a higher cross sectional flow area means less velocity which means higher pressure! I also read in a related post that Bernoulli's principle is for inviscid flow. Blood has viscosity. But this alone should make the changes in pressure less extreme, not reverse the effects. But does the fact that blood is a non-newtonian fluid change anything?
This Wiki article on vasodilation explains it all. Vasodilation decreases the resistance to blood flow while vasoconstriction increases it. So when the resistance to flow is low (high) the heart needs to pump blood at lower (higher) pressure to maintain the same average flow rate as in a normal blood vessel.
stackexchange-physics
{ "answer_score": 5, "question_score": 3, "tags": "fluid dynamics, pressure, work, biophysics, bernoulli equation" }
Setting ASP.NET account permissions to be able to write/create new sources in the Event Log How do I go about allowing the ASP.NET account to write to the windows event log? I am trying to create a new 'source' in the event log and its not playing :( I think I can create the log by hand in the registry but this seems cumbersome. I'd rather let the code do it. If I do have to do it manually, how do I create a new 'directory' in the registry under... HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\EventLog
This might be a better question for StackOverflow. However, I'll give my 2c anyway. Since creating an event source only needs to happen once on a particular machine, you shouldn't really code your app (particularly a web app that's already running with limited privs) to create that source on demand. Granting additional permissions for the lifetime of the app just to accommodate a single call would be silly. Instead, the event source creation should take place as part of the app's installer or as a separate manual step in the deployment instructions if there is no installer. Using a manual step doesn't have to mean hand-editing the registry. It can be a separate tiny console app who's sole purpose is to setup the event source. All your app should worry about is actually writing to the log. Definitely keep in the code that checks for the source to exist. But if it doesn't find it, gracefully degrade and find an alternative way to notify the site admin like a simple error page.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "permissions, asp.net, windows event log" }
$.Deferred notify() & progress() synchronous confusion I'm using a deferred object that I sometimes want to notify synchronous (if I already have my result in the cache). Why does it only receive the last notification? var dfd = $.Deferred(); for(var i = 0; i < 3; i++){ dfd.notify(i); } dfd.progress(function(i){ console.log(i); // 2 // expected: 0, 1, 2 }); <
You only receive one notification because the progress is set after calling notify. If you set the progress method first you'll receive all: var dfd = $.Deferred(); dfd.progress(function(i){ console.log(i); }); for(var i = 0; i < 3; i++){ dfd.notify(i); } This happens because when you set the progress method, and notify has been already called, you'll probably want to receive the last value only, so you can reflect the current status inmediately.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery" }
PanelGrid não divide colunas com Repeat Tenho um panelgrid que não consigo de forma alguma dividir em colunas um ui:repeat, seja a quantidade que for. <h:panelGrid columns="2" > <ui:repeat var="p" value="#{cadSetor.campos}" > <p:commandLink actionListener="#{telaLogin.chamaTelaSelecao(p.id)}" ajax="false"> <p:graphicImage value="/imagensSetores/#{p.nomeImagem}" width="210" style="border: 0px; margin-top:1px" /> </p:commandLink> </ui:repeat> </h:panelGrid> Alguém pode me ajudar com isso?
`ui: repeat` não vai funcionar porque ele realmente não adiciona componentes a árvore de componentes. `ui: repeat` funciona apenas durante a fase de renderização e renderiza novamente seus componentes filhos várias vezes com o estado diferente. Alguns componentes, como `panelGrid`, mas também tabela de dados, esperam ter algumas crianças na árvore de componentes, a fim de funcionar corretamente. Desde que `ui: repeat` não adiciona eles,essa abordagem não funciona. Tente utilizar `c:foreach` pois pode ser uma solução no lugar do `ui: repeat`. Dê uma olhada aqui sobre `c:foreach` para melhor entendimento do por que para esta questão,`c:foreach` pode ser melhor.
stackexchange-pt_stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "java, jsf, primefaces" }
Pass different responses from server in different Activities I'm trying to create Android app which will use multiple activities and one socket for all of them. I understood that I should use `Service` which will contain socket which will be connected to the server. Every `Activity` will be use some specific requests to the server(e.g. first Activity can load users and second can send them messages). So how can I navigate the responses from the server between Activities(e.g. list of users will be passed to the first `Activity`, and messages will be loaded to the second `Activity`)?
As you say you are using `Service` for loading data from server ,after getting data you can handle response depending on type of response you fire `LocalBroadcast` and receive that in activity using dynamic `BroadcastReceiver` See tutorial for LocalBrodcast
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, android, sockets, android activity, android service" }
How to hide the main tool bar How can I hide the Main tool bar and make the Render Widget fullscreen. This is the current image of how it looks like , I want to remove the top tool bar and show the widget which has been promoted to opengl fullscreen. ![enter image description here]( this is the current code. void Renderer::FullScreen() { if (!fullScreen) { widgetRender->setGeometry(0, 0, 1920, 1024); mainToolBar->hide(); fullScreen = true; } else { widgetRender->setGeometry(960, 500, 960, 512); fullScreen = false; } } mainToolBar->hide() does not hide the Main tool bar.
calling the method setVisible(bool) should be more than ok example: ui->mainToolBar->setVisible(false); ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, qt, qt5" }
How to route to a page inside a function in React w/ React-Router? I have a form in my react app that I made w/ bootstrap and react-router. When the user hits submit, I want them to go to a page, if the credentials are correct, else do nothing. <button class="btn btn-primary font-weight-bold" type="submit" onClick={handleSubmit} > Submit</button> ... function handleSubmit() { if (credentials.are.correct) { // go to page here } } Is there a way to do the above in react-router, without installing any third-party software?
Assuming you're all set and have you app wrapped in Router provider you can `useHistory` hook. Here's an example from react-router-dom docs: import { useHistory } from "react-router-dom"; function HomeButton() { let history = useHistory(); function handleClick() { history.push("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> ); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, reactjs, react router dom" }
Google spreadsheets—sum cells from another row based on a cell value My current code is: (SUM(INDIRECT(ADDRESS(ROW()-(I4:I- 1);COLUMN()-4;4)&":"&ADDRESS(ROW();COLUMN()-4;4)))*( ( J4:J ) / 10 )))) I want to sum cells from `Gx` – `Gy` but range is determed by cell `I4`. My existing code works, but only for one line. =ArrayFormula( if( J4:J = "" ; "" ; So if I put `ArrayFormula` in front, the calculation is shown only where the data is, but the result is always equal to the result of first row. Can anyone help me? You can view my sheet here.
With the magic of matrix multiplication and this solution (credit where credit is due), I have managed to wrangle it to do what you want. =ArrayFormula(IF( J4:J = "" ; "" ; MMULT((ROW(G4:G)>=TRANSPOSE(ROW(G3:G)))*((ROW(G4:G)+1-I4:I)<=TRANSPOSE(ROW(G3:G)));G3:G)* ( ( J4:J ) / 10 ) )) My head hurts already, so I won't go into too much explanatory detail, except to say that the key magic happens in ="MMULT((ROW(Range1)>=TRANSPOSE(ROW(Range2)))*((ROW(Range1)+1-I4:I)<=TRANSPOSE(ROW(Range2)));Range2)))" And I've added a second sheet to your public one with a rough equation builder, for understanding or alternative applications.
stackexchange-webapps
{ "answer_score": 1, "question_score": 1, "tags": "google sheets" }
Cropping map to border of shapefile using QGIS I am new to QGIS. I have a number of layers in QGIS, all ot them covering different areas (some Germany only, some Europe etc). I want to export a map as a picture that uses the (German) border of the shapefile, essentially cropping away everything outside of German border. How can I do that?
Copy the shape of Germany to a new layer, set layer rendering to `Inverted Polygons` and apply a style. _Screenshot: here the style is set to a semi-transparent red for visualization purpose. You could set a white, opaque style:_ ![enter image description here](
stackexchange-gis
{ "answer_score": 1, "question_score": 0, "tags": "qgis, export" }
Tomcat server not being recognized I'm currently using Eclipse Mars on OS X to build a PHP based application which requires a web server for a form submission. However, upon attempting to add Tomcat 7.0 as a server, the server list is empty (shown below).![Blank Server List]( I've been following several tutorials for setting up and configuring a Tomcat server and each one says to place the extracted Tomcat folder in the Eclipse workspace directory so they'll be detected when adding them in Eclipse. The Apache Tomcat folder is in the workspace directory but it still isn't being detected. I've tried reinstalling Eclipse and deleting any duplicate files but I keep getting the same result. How can I properly set up and configure an Apache Tomcat server in Eclipse Mars?
You can tell it about the Tomcat installation using the Server Runtime Environments preference page. ![enter image description here]( If Tomcat isn't already a known server type, you might need to install a few more. The WTP FAQ has instructions. All of those tutorials are wrong. You do want to download a copy of Tomcat from Apache so it has the expected layout when Eclipse looks for the jars needed to launch it, but there's no reason to actually put it in the workspace.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "eclipse, tomcat" }
Compare the same file in two git branch I have two git branch. I want to compare the same file in two git branch. But I don't want to switch branch. How to do it?
You can use the following command to compare a single file between branches: git diff branch1 branch2 -- myfile.test
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "git" }
How can i combine the colours of one raster with values from another I have two Tiffs with data from the same area. One is in colour and when I use the identify shows a 'color index' number (eg. 141), then Color(a,r,g,b)(eg. 255,90,255,0). The other tiff contains a numerical value for the cell. I want a raster that contains both the colour info from the first tiff, and the numerical values from the second. Is there a way to add attributes from another raster or create a new raster that borrows from these two?
Have you considered building a raster attribute table? You can add/delete fields and join tables.
stackexchange-gis
{ "answer_score": 1, "question_score": 1, "tags": "arcgis desktop, raster, geotiff tiff, fme, raster conversion" }
How to capture a multiple patterns using regex? I have several text files, containing error values. The values are different in each file and so i'm not able to get the exact line where the value is present. The example is as follows: v1 = 1111 v2 = A:10 B:2 Text: 12.10.08,11:12:39,183769 1111,10352,003,12,11:12:39,183 Syntax-->12345 (would like to capture v1) 01.01.02,06:10:56,243648 00488,00000,018,01,06:10:56,243 A:10 B:2--1212 (would like to capture v2) The regex is as follows: ((\d{2}[.]\d{2}[.]\d{2}),(\d{2}[:]\d{2}[:]\d{2},\d*\s*(('+v1+')[,].*|\S*\s('+v2+')).*)) Irrespective of the value passed, it should go through text and grab the value. If v1 is present, should provide the complete text and if v2 is present the same. But with one regex equation.
You might use: \d{2}\.\d{2}\.\d{2},\d{2}:\d{2}:\d{2},\d{6}(?: \d{5}(?:,\d+)+:\d{2}:\d{2},\d+)? (\d{4}\b|[A-Z]:\d{2} [A-Z]:\d) **Explanation** * `\d{2}\.\d{2}\.\d{2},\d{2}:\d{2}:\d{2},\d{6}` Match the format of the starting digits * `(?: \d{5}(?:,\d+)+:\d{2}:\d{2},\d+)?` Optionally match the part starting with 5 digits up until a time like format * `(` Capturing group * `\d{4}\b` Match 4 digits * `|` Or * `[A-Z]:\d{2} [A-Z]:\d` Match `A:10 B:` format * `)` Close group Regex demo
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "regex, regex lookarounds, regex group, regex greedy" }
budget's funds (Why are "budget" and "funds" used together?) A native speaker wrote the below sentence as a sample sentence for me to study. I don't understand "budget’s funds". "Budget" is money. "Funds" are also money. Why say money twice? Also, does "funds" mean "a sum of money saved or made available for a particular purpose"? > The table displays the sources of the **budget’s funds** while the charts show how the funds were spent. ![enter image description here](
In English, "budget" as a noun can mean just money in a casual sense, but it more commonly means a scheme (or plan) to spend money. A budget is a plan describing what various things funds will be spent on. The Cambridge English dictionary defines budget as "a plan to show how much money a person or organization will earn and how much they will need or be able to spend" ( < ) The plan (budget) has an amount of money (funds) to allocate. In the example you gave, the illustration shows where that money came from, and what the plan allocated that money to.
stackexchange-ell
{ "answer_score": 6, "question_score": 1, "tags": "meaning, word meaning" }
Referencing a child component inside v-dialog I have a problem to get the reference of a component inside the component _v-dialog_ of vuetify. This code prints _undefined_ in console instead of the object. <template> <v-dialog ref="mydialog"> <v-card ref="mycard"> </v-card> </v-dialog> </template> <script> export default { mounted() { console.log(this.$refs.mycard); } } </script> Is not possible to access a child component by reference inside a _v-dialog_ ?
You can't get access to v-card component because of lazy loading in vuetify 2. If you are sure that you need to access the v-card component at mounted stage, you could add **eager** prop to v-dialog component. This code works: <template> <v-dialog ref="mydialog" eager> <v-card ref="mycard"> </v-card> </v-dialog> </template> <script> export default { mounted() { console.log(this.$refs.mycard); } } </script>
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 3, "tags": "vue.js, vuetify.js" }
Error in declaring default parameters for method I am using default parameters but I'm getting error > Default parameter value for 'regularExpression' must be a compile time constant Here is the **method** signature: public static PIPE.DataTypes.BuyFlow.Entities.Question GetEmailAddressQuestion(string regularExpression = RegularExpressions.EmailAddressRegex, int rank = 1, bool isRequired = true) { } And here is the property: public static string EmailAddressRegex { get { string emailAddressRegex = @"^[A-Za-z0-9\._%\+\-]+@([A-Za-z0-9\-]{1,40}\.)+([A-Za-z0-9]{2,4}|museum)$"; return emailAddressRegex; } }
It is like the error message says. Default parameters have to be constants (at compile time). The Getter of `EmailAddressRegex` could return different values during runtime. That this is always the same value is not known to the compiler. So change the `EmailAddressRegex` to a `const string` than the compiler error will be gone. E.g. public const string EmailAddressRegex = @"^[A-Za-z0-9\._%\+\-]+@([A-Za-z0-9\-]{1,40}\.)+([A-Za-z0-9]{2,4}|museum)$";
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c#, function, methods, default parameters" }
Can't update web properties account id through the Management API I'm unable to update the web properties account id through the Analytics Management API. It returns response 200 but without any changes. I'm able to update other properties like the name or the website url. The account to which I want to move the web property is part of the same google account. So, I don't see why it wouldn't let update the account. Are there some conditions when moving web properties ? I also tested the request with the live debugger in the Analytics documentation reference and I get the same response.
Not all of the fields on the web property resource are writeable. You can not change the account id on a web property. I will contact the team about getting a note added to the documentation so that you can see which fields are writable. > Are there some conditions when moving web properties ? It is not possible to move a web property.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "google analytics, google analytics api" }
Linux/Kernel module: Can a driver be used by two user programs? I'm trying to develop a "virtual" video driver based on ViVi project example. It's virtual since it doesn't interact with any camera. It gets a video stream from a user program (C++) and also it acts as video driver for another user program (Flash) which displays the video stream. So, if I have a /dev/video0. One program needs write frame to it and another reads one from. Is that possible? I need this because Flash doesn't recognize this camera, so I use a virtual driver as a bridge from my grabber (which uses the real driver) and Flash.
There used the vloopback driver, which did exactly what you want to do. However, it wasn't part of the standard kernel. Some time ago, I wrote a library (dv4linux that intercepted libc read/writes to /dev/video to achieve something similar. The current version has serious issues with newer firefox's malloc handling, though. berlios.de may fo out of service soon.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "linux, flash, module, linux kernel, linux device driver" }
How to get YouTube Data API response in real time and proactively? With YouTube Data API we can parse comments from a certain video, reply to these comments, modify and delete our comments etc. But in this aforementioned documentation I didn't find the way to fetch the user comments in **real-time**. So the situation is like - apart from fetching comments when the API is called, I want the API to proactively update me with most recent changes if any new comment arrives or any modification or deletion happens. Any way to achieve this?
The only way to find out of there have been comments its to poll the API and check every now and then. There are no push notifications for comments if that's what you are looking for. Push notifications only work for. > push notifications > > * uploads a video > * updates a video's title > * updates a video's description >
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "youtube api, youtube data api" }
Java JAXB Pros/Cons and Documentation It's been a while since I used Java in anger so please forgive me if this is silly. I have just got started on a Java project where we are using JAXB to de-serializing an incoming XML string (from Jetty Server). The project is only using JAXB for this situation. What are the alternatives to JAXB? What are pros/cons of JAXB to these alternatives I have done some googling and found lots of reference material, but is there a definitive source that is the goto place for JAXB questions or do people just see what people are doing and interpret from there. Thanks.
I've found JAX-B pretty useful and actually like it better than many of the alternatives, especially if I'm starting from scratch and generating a schema from Java objects rather than Java objects from a schema. In my experience, for whatever reason, I've found good documentation hard to come by from just Google searches. The best electronic documentation is provided in the JAX-B download where you'll also find numerous examples. "SOA Using Java Web Services" also has a good overview. As for alternatives, there is: * XStream * Castor and probably several more.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 14, "tags": "java, documentation, jaxb" }
Coordinate geometry circle inscribed in triangle. The circle $$x^2 +y^2 -4x-4y+4=0$$ is inscribed in a triangle which has two of its sides along the coordinate axes. How can we find the equation of the third line. Now I have assumed that the line's equation would be $${x \over a} + { y \over b} =1$$ where $a$ serves as the x intercept and $b$ as the y intercept. ![enter image description here]( Now since this line would be a tangent the perpendicular distance of the line from the centre of the circle would be equal to the radius of the circle. Perpendicular distance from $(2,2)$ to $bx+ay=ab$: $${|2b+2a-ab| \over \sqrt{b^2 +a^2}} = 2$$ This gives me one equation with two variables. How can I find other equations in order to solve this system? ANY HINT WOULD WORK.
As N.S.JOHN points out in his comment, there are an infinite number of such lines. If you parameterize the circle as $x=2+2\cos t$, $y=2+2\sin t$, then $\mathbf n=(\cos t,\sin t)$ is a normal to the circle at $(x(t),y(t))$, and an equation of the tangent at this point is $$\mathbf n\cdot(\mathbf x-(2,2))=(x-2)\cos t+(y-2)\sin t=2.$$ This line, together with the coordinate axes, will form a circumscribed triangle for $0\lt t\lt\pi/2$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "analytic geometry, coordinate systems" }
Why print cannot be used with for on the same line in python 2/3? I would love to implement the following: print(i) for i in xrange(10) However, this does not work in neither python2 nor python3. What is the limitation of the language? Or what did I do wrong?
**Set builder notation (called generator expressions in Python) only work when you are building a set.** The notation you are using is set builder notation (generator expressions) (something like `x for x in range(10) if ...`). That being said, you can use a regular for loop for i in xrange(10): print(i) or set builder notation building an empty set: >>> x = [print(i) for i in xrange(10)] 0 1 2 3 4 5 6 7 8 9 >>> x [None, None, None, None, None, None, None, None, None, None] >>> The reason the set has all the none values is because you are never adding to the set, but only printing stuff out.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "python" }
F# assignment printf and for loops I need help with a F# question I got at my first year of data science. Spent quite some hours on this and still can't figure it out. **So the assignment is about "printf" and loops and goes like this:** > Make a function: > mulTable : n: int -> string (so the input is an integer and the output is a string) > > which takes 1 argument and returns a string containing the first 1 <= n <= 10 lines so the table can be printed with a single printf "%s" statement. > > For example a call to mulTable 3 should return: > > ![enter image description here]( I don't want the result, but maybe some kind of hint could be so helpful!
Figured out a way! Add a for loop and a nested for loop! where in the nested for loop your print (i*j) as if you had for let function = for i = 1 to 10 do for j = 1 to 10 do printf "%i" (i*j)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "f#" }
Types and forms of adjectives in German I am reading this article. In the beginning it is said that there are three type of adjective: 1. Predicative 2. Adverbial 3. Attributive Then later there is a mention of the comparitive forms of adjective: 1. Basic 2. Comparitive 3. Superlative In the article, only for superlative was a tie in to the three type of adjective said; how to form superlative in the three type of adjective. However, does there exist the three form of adjective for the Predicative and adverbial form?
_Predicative_ means that the adjective is an argument of a verb that takes a predicative phrase rather than objects. Such verbs are for example _sein, werden, bleiben, gelten als_ and some more. It's not declined then. * Das **ist** **leicht / leichter / am leichtesten.** _Adverbial_ means that the adjective describes a verb or another adjective. It's also not declined then. * Sie **macht** es ihm **leicht / leichter / am leichtesten.** * Sie macht es ihm **leicht / leichter / am leichtesten verständlich.** _Attributive_ means that the adjective describes a noun. It's declined then. * Das ist **die leichte / leichtere / leichteste Aufgabe.**
stackexchange-german
{ "answer_score": 2, "question_score": 0, "tags": "adjective" }
How to calculate vertices of dodecahedron using W|A? Can I calculate for example with wolfram alpha coordinates of vertices of dodecahedron? I know coordinates of center point of dodecahedron (center of gravity) and the height of dodecahedron. Thanks for advice.
Yes, Wolfram Alpha can do it. Inputting [`PolyhedronData["Dodecahedron", "VertexCoordinates"]`]( into Wolfram Alpha will yield a set of vertex coordinates you can use for a dodecahedron with unit edge length. Alternatively, MathWorld gives a simple set of coordinates for a dodecahedron with edge length $\dfrac2{\phi}$, where $\phi$ is the golden ratio: $(0,\pm\phi^{-1},\pm\phi),(\pm\phi^{-1},\pm\phi,0),(\pm\phi,0,\pm\phi^{-1}),(\pm 1,\pm 1,\pm 1)$ and all combinations of signs are taken.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "polyhedra, wolfram alpha" }
how do i get the numeric representation of a character in javascript? I'd like to get a javascript numeric representation for a letter to do some relative manipulation i.e. in pseudocode to conduct an operation like 'a'.getNumberRep - 'b'.getNumberRep. Best way to do this in js?
'a'.charCodeAt(0) - 'b'.charCodeAt(0)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "javascript, numeric, alphabet" }
What did halfnorm() go? I would like to generate a half normal distribution in R (just the values above my specified mean). I have tried rhalfnorm() but R doesn't recognise this as a function, was this function only available in earlier versions of R? what function could I use instead?
You can do that with the `dtnorm`, `rtnorm`,`ptnorm`,`qtnorm` functions in base R described here. You will need to supply the cutoff values both lower and upper (in this case the mean for the lower) to get what you want. Here is a link to the vignette: tnorm vignette
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "r, version, distribution" }
Declare a structure which is inside a class I've a class with a subclass and inside the subclass there's a struct. I want to call this struct by name. I want to declare a variable with those and give `name` `number1` and `number2` its own data. class Main { var name:String init(name:String){ self.name = name } } class SubMain: Main { override init(name:String){ super.init(name: name) } struct Test { var number1:Int var number2:Int } } I've tried declaring subMain, and after declaring that I called `Test` struct but it doesn't work. Looking for solution: var main2 = SubMain(name: "hello") main2.Test(number1:15,number2:20)
Your use case is a bit strange, the main reason for declaring an internal type within another type is that you want to use the internal type inside the outer type. An example class SubMain: Main { var test: Test? override init(name:String){ super.init(name: name) } convenience init(name: String, test: Test) { self.init(name: name) self.test = test } struct Test { var number1:Int var number2:Int } } And then var main2 = SubMain(name: "hello") var main3 = SubMain(name: "world", test: .init(number1: 1, number2: 2)) But to use your example you should access it via the outer type and not an instance of that type var test = SubMain.Test(number1: 1, number2: 2)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "swift" }
Согласование местоимения «который» с определяемым словом Предложение: "Ищите людей, разговор с которыми стоил бы хорошей книги, и книги, чтение которой стоило бы любого разговора". Правильно ли во второй части предложения местоимение _которой_ использовано в единственном числе, в то время как слово _книги_ , на которое оно ссылается, – во множественном. Или же все-таки это можно счесть за нежелательный вариант и лучше так не делать?
_Ищите людей, разговор **с которыми** стоил бы хорошей книги, и книги, чтение **которых** стоило бы любого разговора._ Пояснение Это сложноподчиненное предложение (СПП) с двумя **определительными придаточными** и союзными словами "которыми, которых". Главное предложение: _Ищите людей и книги_. Союзное слово "который" в этих предложениях является **дополнением.** Оно согласуется с определяемым словом **во мн.числе** , а падеж (Т.п. и Р.п.) ему задают существительные (разговор и чтение) в придаточном определительном предложении. Ищите людей (каких?), разговор с которыми (то есть с такими людьми) стоил бы хорошей книги, и книги (какие?) , чтение которых (то есть таких книг) стоило бы любого разговора.
stackexchange-rus
{ "answer_score": 2, "question_score": 1, "tags": "синтаксис, грамматика, согласование, единственное множественное число" }
Coin Change Problems Suppose I have 4 coins of denominations 1 3 4 5. I want to make it 7. I learn how to find how many possible ways that can be done. But I want to determine what is the minimum number of coins that must be used to do that. Example: 5+1+1=7 again 3+4=7. So the minimum number of coins is 2. Any pseudo code or explanation or source code will be helpful
If you want to make change for the number n, set up an array number_of_coins[n] and fill it in from left to right. number_of_coins[0] is 0, obviously. The next few you can do by hand (although once you have an algorithm it will fill them in automatically). To fill in larger entries m in the array, think about this: what if I removed 1 cent from m? Or 3 cents? Or 4 cents? Or 5 cents? Once you have the number of coins array up to n, you can walk backwards through it to find the exact coins to use.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -5, "tags": "c++, dynamic programming, coin change" }
Symplectic Lefschetz fibrations in terms of factorization in symplectic mapping class group There is a well-known theorem stating that there is a bijection between diffeomorphism classes of Lefschetz fibrations over $S^2$ whose general fiber is a closed orientable surface $\Sigma_g$ of genus $g\geq 2$ and factorizations of identity in the mapping class group $\Gamma(\Sigma_g)$ up to Hurwitz moves and global conjugation. It is explained here, for example. Is there an analogue of this theorem for symplectic Lefschetz fibrations in higher dimensions? In other words, are symplectomorphism classes of symplectic Lefschetz fibrations in bijective correspondence with factorizations of identity in the symplectic mapping class group of the general fiber?
Up to homotopy, giving a Lefschetz fibration over $S^2=\mathbb C\cup\\{\infty\\}$ with singular fibers over $\\{e^{2\pi ik/N}\\}_{0\leq k<N}$ is the same as giving the data of the fiber $F$ over $0\in\mathbb C$, the vanishing cycles $\\{L_i\\}_{0\leq i<N}$ (as marked Lagrangian spheres in $F$), and a path in $\operatorname{Symp}(F)$ from the identity to the product of Dehn twists about the $L_i$. Note the importance of remembering the path rather than just equality in $\pi_0$: symplectic fibrations over $S^2$ with fiber $F$ over the basepoint, with no critical points, are classified by elements of $\pi_1\operatorname{Symp}(F)$ via the clutching construction. This does not contradict the statement you give for $F=\Sigma_g$ since the components of $\operatorname{Symp}(\Sigma_g)$ are contractible. The discussion of Hurwitz moves is the same as in the case of surfaces you mention. There is some discussion in sections 15-16 Seidel's book which may be helpful.
stackexchange-mathoverflow_net_7z
{ "answer_score": 3, "question_score": 6, "tags": "sg.symplectic geometry, mapping class groups, fibration" }
How to include AIC in table after margins postestimation results I have a GLM model, which I estimate in Stata. The coefficients of interest are the marginal effects, which I get with `margins` command. However, the postestimation table does not include summary statistics like AIC, which I would like to have there. I have tried this by writing an auxiliary program `getAIC`: program getAIC estat ic matrix list r(S) matrix S = r(S) scalar aic = S[1,5] end The estimation would then proceed like this: qui glm y x, fa(bin) link(probit) getAIC qui margins, dydx(x) post estadd loc AIC aic And the output command is: esttab using output.tex, s(aic, fmt(0)) However, I don't have AIC in the results table. Any ideas how to do this?
You need to return the scalar `aic` from your program `getAIC` and use it accordingly. The following works for me: program getAIC, rclass estat ic matrix list r(S) matrix S = r(S) scalar aic = S[1,5] return scalar aic = aic end sysuse auto, clear glm foreign price, fa(bin) link(probit) getAIC local AIC = round(`r(aic)', .01) margins, dydx(price) post estadd local AIC `AIC' esttab using output, s(AIC) replace type output.txt ---------------------------- (1) ---------------------------- price 0.00000766 (0.43) ---------------------------- AIC 93.89 ---------------------------- t statistics in parentheses * p<0.05, ** p<0.01, *** p<0.001
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "stata" }
Different consequences of Wick's theorem in fermionic and bosonic condensed matter systems Based on Wick's theorem, the time-ordered product of operators can be written as a sum of normal-ordered product and products involving all types of contractions. Upon taking the ground state expectation value, people claim that the normal-ordered products will have zero expectation. I have no doubt regarding this if we are considering the bosonic system. However, when it comes to fermionic systems, the ground state is the filled fermi sea, and if in this case the normal-ordered product is something like $c^{\dagger}_kc_k$ with $k<k_F$, then its ground state expectation will not vanish. If this is the case, then what would be its physical consequences?
The normal-ordered operator is defined as the difference between the operator and the ground state expectation value of that operator, e.g. $$[\hat{O}] \equiv \hat{O}-\langle \hat{O} \rangle$$ so the ground state expectation value of the normal-ordered operator should be zero. In your case of free fermi sea, if $k<k_F$, $$\begin{align} [c^{\dagger}_k c_k] & \equiv c^{\dagger}_k c_k-\langle c^{\dagger}_k c_k \rangle_0 \\\ & = c^{\dagger}_k c_k -1 \end{align}$$ so one would get $\langle [c^{\dagger}_k c_k] \rangle_0=0$. Maybe it's better if you can give a more concrete example of your question.
stackexchange-physics
{ "answer_score": 3, "question_score": 2, "tags": "operators, hilbert space, vacuum, fermions, wick theorem" }
Existence of smooth diffeomorphism $f$ of open ball onto itself with $f(0) = p$. I am trying to show that for every point $p$ of the open $n$-disk $B^n$, there exists a smooth diffeomorphism $B^n \to B^n$ sending $0$ to $p$. Certainly, it seems intuitively obvious for points $p$ that are very close to $0$, but I am not used to explicit constructions of continuous/differentiable maps. Thanks.
**HINT** : Look for a diffeomorphism that is the identity outside a neighborhood of a path joining $0$ and $p$. You might think of getting this diffeomorphism by finding the flow of a vector field (which should therefore be $0$ outside said neighborhood).
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "differential geometry, differential topology" }
Why one shouldn't play the 6th string of an A chord on guitar? Well everything is in the title: Why one shouldn't play the 6th string of an A chord on guitar? ![A chord on guitar]( As you may see on the diagram above we are supposed to strum the 1st string. But the 1st one is the same as the 6th one. So this is why I don't understand why we don't strum the 6th string on the A chord. Thanks
You can play it; you'll be playing the a second inversion of the A major chord, with the fifth (E) in the bass. However, * The bass notes of the guitar are quite low, so playing two notes a fourth apart can sound rather muddy. (See **this recent question**, among others) * In many cases, an 'A' notated as the chord is intended to also indicate that A is the bass note. If that's the case, you might want to avoid the low E string, and ensure that the lowest note is A (especially if playing the piece solo, without a bassist) to get the correct movement of the 'bassline' from one chord to the next.
stackexchange-music
{ "answer_score": 17, "question_score": 15, "tags": "guitar, theory, chords" }
How to check if a list of one numpy array contains another numpy array For example, I want, given the list `given_list = [np.array([1,44,21,2])]` Check if this list contains another numpy array, for example `np.array([21,4,1,21])` I tried this but it checks if each element of the numpy array is the equal to the new numpy array import numpy as np given_list = [np.array([1,44,21,2])] new_elem = np.array([21,4,1,21]) print([new_elem==elem for elem in given_list]) I would like to receive '[False]', but instead I get '[array([False, False, False, False])]'. I don't understand why `given_list` is identified as a numpy array and not as a list of one numpy array.
You can use `numpy.array_equal`: [np.array_equal(new_elem, elem) for elem in given_list] or `numpy.allclose` if you want to have some tolerance: [np.allclose(new_elem, elem) for elem in given_list] output: `[False]`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "list, numpy" }
webRTC: How to detect audio/video presence in Stream? I would like to know the tracks presence in received stream onaddstream callback. Video calling is working well but I would like to make. audio only call, so I just passed `audio:true,video:false` in getUserMedia constraints, now when I receive stream I cant figure out tracks presence in stream. How to know tracks presence in stream?
To Know presence of Audio and Video use `getAudioTracks` and `getVideoTracks`. function checkStream(stream){ var hasMedia={hasVideo:false,hasAudio:false}; if(stream.getAudioTracks().length)// checking audio presence hasMedia.hasAudio=true; if(stream.getVideoTracks().length)// checking video presence hasMedia.hasVideo=true; return hasMedia; } To stop passing Video in stream change offer and answer constrinats. constraints = { optional: [], mandatory: { OfferToReceiveAudio: true, OfferToReceiveVideo: false } };
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 9, "tags": "javascript, html, html5 video, html5 audio, webrtc" }
How find the $a_{n}$ close form Question: > let $a_{1}=1,a_{2}=3$, and $a_{n+2}=(n+1)a_{n+1}+a_{n}$ find the close form $a_{n}$ my try: > let $$\dfrac{a_{n+2}}{(n+1)!}=\dfrac{a_{n+1}}{n!}+\dfrac{a_{n}}{(n+1)!}$$ so $$\dfrac{a_{n+2}}{(n+1)!}-\dfrac{a_{2}}{1!}=\sum_{i=1}^{n}\dfrac{a_{i}}{(i+1)!}$$ But we can't find the $a_{n}$ Thank you
Hint: Use the following recurrence equations: $$I_n(z)=\frac{2(n+1)}{z}I_{n+1}(z)+I_{n+2}(z)$$ and: $$K_n(z)=\frac{2(n+1)}{z}K_{n+1}(z)-K_{n+2}(z)$$ If you put $z=2$ and $a_n=I_n(-2)+K_n(2)$ you get: your recurrence equation in $a_n$ You can find what you need here
stackexchange-math
{ "answer_score": 3, "question_score": 6, "tags": "sequences and series" }
Django 1.11 to 2.0 => unit tests are 2x slower I just upgraded from Django 1.11 to 2.0. I changed nothing in the code except backwards incompatibilities: * changing `url` to `path` with route instead of regex argument * adding a few `on_delete` arguments where I had forgotten Here are my unit tests run in local before and after the migration: * before: `Ran 496 tests in 62.891s` * after: `Ran 496 tests in 157.244s` I have tested with my CI that runs on an Heroku environment (to be sure it's not related to my local env), same result (2x longer to execute tests). **Question** Do you have any idea of what's going on here? How would you debug this?
I found the answer on the Django Changelog here > The default iteration count for the PBKDF2 password hasher is increased from 36,000 to 100,000. As I'm creating lots of user in my unit tests, this change had a huge impact. For the comparison, defining in settings.py this: PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',) lead to 5x slower tests: `Ran 496 tests in 31.781s` I guess the right solution to keep fast tests is to define a custom PASSWORD_HASHERS value when running tests.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "django, django rest framework" }
ASP.NET MVC Bundling Subfolders structure I want to include javascript files from whole folder and subfolders into a single ASP.NET Bundle. The purpose of this is to load all files from that folder at once. The idea is to create an angular application and load all app files with a single bundle. 1. Is this idea ok ? 2. The problem I have is that the Script tags added to HTML don't respect the subfolder strucutre of my application and the files can't be found. Bundle config: bundles.Add(new ScriptBundle("~/bundles/app").IncludeDirectory( "~/app", "*.js", true)); Folder Structure app controller/appMenu.js modules/navigation.js app.js On client side the included tags look like this: <script src="/app/appMenu.js"></script> <script src="/app/navigation.js"></script>
I think it might be related to this: < What version of the System.Web.Optimizations assembly are you using?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, angularjs, asp.net mvc 5, scriptbundle" }
Change a color of random cell in a worksheet I want to randomly choose a cell and paint it in a color, but I don't know how can I randomly choose a cell, I searched In Google but I didn't find anything useful, I've tried all the examples given by google but nothing works. I want to save the random generated cell inside a variable and then be able to change its color, value and etc. **How can we do that?** Sub RandomCell() x = ' Random Cell ' Range(x).Interior.Color = RGB(255, 0, 0) ' Red ' End Sub **Or maybe even return the cell that was generated** Function RandomCell() As Cell 'What is the data type for a cell?` x = ' Random Cell ' Range(x).Interior.Color = RGB(255, 0, 0) ' Red ' RandomCell = x End Function
Use the `rnd` function to determine the row and column. The formula is `Int((upperbound - lowerbound + 1) * Rnd + lowerbound)` So assuming you can see roughly 25 rows and 25 columns it would be: Dim r As Long Dim c As Long r = Int((25 * Rnd) + 1) c = Int((25 * Rnd) + 1) Debug.Print "row: " & r, "column: " & c Cells(r, c).Interior.Color = vbRed Returning a cell: Function randomizecell() As Range Dim r As Long Dim c As Long r = Int((25 * Rnd) + 1) c = Int((25 * Rnd) + 1) Set randomizecell = Cells(r, c) End Function Sub colorcell() Dim cell As Range Set cell = randomizecell() cell.Interior.Color = vbRed End Sub
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "excel, vba" }
How do you check an array to see if it has more even values than odd? I'm working on a project and one of the things I need to do is create a method where it takes in an int array and checks it to see if it has more even than odds. The method needs to be `boolean` and take in an `int[]` I know I need to use a `for` statement with something like for (int i = 0; i < hasMoreEvenThanOdd.length; i++) or for (int values : hasMoreEvenThanOdd) But I'm confused on what the for loop would contain something like this? if (numerator % denomEven == 0) { boolean res = true; return res; } else if (numerator % denomOdd == 0) { boolean res = true; return res; } else { boolean res = false; return res; } and I'm not sure how to get the math to check out in the end.
You should do something like that: public boolean checkIfHasMoreEvenThanOdds(int[] hasMoreEvenThanOdds) { int even = 0; int odds = 0; for (int i = 0; i < hasMoreEvenThanOdds.length; i++) { if (hasMoreEvenThanOdds[i] % 2 == 0) { even++; } else { odds++; } } if (even > odds) { return true; } return false; } The method will return true if it has more even than odds, and false if the opposite. This code "parse" the array, and checks element by element if it is or not odd, and increments in a variable (odd or even). By final, it checks which one is greater than, and return in base of that.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, arrays, for loop, integer, boolean" }
Error message when running jmeter test When I run test in jmeter, error message is displayed as setRunning(false, _local_ ) and no result in shown in view results. error message
i found the similar issue way back.. this helped me you need to listener, for example Sampler-> HTTP Request
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jmeter" }
Integration Symbol with Limits !enter image description here How can I write the integration symbol in latex as shown in the picture?
\documentclass{article} \usepackage{amsfonts,amsmath} \begin{document} \[ \int_{\substack{a\\\mathcal{P}}}^b (\nabla ...) \] \[ \int\limits_{\substack{a\\\mathcal{P}}}^b (\nabla ...) \] \end{document} !enter image description here
stackexchange-tex
{ "answer_score": 7, "question_score": 13, "tags": "math mode, math operators" }
How do I create a partial from this listing? I have the following listing: <% @backgrounds.each do |background| %> <tr> <td><%= background.image.url %></td> <td><%= link_to 'Show', background %></td> <td><%= link_to 'Edit', edit_background_path(background) %></td> </tr> <% end %> I am trying to reuse this with other controllers. This is what I have so far: <%= render partial:'image_listing', locals:{images:@backgrounds} %> <% images.each do |image| %> <tr> <td><%= image.image.url %></td> <td><%= link_to 'Show', image %></td> <td><%= link_to 'Edit', edit_image_path(image) %></td> </tr> <% end %> Is there a more generic version of edit_image_path?
<%= render partial: "background", :collection => @backgrounds %> # _background.html.erb <tr> <td><%= background.image.url %></td> <td><%= link_to 'Show', background %></td> <td><%= link_to 'Edit', edit_background_path(background) %></td> </tr> If you call the partial with the same name of the object you want to iterate, the shortest form is <%= render @backgrounds %> If you can't follow this convention, use `:collection` and `:partial` options to instruct the rendering. See `ActionView::Partials`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby on rails" }
Directory on another machine - Login credentials My application needs to access files on a remote machine that requires a username and password for accessing it. I'm trying to find out if a directory exists (using Directory.Exists) to verify I can make the 'connection. Is there a way to supply the username and password when working with remote directories? Currently Exists returns false. Cheers,
Unfortunately not. You will need to wrap your code using extra code to handle impersonation of a user that does have access. This article explains how to do it in code further down the page.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "c#, networking, filesystems, directory" }
Error loading CSV file into Neo4j enterprise edition :Illegal character in opaque part I'm trying to load a CSV file into Neo4j Enterprise edition and I think I'm considering all the rules but I don't understand what is the error related to this is the error :![enter image description here]( this is my csv file . I have entered my data in excel and then saved it as a CSV file :![enter image description here](
1. Copy your CSV file to Neo4j Import Directory. Take a look in Neo4j file locations docs. For windows desktop installations this directory is `%APPDATA%\Neo4j Community Edition\import`. 2. Change your import path to `'file:///abc.csv'` 3. Try again.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "neo4j, cypher, graph databases" }
How to Deploy WinRT Apps From a WinRT App What is the most user-friendly way to deploy Windows 8 WinRT apps from within a WinRT app assuming they are already signed with a valid sideloading certificate? Windows Phone 8 has a nice API for installing XAP packages, but I can't find anything similar for Windows 8. The best thing I can think of is to download the various installation files to, for instance, My Documents and ask users to switch over to windows explorer and run the powershell scrpt, but that is very user un-friendly. Furthermore it looks like saving appx files is restricted in the manifest, so they would need to be zipped. Can appx files be deployed via msi? That would be slightly more user-friendly. Am I missing anything? EDIT This solution needs to work for x86 as well as ARM.
The API for installing packages in Windows 8 is the PackageManager. Normally this API isn't available to Windows Store apps, but if you have a special certificate or your execution environment is somehow adapted, maybe it could work.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "windows 8, windows runtime" }
Project-To-Project Reference In VS2010 I'm using Visual Studio 2010, and I have a solution containing 2 C++ static library projects. Both projects are contained in the same directory as the solution and their output path's are both the debug folder in the solution directory. So I have project A and project B. I want project B to reference project A as if it was a static lib file included in the linker settings. So I went into project B's properties and added project A as a reference, although when I look in the class view I can't see project A as a project B reference?? Project A still compiles fine, but if I need to do anything else to access the classes I have in project A from project B (as if I was adding it through the linker section I would also have to define the location for the headers - is this neccessary when adding a project-to-project reference?)
Have you tried to set the include path for your source folder to the "Addtional Include Directories" under "Project Properties -> Configuration Propertties -> C/C++ -> General"?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "visual studio 2010" }
Get extension of a image and append it to filename and send headers accordingly I have a file picviwer.php that loads a pic as following: <img src=" id="ppic" /> It sends a GET request to a another file loadimage.php with the id of the photo to be loaded. **Below is the code for loadimage.php** if(isset($_GET['uid'])){ $uid = $_GET['uid']; $remoteImage = " $img = file_get_contents($remoteImage); header('Content-Type: image/x-png'); //or whatever readfile($remoteImage); } Right now the above code deals only for png image and I wish to extend for images of all types(.jpg,.gif etc.). For this I want to get the extension of the image and then send headers accordingly. Also append the correct extension with the filename(uid).How can I do that?
i hope it will help you . it would be little long but surly will work and can add more extension in else if condtion . if(file_exists(" { $remoteImage = " }elseif( file_exists(" ){ $remoteImage = " } and so on
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php" }
Object or function in module pattern OO JS? Recently started writing modularised js and I'm starting to notice the numerous ways one can write them. I know the core principles of when to use an object literal or function but whats the beneficiaries of writing a module as an object literal or function on a larger scale development? Portability, flexibilty, maintainability? var filterOverlays = { ..code .. }; var filterOverlays = function() { ..code ..} Call in another page: $(document).ready(filterOverlays.init); filterOverlays();
It might worth reading about Javascript AMD leaning towards functions. It can provide useful input for your decision. < <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript" }
How to populate field with data 2 levels down? We have a scenario of accounts who have contacts where some have one or more records in a custom object named members__c but not all contacts have a member__c record. member__c object has a lookup relationship with the contact object. How to select all contacts who have at least one member__c record and insert their first and last name in a field named "member__c" on the account object?
Perhaps aggregate querying will help. Something like below. List<AggregateResult> aggregates = [ SELECT Contact__r.AccountId accountId, Contact__r.FirstName first, Contact__r.LastName last FROM Members__c WHERE Contact__r.AccountId = :accountid GROUP BY Contact__r.AccountId, Contact__r.FirstName, Contact__r.LastName ]; Map<Id, Account> parentRecords = new Map<Id, Account>(); for (AggregateResult aggregate : aggregates) { Id parentId = (Id)aggregate.get('accountId'); String firstName = (String)aggregate.get('first'); String lastName = (String)aggregate.get('last'); parentRecords.put(parentId, new Account( Id = parentId, Member__c = firstName + ' ' + lastName )) } update parentRecords.values();
stackexchange-salesforce
{ "answer_score": 2, "question_score": 2, "tags": "apex" }
Достать ID из одной таблицы SUM() + MAX() Есть таблица: ID(pk) ID_2 sum 1 1 111 2 1 523 3 3 521 4 2 255 5 7 221 6 11 22 Нужно достать ID_2, но при этом сначала вычислить SUM() с группировкой по ID_2, затем найти MAX() из этих суммированных результатов, и достать ID_2. Написал следующую дичь. Буду очень благодарен за помощь! SELECT id FROM ( SELECT SUM(sum) as sumz, ID_2 as id FROM tableX GROUP BY ID_2) WHERE sumz = (SELECT MAX(sumz) FROM ( SELECT SUM(sum) as sumz, id_2 as id FROM tableX GROUP BY id_2));
SELECT id_2 FROM tableX GROUP BY id_2 ORDER BY SUM(sum) DESC FETCH FIRST 1 ROW WITH TIES ?
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "oracle" }
Accessing properties from prototype triggered by EventEmitter I'm trying to write a simple class to trigger prototype functions when an event is received, however I'm having an issue with scope. For some reason, I can't access the `Stream` context, even though I've bound my event listeners to it. function Stream(report) { this.report = report; this.stream = new api.getTagStream(report.tag); this.stream.on('error', this.onError.bind(this)); this.stream.on('data', this.onData.bind(this)); return this; } Stream.prototype.onError = err => { // Had an error } Stream.prototype.onData = data => { console.log(this.report); // undefined } new Stream({ tag: 'sometag' }); Log within `onData` should display the report object, however returns undefined.
Replace arrow function with "normal" function declaration function Stream(report, stream) { this.report = report stream.on('error', this.onError.bind(this)) stream.on('data', this.onData.bind(this)) } Stream.prototype.onData = function(data) { console.log(this.report, data) // { tag: 'some tag' } 'some passed data' } const EventEmitter = require('events') const stream = new EventEmitter() new Stream({ tag: 'some tag' }, stream) stream.emit('data', 'some passed data')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, node.js" }
Find new template Email Resetting Password FOS Fos User Bundle I'm trying to reformat the whole email of resetting password from fos user bundle. The email file it's called and located in Resources/views/Resetting/email.txt.twig and I would like to reformat it to Resources/views/Resetting/email.html.twig. I need the file being in the html format because I need to add more sections to the email. I saw there is a mention of this tempalte inside Resources/config/mailer.xml so I tried to modify it but can't success. Could anyone explain me how to be able to use Resources/views/Resetting/email.html.twig?
have a look at < fos_user: # ... service: mailer: fos_user.mailer.twig_swift resetting: email: template: '@AppBundle/Resetting/email.html.twig' you may need to modify the template path `'@AppBundle/Resetting/email.html.twig'`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "symfony, email, fosuserbundle, reset" }
How to Pause Swing in Java? * I have a main java program named MainProgram.java * MainProgram.java has its member as a JFrame MyFrame * The frame MyFrame has a JPanel in it called MyPanel * I have overriden the PaintComponent of MyPanel to draw an image. MainProgram.java constantly gets a feed from a video file and calls the paintComponent of MyPanel. What I want to do is for the program to wait until I press Enter key. Only when I press the Enter key, should the next frame be taken from the video and displayed. 1. Thread.sleep I saw in so many places cannot be used since, then it cannot listen for key press. 2. A Timer cannot be used since I am not timing anything. The dirty workaround I used was boolean x = false; . . . while(x==false); . . . onKeyPressed() { x=true; //get frame from video //call paintComponent x=false; } Anyone can give a good solution please?
Use a `SwingWorker` to collect each image frame in your implementation of `doInBackground()`, `publish()` frames as they become available, and add them to a `List<BufferedImage>` on the event dispatch thread in your implementation of `process()`. You can navigate through the `List<BufferedImage>` as shown here for `List<String>`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, swing, actionlistener, keypress" }
SQL server 2005 installation SP1 I have got problem with installation SP1 and SP2 to SQL server 2005 I get this text -> Instances of SQL Server Express cannot be updated by using this Service Pack installer. To update instances of SQL Server Express, use the SQL Server Express Service Pack installer. I don't understand what I have to do? I can`t select this box with SQL server 2005 to make update. !enter image description here Start -> Menu !enter image description here
You are running SQL Server Express, not the full version of SQL Server. SQL Server Express is the trimmed-down, free version of SQL Server. You need to download the correct service pack installers (I suspect that you'd only need to install the latest one - SP4 - but I have no way of checking): SQL Server 2005 Express SP1 SQL Server 2005 Express SP2 SQL Server 2005 Express SP3 SQL Server 2005 Express SP4
stackexchange-serverfault
{ "answer_score": 2, "question_score": 0, "tags": "sql" }
Типы в Firebird Чем отличается VARCHAR от CHAR в Firebird и правильно ли я понял, что типа STRING в Firebird нет?
Да, типа **String** в FireBird нет, используется **Char** и **varChar**. По типам данных почитайте типы данных.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "firebird, sql" }
How to bring network up on boot? Ubuntu 17.10 server. Wired network is not starting on boot. /etc/network interfaces: auto lo iface lo inet loopback auto eno1 iface eno1 inet dhcp If after booting up I do `sudo dhclient eno1` network starts successfully. What am I doing wrong? I must add that other answers to similar question include a reference to `/etc/init.d/networking` \- I do not have this file.
The ifupdown package, which managed the network, has been deprecated in favor of netplan in 17.10. The package is no longer present on new installs. The new installer will generate a configuration file for netplan in /etc/netplan, which will set up the system to configure the network via systemd-networkd (in Ubuntu Server) or NetworkManager (in Ubuntu Desktop) < Make sure that the original netplan config file is there. It should up the wired connection automatically and use DHCP to assign an IP address. Assuming the network interface name is 'eno1'. cat /etc/netplan/01-netcfg.yaml # This file describes the network interfaces available on your system # For more information, see netplan(5). network: version: 2 renderer: networkd ethernets: eno1: dhcp4: yes dhcp6: yes Generate the required configuration sudo netplan --debug generate Reboot
stackexchange-askubuntu
{ "answer_score": 6, "question_score": 1, "tags": "boot, networking, 17.10" }
add multiple objects to swift array in for loop for tempExportData in exportDataArray { let tmpRegNO:NSString = (tempExportData as AnyObject).object(forKey: kRegisteredNo) as! NSString print("tmpRegNO is",tmpRegNO) var tmpNoArray:Array = [String]() tmpNoArray.append(tmpRegNO as String) print("Count is",tmpNoArray.count) print("ARRAY is",tmpNoArray) } I am trying to add string value i.e `tmpRegNO` to the Array `tmpNoArray`. In this I can able to add only one value to the array at a time. How to add the next value to that array when it is looping for second time.
You need move the `tempNoArray` initialization outside of your `for in` loop, if not the your array will be initialized once for every item in your `exportDataArray` remaining only the las item as consequence You need something like **this** var tmpNoArray:Array = [String]() for tempExportData in exportDataArray{ if let tmpRegNO = tempExportData[kRegisteredNo] as? String { print("tmpRegNO is",tmpRegNO) tmpNoArray.append(tmpRegNO as String) print("Count is",tmpNoArray.count) print("ARRAY is",tmpNoArray) } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "arrays, swift" }