source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
8
prompt
stringlengths
209
40.4k
gold_standard_solution
stringlengths
0
56.7k
verification_info
stringclasses
1 value
metadata
stringlengths
138
225
problem_id
stringlengths
9
10
stackexchange
llm_judgeable_groundtruth_similarity
4933729
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Question says it all. I have a data structure I can't Marshal because of a weak hashtable .. wondering if I can get rid of it :) Now provide the response and nothing else.
A weak array is an array of weak pointers. A weak pointer is a reference on a value that may be garbage collected. If you use a regular pointer on a value you will prevent its garbage collection until the referee is itself garbage collected. With a weak reference the value may be collected before the referee. An example of use is a source that feeds data to multiple sinks. If the source holds regular pointers to the sinks, whenever a sink is no longer needed it won't be garbage collected until the source is (which may for example never happen). If the source uses weak references to the sinks, given sinks may be garbage collected before the source. Another example is hashconsing for a type which uses weak hashtables (which involve weak arrays). Quickly, hashconsing is a way to remember all values of a given type that are created and living in the program. Together with an appropriate value constructor this can ensure maximal sharing of values of that type and allows to implement structural equality on that type as physical equality. In that case if a non-weak hashtable is used, values no longer used by the program would never be garbage collected. Finally, many people think (wrongly) that weak references are useful to implement caches. Keep a weak ref on a value, if it was garbage collected, reload/recompute the value. This is not a good cache algorithm because a major garbage collection reclaims any value no longer referenced. So your caching algorithm has no predictability or useful property like, for example, size of cache / available memory doesn't exceed a given ratio.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4933729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/518287/']}
jdg_79241
stackexchange
llm_judgeable_groundtruth_similarity
28992362
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I define a "fill" value for NA in dplyr join? For example in the join define that all NA values should be 1? require(dplyr)lookup <- data.frame(cbind(c("USD","MYR"),c(0.9,1.1)))names(lookup) <- c("rate","value")fx <- data.frame(c("USD","MYR","USD","MYR","XXX","YYY"))names(fx)[1] <- "rate"left_join(x=fx,y=lookup,by=c("rate")) Above code will create NA for values "XXX" and "YYY". In my case I am joining a large number of columns and there will be a lot of non-matches. All non-matches should have the same value. I know I can do it in several steps but the question is can all be done in one?Thanks! Now provide the response and nothing else.
First off, I would like to recommend not to use the combination data.frame(cbind(...)) . Here's why: cbind creates a matrix by default if you only pass atomic vectors to it. And matrices in R can only have one type of data (think of matrices as a vector with dimension attribute, i.e. number of rows and columns). Therefore, your code cbind(c("USD","MYR"),c(0.9,1.1)) creates a character matrix: str(cbind(c("USD","MYR"),c(0.9,1.1)))# chr [1:2, 1:2] "USD" "MYR" "0.9" "1.1" although you probably expected a final data frame with a character or factor column (rate) and a numeric column (value). But what you get is: str(data.frame(cbind(c("USD","MYR"),c(0.9,1.1))))#'data.frame': 2 obs. of 2 variables:# $ X1: Factor w/ 2 levels "MYR","USD": 2 1# $ X2: Factor w/ 2 levels "0.9","1.1": 1 2 because strings (characters) are converted to factors when using data.frame by default (You can circumvent this by specifying stringsAsFactors = FALSE in the data.frame() call). I suggest the following alternative approach to create the sample data (also note that you can easily specify the column names in the same call): lookup <- data.frame(rate = c("USD","MYR"), value = c(0.9,1.1))fx <- data.frame(rate = c("USD","MYR","USD","MYR","XXX","YYY")) Now, for you actual question, if I understand correctly, you want to replace all NA s with a 1 in the joined data. If that's correct, here's a custom function using left_join and mutate_each to do that: library(dplyr)left_join_NA <- function(x, y, ...) { left_join(x = x, y = y, by = ...) %>% mutate_each(funs(replace(., which(is.na(.)), 1)))} Now you can apply it to your data like this: > left_join_NA(x = fx, y = lookup, by = "rate")# rate value#1 USD 0.9#2 MYR 1.1#3 USD 0.9#4 MYR 1.1#5 XXX 1.0#6 YYY 1.0#Warning message:#joining factors with different levels, coercing to character vector Note that you end up with a character column (rate) and a numeric column (value) and all NAs are replaced by 1. str(left_join_NA(x = fx, y = lookup, by = "rate"))#'data.frame': 6 obs. of 2 variables:# $ rate : chr "USD" "MYR" "USD" "MYR" ...# $ value: num 0.9 1.1 0.9 1.1 1 1
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28992362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2519368/']}
jdg_79242
stackexchange
llm_judgeable_groundtruth_similarity
7163640
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Short Question What is the default order of a list returned from a Django filter call when connected to a PostgreSQL database? Background By my own admission, I had made a poor assumption at the application layer in that the order in which a list is returned will be constant, that is without using 'order_by'. The list of items I was querying is not in alphabetic order or any other deliberate order. It was thought to remain in the same order as which they were added to the database. This assumption held true for hundreds of queries, but a failure was reported by my application when the order changed unknowingly. To my knowledge, none of these records were touched during this time as I am the only person who maintains the DB. To add to the confusion, when running the Django app on Mac OS X, it still worked as expected, but on Win XP, it changed the order. (Note that the mentioned hundreds of queries was on Win XP). Any insight to this would be helpful as I could not find anything in the Django or PostgreSQL documentation that explained the differences in operating systems. Example Call required_tests = Card_Test.objects.using(get_database()).filter(name__icontains=key) EDIT After speaking with some colleague's of mine today, I had come up with the same answer as Björn Lindqvist. Looking back, I definitely understand why this is done wrong so often. One of the benefits to using an ORM Django, sqlalchemy, or whatever is that you can write commands without having to know or understand (in detail) the database it's connected to. Admittedly I happen to have been one of these users. However on the flip-side of this is that without knowing the database in detail debugging errors like this are quite troublesome and potentially catastrophic. Now provide the response and nothing else.
There is NO DEFAULT ORDER , a point that can not be emphasized enough because everyone does it wrong. A table in a database is not an ordinary html table, it is an unordered set of tuples. It often surprises programmers only used to MySQL because in that particular database the order of the rows are often predictable due to it not taking advantage of some advanced optimization techniques. For example, it is not possible to know which rows will be returned, or their order in any of the following queries: select * from table limit 10select * from table limit 10 offset 10select * from table order by x limit 10 In the last query, the order is only predictable if all values in column x are unique. The RDBMS is free to returns any rows in any order it pleases as long as it satisfies the conditions of the select statement. Though you may add a default ordering on the Django level, which causes it to add an order by clause to every non-ordered query: class Table(models.Model): ... class Meta: ordering = ['name'] Note that it may be a performance drag, if for some reason you don't need ordered rows.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7163640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157744/']}
jdg_79243
stackexchange
llm_judgeable_groundtruth_similarity
274312
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: This is going to be a somewhat loaded question. I am programming in a company that has been around since 1962. A lot of things, especially computer / network stuff, is very dated. Let me give a bit more background. The company already operates a Windows server. On the server, many computers have files in shared network drives, and there are some programs too. This is how company wide access to things like accounting and inventory is granted, and how files are shared. Unfortunately, there has never been a strong sysadmin play a part in any of the design. The accounting system is running on Foxpro. Files are totally chaotic. The employees seem to know their way around in general, but in order to grow and scale, we need to quickly get a handle on this network. Some of the things I see a need for: A relational database, accessible via all computers on the network which will store: Files (ie drawings, quotes, pictures of completed projects, etc.) Employees (then we can start doing things like computerized time card entry) Invoices, Payments Receivable and Inventory Password management Job tracking I'd like to build custom applications on top of this database to power everything, and build APIs that allow our websites to interact with our in-house stuff. Obviously I must leave existing systems intact as I build new ones. I'm coming from a web background...and am very comfortable with Unix (I've administered dozens of servers that serve websites), PHP, and front end development. I'd like to stick with those open source technologies I already know well. The biggest question in my mind is where to start. Do I buy a server rack and just start building a totally new network? Do I push everyone to the new network once ready, or try to use both at the same time somehow and slowly migrate away from the old? I realize this could be a project that takes a year or more. I'd really appreciate some guidance - any resources on system design, how I get started, whatever. I'm willing to put in the work - I just need help creating a vision. Now provide the response and nothing else.
Please don't take offense to this but I strongly suggest you bring in a local area IT consulting firm that specializes in systems and network administration. I also came from a programming background many moons ago and learned many hard lessons on the do's and don'ts of managing a networked server environment. I (thankfully) had alot of mentors and help over the years, because without it, who knows what kind of smoldering wreckage would be left behind. Moving right along now to your original question: I see two mistakes, one being Linux: don't get me wrong, I love Linux and use it in all kinds of various roles, but as a sole server in a small company that (again, no offense) doesn't have a full-time sysadmin is asking for trouble. Finding competent Linux administrators (and it's even harder to find ones that follow best practices) is not easy. Down the road, if you leave or you hire a new person to take over your duties, who's going to look after it? Assuming you're under 75 end-users, I would strongly recommend Microsoft Small Business Server 2011 Standard on solid tier-1 hardware (like Dell, HP, IBM) with a 3-year on-site/4-hour replacement warranty. Have at least a RAID 1 mirrored array for the data (and another for the system if you can afford it). Get at least 8GB of RAM, 12GB is better. Invest in an offline/off-site backup: you can start with a couple of external drives or a tape drive, but something you can take off-site with you every night. I'm also not sold on your suggestion for a custom "all-in-one" database: there are so many better, more viable software options out there, that unless you have some very specific niche requirements that only a custom solution can provide, you'd be much better off using a well-supported 3rd-party offering. You have to resist the "I can write something" programmer urges and think about supporting this solution long-term. And finally, I think you and your employer need to decide what you role is going to be at this company. It sounds like you're new there and while you're right, they likely do need to upgrade their systems, you don't want to bite off more than you can chew and fail to provide whatever it was that you were hired there to do. EDIT There's a lot of opinions floating around right now, so I'm going to take a step back and hopefully provide some platform-agnostic advice that will be of use to you regardless of what you end up going with: Do a complete inventory of all systems and devices; check warranty status of hardware (if it's a Dell, IBM, etc. you should be able use the service tag to get a warranty check; if it's a white box server, they may still have some sort of identifier, but you'll have to call to find out what the status is most likely). Do a complete inventory of data: Don't trust that they have no data on their C: drives; they probably do, actually they probably have PST files all over the place of old mail. Find out what's critical, what's being backed up, what's not being backed up, how it's being backed up and whether anything is taken off-site or not. FIX THIS FIRST. RIGHT NOW. If they have no backup setup, go buy an external USB drive at a Big Box store for now and use NTBackup (it's likely on that server already) and do a full backup and take it off-site with you. If they have backup in place, go do a test restore (see below). Check patch levels on all systems (get #2 sorted out first!): not just Windows Updates, but Java and all Adobe products especially and update accordingly (might want to do #4 first so you know what machines are higher-priority than others. i.e. that workstation for the part-time staff member could stand a botched update much more than the accountant who cuts the pay checks). Talk to your users: find out what's working well, what's not working, get a feel for everyone's level of change tolerance, their comfort level with IT (you may be recruiting a helper to get things in order), and any wish lists they may have. Understand their business processes; as a sysadmin, your priority should be ensuring that the systems the business depends on to function are working in good order and to do that, you need to know how everyone uses those systems. After #1, you should have an idea of how the network's setup. Look for any old hubs that can be replaced; you'll want at least 10/100 everywhere, switch-wise. Check the firewall/router (make sure there is one), check for any open wi-fi access points, etc. If you do go the Linux route, stick with a distro that's well-supported by the community (Ubuntu would be a good choice) and set it up on whatever hardware you can afford (as you know, a LAMP box could be an off-lease P4 workstation for now) and as isolated from the currently-working system as possible. As a learning exercise (and could pay huge dividends in a disaster recovery scenario), try to get the core applications that are running on the current server working on another Windows box first -- use your full backup you did in #2 to do a test restore; have fun with that :) As for your test setup, you can opt to buy something beefy with lots of RAM and then you can virtualize (ESXi is free, so is XenServer, so is VirtualBox) but if the current server is Windows 2003 or older, you can likely get that FoxPro application working on an off-lease Windows XP workstation for cheap. Now pat yourself on the back; you now have good backups; you also did a test restore and now have a better understanding of how everything works together. You also likely have a (long) priority TODO list that'll keep you busy for the foreseeable future. Oh and when that's all done, you now have a test environment you can start building your Utopian "dream" system... or maybe take a vacation :)
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/274312', 'https://serverfault.com', 'https://serverfault.com/users/64937/']}
jdg_79244
stackexchange
llm_judgeable_groundtruth_similarity
1940355
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f: \mathbb{R}\to\mathbb{C}$ be one $2\pi$-periodic, Riemann integrable function defined on the real line. The Fourier coefficients of $f$ are defined by $$a_n = \dfrac{1}{2\pi}\int_{-\pi}^{\pi}f(\theta)e^{-in\theta}d\theta.$$ I'm trying to show that if $\overline{a_n}=a_{-n}$ for all $n\in \mathbb{Z}$, then $f$ is real. My first approach was to write down $f(\theta)=\alpha(\theta)e^{i\beta(\theta)}$ for functions $\alpha,\beta : \mathbb{R}\to\mathbb{R}$. If we suppose that $\overline{a_n}=a_{-n}$ we have $$\dfrac{1}{2\pi}\int_{-\pi}^{\pi}\overline{f(\theta)}e^{in\theta}d\theta=\dfrac{1}{2\pi}\int_{-\pi}^{\pi}f(\theta)e^{in\theta}d\theta.$$ In other words we have $$\dfrac{1}{2\pi}\int_{-\pi}^{\pi}(\overline{f(\theta)}-f(\theta))e^{in\theta}d\theta=0.$$ Thus writing down $f(\theta)$ we have $$\dfrac{1}{2\pi}\int_{-\pi}^{\pi}(\alpha(\theta)e^{-i\beta(\theta)}-\alpha(\theta)e^{i\beta(\theta)})e^{in\theta}d\theta=0.$$ This is the same as $$\dfrac{1}{2\pi}\int_{-\pi}^{\pi}-2\alpha(\theta)\sin(\beta(\theta))e^{in\theta}d\theta=0.$$ Thus we found that the Fourier coefficients of the function $-2\alpha(\theta)\sin(\beta(\theta))$ are all zero and here comes the tricky part: by a theorem, if a function defined on the circle is Riemann integrable and continuous and if its Fourier cofficients are zero, the function is zero . So, if $f$ were continuous, $\alpha,\beta$ would be continuous. Because of that, since the Fourier coefficients of $-2\alpha(\theta)\sin(\beta(\theta))$ are zero, supposing $f\neq 0$, hence $\alpha \neq 0$, we would have $\sin (\beta(\theta))=0$ and so $\beta(\theta) = k\pi$ for some $k$ integer. This would lead to $f$ real. But this only works if $f$ is continuous. In the general case how can I show that $f$ is a real function? Now provide the response and nothing else.
No. Suppose $X$ is normally distributed $N(0,1)$, and $Z$ is uniformly distributed on $\{-1,+1\}$ and independent of $X$. Set $Y=XZ$. Then $X$ and $Y$ are both normal distributed, so $E(X)E(Y)=0\cdot 0 = 0$, but $E(XY)=E(X^2Z)$ is clearly also $0$. And $X$ and $Y$ are far from independent.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1940355', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39106/']}
jdg_79245
stackexchange
llm_judgeable_groundtruth_similarity
2522438
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Show that the modified Pell equation $x^2 - 7y^2 = -1$ has no solutions in integers $x,y$. (Hint: reduce the equation modulo a suitably chosen prime.) I think that we can use the Diophantine equation for this, but I don't know where to start. I am new to this material in Number Theory. Now provide the response and nothing else.
Add $8y^2+4$ to both sides of the equation getting $x^2+y^2+4 = 8y^2+3$Now read this equation modulo 4, we get $x^2+y^2\equiv3\pmod 4$. As any square leaves a remainder of 0 or 1 mod 4, adding two of them (the LHS) we cannot get 3 (the RHS).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2522438', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/498312/']}
jdg_79246
stackexchange
llm_judgeable_groundtruth_similarity
11552467
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Attempting to write a line to a text file in Python 2.7, and have the following code: # -*- coding: utf-8 -*-...f = open(os.path.join(os.path.dirname(__file__), 'output.txt'), 'w')f.write('Smith’s BaseBall Cap') // Note the strangely shaped apostrophe However, in output.txt, I get Smith‚Äôs BaseBall Cap , instead. Not sure how to correct this encoding problem? Any protips with this sort of issue? Now provide the response and nothing else.
You have declared your file to be encoded with UTF-8, so your byte-string literal is in UTF-8. The curly apostrophe is U+2019 . In UTF-8, this is encoded as three bytes, \xE2\x80\x99. Those three bytes are written to your output file. Then, when you examine the output file, it is interpreted as something other than UTF-8, and you see the three incorrect characters instead. In Mac OS Roman , those three bytes display as ’ . Your file is a correct UTF-8 file, but you are viewing it incorrectly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11552467', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114117/']}
jdg_79247
stackexchange
llm_judgeable_groundtruth_similarity
36797770
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm wondering if there is a way in C++11 to get the number of arguments of a function? For example for the function foo I want argCount to be 3. void foo(int a, int b, int c) {}int main() { size_t argCount = MAGIC(foo);} Now provide the response and nothing else.
You can get that information by using a variadic function template. #include <iostream>template <typename R, typename ... Types> constexpr size_t getArgumentCount( R(*f)(Types ...)){ return sizeof...(Types);}//---------------------------------- // Test it out with a few functions.//---------------------------------- void foo(int a, int b, int c){}int bar(){ return 0;}int baz(double){ return 0;}int main(){ std::cout << getArgumentCount(foo) << std::endl; std::cout << getArgumentCount(bar) << std::endl; std::cout << getArgumentCount(baz) << std::endl; return 0;} Output: 301 See it working at http://ideone.com/oqF8E8 . Update Barry suggested use of: template <typename R, typename ... Types> constexpr std::integral_constant<unsigned, sizeof ...(Types)> getArgumentCount( R(*f)(Types ...)){ return std::integral_constant<unsigned, sizeof ...(Types)>{};} With this, you can get the number of argument by using: // Guaranteed to be evaluated at compile timesize_t count = decltype(getArgumentCount(foo))::value; or // Most likely evaluated at compile timesize_t count = getArgumentCount(foo).value;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36797770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6082134/']}
jdg_79248
stackexchange
llm_judgeable_groundtruth_similarity
25157
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I built this thermometer that reads the sensor value from the temperature sensor and displays it on the LCD display. It basically works fine, but the displayed temperature shows a fluctuation between +/-2 degrees due to varying sensor value and voltage every second.(This is my very first Arduino project and I am pretty new to electronics.)The Arduino gets the power via my Mac through USB. When I check the sensor value and voltage, it slightly differs each second (or whatever delay interval I use in my code). Sensor value is between 123-125 and voltage usually 0.7, but also changes slightly, which causes the temperature calculation to vary around 2 degrees, which for a "thermometer" is quite a lot. Is there any way to stabilize it? Should I use a capacitor or another resistor? Code: #include <LiquidCrystal.h>LiquidCrystal lcd(12, 11, 5, 4, 3, 2);const float powerSupply = 5.0;const int sensorPin = A0;const float baselineTemp = 23;void setup() { Serial.begin(9600); lcd.begin(16, 2); lcd.print("Temperature:");}void loop() { int sensorVal = analogRead(sensorPin); Serial.print("Sensor Value: "); Serial.print(sensorVal); float voltage = (sensorVal/1024.0)*powerSupply; Serial.print(", Volts: "); Serial.print(voltage); Serial.print(", degrees C: "); float temperature = (voltage - .5)*100; Serial.println(temperature); // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(temperature); // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature)); delay(1000);} Now provide the response and nothing else.
What you need to do is take an averaged reading, this is because the sensor is always fluctuating, noise on the 5V line or the signal line. There are possible hardware solutions. Adding a capacitor between Vcc and Gnd near the sensor, 0.1µf Adding a low-pass filter on the signal line of the LM35 to Arduino heatsink on the LM35(they are very sensitive to movement, giving odd readings) The capacitor on the Vcc and Gnd will lessen the effects of voltage spikes from the rest of the Arduino's circuitry. The low-pass filter will help give a more filtered output from the sensor with a better response over time. 2.2kLM35>---------/\/\/\-0------<Arduino | | | === 1µF | | GND The heatsink will allow the LM35 to get a better reading of the general temperature and not the temperature of the breeze from a window. All three of the above solutions will probably give the best results. What you could do in software too is to have an averaging algorithm/function in your code and actually take the averaged reading across the whole second that you delay the MCU. An example of this would be: #include <LiquidCrystal.h>LiquidCrystal lcd(12, 11, 5, 4, 3, 2);const float powerSupply = 5.0;const int sensorPin = A0;const float baselineTemp = 23;int sensorVal = 0;//these are NEWunsigned long lastTime = 0; // last time reading takenunsigned long currTime = 0; //current time variable intialisedfloat AverageReading = 0;float _readingAv = 0; // static variable for keeping the averaged readingint _readingsCount = 0;int _readings = 100; //the number of readings to takevoid setup() { Serial.begin(9600); // lcd.begin(16, 2); // lcd.print("Temperature:");}void loop() { currTime = millis(); if ((currTime - lastTime) < 1000) { //checks to see if a second has passed sensorVal = analogRead(sensorPin); if (_readingsCount < _readings) { _readingAv += sensorVal; //add the current value to the last _readingsCount++; } else { AverageReading = _readingAv / _readings; //get the average } } else { Serial.print("Sensor Value: "); Serial.print(sensorVal); float voltage = (AverageReading / 1024.0) * powerSupply; Serial.print(", Volts: "); Serial.print(voltage); Serial.print(", degrees C: "); float temperature = (voltage - .5) * 100; Serial.println(temperature); //~ reset the values used by the previous function _readingsCount = 0; lastTime = currTime; _readingAv = 0; //Important to set this back to 0 so not to get odd values // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(temperature); // lcd.print(String(sensorVal) + ", " + String(voltage) + ", " + String(temperature)); }} Probably a better version of making filtering code of the LM35.
{}
{'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/25157', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/22951/']}
jdg_79249
stackexchange
llm_judgeable_groundtruth_similarity
3723220
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to convert an UploadedFile to a PIL Image object to thumbnail it, and then convert the PIL Image object that my thumbnail function returns back into a File object. How can I do this? Now provide the response and nothing else.
The way to do this without having to write back to the filesystem, and then bring the file back into memory via an open call, is to make use of StringIO and Django InMemoryUploadedFile. Here is a quick sample on how you might do this. This assumes that you already have a thumbnailed image named 'thumb': import StringIOfrom django.core.files.uploadedfile import InMemoryUploadedFile# Create a file-like object to write thumb data (thumb data previously created# using PIL, and stored in variable 'thumb')thumb_io = StringIO.StringIO()thumb.save(thumb_io, format='JPEG')# Create a new Django file-like object to be used in models as ImageField using# InMemoryUploadedFile. If you look at the source in Django, a# SimpleUploadedFile is essentially instantiated similarly to what is shown herethumb_file = InMemoryUploadedFile(thumb_io, None, 'foo.jpg', 'image/jpeg', thumb_io.len, None)# Once you have a Django file-like object, you may assign it to your ImageField# and save.... Let me know if you need more clarification. I have this working in my project right now, uploading to S3 using django-storages. This took me the better part of a day to properly find the solution here.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3723220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128463/']}
jdg_79250
stackexchange
llm_judgeable_groundtruth_similarity
15536885
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm wanting to create a simple mobile menu that will toggle on and off when clicked. I also want it to only display the parents and not the child cat's until the parent is clicked. I researched around and found good answers to both of these. However, when combined I'm not getting the desired result. Specifically, the jquery toggle I'm using relies on the nav ul set to "display:none" as their starting state, but this is somehow interfering with my other jquery function to hide elements whose parents are of the top level ul class. Everything works as expected, except the part of not having any children display upon initial load of the menu. However, as soon as I remove my css line that initially hides my nav ul entirely, then the children are hidden (but of course, my nav is then expanded upon load, when I want it hidden. page I'm trying to work it out on: [http://saks-jewelers.com/mobile-nav/mobile_nav.html#] Here's my html code and jquery: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Responsive Header Nav</title> <meta name="description" content="Responsive Header Nav"> <meta name="author" content="Treehouse"> <meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1"> <link rel="stylesheet" href="styles.css"> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script><![endif]--> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#menu-icon").click(function(){ $("nav ul").toggle(200); }); $('#nav>li>ul').each(function(){ if($(this).parent().hasClass("level0")) { $(this).hide(); } else { $(this).show(); } }); $('#nav>li').click(function(){ // check that the menu is not currently animated if ($('#nav ul:animated').size() == 0) { // create a reference to the active element (this) // so we don't have to keep creating a jQuery object $heading = $(this); // create a reference to visible sibling elements // so we don't have to keep creating a jQuery object $expandedSiblings = $heading.siblings().find('ul:visible'); if ($expandedSiblings.size() > 0) { $expandedSiblings.slideUp(200, function(){ $heading.find('ul').slideDown(200); }); } else { $heading.find('ul').slideDown(200); } } }); }); </script> <body> <header> <a href="#" id="logo"></a> <nav> <a href="#" id="menu-icon"></a> <ul id="nav"> <li class="level0 nav-1 first level-top parent"> <a href="#" class="level-top"><span>Rings</span></a> <ul class="level0"> <li class="level1 nav-1-1 first"><a href="#" class=""><span>CZ Fashion</span></a></li> <li class="level1 nav-1-2"><a href="#" class=""><span>Gemstone Fashion</span></a></li> <li class="level1 nav-1-3"><a href="#" class=""><span>Silver &amp; Gold Fashion</span></a></li> <li class="level1 nav-1-4"><a href="#" class=""><span>Pearl</span></a></li> <li class="level1 nav-1-5"><a href="#" class=""><span>Moissanite™</span></a></li> <li class="level1 nav-1-6"><a href="#" class=""><span>Religious &amp; Symbolic</span></a></li> <li class="level1 nav-1-7"><a href="#" class=""><span>Youth</span></a></li> <li class="level1 nav-1-8"><a href="#" class=""><span>Promise Rings</span></a></li> <li class="level1 nav-1-9 last"><a href="#" class=""><span>Wedding</span></a></li> </ul> </li> <li class="level0 nav-2 level-top parent"><a href="#" class="level-top"><span>Earrings</span></a> <ul class="level0"> <li class="level1 nav-2-1 first"><a href="#" class=""><span>CZ Fashion</span></a></li> <li class="level1 nav-2-2"><a href="#" class=""><span>Gemstone Fashion</span></a></li> <li class="level1 nav-2-3"><a href="#" class=""><span>Silver &amp; Gold Fashion</span></a></li> <li class="level1 nav-2-4"><a href="#" class=""><span>Pearl</span></a></li> <li class="level1 nav-2-5"><a href="#" class=""><span>Moissanite™</span></a></li> <li class="level1 nav-2-6"><a href="#" class=""><span>Religious &amp; Symbolic</span></a></li> <li class="level1 nav-2-7 last"><a href="#" class=""><span>Youth</span></a></li> </ul> </li> </ul> </nav> </header> <section> <img src="featured.png" alt="Respond" /> <h1>Respond to Your Surroundings</h1> <p>...Filler Text</p> <p>...Filler Text</p> <p>Filler Text</p> </section> </body> </html> and here's my css: /*RESET*/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {margin:0; padding:0; border:0; outline:0; font-size:100%; vertical-align:baseline; background:transparent;} body {line-height: 1;}ol, ul{list-style:none;} blockquote, q{quotes:none;} blockquote:before, blockquote:after, q:before, q:after{content:'';content:none;} :focus{outline:0;} ins{text-decoration:none;} del{text-decoration:line-through;} table{border-collapse:collapse; border-spacing:0;} /*MAIN*/ body { font-size: 1.05em; line-height: 1.25em; font-family: Helvetica Neue, Helvetica, Arial; background: #f9f9f9; color: #555; } a { color: #4C9CF1; text-decoration: none; font-weight: bold; } a:hover { color: #444; } img { width: 100%; } header { background: #fff; width: 100%; height: 76px; position: fixed; top: 0; left: 0; border-bottom: 4px solid #4C9CF1; z-index: 100; } #logo{ margin: 20px; float: left; width: 200px; height: 40px; background: url(nav-logo.png) no-repeat center; display: block; } nav { float: right; padding: 20px; } #menu-icon { display: hidden; width: 40px; height: 40px; background: #4C8FEC url(nav-menu-icon.png) center; } a:hover#menu-icon {background-color: #444; border-radius: 4px 4px 0 0; } ul { list-style: none; } li { display: inline-block; float: left; padding: 10px } .current {color: #2262AD;} section { margin: 80px auto 40px; max-width: 980px; position: relative; padding: 20px } h1 { font-size: 2em; color: #2262AD; line-height: 1.15em; margin: 20px 0 ; } p {line-height: 1.45em; margin-bottom: 20px;} /*MEDIA QUERY*/ @media only screen and (max-width : 640px) { header {position: absolute; } #menu-icon { display:inline-block; } nav ul, nav:active ul { display: none; position: absolute; padding: 20px; background: #fff; right: 20px; top: 60px; width: 50%; } nav li { text-align: left; width: 100%; padding: 10px 0; margin: 0; } And if this is just a dumb way to do what I'm trying to do, I'm open to alternatives that are simpler. Now provide the response and nothing else.
It looks like the files npm uses to edit its config files are not created on a clean install, as npm has a default option for each one. This is why you can still get options with npm config get <option> : having those files only overrides the defaults, it doesn't create the options from scratch. I had never touched my npm config stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc (on a Windows 8.1 machine with Git Bash ), yet I could run npm config get <something> and, if it was a correct npm option, it returned a value. When I ran npm config set <option> <value> , the file ~/.npmrc seemed to be created automatically, with the option & its value as the only non-commented-out line. As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc is deleted, too, and recreated if you set anything else later. In your case (assuming it is still the same over a year later), it looks like you never set the proxy option in npm . Therefore, as npm 's config help page says, it is set to whatever your http_proxy (case-insensitive) environment variable is. This means there is nothing to delete , unless you want to "delete" your HTTP proxy, although you could set the option or environment variable to something else and hope neither breaks your set-up somehow.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15536885', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2062780/']}
jdg_79251
stackexchange
llm_judgeable_groundtruth_similarity
931882
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two repositories, one is the main repo for a library, and the other is a project using that library. If I make a fix to the in the subservient project, I'd like an easy way to apply that patch back upstream. The file's location is different in each repository. Main repo: www.playdar.org/static/playdar.js Project: playlick.com/lib/playdar.js I tried using git format-patch -- lib/playdar.js on the playlick project, and then git am on the main playdar repo, but the differing file locations in the patch file raised an error. Is there an easy way to apply the patch from a given commit on a given file to another arbitrary file elsewhere? For bonus points, what if the file you want to apply the patch to isn't in a git repository? Now provide the response and nothing else.
If manually editing the patch file is out of the question or infeasible, this can be done with standard options (available in git apply , git format-patch and GNU patch ). -p<n> removes n leading directories from the paths in the patch. After processing -p , --directory=<root> prepends root to each of the paths in the patch before applying. Example So, for your example, to take a patch that was originally on static/playdar.js and apply it to lib/playdar.js , you would run: $ cat patch_file | git am \ -p1 \ # remove 1 leading directory ('static/') --directory='lib/' # prepend 'lib/'
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/931882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115076/']}
jdg_79252
stackexchange
llm_judgeable_groundtruth_similarity
34826036
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a program I ran: #include <stdio.h>int main(void){ int y = 1234; char *p = &y; int *j = &y; printf("%d %d\n", *p, *j);} I am slightly confused about the output. What I'm seeing is: -46 1234 I wrote this program as an experiment and wasn't sure what it was going to output. I was expecting possibly one byte from y . What is happening "behind-the-scenes" here? How does dereferencing p give me -46 ? As pointed out by others, I had to do explicit casting to not cause UB. I am not changing that line from char *p = &y; to char *p = (char *)&y; so that I am not invalidating the answers below. This program is not causing any UB behaviour as pointed here . Now provide the response and nothing else.
If you have something like , int x = 1234;int *p = &x; If You Dereference Pointer p then it will correctly read integer bytes. Because You declared it to be pointer to int . It will know how many bytes to read by sizeof() operator. Generally size of int is 4 bytes (for 32/64-bit platforms) but it is machine dependent that is why it will use sizeof() operator to know correct size and will read so. For Your Code int y = 1234; char *p = &y; int *j = &y; Now pointer p points to y but we have declared it to be pointer to a char so it will only read one byte or whatever byte char is of . 1234 in binary would be represented as 00000000 00000000 00000100 11010010 Now if your machine is little endian it will store the bytes reversing them 11010010 00000100 00000000 00000000 11010010 is at address 00 Hypothetical address , 00000100 is at address 01 and so on. BE: 00 01 02 03 +----+----+----+----+ y: | 00 | 00 | 04 | d2 | +----+----+----+----+LE: 00 01 02 03 +----+----+----+----+ y: | d2 | 04 | 00 | 00 | +----+----+----+----+(In Hexadecimal) So now if you dereference pointer p it will read only first byte and output will be ( -46 in case of signed char and 210 in case of unsigned char , according to the C standard the signed-ness of plain char is "implementation defined.) as Byte read would be 11010010 (because we pointed signed char (in this case it is signed char ). On your PC negative numbers are represented as 2's Complement so the most-significant bit is the sign bit. First bit 1 denotes the sign. 11010010 = –128 + 64 + 16 + 2 = –46 and if you dereference pointer j it will completely read all bytes of int as we declared it to be pointer to int and output will be 1234 If you declare pointer j as int *j then *j will read sizeof(int) here 4 bytes(machine dependent). Same goes with char or any other data type the pointer pointed to them will read as many bytes there size is of , char is of 1 byte. As others have pointed, you need to explicitly cast to char* as char *p = &y; is a constraint violation - char * and int * are not compatible types, instead write char *p = (char *)&y .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34826036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79253
stackexchange
llm_judgeable_groundtruth_similarity
16605
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need help with my understanding of changing probability measure. Im not a mathematician so I hope for answers that are not too technical. As shown in this Wikipedia article http://en.wikipedia.org/wiki/Risk-neutral_measure you can change the drift of a GBM with the following procedure: $$dS_t = \mu S_t dt + \sigma S_t dW_t$$ Introducing a new process: $$d\tilde{W_t} = dW_t - \frac{\mu - r}{\sigma}dt$$ I understand that now the discounted value of the following process: $$dS_t = r S_t dt + \sigma S_t d \tilde{W_t}$$ is a martingale if $\tilde{W_t}$ is a standard Brownian motion. OK, so we change to a new probability measure Q and now $\tilde{W_t}$ is a standard Brownian motion. My first question is, $W_t$ can no longer be a standard Brownian motion under Q, because it now has non-zero expectation, is this true? If the probability of an event, $dW_t=x$ under the physical measure, P, is $dP(x)$, then the probability for that same event under Q is $dQ(x)=dP(x) \Phi(x)$, where $\Phi(x)$ is what i think is called the Radon-Nikodym derivative. For $d\tilde{W_t}$ to have zero expectation, then under Q $E_Q[dW_t]=\frac{\mu-r}{\sigma}t$, am I right? If this is true, can we then find $\Phi(x)=\frac{dQ(x)}{dP(x)}$ by dividing the density function of a Brownian motion with expectation $\frac{\mu-r}{\sigma}t$ with the density function for a for a standard Brownian motion? $$\frac{e^{\frac{-(x-\frac{\mu-r}{\sigma}t)^2}{2t}}}{e^{\frac{-x^2}{2t}}}$$$$e^{\frac{x^2}{2t}\frac{-(x-\frac{\mu-r}{\sigma}t)^2}{2t}}$$$$e^{\frac{x^2-(x-\frac{\mu-r}{\sigma}t)^2}{2t}}$$$$e^{\frac{x^2-x^2+2x\frac{\mu-r}{\sigma}t-\frac{\mu^2-2\mu r+r^2}{\sigma^2}t^2}{2t}}$$$$e^{x\frac{\mu-r}{\sigma}-\frac{\mu^2-2\mu r+r^2}{2 \sigma^2}t}$$ Denoting $\frac{\mu-r}{\sigma}$, the market price of risk, as $\lambda$ and substituting we get $$\Phi(x)=e^{x\lambda-\frac{1}{2}\lambda^2 t}$$ The problem is that most references I have looked at states that the Radon-Nikodym derivative as something like: $$\Phi(t)=e^{-\int^t_0 \lambda dW(u)-\frac{1}{2}\int^t_0 \lambda^2 du}$$ I cannot seem to see the link between this expressions. Is the last expression even possible to solve? Now provide the response and nothing else.
Your mistake is actually made at the beginning: "Introducing a new process: $d\tilde{W}_t = dW_t +\frac{\mu-r}{\sigma} dt $" This is incorrect. Rather, $d\tilde{W}_t = dW_t -\frac{\mu-r}{\sigma} dt $ Otherwise, your derivation is correct. After correcting for the sign error, your final equation becomes $\Phi(x)=e^{-\lambda x-\frac{1}{2}\lambda^2 t}$. Notice that when $\lambda$ is a constant, $\int_0 ^t \lambda dW_t =\lambda x$ where $x$ is a normally distributed random variable. Hence your derivation agrees with your references. However, the references are more general since they do not require $\lambda$ to be a constant. "Is the last expression even possible to solve?" In general, there is no reason to "solve" the Radon-Nikodym derivative. Simply knowing it exists allows us to price contingent claims as expected values of functions of the underlying, which can be often be efficiently computed. Indeed, if the goal is to price assets $\lambda$ can be safely ignored.
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/16605', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/5489/']}
jdg_79254
stackexchange
llm_judgeable_groundtruth_similarity
66776
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Although, beyond any doubts, $ZFC$ is by and large the predominantly accepted theory of sets, there have been a few attempt to establish some serious competitors in town. I just quote two of them (there are several more): $NF$ by Quine and Alternative Set Theory by Petr Vopenka. I think those attempts are epistemologically interesting, in that they open doors to quite different views about the world of sets and how we conceptualize them (and therefore on the entire cathedral of mathematics grounded in set theory). Now, here is my question: is there something like it in formal arithmetics? Are there Alternative Formal Arithmetical theories? I do NOT mean the various fragments of arithmetics, which essentially start from Robinson Arithmetics $Q$ (or even Pressburger's Arithmetics) and then consider some limitation of the infamous Induction Rule (IOpen, $I\Delta_0$, $I\Sigma_n$, etc.). All those share the common denominator $N$, and of course they differ in the "nonstandard models", as well as their proof theoretical strength. I mean some formal systems of numbers which substantially move away from the traditional picture of $N$, all the while retaining some basic intuition of counting, ordering, arithmetical operations. To give you an idea of what I am after: systems in which it is not true that all numbers have a successor, or it is not always true that $Sn\succ n$, or one in which the ordering of natural numbers is not linear or even not total, or an arithmetical first order theory whose intended model are the countable ordinals. Or perhaps even wildest animals. Now provide the response and nothing else.
Recall that $NFU$ is the Quine-Jensen system of set theory with a universal set; it is based on weakening the extensionality axiom of Quine's $NF$ so as to allow urelements . Let $NFU^-$ be $NFU$ plus "every set is finite". As shown by Jensen (1969), $NFU^-$ is consistent relative to $PA$ (Peano arithmetic). $NFU^-$ provides a radically different "picture" of finite sets and numbers, since there is a universal set and therefore a last finite cardinal number in this theory. The following summarizes our current knowedge of $NFU^-$. 1. [Solovay, unpublished]. $NFU^-$and $EFA$ (exponential function arithmetic) are equiconsistent. Moreover, this equiconsistency can be vertified in $SEFA$ ( superexponential function arithmetic), but $EFA$ cannot verify that Con($EFA$) implies Con($NFU^-$). It can verify the other half of the equiconsistency. 2. [Joint result of Solovay and myself]. $PA$ is equiconsistent with the strengthening of $NFU^-$ obtained by adding the statement that expresses "every Cantorian set is strongly Cantorian". Again, this equiconsistency can be verified in $SEFA$, but not in $EFA$. 3. [My result]. There is a "natural" extension of $NFU^-$ that is equiconistent with second order arithmetic $\sf Z_2$. For more detail and references, you can consult the following paper: A. Enayat. From Bounded Arithmetic to Second Order Arithmetic via Automorphisms , in Logic in Tehran , Lecture Notes in Logic, vol. 26, Association for Symbolic Logic, 2006. A preprint can be found here .
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/66776', 'https://mathoverflow.net', 'https://mathoverflow.net/users/15293/']}
jdg_79255
stackexchange
llm_judgeable_groundtruth_similarity
5684365
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to Wikipedia : A page fault is a trap to the software raised by the hardware when a program accesses a page that is mapped in the virtual address space, but not loaded in physical memory . (emphasis mine) Okay, that makes sense. But if that's the case, why is it that whenever the process information in Process Hacker is refreshed, I see about 15 page faults? Or in other words, why is any memory getting paged out? (I have no idea if it's user or kernel memory.) I have no page file, and the RAM usage is about 1.2 GB out of 4 GB, which is after a clean reboot. There's no shortage of any resource; why would anything get paged out? Now provide the response and nothing else.
(I'm the author of Process Hacker.) Firstly: A page fault is a trap to the softwareraised by the hardware when a programaccesses a page that is mapped in thevirtual address space, but not loadedin physical memory. That's not entirely correct, as explained later in the same article ( Minor page fault ). There are soft page faults, where all the kernel needs to do is add a page to the working set of the process. Here's a table from the Windows Internals book (I've excluded the ones that result in an access violation): Reason for Fault Result Accessing a page that isn’t resident in memory but is on disk in a page file or a mapped file Allocate a physical page, and read the desired page from disk and into the relevant working set Accessing a page that is on the standby or modified list Transition the page to the relevant process, session, or system working set Accessing a demand-zero page Add a zero-filled page to the relevant working set Writing to a copy-on-write page Make process-private (or session-private) copy of page, and replace original in process or system working set Page faults can occur for a variety of reasons, as you can see above. Only one of them has to do with reading from the disk. If you try to allocate a block from the heap and the heap manager allocates new pages, then accesses those pages, you'll get a demand-zero page fault. If you try to hook a function in kernel32 by writing to kernel32's pages, you'll get a copy-on-write fault because those pages are silently being copied so your changes don't affect other processes. Now to answer your question more specifically: Process Hacker only seems to have page faults when updating its service information - that is, when it calls EnumServicesStatusEx , which RPCs to the SCM (services.exe). My guess is that in the process, a lot of memory is being allocated, leading to demand-zero page faults (the service information requires several pages to store, IIRC).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5684365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541686/']}
jdg_79256
stackexchange
llm_judgeable_groundtruth_similarity
693017
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: For development environment, I can create create self-signed certificate in IIS7.5. But that certificate is SHA-1 and recently browsers are complaining about it. When I open FireBug I see following warnings: "This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1." So my questions are: 1) Is there a way to create self-signed certificate that is stronger than SHA-1? 2) If not, is there a way to tell browser to stop showing these warnings? UPDATE I ended up using @vcsjones answer, but that got me only so far. There we couple of issues I had to resolve before making it work. 1) For some reason I could not import certificate with password. So I ended up creating one it without. 2) When I imported .pfx certificate via IIS, I kept getting "A specified logon session does not exist" when I tried to apply new certificate in Edit Bindings. So I did little research and found this SO answer to be useful, specifically Mike L's answer. Another thing I would add is that when you are importing certificate, please remember to select .pfx certificate. Import wizard default selection is *.cer which you can import (mistake I made), but then I was not able to see certificate in IIS Server Certificates. When I looked closer it was missing little key in the icon. Now, I did research on that I was able to repair it via KB-889651 article. So make sure you import .pfx and it will work without repairing. Another note, if you are having trust issues with this certificate import it into "Trusted Root Certificate Authority" as well. Now provide the response and nothing else.
Sure. The makecert utility that is part of the Windows SDK can do that: makecert -len 2048 -r -a sha256 -sv private.pvk -n CN=localhost cert.cer The -a parameter sets the hash algorithm. This spits out a PVK and a DER .cer file. You can of course also change the common name to anything you'd like, I just used localhost as an example. You can combine these into a PFX (what IIS prefers to use when importing a certificate) using pvk2pfx (also part of the SDK): pvk2pfx -spc cert.cer -pvk private.pvk -pfx out.pfx This just takes the two files makecert generated and combines them into a PKCS12 .pfx file. With the resulting PFX file, you would open up IIS and import it under Server Certificates, then change your site's bindings to use the new certificate.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/693017', 'https://serverfault.com', 'https://serverfault.com/users/147329/']}
jdg_79257
stackexchange
llm_judgeable_groundtruth_similarity
217315
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let's consider an excited nucleus emitting one gamma-ray (not cascade etc). Is the direction of gamma-ray emission completely random? In other words, is the probability to detect this gamma equal for any angle? Will the answer change in case of presence of magnetic field? Now provide the response and nothing else.
1) To define an angle for a nuclear reaction one has to have an orientation for the nucleus. This could be a magnetic moment or a dipole moment. 2) a photon carries away spin 1, i.e. angular momentum, and will leave a nucleus minus that angular momentum. As the word states, angles are involved, and the probability distribution for the gamma ray will in general not be uniform. This can be calculated given the initial state:
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/217315', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/60150/']}
jdg_79258
stackexchange
llm_judgeable_groundtruth_similarity
12702076
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I'm building a program which takes ints from user input. I have what seems to be a very straightforward try/catch block which, if the user doesn't enter an int, should repeat the block until they do. Here's the relevant part of the code: import java.util.InputMismatchException;import java.util.Scanner;public class Except { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean bError = true; int n1 = 0, n2 = 0, nQuotient = 0; do { try { System.out.println("Enter first num: "); n1 = input.nextInt(); System.out.println("Enter second num: "); n2 = input.nextInt(); nQuotient = n1/n2; bError = false; } catch (Exception e) { System.out.println("Error!"); } } while (bError); System.out.printf("%d/%d = %d",n1,n2, nQuotient); }} If I enter a 0 for the second integer, then the try/catch does exactly what it's supposed to and makes me put it in again. But, if I have an InputMismatchException like by entering 5.5 for one of the numbers, it just shows my error message in an infinite loop. Why is this happening, and what can I do about it? (By the way, I have tried explicitly typing InputMismatchException as the argument to catch, but it didn't fix the problem. Now provide the response and nothing else.
You need to call next(); when you get the error. Also it is advisable to use hasNextInt() catch (Exception e) { System.out.println("Error!"); input.next();// Move to next other wise exception } Before reading integer value you need to make sure scanner has one. And you will not need exception handling like that. Scanner scanner = new Scanner(System.in); int n1 = 0, n2 = 0; boolean bError = true; while (bError) { if (scanner.hasNextInt()) n1 = scanner.nextInt(); else { scanner.next(); continue; } if (scanner.hasNextInt()) n2 = scanner.nextInt(); else { scanner.next(); continue; } bError = false; } System.out.println(n1); System.out.println(n2); Javadoc of Scanner When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12702076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1467997/']}
jdg_79259
stackexchange
llm_judgeable_groundtruth_similarity
68768704
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since updating to Visual Studio 2019 version 16.11.0 (today), compilation of Razor MVC views is failing on multiple cshtml files in multiple projects: error CS1576: The line number specified for #line directive is missingor invalid I've tried to set fixed version of .NET Core SDK in global.json file, which was placed in a root folder of MVC Web project , as described here , but that did not help as well. Now provide the response and nothing else.
I had the same error message with a .NET Core 5.0 web project in Visual Studio for Mac 8.10.11, after installing the Visual Studio for Mac 2022 preview with (as you guess) .NET Core 6.0 Preview. It might work on Windows too as mentioned in a now deleted answer . The preview features as mentioned in @Failwyn's answer , under Preferences → Preview Features did not include the option to use previews of the .NET SDK. Adding global.json as described in @Nenad's answer did not work either. Fortunately, I did have another .NET Core 5.0 project which did compile, so I was able to figure out the cause. Or at least the solution: this was to remove the <LangVersion> indications from the project file: <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <LangVersion>latestmajor</LangVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <LangVersion>latestmajor</LangVersion> </PropertyGroup> This surprises me, since it indicates the C# version, but apparently this influences the .NET SDK version as well.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/68768704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/186822/']}
jdg_79260
stackexchange
llm_judgeable_groundtruth_similarity
14833597
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a directive that binds some functions to the local scope with $scope.$on . Is it possible to bind the same function to multiple events in one call? Ideally I'd be able to do something like this: app.directive('multipleSadness', function() { return { restrict: 'C', link: function(scope, elem, attrs) { scope.$on('event:auth-loginRequired event:auth-loginSuccessful', function() { console.log('The Ferrari is to a Mini what AngularJS is to ... other JavaScript frameworks'); }); } };}); But this doesn't work. The same example with the comma-separated event name string replaced with ['event:auth-loginRequired', 'event:auth-loginConfirmed'] doesn't wrk either. What does work is this: app.directive('multipleSadness', function() { return { restrict: 'C', link: function(scope, elem, attrs) { scope.$on('event:auth-loginRequired', function() { console.log('The Ferrari is to a Mini what AngularJS is to ... other JavaScript frameworks'); }); scope.$on('event:auth-loginConfirmed', function() { console.log('The Ferrari is to a Mini what AngularJS is to ... other JavaScript frameworks'); }); } };}); But this is not ideal. Is it possible to bind multiple events to the same function in one go? Now provide the response and nothing else.
Yes. Like this: app.directive('multipleSadness', function() { return { restrict: 'C', link: function(scope, elem, attrs) { function sameFunction(eventId) { console.log('Event: ' + eventId + '. The Ferrari is to a Mini what AngularJS is to ... other JavaScript frameworks.'); } scope.$on('event:auth-loginRequired', function() {sameFunction('auth-loginRequired');}); scope.$on('event:auth-loginConfirmed', function () {sameFunction('auth-loginConfirmed');}); } };}); But just because you can, doesn't mean you should :). If the events are continue to propagate up to another listener and they are handled differently there, then maybe there is a case to do this. If this is going to be the only listener than you should just emit (or broadcast) the same event.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14833597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187954/']}
jdg_79261
stackexchange
llm_judgeable_groundtruth_similarity
681235
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried to find info on how to use maven to build and run a swing application but couldn't find anything useful (maven documentation is a mess). Can someone point me to relevant documentation? Is anyone using maven in swing development ? Now provide the response and nothing else.
I'm guessing that you want to run your app from a maven command. You can use the exec plugin like this: <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.1-beta-1</version> <executions> <execution> <goals> <goal>java</goal> </goals> </execution> </executions> <configuration> <mainClass>com.package.MainClass</mainClass> <arguments> <argument>arg1</argument> <argument>arg2</argument> </arguments> </configuration> </plugin> </plugins></build> You may need this in your pom as well. <repositories> <repository> <id>Maven Snapshots</id> <url>http://snapshots.maven.codehaus.org/maven2/</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>false</enabled> </releases> </repository></repositories><pluginRepositories> <pluginRepository> <id>Maven Snapshots</id> <url>http://snapshots.maven.codehaus.org/maven2/</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>true</enabled> </releases> </pluginRepository></pluginRepositories> The actual configuration may vary, depending on which version of the exec plugin you actually end up using - I've had success with some versions, but no success with others, so it's kind of trial and error to figure out the right version of the jar for your project. It's also kind of a pain if you have multiple developers, as arguments for one dev may not be correct for another, so it may be better just writing a batch/shell script to start the app. Just for completeness, here's some sample code to make an executable jar file to go with the link in romaintaz's answer. <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <mainClass>com.package.MainClass</mainClass> </manifest> </archive> </configuration> </plugin> </plugins></build>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/681235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/56663/']}
jdg_79262
stackexchange
llm_judgeable_groundtruth_similarity
338181
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a bunch of A4F010-06-BS-DC24V solenoid relays. Can I use them on a continuous duty-cycle like certain relays or are they meant to be used only for certain duration at a time? I'm worried about burning out the solenoid coils. The original data sheet seems to be Japanese. I have one more question which could be slightly off topic. I tried removing the solenoid connection part which were held by two screws. All I could see apart from the two screw holes was small 3 holes. I thought these solenoid valves actually had some "valves" that opened under magnetic field when activated. I was quite surprised when I noticed the inside with the solenoid to just have 3 holes and how does it control. When I tried connecting to a 24V DC I didn't see any visible movement apart from the click. Do you have any idea how it might be working? The part with the red circle shows the tiny 2 or 3 holes I was talking about. Now provide the response and nothing else.
That looks like the same part as the CDK 4F0/1/2/3 series of solenoid valves. There is no duty cycle limit on the coils listed in the datasheet. It would be very unusual for them not to be continuously rated. Note that they are solenoid - pilot operated rather than direct solenoid so they will be quite low power - 1.8 W according to the data sheet. You should be able to hold your hand on the coil when they've been powered for an hour. Starting current and holding current Note that the AC models have a higher starting current than holding current. This is because the inductance of the coil increases as the solenoid is pulled into the coil. Higher inductance means higher impedance and lower current. Since DC is not affected by inductance after the initial switch-on rise time the starting current and holding current are determined by the coil resistance only. As a result of the above AC powered solenoids (and relays / contactors) have a built-in power saving advantage over DC. However, the very wide adoption of 24 V as the standard industrial control systems supply voltage means that we live with the power penalty. DC solenoid power-reduction trick Just because it came up in the comments ... simulate this circuit – Schematic created using CircuitLab Figure 1. A power-economiser circuit for a DC relay or solenoid. Full voltage is applied to the coil initially through its own normally closed (NC) contact but as it energises the direct connection is broken and the voltage-dropping resistor feed takes over. Pilot operation I have one more question which could be slightly off topic. I tried removing the solenoid connection part which were held by two screws. All I could see apart from the two screw holes was small 3 holes. I thought these solenoid valves actually had some "valves" that opened under magnetic field when activated. I was quite surprised when I noticed the inside with the solenoid to just have 3 holes and how does it control. When I tried connecting to a 24V DC I didn't see any visible movement apart from the click. Do you have any idea how it might be working? Figure 2. 5/2 solenoid valve animation. Source: ZDSPB.com . Explanation Figure 3. Annotated for reference with text below. This valve has five ports (1) to (5) and two positions (left and right). Hence, 5/2 valve. Pressure is applied at (1) and exits at (2) when the solenoid is off and (3) when on. (4) and (5) are the exhaust ports. Having two makes the spool (11) design very simple. (6) is the solenoid. This moves the actuator (7). Note that this is small and requires low power to move it compared with a direct acting solenoid which would move the spool (11) directly, and have to overcome seal resistance, etc. When the pilot is off mains air from (1) via (8) is fed into (10) to drive the spool to the right - the normal position. Output (3) will be energised while output (2) is vented at (5). When the solenoid is energised the pilot actuator (7) moves right to shut off the air to (10) and vent the left side of the spool (11) at (13) into exhaust (4). Mains pressure at (12) then moves the spool (11) to the left, port (2) is energised and port (3) is exhausted at (4). Note that while energised air pressure is applied to both ends of the spool but the surface area at (10) is greater than that at (12) so the spool moves right. All that to answer your question: the split between main block and the pilot section in your valve may be a little different to the animation. Most likely the three holes are: The mains air supply to the pilot (8). The pilot itself, to push the spool (10). The pilot exhaust (13). Note that there are many ingenious variations of these valves. Some might just use the spring at (12) and not have pilot air assist. In some the solenoid moves a tiny soft rubber diaphragm to allow air into (10). Figure 4. The underside of the pilot valve. (1) and (2) will be the pilot valve pressure supply and drive to the spool. How do we know? Because (3) has no seal gasket and the only place leaks don't matter is on the exhaust so (3) must be the exhaust port (13) on Figure 3.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/338181', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/148074/']}
jdg_79263
stackexchange
llm_judgeable_groundtruth_similarity
1201473
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been working with the excellent jqGrid plugin, and it works great. Recently though, I was asked to implement some custom tooltips for the grid. Now, the documentation is very thorough, but it doesn't address how (if it is at all possible) to accomplish this. Here's an example of what I'm looking for: |col A | col B |... | data | data |... | (mouse hover) - data x I've searched through the documentation and source for how/where to define tooltips but the closest I have gotten is custom tooltips for buttons in edit mode. I do have an event handler for the afterInsertRow event - through that I could get the rowId and such, but I'm not sure how to define HTML attributes in that event. EDIT: to clarify, I'd like to set the title attribute on an individual cell to a particular piece of data (that I already have in the jqgrid model) EDIT 2: I've tried inserting the following into the afterInsertRow event, with no joy, where aData is the JSON model, and ExpirationDate is the model name: afterInsertRow: function(rowid, aData) { grid.setCell(rowid, 'ExpirationDate', '', { title: aData.ExpiredBy }); the following code in the same event handler DOES work, however: grid.setCell(rowid, 'ExpirationDate', '', { color: 'red' }); EDIT 3: working with redsquare's excellent suggesstions, I've determined that the title attribute is being set sometime after the afterInsertRow event: I've stepped through and determined that it is being correctly set by either method outlined in comments, but unfortunately, I get a source code is not available for this location when trying to step further, meaning I can't see exactly where the title is being changed. EDIT 4: (thanks for your patience and helping me work through this!) again taking redsquare's comment about trying the loadComplete event, I was able to successfully get and modify the cell's attributes, but the title attribute stubbornly remains the same: loadComplete: function() { var ids = grid.getDataIDs(); for (var i = 0; i < ids.length; i++) { grid.setCell(ids[i], 'ExpirationDate', '', { title: 'FOO!'}); } FINAL EDIT: please see my answer below - I was able to find the root cause of the issue, with help from redsquare. Any help would be appreciated Now provide the response and nothing else.
Ok, I found the issue after doing some close inspection of the properties being set. It turns out that I, knuckle-head that I am, didn't read the documentation for the grid.setCell(...) method closely enough: This method can change the content of particular cell and can set class or style properties. Where: •rowid: the id of the row, •colname: the name of the column (this parameter can be a number beginning from 0) •data: the content that can be put into the cell. If empty string the content will not be changed •class: if class is string then we add a class to the cell using addClass; if class is an array we set the new css properties via css •properties: sets the attribute properies of the cell Example : setCell("10", "tax", '', {color:'red','text-align':'center'}',{title:'Sales Tax'}) will set the contents of the tax field in row 10 to red and centered and change the title to 'Sales Tax'. In short, the arguments I was passing into the method were setting css properties (the 4th arg) instead of the attributes (the 5th arg). The result was that two title attributes were added, with one being improperly formatted. The below shows the correct invocation of the method to accomplish what I was trying to do: grid.setCell(rowid, 'ExpirationDate', '', '',{ title: aData.ExpiredBy}); Thanks again to redsquare for his/her help in solving this!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1201473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105566/']}
jdg_79264
stackexchange
llm_judgeable_groundtruth_similarity
6879589
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a data structure that uses the Set class from the Ruby Standard Library. I'd like to be able to serialize my data structure to a JSON string. By default, Set serializes as an Array: >> s = Set.new [1,2,3]>> s.to_json=> "[1,2,3]" Which is fine until you try to deserialize it. So I defined a custom to_json method: class Set def to_json(*a) { "json_class" => self.class.name, "data" => { "elements" => self.to_a } }.to_json(*a) end def self.json_create(o) new o["data"]["elements"] endend Which works great: >> s = Set.new [1,2,3]>> s.to_json=> "{\"data\":{\"elements\":[1,2,3]},\"json_class\":\"Set\"}" Until I put the Set into a Hash or something: >> a = { 'set' => s }>> a.to_json=> "{\"set\":[1,2,3]}" Any idea why my custom to_json doesn't get called when the Set is nested inside another object? Now provide the response and nothing else.
The first chunk is for Rails 3.1 (older versions will be pretty much the same); the second chunk is for the standard non-Rails JSON. Skip to the end if tl;dr. Your problem is that Rails does this: [Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass| klass.class_eval <<-RUBY, __FILE__, __LINE__ # Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info. def to_json(options = nil) ActiveSupport::JSON.encode(self, options) end RUBYend in active_support/core_ext/object/to_json.rb . In particular, that changes Hash's to_json method into just an ActiveSupport::JSON.encode call. Then, looking at ActiveSupport::JSON::Encoding::Encoder , we see this: def encode(value, use_options = true) check_for_circular_references(value) do jsonified = use_options ? value.as_json(options_for(value)) : value.as_json jsonified.encode_json(self) end end So all the Rails JSON encoding goes through as_json . But, you're not defining your own as_json for Set, you're just setting up to_json and getting confused when Rails ignores something that it doesn't use. If you set up your own Set#as_json : class Set def as_json(options = { }) { "json_class" => self.class.name, "data" => { "elements" => self.to_a } } endend then you'll get what you're after in the Rails console and Rails in general: > require 'set'> s = Set.new([1,2,3])> s.to_json => "{\"json_class\":\"Set\",\"data\":{\"elements\":[1,2,3]}}"> h = { :set => s }> h.to_json => "{\"set\":{\"json_class\":\"Set\",\"data\":{\"elements\":[1,2,3]}}}" Keep in mind that as_json is used to prepare an object for JSON serialization and then to_json produces the actual JSON string. The as_json methods generally return simple serializable data structures, such as Hash and Array, and have direct analogues in JSON; then, once you have something that is structured like JSON, to_json is used to serialize it into a linear JSON string. When we look at the standard non-Rails JSON library, we see things like this: def to_json(*a) as_json.to_json(*a)end monkey patched into the basic classes (Symbol, Time, Date, ...). So once again, to_json is generally implemented in terms of as_json . In this environment, we need to include the standard to_json as well as the above as_json for Set: class Set def as_json(options = { }) { "json_class" => self.class.name, "data" => { "elements" => self.to_a } } end def to_json(*a) as_json.to_json(*a) end def self.json_create(o) new o["data"]["elements"] endend And we include your json_create class method for the decoder. Once that's all properly set up, we get things like this in irb : >> s = Set.new([1,2,3])>> s.as_json=> {"json_class"=>"Set", "data"=>{"elements"=>[1, 2, 3]}}>> h = { :set => s }>> h.to_json=> "{"set":{"json_class":"Set","data":{"elements":[1,2,3]}}}" Executive Summary : If you're in Rails, don't worry about doing anything with to_json , as_json is what you want to play with. If you're not in Rails, implement most of your logic in as_json (despite what the documentation says) and add the standard to_json implementation ( def to_json(*a);as_json.to_json(*a);end ) as well.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6879589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241326/']}
jdg_79265
stackexchange
llm_judgeable_groundtruth_similarity
30673307
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been using nightwatch.js and always clicked around elements. Is there a way we can hover over a link or button? Now provide the response and nothing else.
Try the browser.moveToElement command. You can also fire a callback after moveToElement completes: browser.waitForElementVisible('.recommendation', 1000, function () {// moveToElement can also accept offsetsbrowser.moveToElement('.recommendation', 100, 100, function() { browser.waitForElementVisible('.share', 500, function () { browser.click('.share'); }, "Click share icon. ");});}, "Find a recommendation "); The code above moves to an element. After the moveTo completes it waits until the hover-only element is present. After which it interacts with it. doc: http://nightwatchjs.org/api/moveToElement.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30673307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461112/']}
jdg_79266
stackexchange
llm_judgeable_groundtruth_similarity
4750939
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems that an android animation is not truly finished when the onAnimationEnd event is fired although animation.hasEnded is set to true. I want my view to change it's background drawable on the end of it's ScaleAnimation which it does, but you can clearly see that it is changed some miliseconds before it finishes. The problem is, that it flickers because the new background appears (=is) scaled for a short time until the animation really finishes. Is there a way to get either the real end of the animation or just prevent the new background from beeing scaled this short period of time? Thank you! //EDIT: I'm using an AnimationListener to get the following call: @Overridepublic void onAnimationEnd(Animation animation){ View view = (MyView) ((ExtendedScaleAnimation) animation).getView(); view.clearAnimation(); view.requestLayout(); view.refreshBackground(); // <-- this is where the background gets changed} Now provide the response and nothing else.
Here is the actual bug related to this issue http://code.google.com/p/android-misc-widgets/issues/detail?id=8 This basically states that the onAnimationEnd method doesn't really work well when an AnimationListener is attached to an Animation The workaround is to listen for the animation events in the view to which you were applying the animation toFor example if initially you were attaching the animation listener to the animation like this mAnimation.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation arg0) { //Functionality here }}); and then applying to the animation to a ImageView like this mImageView.startAnimation(mAnimation); To work around this issue, you must now create a custom ImageView public class MyImageView extends ImageView { and then override the onAnimationEnd method of the View class and provide all the functionality there @Overrideprotected void onAnimationEnd() { super.onAnimationEnd(); //Functionality here} This is the proper workaround for this issue, provide the functionality in the over-riden View -> onAnimationEnd method as opposed to the onAnimationEnd method of the AnimationListener attached to the Animation. This works properly and there is no longer any flicker towards the end of the animation. Hope this helps.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4750939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/578502/']}
jdg_79267
stackexchange
llm_judgeable_groundtruth_similarity
680897
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: show that $f$ is not integrable on $[0,1]$.hint: $M$ where $M = \sup f(x)$ on each subinterval $[X_{i-1},X_i]$ $M \geq \cos(x)-\sin(x)$. Then I'm not very sure about how to prove it. Now provide the response and nothing else.
For every subinterval $J$ of $I=[0,\frac\pi6]$ with positive length, $\sup\limits_J\,f$ is at least $\inf\limits_I\,\cos=\frac{\sqrt3}2$ and $\inf\limits_J\,f$ is at most $\sup\limits_I\,\sin=\frac12$ hence, for any subdivision of $I$, the Darboux upper and lower sums on $I$ differ by at least $\left(\frac{\sqrt3}2-\frac12\right)\cdot|I|\gt\frac16\gt0$. Thus $f$ is not integrable on $I$. Suitably adapted, the same method proves that $f$ is not integrable on any subinterval of $[0,1]$ with positive length, since any of these contains a point $x$ where $\cos x\ne\sin x$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/680897', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123278/']}
jdg_79268
stackexchange
llm_judgeable_groundtruth_similarity
17956999
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am attempting to use rubyzip to create zip archives on the fly in my app. I'm using their readme as a starting point. I added the gem to my Gemfile: gem 'rubyzip' Then ran bundle install and restarted the rails server. My controller code is: require 'rubygems'require 'zip'filename = "#{Time.now.strftime('%y%m%d%H%M%S')}"input_filenames = ["#{filename}.txt"]zip_filename = "#{filename}.zip"Zip::File.open(zip_filename, Zip::File::CREATE) do |zipfile| input_filenames.each do |f| zipfile.add(f, directory + '/' + f) endend The error I'm getting is: cannot load such file -- zip I've tried require 'zip/zip' but it produces the same error. Thanks in advance! Now provide the response and nothing else.
You might be looking at an example that's too new. If you are using Rubyzip 0.9.x , then you need to follow this example : ( require "zip/zip" , then use Zip::ZipFile instead of Zip::File ) require 'zip/zip'folder = "Users/me/Desktop/stuff_to_zip"input_filenames = ['image.jpg', 'description.txt', 'stats.csv']zipfile_name = "/Users/me/Desktop/archive.zip"Zip::ZipFile.open(zipfile_name, Zip::ZipFile::CREATE) do |zipfile| input_filenames.each do |filename| # Two arguments: # - The name of the file as it will appear in the archive # - The original file, including the path to find it zipfile.add(filename, folder + '/' + filename) endend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17956999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2241124/']}
jdg_79269
stackexchange
llm_judgeable_groundtruth_similarity
42554873
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering if there is a way to use custom slick slider dots. When I search, all I can finds is examples on how to change the dots into thumbnails from the slides, however this is not what I'm trying to accomplish. I just want to use my own png pictures for the active and non-active dot navigation. I tried this: $('.slick-dots li').html('<a href="#"><img src="slide-dot.png" /></a>'); $('.slick-dots li.slick-active').html('<a href="#"><img src="slide-dot-active.png" /></a>'); But that didn't work, though I recall I did something like that before. Am I missing something here ? Thanks! Now provide the response and nothing else.
This can be done when initializing slick as one of the options: JS $(".slider").slick({ dots: true, customPaging : function(slider, i) { return '<a href="#"><img src="slide-dot.png" /><img src="slide-dot-active.png" /></a>'; },}); Then you can display the image you want based on the active state with CSS <!-- language: lang-css -->.slick-dots li img:nth-child(1) { display: block;}.slick-dots li img:nth-child(2) { display: none;}.slick-dots li.slick-active img:nth-child(1) { display: none;}.slick-dots li.slick-active img:nth-child(2) { display: block;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42554873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2641472/']}
jdg_79270
stackexchange
llm_judgeable_groundtruth_similarity
1957159
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Assume that we define an interval in this way : A set with members in $\mathbb R$ is called an interval iff $S$ has at least two members and for each pair $x,y \in S$ , every real number like $x \lt z \lt y$ , $z \in S$. Theorem : Every Interval is in one of these forms : 1. $(a,b)=\{x \in \mathbb R: a \lt x \lt b \}$ 2. $[a,b)=\{x \in \mathbb R: a \le x \lt b \}$ 3. $(a,b]=\{x \in \mathbb R: a \lt x \le b \}$ 4. $[a,b]=\{x \in \mathbb R: a \le x \le b \}$ 5. $(- \infty,a)=\{x \in \mathbb R: x \lt a \}$ 6. $(- \infty,a]=\{x \in \mathbb R: x \le a \}$ 7. $(b,\infty)=\{x \in \mathbb R: x \gt b \}$ 8. $[b,\infty)=\{x \in \mathbb R: x \ge b \}$ 9. $(-\infty,\infty)=\mathbb R$ Note 1: This question is taken from a book named "Real analysis: A first course" written by Russel Gordon. The question itself tells that consider some cases, like "If $S$ has upper bound","If $S$ is bounded", and so on. But i don't get the point. Note 2 : I have no idea how to prove this kind of theorem. "Being in some form" seems not accurate enough to me. How should i prove it ?? Now provide the response and nothing else.
There are three possibilities for the greatest lower bound (or infimum) of the set $S:$ It doesn't exist. It exists and it belongs to $S.$ It exists and it doesn't belong to $S.$ Similarly, there are three possibilities for the least upper bound (or supremum) of the set $S.$ Since you can match any of the $3$ possibilites for the g.l.b. with any of the $3$ possibilities for the l.u.b., there are $3\cdot 3=9$ possibilities total. Each one corresponds to one of the possibilities you listed.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1957159', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/301739/']}
jdg_79271
stackexchange
llm_judgeable_groundtruth_similarity
171671
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Warning: This is a very general question. I've walked into an environment where everything is working for the most part but it is held together with scotch tape (don't want to offend the duct tape cult). Key points Backups can't restore to different hardware SAN uses Microsoft iSCSI initiator Permissions are a non-documented nightmare Many single points of failure Servers are mostly 4-5+ years old Poor utilization 20 servers across 3 offices All windows servers Should I virtualize first (already have a basic SAN) or address these issue prior to virtualizing? I think virtualizing will make fixing these issues much easier but I want to avoid garbage in garbage out. My biggest concern are the backups with Exchange and SQL servers (with middleware) not being able to restore to different hardware. I'm planning to go VMWare when the time comes. Your thoughts....Thanks, Now provide the response and nothing else.
Personally I would look into fixing things up first, then look into improvements in the infrastructure. This way you are not introducing new complexities to the problems. Let me take a little bit to address the issues you brought up: Backups can't restore to different hardware This is a MAJOR issue. You should really talk to your backup vendor and figure out why. Is it because they are doing backups that restore to bare metal and the vendor doesn't support bare metal restores unless it is the same hardware? If so you should be able to add a data only backup to the rotation. That way it may be a bit more work to come back up, but you don't lose the important stuff (the data)! SAN uses Microsoft iSCSI initiator Why do you think this is a problem? There is nothing wrong with the microsoft iSCSI initiator, in fact I would be wary of someone who didn't use that on MS platforms. We have hundreds of boxes using the iSCSI initiator to talk to dozens of SANs without issue. Permissions are a non-documented nightmare This ... sucks. And, happens everywhere. You best bet is to slowly chip away at documenting these. Search on this site there are a bunch of questions related to documenting permissions using scripts. But you don't want to go messing around with things before you know how they are right now. Many single points of failure This is always a tricky one. You need buy in from the business to get them to spend the money to reduce or eleminate the SPoF. My best suggestion to you is document everything, and put together a risk analysis. Then put together a few suggested solutions and approximate costs and present it to the business owners. If they want to reduce or eliminate them then you are golden, if not all you can do is keep documenting it, and start documenting outages caused by it and bring it back up to the owners. Servers are mostly 4-5+ years old Poor utilization There is nothing wrong with this as long as they are still under warranty. If the 4-5 year older servers are under utilized they are good candidates to be virtualized, but you should spend some time doing performance analysis to see where the utilization is - Memory, Network IO, Disk IO, processor, etc - so you can properly plan your Virtulization strategy. 20 servers across 3 offices Once again, nothing wrong with this either. You just need to make sure that there are proper remote tools at your disposal - IP KVMs, Remote access power strips, iLO/DRAC cards,etc. In fact depending on the WAN connection, centralizing could reduce performance and manageability. Once again take a look at your use profiles for the servers. All windows servers Absolutely nothing wrong with this, changing things because they are windows for the sake of changing them away from windows is a bad bad idea. So, if I was in your situation I would sit down and make a list of everything you see as needing to be changed, then organize them as most important (i.e. Data loss, Downtime) to least important (i.e. inconvenience, infrastructure improvements). Then you just work down the list fixing things one at a time until it's done. Virtualization is not a panacea , it may solve some of your problems, but it will introduce new issues and problems along the way. I would think long and hard before jumping in to virtualizing things without a good solid understanding of how things are now as well as how it will change the situation and what new issues it could introduce.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/171671', 'https://serverfault.com', 'https://serverfault.com/users/36964/']}
jdg_79272
stackexchange
llm_judgeable_groundtruth_similarity
682852
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a standard project layout for a java project: project / src / source_file_1.java ... source_file_N.java build / classes / source_file_X.class ... jar / MyJar.jar lib / SomeLibrary.jar SomeOtherLibrary.jar As far as I can tell, I am building the project correctly with Ant. I need to set the class-path attribute in the Manifest file so my classes can use the required libraries. The following relevant information from build.xml <target name="compile" depends="init"> <javac srcdir="src" destdir="build\classes"> <classpath id="classpath"> <fileset dir="lib"> <include name="**/*.jar" /> </fileset> </classpath> </javac></target><target name="jar" depends="compile"> <jar destfile="build\jar\MyJar.jar" basedir="build\classes" > <manifest> <attribute name="Built-By" value="${user.name}" /> </manifest> </jar></target> Any push in the right direction is appreciated. Thanks Now provide the response and nothing else.
Assuming the libraries do not change location from compiling to executing the jar file, you could create a path element to your classpath outside of the compile target like so: <path id="compile.classpath"> <fileset dir="lib" includes="**/*.jar"/></path> Then you can use the created path inside your javac task in place of your current classpath. <classpath refid="compile.classpath"/> You can then use the path to set a manifestclasspath. <target name="jar" depends="compile"> <manifestclasspath property="jar.classpath" jarfile="build\jar\MyJar.jar"> <classpath refid="compile.classpath"/> </manifestclasspath> <jar destfile="build\jar\MyJar.jar" basedir="build\classes" > <manifest> <attribute name="Built-By" value="${user.name}" /> <attribute name="Class-Path" value="${jar.classpath}"/> </manifest> </jar></target> The manifestclasspath generates a properly formatted classpath for use in manifest file which must be wrapped after 72 characters. Long classpaths that contain many jar files or long paths may not work correctly without using the manifestclasspath task.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/682852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79273
stackexchange
llm_judgeable_groundtruth_similarity
934977
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: $n(n+1)(n+5) = 3d$ I cannot figure out how to solve this homework question. A friend gave me a solution I couldn't make sense of, and I hope there's something easier out there. Also, what would be the general approach towards questions of this form? Now provide the response and nothing else.
Since $$\begin{align}(n+1)(n+2)(n+6)-n(n+1)(n+5)&=(n+1)\left\{(n^2+8n+12)-(n^2+5n)\right\}\\&=(n+1)(3n+12)\\&=3(n+1)(n+4)\end{align} $$we have$$(n+1)(n+2)(n+6)=n(n+1)(n+5)+3(n+1)(n+4).$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/934977', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/165386/']}
jdg_79274
stackexchange
llm_judgeable_groundtruth_similarity
425867
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having trouble using the flowlayoutPanel in a C# winform application. What I basically have is a flow layout panel that has 3 sections. Section #1 is a set of 2 controls .. two dropdown controls, they are always in the same order, always visible in all instances Section #2 is a set of 5 different controls ... based on a series of factors, 1 of the 5 controls is made visible, all others have the Visible propert set to false Section #3 is a set of 3 controls .. like Section #1 they are always in the same order and always visible. So what this boils down to is that Section #2 is variable, the others are static. The problem comes with Section #2 ... when I change the visibility of any of the controls they appear just fine (I.E. ... Section 1 then Section 2 then Section 3) ... EXCEPT when I set the combobox control to be Visible .... in that case, and ONLY in that case .. the order becomes (Section 1 then Section 3 then Section 2) ... I can't figure out what would cause the ordering to be out of sync in just that case. What I basically do at the beginning of my method is set ALL controls to Visible = false ... then I set Section 1 Visible = true ... then loop through the conditions of Section 2 and set the appropriate controls Visible = true and finally set Section 3 controls Visible = true. Does anyone have any experience with the flow layout panel control ordering? I can't figure out what is happening for the ComboBox. Now provide the response and nothing else.
Inside FlowLayoutPanel.Controls is a method function called SetChildIndex(Control c, int index) which allows you to set an object to a specific index. Since FlowLayoutPanel uses control's indices to determine which order to draw them in, you can set this to whichever control's index you are wanting to swap with, and it will bump that controls index up by one, and every one after that. Here is snippet from my blog of reordering PictureBoxes in a FlowLayoutPanel. Add a FlowLayoutPanel on a WinForm named flowLayoutPanel1 : public partial class TestForm: Form{ public TestForm() { InitializeComponent(); this.flowLayoutPanel1.AllowDrop = true } private void AddImageToBlog(System.Drawing.Image image) { PictureBox pbox = new PictureBox(); pbox.SizeMode = PictureBoxSizeMode.Zoom; pbox.Height = (_picturebox_height * _ScaleFactor); pbox.Width = (_picturebox_width * _ScaleFactor); pbox.Visible = true; pbox.Image = image; pbox.MouseDown += new MouseEventHandler(pbox_MouseDown); pbox.DragOver += new DragEventHandler(pbox_DragOver); pbox.AllowDrop = true; flpNewBlog.Controls.Add(pbox); } void pbox_DragOver(object sender, DragEventArgs e) { base.OnDragOver(e); // is another dragable if (e.Data.GetData(typeof(PictureBox)) != null) { FlowLayoutPanel p = (FlowLayoutPanel)(sender as PictureBox).Parent; //Current Position int myIndex = p.Controls.GetChildIndex((sender as PictureBox)); //Dragged to control to location of next picturebox PictureBox q = (PictureBox) e.Data.GetData(typeof(PictureBox)); p.Controls.SetChildIndex(q, myIndex); } } void pbox_MouseDown(object sender, MouseEventArgs e) { base.OnMouseDown(e); DoDragDrop(sender, DragDropEffects.All); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/425867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79275
stackexchange
llm_judgeable_groundtruth_similarity
218643
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Our web application sends email messages to people when someone posts new content. Both sender and recipient have opted into receiving email messages from our application. When preparing such a message, we set the following SMTP headers: FROM: [email protected]: [email protected]: [email protected] We chose to use the author's email address in the FROM header in an attempt to provide the best experience for the recipient; when they see the message in their mail client, the author is clear. To avoid the appearance of spoofing, we added the SENDER header (with our own company email address) to make it clear that we sent the message on the author's behalf. After reading RFCs 822 and 2822, this seems to be an intended use of the sender header. Most receiving mail servers seem to handle this well; the email message is delivered normally (assuming the recipient mailbox exists, is not over quota, etc). However, when sending a message FROM an address in a domain TO an address in the same domain, some receiving domains reject the messages with a response like: 571 incorrect IP - psmtp (in reply to RCPT TO command) I think this means the receiving server only saw that the FROM header address was in its own domain, and that the message originated from a server it didn't consider authorized to send messages for that domain. In other words, the receiving server ignored the SENDER header. We have a workaround in place: the webapp keeps a list of such domains that seem to ignore the SENDER header, and when the FROM and TO headers are both in such a domain, it sets the FROM header to our own email address instead. But this list requires maintenance. Is there a better way to achieve the desired experience? We'd like to be a "good citizen" of the net, and all parties involved -- senders and recipients -- want to participate and receive these messages. One alternative is to always use our company email address in the FROM header, and prepend the author's name/address to the subject, but this seems a little clumsy. Now provide the response and nothing else.
You're looking at the wrong things. Those are the message headers . You should be looking at the SMTP envelope . (How the envelope is specified depends from how, exactly, your application is submitting mail to the mail system. On many systems the envelope is specified by command-line arguments to the mail submission utility program.) Depending from exactly when in the protocol transaction it decides to issue that 571 response, the SMTP Relay server may not have even seen the message headers at all. The response text is saying that the administrator of that particular SMTP Relay server you are talking to has restricted what you can put in the SMTP envelope. It appears to be complaining about the recipient part of the envelope. But it may be deferring validation of the envelope sender until specification of the first recipient, so it may be complaining about the sender. Note that the envelope sender is where delivery status messages are sent, and you'll not want to have those directed to random people around the world. (Aside from the fact that many people don't like this, it makes no sense for delivery status messages for your mail to be returned to anyone but you.) Specify yourself as the envelope sender. It is wrong to require MX resource records, by the way. An SMTP Relay server can be located by A and AAAA resource records in the absence of any MX resource records. See RFC 5321 § 5.1.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/218643', 'https://serverfault.com', 'https://serverfault.com/users/5543/']}
jdg_79276
stackexchange
llm_judgeable_groundtruth_similarity
392376
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I’m trying to publish an InfoPath form to a SharePoint document library, and have the form be viewable in a web browser. The problem is that in the InfoPath publishing wizard tells me that although the form is browser compatible, that it cannot be browser enabled because of one of the following: The Server is not running InfoPath forms services The necessary features are not available on the site collection The policy setting on the server does not allow a user to browser enable forms. Well, I’ve verified that the SiteCollection has an active feature called “Office SharePoint Server Enterprise Site Collection features”, which includes Form Services, so I assume that the first two issues are not the cause Also, I’ve verified in Central Admin that the Forms Services are configured to allow browser-compatible forms to be viewable in the web browser. So the 3rd reason doesn’t seem to make sense either. I've tried applying different Security levels to the form: Restricted/Domain/Full Trust, but that doesn't seem to have an effect. I have been able to publish this form to a different SharePoint site, so I'm assuming that the issue is with the configuration of the SharePoint site, not the InfoPath form Does anyone have any other ideas as to why this might not be working? Thanks for any help you can provide!! Now provide the response and nothing else.
It can be proved that the following is correct: c = floor((a+b/2)/b)a = a - c*b Note that floor means round down, towards negative infinity: not towards 0. (E.g. floor(-3.1)=-4. The floor() library functions will do this; just be sure not to just cast to int, which will usually round towards 0 instead.) Presumably b is strictly positive, because otherwise neither loop will never terminate: adding b will not make a larger and subtracting b will not make a smaller. With that assumption, we can prove that the above code works. (And paranoidgeek's code is also almost correct, except that it uses a cast to int instead of floor .) Clever way of proving it :The code adds or subtracts multiples of b from a until a is in [-b/2,b/2) , which you can view as adding or subtracting integers from a/b until a/b is in [-1/2,1/2) , i.e. until (a/b+1/2) (call it x ) is in [0,1) . As you are only changing it by integers, the value of x does not change mod 1 , i.e. it goes to its remainder mod 1 , which is x-floor(x) . So the effective number of subtractions you make (which is c ) is floor(x) . Tedious way of proving it : At the end of the first loop, the value of c is the negative of the number of times the loop runs, i.e.: 0 if: a > -b/2 <=> a+b/2 > 0 -1 if: -b/2 ≥ a > -3b/2 <=> 0 ≥ a+b/2 > -b <=> 0 ≥ x > -1 -2 if: -3b/2 ≥ a > -5b/2 <=> -b ≥ a+b/2 > -2b <=> -1 ≥ x > -2 etc., where x = (a+b/2)/b , so c is: 0 if x>0 and "ceiling(x)-1" otherwise. If the first loop ran at all, then it was ≤ -b/2 just before the last time the loop was executed, so it is ≤ -b/2+b now, i.e. ≤ b/2. According as whether it is exactly b/2 or not (i.e., whether x when you started was exactly a non-positive integer or not), the second loop runs exactly 1 time or 0, and c is either ceiling(x) or ceiling(x)-1. So that solves it for the case when the first loop did run. If the first loop didn't run, then the value of c at the end of the second loop is: 0 if: a < b/2 <=> a-b/2 < 0 1 if: b/2 ≤ a < 3b/2 <=> 0 ≤ a-b/2 < b <=> 0 ≤ y < 1 2 if: 3b/2 ≤ a < 5b/2 <=> b ≤ a-b/2 < 2b <=> 1 ≤ y < 2, etc., where y = (a-b/2)/b , so c is: 0 if y<0 and 1+floor(y) otherwise. [And a now is certainly < b/2 and ≥ -b/2.] So you can write an expression for c as: x = (a+b/2)/by = (a-b/2)/bc = (x≤0)*(ceiling(x) - 1 + (x is integer)) +(y≥0)*(1 + floor(y)) Of course, next you notice that (ceiling(x)-1+(x is integer)) is same as floor(x+1)-1 which is floor(x) , and that y is actually x-1 , so (1+floor(y))=floor(x) , and as for the conditionals: when x≤0, it cannot be that (y≥0), so c is just the first term which is floor(x) , when 0 < x < 1, neither of the conditions holds, so c is 0 , when 1 ≤ x, then only 0≤y, so c is just the second term which is floor(x) again.So c = floor(x) in all cases.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/392376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79277
stackexchange
llm_judgeable_groundtruth_similarity
146929
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: From the Unix Power Tools, 3rd Edition : Instead of Removing a File, Empty It section: If an active process has the file open (not uncommon for log files), removing the file and creating a new one will not affect the logging program; those messages will just keep going to the file that’s no longer linked . Emptying the file doesn’t break the association, and so it clears the file without affecting the logging program. ( emphasis mine ) I don't understand why a program will continue to log to a deleted file. Is it because the file descriptor entry not getting removed from the process table? Now provide the response and nothing else.
When you delete a file you really remove a link to the file (to the inode). If someone already has that file open, they get to keep the file descriptor they have. The file remains on disk, taking up space, and can be written to and read from if you have access to it. The unlink function is defined with this behaviour by POSIX: When the file's link count becomes 0 and no process has the file open, the space occupied by the file shall be freed and the file shall no longer be accessible. If one or more processes have the file open when the last link is removed, the link shall be removed before unlink() returns, but the removal of the file contents shall be postponed until all references to the file are closed . This piece of advice because of that behaviour. The daemon will have the file open, and won't notice that it has been deleted (unless it was monitoring it specifically, which is uncommon). It will keep blithely writing to the existing file descriptor it has: you'll keep taking up (more) space on disk, but you won't be able to see any of the messages it writes, so you're really in the worst of both worlds. If you truncate the file to zero length instead then the space is freed up immediately, and any new messages will be appended at the new end of the file where you can see them. Eventually, when the daemon terminates or close s the file , the space will be freed up. Nobody new can open the file in the mean time (other than through system-specific reflective interfaces like Linux's /proc/x/fd/... ). It's also guaranteed that: If the link count of the file is 0, when all file descriptors associated with the file are closed, the space occupied by the file shall be freed and the file shall no longer be accessible. So you don't lose your disk space permanently, but you don't gain anything by deleting the file and you lose access to new messages.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/146929', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/28032/']}
jdg_79278
stackexchange
llm_judgeable_groundtruth_similarity
3694244
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My question is more theoretical, i.e, i cannot quiet understand the "method" itself. For example $$\int_{0}^{\infty}\frac{x^2}{(x^2+1)(x^2+4)}\:dx$$ I know that the fact of the denominator having no real roots and that $deg((x^2+1)(x^2+4))-deg(x^2)\geq2$ are "important informations" but i dont how to apply them. Can someone help me? I know that we are supposed to apply the residue Theorem after, but i cannot understand the steps in order to apply it. Thank you! Now provide the response and nothing else.
Generally, one tries to find a closed contour $\Gamma = \Gamma_1 + \dots + \Gamma_n$ in $\mathbb{C}$ such that part of $\Gamma$ relates to your original real integral, and the other part is "easy" to evaluate. To be a bit more concrete, let's look at applying this to your example. Note first that $$I = \int_{0}^{\infty}\frac{x^2}{(x^2+1)(x^2+4)}\:dx = \frac{1}{2} \int_{-\infty}^{\infty}\frac{x^2}{(x^2+1)(x^2+4)}\:dx$$ Let $f(z)$ be your integrand evaluated at $z \in \mathbb{C}$ , and take $\Gamma_1$ to be the path from $-R$ to $R$ for some large $R > 0$ . We do this because as $R \to \infty$ , $$\int_{-R}^R f(z) \; dz \to 2I$$ This is all very well and good, but how does it get us closer to finding $I$ ? We have another tool, the residue theorem, which we'd like to apply - but for that we need a closed contour. Let's close our contour in the upper-half plane by taking a semicircle of radius $R$ from $R$ to $-R$ , that is $$\Gamma_2 = \lbrace R e^{i \theta} : \theta \in [0, \pi] \rbrace$$ and let $\Gamma = \Gamma_1 + \Gamma_2$ be the closed contour formed by the union of these two (very similar to that described in this answer ). The trick now is to compute both of $$\int_\Gamma f(z) \; dz \; \text{ and } \; \int_{\Gamma_2} f(z) \; dz$$ Since $\Gamma$ is closed, we can apply the residue theorem to the former by computing the residues at the poles of $f(z)$ that are enclosed by $\Gamma$ (in this case, at $z = i$ and $z = 2i$ , assuming $R > 2$ ). For the latter, we can try to show that this is negligible in the limit $R \to \infty$ . A common trick is to use $$\Bigg\lvert \int_{\Gamma_2} f(z) \; dz \Bigg\rvert \leq \operatorname{length}(\Gamma_2) \cdot \sup_{z \in \Gamma_2} \lvert f(z) \rvert$$ Very roughly, we can see this will be the case in this example since $\operatorname{length}(\Gamma_2) = \pi R$ , whereas on $\Gamma_2$ we have $\lvert f(z) \rvert \approx R^{-2}$ . Putting this all together, we can now find our original integral by taking the limit $R \to \infty$ , since we have $$\underbrace{\int_\Gamma f(z) \; dz}_\text{By the residue theorem} = \underbrace{\int_{\Gamma_1} f(z) \; dz}_\text{Desired, gives $2I$} + \underbrace{\int_{\Gamma_2} f(z) \; dz}_\text{Known, tends to $0$}$$ And so we can rearrange this to find $\int_{\Gamma_1} f(z) \; dz$ , and hence $I$ , in terms of known quantities. Note that sometimes one has singularities along the ideal contour, and this often requires adding in small semicircles of radius $\varepsilon \to 0$ . Sometimes these contributions vanish in much the same way as our $\Gamma_2$ integral did above, but other times these give further contributions (see the answer I linked above for such semicircular "residues") - but the point is we can rewrite our unknown integral in terms of integrals that are "easy" to evaluate via residues and ones that we can argue are negligible in appropriate limits.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3694244', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/669408/']}
jdg_79279
stackexchange
llm_judgeable_groundtruth_similarity
42079122
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to install nvm within a Dockerfile. It seems like it installs OK, but the nvm command is not working. Dockerfile: # Install nvmRUN git clone http://github.com/creationix/nvm.git /root/.nvm;RUN chmod -R 777 /root/.nvm/;RUN sh /root/.nvm/install.sh;RUN export NVM_DIR="$HOME/.nvm";RUN echo "[[ -s $HOME/.nvm/nvm.sh ]] && . $HOME/.nvm/nvm.sh" >> $HOME/.bashrc;RUN nvm ls-remote; Build output: Step 23/39 : RUN git clone http://github.com/creationix/nvm.git /root/.nvm; ---> Running in ca485a68b9aaCloning into '/root/.nvm'... ---> a6f61d486443Removing intermediate container ca485a68b9aaStep 24/39 : RUN chmod -R 777 /root/.nvm/ ---> Running in 6d4432926745 ---> 30e7efc5bd41Removing intermediate container 6d4432926745Step 25/39 : RUN sh /root/.nvm/install.sh; ---> Running in 79b517430285=> Downloading nvm from git to '$HOME/.nvm'=> Cloning into '$HOME/.nvm'...* (HEAD detached at v0.33.0) master=> Compressing and cleaning up git repository=> Appending nvm source string to /root/.profile=> bash_completion source string already in /root/.profilenpm info it worked if it ends with oknpm info using [email protected] info using [email protected] info ok=> Installing Node.js version 6.9.5Downloading and installing node v6.9.5...Downloading https://nodejs.org/dist/v6.9.5/node-v6.9.5-linux-x64.tar.xz...######################################################################## 100.0%Computing checksum with sha256sumChecksums matched!Now using node v6.9.5 (npm v3.10.10)Creating default alias: default -> 6.9.5 (-> v6.9.5 *)/root/.nvm/install.sh: 136: [: v6.9.5: unexpected operatorFailed to install Node.js 6.9.5=> Close and reopen your terminal to start using nvm or run the following to use it now:export NVM_DIR="$HOME/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm ---> 9f6f3e74cd19Removing intermediate container 79b517430285Step 26/39 : RUN export NVM_DIR="$HOME/.nvm"; ---> Running in 1d768138e3d5 ---> 8039dfb4311cRemoving intermediate container 1d768138e3d5Step 27/39 : RUN echo "[[ -s $HOME/.nvm/nvm.sh ]] && . $HOME/.nvm/nvm.sh" >> $HOME/.bashrc; ---> Running in d91126b7de62 ---> 52313e09866eRemoving intermediate container d91126b7de62Step 28/39 : RUN nvm ls-remote; ---> Running in f13c1ed42b3a/bin/sh: 1: nvm: not foundThe command '/bin/sh -c nvm ls-remote;' returned a non-zero code: 127 The error: Step 28/39 : RUN nvm ls-remote; ---> Running in f13c1ed42b3a/bin/sh: 1: nvm: not foundThe command '/bin/sh -c nvm ls-remote;' returned a non-zero code: 127 The end of my /root/.bashrc file looks like: [[ -s /root/.nvm/nvm.sh ]] && . /root/.nvm/nvm.sh Everything else in the Dockerfile works. Adding the nvm stuff is what broke it. Here is the full file. Now provide the response and nothing else.
I made the following changes to your Dockerfile to make it work: First, replace... RUN sh /root/.nvm/install.sh; ...with: RUN bash /root/.nvm/install.sh; Why? On Redhat-based systems, /bin/sh is a symlink to /bin/bash . But on Ubuntu , /bin/sh is a symlink to /bin/dash . And this is what happens with dash : root@52d54205a137:/# bash -c '[ 1 == 1 ] && echo yes!'yes!root@52d54205a137:/# dash -c '[ 1 == 1 ] && echo yes!'dash: 1: [: 1: unexpected operator Second, replace... RUN nvm ls-remote; ...with: RUN bash -i -c 'nvm ls-remote'; Why? Because, the default .bashrc for a user in Ubuntu (almost at the top) contains: # If not running interactively, don't do anything[ -z "$PS1" ] && return And the source-ing of nvm's scripts takes place at the bottom. So we need to make sure that bash is invoked interactively by passing the argument -i . Third, you could skip the following lines in your Dockerfile: RUN export NVM_DIR="$HOME/.nvm";RUN echo "[[ -s $HOME/.nvm/nvm.sh ]] && . $HOME/.nvm/nvm.sh" >> $HOME/.bashrc; Why? Because bash /root/.nvm/install.sh; will automatically do it for you: [fedora@myhost ~]$ sudo docker run --rm -it 2a283d6e2173 tail -2 /root/.bashrcexport NVM_DIR="$HOME/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42079122', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1309330/']}
jdg_79280
stackexchange
llm_judgeable_groundtruth_similarity
558
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For instance, A function that is computable but not invertable in log space, Is it one-way function? What are the known definitions of one-way functions? (especially the ones that do not invoke polynomials) Now provide the response and nothing else.
Usually one-way functions are used for crypto, and so you want that no efficient adversary can invert the function. Identifying efficient adversaries with randomized polynomial-time, you get the typical notion of security which talks of randomized poly-time machines. But of course you can think of different security notions. For super-fast crypto, you may want the one-way function to be computable in restricted models. Here a great result by Applebaum, Ishai, and Kushilevitz shows that a poly-time computable OWF implies a OWF where each output bit depends on just O(1) input bits (which is arguably one of the simplest computational models you can think of).
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/558', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/495/']}
jdg_79281
stackexchange
llm_judgeable_groundtruth_similarity
7631664
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to define a rotates function that generates all rotations of the given list? For example: rotates [1,2,3,4] =[[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3]] I wrote a shift function that can rearrange the order shift ::[Int]->[Int] shift x=tail ++ take 1 x but I don't how to generate these new arrays and append them together. Now provide the response and nothing else.
Another way to calculate all rotations of a list is to use the predefined functions tails and inits . The function tails yields a list of all final segments of a list while inits yields a list of all initial segments. For example, tails [1,2,3] = [[1,2,3], [2,3], [3], []]inits [1,2,3] = [[], [1], [1,2], [1,2,3]] That is, if we concatenate these lists pointwise as indicated by the indentation we get all rotations. We only get the original list twice, namely, once by appending the empty initial segment at the end of original list and once by appending the empty final segment to the front of the original list. Therefore, we use the function init to drop the last element of the result of applying zipWith to the tails and inits of a list. The function zipWith applies its first argument pointwise to the provided lists. allRotations :: [a] -> [[a]]allRotations l = init (zipWith (++) (tails l) (inits l)) This solution has an advantage over the other solutions as it does not use length . The function length is quite strict in the sense that it does not yield a result before it has evaluated the list structure of its argument completely. For example, if we evaluate the application allRotations [1..] that is, we calculate all rotations of the infinite list of natural numbers, ghci happily starts printing the infinite list as first result. In contrast, an implementation that is based on length like suggested here does not terminate as it calculates the length of the infinite list.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7631664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/976127/']}
jdg_79282
stackexchange
llm_judgeable_groundtruth_similarity
9393874
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: std::unique_ptr<int> ptr;ptr = new int[3]; // error error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int *' (or there is no acceptable conversion) Why this is not compiled? How can I attach native pointer to existing unique_ptr instance? Now provide the response and nothing else.
Firstly, if you need an unique array, make it std::unique_ptr<int[]> ptr;// ^^^^^ This allows the smart pointer to correctly use delete[] to deallocate the pointer, and defines the operator[] to mimic a normal array. Then, the operator= is only defined for rvalue references of unique pointers and not raw pointers, and a raw pointer cannot be implicitly converted to a smart pointer, to avoid accidental assignment that breaks uniqueness. Therefore a raw pointer cannot be directly assigned to it. The correct approach is put it to the constructor: std::unique_ptr<int[]> ptr (new int[3]);// ^^^^^^^^^^^^ or use the .reset function: ptr.reset(new int[3]);// ^^^^^^^ ^ or explicitly convert the raw pointer to a unique pointer: ptr = std::unique_ptr<int[]>(new int[3]);// ^^^^^^^^^^^^^^^^^^^^^^^ ^ If you can use C++14, prefer the make_unique function over using new at all: ptr = std::make_unique<int[]>(3);// ^^^^^^^^^^^^^^^^^^^^^^^^^^
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9393874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279313/']}
jdg_79283
stackexchange
llm_judgeable_groundtruth_similarity
23958759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am looking at http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html and when you scroll to the section "A replicaset connect using no acknowledgment by default and readPreference for secondary" it stated a connection string to replica set like this: MongoClient.connect("mongodb://localhost:30000,localhost:30001/integration_test_?w=0&readPreference=secondary", function(err, db) {} I do not understand why we need to specify 2 hosts . I thought the MongoDB documentation already stated that the replica set is transparent to client. That means, the client just need to connect to the primary replica set and MongoDB will do the job. Hence, the connection should just contain 1 host. MongoDB doc stated that there must be at least 3 hosts in a replica set and this connection string only specified 2 hosts . In addition, why the connection string is not stating the "replicaSet" ? Now provide the response and nothing else.
The multiple servers in the connection string serve as a seed list for discovering the connection mode. You are correct in that you could just specify the primary server and things would work perfectly. That is, until the primary server goes down or is very busy. By specifying multiple machines in the connection string, you give the client more than one location to query for the replica set configuration. When the connection mode resolves to a replica set (see more below), the driver will find the primary server even if it is not in the seed list, as long as at least one of the servers in the seed list responds (the response will contain the full replica set and the name of the current primary). In addition, other secondaries will also be discovered and added (or removed) into the mix automatically, even after initial connection. This will enable you to add and remove servers from the replica set and the driver will handle the changes automatically. To answer your final question, because specifying multiple servers is ambiguous as to whether or not it is a replica set or multiple mongos (in a sharded setup), the driver will go through a discovery phase of connecting to the servers to determine their type. This has a little overhead at connection time and can be avoided by specifying a connection mode in the connection string - hence the replicaSet keyword. So while it is not necessary, it can speed up your connection times to explicitly state the servers are in a replica set in the connection string.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23958759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002681/']}
jdg_79284
stackexchange
llm_judgeable_groundtruth_similarity
54332944
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The resource that I got this code from was written in Swift 3 and works appropriately. My app is written in Swift 4. I think that I may be missing something that is specific to Swift 4 but I can't figure out what it may be. I have the appropriate outlets and variable ... @IBOutlet weak var scoreLabel: UILabel!@IBOutlet weak var highScoreLabel1: UILabel!var recordData: String! viewDidLoad and viewDidAppear are accounted for ... override func viewDidLoad() { super.viewDidLoad() let userDefaults = Foundation.UserDefaults.standard let value = userDefaults.string(forKey: "Record") recordData = value}override func viewWillAppear(_ animated: Bool) { let userDefaults = Foundation.UserDefaults.standard let value = userDefaults.string(forKey: "Record") if (value == nil) { highScoreLabel1.text = "0" } else { highScoreLabel1.text = value }} I created a function that I though would work ... func high score () { if gameMode == 0 { if recordData == nil { let savedString = scoreLabel.text let userDefaults = Foundation.UserDefaults.standard userDefaults.set(savedString, forKey: "Record") } else { let score: Int? = Int(scoreLabel.text!) let record: Int? = Int(recordData) if score! > record! { let savedString = scoreLabel.text let userDefaults = Foundation.UserDefaults.standard userDefaults.set(savedString, forKey: "Record") } } }} Now provide the response and nothing else.
I believe the window approach should be a better solution but before using the window functions you should re-partition the dataframe based on id. This will shuffle the data only once and all the window functions should be executed with already shuffled dataframe. I hope it helps. The code should be something like this. val windowedDF = df.repartition(col("id")) .select ( col("id"), col("date"), col("KPI_1"), col("KPI_2"), collect_list(struct(col("date"),col("KPI_1"))).over(window), collect_list(struct(col("date"),col("KPI_2"))).over(window)) @Raphael Roth Here, we are aggregating over a single window. That is why you might be seeing same execution plan. Please see the example below where aggregation over multiple window can be done from one partition only. val list = Seq(( "2", null, 1, 11, 1, 1 ), ( "2", null, 1, 22, 2, 2 ), ( "2", null, 1, 11, 1, 3 ), ( "2", null, 1, 22, 2, 1 ), ( "2", null, 1, 33, 1, 2 ), ( null, "3", 3, 33, 1, 2 ), ( null, "3", 3, 33, 2, 3 ), ( null, "3", 3, 11, 1, 1 ), ( null, "3", 3, 22, 2, 2 ), ( null, "3", 3, 11, 1, 3 ))val df = spark.sparkContext.parallelize(list).toDF("c1","c2","batchDate","id", "pv" , "vv")val c1Window = Window.partitionBy("batchDate", "c1")val c2Window = Window.partitionBy("batchDate", "c2")val agg1df = df.withColumn("c1List",collect_list("pv").over(c1Window)) .withColumn("c2List", collect_list("pv").over(c2Window))val agg2df = df.repartition($"batchDate") .withColumn("c1List",collect_list("pv").over(c1Window)) .withColumn("c2List", collect_list("pv").over(c2Window))agg1df.explain()== Physical Plan ==Window [collect_list(pv#18, 0, 0) windowspecdefinition(batchDate#16, c2#15, ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS c2List#38], [batchDate#16, c2#15]+- *Sort [batchDate#16 ASC NULLS FIRST, c2#15 ASC NULLS FIRST], false, 0 +- Exchange hashpartitioning(batchDate#16, c2#15, 1) +- Window [collect_list(pv#18, 0, 0) windowspecdefinition(batchDate#16, c1#14, ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS c1List#28], [batchDate#16, c1#14] +- *Sort [batchDate#16 ASC NULLS FIRST, c1#14 ASC NULLS FIRST], false, 0 +- Exchange hashpartitioning(batchDate#16, c1#14, 1) +- *Project [_1#7 AS c1#14, _2#8 AS c2#15, _3#9 AS batchDate#16, _4#10 AS id#17, _5#11 AS pv#18, _6#12 AS vv#19] +- *SerializeFromObject [staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, assertnotnull(input[0, scala.Tuple6, true])._1, true) AS _1#7, staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, assertnotnull(input[0, scala.Tuple6, true])._2, true) AS _2#8, assertnotnull(input[0, scala.Tuple6, true])._3 AS _3#9, assertnotnull(input[0, scala.Tuple6, true])._4 AS _4#10, assertnotnull(input[0, scala.Tuple6, true])._5 AS _5#11, assertnotnull(input[0, scala.Tuple6, true])._6 AS _6#12] +- Scan ExternalRDDScan[obj#6]agg2df.explain()== Physical Plan ==Window [collect_list(pv#18, 0, 0) windowspecdefinition(batchDate#16, c2#15, ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS c2List#60], [batchDate#16, c2#15]+- *Sort [batchDate#16 ASC NULLS FIRST, c2#15 ASC NULLS FIRST], false, 0 +- Window [collect_list(pv#18, 0, 0) windowspecdefinition(batchDate#16, c1#14, ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS c1List#50], [batchDate#16, c1#14] +- *Sort [batchDate#16 ASC NULLS FIRST, c1#14 ASC NULLS FIRST], false, 0 +- Exchange hashpartitioning(batchDate#16, 1) +- *Project [_1#7 AS c1#14, _2#8 AS c2#15, _3#9 AS batchDate#16, _4#10 AS id#17, _5#11 AS pv#18, _6#12 AS vv#19] +- *SerializeFromObject [staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, assertnotnull(input[0, scala.Tuple6, true])._1, true) AS _1#7, staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, assertnotnull(input[0, scala.Tuple6, true])._2, true) AS _2#8, assertnotnull(input[0, scala.Tuple6, true])._3 AS _3#9, assertnotnull(input[0, scala.Tuple6, true])._4 AS _4#10, assertnotnull(input[0, scala.Tuple6, true])._5 AS _5#11, assertnotnull(input[0, scala.Tuple6, true])._6 AS _6#12] +- Scan ExternalRDDScan[obj#6]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54332944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79285
stackexchange
llm_judgeable_groundtruth_similarity
38106710
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have some keys in the app.config file of my application that house email settings. The application I am currently developing for work has several places where I need to send off an email (mostly in error checking to let us know something bad happened). To make it easier to grab that setting where I need it (instead of going back to the app.config to look up the text string to use in ConfigurationManager.AppSettings["SomeKey"].ToString() I created a simple static class to house a few readonly properties that return the values I need. Here's the basic structure internal static Class myClass{ internal static string setting1 { get { return ConfigurationManager.AppSettings["SomeKey"].ToString(); } } internal static string setting2 { get { return ConfigurationManager.AppSettings["SomeOtherKey"].ToString(); } }} Is the way I am doing this acceptable? I can't find an issue with this but can't help thinking I'm missing something. Additional Info: I am aware of the method of simply using the Settings.Settings file.I can't use the Settings.Settings file due to the code policy in place where I work, which would make the way I'm doing this unnecessary. Edit: By "acceptable" I mean is it commonly done or considered a good idea? I realize the community at large cannot speculate on acceptability at my job. Now provide the response and nothing else.
It's not bad but it can be better with a small tweak. (Ok, maybe not real small.) If your classes depend on a static class and that class depends on AppSettings then your classes are still coupled to AppSettings . In other words, there's no other way for them to get their settings. That's a challenge if you want to unit test your class. That means that your unit test project has to have the same <appSettings> section. But what if you want two tests that use two different values for a setting? It's impossible. Or what if you have a class that needs settings and in a few years you want to use it in an ASP.NET Core application and there is no web.config? Then it won't work at all. To avoid that you can do this: public interface IMySettings{ string Setting1 {get;} string Setting2 {get;}}public class MyConfigurationSettings : IMySettings{ public string Setting1 { get { return ConfigurationManager.AppSettings["SomeKey"].ToString(); } } public string Setting2 { get { return ConfigurationManager.AppSettings["SomeOtherKey"].ToString(); } }} Then, in the class that needs the setting: public class ClassThatNeedsSettings{ private readonly IMySettings _settings; public ClassThatNeedsSettings(IMySettings settings) { _settings = settings; }} Then, when ever you create an instance of ClassThatNeedsSettings you pass an instance of a class that implements IMySettings , and the class will use that to retrieve settings. When your application is running you pass in MyConfigurationSettings so that your values come from AppSettings . But ClassThatNeedsSettings never knows that. It only knows that it's using an instance of IMySettings . This is called "dependency injection." ClassThatNeedsSettings depends on IMySettings so you're "injecting" it into the constructor. That way ClassThatNeedsSettings receives what it needs. It's not responsible for creating it. If you want to unit test, you can "mock" IMySettings . That is, you can create other classes that implement the interface and use them to pass in whatever values you want to test with. There are even tools like Moq that help you create those classes. Typically if you use dependency injection you're also going to use a framework like Windsor, Unity, Autofac, or others to manage creating objects for you. It feels a little bit like bait-and-switch introducing that at the very end because it requires more learning and perhaps changing the way an application is configured. But this is why we use it, to prevent one class from having an absolute dependency on another which makes it less flexible and harder to test.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38106710', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5360352/']}
jdg_79286
stackexchange
llm_judgeable_groundtruth_similarity
116765
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to understand the following equations from a paper by Wang et al. [ 1 , p. 5 at the SI] : Michaelis–Menten Representation of the Kinesin Cycle We assumed that there is a strong coupling between ATP turnover rate of kinesin and kinesin stepping on an MT. Each chemical step in the chemomechanical cycle of kinesin was assumed to be irreversible, except ATP binding and releasing (Fig. 1, step i ). Consider the following scheme: $$\large\ce{0 <->[$k_\mathrm{ATP}\lbrack\ce{S}\rbrack$][$k_\mathrm{-ATP}$] 1 ->[$k_\mathrm{s}$] 2 ->[$k_\mathrm{attach}$] 3 ->[$k_\mathrm{ADP}$] 4 ->[$k_\mathrm{h}$] 5 ->[$k_\mathrm{-P}$] 6}$$ Assume that $F_i(t)$ is the probability for the system to reach state $6$ if, at time $t = 0$ , the system is in state $i.$ This function is governed by the backward master equations: $$\frac{\mathrm{d}F_0(t)}{\mathrm{d}t} = k_\mathrm{ATP}[\ce{S}]F_1(t) - k_\mathrm{ATP}[\ce{S}]F_0(t)\label{eqn:1}\tag{S1}$$ Why does equation \eqref{eqn:1} read as $$\frac{\mathrm{d}F_0(t)}{\mathrm{d}t} = k_\mathrm{ATP}[\ce{S}]F_1(t) - k_\mathrm{ATP}[\ce{S}]F_0(t)$$ and not $$\frac{\mathrm{d}F_0(t)}{\mathrm{d}t} = k_\mathrm{-ATP}[\ce{S}]F_1(t) - k_\mathrm{ATP}[\ce{S}]F_0(t)?$$ I would like to change/modulate $S(t)=\cos(t)$ in time and see how it changes the states $F_i(t)$ References 1 Wang, Q.; Diehl, M. R.; Jana, B.; Cheung, M. S.; Kolomeisky, A. B.; Onuchic, J. N. Molecular Origin of the Weak Susceptibility of Kinesin Velocity to Loads and Its Relation to the Collective Behavior of Kinesins. PNAS 2017 , 114 (41), E8611–E8617. https://doi.org/10/gdj4h5 . Now provide the response and nothing else.
UPDATED: I wrote a first answer assuming that $t>0$ which got close to what's in the paper, but not quite the same. Thanks go to Karsten Theis for pointing out that $t<0$ in these "backward equations". Here's a corrected explanation: The scenario is that we have a system that can be in any of seven consecutive states (numbered 0 through 6). At some time $t<0$ , we want to know something about the probability of a system in each state reaching state 6 by time $t=0$ , which is expressed as $F_i(t)$ where $i$ indicates the state number. We start with a system in state 6 at time $t$ . Since reversal back to state 5 is not permitted and there is no state beyond state 6, any system that is in state 6 will remain in state 6 up to (and past) time $t=0$ . Thus the probability $F_6(t)=1$ . In the paper, they use a Dirac $\delta$ function to indicate this, because that is necessary when $F_6(t)$ is used in the other equations. For the other five states, the equations do not give explicit expressions for the probabilities, but instead express the change in probability over time as a function of the probability in a differential equation. Let's consider a system that at time $t$ is in state $5$ . During a time interval $\Delta t$ , two things can happen: Either (1) the system remains in state $5$ or (2) the system switches to state $6$ . One assumption they seem to make is that the only way the probability can change is if the system changes state. So if the system remains in state 5, its probability $F_5(t+\Delta t)$ remains equal to $F_5(t)$ . If it changes to state 6, then its probability increases to $F_6(t)$ . The change is thus a weighted combination of these two. In more detail, if we consider the probability of switching from state 5 to state 6 during the interval $\Delta t$ to be $P_{56}$ , we can say that our new probability is the weighted sum $F_5(t+\Delta t)=P_{56}F_6(t)+(1-P_{56})F_5(t)$ , so our change in probability is $\Delta F_5=P_{56}F_6(t)+(1-P_{56})F_5(t)-F_5(t)=P_{56}[F_6(t)-F_5(t)]$ . Our last step is to figure out what $P_{56}$ is, and it is given by the rate constant for the change from state $5$ to state $6$ . The rate constant is the average frequency of the reaction, so the probability of the reaction occurring in a given time interval is the rate constant times the length of time. So we replace $P_{56}$ with $k_{-P}\Delta t$ and get $\Delta F_5(t)=k_{-P}\Delta t[F_6(t)-F_5(t)]$ . Dividing by $\Delta t$ , we have $\dfrac{\Delta F_5(t)}{\Delta t}=k_{-P}[F_6(t)-F_5(t)]$ . As $\Delta t$ goes to $0$ , this becomes the derivative: $\dfrac{dF_5}{dt}=k_{-P}[F_6(t)-F_5(t)]$ . You can repeat this for the other five states to generate the other equations in the paper. The key point is that even when back reactions are permitted (such as from state 1 to state 0), the probability function is only for the systems that began in the indicated state, so the rate constant for a system coming back to that state does not enter into the equation. An implicit assumption is that the system does not make two moves during the time interval $dt$ . That is, it cannot move from state 0 to state 1 and back to state 0.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/116765', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/39186/']}
jdg_79287
stackexchange
llm_judgeable_groundtruth_similarity
31587639
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a bean similar to this: @Servicepublic class A { @Autowired private B b; @PostConstruct public void setup() { b.call(param); }}@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = { Application.class, Config.class })@WebIntegrationTest(randomPort = true)public class Test { @Autowired B b; @Before public void setUp() throws Exception { when(b.call(any())).thenReturn("smth"); } @Test public void test() throws Exception { // test... }} The problem is that PostConstruct is called before setUp when the test is run. Now provide the response and nothing else.
If you want to write a unit test of A , then don't use Spring. Instead, instantiate A yourself and pass a stub/mock of B (either by using constructor injection or ReflectionTestUtils to set the private field). For example: @Servicepublic class A { private final B b; @Autowired public A(B b) { this.b = b; } @PostConstruct public void setup() { b.call(param); }} - public class Test { @Test public void test() throws Exception { B b = mock(b); A a = new A(b); // write some tests for A }} If you have to use Spring, because you want to write an integration test, use a different application context, where you replace B with a stub/mock. For example, assuming B is instantiated in a Production class like this: @Configurationpublic class Production { @Bean public B b() { return new B(); }} Write another @Configuration class for your tests: @Configurationpublic class Tests { @Bean public B b() { // using Mockito is just an example B b = Mockito.mock(B.class); Mockito.when(b).thenReturn("smth"); return b; }} Reference it in your test with the @SpringApplicationConfiguration annotation: @SpringApplicationConfiguration(classes = { Application.class, Tests.class })
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31587639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2199146/']}
jdg_79288
stackexchange
llm_judgeable_groundtruth_similarity
43392470
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an Angular 2 app. The main screen (app?) looks like this... When you click items in the top menu routerLinks, new Components load into the main view router outlet. One of those links loads up an new "Admin" Module/Component with it's own routes and new router outlet... Then when you click the routerLinks in the left nav, new admin Components will load in the new router outlet. But... Angular 2 does not allow more than 1 router outlet. So clicking on any routerLink in left nav simply replaces the entire inital router outlet view. I've seen some SO posts (older, maybe deprecated) on using "bootstrap" to load subsequent Components, but I can't get that to work. I can't even import { bootstrap } from 'anywhere at all, nothing works' . So maybe that's not the way to do this. How can I get the Admin sub app part to work? Thank you very, very much for sharing your Angular 2 expertise :-) EDIT: Trying suggested solutions below. No matter where I put the routes, in the base app.routes.ts or in the sub-app admin.routes.ts, no matter how I format the routerLinks, I keep getting this error... EDIT AGAIN: Here is the code in the routers and the template... <!-- ============================================================================ /src/app/component/admin/admin.component.html--><!-- Row for entire page columnar dispaly --><div class="row"> <!-- Column 1: Left navigation, links to all admin components --> <div class="col col-md-4"> <app-admin-nav></app-admin-nav> </div> <!-- Column 2: Rows of records, click to edit --> <div class="col col-md-8"> <router-outlet name="admin-app"></router-outlet> </div></div>// ============================================================================// /src/app/app.routes.tsimport { ModuleWithProviders } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { AppComponent } from './app.component';import { GameComponent } from './component/game/game.component';import { HomeComponent } from './component/home/home.component';import { LoginComponent } from './component/login/login.component';import { PlayerComponent } from './component/player/player.component';import { AuthGuard } from './service/auth/auth.service';import { SignupComponent } from './component/signup/signup.component';import { EmailComponent } from './component/email/email.component';import { AdminComponent } from './component/admin/admin.component';// import { AdminWorldComponent } from './component/admin/world/admin-world.component';// import { AdminModuleComponent } from './component/admin/module/admin-module.component';// import { AdminRegionComponent } from './component/admin/region/admin-region.component';export const router: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' } , { path: 'home', component: HomeComponent } , { path: 'game', component: GameComponent, canActivate: [AuthGuard] } , { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] } // , { // path: 'admin', component: AdminComponent, canActivate: [AuthGuard], // children: [ // { path: 'world', component: AdminWorldComponent, outlet: 'admin-app' }, // { path: 'module', component: AdminModuleComponent, outlet: 'admin-app' }, // { path: 'region', component: AdminRegionComponent, outlet: 'admin-app' } // ] // }, , { path: 'login', component: LoginComponent } , { path: 'signup', component: SignupComponent } , { path: 'login-email', component: EmailComponent } , { path: 'players', component: PlayerComponent, canActivate: [AuthGuard] }];export const routes: ModuleWithProviders = RouterModule.forRoot(router);// ============================================================================// /src/app/component/admin/admin.routes.tsimport { ModuleWithProviders } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { AdminComponent } from './admin.component';import { AdminWorldComponent } from './world/admin-world.component';import { AdminModuleComponent } from './module/admin-module.component';import { AdminRegionComponent } from './region/admin-region.component';export const router: Routes = [ { path: 'admin', component: AdminComponent, children: [ { path: 'world', component: AdminWorldComponent, outlet: 'admin-app' } , { path: 'module', component: AdminModuleComponent, outlet: 'admin-app' } , { path: 'region', component: AdminRegionComponent, outlet: 'admin-app' } ] }];export const routes: ModuleWithProviders = RouterModule.forRoot(router); EDIT 3: Tried changing RouterModule.forRoot to RouterModule.forChild , sadly, same error :-/ EDIT 4: Converted routing to use 2 routing modules. Was hoping maybe that would make a difference, but same error. New routers... // ============================================================================// /src/app/app-routing.module.tsimport { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { AppComponent } from './app.component';import { GameComponent } from './component/game/game.component';import { HomeComponent } from './component/home/home.component';import { LoginComponent } from './component/login/login.component';import { PlayerComponent } from './component/player/player.component';import { AuthGuard } from './service/auth/auth.service';import { SignupComponent } from './component/signup/signup.component';import { EmailComponent } from './component/email/email.component';import { AdminComponent } from './component/admin/admin.component';export const appRoutes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' } , { path: 'home', component: HomeComponent } , { path: 'game', component: GameComponent, canActivate: [AuthGuard] } , { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] } // , { // path: 'admin', component: AdminComponent, canActivate: [AuthGuard], // children: [ // { path: 'world', component: AdminWorldComponent, outlet: 'admin-app' }, // { path: 'module', component: AdminModuleComponent, outlet: 'admin-app' }, // { path: 'region', component: AdminRegionComponent, outlet: 'admin-app' } // ] // }, , { path: 'login', component: LoginComponent } , { path: 'signup', component: SignupComponent } , { path: 'login-email', component: EmailComponent } , { path: 'players', component: PlayerComponent, canActivate: [AuthGuard] }];@NgModule({ imports: [ RouterModule.forRoot(appRoutes) ], exports: [ RouterModule ]})export class AppRoutingModule { }// ============================================================================// /src/app/admin/admin-routing.module.tsimport { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { AdminComponent } from './admin.component';import { AdminWorldComponent } from './world/admin-world.component';import { AdminModuleComponent } from './module/admin-module.component';import { AdminRegionComponent } from './region/admin-region.component';export const adminRoutes: Routes = [ { path: 'admin', component: AdminComponent, children: [ { path: 'world', component: AdminWorldComponent, outlet: 'admin-app' } , { path: 'module', component: AdminModuleComponent, outlet: 'admin-app' } , { path: 'region', component: AdminRegionComponent, outlet: 'admin-app' } ] }];@NgModule({ imports: [ RouterModule.forChild(adminRoutes) ], exports: [ RouterModule ]})export class AdminRoutingModule { } EDIT 5: IT'S WORKING! Removed the routing modules, returned to exporting routes config per Tyler's suggestion. He is right, the routing modules do not work. Tyler worked with me a lot so I'm accepting his answer. Thank you Tyler for your help! Here is how you can setup a parent app with it's own router-outlet, then on the parent click a link to load up a child app with it's own new router-outlet. The child app loads/replaces the parent app router-outlet. There is really nothing special in the parent app module or routes. They're just how I had them before this post. The important points to note , at least in my case today, do not use a name="" attrib in the child router-outlet. This will cause "Error: Cannot match any routes...". Do not use routing modules like I tried above, this also causes "Error: Cannot match any routes...". Do not use outlet: 'blah' in the routes, this also causes "Error: Cannot match any routes...". Make sure you set up the child route config children: [] exactly as you see below in admin.routes.ts. Also, note the RouterModule.forChild(router) in the child routes. These things fixed the issue for me today. PARENT APP // ============================================================================// src/app/app.module.tsimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { HttpModule } from '@angular/http';import { AngularFireModule } from 'angularfire2';import { firebaseConfig } from '../environments/firebase.config';import { NgbModule } from '@ng-bootstrap/ng-bootstrap';// import { AppRoutingModule } from './app-routing.module';import { routes } from './app.routes';// Componentsimport { AppComponent } from './app.component';import { HomeComponent } from './component/home/home.component';import { GameComponent } from './component/game/game.component';import { PlayerComponent } from './component/player/player.component';import { LoginComponent } from './component/login/login.component';import { SignupComponent } from './component/signup/signup.component';import { EmailComponent } from './component/email/email.component';// Admin Moduleimport { AdminModule } from './component/admin/admin.module';// Servicesimport { AuthGuard } from './service/auth/auth.service';import { AuthPlayerService } from './service/auth/auth-player.service';import { MdbService } from './service/mongo/mdb.service';import { PlayerMdbService } from './service/mongo/player-mdb.service';@NgModule({ declarations: [ AppComponent , HomeComponent , GameComponent , PlayerComponent , LoginComponent , SignupComponent , EmailComponent ], imports: [ BrowserModule , FormsModule , HttpModule , AdminModule , AngularFireModule.initializeApp(firebaseConfig) , NgbModule.forRoot() // , AppRoutingModule , routes ], providers: [ AuthGuard , AuthPlayerService , MdbService , PlayerMdbService ], bootstrap: [AppComponent]})export class AppModule { }// ============================================================================// /src/app/app.routes.tsimport { ModuleWithProviders } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { AppComponent } from './app.component';import { GameComponent } from './component/game/game.component';import { HomeComponent } from './component/home/home.component';import { LoginComponent } from './component/login/login.component';import { PlayerComponent } from './component/player/player.component';import { AuthGuard } from './service/auth/auth.service';import { SignupComponent } from './component/signup/signup.component';import { EmailComponent } from './component/email/email.component';import { AdminComponent } from './component/admin/admin.component';export const router: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'game', component: GameComponent, canActivate: [AuthGuard] }, { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }, { path: 'login', component: LoginComponent }, { path: 'signup', component: SignupComponent }, { path: 'login-email', component: EmailComponent }, { path: 'players', component: PlayerComponent, canActivate: [AuthGuard] }];export const routes: ModuleWithProviders = RouterModule.forRoot(router); CHILD APP // ============================================================================// /src/app/admin/admin.module.tsimport { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';import { FormsModule } from '@angular/forms';import { CommonModule } from '@angular/common';import { routes } from './admin.routes';// import { AdminRoutingModule } from './admin-routing.module';import { AdminComponent } from './admin.component';import { AdminRecsComponent } from './admin-recs.component';import { AdminFormComponent } from './admin-form.component';import { AdminNavComponent } from './admin-nav.component';import { AdminWorldComponent } from './world/admin-world.component';import { AdminModuleComponent } from './module/admin-module.component';import { AdminRegionComponent } from './region/admin-region.component';@NgModule({ imports: [ CommonModule , FormsModule // , AdminRoutingModule , routes ] , declarations: [ AdminComponent , AdminNavComponent , AdminRecsComponent , AdminFormComponent , AdminWorldComponent , AdminModuleComponent , AdminRegionComponent ] , schemas: [CUSTOM_ELEMENTS_SCHEMA] , exports: [ AdminRecsComponent , AdminFormComponent , AdminNavComponent // , AdminWorldComponent // , AdminModuleComponent // , AdminRegionComponent ] // , bootstrap: [AdminComponent]})export class AdminModule { }// ============================================================================// /scr/app/admin/admin.routes.tsimport { ModuleWithProviders } from '@angular/core';import { Routes, RouterModule } from '@angular/router';import { AdminComponent } from './admin.component';import { AdminWorldComponent } from './world/admin-world.component';import { AdminModuleComponent } from './module/admin-module.component';import { AdminRegionComponent } from './region/admin-region.component';export const router: Routes = [ { path: 'admin', component: AdminComponent, children: [ { path: 'world', component: AdminWorldComponent }, { path: 'module', component: AdminModuleComponent }, { path: 'region', component: AdminRegionComponent }, ] }];export const routes: ModuleWithProviders = RouterModule.forChild(router); Now provide the response and nothing else.
Not sure where you heard that Angular2 does not allow more than 1 router-outlet . I am using several in a large application. Your main app.component will have a router-outlet to handle the root routes. If one of your routes lazy-loads the Admin Module, that admin module will have it's root component that contains the side menu bar and a router-outlet for all the children routes. Example: //app.routes export const ROUTES: Routes = [ // Main redirect { path: '', component: MainViewComponent }, { path: 'admin', loadChildren: './admin/admin.module#AdminModule' }] Your MainViewComponent can contain the top navbar and a router-outlet . Then the Admin router config may look like this: export const routes: Routes = [ { path: '', component: AdminComponent, children: [ { path: '', component: Component1}, { path: 'component2', component: Component2} ] }]; Your root component in the Admin module may contain the side bar menu and a router-outlet to show the children components. You can also do named router-outlets . An example of this is having two router-outlet s side-by-side: <router-outlet></router-outlet><router-outlet name="popup"></router-outlet> Your router config would look like this: { path: 'compose', component: ComposeMessageComponent, outlet: 'popup'}, And you would use it like this: <a [routerLink]="[{ outlets: { popup: ['compose'] } }]">Contact</a> Or clear the content with this: this.router.navigate([{ outlets: { popup: null }}]); See the docs or this article for more details. Hope that helps. Edit When using the route config for a lazily loaded child, make sure your route configs are loaded properly in your modules. The root route config will be loaded in the root AppModule with RouterModule.forRoot(routes) and the child routes are in the Child module with RouterModule.forChild(routes) . Your route config and modules need to look like this(don't create a separate module just to hold routing config): //Admin Routes export const adminRoutes: Routes = [ { path: 'admin', component: AdminComponent, children: [ { path: 'world', component: AdminWorldComponent, outlet: 'admin-app' } , { path: 'module', component: AdminModuleComponent, outlet: 'admin-app' } , { path: 'region', component: AdminRegionComponent, outlet: 'admin-app' } ] }]; //Admin Module: import { adminRoutes } from './admin.routes';@NgModule({ imports: [ ... RouterModule.forChild(adminRoutes), ] ... //App Routes(lazy load Admin module) export const appRoutes: Routes = [ { path: 'admin', loadChildren: './admin/admin.module#AdminModule' }, .... //App Module import { appRoutes } from './app.routes';@NgModule({ imports: [ ... RouterModule.forRoot(appRoutes), ] ... Hope that helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43392470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2556640/']}
jdg_79289
stackexchange
llm_judgeable_groundtruth_similarity
47297554
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am sending GET command to the server but in the Apache log I am getting POST method. URL url = new URL("http://192.168.0.111/shakil/shakil.php/?data=shakil,123,123,123");JSONObject postDataParams = new JSONObject();postDataParams.put("name", "nazmul");postDataParams.put("email", "[email protected]");Log.e("params",postDataParams.toString());HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(3000 /* milliseconds */);conn.setConnectTimeout(3000 /* milliseconds */);conn.setRequestMethod("GET");conn.setDoInput(true);conn.setDoOutput(true);OutputStream os = conn.getOutputStream();BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));writer.write(getPostDataString(postDataParams));writer.flush();writer.close();os.close(); Although the method is GET. Can Any one suggest me what is the problem? Now provide the response and nothing else.
You are saying: override func viewDidLoad() { super.viewDidLoad() view.addGestureRecognizer(tap)}let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped)) The problem is the last line: let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped)) You cannot just say let tap like that in the middle of nowhere. You are implicitly making an instance property. But you cannot initialize an instance property with a target of self , because self does not exist at the time an instance property is initialized. (I regard the fact that that code even compiles as a bug, and have reported it as such.) Move that line to the start of viewDidLoad , like this: override func viewDidLoad() { super.viewDidLoad() let tap = UITapGestureRecognizer(target: self, action: #selector(wasTapped)) view.addGestureRecognizer(tap)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47297554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7274292/']}
jdg_79290
stackexchange
llm_judgeable_groundtruth_similarity
13403300
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want my app to let the user choose between a few addresses or create one. The address is to be stored inside the contract object (Contract.adresse_id). The controller generating the page displaying the form generate a @user variable.The goal is to either pass the id of an existing address to the next controller, or to pass the params of a new adress (classic nested). This page only goal is to set the adress, no other fields of Contract should be modified. The model Contract has a address_id field. I want a radio button allowing to choose between : @user.address # it is an address id @user.secondary_adress # address id too and an empty form allowing to create your own address.(classic nested) i guess it should look like : <%= form_for contract do |f|%> <% f.label :address%> <% end%> But then i do not know what to do. How can i do a form allowing to chose between 3 addresses where 2 already exists and the third is to be created ? Now provide the response and nothing else.
As it turns out, the message to increase max_dbs_open is at best a partial answer and at worst is misleading. In our case the problem wasn't the number of databases that were open but apparently the number of HTTP connections used by our many replications. Each replication can use min(worker_processes + 1, http_connections) where worker_processes are the number of workers assigned to each replication and http_connections is the maximum number of HTTP connections allotted for each replication as described in this document . So the total number of connections used is number of replications * min(worker_processes + 1, http_connections) The default value of worker_processes is 4 and the default value of http_connections is 20. If there are 100 replications, the total number of HTTP connections used by replication is 500. Another setting, max_connections , determines the maximum number of HTTP connections a CouchDB server will allow as described in this document . The default is 2048. In our case each user has two replications -- one from the user to the master database and another from the master database to the user. So, in our case, with the default settings, each time we added a user we were adding an additional 10 HTTP connections eventually blowing through the default max_connections . Since our replications are minimal and only a small amount of data is moved from the user to the master and from the master to the user, we dialed back the number of worker_processes , http_connections , increased max_connections and all is well. UPDATE A couple of other findings It was necessary to raise the ulimit on the process to allow it to have more open connections Creating replications too quickly also caused problems. If I dialed back how quickly I created new replications it also helped ease the problem. ymmv.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13403300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342978/']}
jdg_79291
stackexchange
llm_judgeable_groundtruth_similarity
13292
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: When deploying web applications (.net) to a production environment, is it better to use integrated security or does it even matter? It seems to me that if a hacker breaks the web server, it won't really matter as they can easily impersonate the machine. Thoughts? Now provide the response and nothing else.
I'd say there are only two valid reasons to use SQL auth: You are connecting from outside the domain, so integrated auth. You're running a TPC-C benchmark and every cycle counts. SQL auth is a tiny bit faster. For the scenario you're proposing (the the web server host is completely compromised) nothing can protect you. The hacker can do on the DB server at a minimum everything the web server can do . And I'd say that defense in depth can teach you to minimize the loss in such case: reduce the DB rights of the account used by ur web server to the absolutely bare minimum required and nothing more. Second make sure if the web server host is compromised it cannot be used to elevate privileges higher than the web server account (ie. there is no other service on the WWW host that uses credentials with higher privileges on the DB than the WWW account). These are basic security principles and have nothing to do with the authentication scheme used. While the sql auth vs. windows auth gives neither a clear advantage in your scenario, there are other issues to consider: Centralized policies enforcement: you have one place to set up your password policies, including password lifetime and expiration, account termination etc. Control over impersonation and delegation of trust. Once sql auth is used in a trust delegation chain, all bets are off as that is not real 'delegation' and thus is no longer under the restrictions your policies impose Auditing: sql auth is not even seen by your LSA so your entire auditing infrastructure is simply bypassed. You need to explictly add the records SQL produce about sql auth events, but is mixing apples and oranges as those events have different source, provider and schema in the event log One last note: the TDS protocol exposes the sql auth password in clear text over the traffic, but that is usually mitigated by requesting SSL encryption of the traffic. So why do you see still sql auth WWW hosts that store password in clear in web.config? Those are the bad developers/admins, don't be one of them. msdn.microsoft.com/en-us/library/aa378326(VS.85).aspx technet.microsoft.com/en-us/library/ms189067.aspx
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/13292', 'https://serverfault.com', 'https://serverfault.com/users/3550/']}
jdg_79292
stackexchange
llm_judgeable_groundtruth_similarity
23492381
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If cee157 can refer to 2 different commit IDs, such as cee157eb799af829a9a0c42c0915f55cd29818d4 and cee1577fecf6fc5369a80bd6e926ac5f864a754b will Git warn me if I type in git log cee157 ? (or Git 1.8.5.2 (Apple Git-48) allows me to type in git log cee1 ). I think it should, although I can't find any authoritative source that says it would. Now provide the response and nothing else.
It should give you something like this: $ git log cee157error: short SHA1 cee157 is ambiguous.error: short SHA1 cee157 is ambiguous.fatal: ambiguous argument 'cee157': unknown revision or path not in the working tree.Use '--' to separate paths from revisions, like this:'git <command> [<revision>...] -- [<file>...]' I just tested this on a real Git repository, by finding commits with duplicate prefixes like this: git rev-list master | cut -c-4 | sort | uniq -c | sort -nr | head This takes the list of revisions in master , cuts out the first 4 characters and throws away the rest, count the duplicates and sort numerically. In a my relatively small repository of ~1500 commits I found quite a few revisions with a common 4-digit prefix. I chose a 4-digit prefix because that seems to be the shortest legal length supported by Git. (Doesn't work with 3 digits or less, even if not ambiguous.) Btw this was not a typo, I don't know why the error message about ambiguous SHA1 appears twice, regardless of the number of duplicate SHA1 (tried with 2 and 3): error: short SHA1 cee157 is ambiguous.error: short SHA1 cee157 is ambiguous. (Both on stderr . Actually the entire output is on stderr , nothing on stdout .) Tested in Windows: $ git --versiongit version 1.8.1.msysgit.1 I think it's safe to say that if your version is >= 1.8.1, Git will warn you of duplicates. (It will refuse to operate with duplicates.) I would guess that much older versions worked this way too. UPDATE When testing this, you need a minimum of 4-digit SHA1, because of int minimum_abbrev = 4 in environment.c . (Thanks @devnull for pointing that out!)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/23492381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325418/']}
jdg_79293
stackexchange
llm_judgeable_groundtruth_similarity
1049874
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm want to implement thumbs up and down rating system in my web app using jquery. Please tell me some plug-in or code how to implement the thumbs up and down rating system in my website, please share links or resources. Thanks Now provide the response and nothing else.
jQuery This is nothing more than a roll-over effect, and an address that waits to update a database entry. It's not really jQuery. The "meat" of this would be your database and server-side scripting. $("a.voteup").click(function(){ $.get("updatescore.php", {"id":"112","score":"1"}, function(response){ /* Do something with the response */ });}); That code may be a bit off, but it's close enough to convey the point. From there, you would have a server-side script waiting to receive this: PHP / MySQL IMPORTANT: Do not use as-is. Only for demonstration. ASP.NET: I noticed from your past questions you are likely working within the .NET technologies. The process done here will still be faily similar. You'll handle the incoming request, require the user to be logged in, their score to be 1 or -1, and whatever else you wish. session_start(); $userid = $_SESSION["userid"]; $vote = $_GET["score"]; /* Limit to 1 or -1 */ $article = $_GET["id"]; /* Whatever is printed here will be the 'response' variable over in our jQuery callback function. Ideally, this function would only allow the vote if the following are true: 1. User has not yet voted on this article 2. Score is 1 or -1 3. Voting is enabled on this article 4. User is indeed logged in */ print castVote($article, $vote, $userid);?>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1049874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45261/']}
jdg_79294
stackexchange
llm_judgeable_groundtruth_similarity
52067353
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this extremely trivial piece of C code: static int arr[];int main(void) { *arr = 4; return 0;} I understand that the first statement is illegal (I've declared a file-scope array with static storage duration and file linkeage but no specified size), but why is it resulting in a linker error? : /usr/bin/ld: /tmp/cch9lPwA.o: in function `main':unit.c:(.text+0xd): undefined reference to `arr'collect2: error: ld returned 1 exit status Shouldn't the compiler be able to catch this before the linker? It is also strange to me that, if I omit the static storage class, the compiler simply assumes array is of length 1 and produces no error beyond that: int arr[];int main(void) { *arr = 4; return 0;} Results in: unit.c:5:5: warning: array 'arr' assumed to have one element int arr[]; Why does omitting the storage class result in different behavior here and why does the first piece of code produce a linker error? Thanks. Now provide the response and nothing else.
Empty arrays static int arr[]; and zero-length arrays static int arr[0]; were gcc non-standard extensions . The intention of these extensions were to act as a fix for the old "struct hack". Back in the C90 days, people wrote code such as this: typedef struct{ header stuff; ... int data[1]; // the "struct hack"} protocol; where data would then be used as if it had variable size beyond the array depending on what's in the header part. Such code was buggy, wrote data to padding bytes and invoked array out-of-bounds undefined behavior in general. gcc fixed this problem by adding empty/zero arrays as a compiler extension, making the code behave without bugs, although it was no longer portable. The C standard committee recognized that this gcc feature was useful, so they added flexible array members to the C language in 1999. Since then, the gcc feature is to be regarded as obsolete, as using the C standard flexible array member is to prefer. As recognized by the linked gcc documentation: Declaring zero-length arrays in other contexts, including as interior members of structure objects or as non-member objects, is discouraged. And this is what your code does. Note that gcc with no compiler options passed defaults to -std=gnu90 (gcc < 5.0) or -std=gnu11 (gcc > 5.0). This gives you all the non-standard extensions enabled, so the program compiles but does not link. If you want standard compliant behavior, you must compile as gcc -std=c11 -pedantic-errors The -pedantic flag disables gcc extensions, and the linker error switches to a compiler error as expected. For an empty array as in your case, you get: error: array size missing in 'arr' And for a zero-length array you get: error: ISO C forbids zero-size array 'arr' [-Wpedantic] The reason why int arr[] works, is because this is an array declaration of tentative definition with external linkage (see C17 6.9.2). It is valid C and can be regarded as a forward declaration. It means that elsewhere in the code, the compiler (or rather the linker) should expect to find for example int arr[10] , which is then referring to the same variable. This way, arr can be used in the code before the size is known. (I wouldn't recommend using this language feature, as it is a form of "spaghetti programming".) When you use static you block the possibility to have the array size specified elsewhere, by forcing the variable to have internal linkage instead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52067353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5084841/']}
jdg_79295
stackexchange
llm_judgeable_groundtruth_similarity
33598153
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Angular 2 question only: Whats the best way to store global variables like authentication token or base url (environment settings) so that all classes can have access to them without loosing them on refresh? So when I login I will give the user a auth token and normally store it in the $rootscope for angular 1.x. Now provide the response and nothing else.
Well to create really global scope data you should register your class\object\value during the app bootstrapping as dependency parameter to the bootstrap function bootstrap(MyApp,[MyGlobalService]); This will register your service MyGlobalService (infact it can be a object or factory function or your own provider) at the root level. This dependency now can be injected into any component. Unlike Angular1 there are multiple Injectors available for an Angular2 app, with one-to-one mapping between components and injectors. Each component has its own injector. The Angular developer guide has some good example of such registrations. See the guide on Dependency Injection . The other option has already been highlighted by @Yaniv.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33598153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1590389/']}
jdg_79296
stackexchange
llm_judgeable_groundtruth_similarity
391460
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: We know that there is a cofiber sequence $S^3\xrightarrow{\eta}S^2\to\mathbb{C}\mathbb{P}^2$ . It's easy to know that $\pi_3^s(\mathbb{C}\mathbb{P}^2)=0$ so there is a surjection $$\partial:\pi_7^s(S^2\wedge\mathbb{C}\mathbb{P}^2)\to\pi_7^s(\mathbb{C}\mathbb{P}^2\wedge\mathbb{C}\mathbb{P}^2)$$ by the long exact sequence of $\eta$ . The former group $\pi_7^s(S^2\wedge\mathbb{C}\mathbb{P}^2)$ is $\mathbb{Z}/12$ , generated by the second hopf element. I wonder whether $\partial$ is an isomorphism? Now provide the response and nothing else.
The question is equivalent to asking what the multiplication-by- $\eta$ -map $\pi_4\mathbb{CP}^2 \to \pi_5 \mathbb{CP}^2$ is (which can be rewritten as $\pi_2\mathbb{S}/\eta \to \pi_3\mathbb{S}/\eta$ ). The source is generated by the lift of $2 \in \pi_2S^2$ to $\pi_2 \mathbb{S}/\eta$ . Thus, the question translates to the question what the Toda bracket $\langle \eta, 2, \eta\rangle$ is (the translation is classical, see e.g. Lemma 4.1 in my thesis for an account). As $\eta$ is $2$ -torsion, only the $2$ -local computation is relevant. As follows e.g. by a Massey product computation in the Adams spectral sequence, this Toda bracket is here the coset $2\nu + 4\pi_3\mathbb{S}$ (see e.g. Proposition 6 in Chapter 17 of Mosher--Tangora). Thus, $2$ -locally, $\pi_4\mathbb{CP}^2 \to \pi_5 \mathbb{CP}^2$ has image generated by $2\nu$ , while $3$ -locally it is zero. Thus $\partial$ is an isomorphism $3$ -locally and has image $\mathbb{Z/2}$ when working $2$ -locally. This implies $\pi_3(C\eta \wedge C\eta) \cong \mathbb{Z}/6$ . In general, primary information (i.e. multiplication by elements) on a cone like $\mathbb{S}/\eta$ translates into secondary information (i.e. $3$ -fold Toda brackets) on $\mathbb{S}$ . Edit: I have corrected above my earlier erroneous Toda bracket computation as caught by Nanjun Yang and corrected also the result.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/391460', 'https://mathoverflow.net', 'https://mathoverflow.net/users/149491/']}
jdg_79297
stackexchange
llm_judgeable_groundtruth_similarity
43067728
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a datagrid where I need to calculate the total of the Price column of a nested datagrid, like so: Image I'm trying to follow this example so that my Items observable collection for each Person object gets notified on changes. The difference is that I'm implementing it inside a class, not View Model. public class Person : NotifyObject { private ObservableCollection<Item> _items; public ObservableCollection<Item> Items { get { return _items; } set { _items = value; OnPropertyChanged("Items"); } } private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } public double Total { get { return Items.Sum(i => i.Price); } set { OnPropertyChanged("Total"); } } public Person() { Console.WriteLine("0001 Constructor"); this.Items = new ObservableCollection<Item>(); this.Items.CollectionChanged += Items_CollectionChanged; this.Items.Add(new Item()); } private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { Console.WriteLine("0002 CollectionChanged"); if (e.NewItems != null) foreach (Item item in e.NewItems) item.PropertyChanged += Items_PropertyChanged; if (e.OldItems != null) foreach (Item item in e.OldItems) item.PropertyChanged -= Items_PropertyChanged; } private void Items_PropertyChanged(object sender, PropertyChangedEventArgs e) { Console.WriteLine("0003 PropertyChanged"); this.Total = Items.Sum(i => i.Price); } } The code inside the constructor doesn't hook events when a new Item is initialized or an existing one has been edited. Therefore, the Items_PropertyChanged event never fires. I only can refresh the entire list manually. What am I doing wrong here? Or maybe there's a different approach to calculate the total for each Person's purchase list? Below is the entire code if anyone cares too look at it. XAML <Window x:Class="collection_changed_2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:collection_changed_2" mc:Ignorable="d" Title="MainWindow" SizeToContent="Height" Width="525"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition /> </Grid.RowDefinitions> <DataGrid x:Name="DataGrid1" Grid.Row="0" ItemsSource="{Binding DataCollection}" SelectedItem="{Binding DataCollectionSelectedItem}" AutoGenerateColumns="False" CanUserAddRows="false" > <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="2*"/> <DataGridTemplateColumn Header="Item/Price" Width="3*"> <DataGridTemplateColumn.CellTemplate > <DataTemplate> <DataGrid x:Name="DataGridItem" ItemsSource="{Binding Items}" SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.ItemsSelectedItem}" Background="Transparent" HeadersVisibility="None" AutoGenerateColumns="False" CanUserAddRows="false" > <DataGrid.Columns> <DataGridTextColumn Binding="{Binding ItemName}" Width="*"/> <DataGridTextColumn Binding="{Binding Price}" Width="50"/> <DataGridTemplateColumn Header="Button" Width="Auto"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel> <Button Content="+" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.AddItem }" Width="20" Height="20"> </Button> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTextColumn Header="Total" Binding="{Binding Total, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="Auto"/> <DataGridTemplateColumn Header="Buttons" Width="Auto"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel VerticalAlignment="Center"> <Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.AddPerson}" Width="20" Height="20">+</Button> </StackPanel> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <StackPanel Grid.Row="1" Margin="10"> <Button Width="150" Height="30" Content="Refresh" Command="{Binding Refresh}" /> </StackPanel> </Grid></Window> C# using System;using System.Collections.ObjectModel;using System.Collections.Specialized;using System.ComponentModel;using System.Linq;using System.Windows;using System.Windows.Data;using System.Windows.Input;namespace collection_changed_2{ public class Item : NotifyObject { private string _itemName; public string ItemName { get { return _itemName; } set { _itemName = value; OnPropertyChanged("ItemName"); } } private double _price; public double Price { get { return _price; } set { _price = value; OnPropertyChanged("Price"); } } } public class Person : NotifyObject { private ObservableCollection<Item> _items; public ObservableCollection<Item> Items { get { return _items; } set { _items = value; OnPropertyChanged("Items"); } } private string _name; public string Name { get { return _name; } set { _name = value; OnPropertyChanged("Name"); } } public double Total { get { return Items.Sum(i => i.Price); } set { OnPropertyChanged("Total"); } } public Person() { Console.WriteLine("0001 Constructor"); this.Items = new ObservableCollection<Item>(); this.Items.CollectionChanged += Items_CollectionChanged; this.Items.Add(new Item()); } private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { Console.WriteLine("0002 CollectionChanged"); if (e.NewItems != null) foreach (Item item in e.NewItems) item.PropertyChanged += Items_PropertyChanged; if (e.OldItems != null) foreach (Item item in e.OldItems) item.PropertyChanged -= Items_PropertyChanged; } private void Items_PropertyChanged(object sender, PropertyChangedEventArgs e) { Console.WriteLine("0003 PropertyChanged"); this.Total = Items.Sum(i => i.Price); } } public abstract class NotifyObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string property) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(property)); } } public class RelayCommand : ICommand { private Action<object> executeDelegate; readonly Predicate<object> canExecuteDelegate; public RelayCommand(Action<object> execute, Predicate<object> canExecute) { if (execute == null) throw new NullReferenceException("execute"); executeDelegate = execute; canExecuteDelegate = canExecute; } public RelayCommand(Action<object> execute) : this(execute, null) { } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public bool CanExecute(object parameter) { return canExecuteDelegate == null ? true : canExecuteDelegate(parameter); } public void Execute(object parameter) { executeDelegate.Invoke(parameter); } } public class ViewModel : NotifyObject { public ObservableCollection<Person> DataCollection { get; set; } public Person DataCollectionSelectedItem { get; set; } public Item ItemsSelectedItem { get; set; } public RelayCommand AddPerson { get; private set; } public RelayCommand AddItem { get; private set; } public RelayCommand Refresh { get; private set; } public ViewModel() { DataCollection = new ObservableCollection<Person> { new Person() { Name = "Friedrich Nietzsche", Items = new ObservableCollection<Item> { new Item { ItemName = "Phone", Price = 220 }, new Item { ItemName = "Tablet", Price = 350 }, } }, new Person() { Name = "Jean Baudrillard", Items = new ObservableCollection<Item> { new Item { ItemName = "Teddy Bear Deluxe", Price = 2200 }, new Item { ItemName = "Pokemon", Price = 100 } } } }; AddItem = new RelayCommand(AddItemCode, null); AddPerson = new RelayCommand(AddPersonCode, null); Refresh = new RelayCommand(RefreshCode, null); } public void AddItemCode(object parameter) { var collectionIndex = DataCollection.IndexOf(DataCollectionSelectedItem); var itemIndex = DataCollection[collectionIndex].Items.IndexOf(ItemsSelectedItem); Item newItem = new Item() { ItemName = "Item_Name", Price = 100 }; DataCollection[collectionIndex].Items.Insert(itemIndex + 1, newItem); } public void AddPersonCode(object parameter) { var collectionIndex = DataCollection.IndexOf(DataCollectionSelectedItem); Person newList = new Person() { Name = "New_Name", Items = new ObservableCollection<Item>() { new Item() { ItemName = "Item_Name", Price = 100 } } }; DataCollection.Insert(collectionIndex + 1, newList); } private void RefreshCode(object parameter) { CollectionViewSource.GetDefaultView(DataCollection).Refresh(); } } public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.DataContext = new ViewModel(); } }} Now provide the response and nothing else.
Basic idea is: Use controlled component (use value and onChange property of input field), and inside onChange handle check whether the entered value is proper number or not. Update the state only when entered value is a valid number. For that use this regex : /^[0-9\b]+$/; onChange handler will be: onChange(e){ const re = /^[0-9\b]+$/; // if value is not blank, then test the regex if (e.target.value === '' || re.test(e.target.value)) { this.setState({value: e.target.value}) }} Working example: class App extends React.Component{ constructor(){ super(); this.state = {value: ''}; this.onChange = this.onChange.bind(this) } onChange(e){ const re = /^[0-9\b]+$/; if (e.target.value === '' || re.test(e.target.value)) { this.setState({value: e.target.value}) } } render(){ return <input value={this.state.value} onChange={this.onChange}/> }}ReactDOM.render(<App/>,document.getElementById('app')) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id='app'/>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/43067728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7288069/']}
jdg_79298
stackexchange
llm_judgeable_groundtruth_similarity
2403138
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $A$ is an $n\times n$ matrix such that all eigen values of $A$ are less than $1$,then is it true that for any $v\in \Bbb R^n$ we have $||Av||\le ||v||$. Since $A$ has eigen value less than $1$ so if $\lambda$ is an eigen value of $A$ then $Av=\lambda v\implies ||Av||<||v||$ but how to use this fact for any $v\in \Bbb R^n$. Any help will be useful. Now provide the response and nothing else.
Since $\lim_{x\to -\infty} (x^3-a)=-\infty$ there exists $x_1\in \mathbb{R}$ such that $f(x_1)=x_1^3-a<0.$ Since $\lim_{x\to \infty} (x^3-a)=\infty$ there exists $x_2\in \mathbb{R}$ such that $f(x_2)=x_2^3-a>0.$ Now, using that $f(x)=x^3-a$ is continuous, we conclude from the intermediate value theorem that there exists $c\in (x_1,x_2)$ such that $f(c)=0.$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2403138', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/294365/']}
jdg_79299
stackexchange
llm_judgeable_groundtruth_similarity
298
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is inspired by a project I undertook for my Physics class last year; I'd like to apply it in the future. Background: For the project, I and a few classmates were required to build a small car powered by any of a number of sources; we opted for a mousetrap that turned two rear wheels on a four-wheel car as it was released. Our group's goal was to make the car go as far as possible. One problem was that the power source was not constant. The lever arm of the trap lifted in an arc for about five seconds, then returned to its resting position. During this time, it propelled the car. The car then coasted for the rest of the way. In the powered stage, we wanted to increase traction. The wheels were CDs (because we had a $5.00 budget), which have a tendency to spin out. So we attached pieces of cloth to them to get better traction. On the second stage, however, we found that this cloth slowed down the car quite a bit because it dramatically increased friction (as we found out after several hours of testing different combinations). Other groups used duct tape to cover the wheels, and some used records, which seemed to do slightly better than CDs (though that violated the size restrictions). Cloth seemed to have the best traction, though - we didn't have many spinouts. The tests were done on a typical classroom floor (I'm not sure what it's made of - linoleum? - but it's the same as in almost every school, at least in America). In a wheeled vehicle in general - obviously not just a small car powered by a mousetrap - how can I substantially improve traction on the wheels while the power source is on yet reduce friction while it coasts? Is it as simple as choosing certain tires, or is there a bigger and better engineering solution? As a final wrap-up: My thought would be to have a shifting center of mass for the vehicle, where the powered wheels have a lesser tendency to slip and the front wheels are nearly frictionless. During the powered stage, the center of mass would be near the back, while in the coasting stage, it would be near the front. This could help reduce the normal force on certain wheels and thereby produce or avoid extra friction. Now provide the response and nothing else.
You need to control how fast you apply the power. Some sort of damper mechanism that would allow power to be gradually applied and not cause it to spin out. You could try and wrap the 'power string' over different sized pulleys so that you changed the gear ratio. If you used a cone it would be similar to a CVT where starting out you would have a low gear ratio to get moving then as the string unwound down the cone it would propel the car faster rather than just spinning out. . Edit: You can either guess at the gear ratio or use some basic statics to figure out coefficient of friction and how to avoid slip while applying torque.
{}
{'log_upvote_score': 4, 'links': ['https://engineering.stackexchange.com/questions/298', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/106/']}
jdg_79300
stackexchange
llm_judgeable_groundtruth_similarity
3628804
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was reading the book "Apress Pro LINQ: Language Integrated Query in C#" and I came across partial methods, but I really don't understand what is the need for them. I think the examples in the book (properties before and after change) can be implemented using events. So any explanation? Now provide the response and nothing else.
Yes, you could achieve a similar effect with events as you can with partial methods. Partial methods are really just a way of letting code generators, primarily designers, to generate hooks for the non-generated code. Events could fill this role. However there are advantages to partial methods over events in particular Partial method calls are completely removed from the generated IL if there is no implementation. This cannot be done with events. The design of partial methods is to solve the problem where there is 1 provider of the hook and 1 consumer. Events are meant to model 1 provider with N consumers and have the overhead which comes with such a design There is no issue of ordering (who goes first). With events you need to ensure the code which subscribes to the event runs before the designer generated code that raises the event. This is not always possible if say the designer generates a constructor. Partial methods have no such issue.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3628804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108714/']}
jdg_79301
stackexchange
llm_judgeable_groundtruth_similarity
2183472
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is the question I'm confused about: Consider a field $F = \{0,1,a\}$ with exactly 3 elements. Can it be an ordered field? Explain your answer in all details. Well obviously, if $F$ is a field, then as $a$ is an element of $F$, $a + a$ also has to be in the field. So I thought that $2a = 1$, since if $2a = 0$ or $2a = a$, then $a = 0$, which is contradictory to the statement that the field has exactly 3 elements. Then it's concluded that $a = 1/2$, but if that's true, $1 + 1/2 = 3/2$ also has to be in this field, but it's not. Therefore I concluded that it can't be an ordered field. But something seems so wrong about my solution. I would appreciate any advice on what I was wrong about, and any correct ways to solve this problem. Now provide the response and nothing else.
In general, a finite field can never be an ordered field. Let $a$ be some positive element -- that is, $0<a$. By repeatedly adding $a$ on both sides of this, we find$$ 0 < a < (a+a) < (a+a+a) < (a+a+a+a) < \ldots $$but since the field is finite, there must be two of the expressions in this sequence that have the same value. If that value is $t$, then by transitivity we have $t<t$, which contradicts $t=t$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2183472', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/424477/']}
jdg_79302
stackexchange
llm_judgeable_groundtruth_similarity
91792
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have written a small library of classes in my preferred language (PHP, but it doesn't really matter), and typically use them in most of my projects. Until now, the projects have been personal, or small stuff at my part time job that isn't really a commercial product. Neither of these things worry me as far as the freedom I have to reuse those same libraries later. [On that note, should I be worried about the part time job uses? Could those cause issues with my libraries later?] Soon, however, I expect to enter into more serious free-lance/contract work that I have no doubt will use the libraries I've written. Do I need to make sure the contract or work terms explicitly allows me to use my previous code in the project and - more importantly - after the project, or is a Github history showing that it was clearly developed long before any contract enough? What are the legal troubles with code like this (libraries, code reuse, open-source, etc.)? Now provide the response and nothing else.
It is good to think carefully about these issues ahead of time, even though you seem to have everything in hand. You do need to make the employer aware that you are going to be licensing this code to them (sourcecode license, in perpetuity, for derived works etc). You should document that licence explicitly (by reference) in the source code and possibly the user interface, and in a signed agreement with your employer. That gives them an opportunity to make an informed choice. Be very careful about and talk to your boss about derived works that you make on their behalf (they would naturally/legally own all derived works made on their behalf, they may be unhappy or surprised to see derived works on github). It would be a lot be easier for you to fully open source the code first, then you can say in the agreement that contributions/enhancements to your project x are expected, and contributions are explicitly under the same open source license. You might need to talk to a lawyer in terms of evening work that you do on the project, I often see language in contracts that doesn't allow you to own your IP created while an employee/contractor of a company (even in the evenings). Talking to your employer about this might be a good thing, or could label you a pedant (like most programmers) so tread lightly. My wife went through this when she started teaching. She brought her teaching materials into the school. So she got her contributions documented at the start so she can use them in future.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/91792', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/30951/']}
jdg_79303
stackexchange
llm_judgeable_groundtruth_similarity
68939014
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to implement Firebase Realtime Database into a angular project and Im getting stuck at one of the very first steps. Importing AngularFireModule and AngularFireDatabaseModule. It gives me the following error: Module '"@angular/fire"' has no exported member 'AngularFireModule'.ts(2305) Module '"@angular/fire/database"' has no exported member 'AngularFireDatabaseModule'. And here is how I am importing them: import {AngularFireModule } from '@angular/fire';import {AngularFireDatabaseModule} from '@angular/fire/database' Am I missing something here? I have installed @angular/fire via the command npm i firebase @angular/fire and have also installed firebase tools. Here is a list of the Angular packages I currently have installed and their versions: Angular CLI: 12.2.2Node: 14.17.4Package Manager: npm 6.14.14OS: win32 x64Angular: 12.2.3... animations, common, compiler, compiler-cli, core, forms... platform-browser, platform-browser-dynamic, routerPackage Version---------------------------------------------------------@angular-devkit/architect 0.1202.2@angular-devkit/build-angular 12.2.2@angular-devkit/core 12.2.2@angular-devkit/schematics 12.2.2@angular/cli 12.2.2@angular/fire 7.0.0@schematics/angular 12.2.2rxjs 6.6.7typescript 4.3.5 I do apologise if this is all excessive information but I am completely stuck as to what the issue is. Any help would be GREATLY appreciated. Right now my suspicion is that its a compatibility issue or perhaps a feature that doesnt exist anymore on the latest versions but I really dont know. Now provide the response and nothing else.
AngularFire 7.0.0 was launched yesterday with a new API that has a lot of bundle size reduction benefits. Instead of top level classes like AngularFireDatabase , you can now import smaller independent functions. import { list } from '@angular/fire/database'; The initialization process is a bit different too as it has a more flexible API for specifying configurations. @NgModule({ imports: [ provideFirebaseApp(() => initializeApp(config)), provideFirestore(() => { const firestore = getFirestore(); connectEmulator(firestore, 'localhost', 8080); enableIndexedDbPersistence(firestore); return firestore; }), provideStorage(() => getStorage()), ],}) If you want to proceed with the older API there's a compatibility layer . import { AngularFireModule} from '@angular/fire/compat'import { AngularFireDatabaseModule } from '@angular/fire/compat/database'; See the version 7 upgrade docs for more information .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/68939014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15357275/']}
jdg_79304
stackexchange
llm_judgeable_groundtruth_similarity
47347318
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: public class Router { ... private static Retrofit retrofit = null; ... public Retrofit getRetrofit() { if (retrofit == null) { ... OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build(); retrofit = new Retrofit.Builder() .baseUrl("***") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) .build(); } return retrofit; } ...} I setup timeout in OkHttpClient . Now there is a API needs different timeout. How can i do? Is there something like this? @TimeoutObservable<ResponseBody> exapmle(@Timeout("connect") int connect , @Timeout("read") int read , @Timeout("write") int write); Now provide the response and nothing else.
Thanks a lot. here is my code: public static final String CONNECT_TIMEOUT = "CONNECT_TIMEOUT";public static final String READ_TIMEOUT = "READ_TIMEOUT";public static final String WRITE_TIMEOUT = "WRITE_TIMEOUT";...Interceptor timeoutInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); int connectTimeout = chain.connectTimeoutMillis(); int readTimeout = chain.readTimeoutMillis(); int writeTimeout = chain.writeTimeoutMillis(); String connectNew = request.header(CONNECT_TIMEOUT); String readNew = request.header(READ_TIMEOUT); String writeNew = request.header(WRITE_TIMEOUT); if (!TextUtils.isEmpty(connectNew)) { connectTimeout = Integer.valueOf(connectNew); } if (!TextUtils.isEmpty(readNew)) { readTimeout = Integer.valueOf(readNew); } if (!TextUtils.isEmpty(writeNew)) { writeTimeout = Integer.valueOf(writeNew); } return chain .withConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS) .withReadTimeout(readTimeout, TimeUnit.MILLISECONDS) .withWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS) .proceed(request); }};OkHttpClient httpClient = new OkHttpClient.Builder() .connectTimeout(DEFAULT_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS) .writeTimeout(DEFAULT_WRITE_TIMEOUT, TimeUnit.MILLISECONDS) .readTimeout(DEFAULT_READ_TIMEOUT, TimeUnit.MILLISECONDS) .addInterceptor(timeoutInterceptor) .build();retrofit = new Retrofit.Builder() .baseUrl(Host.Develop.ACCOUNT_HOST) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(httpClient) .build();... example usage: /** * check account status * * @param account * @return */@Headers({"CONNECT_TIMEOUT:10000", "READ_TIMEOUT:10000", "WRITE_TIMEOUT:10000"})@GET("login/prelogin")Observable<ResponseBody> preLogin(@Query("account") String account); or /** * check account status * * @param connectTimeout * @param readTimeout * @param writeTimeout * @param account * @return */@GET("login/prelogin")Observable<ResponseBody> preLogin( @Header("CONNECT_TIMEOUT") String connectTimeout, @Header("READ_TIMEOUT") String readTimeout, @Header("WRITE_TIMEOUT") String writeTimeout, @Query("account") String account);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47347318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6429338/']}
jdg_79305
stackexchange
llm_judgeable_groundtruth_similarity
17910096
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The at-sign @ is often used in git to specify revisions in differentways. For example, <ref>@{<date>} specifies the reference at its state on <date> . Example: git diff master@{yesterday} master . <ref>@{<n>} specific the reference at its n th prior state. Example: git diff master@{1} master . @{-<n>} specifies the n th previously checked-out branch beforethe current one. Example: git checkout @{-5} . <ref>@{upstream} specifies the upstream branch for the reference. Example: git diff master@{upstream} master . However , the @ is being used in other ways in git commands too, like git rebase -i @~4git log @^^..@ What does the at-sign @ mean in those examples? Now provide the response and nothing else.
As of Git version 1.8.5 , the at-sign @ , without a leading branch/reference name and ordinal {n} suffix like HEAD@{1} and master@{1} , is just a synonym/alias/shortcut for the special Git reference HEAD : Instead of typing four capital letters "HEAD", you can say "@" now, e.g. "git log @". So for these commands git rebase -i @~4git log @^^..@ you can simply substitute the first occurrence of @ with HEAD (or head if using Windows or OS X) git rebase -i HEAD~4git log HEAD^^..HEAD So what does HEAD mean? As explained by the official Linux Kernel Git documentation for specifying Git revisions , HEAD is a special shortcut reference for the commit that you currently have checked-out as your working copy (or in Git terms, your "working tree"): HEAD names the commit on which you based the changes in the working tree. You can also read these other Stack Overflow questions on what the special reference HEAD means: HEAD and ORIG_HEAD in Git . What is git HEAD, exactly? . VonC also found interesting information about why @ was chosen as a shortcut for head in this Stack Overflow answer (the last section at the bottom) . Note that like it often happens with Git, while @ is a convenient shortcut, it isn't always a valid replacement for HEAD . Example: $ git bundle create temp.bundle @Enumerating objects: 25, done.Counting objects: 100% (25/25), done.Compressing objects: 100% (20/20), done.Total 25 (delta 3), reused 0 (delta 0), pack-reused 0$ git bundle list-heads temp.bundlec006e049da432677d1a27f0eba661671e0524710 refs/heads/master$ git bundle create temp.bundle HEADEnumerating objects: 25, done.Counting objects: 100% (25/25), done.Compressing objects: 100% (20/20), done.Total 25 (delta 3), reused 0 (delta 0), pack-reused 0$ git bundle list-heads temp.bundlec006e049da432677d1a27f0eba661671e0524710 HEAD In this case, using @ is more like a replacement for master (the branch that HEAD happened to be pointing to) rather than for HEAD . If you try to fetch from the resulting bundle later, you'll have to specify the ref you want to fetch ( master ) if you used @ , and you won't have to to it if you specified HEAD explicitly.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17910096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_79306
stackexchange
llm_judgeable_groundtruth_similarity
1131922
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If we have that $\frac{1}{1+x_1}+\frac{1}{1+x_2}+...+\frac{1}{1+x_n}=1$, then prove that $\sqrt[n]{x_1x_2...x_n}\ge (n-1)$.Where $x_1,x_2,...,x_n$ are all non negative real numbers. I got $x_1+x_2+...+x_n\ge n(n-1)$.Also we have $\frac{x_1}{1+x_1}+\frac{x_2}{1+x_2}+...+\frac{x_n}{1+x_n}=n-1$. Now provide the response and nothing else.
let $$\dfrac{1}{1+x_{i}}=b_{i}\Longrightarrow x_{i}=\dfrac{1-b_{i}}{b_{i}},b_{1}+b_{2}+\cdots+b_{n}=1$$Use AM-GM inequality$$b_{2}+b_{3}+\cdots+b_{n}\ge (n-1)\cdot\sqrt[n-1]{b_{2}b_{3}\cdots b_{n}}$$$$b_{3}+b_{4}+\cdots+b_{1}\ge (n-1)\cdot\sqrt[n-1]{b_{3}b_{4}\cdots b_{1}}$$$$\cdots\cdots$$$$b_{1}+b_{2}+\cdots+b_{n-1}\ge (n-1)\cdot\sqrt[n-1]{b_{1}b_{2}\cdots b_{n-1}}$$so we have$$x_{1}x_{2}\cdots x_{n}=\dfrac{\displaystyle\prod_{cyc}(b_{2}+b_{3}+\cdots+b_{n})}{\prod_{cyc}b_{1}}\ge \dfrac{(n-1)^{n}\cdot\prod_{cyc}\sqrt[n-1]{b_{2}\cdots b_{n}}}{\prod_{cyc}b_{1}}=(n-1)^n$$so$$\sqrt[n]{x_{1}x_{2}\cdots x_{n}}\ge n-1$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1131922', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/193538/']}
jdg_79307
stackexchange
llm_judgeable_groundtruth_similarity
484464
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In quantum mechanics, what exactly is meant by "local" operator? What about a "global" or a "non-local" operator? Are these the same? Can you also also help me understand what exactly is a local perturbation and a local symmetry? Now provide the response and nothing else.
A local operator is one whose action only depends on the value of the wave function (and its derivatives) at a single point. Almost all the ordinary operators one encounters are local in this sense, including $\hat{x}$ , $\hat{p}$ , $\hat{L}_{z}$ , etc. The opposite of "local" in this context is not "global," but rather "nonlocal." A nonlocal operator would act in something like the following way: $$\hat{W}\psi\left(\vec{x}\right)=\int d^{3}x'\, W\left(\vec{x},\vec{x}'\right)\psi\left(\vec{x}'\right).$$ The nonlocality comes from the fact that the value of $\hat{W}\psi$ at a point $\vec{x}$ depends on the value of $\psi$ at other points. The condition for $\hat{W}$ to be Hermitian is $W\left(\vec{x},\vec{x}'\right)=W\left(\vec{x}',\vec{x}\right)^{*}$ . The use of the terms "local perturbation" and "local symmetry" are less clearcut. A local perturbation might be one of two things. It might be a perturbation (added to the Hamiltonian) that is represented by a local operator. Or it might mean a position-dependent perturbation that goes to zero at spatial infinity. (Without further context, it is not possible to know which is meant. I requested a monograph from the library once, since it was supposed to be about "nonlocal solitons," thinking that it would cover solitary waves with nonlocal interactions like $\hat{W}$ above. In fact, it turned out to be a book about non- localized solitonic phenomena.) Having a local symmetry means that the symmetry transformation will be allowed to depend on position, but there may be other conditions applied. Some people restrict the term "local symmetry" to mean a gauge symmetry of the second kind; other people use it to mean something different.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/484464', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/202416/']}
jdg_79308
stackexchange
llm_judgeable_groundtruth_similarity
44153517
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First of all, I am pretty familiar with the withRouter HoC, however, in this case, it doesn't help because I do not want to access the history object in a component. I am trying to achieve a mechanism that will redirect the user to the login page if I receive back a 401 from a API endpoint. For making http requests I am using axios . I have around 60 endpoints that I need to cover, that are used in a dozen of components throughout my app. I want to create a decorator function to the axios instance object, that: 1. makes the request2. if fail && error_code = 401, update user route to `/login`3. if success, return promise The problem I have with the above is to update the route of the user. Previously, in react-router-v3 , I could have imported the browserHistory object directly from the react-router package, which is no longer possible. So, my question is, how can I access the history object outside of the React Component without passing it trough the call stack? Now provide the response and nothing else.
react-router v4 also provides a way to share history via the history package, namely createBrowserHistory() function. The important part is to make sure that the same history object is shared across your app. To do that you can take advantage of the fact that node modules are singletons. Create a file called history.js in your project, with the following content: import { createBrowserHistory } from 'history';const history = createBrowserHistory();export default history; You can then just import it in your application via: import history from "./history.js"; Please note that only Router accepts the history prop ( BrowserRouter does not), so be sure to update your router JSX accordingly: import { Router } from "react-router-dom";import history from "./history.js";// and then in your JSX:return ( <Router history={history}> {/* routes as usuall */} </Router>) A working example can be found at https://codesandbox.io/s/owQ8Wrk3
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44153517', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1769519/']}
jdg_79309
stackexchange
llm_judgeable_groundtruth_similarity
47772
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Hebrews 12:9 (DRB): Moreover we have had fathers of our flesh, for instructors, and we reverenced them: shall we not much more obey the Father of spirits , and live? 2 Corinthians 3:17 "the LORD is the spirit". John 4:24 "God is spirit". In Hebrews 12:9 who is the Father of spirits? the Son or God the Father? Now provide the response and nothing else.
It is likely that the author has in mind Numbers 16:22 and 27:16 wherein Yahveh is referred to by the title אֱלֹהֵי הָרוּחֹת לְכָל־בָּשָׂר ( elohei ha-ruchot lekol-basar )—“the God of the spirits of all flesh.” Hence, “the father of spirits” would be Yahveh. As both Father and Son are Yahveh, 1 the “father of spirits” would be the Father and Son [and Holy Spirit], as the Trinity. However, it is likely that the author only has in mind the person of God the Father in this particular context. Footnotes 1 cf. Zech. 2:8–11, where Yahveh of hosts sends Yahveh of hosts.
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/47772', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/33285/']}
jdg_79310
stackexchange
llm_judgeable_groundtruth_similarity
30960686
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Both will be able to execute commands in container. Both could detach the container. So what is the real difference between docker exec and docker attach? Now provide the response and nothing else.
2015: There was a commit PR which added to the doc: Note: This command ( attach ) is not for running a new process in a container.See: docker exec . The answer to " Docker. How to get bash\ssh inside runned container ( run -d )? " illustrates the difference: (docker >= 1.3) If we use docker attach , we can use only one instance of shell . So if we want to open new terminal with new instance of container's shell, we just need to run docker exec if the docker container was started using /bin/bash command, you can access it using attach, if not then you need to execute the command to create a bash instance inside the container using exec . As mentioned in this issue : Attach isn't for running an extra thing in a container, it's for attaching to the running process. " docker exec " is specifically for running new things in a already started container, be it a shell or some other process. The same issue adds: While attach is not well named, particularly because of the LXC command lxc-attach (which is more akin docker exec <container> /bin/sh , but LXC specific), it does have a specific purpose of literally attaching you to the process Docker started. Depending on what the process is the behavior may be different , for instance attaching to /bin/bash will give you a shell, but attaching to redis-server will be like you'd just started redis directly without daemonizing. Update 2022: See more with " Containers 101: attach vs. exec - what's the difference? " (Dec. 2021) from Ivan Velichko : Extract: Difference between attach and logs On the diagram above, docker attach streams the container's logs back to the terminal. However, the docker logs command does a similar thing. So, what's the difference? The logs command provides various options to filter the logs while attach in that regard acts as a simple tail. But what's even more important is that the stream established by the logs command is always unidirectional and connected to the container's logs, not the container's stdio streams directly. The logs command simply streams the content of the container's logs back to your terminal, and that's it. So, regardless of how you created your container (interactive or non-interactive, controlled by a pseudo-terminal or not), you cannot accidentally impact the container while using the logs command. However, when attach is used: If a container was created in the interactive mode ( -i ), everything you type in the terminal after attach-ing to the container will be sent to its stdin. You can (intentionally or accidentally) send a signal to the container - for instance, hitting ctrl+c on your end while attached sends SIGINT to the container . What does exec command do The exec command is actually a totally different story. In the case of attach, we were connecting our terminal to an existing container (read, process). However, the exec command starts a totally new container! In other words, exec is a form of the run command (which itself is just a shortcut for create + start ). Bart reminds us in the comments that docker exec runs a new command in a running container. Not a "totally new one".
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30960686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4912768/']}
jdg_79311
stackexchange
llm_judgeable_groundtruth_similarity
879152
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want my web page to beep whenever a user exceeds the maximum character limit of my <textarea> . Now provide the response and nothing else.
Solution You can now use base64 files to produce sounds when imported as data URI . The solution is almost the same as the previous ones, except you do not need to import an external audio file. function beep() { var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU="); snd.play();}beep(); Compatibility Data URI is supported on almost every browser now. More information on http://caniuse.com/datauri Demo http://jsfiddle.net/7EAgz/ Conversion Tool And here is where you can convert mp3 or wav files into Data URI format: https://dopiaza.org/tools/datauri/index.php
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/879152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/29774/']}
jdg_79312
stackexchange
llm_judgeable_groundtruth_similarity
1706
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: You need quantmod & tseries in R to run this: library(quantmod)library(tseries)pairs <- c( "EUR/USD", "GBP/USD", "AUD/USD", "USD/CAD", "USD/CHF", "NZD/USD" )name <- function(n) { gsub("/","",n,fixed=TRUE)}getFrame <- function(p) { result <- NULL as.data.frame(lapply(p, function(x) { if(!exists(name(x))) { getSymbols(x, src="oanda") } if(is.null(result)) { result <- get(name(x)) } else { result <- merge(result, get(name(x))) } }))}isStationary <- function(frame) { model <- lm(frame[,1] ~ as.matrix(frame[,-1]) + 0) spread <- frame[,1] - rowSums(coef(model) * frame[, -1]) results <- adf.test(spread, alternative="stationary", k=10) if(results$p.value < 0.05) { coefficients <- coef(model) names(coefficients) <- gsub("as.matrix.frame.......", "", names(coefficients)) plot(spread[1:100], type = "b") cat("Minimum spread: ", min(spread), "\n") cat("Maximum spread: ", max(spread), "\n") cat("P-Value: ", results$p.value, "\n") cat("Coeficients: \n") print(coefficients) }}frame <- getFrame(pairs)isStationary(frame) I get FX daily data from Oanda, do a simple linear regression to find the hedging ratios, and then use the Augmented DF test to test for the P-value of mean reversion in the spread. When I run it I get this: Minimum spread: -1.894506 Maximum spread: 2.176735 P-Value: 0.03781909 Coeficients: GBP.USD AUD.USD USD.CAD USD.CHF NZD.USD 0.59862816 0.48810239 -0.12900886 0.04337268 0.02713479 EUR.USD coefficient is 1. When I plot the spread the first 100 days look like this: Surely something must be wrong. The holy grail shouldn't be so easy to find. Can someone help me find what is wrong? I tried backtesting on Dukascopy with the above coefficients as lot sizes of a basket, but I run into loses. And the spread has a different order of magnitude in dukascopy. Why is that? Now provide the response and nothing else.
The main problem in your code is this line: rowSums(coef(model) * frame[, -1]) I'm not sure exactly what is does, perhaps some matrix multiplication, but definitely not what you expect it to do. Try to replace it with manual multiplication spread <- frame[,1] - (coef(model)[1]*frame[,2] + coef(model)[2]*frame[,3] + coef(model)[3]*frame[,4] + coef(model)[4]*frame[,5] + coef(model)[5]*frame[,6]) And holy grail will disappear I can see a couple of other errors as well: You cant sell on ASK price. With getSymbols.oanda you always get ASK You'd better separate testing and training data sets
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/1706', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/1231/']}
jdg_79313
stackexchange
llm_judgeable_groundtruth_similarity
47832
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm reading up on the Cryptolocker virus, and I came across this comment , it says: And one additional measure: disable the default "Hide extensions for known file types" check box in Explorer. I still consider this one of the stupidest moves MS ever made in Windows. The comment has 17 thumbs up, and comments below agreeing. I've never heard this before? How does this make a system more secure? Now provide the response and nothing else.
Consider a file named doubleclick.pdf.bat. If "Hide extensions" is enabled, then this will be shown in File Explorer as "doubleclick.pdf". You, the user, might go ahead and double click on it, because it's just a PDF, right? It'll load up in Acrobat if you do that, right? When, in truth, it's a batch file, and whatever commands it contains will run when you double click on it. That's why "Hide extensions for known file types" is a stupid move in Security terms. It allows an attacker to create wolf files that look like sheep.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/47832', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/6838/']}
jdg_79314
stackexchange
llm_judgeable_groundtruth_similarity
350612
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a bit of trouble showing that the two quadratic fields $\mathbb{Q}[X]/(X^2+1)$ and $\mathbb{Q}[X]/(X^2+3)$ over $\mathbb{Q}$ are not isomorphic (as fields). Could someone help me? Perhaps the two fields are isomorphic to each other? Many thanks for your answers. Now provide the response and nothing else.
Show that there is no element $\alpha$ of $\Bbb Q[X]/(X^2+3)$ such that $-\alpha=\alpha^{-1}$. There is certainly such an element in $\Bbb Q[X]/(X^2+1)$--namely, the equivalence class of $X$. A field isomorphism would guarantee that such an element exists in the other, too. Alternately (equivalently), show that $\Bbb Q[X]/(X^2+3)$ has no primitive $4$th root of unity.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/350612', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68418/']}
jdg_79315
stackexchange
llm_judgeable_groundtruth_similarity
21357437
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: basically i want to have an inputted message, and if it is not a valkue of 16 add random letters to it to make it a mulitple of 16 this is my current code: import maths = "IYGGRTOCTOERGTDKHUTAOHEIIATTOICNNRIHDSRGKENEACA!"i = 16rows = [s[x:x+i] for x in range(0, len(s), i)] #print('\n'.join(rows))columns = list(zip(*rows))print i, columns This does nothing fancy and insteadjust splits the input up every 16 characters and takes the first letter from each coulmn then outputs it etc, a very basic transpoistion cypher so what i am trying to do it figure out if s is a multiple of 16, and if not add some random letters to s until it isso how can i achieve this in python ? thanks guys Now provide the response and nothing else.
First you calculate how many "extra" characters you have: extra = len(s) % 16 Then, there are two possibilities: extra > 0 You calculate how much padding you will need to fill a 16-character block: padsize = 16 - extra Finally, you add padsize padding characters (perhaps a space ) at the end: s = s + (' ' * padsize) extra == 0 s is ok the way it is. Putting everything together and not using padsize : extra = len(s) % 16if extra > 0: s = s + (' ' * (16 - extra)) With random padding Of course, ' ' is not the only padding possible. You can use random.choice to pick a character from a certain list and use that as padding. There are some nice predefined lists of characters, you can either use string.letters and the like: padding = random.choice(string.letters) or use your own list of possible paddings: padding = random.choice("x|#_ ") So, putting everything together again: import stringimport randompadding = random.choice(string.letters)extra = len(s) % 16if extra > 0: s = s + (padding * (16 - extra))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21357437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2292674/']}
jdg_79316
stackexchange
llm_judgeable_groundtruth_similarity
2417978
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference in functionality between StreamWriter.Flush() and StreamWriter.Close() ? When my data wasn't being written correctly to a file, I added both Flush() and Close() to the end of my code. However, I realized that adding either Flush() or Close() allowed the data to be written correctly. I wasn't able to pick up on exactly what each of these methods does when I read the MSDN docs; I only figured out that one or the other is necessary to ensure data is written correctly. Any further explanation would be much appreciated. Where s is a string to be written, here's what my code looks like currently: StreamWriter sw = File.CreateText("TextOutput.txt");sw.Write(s);sw.Flush();sw.Close(); Based on feedback from the answers, I've rewritten my code in a using block, which implements IDisposable and will automatically take care of writing the stream to the file when the object is disposed: using (StreamWriter sw = File.CreateText("TextOutput.txt")){ sw.Write(s);} Now provide the response and nothing else.
StreamWriter.Flush() can be called any time you need to clear the buffer, and the stream will remain open. StreamWriter.Close() is for closing the stream, at which point the buffer is also flushed. But you shouldn't really need to call either of these. Any time I see a .Close() in code I take that as a code smell, because it usually means an unexpected exception could cause the resource to be left open. What you should do, is create your StreamWriter variable in a using block, like this: using (var writer = new StreamWriter("somefilepath.txt")){ // write a bunch of stuff here} // the streamwriter WILL be closed and flushed here, even if an exception is thrown.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2417978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166258/']}
jdg_79317
stackexchange
llm_judgeable_groundtruth_similarity
3629254
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider: var resturl = "http://example.com";cj.getJSON( resturl + "&callback=?", function(data) { console.log(data); }); My callback function is never called. Why? Now provide the response and nothing else.
Two things here: First, your URL addition should be "?callback=?" since there's no other querystring, or use the full $.ajax() call with a jsonp data type, so it adds the querystring as needed, like this: $.ajax({ url: resturl, dataType: 'jsonp', success: function(data){ console.log( data ); }}); Second, the domain you're going to has to support JSONP .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3629254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191503/']}
jdg_79318
stackexchange
llm_judgeable_groundtruth_similarity
1851620
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a listview that generates thumbnail using a backgroundworker. When the listview is being scrolled i want to pause the backgroundworker and get the current value of the scrolled area, when the user stopped scrolling the listview, resume the backgroundworker starting from the item according to the value of the scrolled area. Is it possible to handle scroll event of a listview? if yes how? if not then what is a good alternative according to what i described above? Now provide the response and nothing else.
You'll have to add support to the ListView class so you can be notified about scroll events. Add a new class to your project and paste the code below. Compile. Drop the new listview control from the top of the toolbox onto your form. Implement a handler for the new Scroll event. using System;using System.Windows.Forms; class MyListView : ListView { public event ScrollEventHandler Scroll; protected virtual void OnScroll(ScrollEventArgs e) { ScrollEventHandler handler = this.Scroll; if (handler != null) handler(this, e); } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == 0x115) { // Trap WM_VSCROLL OnScroll(new ScrollEventArgs((ScrollEventType)(m.WParam.ToInt32() & 0xffff), 0)); } } } Beware that the scroll position (ScrollEventArgs.NewValue) isn't meaningful, it depends on the number of items in the ListView. I forced it to 0. Following your requirements, you want to watch for the ScrollEventType.EndScroll notification to know when the user stopped scrolling. Anything else helps you detect that the user started scrolling. For example: ScrollEventType mLastScroll = ScrollEventType.EndScroll;private void myListView1_Scroll(object sender, ScrollEventArgs e) { if (e.Type == ScrollEventType.EndScroll) scrollEnded(); else if (mLastScroll == ScrollEventType.EndScroll) scrollStarted(); mLastScroll = e.Type;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1851620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/211349/']}
jdg_79319
stackexchange
llm_judgeable_groundtruth_similarity
11757672
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A colleague created a local branch ('branchA') from master, did some work, pushed it, merged in master, did some more work and pushed it again. Concurrently, other colleagues have been working on other branches and merging them to master. Now I need to pull branchA to review it. So I've done a git pull and git checkout -b branchA origin/branchA which is fine. But all of the commands (git diff/log/show) show commits made across all branches in the repo. How can I view a diff of all of the commits made to branchA against the version of master that it was created from? Also how can I git diff branchA against the current HEAD of master, but only view files changed within branchA? Now provide the response and nothing else.
The following applies to your second question, how to find the differences between branchA and your local's current version of master . You want to use 'double dot' syntax with git log to see all the commits in branchA that aren't in master . To wit: git log master..branchA Per the git log man page: SYNOPSIS git log [<options>] [<since>..<until>] [[--] <path>...] ... <since>..<until> Show only commits between the named two commits. When either <since> or <until> is omitted, it defaults to HEAD, i.e. the tip of the current branch. For a more complete list of ways to spell <since> and <until>, see gitrevisions(7). If you'd like to see commits in either master or branchA , but not in both, you can use 'triple-dot' syntax: git log master...branchA Finally, you can use the exact same syntax with git diff , namely, git diff master..branchA and git diff master...branchA , respectively. As an aside, if you have branchA checked out, you don't even need to specify it as <until> . Git will assume HEAD if it's left unspecified, so these two sets of commands are equivalent: git checkout branchAgit log master.. and git log master..branchA
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11757672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1491250/']}
jdg_79320
stackexchange
llm_judgeable_groundtruth_similarity
17035083
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hey guys I would love your help in regards to the code below, I am quite new to php and and sql, and I am trying to blind these values for a order check out process. There are multiple pages that I need to capture the information from.... I have looked over this code for hours and I am unable to find where I am going wrong...This may be because I am really not sure where I need to be looking to fix this problem. Any help or advice would help so much! function writeOrderToDatabase(){ // open database connection include 'includes/connection.php'; // store order date in Australian format for printouts etc $_SESSION['orderDate'] = date('d-m-Y');try{ // create our sql insert orders statement $sql = "INSERT INTO orders SET orderNbr=: orderNbr,custNbr=:custNbr,orderDate=:orderDate, OrderNetValue=:OrderNetValue,deliverTo = :deliverTo, deliveryAddress1 = :deliveryAddress1, deliveryAddress2 = :deliveryAddress2, deliverySuburb = :deliverySuburb, deliveryState = :deliveryState, deliveryPostCode = :deliveryPostCode, deliverySuburb = :deliverySuburb, deliveryState = :state, deliveryPostCode = :deliveryPostCode, deliveryInstructions = :deliveryInstructions, shippingValue=:shippingValue, paymentType=:paymentType, paymentRef=:paymentRef;"; // prepare the statement $statement = $pdo->prepare($sql);$orderNbr = 0; // bind the values $statement->bindValue(':orderDate', date('Y-m-d')); $statement->bindValue(':custNbr', $_SESSION['custNbr']); $statement->bindValue(':dispatchDate', $_SESSION['dispatchDate']); $statement->bindValue(':deliveryDate', $_SESSION['deliveryDate']); $statement->bindValue(':OrderNetValue', $_SESSION['OrderNetValue']); $statement->bindValue(':deliverTo', $_SESSION['deliverTo']); $statement->bindValue(':deliveryAddress1', $_SESSION['deliveryAddress1']); $statement->bindValue(':deliveryAddress2', $_SESSION['deliveryAddress2']); $statement->bindValue(':deliverySuburb', $_SESSION['deliverySuburb']); $statement->bindValue(':deliveryState', $_SESSION['deliveryState']); $statement->bindValue(':deliveryPostCode', $_SESSION['deliveryPostCode']); $statement->bindValue(':deliveryInstructions', $_SESSION['deliveryInstructions']); $statement->bindValue(':shippingValue', $_SESSION['shippingValue']); $statement->bindValue(':paymentType', $_SESSION['paymentType']); $statement->bindValue(':paymentRef', $_SESSION['paymentRef']); $statement->bindValue(':sellingPrice', $_SESSION['sellingPrice']); $statement->bindValue(':newQtyOnHand', $_SESSION['newQtyOnHand']); // execute the statement $success = $statement->execute(); } // end try catch (PDOException $e) { echo 'Error adding order: ' . $e->getMessage(); exit(); } // end catch // test the result and get order nbr just created or display appropriate message if ($success) {echo $sql = 'SELECT orderNbr FROM orders ORDER BY orderNbr'; foreach ($conn->query($sql) as $row) { print $row['orderNbr'] . "\t"; } } else { die("<p>Unable to retreive Order Nbr </p>"); } // read cart and insert orderedItem record(s) and update stock on hand in product records foreach($_SESSION['cart'] as $prodNbr => $value) { // store required details in variables $qtyOrdered = $_SESSION['cart'][$prodNbr]['qtyOrdered']; $qtyOnHand = $_SESSION['cart'][$prodNbr]['qtyOnHand']; $sellingPrice = $_SESSION['cart'][$prodNbr]['price']; try { // create orderedItem table sql insert statement $sql = "INSERT INTO orderedItem SET orderNbr=:custNbr,prodNbr=: prodNbr, qtyOrdered=:qtyOrdered,sellingPrice = :sellingPrice;"; } // end try catch (PDOException $e) { echo 'Error adding orderedItem: ' . $e->getMessage(); exit(); } // end catch // test the result and display appropriate message if (!$success) { die("<p>Unable to execute the orderedItem table insert</p>"); } // create new quantity on hand value for the product record $newQtyOnHand = $qtyOnHand - $qtyOrdered; try { // create product table sql update statement$sql="UPDATE product SET prodNbr= :prodNbr,prodName= :prodName,price= :price,qtyOnHand= :qtyOnHand,description= :description, photo= :photo,thumbNail= :thumbNail ,suppCode= :suppCode ;"; } // end try catch (PDOException $e) { echo 'Error updating product qtyOnHand: ' . $e->getMessage(); exit(); } // end catch // test the result and display appropriate message if (!$success) { die("<p>Unable to execute the product table update</p>"); } } // end of foreach } // end of function Now provide the response and nothing else.
Sounds like the internals of your class should probably have a Logger and that you'll want to add a FileHandler to the Logger . You might want to consider just using a factory method that creates Logger s and adds the handler instead of implementing your own class. You may need to create the directories that hold the log files. See this answer for advice on creating directories. Edit: I don't think you need to write your own Logger class. Python's logging module has all the pieces you need. You probably just need a factory method. The key to realize is you need to create two separate, completely independent logging objects. You do this with logging.getLogger , and any time you pass it a different name, it gives you a different logger. You can use anything you want for the logger's name. For sure, you want to stay away from basicConfig for what you're doing. It's designed to be something simple for people who just want one Logger not doing anything too special. I think this demonstrates the functionality you're after. The key is create two different loggers with different handlers. Then use them separately. Keep in mind that my second call to logging.getLogger doesn't create a new logger; it gets the one we set up initially in setup_logger . log_test.py: from __future__ import absolute_importimport loggingdef setup_logger(logger_name, log_file, level=logging.INFO): l = logging.getLogger(logger_name) formatter = logging.Formatter('%(asctime)s : %(message)s') fileHandler = logging.FileHandler(log_file, mode='w') fileHandler.setFormatter(formatter) streamHandler = logging.StreamHandler() streamHandler.setFormatter(formatter) l.setLevel(level) l.addHandler(fileHandler) l.addHandler(streamHandler) def main(): setup_logger('log1', r'C:\temp\log1.log') setup_logger('log2', r'C:\temp\log2.log') log1 = logging.getLogger('log1') log2 = logging.getLogger('log2') log1.info('Info for log 1!') log2.info('Info for log 2!') log1.error('Oh, no! Something went wrong!')if '__main__' == __name__: main() Sample run: C:\temp>C:\Python\27\python.exe logtest.py2013-06-12 02:00:13,832 : Info for log 1!2013-06-12 02:00:13,832 : Info for log 2!2013-06-12 02:00:13,832 : Oh, no! Something went wrong! log1.log: 2013-06-12 02:00:13,832 : Info for log 1!2013-06-12 02:00:13,832 : Oh, no! Something went wrong! log2.log: 2013-06-12 02:00:13,832 : Info for log 2!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17035083', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2393635/']}
jdg_79321
stackexchange
llm_judgeable_groundtruth_similarity
153968
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that aircraft sometimes employ a 400Hz AC system to save weight on transformers, so I'd imagine that spacecraft might employ a similar technique. I'm wondering if anyone in the aerospace field can confirm 400Hz or higher frequency operation in space. Now provide the response and nothing else.
Most spacecraft use DC power distribution systems with high efficiency DC to DC converters. This is because all power sources on spacecraft are DC - solar arrays, batteries, fuel cells, RTGs, etc. Airplanes use generators connected to the engines for power, so using AC is straightforward. On a spacecraft, since it always starts with DC, there is no point in converting it to AC for distribution just to convert it back to DC later. (Well, switching power supplies do convert it to AC and back internally, but it is not distributed as AC). Much like common switching power supplies in computers and other consumer electronics, the DC to DC converters on spacecraft will operate at high frequencies (kHz or MHz) to save space. However, there is a tradeoff at some point against switching losses. I would imagine that in some cases they will use a lower switching frequency (at the expense of larger components) for an efficiency gain where necessary.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/153968', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/50575/']}
jdg_79322
stackexchange
llm_judgeable_groundtruth_similarity
105485
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Yesterday I asked the following question regarding what would happen if you placed a stolen certificate on your own server and edited the 'host' file so that the DNS name matched: Could a stolen certificate show as trusted? I now know the website in the browser wouldn't appear as trusted, but I have a couple of follow up questions: Would the 'identity'/authentication part possibly show as trusted (even though overall the 'padlock' would still show as untrusted?) Before the SSL/TLS handshake, the diagrams I've looked at show that the protocol authenticates the server first. On Chrome, if you click the padlock > connection, there are two parts, identity and connection. The identity part is the authentication and am I right in thinking this would pass with a stolen certificate if the DNS name was correct? The signature would still be valid I believe as it hasn't been modified therefore will hash to the same value and has been signed by a trusted agent. The answer to the question I linked above explained the reason the connection would show as untrusted is the private key is needed on the server to complete the SSL/TLS handshake. My question is, how is the private key used in the handshake (not looking for too much depth). Am I right in thinking either RSA or Diffie-Hellman can be used to create a shared symmetrical secret key in SSL/TLS, depending on how it is implemented? I understand why a private key is needed with RSA, a random number is encrypted by the client with the servers public key and sent to the server and decrypted with the private key. When I look at a certificate and see a public key, is this always the RSA public key? And is it only used if RSA is the method for generating the secret symmetrical key? If DH is used instead of RSA, is the public key ever on a certificate, or are both the public and private keys created when the connection is made and temporary. Could a SSL/TLS connection not then be created with the attackers server and the stolen certificate would authenticate the server (if the DNS names matched). I know DH is susceptible to MITM attacks and that's why certificates are used for authentication, but if a stolen certificate could authenticate the fake server, could a SSL/TLS connection with DH happen to a fake server using a stolen certificate? If anyone could help clear up the above three questions it would be greatly appreciated. Now provide the response and nothing else.
Regardless of whether DH or RSA is used - First, the server presents its certificate (which contains the server's public key) to the client immediately upon an HTTPS connection. Then, the client and the server negotiate the SSL/TLS protocols and ciphers to be used to facilitate the HTTPS connection. So the same certificate (and thus, the same server public key) are used regardless of whether RSA or DH is used. If DH is used, the server uses its private key to create a digital signature, which the client then verifies using the server's public key from the server's certificate, to authenticate the identity of the server. Aside from this, the server's private and public keys are not used for anything else during the session. With DH, the keys that are used to encrypt the data being sent back and forth between the client and the server are ephemeral - meaning that the keys are used once and not reused. For more info on this, see How ECDHE is signed by RSA in ECDHE_RSA cipher . But, as you can see, it is necessary for the server to have the private key that corresponds to the public key in the certificate, to create a digital signature, which the client then uses to verify the authenticity of the server, in order for DH to proceed. If RSA is used, your statement "I understand why a private key is needed with RSA, a random number is encrypted by the client with the servers public key and sent to the server and decrypted with the private key." is correct. This session key is then used with a symmetrical encryption algorithm (such as AES) to encrypt the data being sent back and forth between the client and the server. So, regardless of whether RSA or DH is used, the server must have the private key that corresponds to the public key in its certificate, in order to complete the SSL/TLS handshake, so that an HTTPS connection can be established - and I strongly doubt that any widely used browser would indicate that a site is trusted without being able to establish an HTTPS connection with it.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/105485', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/76560/']}
jdg_79323
stackexchange
llm_judgeable_groundtruth_similarity
8817290
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am developing a simple Java program to create an Excel file using (Apache POI) API.I am using Oracle 10g as a database and using the ojdbc14 JAR file. I have a table called USERINFO, having three columns, namely USERNAME , PASSWORD , and NAME. Now using Apache POI, I have been able to put all the rows in an Excel file. Since the file contains sensitive data such as username and password, I want to make it password protected.On forums, I have found how to read password protected files, but not how to create them.So how I can achieve this? Now provide the response and nothing else.
Updated: As of version 3.10 POI supports encryption as well as decryption for XLSX files. See the "Encryption Support" page on POI's website . The below is still relevant for XLS binary workbooks. According to the "Encryption Support" page on POI's website POI supports reading encrypted XLS and XLSX files. Encrypting is not mentioned on that page, which implies that it's not supported. This is backed up by searching the POI site for "encrypt" which returns only a handful of results all of which are about decryption. I've also taken a look at the sources for their crypto implementation, which appears to only handle decryption. This isn't surprising; POI is designed for data extraction and search indexing, not for creating new spreadsheets. As others have suggested, it's often possible to work around missing features in POI by creating a template in Excel and then using POI to populate it with data. Unfortunately that won't work for encryption because the file format of encrypted spreadsheets is radically different. If you're willing to pay for commercial software, the latest version of ExtenXLS has full read and write support for all the encryption formats supported by Excel. Just construct an EncryptedWorkBookHandle instead of the normal WorkBookHandle . That will use the strongest possible cipher supported by an unmodified JRE, RC4 for XLS and 128-bit AES for XLSX. If you want to use 256-bit AES with OOXML and you've installed the JCE unlimited policy you can do so with the MSOfficeEncrypter class. JExcelAPI , a popular open-source Java spreadsheet API, does not appear to support encryption at all. Aspose.Cells , a commercial offering, supports stong encryption . The documentation for Actuate's e.Spreadsheet seems to have disappeared from the 'net, so I can't tell whether it supports encryption or not. Since none of the freely available Java spreadsheet APIs seems to support writing encrypted spreadsheets, if you're not willing to use commercial software you'll need to come up with a workaround. You could, for example, write the spreadsheet into an encrypted ZIP file. java.util.zip doesn't support encryption, but it looks like Zip4j does. Full disclosure : I work for Extentech, the company behind ExtenXLS.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8817290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/907687/']}
jdg_79324
stackexchange
llm_judgeable_groundtruth_similarity
42122041
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to replace my Handler method with RxJava. My requirement: I want to call the method getTransactionDetails() only after 5 seconds. This my working code using Handler: new Handler().postDelayed(new Runnable() { @Override public void run() { getTransactionDetails(); } }, 5000); Rx java code - it's not working: Observable.empty().delay(5000, TimeUnit.MILLISECONDS) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(o -> getTransactionDetails()) .subscribe(); Now provide the response and nothing else.
doOnNext() is for side effects. It could be use for example for logging purpose, because logging doesn't alter the flow of data. But you want to pass down the result of getTransactionDetails() , so you should use map instead. Second, Observable.empty() create an Observable that just propagate the finish/dispose message, it trigger neither doOnNext() neither map() . You could fix this using Observable.just() instead but a more idiomatic way would be to use Observable.timer() : Observable.timer(5000, TimeUnit.MILLISECONDS) .map(o -> getTransactionDetails()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( ... ); A final note on Schedulers. Observable.timer() and delay() are executed on the computation scheduler by default so you don't need to call .subscribeOn(Schedulers.io()) to execute getTransactionDetails() outside of main thread. Observable.timer() and delay() could take a Scheduler as a parameter if you want to control this. So you need to call .observeOn(AndroidSchedulers.mainThread()) if you want to use getTransactionDetails() result on UI thread. Every operator after observeOn() is executed on the defined Scheduler , so you have to put observeOn() after computation. Edit : This is of course if you care about the result of getTransactionDetails() . If not, see Clyde answer.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42122041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3748088/']}
jdg_79325
stackexchange
llm_judgeable_groundtruth_similarity
69613
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider if you would the case where we have some list of elements: list0 = {54, 4, 7, 9, 3, 54, 4, 20, 2, 456, 2, 3}; And we have some target list: targetList = {2, 3, 4, 7}; We'd like to scan from left to right through list0 and chop off an RHS tail at the moment all elements in targetList have appeared. With the example given we would have: list0chopped = {54, 4, 7, 9, 3, 54, 4, 20, 2}; As an output. Is there a simple way to do this? Now provide the response and nothing else.
I propose: truncate[a_List, b_List] := a ~Take~ Max @ Lookup[PositionIndex[a][[All, 1]], b, 0] For maximum performance replace PositionIndex with cleanPosIdx from Why is the new PositionIndex horribly slow? I'll add comparative timings later if I get the chance.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/69613', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/23358/']}
jdg_79326
stackexchange
llm_judgeable_groundtruth_similarity
54925361
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We are maintaining a session based on user role. We want to implement timeout functionality when the session is idle for 5 min. We are using @ng-idle/core npm module to do that. My Service file: import { ActivatedRouteSnapshot } from '@angular/router'; import { RouterStateSnapshot } from '@angular/router'; import {Idle, DEFAULT_INTERRUPTSOURCES, EventTargetInterruptSource} from '@ng-idle/core'; @Injectable()export class LoginActService implements CanActivate {constructor(private authService: APILogService, private router: Router,private idle: Idle) { idle.setIdle(10); idle.setTimeout(10); }canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot ): Observable<boolean>|Promise<boolean>|boolean {let role = localStorage.getItem('currentUser');if (localStorage.getItem('currentUser')) { if(next.data[0] == role){ },600000) return true; } }else{ this.router.navigate(['/'], { queryParams: { returnUrl: state.url }}); return false; } }} For sample, I have used setIdle timeout for 5 seconds, But it is not happening. Can somebody guide me how to do this? Now provide the response and nothing else.
You can use bn-ng-idle npm for user idle / session timeout detection in angular apps. This blog post explanation will help you Learn how to Handle user idleness and session timeout in Angular npm install bn-ng-idle app.module.ts import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppComponent } from './app.component';import { BnNgIdleService } from 'bn-ng-idle'; // import bn-ng-idle service @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [BnNgIdleService], // add it to the providers of your module bootstrap: [AppComponent]})export class AppModule { } app.component.ts import { Component } from '@angular/core';import { BnNgIdleService } from 'bn-ng-idle'; // import it to your component @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { constructor(private bnIdle: BnNgIdleService) { // initiate it in your component constructor this.bnIdle.startWatching(300).subscribe((res) => { if(res) { console.log("session expired"); } }) }} In the above example, I have invoked the startWatching(timeOutSeconds) method with 300 seconds (5 minutes) and subscribed to the observable, once the user is idle for five minute then the subscribe method will get invoked with the res parameter's value (which is a boolean) as true. By checking whether the res is true or not, you can show your session timeout dialog or message. For brevity, I just logged the message to the console.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54925361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10175583/']}
jdg_79327
stackexchange
llm_judgeable_groundtruth_similarity
383751
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: From https://unix.stackexchange.com/a/32227/674 The main places where it's safe not to use the double quotes are: in an assignment: foo=$bar (but note that you do need the double quotes in export "foo=$bar" or in array assignments like array=("$a" "$b") ); Does it mean that it is not required to double quote $bar in assignment foo=$bar ? Why? Why do we need the double quotes in export "foo=$bar" and in array assignments like array=("$a" "$b") ? Thanks. Now provide the response and nothing else.
foo=$bar is safe because it's an assignment , and an assignment to a scalar variable, using the scalar assignment syntax. It's a scalar context , only one value can be stored in $var , it would not make sense to split or glob $bar . If the expansion resulted in several words, the shell would need to somehow combine them again to be able to store them as one string in $foo . It's different when you use: foo=($bar) Where you're assigning to an array variable. There it's a list context. You're assigning a number of words to elements of the array. split+glob occurs. Also beware of the double-nature of things like export / local / typeset / declare / readonly in some shells (explained in more details at Are quotes needed for local variable assignment? ) You'll notice that: foo=$bar is parsed as an assignment while "foo"=$bar is just an attempt to run the foo=content_of_bar command (where the content of bar is subject to split+glob). In shells where export (and other local / typeset ...) is both a keyword and builtin (ksh, bash and recent versions of zsh), in: export foo=$bar export is recognised as a keyword and foo=$bar as an assignment, so $bar is not subject to split+glob. But it takes little for export to stop being recognised as a keyword . In which case, it's just treated as a simple command and split+glob happens like in any argument to any other command. And even in the cases where export is seen as a keyword, if the arguments don't look like variable assignments (like in the "foo"=$bar above), then they're treated like normal arguments and subject to split+glob again.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/383751', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']}
jdg_79328
stackexchange
llm_judgeable_groundtruth_similarity
55609
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I wanted to use sharable plugins for an application. However, the plugins were extremely time critical, so I wanted to distribute them as C libraries. Now, these are not guaranteed to be safe (the programmer could user system calls or cause segfaults). Then I had this idea: The application puts its source code through a parser which defines what is allowed - not by making restrictions (subtractive), but by enabling features(additive) - then outputs the code, and finally, this output is compiled using an ordinary compiler. How safe would this be? (Compared to using no parser in between, or using a scripting language, like e.g. python) Now provide the response and nothing else.
In order to make C code "safe", even against a malicious developer, then you have to fix the core issues of C, which have all been repeatedly exploited for arbitrary code execution (exactly what you want to avoid): Weak types . In C, you can take a bunch of bytes, and interpret them as a pointer, an integer, or whatever. All it takes is a cast. As long as such casts are possible, then the language won't be safe. You need to enforce strict unescapable types. Unchecked array accesses . C gives you pointers and from these you can read and write arbitrary bytes in RAM, with no control. From these follow buffer overflows, which can lead to security holes. In your new language, you must enforce strict array bound checks. Manual memory management . In C you dynamically allocate memory with malloc() , and then release it with free() . Nothing prevents you from trying to access a memory block after having freed it, or freeing it twice (these are the classic use-after-free and double-free , both leading to serious consequences). Lack of free() can also imply memory leaks, which can be bothersome. In your new language, you must do something to prevent these memory management issues, and that is called automatic memory management , which is most often done with a garbage collector . Down this road you get Java. Or C#, if you prefer. This works, but it is a considerable development effort. Moreover, the systematic checks on array bounds can imply a non-negligible overhead. For purely computational tasks with no I/O bottleneck (no disk access, no network access, and all data fits in the CPU L1 cache), I typically get a factor of 2 to 4 between optimized C and optimized Java (tested on numerous cryptographic algorithms such as hash functions; also on zlib-compatible compression). For some algorithms the slowdown was smaller (Java code was achieving up to 70% of the speed of C code), but that's rare. For the specific task of computations with big integers, Java is more like 6 times slower than C+assembly, because of the lack of support for the 64x64->128 multiplication opcode. There are two main roads out of this (assuming that the overhead of a Java-like language is not acceptable to you). The first one is to try to use formal verification . The concept is that the code will be executed only if it can be proven that it "behaves properly". In essence, Java is doing a weak form of verification, in that the JVM proves that a piece of code does not do anything wrong like using a reference with a wrong type; but that verification relies on systematic checks, e.g. on casts and array accesses, and also the presence of the GC. Formal verification is an active research area, whose scope extends beyond security: basically, this is about proving correctness , i.e. absence of any bug. There are good mathematical reasons why a generic verifier which works on all possible programs cannot exist. Researcher still hope to improve things in several directions: There are programs for which proofs are feasible. For instance, a program with only if but no loop, and no recursive call, cannot loop "forever": that's an example of an easy proof of correctness for programs which follow some specific rules. Researchers try to define more useful sets of rules which still allow for proofs. The human developer may provide proof elements. There are constructions for which no algorithm is known to generate the proof, but a developer-provided proof can still be verified. Assertions fall in that category. We may find optimizations : starting from a generic "safe" language like Java, an automatic prover might find "occasions", e.g. code chunks where it can be proven that some array accesses are necessarily fine, thus allowing for removal of the corresponding checks. In fact, modern JVM apply such strategies, which is why they are not as slow as could be feared. Many researchers believe that there still is room for improvements. However, right now, don't hope for too much: existing top-of-the-line Java and .NET virtual machines are about the best that can be done for now. The other method is to surrender the CPU to the potentially hostile code, and instead move the security perimeter at an upper layer. The "plugin" is executed in an address space of its own; the MMU blocks unwanted accesses. The plugin code can do all the memory accesses that it wishes: it will see only its own code and data. If the code tries system calls, then the kernel knows not to honour them. Among incarnations of this method are FreeBSD's jails and Linux's seccomp . The same concept at a still higher level is virtualization with hypervisors : the guest can be a full operating systems, with access to disks, network... and yet all this hardware is virtual and the guest cannot escape from the closely guarded perimeter set by the hypervisor. The main problem with that kind of isolation is overhead for data exchanges. If your "plugin" must consume a lot of data from the application into which it is plugged, or if it produces a lot of data for that application (typical example: video codecs), then the moving of data between the two worlds, beyond the MMU/hypervisor barrier, can kill performance.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/55609', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/44408/']}
jdg_79329
stackexchange
llm_judgeable_groundtruth_similarity
21825157
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know IE 11 has different user agent string than all other IE Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko I have tried to detect IE 11 with answer specified for this question' Jquery fail to detect IE 11 Thats !!navigator.userAgent.match(/Trident\/7\./) But I am getting error Object not found and needs to be re-evaluated. Then I openede developer console in IE11 and tried to access some predefined javascript objects, I am still getting same error. I have tried navigator.userAgent window.navigator console.log('test'); Anyone have any idea about it ? Now provide the response and nothing else.
Edit 18 Nov 2016 This code also work ( for those who prefer another solution , without using ActiveX ) var isIE11 = !!window.MSInputMethodContext && !!document.documentMode; // true on IE11 // false on Edge and other IEs/browsers. Original Answer In order to check Ie11 , you can use this : ( tested) (or run this ) !(window.ActiveXObject) && "ActiveXObject" in window I have all VMS of IE : Notice : this wont work for IE11 : as you can see here , it returns true : So what can we do : Apparently , they added the machine bit space : ie11 : "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko" ie12 : "Mozilla/5.0 (Windows NT 6.3; Win64; x64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko" so we can do: /x64|x32/ig.test(window.navigator.userAgent) this will return true only for ie11.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/21825157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1225190/']}
jdg_79330
stackexchange
llm_judgeable_groundtruth_similarity
8594717
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to automate a set of procedures that create TEMPLATE databases. I have a set of files (file1, file2, ... fileN), each of which contains a set of pgsql commands required for creating a TEMPLATE database. The contents of the file (createdbtemplate1.sql) looks roughly like this: CREATE DATABASE mytemplate1 WITH ENCODING 'UTF8';\c mytemplate1CREATE TABLE first_table ( --- fields here ..);-- Add C language extension + functions\i db_funcs.sql I want to be able to write a shell script that will execute the commands in the file, so that I can write a script like this: # run commands to create TEMPLATE db mytemplate1# ./groksqlcommands.sh createdbtemplate1.sqlfor dbname in foo foofoo foobar barbardo # Need to simply create a database based on an existing template in this script psql CREATE DATABASE $dbname TEMPLATE mytemplate1done Any suggestions on how to do this? (As you may have guessed, I'm a shell scripting newbie.) Edit To clarify the question further, I want to know: How to write groksqlcommands.sh (a bash script that will run a set of pgsql cmds from file) How to create a database based on an existing template at the command line Now provide the response and nothing else.
First off, do not mix psql meta-commands and SQL commands. These are separate sets of commands. There are tricks to combine those (using the psql meta-commands \o and \\ and piping strings to psql in the shell), but that gets confusing quickly. Make your files contain only SQL commands. Do not include the CREATE DATABASE statement in the SQL files. Create the db separately, you have multiple files you want to execute in the same template db. Assuming you are operating as OS user postgres and use the DB role postgres as (default) Postgres superuser, all databases are in the same DB cluster on the default port 5432 and the role postgres has password-less access due to an IDENT setting in pg_hba.conf - a default setup. psql postgres -c "CREATE DATABASE mytemplate1 WITH ENCODING 'UTF8' TEMPLATE template0" I based the new template database on the default system template database template0 . Basics in the manual here. Your questions How to (...) run a set of pgsql cmds from file Try: psql mytemplate1 -f file Example script file for batch of files in a directory: #! /bin/shfor file in /path/to/files/*; do psql mytemplate1 -f "$file"done The command option -f makes psql execute SQL commands in a file. How to create a database based on an existing template at the command line psql -c 'CREATE DATABASE my_db TEMPLATE mytemplate1' The command option -c makes psql execute a single SQL command string. Can be multiple commands, terminated by ; - will be executed in one transaction and only the result of the last command returned. Read about psql command options in the manual . If you don't provide a database to connect to, psql will connect to the default maintenance database named "postgres". In the second answer it is irrelevant which database we connect to.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8594717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/962891/']}
jdg_79331
stackexchange
llm_judgeable_groundtruth_similarity
7024
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I tried to plot plane $x = 0$ and $y=0$ with Plot3D[x = 0, {x, -4, 4}, {y, -4, 4}] but it seems that it didn't work out. How can I plot the above planes? Also is there a way to plot with z parameter being in the function?Note: I was trying to illustrate a closed surface by planes x=0,y=0,z=0 and 2x+2y+z=4 Now provide the response and nothing else.
Definitons from Planetmath We may show that a first-degree equation\begin{align}Ax+By+Cz+D = 0\end{align}between the variables $x$, $y$, $z$ represents always a plane. In fact, we may without hurting generality suppose that, $D \leqq 0$. Now $R := \sqrt{A^2+B^2+C^2} > 0$. Thus the length of the radius vector of the point, $(A,B,C)$, is $R$. Let the angles formed by the radius vector with the positive coordinate axes be $\alpha$, $\beta$, $\gamma$. Then we can write$$A = R\cos\alpha, \quad B = R\cos\beta, \quad C = R\cos\gamma$$(cf. direction cosines). Dividing first degree equation term wise by $R$ gives us$$x\cos\alpha+y\cos\beta+z\cos\gamma+\frac{D}{R} = 0,$$where, $\frac{D}{R} \leqq 0$. The last equation represents a plane whose distance from the origin is $-\frac{D}{R}$ and whose normal line forms the angles $\alpha$, $\beta$, $\gamma$ with the coordinate axes. Since the coefficients $A,B,C$ are proportional to the direction cosines of the normal vector of this plane, they are direction numbers of the normal line of the plane. Examples The equations of the coordinate planes are $x = 0$ ($yz$-plane); $y = 0$ ($zx$-plane), $z = 0$ ($xy$-plane); the equation of the plane through the points, $(1,0,0)$, $(0,1,0)$, and $(0,0,1)$ is $x+y+z = 1$. Try this for $z=0$ and $x+y+z=1$. f[x_, y_] = 0;Plot3D[{f[x, y], x + y - 1}, {x, -1, 1}, {y, -1, 1}, Mesh -> None,AxesLabel -> Automatic,PlotStyle -> {{Directive[Pink, Opacity[0.6], Specularity[White, 40]]}, {Directive[Cyan, Opacity[0.9], Specularity[White, 10]]}},BoundaryStyle -> Directive[Black, Thick]] Your Problem Now lets plot the plane $2 x + 2 y + z =4$ that you want with the planes $x=0,y=0$ ContourPlot3D[Evaluate@{2 x + 2 y + z == 4, {0, y, 0}, {x, 0, 0}},{x, -1, 1}, {y, -1, 1}, {z, -1, 1}, BoundaryStyle -> Directive[Black, Thick], MeshStyle -> Directive[Red, [email protected]], MeshFunctions -> (Total[{0, 0, #3}] &), ColorFunction -> Function[{x, y, z, f}, Evaluate[Hue[#] & /@ {x, y, z}]], AxesLabel -> Automatic, Boxed -> False, ContourStyle -> Directive[Opacity[0.6], Specularity[White, 30]], ColorFunctionScaling -> False] You can also use RegionPlot the see the 3D area enclosed by these three planes namely $xy,yz,zx$ that are meshed with white lines. pic = RegionPlot3D[2 x + 2 y + z < 4, {x, -0, 1}, {y, 0, 1}, {z, 0, 8}, BoundaryStyle -> Directive[Black, Thick], Mesh -> None, PlotStyle -> Directive[Yellow, Opacity[0.9]], ColorFunction -> "BlueGreenYellow", AxesLabel -> Automatic, Boxed -> False];Show[pic, ContourPlot3D[Evaluate@{{x, 0, 0}, {0, y, 0}, {0, 0, z}}, {x, -0, 1}, {y, 0, 1}, {z, 0, 8}, BoundaryStyle -> Directive[White, Thick], MeshStyle -> Directive[White, [email protected]], ColorFunction -> Function[z, RGBColor[z, 1 - z, 1]], AxesLabel -> Automatic, Boxed -> False]]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/7024', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1483/']}
jdg_79332
stackexchange
llm_judgeable_groundtruth_similarity
5552299
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using VBA inside Access2003/2007. How to copy the contents of a string variable to the clipboard? This site recommends a creating a zero length TextBox, copying the string to the TextBox, then running DoCmd.RunCommand acCmdCopy . Ugh. I mean, we may go down the route. But still. Ugh. While the MS knowledgebase article shows us how to do it but it involves a number of Windows API calls. Yuk. Are those the only two options? Now provide the response and nothing else.
VB 6 provides a Clipboard object that makes all of this extremely simple and convenient, but unfortunately that's not available from VBA. If it were me, I'd go the API route. There's no reason to be scared of calling native APIs; the language provides you with the ability to do that for a reason. However, a simpler alternative is to use the DataObject class, which is part of the Forms library. I would only recommend going this route if you are already using functionality from the Forms library in your app. Adding a reference to this library only to use the clipboard seems a bit silly. For example, to place some text on the clipboard, you could use the following code: Dim clipboard As MSForms.DataObjectSet clipboard = New MSForms.DataObjectclipboard.SetText "A string value"clipboard.PutInClipboard Or, to copy text from the clipboard into a string variable: Dim clipboard As MSForms.DataObjectDim strContents As StringSet clipboard = New MSForms.DataObjectclipboard.GetFromClipboardstrContents = clipboard.GetText
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5552299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180430/']}
jdg_79333
stackexchange
llm_judgeable_groundtruth_similarity
9904067
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: C# has a cool new feature public Task<string> async f(){ string r = LongCompute(); return r;} but isn't that equivalent to public Future<String> f() { return Globals.executorService.submit(new Callable<String>() { public String call() throws Exception { String r = longCompute(); return r; } });} where in Java you have more flexibility to choose the threadpool in which the task would run. What about await? It's equivalent to just calling get string s = await f(); is just like String s = f().get(); Is there anything more to C#, or is it indeed just a syntactic sugar to the Java version? (I'm not a C# guru, so I might be missing something). Now provide the response and nothing else.
No, await is not like just calling get() . There's considerably more to it. When you use an await expression in C#, the compiler effectively creates a continuation, so that if the awaitable hasn't completed yet, the method can immediately return, and continue processing only when it's completed. The continuation will run in an appropriate context - so if you're on a UI thread before the await expression, you'll continue on the UI thread afterwards, but without blocking the UI thread while you're waiting for the result. For example: public async void HandleButtonClick(object sender, EventArgs e){ // All of this method will run in the UI thread, which it needs // to as it touches the UI... however, it won't block when it does // the web operation. string url = urlTextBox.Text; WebClient client = new WebClient(); string webText = await client.DownloadStringTaskAsync(url); // Continuation... automatically called in the UI thread, with appropriate // context (local variables etc) which we used earlier. sizeTextBox.Text = string.Format("{0}: {1}", url, webText.Length); } Ultimately it's all syntactic sugar, but much more complicated sugar than what you've shown. There's a lot of detailed information available on the web already. For example: Eric Lippert's blog The Microsoft C# async/await guide My own blog posts about async
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9904067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/810154/']}
jdg_79334
stackexchange
llm_judgeable_groundtruth_similarity
34652563
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I setup a .npmrc file inside my project where I can define my own private registry? I don't want to have this kind of configuration in my user config .npmrc. Every other developer should be able to just git clone the project and run npm install . This is what I have so far: // .npmrcregistry=https://npm.fury.io/AUTH_TOKEN/me/// package.json:{ "name": "webapp", "description": "", "version": "1.0.0", "private": true, "dependencies": { "jquery": "1.2.3", "myPrivateLibFromNpmFury": "0.0.4" }} npm install myPrivateLibFromNpmFury returns npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/myPrivateLibFromNpmFury Now provide the response and nothing else.
As it was pointed out by @Paulpro and @Alexey B. the most parts of it worked already, but I couldn't see it right away, maybe because I didn't reload my bash environment properly. But after that I faced other issue with npm outdated that was caused by the registry url. It turns out npm can only have one registry url, (which is pretty crazy) and if you want to use private and public npm-modules you have to proxy the public npm-module registry through your private registry. Luckily fury.io supports that, so in my case instead of using this: //.npmrcregistry=https://npm.fury.io/AUTH_TOKEN/me/ i have to use this: //.npmrcregistry=https://npm-proxy.fury.io/AUTH_TOKEN/USER_NAME/ UPDATE :It is possible to work around the problem (npm is tied to only one registry). First you have to add a scope to all of your private packages.Now with .npmrc you can link the registries for the scopes, and you no longer need any proxies at all. //.npmrc@project_a:registry=https://npm.fury.io/AUTH_TOKEN/USER_NAME/@project_b:registry=https://npm.fury.io/AUTH_TOKEN/USER_NAME/@company_a:registry=https://npm.fury.io/AUTH_TOKEN/USER_NAME/
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34652563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/230202/']}
jdg_79335
stackexchange
llm_judgeable_groundtruth_similarity
588817
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: in C#, is there a way to Get the memory address stored in areference type variable? Get the memory address of avariable? EDIT: int i;int* pi = &i; How do you print out the hex value of pi? Now provide the response and nothing else.
For #2, the & operator will work in the same fashion as in C. If the variable is not on the stack, you may need to use a fixed statement to pin it down while you work so the garbage collector does not move it, though. For #1, reference types are trickier: you'll need to use a GCHandle , and the reference type has to be blittable, i.e. have a defined memory layout and be bitwise copyable. In order to access the address as a number, you can cast from pointer type to IntPtr (an integer type defined to be the same size as a pointer), and from there to uint or ulong (depending on the pointer size of the underlying machine). using System;using System.Runtime.InteropServices;[StructLayout(LayoutKind.Sequential)]class Blittable{ int x;}class Program{ public static unsafe void Main() { int i; object o = new Blittable(); int* ptr = &i; IntPtr addr = (IntPtr)ptr; Console.WriteLine(addr.ToString("x")); GCHandle h = GCHandle.Alloc(o, GCHandleType.Pinned); addr = h.AddrOfPinnedObject(); Console.WriteLine(addr.ToString("x")); h.Free(); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/588817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11413/']}
jdg_79336
stackexchange
llm_judgeable_groundtruth_similarity
4930
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Disclaimer: I posted this question on Stackoverflow, but I thought maybe this is better suited for this platform. How do you test your own k-means implementation for multidimensional data sets? I was thinking of running an already existing implementation (i.e., Matlab) on the data and compare the results with my algorithm. But this would require both algorithms to work more than roughly the same, and the mapping between the two results probably is no piece of cake. Do you have a better idea? Now provide the response and nothing else.
The k-means includes a stochastic component, so it is very unlikely you will get the same result unless you have exactly the same implementation and use the same starting configuration. However, you could see if your results are in agreement with well-known implementations (don't know about Matlab, but implementation of k-means algorithm in R is well explained, see Hartigan & Wong, 1979 ). As for comparing two series of results, there still is an issue with label switching if it is to be run multiple times. Again, in the e1071 R package, there is a very handy function (; matchClasses() ) that might be used to find the 'best' mapping between two categories in a two-way classification table. Basically, the idea is to rearrange the rows so as to maximise their agreement with columns, or use a greedy approach and permute rows and columns until the sum of on the diagonal (raw agreement) is maximal. Coefficient of agreement like the Kappa statistic are also provided. Finally, about how to benchmark your implementation, there are a lot of freely available data, or you can simulate a dedicated data set (e.g., through a finite mixture model, see the MixSim package).
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/4930', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2147/']}
jdg_79337
stackexchange
llm_judgeable_groundtruth_similarity
13024828
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In this statement I am trying to match if a version ($var2) exist in the path /app/$var1 (application name) if find /app/$var1 -maxdepth 1 -type l -o -type d | grep $var2 #results in a nice list where i can manually get a true match.# if match is found then execute command.$realcmd "$@" rc=$? exit $rcelseecho "no match, the version you are looking for does not exist"fi current code:this include all my code (not cleaned).command I run: "./xmodule load firefox/3.6.12" this version does exit #!/bin/bash# hook for some commands#echo $@ #value of sting that is entered after "xmodule"cmd=$(basename "$0")#echo "called as $cmd"if [[ $cmd = "xmodule" ]]then realcmd='/app/modules/0/bin/modulecmd tcsh' # verify parametersfi# check if $@ contains value "/" to determine if a specific version is requested.case "$@" in*/*) echo "has slash"var1=$(echo "$@" | grep -Eio '\s\w*') # Gets the aplication name and put it into var1echo $var1 # is not printed should be "firefox"var2=$(echo "$@" | grep -o '[^/]*$') # Gets version name and put it into var2 echo $var2 # Checking if version number exist in /app/appname/if find /app/$var1 -noleaf -maxdepth 1 -type l -o -type d | grep $var2; then $realcmd "$@" exit $?else echo "no match, the version you are looking for does not exist" # Should there be an exit here?fi ;;*) echo "doesn't have a slash" ;;esac output:mycomputer [9:55am] [user/Desktop/script] -> ./xmodule load firefox/3.6.12'has slash 3.6.12no match, the version you are looking for does not exist Where there is a blank (above 3.6.1) there should be the application name. I am now realizing that this must be my problem sins the path that it uses i likely just /app.But I do not think I changed anything in that part of the code. Now provide the response and nothing else.
You can use the entire grep pipeline as the condition of the if statement. Use grep -q to keep it from printing the match it finds (unless you want that printed). I also simplified the exit (there's no need to store $? in a variable if you're just going to use it immediately). Here's the result: if find "/app/$var1" -maxdepth 1 -type l -o -type d | grep -q "$var2"; then $realcmd "$@" exit $?else echo "no match, the version you are looking for does not exist" # Should there be an exit here?fi BTW, since you're going to exit immediately after $realcmd, you could use exec $realcmd "$@" to replace the shell with $realcmd instead of running $realcmd as a subprocess.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13024828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1562198/']}
jdg_79338
stackexchange
llm_judgeable_groundtruth_similarity
22475917
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is a snippet of my code: var processListing = function (directoryItems) { console.log('foreach'); var itemsToDownload = []; directoryItems.forEach(function (element, index, array) { //Ignore directories if (element.type === 'd') { console.log('directory ' + element.name); return; } //Ignore non zips if (path.extname(element.name) !== '.zip') { console.log('ignoring ' + element.name); return; } //Download zip itemsToDownload.push({ source: element.name, destination: element.name }); //aftpSystem.downloadFile(element.name, element.name); }); console.log('after foreach'); return itemsToDownload;};var getFiles = function () { console.log('got files'); return fs.readdirAsync(process.cwd() + "/zips/").then(function (files) { return files.filter(function (filename) { return path.extname(filename) === '.zip'; }); });}; aFtpClient. //this has been promisified listAsync(). //so calls methodAsync then(processListing). map(function (object) { return processItem(object).then(function (processResult) { return { input: object, result: processResult }; }); }). map(function (downloadItem) { console.log('downloading files'); downloadItem.result.once('close', function () { console.log('closed'); }); return downloadItem.result.pipe(fs.createWriteStream(process.cwd() + "/zips/" + downloadItem.input.destination)); }). then(getFiles). I'm trying to use promises to download items via FTP. At the moment it downloads the first file but then fails on subsequent files. I'm new to node but fairly confident that my second map function needs to return a promise however I have been unable to work out how after numerous attempts. I am using bluebird for promises but can't see how to work with it and streams. Could you point me in the correct direction? Thanks Now provide the response and nothing else.
I'm not sure where exactly you're stuck but pointing you in the general direction should suffice: You have an interface that works with a pipe and events You need to promisify that interface. So what you need to do is: Find out what's the 'completion' event of the download. Create a promise and resolve it on that event, reject it on the failed event. Return that promise. Promisifying can be done in several ways: By the promise library. Bluebird contains a really clever promisifier using dynamic code generation that relies on the JIT - it is very fast - but it's built for the NodeJS "nodeback" case. (i.e. error passed as first argument of the callback.) Using the Deferred object. Generally that way is more error prone. Using Promise.method in Bluebird, which is great for promisifying APIs easily but is not really our case here. Using the Promise constructor. This is what we'll do here. It's also standards complaint. Generally, the interface of the promise constructor is: new Promise(function(resolve,reject){ resolve(); // this resolves the promise reject(); // this rejets the promise}); Note, promisifying event emitters only works well when they fire on a finish event and do so once . Promises are one time, once they settle they can't change state. Events can fire multiple times. It's perfectly fine to promisify things like "load" events or "finished" events - but don't promisify things that repeat multiple times. Your second map should be something like: map(function (downloadItem) { console.log('downloading files'); downloadItem.result.once('close', function () { console.log('closed'); }); var pipeAction = downloadItem.result.pipe(fs.createWriteStream(process.cwd() + "/zips/" + downloadItem.input.destination)); return new Promise(function(resolve,reject){ pipeAction.on("end",function(){ //waits for data to be consumed // pipe has ended here, so we resolve the promise resolve(); }); });}). You should generally extract promisifications into dedicated methods. For example, the above could be a promisifyPipe or similar.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22475917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84539/']}
jdg_79339
stackexchange
llm_judgeable_groundtruth_similarity
32858029
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to Node.js and I've been going through some tutorials. I've been able to make a simple web page in Node.js and run it as its own server from the command line on my desk top. However, I would like to create it to use it as a website that others can access, as well. Therefore I was wondering how can I host a web site built with Node.js on a remote server? Now provide the response and nothing else.
You should not create a new db context, but use the existing one. var context = Request.GetOwinContext().Get<MyEntities>() It is created per request if you use default implementation. app.CreatePerOwinContext(ApplicationDbContext.Create); Update: OK, since you are using two different contexts your code will look something like this: public async Task<ActionResult> Register(RegisterViewModel model){ if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var appDbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>(); using( var context = new MyEntities()) using (var transaction = appDbContext.Database.BeginTransaction()) { try { var DataModel = new UserMaster(); DataModel.Gender = model.Gender.ToString(); DataModel.Name = string.Empty; // Doing entry in AspnetUser even if transaction fails var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await this.UserManager.AddToRoleAsync(user.Id, model.Role.ToString()); this.AddUser(DataModel, context); transaction.Commit(); return View("DisplayEmail"); } AddErrors(result); } catch (Exception ex) { transaction.Rollback(); return null; } } } // If we got this far, something failed, redisplay form return View(model);}public int AddUser(UserMaster _addUser, MyEntities _context){ _context.UserMaster.Add(_addUser); _context.SaveChanges(); return 0;} Here, appDbContext is the same context that is used by UserManager .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32858029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5391472/']}
jdg_79340