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 | 50804427 |
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 add a new column with some values in my dataframe using pandas and have it repeat the same values until it reaches the end of the index: I have tried: df['Fruit Type']=['Bananas','Oranges','Strawberries'] it says: ValueError: length of values does not match length of index **My index is about 8000 rows long, so there is a mismatch between index and the number of new column values I want the column to look like: Fruit Type:BananasOrangesStrawberriesBananasOrangesStrawberriesBananasOrangesStrawberries I found a solution after a while: df.insert(0, 'Fruit Type', ['Bananas', 'Oranges','Strawberries']*int(((len(df))/3))) The 0 stands for column number, followed by column name, then column values. The *int...takes the index divided by 3 and repeats the values for that amount. Thanks to @acai for the multiplier at the end
Now provide the response and nothing else.
| Method 1: Let's say your dataframe were 10 elements long (and you want to repeat your list of 3 fruits). >>> df column_a0 a1 b2 c3 d4 f5 e6 x7 s8 n9 i Using itertools.cycle , you can turn your list into an iterator and cycle through it until the end of the dataframe: from itertools import cyclefruits = cycle(['Bananas','Oranges','Strawberries'])df['Fruit_Type'] = [next(fruits) for fruit in range(len(df))]>>> df column_a Fruit_Type0 a Bananas1 b Oranges2 c Strawberries3 d Bananas4 f Oranges5 e Strawberries6 x Bananas7 s Oranges8 n Strawberries9 i Bananas Method 2 Here is an ugly hack that you can use as an alternative: You can use pandas.np.tile (which is a wrapper for numpy.tile ) to repeat your list however many times is necessary (using the // operator), and then just add the list up to the n th element necessary to fill the dataframe: fruits = ['Bananas','Oranges','Strawberries']df['Fruit Type']= pd.np.tile(fruits, len(df) // len(fruits)).tolist() + fruits[:len(df)%len(fruits)]>>> df column_a Fruit Type0 a Bananas1 b Oranges2 c Strawberries3 d Bananas4 f Oranges5 e Strawberries6 x Bananas7 s Oranges8 n Strawberries9 i Bananas | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50804427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9779206/']} | jdg_72841 |
stackexchange | llm_judgeable_groundtruth_similarity | 12438209 |
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 added a button inside a notification but I don't know how to have it call a function when it's clicked. I tried an approach like this https://code.google.com/p/languagepickerwidget/source/browse/trunk/trunk/src/org/gnvo/langpicker/LangPicker.java since it's also using a RemoteViews object but nothing happens when I click the button. This is what I currently have: private void createNotification(){ String ns = Context.NOTIFICATION_SERVICE; NotificationManager notificationManager = (NotificationManager) getSystemService(ns); Notification notification = new Notification(R.drawable.ic_launcher, null, System.currentTimeMillis()); RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification_switch); //the intent that is started when the notification is clicked (works) Intent notificationIntent = new Intent(this, SettingsActivity.class); PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.contentView = notificationView; notification.contentIntent = pendingNotificationIntent; notification.flags |= Notification.FLAG_NO_CLEAR; //this is the intent that is supposed to be called when the button is clicked Intent switchIntent = new Intent(this, switchButtonListener.class); PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0); notificationView.setOnClickPendingIntent(R.id.buttonswitch, pendingSwitchIntent); notificationManager.notify(1, notification);}public static class switchButtonListener extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("TAG", "test"); }} I can start an activity with the button but I didn't succeed to have it call a simple function. What would be the best way to do this? Edit: I found out that I had to register "switchButtonListener" in AndroidManifest.xml <receiver android:name="SettingsActivity$switchButtonListener" /> Source: Android Activity with no GUI It works now.
Now provide the response and nothing else.
| I found out that I had to register "switchButtonListener" in AndroidManifest.xml <receiver android:name="SettingsActivity$switchButtonListener" /> Source: Android Activity with no GUI Later I found out that I can also use code like this to achieve the same thing without modifying the manifest. switchButtonListener = new SwitchButtonListener();registerReceiver(switchButtonListener, new IntentFilter(SWITCH_EVENT)); . public class switchButtonListener extends BroadcastReceiver {@Override public void onReceive(Context context, Intent intent) { Log.d("TAG", "test"); }} . Intent switchIntent = new Intent(LangService.SWITCH_EVENT);PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(context, 0, switchIntent, 0);notificationView.setOnClickPendingIntent(R.id.buttonswitch, pendingSwitchIntent); Note that this way I can declare the switchButtonListener class without the static attribute (if not static, it would crash in the previous example) giving me much more flexibility. Don't forget to call unregisterReceiver() later. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12438209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1673204/']} | jdg_72842 |
stackexchange | llm_judgeable_groundtruth_similarity | 45090808 |
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 not sure what the difference between an IntArray and an Array<Int> is in Kotlin and why I can't used them interchangeably: I know that IntArray translates to int[] when targeting the JVM , but what does Array<Int> translate to? Also, you can also have String[] or YourObject[] . Why Kotlin has classes of the type {primitive}Array when pretty much anything can be arranged into an array, not only primitives.
Now provide the response and nothing else.
| Array<Int> is an Integer[] under the hood, while IntArray is an int[] . That's it. This means that when you put an Int in an Array<Int> , it will always be boxed (specifically, with an Integer.valueOf() call). In the case of IntArray , no boxing will occur, because it translates to a Java primitive array. Other than the possible performance implications of the above, there's also convenience to consider. Primitive arrays can be left uninitialized and they will have default 0 values at all indexes. This is why IntArray and the rest of the primitive arrays have constructors that only take a size parameter: val arr = IntArray(10)println(arr.joinToString()) // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 In contrast, Array<T> doesn't have a constructor that only takes a size parameter: it needs valid, non-null T instances at all indexes to be in a valid state after creation. For Number types, this could be a default 0 , but there's no way to create default instances of an arbitrary type T . So when creating an Array<Int> , you can either use the constructor that takes an initializer function as well: val arr = Array<Int>(10) { index -> 0 } // full, verbose syntaxval arr = Array(10) { 0 } // concise version Or create an Array<Int?> to avoid having to initialize every value, but then you'll be later forced to deal with possible null values every time you read from the array. val arr = arrayOfNulls<Int>(10) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/45090808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1949554/']} | jdg_72843 |
stackexchange | llm_judgeable_groundtruth_similarity | 20660 |
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've noticed that there are a good number of sites (Google, Twitter, Wikipedia ) that are serving up every page over HTTPS . I can understand given that everyone is concerned over privacy now, but has there been some sort of best practice/impetus for this change? Perhaps it's one of those things that it's just easier to use, because you get certain guarantees out-of-the-box? It's been explained to me that it could be because of privacy concerns that were emphasized when the Firesheep Firefox plugin was released at Toorcon 12, but that was two years ago, and I seem to recall major sites making the switch to HTTPS-exclusive more recently.
Now provide the response and nothing else.
| HTTPS is the easiest solution to a large number of security problems: Every form of Man In The Middle attack is completely impractical over an HTTPS connection (you'd need to either break SSL or hack into a certificate authority). This includes protecting your users while they're on public wifi. If any page isn't secure, and a user clicks a "login" link (which is presumably HTTPS), an attacker could replace it with a link to an insecure version that steals passwords. The only secure way to do this is either to serve the whole site over HTTPS or make sure users pay attention to the URL bar. Only one of those two options is possible. Since all of your pages are secure, you don't need to think about which pages are secure and which ones aren't (user clicks login -> redirect to HTTPS version -> user logs in -> redirect back to HTTP -> user goes to their profile -> redirect to HTTPS...). Modern browsers give mixed content warnings if an HTTPS page contains insecure content (styles, scripts, images, etc.). Most browsers treat this kind of page as if it's not secure at all (showing the scary red URL box). The easiest way to make sure you never run into this problem is to just serve all of your content over HTTPS. If you're HTTPS-only, you can enable HTTP Strict Transport Security to further reduce vulnerability to MITM attacks (once a user has been to your site once, their browser will always choose the HTTPS version, even if directed to a http:// URL). Honestly, I don't know why anyone doesn't enable HTTPS. It's completely trivial and it can be free . | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/20660', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/6433/']} | jdg_72844 |
stackexchange | llm_judgeable_groundtruth_similarity | 38601440 |
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 looking at the WSGI specification and I'm trying to figure out how servers like uWSGI fit into the picture. I understand the point of the WSGI spec is to separate web servers like nginx from web applications like something you'd write using Flask . What I don't understand is what uWSGI is for. Why can't nginx directly call my Flask application? Can't flask speak WSGI directly to it? Why does uWSGI need to get in between them? There are two sides in the WSGI spec: the server and the web app. Which side is uWSGI on?
Now provide the response and nothing else.
| Okay, I think I get this now. Why can't nginx directly call my Flask application? Because nginx doesn't support the WSGI spec. Technically nginx could implement the WSGI spec if they wanted, they just haven't. That being the case, we need a web server that does implement the spec, which is what the uWSGI server is for. Note that uWSGI is a full fledged http server that can and does work well on its own. I've used it in this capacity several times and it works great. If you need super high throughput for static content, then you have the option of sticking nginx in front of your uWSGI server. When you do, they will communicate over a low level protocol known as uwsgi . "What the what?! Another thing called uwsgi?!" you ask. Yeah, it's confusing. When you reference uWSGI you are talking about an http server. When you talk about uwsgi (all lowercase) you are talking about a binary protocol that the uWSGI server uses to talk to other servers like nginx . They picked a bad name on this one. For anyone who is interested, I wrote a blog article about it with more specifics, a bit of history, and some examples. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/38601440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1334007/']} | jdg_72845 |
stackexchange | llm_judgeable_groundtruth_similarity | 19203928 |
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: try{ class MyException extends Exception{} try{ throw new MyException; } catch(Exception $e){ echo "1:"; throw $e; } catch(MyException $e){ echo "2:"; throw $e; }}catch(Exception $e){ echo get_class($e);} I am confused with this try and catch. I am expecting a 2:MyException result because of the second try throw MyException . But the actual result is 1:MyException . What is the explanation?
Now provide the response and nothing else.
| MyException extends Exception , so Exception is more general than MyException , and the first catch block will catch it. If you want to catch MyException you need to reverse the order of the catch blocks: class MyException extends Exception{}try { try { throw new MyException; } catch(MyException $e){ echo "2:"; throw $e; } catch(Exception $e){ echo "1:"; throw $e; }}catch(Exception $e){echo get_class($e);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19203928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1642129/']} | jdg_72846 |
stackexchange | llm_judgeable_groundtruth_similarity | 2443239 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
(note that this question is not about CAS, it's about the "May fail spuriously" Javadoc). The only difference in the Javadoc between these two methods from the AtomicInteger class is that the weakCompareAndSet contains the comment: "May fail spuriously" . Now unless my eyes are cheated by some spell, both method do look to be doing exactly the same: public final boolean compareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update);}/* ... * May fail spuriously. */public final boolean weakCompareAndSet(int expect, int update) { return unsafe.compareAndSwapInt(this, valueOffset, expect, update);} So I realize that "May" doesn't mean "Must" but then why don't we all start adding this to our codebase: public void doIt() { a();}/** * May fail spuriously */public void weakDoIt() { a();} I'm really confused with that weakCompareAndSet() that appears to do the same as the compareAndSet() yet that "may fail spuriously" while the other can't. Apparently the "weak" and the "spurious fail" are in a way related to "happens-before" ordering but I'm still very confused by these two AtomicInteger (and AtomicLong etc.) methods: because apparently they call exactly the same unsafe.compareAndSwapInt method . I'm particularly confused in that AtomicInteger got introduced in Java 1.5, so after the Java Memory Model change (so it is obviously not something that could "fail spuriously in 1.4" but whose behavior changed to "shall not fail spuriously in 1.5" ).
Now provide the response and nothing else.
| There is a difference between implementation and specification... Whilst on a particular implementation there may not be much point in providing different implementations, future implementations perhaps on different hardware may want to. Whether this method carries its weight in the API is debatable. Also the weak methods do not have happens-before ordering defined. The non- weak versions behave like volatile fields. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2443239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257356/']} | jdg_72847 |
stackexchange | llm_judgeable_groundtruth_similarity | 21966607 |
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 void get10FirstLines(){ StreamReader sr = new StreamReader(path); String lines = ""; lines = sr.readLine();} How can I get the first 10 lines of the file in the string?
Now provide the response and nothing else.
| Rather than using StreamReader directly, use File.ReadLines which returns an IEnumerable<string> . You can then use LINQ: var first10Lines = File.ReadLines(path).Take(10).ToList(); The benefit of using File.ReadLines instead of File.ReadAllLines is that it only reads the lines you're interested in, instead of reading the whole file. On the other hand, it's only available in .NET 4+. It's easy to implement with an iterator block if you want it for .NET 3.5 though. The call to ToList() is there to force the query to be evaluated (i.e. actually read the data) so that it's read exactly once. Without the ToList call, if you tried to iterate over first10Lines more than once, it would read the file more than once (assuming it works at all; I seem to recall that File.ReadLines isn't implemented terribly cleanly in that respect). If you want the first 10 lines as a single string (e.g. with "\r\n" separating them) then you can use string.Join : var first10Lines = string.Join("\r\n", File.ReadLines(path).Take(10)); Obviously you can change the separator by changing the first argument in the call. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21966607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2891133/']} | jdg_72848 |
stackexchange | llm_judgeable_groundtruth_similarity | 4676223 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a simpler way than using ___ in object to check the existence of each level of an object to check the existence of a single member? More concisely: How can I check if someObject.member.member.member.value exists?
Now provide the response and nothing else.
| In general, you can use if(property in object) , but this would be still cumbersome for nested members. You could write a function: function test(obj, prop) { var parts = prop.split('.'); for(var i = 0, l = parts.length; i < l; i++) { var part = parts[i]; if(obj !== null && typeof obj === "object" && part in obj) { obj = obj[part]; } else { return false; } } return true;}test(someObject, 'member.member.member.value'); DEMO | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4676223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482489/']} | jdg_72849 |
stackexchange | llm_judgeable_groundtruth_similarity | 13556703 |
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 input arrays x and y of the same shape. I need to run each of their elements with matching indices through a function, then store the result at those indices in a third array z. What is the most pythonic way to accomplish this? Right now I have four four loops - I'm sure there is an easier way. x = [[2, 2, 2], [2, 2, 2], [2, 2, 2]]y = [[3, 3, 3], [3, 3, 3], [3, 3, 1]]def elementwise_function(element_1,element_2): return (element_1 + element_2)z = [[5, 5, 5], [5, 5, 5], [5, 5, 3]] I am getting confused since my function will only work on individual data pairs. I can't simply pass the x and y arrays to the function.
Now provide the response and nothing else.
| One "easier way" is to create a NumPy-aware function using numpy.vectorize . A "ufunc" is NumPy terminology for an elementwise function (see documentation here ). Using numpy.vectorize lets you use your element-by-element function to create your own ufunc, which works the same way as other NumPy ufuncs (like standard addition, etc.): the ufunc will accept arrays and it will apply your function to each pair of elements, it will do array shape broadcasting just like standard NumPy functions, etc. The documentation page has some usage examples that might be helpful. In [1]: import numpy as np ...: def myfunc(a, b): ...: "Return 1 if a>b, otherwise return 0" ...: if a > b: ...: return 1 ...: else: ...: return 0 ...: vfunc = np.vectorize(myfunc) ...: In [2]: vfunc([1, 2, 3, 4], [4, 3, 2, 1]) ...: Out[2]: array([0, 0, 1, 1])In [3]: vfunc([1, 2, 3, 4], 2) ...: Out[3]: array([0, 0, 1, 1]) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13556703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1764386/']} | jdg_72850 |
stackexchange | llm_judgeable_groundtruth_similarity | 47023 |
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to merge duplicate column and sum their value? What I have A 30A 40B 50 What I need A 70B 50 DF for this example d = {'address': ["A", "A", "B"], 'balances': [30, 40, 50]}df = pd.DataFrame(data=d)df
Now provide the response and nothing else.
| You may use df2 = df.groupby(['address']).sum() or df2 = df.groupby(['address']).agg('sum') If there are columns other than balances that you want to peak only the first or max value, or do mean instead of sum , you can go as follows: d = {'address': ["A", "A", "B"], 'balances': [30, 40, 50], 'sessions': [2, 3, 4]} df = pd.DataFrame(data=d) df2 = df.groupby(['address']).agg({'balances': 'sum', 'sessions': 'mean'}) That outputs balances sessionsaddress A 70 2.5 B 50 4.0 You may add as_index = False to groupby arguments to have: address balances sessions0 A 70 2.51 B 50 4.0 | {} | {'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/47023', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/69233/']} | jdg_72851 |
stackexchange | llm_judgeable_groundtruth_similarity | 4223826 |
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:
$$\lim_{x \to \frac{\pi}{2}} \biggl|\frac{1}{(1+\sin x)\log(\sin x)}+\frac{1}{\cos^2x} \biggl| $$ My Approach: $$\lim_{x \to \frac{\pi}{2}} \biggl|\frac{1}{(1+\sin x)\log(\sin x)}+\frac{1}{(1-\sin x)(1+\sin x)} \biggl|$$ $$\lim_{x \to \frac{\pi}{2}} \frac{1}{2}\biggl|\frac{1}{\log(\sin x)}+\frac{1}{(1-\sin x)} \biggl| $$ $$\lim_{x \to \frac{\pi}{2}} \frac{1}{2}\biggl|\frac{(\sin x - 1)}{(\sin x-1)\log(1+(\sin x - 1))}+\frac{1}{(1-\sin x)} \biggl|$$ I could not processed further. By Applying L'Hôpital's Rule I get answer $0$ but given answer is $\frac{1}{4}$ Also L'Hôpital's Rule is going lengthy.
Now provide the response and nothing else.
| Let me use $\ln$ in place of $\log$ and get from your third line $$\frac{1}{\ln(\sin x)}+\frac{1}{(1-\sin x)} =\frac{1-\sin x+\ln(\sin x)}{(1-\sin x)\ln(\sin x)} = \\=\frac{1-\sin x+\sin x -1+(\sin x-1)^2\frac{1}{2}-(\sin x - 1)^3\frac{1}{3}+\cdots}{-(\sin x - 1)^2}\to -\frac{1}{2}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4223826', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/263092/']} | jdg_72852 |
stackexchange | llm_judgeable_groundtruth_similarity | 16234669 |
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 between set(String) and setValue(String) in the SimpleStringProperty class? I know that set(String) is derived from StringPropertyBase , but this makes me even more wonder, why there additionally is setValue(String) ?
Now provide the response and nothing else.
| set/setValue and get/getValue methods pairs exist to align Object properties with primitive types properties like BooleanProperty or DoubleProperty : BooleanProperty: void set(boolean value)void setValue(java.lang.Boolean v) DoubleProperty: void set(double value)void setValue(java.lang.Number v) In these property classes ___Value methods work with corresponding to type objects while direct methods work with primitive types. Looking in the code you may find a bit of a difference in the logic. For example, DoubleProperty#setValue(null) is equal to DoubleProperty#set(0.0) (which was required by binding). So generally I'd advise to use set/get methods and leave setValue/getValue to binding needs as they may incorporate additional logic. For Object/String properties there is no difference between set and setValue methods. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16234669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298288/']} | jdg_72853 |
stackexchange | llm_judgeable_groundtruth_similarity | 31615 |
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:
Given a list of real numbers, I need to write a function that returns the value of the first element in the list that differs from the mean of the previous $N$ elements by greater than $P$ standard deviations of those same elements. (I use mean and standard deviation as sample functions, I may decide to use something else.) Clearly, I can write a loop to do this, but I'd like to use functional programming techniques to do this, and continue to learn better Mathematica programming style. Select[ ] looked promising, but I see no way to involve the previous list elements in the selection criterion. Thanks in advance for your help!Tom
Now provide the response and nothing else.
| Here's an attempt (without select) lst = {1, 2, 2, 1, 2, 5, 2, 4};n = 4;p = 1;Flatten[If[Abs[Take[#, -1] - Mean[Drop[#, -1]]][[1]] > p *StandardDeviation[Drop[#, -1]], Take[#, -1], {}] & /@ Partition[lst, n + 1, 1, 1]] // First Alternatively with Select. Select[Partition[lst, n + 1, 1, 1], Abs[Take[#, -1] - Mean[Drop[#, -1]]][[1]] > p*StandardDeviation[Drop[#, -1]] &] // First // Last For a more efficient implementation - see Mr Wizard's answer | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/31615', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2052/']} | jdg_72854 |
stackexchange | llm_judgeable_groundtruth_similarity | 1554181 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently i have attended an interview . A code snippet is given to me.I know,the interviewer took it from albhari's threading sample. public static void Main() { try { new Thread (Go).Start(); } catch (Exception ex) { // We'll never get here! Console.WriteLine ("Exception!"); }}static void Go() { throw null; } The modification of the above code as public static void Main(){ new Thread (Go).Start();}static void Go() { try { ... throw null; // this exception will get caught below ... } catch (Exception ex) { Typically log the exception, and/or signal another thread that we've come unstuck ... }} would be the good candidate to handle the exception. I have been asked, "Except the above trail what are the other alternatives would fit as good solution?. It was hard to find the alternative,so i raise it here to gather your suggestion.
Now provide the response and nothing else.
| Exception thrown in a thread normally couldn't be caught in another thread. You'd better to catch it in function Go and pass it to main thread explicitly. However, if you just want to log all unhandled messages from all threads, you may use AppDomain.UnhandledException event or equivalent events at Application class if you are developing WinForms or WPF app. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1554181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184805/']} | jdg_72855 |
stackexchange | llm_judgeable_groundtruth_similarity | 115150 |
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:
I always thought that high voltage power lines would attract a lightning strike more than other structures in the same area. Turns out I was wrong. My neighbor's chimney got struck by lightning and it destroyed a lot of stuff (street lamps, wifi APs, small home electronics). We live very close to high voltage power lines - so, is my premise wrong? Do power lines not attract a lightning strike more that other objects? Also, if a chimney isn't connected to the power grid (or am I wrong?), then how is it possible, that almost all of the street lamps don't work and other electronic devices were destroyed?
Now provide the response and nothing else.
| A few things I can think of straight away: Power line pylons are usually the tallest objects in the countryside. They are giant grounded metal objects. As lightning wants to move along the path of least resistance, they are preferred over other objects. Power lines also usually have one or two grounded wires on top, which act as lightning rods which protect the powered conductors from most lightning strikes. High voltage lines ionize the air around the conductors, this is especially true for 220kV+ lines (they even glow purple in a dark night, the glow comes from something called corona discharges). Ionized air is a better conductor than ordinary air. The voltage(potential) difference between a power line and a storm cloud can be significantly lower than the difference between storm cloud and ground. The maximum difference for a 220kV line can the peak voltage, which is $220kV\sqrt{2}$, while the ground is at $0V$. Lightning strikes usually overcome a few hundred to more than a thousand $kV$. Therefore lightning only has to overcome 2/3 of the usual voltage difference. Lightning can kill you even if you are not struck by it. Like dropping a stone in a pond, the voltage is spread out around the place of the strike, falling off with distance. If both your feet are one meter apart and in line with the strike point, you will experience a voltage difference between your legs. Animals like cows and horses are susceptible to this, as the distance between fore- and aft legs is significant. Electromagnetic influence is the last factor. A charged cloud attracts a charge of the opposite sign on the ground, this affects a large area. When the final discharge(lightning) occurs, the charge that was bound at this location won't have anything holding it there. Therefore it will move back to where it came from creating currents on the way. This can damage power lines and electrical equipment. This could be interpreted as an EMP-like effect. I hope that I didn't miss anything. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/115150', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/47604/']} | jdg_72856 |
stackexchange | llm_judgeable_groundtruth_similarity | 29678675 |
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 the new Android Design Guidelines for the Floating Action Button, it should be reasonable to transform the Floating Action Button into a Toolbar . Are there any samples / examples to perform such a transformation?
Now provide the response and nothing else.
| To use reveal animation you need add a onLayoutChange listener to the view in onCreateView callback like this: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment final View view = inflater.inflate(R.layout.fragment_map_list, container, false); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { v.removeOnLayoutChangeListener(this); revealView(view); } }); } return view; } where the revealView() method will be: private void revealView(View view) { toolbar = view.findViewById(R.id.mytoolbar); int cx = (view.getLeft() + view.getRight()) / 2; int cy = (view.getTop() + view.getBottom()) / 2; float radius = Math.max(infoContainer.getWidth(), infoContainer.getHeight()) * 2.0f; if (infoContainer.getVisibility() == View.INVISIBLE) { infoContainer.setVisibility(View.VISIBLE); ViewAnimationUtils.createCircularReveal(infoContainer, cx, cy, 0, radius).start(); } else { Animator reveal = ViewAnimationUtils.createCircularReveal( infoContainer, cx, cy, radius, 0); reveal.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { toolbar.setVisibility(View.INVISIBLE); } }); reveal.start(); }} In this way you should be able to create your animation. This is the way to use it. Just apply this at your fab onClick() method | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29678675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/503508/']} | jdg_72857 |
stackexchange | llm_judgeable_groundtruth_similarity | 147646 |
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 comes from Jacobson's Basic Algebra I, Exercise 4 of Section 1.4, found on page 42. I don't understand the following problem. For a given binary composition define a simple product of the sequence of elements $a_1,a_2,\dots,a_n$ inductively as either $a_1u$ where $u$ is a simple product of $a_2,\dots,a_n$ or as $va_n$ where $v$ is a simple product of $a_1,\dots,a_{n-1}$. Show that any product of $\geq 2^r$ elements can be written as a simple product of $r$ elements (which are themselves products). I thought about approaching this by induction on $r$. But then for $r=1$, it seems to ask that any product of $\geq 2$ elements can be written as a simple product of $1$ element, which sounds unusual to me. The inductive definition given doesn't make sense to me, is there a better way to approach this problem?
Now provide the response and nothing else.
| None of them is incorrect; they are all correct within their magisteria. That's why we talk about " group isomorphism", " order isomorphism", " field isomorphism", etc. We omit the specific kind when it is understood from context. Asking which is "correct" and which is "incorrect" is like asking which of the many "Jones" in the telephone directory is "the real Jones", and which ones are impostors. And just like a particular surname may be common, if in your place of work there is only one person with that surname, they may be refered to as "Jones" without fear of confusion. When you are working with groups, you are interested in group homomorphisms and group isomorphisms. When you are working with semigroups, you are interested in semigroup homomorphisms and semigroup isomorphisms. When you are working with ordered sets, yo uare interested in order homomorphisms and order isomorphisms. Etc. The reason that an isomorphism corresponds to the "essentially the same object" idea is that a bijection works like a "relabeling" of the objects. Consider the act of translating numbers from English to Spanish. Addition of numbers should not depend on which language we are speaking, in the sense that since "two" corresponds to dos , and "three" corresponds to tres , we should expect "five" (which is "two" plus "three") to corrrespond to whatever dos mas tres (namely, cinco ) corresponds. The properties that the numbers and addition of numbers have do not depend on what we call the numbers, but rather on the properties of the numbers. So, numbers-under-addition is "essentially the same, except for the names we use" as números-bajo-suma. An isomorphism is the way of saying that the only differences between the two objects, as far as the particular structure we are interested about is concerned are the "names" we give to the objects and the operations. Your example deals with a very specific construction of $\mathbb{Z}$ in terms of $\mathbb{N}$. The identification is in fact an identification that carries a lot of properties; it is a bijection that respects (i) order; (ii) addition; (iii) multiplication; and (iv) any derived operation from these. There are other ways of defining $\mathbb{Z}$ that do include $\mathbb{N}$ as a subset. The point of the isomorphism is that it does not matter how we construct $\mathbb{Z}$ and how we construct $\mathbb{N}$, in the end we have a set with certain properties, sitting inside another set that has further properties, and these properties are maintained regardless of how we constructed these objects. Correction: It is not quite correct that "homomorphism is the same as isomorphism but not necessarily a bijection". For example, in the case of "order homomorphism", the condition only requires that $a\leq b\implies f(a)\preceq f(b)$, and the converse is not required (though the converse is required for isomorphisms). It is a bit better to say that an isomorphism of partially ordered sets is a homomorphism that has an inverse that is also a homomorphism; this gives you the biconditional as a consequence, rather than as a premise, and it makes it fit into the general scheme better. (We do the same thing with topological spaces, where the concept of isomorphism is that of homeomorphism , which is a continuous map that has an inverse, and the inverse is also continuous. The definition works in the context of groups, rings, semigroups, fields, etc., but it turns out that in those cases, being a bijective homomorphism suffices to guarantee that the set-theoretic inverse is also a homomorphism.) As to homomorphisms vs. isomorphisms: There is a very fruitful philosophy that is that maps between objects are more important than objects. If you look at vector spaces, you can stare at particular vector spaces and get a lot of nice things, but vector spaces don't truly come into their own (in terms of power, applicability, usefulness, etc) until you introduce linear transformations (which are homomorphisms of vector spaces). Groups are ubiquitous, but it is homomorphisms between groups (which allow you to consider representations, group actions, and many other things) that make them impressively useful. The real numbers, as a metric space, is very nice; but it is continuous functions (homomorphisms of metric spaces/topological spaces) that are the cornerstone of their applicability to physics and other contexts. Homomorphism are "functions that play nice with the structure we are interested in." Functions are very useful, the structure may be very useful, and homomorphisms is a way of getting the best of both worlds: functions, and structure. Homomorphisms are more powerful than simply isomorphisms because isomorphisms don't really let us "change" the structure, it only let us change the names we give to the objects in the structure. It is homomorphisms that truly allow us to switch contexts. If you only allowed continuous bijections from $\mathbb{R}$ to $\mathbb{R}$ with continuous inverses (what an isomorphism of metric spaces is), you would get a lot of interesting stuff, but nowhere near what you get when you allow yourself to consider all continuous functions. This philosophy (concentrate on maps between objects, not on objects themselves) is at the very core of Category Theory (as Pete Clark mentions in the comments), and of modern takes on many subjects. Added. As Jackson Walters points out, I've downplayed the importance of isomorphisms above. One of the fundamental problems in almost every area of mathematics is "When are two objects that may look different actually the same ?" This is usually stated in terms of a "classification problem," and it usually comes down to asking whether there is an easy way to tell if there is an isomorphism between two given objects without having to explicitly look for one, or whether there is some "tractable" complete list of all objects of interest up to isomorphism. Examples of the former are the theorem that says that two vector spaces over the same field are isomorphic if and only if they have the same dimension. Examples of the latter are the "Fundamental Theorem of Finitely Generated Abelian Groups" (that tells you that every finitely generated abelian group is isomorphic to one with a particularly nice structure), and to a lesser extent the classification of finite simple groups (which tells you that there are some families plus a finite list that contains all finite simple groups). Isomorphisms are important, especially as a way of simplifying the study of objects by helping us look at what the things "are" instead of what they look like. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/147646', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24461/']} | jdg_72858 |
stackexchange | llm_judgeable_groundtruth_similarity | 637201 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to decommission two SSD disks from one of my Linux hosted servers. In order to safely delete data stored in the disks I was planning to use: hdparm --security-erase . I read this document and it suggested not having any disks connected to the host, other than the ones intended for deletion. And this article points out that if there are kernel or firmware bugs, this procedure might render the drive unusable or crash the computer it's running on . This server is currently in production, with a software RAID configuration for production disks. There is no RAID controller for the disks I need to remove. Question: Is this a rather safe operation to perform in a production environment, or would I be better served by removing the disks and performing this procedure in another host? Edit: just a link with a nice documented procedure
Now provide the response and nothing else.
| ATA Secure Erase is part of the ATA ANSI specification and when implemented correctly , wipes the entire contents of a drive at the hardware level instead of through software tools. Software tools over-write data on hard drives and SSDs, often through multiple passes; the problem with SSDs is that such software over-writing tools cannot access all the storage areas on an SSD, leaving behind blocks of data in the service regions of the drive (examples: Bad Blocks, reserved Wear-Leveling Blocks, etc.) When an ATA Secure Erase (SE) command is issued against a SSD’s built-in controller that properly supports it , the SSD controller resets all its storage cells as empty (releasing stored electrons) - thus restoring the SSD to factory default settings and write performance. When properly implemented, SE will process all storage regions including the protected service regions of the media. Liberally copied from http://www.kingston.com/us/community/articledetail?ArticleId=10 [via archive.org] , emphasis mine. The problem is, that according to some that both support and proper implementation of ATA Secure Erase by the manufacturers are "lacking". This research paper from 2011 shows on half the SSDs tested the ATA secure erase failed to effectively destroy the data on the drive. In that same research paper testing showed that maybe surprisingly to some, traditional multi-pass overwrites of the SSD were actually mostly successful, although still some data (possibly from those reserved area's of an SSD that are outside the disks reported size) could be recovered. So the short answer is: using software to sanitize a whole SSD may or may not be 100% effective. It may still be sufficient for your requirements though. Second, doing it on a server running production: My impression is that most manuals advise booting from a rescue disk to wipe disks for the simple reason that using software to wipe your boot/OS disk will fail miserably and most laptops and PC's have only a single disk. The universal risks of executing potentially (or rather intentional) destructive commands on production systems apply as well of course. Encrypting your drives will make (partial) recovery of data from disposed disks (SSD's or the spinning kind) much less likely. As long as the whole drive was encrypted and you didn't have an un-encrypted (swap) partition on it of course. Otherwise, these always the shredder . | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/637201', 'https://serverfault.com', 'https://serverfault.com/users/226840/']} | jdg_72859 |
stackexchange | llm_judgeable_groundtruth_similarity | 20210495 |
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 please let me be clear that I am a windows user and very new to the web world. For the past months I have been learning both python and django, and it has been a great experience for me. Now I have somehow created a small project that I would like to deploy in the production server. Since django has its built-in development server there was no problem for me. But now that I have to deploy it to a production server I googled around and found Nginx + uWSGI or Nginx + Gunicorn as the best option for it. And as uWSGI and Gunicord are incompatible with Windows, I think I should adapt Ubuntu or other Unix system. So my questions are: Just to be clear, as I will have to work with one of the above, please explain to me why do I need two servers? If I have to adapt the Ubuntu environment, do I have to learn Ubuntu shell scripting, SSH and other stuff? Or the hosting provider will help me do that? Please let me be aware of what else do I need for the above concerned. Thank you so much for your time and please pardon if my question was a lame question. Hoping for positive response answers.
Now provide the response and nothing else.
| A typical configuration involves two server processes (which can be run together on the same actual hardware or virtual server) so that the proxy server in front can buffer slow clients. For instance: a slow client will connect to nginx with a request. Nginx will pass the request on to Gunicorn and Gunicorn will respond. Nginx will then consume the Gunicorn response immediately, freeing up the Gunicorn resources right away. At that point, the slow client can take as much time as it wants to consume the response from Nginx without tying up much in the way of server resources. Alternatives to the two-server-process model are to use async workers with Gunicorn and put Gunicorn itself in front, or to use an async-sync combo like Waitress . Nginx in front has the added benefit of doubling as a ready-to-use statics server, though. Note that "slow clients" can describe: mobile phones that lose their connection and leave the TCP socket hanging until timeout mid-request; mobile phones that are just slow; unreliable connections of all types; hostile denial-of-service clients who are deliberately trying to use server resources; sometimes any old connection that has a hiccup or malfunction for any reason. So this is a problem that will affect nearly any site. You won't need shell scripting per se but getting used to Ubuntu will take some time. There is a lot to learn even outside of scripting, like how to use the package manager, how to configure packages once they're installed in ways that won't confound future updates, etc. And you will definitely have to learn to use SSH; it is one of the most fundamental server administration tools in the *nix world. An alternative to learning to use Ubuntu or another server platform is to use a Platform-as-a-Service option like Heroku, as PaaS hosting providers really will take care of all of that stuff for you. I recommend this approach. That having been said, even though I think PaaS is a good option for people who want to focus on development and not server admin regardless of their level of skill, it's also true that a little bit of experience with Linux server platforms goes a long way in helping you to understand the environment that your code runs in. So even if you go with PaaS, you would still benefit from tinkering with Ubuntu a little (or a lot). Another benefit from a PaaS is that normally their infrastructure handles the Nginx part of the deal (buffering of slow requests via proxy). This is the case with Heroku, for instance. So you won't have to worry about that part of the infrastructure at all. This part of the question is too broad to answer, but let me know in the comments if you need clarification. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20210495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3035160/']} | jdg_72860 |
stackexchange | llm_judgeable_groundtruth_similarity | 304389 |
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:
Processing text, I need to remove the newline character every two lines. Sample text: this is line oneand this is line twothe third and thefourth must be pasted too Desired output: this is line one and this is line twothe third and the fourth must be pasted too I tried a while loop, but a while loop is bad practice. Is it possible to do it using tr or any other command?
Now provide the response and nothing else.
| paste (also a standard POSIX simple utility like tr ) is your tool for that. Assuming you want those newline characters replaced with a space instead of just removed as in your sample: paste -d ' ' - - < file Or: paste -sd ' \n' file Replace ' ' with '\0' if you do indeed want them removed. To replace 2 out of 3: paste -sd ' \n' file 1 out of 3, starting with the second: paste -sd '\n \n' file And so on. Another good thing with paste is that it won't leave a line non-terminated. For instance, if you remove every newline in a file (as with tr -d '\n' < file or tr '\n' ' ' < file ), you end up with no line at all as lines need to be terminated with a newline character. So it's generally better to use paste instead for that (as in paste -sd '\0' file or paste -sd ' ' file ) which will add that trailing newline character necessary to have valid text. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/304389', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/163676/']} | jdg_72861 |
stackexchange | llm_judgeable_groundtruth_similarity | 2929666 |
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 CakePHP 1.2, I am trying produce a GROUP BY query: SELECT `categories`.*, COUNT(`entities`.id)FROM `categories` LEFT JOIN `entities` ON (`categories`.`id` = `entities`.`category_id`)GROUP BY `categories`.`id` How would/should I go about doing this? I am using 'Containable' if that helps.
Now provide the response and nothing else.
| This is what I eneded up with: $options = array( 'conditions' => $conditions, 'fields'=>array('Category.*','COUNT(`Entity`.`id`) as `entity_count`'), 'joins' => array('LEFT JOIN `entities` AS Entity ON `Entity`.`category_id` = `Category`.`id`'), 'group' => '`Category`.`id`', 'contain' => array('Domain' => array('fields' => array('title'))) ); return $this->find('all', $options); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2929666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123140/']} | jdg_72862 |
stackexchange | llm_judgeable_groundtruth_similarity | 104662 |
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:
How to quickly and clearly argue/show that there is or is not a linear surjective map $\phi$ $\phi: \mathbb{R} \to \mathbb{R}²$
Now provide the response and nothing else.
| Assuming you mean an $\mathbb{R}$-linear map, one can argue as follows: let $v = \varphi(1)$. Then for all $\alpha \in \mathbb{R}$, $\varphi(\alpha) = \varphi(\alpha \cdot 1) = \alpha \varphi(1) = \alpha v$. Thus the image of $\varphi$ consists of all scalar multiples of the vector $v$. This is the origin if $v = 0$ and a line through the origin otherwise. It is clearly not the entire plane: e.g., if $v = (x,y)$ is not zero, then $(-y,x)$ is not of the form $\alpha (x,y)$ for any $\alpha \in \mathbb{R}$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/104662', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24189/']} | jdg_72863 |
stackexchange | llm_judgeable_groundtruth_similarity | 42346498 |
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 used this tutorial to create my first docker webapi project. I'm using windows 7 (docker toolbox). This what I've ran: dotnet new webapi This is the Dockerfile: FROM microsoft/dotnet:latestCOPY . /appWORKDIR /appRUN ["dotnet", "restore"]RUN ["dotnet", "build"]EXPOSE 5000/tcpENV ASPNETCORE_URLS http://*:5000ENTRYPOINT ["dotnet", "run"] This is how I created the image: docker build -t mydemos:aspnetcorehelloworld . And this is how I've created and ran the container: docker run -d -p 8080:5000 -t mydemos:aspnetcorehelloworld My service ran successfully as a docker container. Then, I tried changing the Dockerfile to work on a aspnetcore base image: FROM microsoft/dotnet:latest was changed to FROM microsoft/aspnetcore:1.0.1 The new Dockerfile looks like: FROM microsoft/aspnetcore:1.0.1COPY . /appWORKDIR /appRUN ["dotnet", "restore"]RUN ["dotnet", "build"]EXPOSE 5000/tcpENV ASPNETCORE_URLS http://*:5000ENTRYPOINT ["dotnet", "run"] Now, I've tried to build the new image using docker build -t mydemos:aspnetcorehelloworld1 . And I get an error. This is the build log: Sending build context to Docker daemon 636.9 kBStep 1/8 : FROM microsoft/aspnetcore:1.0.1 ---> 2c7bbc508bb2Step 2/8 : COPY . /app ---> Using cache ---> 1d5b9bd908b3Step 3/8 : WORKDIR /app ---> Using cache ---> c1d5d091d111Step 4/8 : RUN dotnet restore ---> Running in 8399e21caeb2Did you mean to run dotnet SDK commands? Please install dotnet SDK from: http://go.microsoft.com/fwlink/?LinkID=798306&clcid=0x409The command 'dotnet restore' returned a non-zero code: 145 I went into the url, reinstalled stuff and I still get an error. I've tried to use the dotnet cli commands in the same command line session and I succeed ( dotnet restore works). I've tried to search this error around, but couldn't really find any solution. What am I missing here? I'm getting this 145 error on multiple occasions and tests.
Now provide the response and nothing else.
| The image you are using contains the .NET Core runtime only, not the SDK. Try a base image from the following repository: https://hub.docker.com/r/microsoft/aspnetcore-build/ Your Dockerfile has the following lines in it: RUN ["dotnet", "restore"]RUN ["dotnet", "build"] Which means that the dotnet restore and dotnet build commands are running within the image you're using. As the image you are using doesn't have the SDK installed, these commands cannot be found and fail as you're seeing. The images in the repository I linked above have the SDK installed within them and so the dotnet restore and dotnet build commands can be found and executed. The alternative to using a base image with the SDK installed would be to perform the build/publish process on your development machine and then simply copy the published output into the image. Your Dockerfile would then only need to look something along the lines of: FROM microsoft/aspnetcore:1.0.1WORKDIR /appCOPY ./app .ENTRYPOINT ["dotnet", "TheNameOfYourProject.dll"] Note that now the dotnet commands run within the image is simply the one that runs your (pre-built) DLL. This only requires the runtime, and not the SDK. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42346498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3213034/']} | jdg_72864 |
stackexchange | llm_judgeable_groundtruth_similarity | 23975019 |
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 often find myself writing something like this: var fields = _type.GetProperties() .Select(prop => new { Prop = prop, Attrib = prop.GetCustomAttribute<ColumnAttribute>() }) .Where(t => t.Attrib != null) .ToList(); Where I'm bothered is that I'm unnecessarily creating objects in the cases where the where clause fails. Granted the overhead is small, but I'd still prefer to save the allocation, as I would if I were simply looping over it or did the more painful: var fields = _type.GetProperties() .Select(prop => { var attrib = prop.GetCustomAttribute<ColumnAttribute>(); return attrib == null ? null : new {Prop = prop, Attrib = attrib}; }) .Where(t => t != null); Is there a better pattern/extension method I'm missing? Or is it possible that LINQ could make that optimization under the covers? Much appreciated! Update: I guess something like this is what I mean, but I'm expecting something equivalent already exists and I'm just searching poorly: public static IEnumerable<TResult> SelectWhereNotNull<TSource, TValue, TResult>(this IEnumerable<TSource> source, Func<TSource, TValue> valueSelector, Func<TSource, TValue, TResult> selector) where TValue:class where TResult:class{ return source .Select(s => { var val = valueSelector(s); if (val == null) { return null; } return selector(s, val); }) .Where(r => r != null);}var fields = _type.GetProperties() .SelectWhereNotNull(prop => prop.GetCustomAttribute<ColumnAttribute>(), Tuple.Create);
Now provide the response and nothing else.
| For the type of query you're performing, you can't really get around it. You will want to have a place to put that attribute somewhere. Whether you hide it in a separate method or operate on your result object, it has to be done. It would be counter productive to worry about it. But there are ways you can make it more readable. If you rewrote your query in the query syntax, you can hide the fact that it is being done var fields = from prop in _type.GetProperties() let attr = prop.GetCustomAttribute<ColumnAttribute>() where attr != null select new { Prop = prop, Attrib = attr, }; For this however, I would probably package it up in a generator. It doesn't need to be written in terms of LINQ, you'd be seriously limiting yourself if you try to. public static IEnumerable<TResult> SelectWhere<TSource, TValue, TResult>( this IEnumerable<TSource> source, Func<TSource, TValue> valueSelector, Func<TSource, TValue, bool> predicate, Func<TSource, TValue, TResult> resultSelector){ foreach (var item in source) { var value = valueSelector(item); if (predicate(item, value)) yield return resultSelector(item, value); }} Your query becomes this: var fields = _type.GetProperties() .SelectWhere( p => p.GetCustomAttribute<ColumnAttribute>(), (p, a) => a != null, (p, a) => new { Prop = p, Attrib = a } ) .ToList(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23975019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179166/']} | jdg_72865 |
stackexchange | llm_judgeable_groundtruth_similarity | 11081573 |
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 working with a library which exposes an interface to work with. One of the functions of this library is like this : template <int a>void modify(){} I have to modify parameters from 1 to 10 i.e. call modify with with template arguments from 1 to 10. For that I wrote this code (a basic version of code, actual code is much larger). for(int i=0; i<10; i++){ modify<i>();} On compilation I receive the following error error: 'i' cannot appear in constant-expression After going through some links on the internet, I came to know that I cannot pass any value as template argument which is not evaluated at compile time.My question are as follows:1. Why can't compiler evaluate i at compile time?2. Is there any other to achieve the objective I am trying to achieve without changing the API interface? There is another thing I want to do. Call modify as modify where VAR is the output of some functional computation. How can I do that?
Now provide the response and nothing else.
| What is the value of i (that is not a constant) at compile time? There is no way to answer unless executing the loop. But executing is not "compiling"Since there is no answer, the compiler cannot do that. Templates are not algorithm to be executed, but macros to be expanded to produce code.What you can do is rely on specialization to implement iteration by recursion, like here: #include <iostream>template<int i>void modify(){ std::cout << "modify<"<<i<<">"<< std::endl; }template<int x, int to>struct static_for{ void operator()() { modify<x>(); static_for<x+1,to>()(); }};template<int to>struct static_for<to,to>{ void operator()() {}};int main(){ static_for<0,10>()();} Note that, by doing this, you are, in fact, instantiating 10 functions named modify<0> ... modify<9> , called respectively by static_for<0,10>::operator() ... static_for<9,10>::operator() . The iteration ends because static_for<10,10> will be instantiated from the specialization that takes two identical values, that does nothing. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11081573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/765886/']} | jdg_72866 |
stackexchange | llm_judgeable_groundtruth_similarity | 45690368 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi I got a function which will update after a http request to the server. It seems that the console.log show that the value has been updated but the UI is not updating unless I click on any other component(ex. input). This is my function: fileTransfer.upload(this.created_image, upload_url, options).then((data) => { console.log("success:"+data.response); //This is showing correct response var obj = JSON.parse(data.response); this.sv_value = obj.value; console.log(this.sv_value); //This is showing correct value}, (err) => { console.log("failure:");}) This is my view html: <ion-row> <ion-col center width-100 no-padding> <h2>{{sv_value}}</h2> //This is not updated </ion-col> </ion-row> Is there any way I can tackle this issue? Thank you
Now provide the response and nothing else.
| Try placing this.sv_value = obj.value; inside NgZone.run(); to make Angular detect the change. import { Component, NgZone } from "@angular/core";...export class MyComponentPage { constructor( private zone: NgZone ... ){ } yourFunction(){ fileTransfer.upload(this.created_image, upload_url, options) .then((data) => { console.log("success:"+data.response); //This is showing correct response var obj = JSON.parse(data.response); this.zone.run(() => { this.sv_value = obj.value; }); console.log(this.value); //This is showing correct value }, (err) => { console.log("failure:"); }); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45690368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2007826/']} | jdg_72867 |
stackexchange | llm_judgeable_groundtruth_similarity | 2432817 |
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 $X$ and $Y$ be topological spaces and let $A \subseteq X$ be a subspace of $X$. Suppose $A$ is homeomorphic to some subspace $B \subseteq Y$ of $Y$. Let $f$ explicitly denote this homeomorphism. If $f : A \to B$ is a homeomorphism, does $f$ extend to a homeomorphism between $\text{Cl}_X(A)$ and $\text{Cl}_Y(B)$, i.e does there exist a $g : Cl_X(A) \to Cl_Y(B)$, such that $g|_{A} = f$. More generally if $A$ and $B$ are homeomorphic, does that imply that $Cl_X(A)$ and $Cl_Y(B)$ are homeomorphic? If $X$ and $Y$ are homeormorphic, then this is true, since it is a well known-theorem that $f[Cl_X(A)] = Cl_Y(f[A] = B)$, if $f : X \to Y$ is a homeomorphism. However I can't seem to come up with a counterexample for my question, since I assume the implication is false. Edit : I know a counterexample that comes from CW Complexes, where if $(X, \xi)$ is a CW-Complex, then $\xi$ is a collection of open cells $e$, which are topological spaces homeomorphic to $\mathbb{B}^n$ the open unit ball in $\mathbb{R}^n$. Each $e \subseteq X$ is a subspace of a haursdoff space $X$. Also a closed cell $\bar{e}$ is a topological space homeomorphic to the closed unit ball $\mathbb{\bar{B}}^n \subseteq \mathbb{R}^n$ Now in this example $Y = \mathbb{R}^n$. It is also known that for any $e \in \xi$, $Cl_X(e) \neq \bar{e} \cong {\mathbb{\bar{B}}^n} = Cl_Y(\mathbb{{B}}^n \cong e) $ Hence $e$ and $\mathbb{B}^n$ are homeomorphic, however $Cl_X(e)$ is not homeomorphic to $Cl_Y(\mathbb{B}^n) = \mathbb{\bar{B}}^n$, since $Cl_X(e) \neq \bar{e}$ But using the above example feels like bringing a gun to a knife fight, are there any simpler counterexamples?
Now provide the response and nothing else.
| $A=S^1\setminus \{p\} \subseteq X= S^1$ (for any $p \in S^1$) is homeomorphic to $B=(0,1) \subseteq Y = [0,1]$. But their respective closures $X$ and $Y$ are not. More trivially: $A = (0,1) \subseteq X=\mathbb{R}$ and $B = Y = \mathbb{R}$, where $\overline{B} = B$ but $\overline{A}$ becomes compact. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2432817', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/266135/']} | jdg_72868 |
stackexchange | llm_judgeable_groundtruth_similarity | 37621770 |
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 SUPER new to ruby, and I am trying to following instructions on how to build a rectangle. I am following along as carefully as possible, I triple checked I typed it correctly. I even retyped it. The problem seems to be in the end. My terminal keeps giving me the error: shapes.rb:25: syntax error, unexpected end-of-input, expecting keyword_end Can anyone help me? I think it might be an issue with the 1.upto, but i'm not sure. Thank you so much!! puts "Welcome to Shapes" print "How big do you want your shape? " shape_size = gets shape_size = shape_size.chomp print "Outside letter: " outside_letter = gets outside_letter = outside_letter.chomp print " Inside Letter: " inside_letter = gets inside_letter = inside_letter.chomp puts "About to draw a shape #{shape_size} big" puts "using #{outside_letter} for the edge" puts "and #{inside_letter} for the inside" width = shape_size height=shape_size 1.upto(height) do |row| if row==1 puts outside_letter * width elsif row==height puts outside_letter * width else middle= inside_letter * (width-2) puts "#{outside_letter}#{middle}#{outside_letter}" end
Now provide the response and nothing else.
| You need one more end : puts "Welcome to Shapes"print "How big do you want your shape? "shape_size = getsshape_size = shape_size.chompprint "Outside letter: "outside_letter = getsoutside_letter = outside_letter.chompprint " Inside Letter: "inside_letter = getsinside_letter = inside_letter.chompputs "About to draw a shape #{shape_size} big"puts "using #{outside_letter} for the edge"puts "and #{inside_letter} for the inside"width = shape_sizeheight=shape_size1.upto(height) do |row| if row==1 puts outside_letter * width elsif row==height puts outside_letter * width else middle= inside_letter * (width-2) puts "#{outside_letter}#{middle}#{outside_letter}" endend # <--- here Since you are learning here, I felt compelled to add more detail: When you have a block, such as the 1.upto(height) do |row| in your code, that will always require an end , as it is a block (think of it like a unit of code). Within that block, you are executing the code for each item within the enumerable (ex. array). In this case, your enumerable is an array of each whole number between 1 and the value of height : 2.3.0 :005 > 1.upto(4) do |number|2.3.0 :006 > puts "The number is: #{number}"2.3.0 :007?> endThe number is: 1The number is: 2The number is: 3The number is: 4 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37621770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5314186/']} | jdg_72869 |
stackexchange | llm_judgeable_groundtruth_similarity | 4216716 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Is there a conditional ternary operator in VB.NET? Is there a version of the shorthand If-Then-Else in C#: c = (a > b) ? a : b; meaning... if (a > b) { c = a; }else { c = b; } .. in VB.Net?
Now provide the response and nothing else.
| You want to use the If operator : Dim maximum = If(a > b, a, b) There's also the older Iif function , which still works, but If is superior, since it: performs type inference (if a and b are both integers, the return value will be an integer instead of an object) and short-cuts the operation (if a > b , only a is evaluated, and vice-versa) -- this is relevant if a or b is a function call. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4216716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/512334/']} | jdg_72870 |
stackexchange | llm_judgeable_groundtruth_similarity | 1039530 |
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 try to prove normal matrix is diagonalizable. I found that $A^*A$ is hermitian matrix. I know that hermitian matrix is diagonalizable. I can not go more. I want to prove statement use only this fact. I need you help. (professor said that we can prove only use this fact.
Now provide the response and nothing else.
| This Wikipedia article contains a sketch of a proof. It has three steps. If a normal matrix is upper triangular, then it's diagonal. (Proof: show the upper left corner is the only nonzero entry in that row/column using a matrix-norm argument; then use induction.) Details of proof: write $A$ as $Q T Q^{-1}$ for some unitary matrix Q, where $T$ is upper triangular. From $A A^{*} = A^{*} A$, conclude that $T T^{*} = T^{*} T$. Observe that the left hand side is the matrix whose $ij$ entry is $\langle t_i, t_j\rangle$, where $t_i$ is the $i$th column of $T$. The right hand side has an $ij$ entry that's $\langle s_i, s_j\rangle$, where $s_i$ is the $i$ the row. Considering $i = 1$, you can conclude that the norm of the first row is the same as the norm of the first column, so all the non-diagonal entries of that row must be zero. Now look at the $(2,2)$ entries of the two matrices: the second column has the form $(0, t_{2,2}, 0, \ldots, 0)$; the second row may have nonzero entries after the second. But the norms of these two vectors must be equal, so all those potentially nonzero entries must be zero. Continue in this vein until you've shown that all off-diagonal entries are zero. Show that every matrix is (unitarily) similar to an upper triangular one [that's called the Schur Decomposition], and that the similarity doesn't change "normality": if $A$ is similar to upper-triangular $T$, and $A$ is normal, then so is $T$. Conclude that a normal matrix is similar to an upper-triangular normal matrix, which is necessarily diagonal, by step 1, so you're done. I know that's not the proof you asked for, but as @lhf points out, your proposed proof goes via a route that doesn't require normality, so it can't possibly work. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1039530', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/148928/']} | jdg_72871 |
stackexchange | llm_judgeable_groundtruth_similarity | 29210176 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Sample program: public final class CollectorTest{ private CollectorTest() { } private static <T> BinaryOperator<T> nope() { return (t, u) -> { throw new UnsupportedOperationException("nope"); }; } public static void main(final String... args) { final Collector<Integer, ?, List<Integer>> c = Collector.of(ArrayList::new, List::add, nope()); IntStream.range(0, 10_000_000).boxed().collect(c); }} So, to simplify matters here, there is no final transformation, so the resulting code is quite simple. Now, IntStream.range() produces a sequential stream. I simply box the results into Integer s and then my contrived Collector collects them into a List<Integer> . Pretty simple. And no matter how many times I run this sample program, the UnsupportedOperationException never hits, which means my dummy combiner is never called. I kind of expected this, but then I have already misunderstood streams enough that I have to ask the question... Can a Collector 's combiner ever be called when the stream is guaranteed to be sequential?
Now provide the response and nothing else.
| A careful reading of the streams implementation code in ReduceOps.java reveals that the combine function is called only when a ReduceTask completes, and ReduceTask instances are used only when evaluating a pipeline in parallel. Thus, in the current implementation, the combiner is never called when evaluating a sequential pipeline. There is nothing in the specification that guarantees this, however. A Collector is an interface that makes requirements on its implementations, and there are no exemptions granted for sequential streams. Personally, I find it difficult to imagine why sequential pipeline evaluation might need to call the combiner, but someone with more imagination than me might find a clever use for it, and implement it. The specification allows for it, and even though today's implementation doesn't do it, you still have to think about it. This should not surprising. The design center of the streams API is to support parallel execution on an equal footing with sequential execution. Of course, it is possible for a program to observe whether it is being executed sequentially or in parallel. But the design of the API is to support a style of programming that allows either. If you're writing a collector and you find that it's impossible (or inconvenient, or difficult) to write an associative combiner function, leading you to want to restrict your stream to sequential execution, maybe this means you're heading in the wrong direction. It's time to step back a bit and think about approaching the problem a different way. A common reduction-style operation that doesn't require an associative combiner function is called fold-left . The main characteristic is that the fold function is applied strictly left-to-right, proceeding one at a time. I'm not aware of a way to parallelize fold-left. When people try to contort collectors the way we've been talking about, they're usually looking for something like fold-left. The Streams API doesn't have direct API support for this operation, but it's pretty easy to write. For example, suppose you want to reduce a list of strings using this operation: repeat the first string and then append the second. It's pretty easy to demonstrate that this operation isn't associative: List<String> list = Arrays.asList("a", "b", "c", "d", "e");System.out.println(list.stream() .collect(StringBuilder::new, (a, b) -> a.append(a.toString()).append(b), (a, b) -> a.append(a.toString()).append(b))); // BROKEN -- NOT ASSOCIATIVE Run sequentially, this produces the desired output: aabaabcaabaabcdaabaabcaabaabcde But when run in parallel, it might produce something like this: aabaabccdde Since it "works" sequentially, we could enforce this by calling sequential() and back this up by having the combiner throw an exception. In addition, the supplier must be called exactly once. There's no way to combine the intermediate results, so if the supplier is called twice, we're already in trouble. But since we "know" the supplier is called only once in sequential mode, most people don't worry about this. In fact, I've seen people write "suppliers" that return some existing object instead of creating a new one, in violation of the supplier contract. In this use of the 3-arg form of collect() , we have two out of the three functions breaking their contracts. Shouldn't this be telling us to do things a different way? The main work here is being done by the accumulator function. To accomplish a fold-style reduction, we can apply this function in a strict left-to-right order using forEachOrdered() . We have to do a bit of setup and finishing code before and after, but that's no problem: StringBuilder a = new StringBuilder();list.parallelStream() .forEachOrdered(b -> a.append(a.toString()).append(b));System.out.println(a.toString()); Naturally, this works fine in parallel, though the performance benefits of running in parallel may be somewhat negated by the ordering requirements of forEachOrdered() . In summary, if you find yourself wanting to do a mutable reduction but you're lacking an associative combiner function, leading you to restrict your stream to sequential execution, recast the problem as a fold-left operation and use forEachRemaining() on your accumulator function. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29210176', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1093528/']} | jdg_72872 |
stackexchange | llm_judgeable_groundtruth_similarity | 1877782 |
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:[-5,3]\to \mathbb{R}$ such that $f$ is differentiable, moreover $\int_{-5}^{-1}fdx=\int_{-1}^{3}fdx$ Prove: there is $x_0\in[-5,3]$ such that $f'(x_0)=0$ $f$ is differentiable $\Rightarrow$ continuous$\Rightarrow$ integrable, now, from the Mean Value Theorem for Integrals $\int_{-5}^{3}fdx=8\cdot f(c)$ I can not see how $\int_{-5}^{-1}fdx=\int_{-1}^{3}fdx$ can help me find that $f'(c)=0$
Now provide the response and nothing else.
| A small modification of your Mean Value Theorem for Integrals idea works. By the MVT for integrals, there is a $c$ strictly between $-5$ and $-1$ such that the first integral is $4f(c)$. Similarly, there is a $d$ between $-1$ and $3$ such that the second integral is $4f(d)$. But the two integrals are equal, so $f(c)=f(d)$. The result now follows from Rolle's Theorem. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1877782', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103441/']} | jdg_72873 |
stackexchange | llm_judgeable_groundtruth_similarity | 363534 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm configuring Windows 7 Professional x64 to run a custom application as the shell, in "kiosk" mode. That is, replacing the default shell ( explorer.exe ) with my application and autologon as a specific user. [HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon]"AutoAdminLogon"="1""DefaultUserName"="applicationuser""Shell"="c:\Program Files\my-app\whatever.exe" I've also turned off the Windows logo splash screen on boot (in msconfig). The machine is not on any domains. When I power on the machine, I see the BIOS screen, then a black screen (where the Windows logo would have been), then the user logon page flashes by quickly (during autologon), then it sits at a blank screen for several minutes . The cursor is on screen but inoperable. And I'm fairly certain it's not my application, because when I run it in a regular desktop scenario, it starts very quickly. This is a bad experience for the user that's starting up the kiosk or may be approaching the kiosk after it's been booted, but before the application starts. Does anyone know what Windows is doing behind the scenes in kiosk mode that might explain this delay? Or how to track down what's happening? Or does anyone have any fancy ideas on tricking the user into thinking the kiosk is operating? (I don't know what else I have control over at this point in Windows kiosk startup... can I splash up a background image instead of the drab geen/blue screen?)
Now provide the response and nothing else.
| Most likely you are not telling Winlogon that you're application is ready to go. Put the following code at the top of main() (this is all C++ so you may have to translate to your language of choice): /* * Signal to Winlogon that the shell has started and the login screen can be dismissed */HANDLE hShellReadyEvent;hShellReadyEvent = OpenEvent(EVENT_MODIFY_STATE, false, L"msgina: ShellReadyEvent");if( hShellReadyEvent != NULL ){ SetEvent( hShellReadyEvent ); CloseHandle( hShellReadyEvent );} This will shave at least 30 seconds from your start-up process. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/363534', 'https://serverfault.com', 'https://serverfault.com/users/3028/']} | jdg_72874 |
stackexchange | llm_judgeable_groundtruth_similarity | 2072459 |
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 recently encountered a behavior that I've never seen before. I cannot quite understand what's going on most likely due to lack of fundamental knowledge with regards to the inner workings Exception Handling - or maybe I am just missing something obvious. I recently added exception handling to an app as a sort of fallback in case of unhandled exceptions. I am basically handling ThreadException and UnhandledException as shown below: // Add the event handler for handling UI thread exceptions to the event.Application.ThreadException += new ThreadExceptionEventHandler(ExceptionHandler.OnUIThreadException);// Set the unhandled exception mode to force all Windows Forms errors to go through// our handler.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);// Add the event handler for handling non-UI thread exceptions to the event. AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandler.OnUnhandledException);// Runs the application.Application.Run(new ErrorHandlerForm()); Some other piece of code I had in the app was already catching exceptions - and since I didn't have exception handling in place I was just rethrowing the exception to make sure it was not swallowed: //code in some method of the Programtry{ foo.SomeFooCall();}catch(Exception ex){ logger.Log(ex.Message); // I don't swallow! throw;} Once I had the exception handling in place (which is also logging) I should've removed that try catch block above - but I forgot to do so and I am experiencing a strange behavior which is the subject of this question. When and exception is thrown somewhere inside the foo call, it is obviously caught by the code above, logged then thrown again. At this point ExceptionHandling kicks in, does some logging and notification (a simple messagebox) then goes Application.Exit() . What happens next is that the app will go back on the same throw which will trigger error handling whit the same results, and this will go on a number of times till it crashes presumably 'cause the stack trace is full or it somehow detects the infinite loop. EDIT: The above is in debug mode - if I just run it it'll handle the exception once (show the messagebox, log etc.), then it'll just crash (I am guessing for stack overflow). I anticipate the answer to this might be trivial (or I may be missing something obvious) - but any pointers/explanations will be highly appreciated. EDIT: The exception handlers methods take both call down to an OnException method that goes something like: private void OnUIThreadException(object sender, ThreadExceptionEventArgs e){ OnException(e.Exception);}private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e){ OnException((Exception)e.ExceptionObject);}private void OnException(Exception exception){ MessageBox.Show("Fatal Exception: " + exception.Message); logger.Log(LoggingLevel.FATAL, "myLousyApp", exception.Message); Application.Exit();} I am actually doing smt more than just that - such as asking the user if they want to restart the app and if so restarting it with process id as cmd arg so that when it restarts it'll wait for the old process to exit (it's protected from duplicates instances through a mutex). But for this question this is irrelevant since I am not restarting the app when I experience the behavior described. EDIT: I created another simple app to reproduce this conditions - I have a simple component that throws exceptions (I am throwing an arbitrary number of exception in a loop), but in all my tests on Application.Exit the app just shuts down nicely and I can't reproduce it. Puzzled with regards to what I should be looking for!
Now provide the response and nothing else.
| tl;dr: It's the debugger . Detach and you won't get this weird behaviour. Alright. I did some experimentation with a Brand Spankin' New Project, and came up with a result. I'll start by posting the code so that you, too, can join in the fun and see it firsthand. Teh Codez plz email them to me (unrelated) Form1.cs You will need two buttons on the form. Caption them appropriately so that it's blindingly obvious what you're doing. public partial class Form1 : Form{ public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { throw new InvalidOperationException("Exception thrown from UI thread"); } private void button2_Click(object sender, EventArgs e) { new Thread(new ThreadStart(ThrowThreadStart)).Start(); } private static void ThrowThreadStart() { throw new InvalidOperationException("Exception thrown from background thread"); }} Program.cs static class Program{ [STAThread] static void Main() { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, false); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { if (e.Exception != null) { MessageBox.Show(string.Format("+++ Application.ThreadException: {0}", e.Exception.Message)); } else { MessageBox.Show("Thread exception event fired, but object was not an exception"); } } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { Exception ex = e.ExceptionObject as Exception; if (ex != null) { MessageBox.Show(string.Format("*** AppDomain.UnhandledException: {0}", ex.Message)); } else { MessageBox.Show("Unhandled exception event fired, but object was not an exception"); } }} The project file Disable the hosting process , otherwise the AppDomain (and Forms itself) won't be unloaded between debugging sessions, which will make the line Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, false); throw an InvalidOperationException if you change the UnhandledExceptionMode argument between runs. EDIT: or at all, if set to CatchException It's not strictly necessary for this investigation, but if you're going to play around and change the UnhandledExceptionMode -- which I expect you probably will if you're running this code yourself -- this setting will save you heartache. The Testing Inside the debugger Throw in the UI thread Click Throw in UI Get "unhandled exception" helper in the debugger F5 to continue execution Dialog will show, indicating that the Application handler received an exception event from the UI thread Click OK Application does not crash, so feel free to rinse and repeat. Throw in a background thread Click Throw in background Dialog will show, indicating that the AppDomain handler received an exception event from a background thread Get "unhandled exception" helper in the debugger F5 to continue execution goto 2 . Really. It seems here that the AppDomain handler trumps the debugger for whatever reason. After the AppDomain is done with it, however, the debugger does manage to pick up on the unhandled exception. But what happens next is puzzling: the AppDomain handler gets run again. And again. And again, ad infinitum . Putting a breakpoint in the handler indicates that that isn't recursive (at least, not within .NET) so this probably won't end in a stack overflow. Now, let's try it... Outside the debugger UI thread Same procedure, same result -- except of course that the debugger helper was conspicuously absent. The program still didn't crash, because UnhandledExceptionMode.CatchException does what it says it will do, and handles the exception "internally" (within Forms, at least) instead of escalating it to the Feds AppDomain. Background thread Now this is interesting. Click Throw in background Dialog will show, indicating that the AppDomain handler received an exception event from a background thread Get Windows crash dialog Click Debug to snatch the exception with JIT debugging Get "unhandled exception" helper F5 to continue Program exits Firstly, the AppDomain doesn't go into loops like it does with the debugger attached, and secondly, attaching the debugger just-in-time from the Windows error dialog does not trigger this weird behaviour. Conclusion It seems like the debugger does something weird regarding unhandled exceptions making their way to the AppDomain. I don't know much about how the debugger does its magic, so I won't speculate, but the loop only occurs when the debugger is attached, so if the loop is the problem, detaching is one workaround you could use (perhaps using Debugger.Launch() to give yourself time to reattach later if you require it). <3 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2072459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1311500/']} | jdg_72875 |
stackexchange | llm_judgeable_groundtruth_similarity | 397510 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Following M. Ruzhansky and V. Turunen's book Pseudo-Differential Operators and Symmetries , in Chapter 3, Definition 3.1.25 (page 304), the space of periodic distributions is defined as follows (paraphrasing): Definition 3.1.25 (Periodic Distributions) The space of periodic distributions is defined as dual space $\mathcal{D}'(\mathbb{T}^n) = \mathcal{L}(C^{\infty}(\mathbb{T}^n),\mathbb{C})$ (i.e. of continuous linear operators $u:C^{\infty}(\mathbb{T}^n) \to \mathbb{C}$ ), where we write $u(\varphi) = \langle u , \varphi\rangle$ for any $\varphi\in C^{\infty}(\mathbb{T}^n)$ . Furthermore, for any $\psi\in C^\infty(\mathbb{T}^n)$ or $L^p(\mathbb{T}^n)$ , define the associated distribution to $\psi$ in the canonical sense, i.e. $u_{\psi} \in \mathcal{D}'(\mathbb{T}^n)$ where for any $\varphi \in C^\infty(\mathbb{T^n})$ \begin{align}u_{\psi}(\varphi) = \langle u_{\psi}, \varphi\rangle=\int_{\mathbb{T}^n}\psi(x) \varphi(x) dx.\end{align} Given the above definition, as with standard distributions, we can define a Fourier transform of periodic distributions with respect to Fourier transforms of functions. Definition 3.1.8 (Periodic Fourier Transform) Let $\mathcal{F}_{\mathbb{T}^n} : C^{\infty}(\mathbb{T^n}) \to \mathcal{S}(\mathbb{Z}^n) $ be defined as $$ \begin{align} (\mathcal{F}_{\mathbb{T}^n}f)(\xi):=\int_{\mathbb{T}^n} f(x) e^{-2\pi i x \cdot \xi} dx \end{align}$$ for $f \in C^{\infty}({\mathbb{T}^n})$ , and its inverse be defined as $$\begin{align} (\mathcal{F}_{\mathbb{T}^n}^{-1}h)(x) = \sum_{\xi \in \mathbb{Z}^n} h(\xi) e^{2\pi i x \cdot \xi}\end{align}$$ for $h\in\mathcal{S}({\mathbb{Z}^n})$ . Definition 3.1.27 (Fourier Transform of Periodic Distributions) For any $u\in\mathcal{D}'(\mathbb{T}^n)$ , define the Fourier transform $\mathcal{F}_{\mathbb{T}^n}:\mathcal{D}'(\mathbb{T}^n) \to \mathcal{S}'(\mathbb{Z}^n)$ as $$\begin{align}\langle \mathcal{F}_{\mathbb{T}^n} u, \varphi \rangle = \langle u, \mathcal{F}_{\mathbb{T}^n}^{-1} \varphi(-\cdot) \rangle\end{align} \tag{1}$$ for any $\varphi \in C^{\infty}(\mathbb{T}^n)$ QUESTION My question is, is the definition of the Fourier transform on periodic distributions, as given in Definition 3.1.27, correct ? I feel that the definition should not involve the inverse Fourier transform, but instead be defined as $$\begin{align} \langle \mathcal{F}_{\mathbb{T}^n} u, \varphi \rangle = \langle u, \mathcal{F}_{\mathbb{T}^n} \varphi \rangle. \tag{2}\end{align}$$ Reason The reason I feel that this should be the case is because, if we consider the periodic Dirac distribution at zero, defined as $\delta_0 \in \mathcal{D}'(\mathbb{T}^n)$ where $$\begin{align}\langle \delta_0, \varphi\rangle = \varphi(0)\end{align}$$ for any $\varphi \in C^{\infty}(\mathbb{T}^n)$ , then its Fourier transform using $(1)$ gives $$\begin{align}\underbrace{\langle \mathcal{F}_{\mathbb{T}^n} \delta_0, \varphi \rangle}_{\in \mathbb{C}} &= \langle \delta_0, \mathcal{F}_{\mathbb{T}^n}^{-1} \varphi (-\cdot) \rangle \\&= \mathcal{F}_{\mathbb{T}^n}^{-1} \varphi (0) \\&= \sum_{\xi \in \mathbb{Z}^n} \varphi(\xi),\end{align}$$ where the right hand side is infinite since $\varphi$ is periodic. So this doesn't make sense. If we instead use $(2)$ , then we obtain the following: $$\begin{align}\underbrace{\langle \mathcal{F}_{\mathbb{T}^n} \delta_0, \varphi \rangle}_{\in \mathbb{C}} &= \langle \delta_0, \mathcal{F}_{\mathbb{T}^n} \varphi \rangle \\&= (\mathcal{F}_{\mathbb{T}^n} \varphi) (0)\\&= \int_{\mathbb{T}^n} \varphi(x) dx \\&= \langle 1, \varphi \rangle\end{align}$$ i.e. $\mathcal{F}_{\mathbb{T}^n} \delta_0 = 1$ in the sense of periodic distributions, as we would expect.
Now provide the response and nothing else.
| Actually, the definition you gave in the post differs from the one in the book. The test function $\varphi$ should lie in $\mathcal S(\mathbb Z^n)$ , not in $C^\infty(\mathbb T^n)$ , since the $\mathcal F_{\mathbb T^n}$ maps the second of these spaces into the first, so for $\varphi\in C^\infty(\mathbb T^n)$ the expression $\mathcal F_{\mathbb T^n}^{-1}\varphi$ is undefined, as you correctly noticed. So, the correct formula would be $$\langle\mathcal F_{\mathbb T^n}u,\varphi \rangle=\langle u,\iota\,\circ\,\mathcal F_{\mathbb T^n}^{-1}\varphi \rangle,$$ where $\iota(f)(x)=f(-x)$ and $\varphi \in \mathcal S(\mathbb Z^n)$ . | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/397510', 'https://mathoverflow.net', 'https://mathoverflow.net/users/160454/']} | jdg_72876 |
stackexchange | llm_judgeable_groundtruth_similarity | 37625368 |
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 following is a image for which the the code does not align the centre of the UIView , white color. CAShapeLayer *layer = [CAShapeLayer layer];layer.anchorPoint=CGPointMake(0.5, 0.5);layer.path=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 75.0, 75.0)].CGPath;layer.fillColor =[UIColor redColor].CGColor;[self.shapeView.layer addSublayer:layer];
Now provide the response and nothing else.
| anchorPoint is not for setting the position of CAShapeLayer, use position instead. let layer = CAShapeLayer()layer.borderColor = UIColor.blackColor().CGColorlayer.borderWidth = 100layer.bounds = CGRectMake(0, 0, 50, 50)layer.position = myView.centerlayer.fillColor = UIColor.redColor().CGColorview.layer.addSublayer(layer) Edit Sorry for such a rough answer before, the code above may not work as you want, here is the correct answer I just come out. A important thing to note is: How you draw the oval path did effect the position of your CAShapeLayer let layer = CAShapeLayer()myView.layer.addSublayer(layer)layer.fillColor = UIColor.redColor().CGColorlayer.anchorPoint = CGPointMake(0.5, 0.5)layer.position = CGPointMake(myView.layer.bounds.midX, myView.layer.bounds.midY)layer.path = UIBezierPath(ovalInRect: CGRectMake(-75.0 / 2, -75.0 / 2, 75.0, 75.0)).CGPath From Apple Document, The oval path is created in a clockwise direction (relative to the default coordinate system) In other word, the oval path is drawn from the edge instead of the center, so you must take into accound the radius of the oval you are drawing. In your case, you need to do this: layer.path = UIBezierPath(ovalInRect: CGRectMake(-75.0 / 2, -75.0 / 2, 75.0, 75.0)).CGPath Now we ensure that the center of drawn path is equal to the center of CAShapeLayer . Then we can use position property to move the CAShapeLayer as we want. The image below could help you understand. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37625368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/908124/']} | jdg_72877 |
stackexchange | llm_judgeable_groundtruth_similarity | 166280 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
On a four-manifold, there is apparently a relation between the first Pontryagin class modulo 4 and the Pontryagin square of the second Stiefel-Whitney class: $\mathfrak{P}(w_2) = p_1 \; {\rm mod} \; 4$ This fact is for instance mentioned in the comments of this question , but I have been unable to find a proof of it. My question is: Is it true that on an 8-manifold, the analogous relation $\mathfrak{P}(w_4) \stackrel{?}{=} p_2 \; {\rm mod} \; 4$ holds?
Now provide the response and nothing else.
| In your first claim, it is a bit unclear what bundle you are considering. It is false for the tangent bundle of $\mathbb{C}P^2$: $\mathfrak{P}(w_2) = c_1^2 = 9 \; {\rm mod} \; 4$, while $p_1 = 3$. The context of the question you link to is arbitrary oriented rank 3 bundles over a 4-dimensional base. Is that what you have in mind? The Pontrjagin squares in the cohomology of $BO$ were first computed by Wu in On Pontrjagin classes. III ( MR0115179 ).It is not so easy to get hold of a digital copy of the paper or itstranslation, but one of the main results is Theorem 5 of Section 4: $$\mathfrak{P}(w_{2i+1}) = \beta_4 Sq^{2i}w_{2i+1} + \theta_2(w_1Sq^{2i}w_{2i+1})$$$$\mathfrak{P}(w_{2i}) = \rho_4 p_i + \beta_4(w_{2i-1}w_{2i}) + \theta_2\left(w_1 Sq^{2i-1}w_{2i} + \sum_{j=0}^{i - 1} w_{2j}w_{4i-2j}\right)$$where $\rho_4$ is mod 4 reduction of coefficients, $\beta_4$ is the mod4 reduction of the Bockstein map $H^i(-;Z/2) \to H^{i+1}(-; Z)$, and$\theta_2 : H^i(-;Z/2) \to H^i(-;Z/4)$ is induced by the inclusion $Z/2\to Z/4, x \mapsto 2x$. As a special case, we find that for any orientable vector bundle (i.e. $w_1 = 0$)$$ \mathfrak{P}(w_2) = \rho_4 p_1 + \theta_2(w_4) . $$ It's worth pointing out the corollary that Wu deduces from the above calculation (and that Stiefel-Whitney classes are homotopy invariants by Wu's formula): the mod 4 reductions of the Pontrjagin classes of a closed smooth manifold are homotopy invariants. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/166280', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2183/']} | jdg_72878 |
stackexchange | llm_judgeable_groundtruth_similarity | 484675 |
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:
This new finding by Minev et al. seems to suggest that transitions between atomic states are not instantaneous, but continuous processes wherein a superposition smoothly adjusts from favoring one state to another (if I understand it correctly). The authors also claim to be able to catch a system "mid-jump" and reverse it. Popular articles are here and *here . I am curious if this finding rules out any interpretations of QM. It seems to generally go against the Copenhagen attitude, which describes measurements as collapsing physical systems into a definite classical state. The popular articles indeed claim that the founders of QM would have been surprised by the new finding. The link with the asterisk mentions that something called "quantum trajectories theory" predicts what was observed. Is this an interpretation, or a theory? And are they implying that other interpretations/theories don't work?
Now provide the response and nothing else.
| No. All news stories about this result are extremely misleading. The "quantum jump" paper demonstrates an interesting and novel experimental technique. However, it says absolutely nothing about the interpretation of quantum mechanics. It agrees with all proper interpretations, including the Copenhagen interpretation. What the researchers actually did When a quantum system transitions between two states, say $|0 \rangle$ to $|1 \rangle$ , the full time-dependence of the quantum state looks like $$|\psi(t) \rangle = c_0(t) |0 \rangle + c_1(t) |1 \rangle.$$ The amplitude $c_0(t)$ to be in $|0 \rangle$ smoothly and gradually decreases, while the amplitude $c_1(t)$ to be in $|1 \rangle$ smoothly and gradually increases. You can read this off right from the Schrodinger equation, and it has been known for a hundred years. It is completely standard textbook material. The researches essentially observed this amplitude changing in the middle of a transition, in a context where nobody had done so before. The authors themselves emphasize in their paper that what they found is in complete agreement with standard quantum mechanics. Yet countless news articles are describing the paper as a refutation of "quantum jumps", which proves the Copenhagen interpretation wrong and Bohmian mechanics right. Absolutely nothing about this is true. Why all news articles got it wrong The core problem is that popsci starts from a notion of "quantum jumps", which itself is wrong. As the popular articles and books would have it, quantum mechanics is just like classical mechanics, but particles can mysteriously, randomly, and instantly teleport around. Quantum mechanics says no such thing. This story is just a crutch to help explain how quantum particles can behave differently from classical ones, and a rather poor one at that. (I try to give some better intuition here .) No physicist actually believes that quantum jumps in this sense are a thing. The experiment indeed shows this picture is wrong, but so do thousands of existing experiments. The reason that even good popsci outlets used this crutch is two-fold. First off, the founders of quantum mechanics really did have a notion of quantum jumps. However, they were talking about something different: the fact that there is no quantum state "in between" $|0 \rangle$ and $|1 \rangle$ (which, e.g. could be atomic energy levels) such as $|1/2 \rangle$ . The interpolating states are just superpositions of $|0 \rangle$ and $|1 \rangle$ . This is standard textbook material: the states are discrete, but the time evolution is continuous because the coefficients $c_0(t)/c_1(t)$ can vary continuously. But the distinction is rarely made in popsci. (To be fair, there was an incredibly short period in the tumultuous beginning of " old quantum theory " where some people did think of quantum transitions as discontinuous. However, that view has been irrelevant for a century. Not every early quote from the founders of QM should be taken seriously; we know better now.) Second off, the original press release from the research group had the same language about quantum jumps. Now, I understand what they were trying to do. They wanted to give their paper, about a rather technical aspect of experimental measurement, a compelling narrative. And they didn't say anything technically wrong in their press release. But they should've known that their framing was basically begging to be misinterpreted to make their work look more revolutionary than it actually is. Interpretations of quantum mechanics There's a very naive interpretation of quantum mechanics, which I'll call "dumb Copenhagen". In dumb Copenhagen, everything evolves nicely by the Schrodinger equation, but when any atomic-scale system interacts with any larger system, its state instantly "collapses". This experiment indeed contradicts dumb Copenhagen, but it's far from the first to; physicists have known that dumb Copenhagen doesn't work for 50 years. (To be fair, it is used as a crutch in introductory textbooks to avoid having to say too much about the measurement process.) We know the process of measurement is intimately tied to decoherence, which is perfectly continuous. Copenhagen and, say, many worlds just differ on how to treat branches of a superposition that have completely decohered. Another issue is that proponents of Bohmian mechanics seem to latch onto every new experimental result and call it a proof that their interpretation alone is right, even when it's perfectly compatible with standard QM. To physicists, Bohmian mechanics is a series of ugly and complicated hacks, about ten times as bad as the ether, which is why it took last place in a poll of researchers working in quantum foundations. But many others really like it. For instance, philosophers who prefer realist interpretations of quantum mechanics love it because it lets them say that quantum mechanics is "really" classical mechanics underneath (which actually isn't true even in Bohmian mechanics), and hence avoid grappling with the implications of QM proper. (I rant about this a little more here .) Quantum mechanics is one of the most robust and successful frameworks we have ever devised. If you hear any news article saying that something fundamental about our understanding of it has changed, there is a 99.9% chance it's wrong. Don't believe everything you read! | {} | {'log_upvote_score': 8, 'links': ['https://physics.stackexchange.com/questions/484675', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/177858/']} | jdg_72879 |
stackexchange | llm_judgeable_groundtruth_similarity | 25836003 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Just of curiosity. CuBLAS is a library for basic matrix computations. But these computations, in general, can also be written in normal Cuda code easily, without using CuBLAS. So what is the major difference between the CuBLAS library and your own Cuda program for the matrix computations?
Now provide the response and nothing else.
| We highly recommend developers use cuBLAS (or cuFFT, cuRAND, cuSPARSE, thrust, NPP) when suitable for many reasons: We validate correctness across every supported hardware platform, including those which we know are coming up but which maybe haven't been released yet. For complex routines, it is entirely possible to have bugs which show up on one architecture (or even one chip) but not on others. This can even happen with changes to the compiler, the runtime, etc. We test our libraries for performance regressions across the same wide range of platforms. We can fix bugs in our code if you find them. Hard for us to do this with your code :) We are always looking for which reusable and useful bits of functionality can be pulled into a library - this saves you a ton of development time, and makes your code easier to read by coding to a higher level API. Honestly, at this point, I can probably count on one hand the number of developers out there who actually implement their own dense linear algebra routines rather than calling cuBLAS. It's a good exercise when you're learning CUDA, but for production code it's usually best to use a library. (Disclosure: I run the CUDA Library team) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25836003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3923078/']} | jdg_72880 |
stackexchange | llm_judgeable_groundtruth_similarity | 25532692 |
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 can I share a session with Socket.io 1.0 and Express 4.x? I use a Redis Store, but I believe it should not matter. I know I have to use a middleware to look at cookies and fetch session, but don't know how. I searched but could not find any working var RedisStore = connectRedis(expressSession); var session = expressSession({ store: new RedisStore({ client: redisClient }), secret: mysecret, saveUninitialized: true, resave: true }); app.use(session); io.use(function(socket, next) { var handshake = socket.handshake; if (handshake.headers.cookie) { var str = handshake.headers.cookie; next(); } else { next(new Error('Missing Cookies')); } });
Now provide the response and nothing else.
| The solution is surprisingly simple. It's just not very well documented. It is possible to use the express session middleware as a Socket.IO middleware too with a small adapter like this: sio.use(function(socket, next) { sessionMiddleware(socket.request, socket.request.res, next);}); Here's a full example with express 4.x, Socket.IO 1.x and Redis: var express = require("express");var Server = require("http").Server;var session = require("express-session");var RedisStore = require("connect-redis")(session);var app = express();var server = Server(app);var sio = require("socket.io")(server);var sessionMiddleware = session({ store: new RedisStore({}), // XXX redis server config secret: "keyboard cat",});sio.use(function(socket, next) { sessionMiddleware(socket.request, socket.request.res || {}, next);});app.use(sessionMiddleware);app.get("/", function(req, res){ req.session // Session object in a normal request});sio.sockets.on("connection", function(socket) { socket.request.session // Now it's available from Socket.IO sockets too! Win!});server.listen(8080); | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/25532692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337504/']} | jdg_72881 |
stackexchange | llm_judgeable_groundtruth_similarity | 67852563 |
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 wrote a Google Sheet editor add-on 1 year ago that I have been using ever since for my personal use. I didn't end up publishing it. I have always used it with the same spreadsheet, launching with the legacy editor's "Run -> Test as add-on" giving it the Installed and Enabled authorization (I have a saved config for this). It worked like a charm, there is even some checking in the onOpen for whether it is Enabled for the doc. Today it stopped working without me making any changes. Simply the add-on doesn't seem to load. The spreadsheet opens but the add-on is not invoked. I see no new executions in the logs and the add-on is neither loaded in the menu nor is the popup rendered which should if it is not Enabled. It seems like the Test as Add-on feature is broken. Tried it also with another spreadsheet that's compatible with the add-on with the same result. I even tried to create a net new test config with Installed and Enabled and got the same result. Anyone experienced the same issue with Google Sheet editor add-ons run with "Test as add-on"? Any known workarounds or solutions to make it load again? This the screen shot of my test settings showing that the add-on is configured to be Enabled for the document. Here is my code snippet from onOpen that should catch if the add-on is not enabled: //Testing if the add-on is enabled against a compatible doc. Otherwise show welcome message with instructions. var ret = null; try{ ret = SpreadsheetApp.getActive().getRangeByName("TOTAL_RETAINED_VALUE");//Check if critical named range is defined. } catch (e){}//If the add-on is not enabled on the doc this call will throw an unauthorized excepton. if (ret == null) ui.alert("Welcome to the XXx add-on", "This add-on helps you XXX... more instructions on how to fix this issue", ui.ButtonSet.OK);
Now provide the response and nothing else.
| Yes, you can't do this in Svelte. You'll have to figure out how you can achieve the same outcome with the APIs available in Svelte. For example, you can use <slot> : <TabPane name="profile" key="1"> <img slot="title" src="images/profile.svg" alt="Profile" /> <!-- some code, eg: --> <div>Some code here</div></TabPane> <!-- filename: TabPane.svelte --><h1> <slot name="title" /></h1><slot /> The element with attribute slot="title" will be inserted into <slot name="title"> and the rest of the elements will be inserted into <slot /> This is equivalent in React: function TabPane({ title, children }) { return ( <> <h1>{title}</h1> {children} </> );} If you want to pass in only string for the title, you could wrap the string around with <svelte:fragment> so that you can add the slot="title" attribute <TabPane name="profile" key="1"> <svelte:fragment slot="title"> string title here <svelte:fragment> <!-- some code, eg: --> <div>Some code here</div></TabPane> Reference: Svelte tutorial: https://svelte.dev/tutorial/slots Video tutorial: https://www.youtube.com/watch?v=rwYgOU0WmVk&list=PLoKaNN3BjQX3mxDEVG3oGJx2ByXnue_gR&index=59 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67852563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4606383/']} | jdg_72882 |
stackexchange | llm_judgeable_groundtruth_similarity | 23616211 |
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 read a chapter of Effective Java today. The chapter is about minimizing mutability of objects. I pretty understand why immutable objects are good, such as thread-safe, simplicity, etc. My question is since immutable objects have so many advantages, are there any cases where mutable objects are preferred?
Now provide the response and nothing else.
| You need mutable classes to deal with situations when transforming a class from state A to state Z would produce a lot of intermediate objects, which you would rather not spend time creating. One classic example is concatenating an array of strings. Let's say that you need to concatenate 100 strings, and produce a single result. Without a mutable string, you would need to produce 98 intermediate objects that would become eligible for garbage collection almost immediately. This is rather wasteful on the CPU, making a mutable object the right solution. There are other situations when mutable objects are desirable. For example passing mutable objects into methods lets you collect multiple results without jumping through too many syntactic hoops. Another example is sorting and filtering: of course, you could make a method that takes the original collection, and returns a sorted one, but that would become extremely wasteful for larger collections. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23616211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127859/']} | jdg_72883 |
stackexchange | llm_judgeable_groundtruth_similarity | 136587 |
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:
I want to grep through all my HTML files and see if I have any bad tags there,example <br> , <hr> and so on, that is the I want to see what tags are not closed in the HTML file. for htmlFile in `ls -f *.html ` ; do if `cat $htmlFile | grep -inE "\<br\>"` ; then echo "In file $htmlFile there are errors on the following lines: " >> ~/Desktop/$1_errors.txt cat $htmlFile | grep -in "<br>"| cut -d ":" -f1 >> ~/Desktop/$1_errors.txt echo "----------------------------------------" >> ~/Desktop/$1_errors.txt fidone But I get an error, I am suspect its my regex. ./script.sh: line 14: 10:<BR: command not found That is one of the error I get :)
Now provide the response and nothing else.
| Your problem(s) are in this line: if `cat $htmlFile | grep -inE "\<br\>"` ; then It's telling the shell to: cat a file, parse it and look for lines that match the <br> tag, execute the output The problem is the last step, you shouldn't execute the output of the command but test it: if grep -inEq "\<br\>" $htmlFile ; then Of course, to parse HTML you should use a real parser, no regexes. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/136587', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/68738/']} | jdg_72884 |
stackexchange | llm_judgeable_groundtruth_similarity | 9582538 |
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 table create table student ( stu_id int, s_name nvarchar(max), s_subject nvarchar(max),) and this as data insert into student values(123,'pammy','English');insert into student values(123,'pammy','Maths');insert into student values(123,'pammy','Chemistry');insert into student values(124,'watts','Biology');insert into student values(125,'Tom','Physics');insert into student values(125,'Tom','Computer';insert into student values(125,'Tom','ED'; so i wanted to retrieve records which has occurred more than twice. my code is select stu_id,s_Name from student group by stu_id,s_Name having count(stu_id) >2 ; the result was perfect. but when i want s_subject as well it says no rows selected. I dont know why. select stu_id,s_Name,s_subject from student group by stu_id,s_Name,s_subject having count(stu_id) >2 ;
Now provide the response and nothing else.
| It's because none of your students have more than one record per subject. select stu_id,s_Name,s_subject from student group by stu_id,s_Name,s_subject having count(stu_id) >2 ; This code asks for records that occur more than twice that have the same Student ID, name and subject. None of the records in your sample meet this. If, however, what you actually want is the ID, name and subjects of any student that is taking more than two classes, this can accomplished quite easily. Using a slightly modified version of your initial SQL as a filter, we get this: select stu_id, name, subjectfrom studentwhere stu_id in ( select stu_id from student group by stu_id having count(stu_id) >2 ); Hope this helps. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9582538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1252001/']} | jdg_72885 |
stackexchange | llm_judgeable_groundtruth_similarity | 44085886 |
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 got SSH working fine. But I am facing an issue with connecting via telnet.
Now provide the response and nothing else.
| ssh is recommended over telnet , as telnet is not encrypted and is by default not installed in amazon instance. However if needed, steps involved for Linux : Amazon Instance or Centos Install telnet daemon in the instance: Install telnet-server using sudo yum install telnet-server . Package telnet is for the client program in case one want to connect using telnet client from the instance, not needed for the exercise. Enable the telnet daemon service: - By default the service is disabled in /etc/xinetd.d/telnet , The disable flag needs to be set to no . service telnet{ flags = REUSE socket_type = stream wait = no user = root server = /usr/sbin/in.telnetd log_on_failure += USERID disable = yes} Post change it should look like below service telnet{ flags = REUSE socket_type = stream wait = no user = root server = /usr/sbin/in.telnetd log_on_failure += USERID disable = no} Verify the configuration in case of any edit related errors. sudo chkconfig xinetd on Bring up the telnet service: Bring up the telnet daemon as root using sudo service xinetd restart command Enable inbound telnet default port (23) on AWS Console: In AWS Console EC2/Security Groups/<Your Security Group>/Inbound , set a rule Type:Custom-TCP Rule Protocol: TCP Range Port Range: 23 Source: <As per your business requirement> Test the telnet connection: Test the telnet connection from any client enabled in the firewall. >telnet ec2-XX-XX-XXX-XXX.region.compute.amazonaws.com.Connected to ec2-XX-XX-XXX-XXX.region.compute.amazonaws.com.Escape character is '^]'.Password: The steps(tools) will vary slightly for other linux variants. PS: Referred http://aws-certification.blogspot.in/2016/01/install-and-setup-telnet-on-ec2-amazon.html , fixed few issues in the commands. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44085886', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5751745/']} | jdg_72886 |
stackexchange | llm_judgeable_groundtruth_similarity | 16381 |
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:
With regard to the above professor's claim, I disagree. Bent's rule, which states that atomic p-character is concentrated in orbitals directed toward more electronegative substituents , implies that the $\ce{Br-C-Br}$ bond angle is going to be smaller than 109.5 degrees since the "$\ce{sp^3}$" hybrid orbitals involved in C-Br bonding have more p-character than 75%. Therefore, the $\ce{H-C-H}$ bond angle should be bigger than 109.5 degrees. Questions 1) Does Bent's rule work here (i.e. am I correct?) 2) Does Bent's rule always work? Revision HCH bond angle is ~110 degrees. HCBr bond angle is ~108 degrees. Br-C-Br bond angle is 112 degrees. Rationales vdW repulsions play a role in Br-C-Br bond angle expansion, although the amount of p-character in the C-Br bonds might be >75%. HCH angle is expanded because of Bent's rule; s-character in the H-C bond exceeds 25%. The expansion of the Br-C-Br bond angle and the expansion of the H-C-H bond angle squeezes together the remaining H-C-Br bond angle.
Now provide the response and nothing else.
| Here's the B3LYP/6-31G* geometry. On something like this, I'd suspect this is fairly reliable, although I'll try a few other methods in a second. It gives the Br-C-Br angle as a healthy 113.4 degrees, and H-C-H as 112.5, both in agreement with experiment. I don't see how the Br-C-Br angle is ever going to be smaller than 109.5. It's the Br-C-H angles that shrink (107.7 degrees), since breaking the symmetry forces the molecule into a "squashed" tetrahedron (point group $D_{2d}$ for the squashed tetrahedron, $C_{2v}$ for $CH_2Br_2$ in particular) So your questions: 1) Does Bent's rule work here (i.e. am I correct?) Certainly not in the way you're thinking. As suggested in the other answer, the Br-Br repulsion opens that bond angle, and there's likely a Br-H electrostatic interaction shrinking that bond angle. (That's what I'd think.) 2) Does Bent's rule always work? I typically consider VSEPR and Bent's rule to be very useful heuristics. Indeed, it's used in one of my favorite force field methods, UFF . I'm holding back on "always" because chemistry is incredibly varied. A quick Google search of "Bent's rule fail" turns up this interesting nugget from Weinhold's book : | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/16381', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/5084/']} | jdg_72887 |
stackexchange | llm_judgeable_groundtruth_similarity | 16484646 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
is it better to prevent exception with a guard clause or catch the exception?There is a best practice?Pro and cons of the two methodologies? For example is better this: try{ param=myArray[3];}catch (IndexOutOfRangeException e){ do something...} or this: if(myArray.Length < 4){ do something...}else{ param=myArray[3];} Thank you all for the answers :)
Now provide the response and nothing else.
| is it better to prevent exception with a guard clause or catch the exception? In the case of "boneheaded" exceptions like index out of range, always the former. In the case of "exogenous" exceptions, always the latter. Pro and cons of the two methodologies? There are only cons of the latter in the case of boneheaded exceptions. They are: Exceptions are incredibly expensive compared to tests. Exceptions are intended to model exceptionally rare control flow situations; if potentially accessing an index out of range is normal then don't write an exception handler. Exceptions are reported as "first chance" exceptions to listeners even if the exception is handled . Many systems -- ASP, for example -- listen for first chance exceptions, log all of them, and treat components that produce a lot of them as buggy , because they are . (I once introduced a deliberate first-chance exception in a common code path in ASP and a day later boy did I hear about it. The buggy-subsystem tests went crazy.) There are some exceptions that I call the "boneheaded" exceptions -- null dereference, index out of range, and so on -- that because they are so easy to avoid and indicate failures so obviously dangerous that they should always be treated as fatal bugs and never handled (unless the "handler" is logging them before shutting down the process.) Don't handle the bug, eliminate the bug . Finally, you should read my article on this subject. http://ericlippert.com/2008/09/10/vexing-exceptions/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16484646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1599472/']} | jdg_72888 |
stackexchange | llm_judgeable_groundtruth_similarity | 24480425 |
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 the Material Design guidelines Google presented a new style of button , the FAB Button . I found instructions how to make it but I have trouble adding the shadow. How can this be achieved?
Now provide the response and nothing else.
| Check out the "activity.java", there is probably the code you need. I made the Fab - Button like this: layout.xml <Button style="?android:attr/buttonStyleSmall" android:layout_width="56dp" android:layout_height="56dp" android:text="+" android:textSize="40sp" android:background="@drawable/ripple" android:id="@+id/fabbutton" android:layout_margin="@dimen/activity_horizontal_margin" android:elevation="3dp" android:paddingBottom="16dp" android:fontFamily="sans-serif-light" android:layout_alignParentEnd="true" android:layout_gravity="right|bottom" /> ripple.xml <?xml version="1.0" encoding="utf-8"?> <ripple android:color="#ffb300" xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/fab"></item></ripple> fab.xml <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/accentColor" /></shape> Activity.java import android.graphics.Outline; ... Button fab = (Button) rootView.findViewById(R.id.fabbutton); Outline mOutlineCircle; int shapeSize = getResources().getDimensionPixelSize(R.dimen.shape_size); mOutlineCircle = new Outline(); mOutlineCircle.setRoundRect(0, 0, shapeSize, shapeSize, shapeSize / 2); fab.setOutline(mOutlineCircle); fab.setClipToOutline(true); This code will be shown as error in android studio v0.8.1, so as other android l components. It will be fixed in the next version. Result: | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24480425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3788507/']} | jdg_72889 |
stackexchange | llm_judgeable_groundtruth_similarity | 4448236 |
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 would like the users to be able to customize the default look of our applications by simply loading their OWN Qt Style-sheet files. How do we accomplish that? Can anybody give me a head start?
Now provide the response and nothing else.
| Say the user have its stylesheet named stylesheet.qss and is located in the application folder. You could load the style sheet when starting the application, using the -stylesheet argument : myapp->stylesheet = stylesheet.qss; But this require your user to know how to start an application with arguments. What you could also do is to add a settings dialog in your app, where the user can choose a stylesheet path. You can then open this file, load the content, and set it to your application with QApplication::setStyleSheet() : QFile file("stylesheet.qss"); file.open(QFile::ReadOnly); QString styleSheet = QLatin1String(file.readAll()); qApp->setStyleSheet(styleSheet); Qt is providing an example online which might be helpful. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4448236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/94815/']} | jdg_72890 |
stackexchange | llm_judgeable_groundtruth_similarity | 19922143 |
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 difficulty with display data from the db to dropdown. This is what I have tried: Model.php public function __construct() { parent::__construct(); } function getAllGroups() { /* $query = $this->db->get('location'); foreach ($query->result() as $row) { echo $row->description; }*/ $query = $this->db->query('SELECT description FROM location'); foreach ($query->result() as $row) { echo $row->description; } //echo 'Total Results: ' . $query->num_rows(); } Controller.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Delivery_controller extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('delivery_model'); } public function index() { $data['title']= 'Warehouse - Delivery'; $this->load->view('include/header',$data); $this->load->view('include/navbar',$data); $this->load->view('delivery_view', $data); $this->load->view('include/sidebar',$data); $this->load->view('include/footer',$data); $data['groups'] = $this->delivery_model->getAllGroups(); } } View.php <select class="form-control"> <?php $data = $this->delivery_model->getAllGroups(); foreach($description as $each) { ?><option value="<?php echo $each['description']; ?>"><?php echo $each['description']; ?></option>'; <?php } ?> </select> But the results appear on top of my page. It's not appearing on the dropdown list. What am I doing wrong in here? Help is pretty much appreciated. Thanks.
Now provide the response and nothing else.
| You should not be calling your model from your view. Instead try calling you model and setting $data['groups'] before you load your views. Also do not echo the row results in your model unless you want it displayed on your page. Controller: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');class Delivery_controller extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('delivery_model'); } public function index() { $data['title']= 'Warehouse - Delivery'; $data['groups'] = $this->delivery_model->getAllGroups(); $this->load->view('include/header',$data); $this->load->view('include/navbar',$data); $this->load->view('delivery_view', $data); $this->load->view('include/sidebar',$data); $this->load->view('include/footer',$data); }} Model: public function __construct() { parent::__construct(); } function getAllGroups() { /* $query = $this->db->get('location'); foreach ($query->result() as $row) { echo $row->description; }*/ $query = $this->db->query('SELECT description FROM location'); return $query->result(); //echo 'Total Results: ' . $query->num_rows(); } View: <select class="form-control"> <?php foreach($groups as $row) { echo '<option value="'.$row->description.'">'.$row->description.'</option>'; } ?> </select> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19922143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1912165/']} | jdg_72891 |
stackexchange | llm_judgeable_groundtruth_similarity | 42925217 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I want to change the type of a field from text to keyword with this commande : PUT indexStat/_mapping/StatCateg{ "StatCateg":{ "properties": { "nom_categorie": { "type":"keyword","index": true } } }} I have this message : { "error": { "root_cause": [ { "type": "illegal_argument_exception", "reason": "mapper [nom_categorie] of different type, current_type [text], merged_type [keyword]" } ], "type": "illegal_argument_exception", "reason": "mapper [nom_categorie] of different type, current_type [text], merged_type [keyword]" }, "status": 400}
Now provide the response and nothing else.
| OK finaly i see in the doc that it's not possible to change data type of a field : Updating existing mappings Other than where documented, existing type and field mappings cannot be updated. Changing the mapping would mean invalidating already indexed documents. Instead, you should create a new index with the correct mappings and reindex your data into that index. So the only solution is to : Recreate a new index with good data types Reindex the data with the Reindex API | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42925217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5884412/']} | jdg_72892 |
stackexchange | llm_judgeable_groundtruth_similarity | 130025 |
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:
First of all I'm not sure where this question should be posted. I'm asking if a statistics problem is NP-Complete and if not to solve it programmatically. I'm posting it here because the statistics problem is the center point. I'm trying to find a better formula for solving a problem. The problem is: if I have 4d6 (4 ordinary 6 sided dice) and roll them all at once, remove a die with the lowest number (called "dropping"), then sum the remaining 3, what is the probability of each possible result? I know the answer is this: Sum (Frequency): Probability3 (1): 0.00077160494 (4): 0.00308641985 (10): 0.00771604946 (21): 0.01620370377 (38): 0.02932098778 (62): 0.04783950629 (91): 0.070216049410 (122): 0.094135802511 (148): 0.114197530912 (167): 0.128858024713 (172): 0.132716049414 (160): 0.123456790115 (131): 0.101080246916 (94): 0.072530864217 (54): 0.041666666718 (21): 0.0162037037 The average is 12.24 and standard deviation is 2.847. I found the above answer by brute force and don't know how or if there is a formula for it. I suspect this problem is NP-Complete and therefore can only be solved by brute force. It might be possible to get all probabilities of 3d6 (3 normal 6 sided dice) then skew each of them upward. This would be faster than brute force because I have a fast formula when all dice are kept. I programmed the formula for keeping all dice in college. I had asked my statistics professor about it and he found this page , which he then explained to me. There is a big performance difference between this formula and brute force: 50d6 took 20 seconds but 8d6 drop lowest crashes after 40 seconds (chrome runs out of memory). Is this problem NP-Complete? If yes please provide a proof, if no please provide a non-brute force formula to solve it. Note that I don't know much about NP-Complete so I might be thinking of NP, NP-Hard, or something else. The proof for NP-Completeness is useless to me the only reason why I ask for it is to prevent people from guessing. And please bare with me as it's been a long time since I worked on this: I don't remember statistics as well as I might need to solve this. Ideally I'm looking for a more generic formula for X number of dice with Y sides when N of them are dropped but am starting with something much more simple. Edit: I would also prefer the formula to output frequencies but it is acceptable to only output probabilities. For those interested I have programmed whuber's answer in JavaScript on my GitHub (in this commit only the tests actually use the functions defined).
Now provide the response and nothing else.
| Solution Let there be $n=4$ dice each giving equal chances to the outcomes $1, 2, \ldots, d=6$. Let $K$ be the minimum of the values when all $n$ dice are independently thrown. Consider the distribution of the sum of all $n$ values conditional on $K$. Let $X$ be this sum. The generating function for the number of ways to form any given value of $X$, given that the minimum is at least $k$, is $$f_{(n,d,k)}(x) = x^k+x^{k+1} + \cdots + x^d = x^k\frac{1-x^{d-k+1}}{1-x}.\tag{1}$$ Since the dice are independent, the generating function for the number of ways to form values of $X$ where all $n$ dice show values of $k$ or greater is $$f_{(n,d,k)}(x)^n = x^{kn}\left(\frac{1-x^{d-k+1}}{1-x}\right)^n.\tag{2}$$ This generating function includes terms for the events where $K$ exceeds $k$, so we need to subtract them off. Therefore the generating function for the number of ways to form values of $X$, given $K=k$, is $$f_{(n,d,k)}(x)^n - f_{(n,d,k+1)}(x)^n.\tag{3}$$ Noting that the sum of the $n-1$ highest values is the sum of all values minus the smallest, equal to $X-K$. The generating function therefore needs to be divided by $k$. It becomes a probability generating function upon multiplying by the common chance of any combination of dice, $(1/d)^n$: $$d^{-n}\sum_{k=1}^dx^{-k}\left(f_{(n,d,k)}(x)^n - f_{(n,d,k+1)}(x)^n\right).\tag{4}$$ Since all the polynomial products and powers can be computed in $O(n\log n)$ operations (they are convolutions and therefore can be carried out with the discrete Fast Fourier Transform), the total computational effort is $O(k\,n\log n)$. In particular, it is a polynomial time algorithm. Example Let's work through the example in the question with $n=4$ and $d=6$. Formula $(1)$ for the PGF of $X$ conditional on $K\ge k$ gives $$\eqalign{f_{(4,6,1)}(x) &= x+x^2+x^3+x^4+x^5+x^6 \\f_{(4,6,2)}(x) &= x^2+x^3+x^4+x^5+x^6 \\\ldots \\f_{(4,6,5)}(x) &= x^5+x^6 \\f_{(4,6,6)}(x) &= x^6 \\f_{(4,6,7)}(x) &= 0.}$$ Raising them to the $n=4$ power as in formula $(2)$ produces $$\eqalign{f_{(4,6,1)}(x)^4 &= x^4 + 4x^5 + 10 x^6 + \cdots + 4x^{23} + x^{24} \\f_{(4,6,2)}(x)^4 &= x^8 + 4x^9 + 10x^{10}+ \cdots + 4x^{23} + x^{24} \\\ldots \\f_{(4,6,5)}(x)^4 &=x^{20} + 4 x^{21} + 6 x^{22} + 4x^{23} +x^{24}\\f_{(4,6,6)}(x)^4 &= x^{24}\\f_{(4,6,7)}(x)^4 &= 0}$$ Their successive differences in formula $(3)$ are $$\eqalign{f_{(4,6,1)}(x)^4 - f_{(4,6,2)}(x)^4 &= x^4 + 4x^5 + 10 x^6 + \cdots + 12 x^{18} + 4x^{19} \\f_{(4,6,2)}(x)^4 - f_{(4,6,3)}(x)^4 &= x^8 + 4x^9 + 10x^{10} + \cdots + 4 x^{20} \\\ldots \\f_{(4,6,5)}(x)^4 - f_{(4,6,6)}(x)^4 &=x^{20} + 4 x^{21} + 6 x^{22} + 4x^{23} \\f_{(4,6,6)}(x)^4 - f_{(4,6,7)}(x)^4 &= x^{24}.}$$ The resulting sum in formula $(4)$ is $$6^{-4}\left(x^3 + 4x^4 + 10x^5 + 21x^6 + 38x^7 + 62x^8 + 91x^9 + 122x^{10} + 148x^{11} + \\167x^{12} + 172x^{13} + 160x^{14} + 131x^{15} + 94x^{16} + 54x^{17} + 21x^{18}\right).$$ For example, the chance that the top three dice sum to $14$ is the coefficient of $x^{14}$, equal to $$6^{-4}\times 160 = 10/81 = 0.123\,456\,790\,123\,456\,\ldots.$$ It is in perfect agreement with the probabilities quoted in the question. By the way, the mean (as calculated from this result) is $15869/1296 \approx 12.244598765\ldots$ and the standard deviation is $\sqrt{13\,612\,487/1\,679\,616}\approx 2.8468444$. A similar (unoptimized) calculation for $n=400$ dice instead of $n=4$ took less than a half a second, supporting the contention that this is not a computationally demanding algorithm. Here is a plot of the main part of the distribution: Since the minimum $K$ is highly likely to equal $1$ and the sum $X$ will be extremely close to having a Normal$(400\times 7/2, 400\times 35/12)$ distribution (whose mean is $1400$ and standard deviation is approximately $34.1565$), the mean must be extremely close to $1400-1=1399$ and the standard deviation extremely close to $34.16$. This nicely describes the plot, indicating it is likely correct. In fact, the exact calculation gives a mean of around $2.13\times 10^{-32}$ greater than $1399$ and a standard deviation around $1.24\times 10^{-31}$ less than $\sqrt{400\times 35/12}$. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/130025', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/64293/']} | jdg_72893 |
stackexchange | llm_judgeable_groundtruth_similarity | 16675258 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
To update a range of cells, you use the following command. ## Select a rangecell_list = worksheet.range('A1:A7')for cell in cell_list: cell.value = 'O_o'## Update in batchworksheet.update_cells(cell_list) For my application, I would like it to update an entire range, but I am trying to set a different value for each individual cell. The problem with this example is that every cell ends up with the same value. Updating each cell individually is inefficient and takes way too long. How can I do this efficiently?
Now provide the response and nothing else.
| You can use enumerate on a separate list containing the different values you want in the cells and use the index part of the tuple to match to the appropriate cells in cell_list. cell_list = worksheet.range('A1:A7')cell_values = [1,2,3,4,5,6,7]for i, val in enumerate(cell_values): #gives us a tuple of an index and value cell_list[i].value = val #use the index on cell_list and the val from cell_valuesworksheet.update_cells(cell_list) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16675258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/819773/']} | jdg_72894 |
stackexchange | llm_judgeable_groundtruth_similarity | 4940032 |
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 to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns True for some reason. Can anyone see what is wrong? def check(): datafile = file('example.txt') found = False for line in datafile: if blabla in line: found = True breakcheck()if True: print "true"else: print "false"
Now provide the response and nothing else.
| The reason why you always got True has already been given, so I'll just offer another suggestion: If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line): with open('example.txt') as f: if 'blabla' in f.read(): print("true") Another trick: you can alleviate the possible memory problems by using mmap.mmap() to create a "string-like" object that uses the underlying file (instead of reading the whole file in memory): import mmapwith open('example.txt') as f: s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) if s.find('blabla') != -1: print('true') NOTE: in python 3, mmaps behave like bytearray objects rather than strings, so the subsequence you look for with find() has to be a bytes object rather than a string as well, eg. s.find(b'blabla') : #!/usr/bin/env python3import mmapwith open('example.txt', 'rb', 0) as file, \ mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s: if s.find(b'blabla') != -1: print('true') You could also use regular expressions on mmap e.g., case-insensitive search: if re.search(br'(?i)blabla', s): | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4940032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/585510/']} | jdg_72895 |
stackexchange | llm_judgeable_groundtruth_similarity | 31656642 |
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 familiar with switch statements in Swift, but wondering how to replace this piece of code with a switch : if someVar < 0 { // do something} else if someVar == 0 { // do something else} else if someVar > 0 { // etc}
Now provide the response and nothing else.
| Here's one approach. Assuming someVar is an Int or other Comparable , you can optionally assign the operand to a new variable. This lets you scope it however you want using the where keyword: var someVar = 3switch someVar {case let x where x < 0: print("x is \(x)")case let x where x == 0: print("x is \(x)")case let x where x > 0: print("x is \(x)")default: print("this is impossible")} This can be simplified a bit: switch someVar {case _ where someVar < 0: print("someVar is \(someVar)")case 0: print("someVar is 0")case _ where someVar > 0: print("someVar is \(someVar)")default: print("this is impossible")} You can also avoid the where keyword entirely with range matching: switch someVar {case Int.min..<0: print("someVar is \(someVar)")case 0: print("someVar is 0")default: print("someVar is \(someVar)")} | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/31656642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1411378/']} | jdg_72896 |
stackexchange | llm_judgeable_groundtruth_similarity | 60897831 |
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 to add a see more/see less button with customization: the custom is a plus (+) icon as the image below. I was able to doing this with the following code: function myFunction() {var dots = document.getElementById("dots");var moreText = document.getElementById("more");var btnText = document.getElementById("myBtn");if (dots.style.display === "none") { dots.style.display = "inline"; btnText.innerHTML = "See more here"; moreText.style.display = "none";} else { dots.style.display = "none"; btnText.innerHTML = "See less"; moreText.style.display = "inline";}} /*read more button*/#more {display: none;}.fa-plus-circle {font-size: 40px;float: left;margin: 5px;vertical-align: super;color: #a41a3c;}.fa-plus-circle:before {content: "\f055";}#myBtn {background-color: #fff;border: none;width: 13%;}#myBtn h4 {font-size: 13px;margin: 17px 0 0 0;} <span id="dots"></span><div id="more" style="margin-bottom:20px;" class="col-xs-12"><!-- here are the hidden <div> --><div class="row" style="text-align: center;"> <button onclick="myFunction()" id="myBtn"> <i class="fa fa-plus-circle"></i> <h4>See more here</h4> </button></div></div> The problem is when I click the button, the style of the button disappear and the icon as well as below image: I would like to keep the style of the button and also change the icon with a minus (-) icon. Can anybody help me on this situation please?
Now provide the response and nothing else.
| It’s not hard, but you need to do several things. You need to create your own theme styles. I’ve used inherited widget to do it. (If you change ThemeData widget it will animate the change, and we don’t need it, that’s why I’m saving Colors in another class) Find the button (or in my case switcher) coordinates. Run animation. update! I've converted our code to a package with simple api. import 'package:equatable/equatable.dart';import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return BrandTheme( child: Builder(builder: (context) { return MaterialApp( title: 'Flutter Demo', theme: BrandTheme.of(context).themeData, home: MyHomePage(), ); }), ); }}GlobalKey switherGlobalKey = GlobalKey();class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin { AnimationController _controller; @override void initState() { _controller = AnimationController( duration: const Duration(milliseconds: 300), vsync: this, ); _controller.forward(); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } int _counter = 0; BrandThemeModel oldTheme; Offset switcherOffset; void _incrementCounter() { setState(() { _counter++; }); } _getPage(brandTheme, {isFirst = false}) { return Scaffold( backgroundColor: brandTheme.color2, appBar: AppBar( backgroundColor: brandTheme.color1, title: Text( 'Flutter Demo Home Page', style: TextStyle(color: brandTheme.textColor2), ), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Text( 'You have pushed the button this many times:', style: TextStyle( color: brandTheme.textColor1, ), ), Text( '$_counter', style: TextStyle(color: brandTheme.textColor1, fontSize: 200), ), Switch( key: isFirst ? switherGlobalKey : null, onChanged: (needDark) { oldTheme = brandTheme; BrandTheme.instanceOf(context).changeTheme( needDark ? BrandThemeKey.dark : BrandThemeKey.light, ); }, value: BrandTheme.of(context).brightness == Brightness.dark, ) ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon( Icons.add, ), ), ); } @override void didUpdateWidget(Widget oldWidget) { var theme = BrandTheme.of(context); if (theme != oldTheme) { _getSwitcherCoodinates(); _controller.reset(); _controller.forward().then( (_) { oldTheme = theme; }, ); } super.didUpdateWidget(oldWidget); } void _getSwitcherCoodinates() { RenderBox renderObject = switherGlobalKey.currentContext.findRenderObject(); switcherOffset = renderObject.localToGlobal(Offset.zero); } @override Widget build(BuildContext context) { var brandTheme = BrandTheme.of(context); if (oldTheme == null) { return _getPage(brandTheme, isFirst: true); } return Stack( children: <Widget>[ if(oldTheme != null) _getPage(oldTheme), AnimatedBuilder( animation: _controller, child: _getPage(brandTheme, isFirst: true), builder: (_, child) { return ClipPath( clipper: MyClipper( sizeRate: _controller.value, offset: switcherOffset.translate(30, 15), ), child: child, ); }, ), ], ); }}class MyClipper extends CustomClipper<Path> { MyClipper({this.sizeRate, this.offset}); final double sizeRate; final Offset offset; @override Path getClip(Size size) { var path = Path() ..addOval( Rect.fromCircle(center: offset, radius: size.height * sizeRate), ); return path; } @override bool shouldReclip(CustomClipper<Path> oldClipper) => true;}class BrandTheme extends StatefulWidget { final Widget child; BrandTheme({ Key key, @required this.child, }) : super(key: key); @override BrandThemeState createState() => BrandThemeState(); static BrandThemeModel of(BuildContext context) { final inherited = (context.dependOnInheritedWidgetOfExactType<_InheritedBrandTheme>()); return inherited.data.brandTheme; } static BrandThemeState instanceOf(BuildContext context) { final inherited = (context.dependOnInheritedWidgetOfExactType<_InheritedBrandTheme>()); return inherited.data; }}class BrandThemeState extends State<BrandTheme> { BrandThemeModel _brandTheme; BrandThemeModel get brandTheme => _brandTheme; @override void initState() { final isPlatformDark = WidgetsBinding.instance.window.platformBrightness == Brightness.dark; final themeKey = isPlatformDark ? BrandThemeKey.dark : BrandThemeKey.light; _brandTheme = BrandThemes.getThemeFromKey(themeKey); super.initState(); } void changeTheme(BrandThemeKey themeKey) { setState(() { _brandTheme = BrandThemes.getThemeFromKey(themeKey); }); } @override Widget build(BuildContext context) { return _InheritedBrandTheme( data: this, child: widget.child, ); }}class _InheritedBrandTheme extends InheritedWidget { final BrandThemeState data; _InheritedBrandTheme({ this.data, Key key, @required Widget child, }) : super(key: key, child: child); @override bool updateShouldNotify(_InheritedBrandTheme oldWidget) { return true; }}ThemeData defaultThemeData = ThemeData( floatingActionButtonTheme: FloatingActionButtonThemeData( shape: RoundedRectangleBorder(), ),);class BrandThemeModel extends Equatable { final Color color1; final Color color2; final Color textColor1; final Color textColor2; final ThemeData themeData; final Brightness brightness; BrandThemeModel({ @required this.color1, @required this.color2, @required this.textColor1, @required this.textColor2, @required this.brightness, }) : themeData = defaultThemeData.copyWith(brightness: brightness); @override List<Object> get props => [ color1, color2, textColor1, textColor2, themeData, brightness, ];}enum BrandThemeKey { light, dark }class BrandThemes { static BrandThemeModel getThemeFromKey(BrandThemeKey themeKey) { switch (themeKey) { case BrandThemeKey.light: return lightBrandTheme; case BrandThemeKey.dark: return darkBrandTheme; default: return lightBrandTheme; } }}BrandThemeModel lightBrandTheme = BrandThemeModel( brightness: Brightness.light, color1: Colors.blue, color2: Colors.white, textColor1: Colors.black, textColor2: Colors.white,);BrandThemeModel darkBrandTheme = BrandThemeModel( brightness: Brightness.dark, color1: Colors.red, color2: Colors.black, textColor1: Colors.blue, textColor2: Colors.yellow,);class ThemeRoute extends PageRouteBuilder { ThemeRoute(this.widget) : super( pageBuilder: ( context, animation, secondaryAnimation, ) => widget, transitionsBuilder: transitionsBuilder, ); final Widget widget;}Widget transitionsBuilder( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child,) { var _animation = Tween<double>( begin: 0, end: 100, ).animate(animation); return SlideTransition( position: Tween<Offset>( begin: const Offset(0, 1), end: Offset.zero, ).animate(animation), child: Container( child: child, ), );} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/60897831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11404869/']} | jdg_72897 |
stackexchange | llm_judgeable_groundtruth_similarity | 34731 |
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:
Would someone be able to tell me what the dimension is of the following vector space? The space consists of all $C^2$ functions $f: [a,b]\longrightarrow\mathbb{C}$ which, for pre-specified real $\alpha_1,\alpha_2,\beta_1,\beta_2$, meet the conditions: $$\alpha_1f(a)-\alpha_2f'(a)=0,\qquad\beta_1f(b)-\beta_2f'(b)=0$$ I hope you can help.Thank you.
Now provide the response and nothing else.
| Your space is the kernel of the linear map $C^2 \to \mathbb{C}^2$ given by $f \mapsto \begin{bmatrix} \alpha_1 f(a) - \alpha_2 f'(a) \\\ \beta_1 f(b) - \beta_2 f'(b)\end{bmatrix}.$ Since $C^2$ is obviously infinite-dimensional (the dimension is $\mathfrak{c} = 2^{\aleph_0}$), the kernel of this map has co-dimension at most two, so it must be infinite-dimensional as well. As Willie states in his comment, this question becomes much more interesting when the functions $f$ are subject to some differential equation. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/34731', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9769/']} | jdg_72898 |
stackexchange | llm_judgeable_groundtruth_similarity | 7909986 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Will Apple accept Apps for selling inside the App-Store with deprecated code?
Now provide the response and nothing else.
| Yes. Deprecated doesn't mean unavailable or disallowed; if it did, it would be called something else, or those methods would simply be removed from the API. Deprecation is a way of letting you know that you should start transitioning your existing codebase. The rule of thumb should be: don't add code that you know uses deprecated functionality, that's just silly. Be aware as you work on older code bases that deprecated methods you were using may need your attention sooner or later. One of the risks of continuing to use deprecated methods is that they may be more primitive and dangerous than newer versions, may not take into account all current OS realities, and possibly less well tested by Apple over time. You run the risk of having this bite you even before they vanish from the framework. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7909986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/995888/']} | jdg_72899 |
stackexchange | llm_judgeable_groundtruth_similarity | 338625 |
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:
P-adic numbers are complete in one sense and incomplete in another sense. Is it so? Firstly, does not complete mean connected? I read somewhere that there is not intermediate value theorem for p-adics because they are not connected. (if I am correct). It seems I need elaboration of this "It can be shown that the rationals, together with the $p$-adic metric, do not form a complete metric space. The completion of this space can therefore be constructed, and the set of $p$-adic numbers $\mathbb{Q}_p$is defined to be this completed space." Math World . How is the completion constructed with same metric and same numbers?
Now provide the response and nothing else.
| To see that $\mathbb Q$ is incomplete under the $p$-adic valuation, it suffices to find an element of $\mathbb Q_p$ not in the rationals. For $p=2$, $\sqrt{-7}$ will do, for $p=3$, $\sqrt7$ will do, and for $p>3$, the field $\mathbb Q_p$ contains all $p-1$ roots of unity of order $p-1$. The existence of these irrationalities in the $p$-adics drops out of Hensel’s Lemma, the basic fact of $p$-adic life. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/338625', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_72900 |
stackexchange | llm_judgeable_groundtruth_similarity | 16910604 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When i start working on new project, i find big issuse.Main.phtml layout executed 26 times for every page. <?= $this->doctype() ?><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US"> <? $adapter = new Zend_Db_Adapter_Pdo_Mysql(array( 'host' => 'xxx', 'username' => 'xxx', 'password' => 'xxx', 'dbname' => 'xxx' )); $adapter->query('SET NAMES UTF8'); $debug = $adapter->select() ->from (array ('d'=>'debug')) ->where ('id = ?',1) ->query() ->fetchAll(); $pageCount = $debug [0] ['page']; $pageCount +=1; $debug [0]['page'] = $pageCount; $adapter ->update('debug', $debug [0], $debug [0] ['id']);?> <head> <?= $this->headMeta() ?> <?= $this->headTitle() ?> <?= $this->headScript() ?> <?= $this->headLink() ?> <?= $this->headStyle() ?> I put count in head of that layout for check it value in database. 26 times for every page!So i have questions about Zend.1. How many times one layout for one page must be executed?2. Where i can find part, who realy call that layout? frompublic/index.php. {main}:37tozend->view->_run:105 It all what i can find in callstack, it going 26 times on every page. bootstrap <?phpclass Bootstrap extends ExtZF_Application_Bootstrap_Bootstrap{ protected function _initAutoload() { $moduleAutoloader = new Zend_Application_Module_Autoloader(array( 'namespace' => '', 'basePath' => realpath(dirname(__FILE__) . '/..'), )); $moduleAutoloader->addResourceTypes(array( 'core' => array( 'namespace' => 'Core', 'path' => 'core' ) )); } protected function _initConfig() { $this->bootstrap('frontController'); $router = new Zend_Controller_Router_Rewrite(); $request = new Zend_Controller_Request_Http(); $router->route($request); $module = $request->getModuleName(); $configPath = realpath(dirname(__FILE__) . '/..') . '/configs/modules/' . $module . '.ini'; $config = new Zend_Config_Ini( $configPath, APPLICATION_ENV ); $this->setOptions($config->toArray()); } protected function _initSettings() { $this->_bootstrap('db'); $settingsGateway = new Model_SettingOption_Gateway(); $settings = $settingsGateway->fetch()->toConfig(); App::getConfig()->merge($settings); } protected function _initCache() { $this->_bootstrap('cachemanager'); Zend_Db_Table_Abstract::setDefaultMetadataCache( App::getCacheManager()->getCache('database')); Zend_Locale::setCache( App::getCacheManager()->getCache('default')); } public function _initRoutes() { $this->bootstrap('locale'); $langRoute = new Zend_Controller_Router_Route( ':lang', array( 'lang' => '', 'module' => 'default', 'controller' => 'index', 'action' => 'index' ), array( 'lang' => "^(ru|en)$" ) ); $defaultRoute = new Zend_Controller_Router_Route_Module( array( 'module' => 'default', 'controller' => 'index', 'action' => 'index' ) ); $defaultRoute = $langRoute->chain($defaultRoute); $router = $this->getResource('FrontController')->getRouter(); $router->addRoute('langRoute', $langRoute); $router->addRoute('defaultRoute', $defaultRoute); } protected function _initPlugins() { $frontController = Zend_Controller_Front::getInstance(); $frontController->registerPlugin(new Plugin_ContextAction()) ->registerPlugin(new Plugin_ErrorHandler()) ->registerPlugin(new Plugin_Ssl()) ->registerPlugin(new Plugin_View()); } protected function _initViewHelpers() { ExtZF_Grid::setCellPartial('_partials/grid/cell.phtml'); ExtZF_Grid::setRowPartial('_partials/grid/row.phtml'); ExtZF_Grid::setHeaderPartial('_partials/grid/header.phtml'); ExtZF_Grid::setTablePartial('_partials/grid/table.phtml'); ExtZF_Grid::setHeaderSortPartial('_partials/grid/header-sort.phtml'); ExtZF_Grid::setCheckBoxPartial('_partials/grid/check-box.phtml'); ExtZF_Grid::setFormPartial('_partials/grid/form.phtml'); ExtZF_Grid::setTextFilterPartial('_partials/grid/textFilter.phtml'); ExtZF_Grid::setRangeFilterPartial('_partials/grid/rangeFilter.phtml'); ExtZF_Grid::setSelectFilterPartial('_partials/grid/selectFilter.phtml'); ExtZF_Grid::setFilterButtonsPartial('_partials/grid/filterButtons.phtml'); ExtZF_Grid::setMassActionsPartial('_partials/grid/massActions.phtml'); } protected function _initHelpers() { Zend_Controller_Action_HelperBroker::addPath( 'ExtZF/Controller/Action/Helper/', 'ExtZF_Controller_Action_Helper' ); }} IndexController class IndexController extends Zend_Controller_Action{ public function init() { } public function indexAction() { }} index.php <?php// Define path to application directorydefined('APPLICATION_PATH') || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));// Define application environmentdefined('APPLICATION_ENV') || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));set_include_path( implode(PATH_SEPARATOR, array( realpath(APPLICATION_PATH . '/../library'), realpath(APPLICATION_PATH . '/../library/ExtZF'), get_include_path() ))); // Zend_Applicationrequire_once 'Zend/Application.php';require_once 'Zend/Config/Ini.php';require_once APPLICATION_PATH . '/App.php';// Set configuration$config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV, true);App::setConfig($config);// Create application, bootstrap, and run$application = new Zend_Application( APPLICATION_ENV, $config);$application->bootstrap() ->run();
Now provide the response and nothing else.
| In both function calls, what you pass to the function is an int & (in the sense of: "an lvalue of type int "). So, presented with the declaration of inc1 , the compiler must deduce T such that T && matches the argument you provided, i.e. int & . The only way to do this is to assume that T is int & , because then T && is int & && , which is equivalent to int & . So T becomes int & and the local y is declared as such. On the other hand, in inc2 , the compiler must deduce T such that T & matches the argument type you provided, which is still int & . That's easiest done by assuming T is simply int , so that's what you get for the type of the local y then. Reply to a few comments (that have meanwhile been deleted): If you have a function with a predefined argument type, such as inc3(int x) { /*...*/ } then, when you call this e.g. as inc3(a) , the compiler will apply whatever implicit conversion necessary to the argument to make it fit. In the case of inc3(a) this means to transform a from int & (in the sense of lvalue) to int (in the sense of rvalue) – which is called lvalue-to-rvalue conversion and a valid implicit conversion. It basically amounts to transforming the variable a into the value it represents at that time. But when you declare a template , such as inc1 and inc2 from the question, and the function argument is defined in terms of a template parameter, then the compiler will not, or not only, try to apply implicit conversions to the argument to make it fit. Instead, it will choose the argument type parameter T so it matches the argument type you provided. The rules for this are complicated, but in the case of a T && type argument declaration, they work as described above. (In the case of a pure T argument declaration, an lvalue argument will still undergo lvalue-to-rvalue conversion, and T will be deduced as int , not int & .) This is why, while int && is an rvalue reference, T && (where T is a template parameter) is not necessarily an rvalue reference. Instead, it is whatever results from fitting T to the argument provided. The expression T && in this case has therefore been called universal reference (as oppossed to lvalue or rvalue reference) – it is a reference that becomes either an lvalue or rvalue one, as necessary. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16910604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2190357/']} | jdg_72901 |
stackexchange | llm_judgeable_groundtruth_similarity | 2436762 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
They're both resizable arrays, and std::basic_string doesn't have any specifically character-related functions like upper(). What's special about string to make it better for character data?
Now provide the response and nothing else.
| Most of the reason has to do with localization and internationalization (L10I18),performance and for historical reasons. For the L10I18 issues, char_traits was added, and you will note that streams has these as well. The intent was to make "smarter characters" in a way, but the outcome was useless. About the only thing char_traits is good for is to specialize some of the std::string/wstring compares, copies, etc as compiler intrinsics. The failure is mostly due to UNIX streams themselves, which see the character as the main "atom" where in GUIs, web etc that are internationalized the string is the main "atom." In other words, in C/C++ land, we have "dumb arrays of smart characters" for strings, whereas every other language uses "smart arrays of dumb characters." Unicode takes the latter approach. Another big difference between basic_string and vector -- basic_string can only contain POD types. This can make a difference in some cases somoetime the compiler has an easier time optimizing basic_string compared to vector. basic_string sometimes has many other optimization, such as Copy on Write and Small String Optimization. These vary from one implementation to the next. However probably the most reason there are two things nearly the same is historical: strings predates the STL quite a bit, and most of the work seemed to center on making them interoperate with IOStream library. One C++ Urban Myth is that STL is a "container library" that was added to C++. It is not, and to get it adopted into C++, containers were added. An "STL Interface" was also bolted onto the existing string class. std::vector was largely taken from a vector implemenation that existed in the AdaSTL. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2436762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/287586/']} | jdg_72902 |
stackexchange | llm_judgeable_groundtruth_similarity | 9300941 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Adding two empty arrays: [] + [] results in an empty string. Why?
Now provide the response and nothing else.
| The + operator only exists for numbers and strings. When you use it on another type, JavaScript tries to convert the type (first to string, then int). When arrays are casts to strings, they are output as comma-separated strings. So, [] + [] => "" + "" => "" . Another example: [1,2] + [3,4] => "1,2" + "3,4" => "1,23,4" Relevant Spec: https://tc39.es/ecma262/#sec-addition-operator-plus | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9300941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275249/']} | jdg_72903 |
stackexchange | llm_judgeable_groundtruth_similarity | 5967564 |
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 including some forms inside a HTML table to add new rows and update current rows. The problem that I'm getting is that when I inspect the forms in my dev tools, I see that the form elements are closed immediately after opening (inputs, etc are not included within the form). As such, submitting a form fails to include the fields. The table row and inputs are as follows: <tr> <form method="post" action=""> <td> <input type="text" name="job_num"> </td> <td> <input type="text" name="desc"> </td> </form></tr> Any help would be great, thank you.
Now provide the response and nothing else.
| A form is not allowed to be a child element of a table , tbody or tr . Attempting to put one there will tend to cause the browser to move the form to it appears after the table (while leaving its contents — table rows, table cells, inputs, etc — behind). You can have an entire table inside a form. You can have a form inside a table cell. You cannot have part of a table inside a form. Use one form around the entire table. Then either use the clicked submit button to determine which row to process (to be quick) or process every row (allowing bulk updates). HTML 5 introduces the form attribute . This allows you to provide one form per row outside the table and then associate all the form control in a given row with one of those forms using its id . | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5967564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/687581/']} | jdg_72904 |
stackexchange | llm_judgeable_groundtruth_similarity | 16107713 |
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 the following CSS: td: hover { background-color:red; } td { cursor: pointer; background-color: rgb(150,150,150); } and my HTML is just: <table><tr><td> </td></tr></table> I can't get the hover to work. Why is that?
Now provide the response and nothing else.
| :hover is a pseudo-selector, and everything beginning with : is such (e.g. :active , :before etc.). This can be confused with specifying values: something: value; So you need to think about pseudo-selectors as separate objects, not a value. That's why you need to fix your td: hover so it looks like td:hover . Note that if you put a space after td like so: td :hover { ... This is equal to: td: *:hover { ... and therefore will select all items descending from td and apply a style on hover to them ( see this example ). Remember, spaces have a meaning in CSS. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16107713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2107544/']} | jdg_72905 |
stackexchange | llm_judgeable_groundtruth_similarity | 666035 |
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:
I'm not planning to shoot any astronauts, but researching a problem for a story. Picture a rotating centrifuge in space, spun to generate artificial gravity, like so: https://media.wired.com/photos/5b33cf8f8d9ebd40cd3edeee/master/w_1600%2Cc_limit/rotatingspacecraft1.png What I want to happen is to have this spinning at the right rate so that a bullet fired from a typical handgun will travel in a path maintaining constant height above the floor (where a person would be standing),completing at least one orbit before atmospheric affects cause it to fall. For this to happen, the bullet must be travelling in the direction opposite to the spin direction--the coriolis effect will cause it to drift away from the "floor", so that it drifts upwards. My initial assumption is that this will work if the bullet's velocity matches the rim velocity of the centrifuge. A quick calculation ( http://www.artificial-gravity.com/sw/SpinCalc/SpinCalc.htm ) tells me that this can work just fine--with a bullet velocity of ~200 m/s for a typical pistol, this would work in a centrifuge of a radius if 4 km or so. Big, of course, but not outside the realms of possibility or comfort, and it would give it a reasonable speed of half a rotation per minute. But what I'm not sure about is the atmospheric affects. How much will drag on a bullet move it off its initial course? Does this need to happen in a vacuum to work? Are there any errors in my assumption that make this impossible? Any help would be appreciated. Edit: This image illustrates what I'm talking about. (Source: https://oikofuge.com/coriolis-effect-rotating-space-habitat/ ) The projectile to an outside observer would appear to be stationary. Which is bad news for anyone firing bullets in this thing. This and other sources seem to confirm my thinking. Am I reading them right?
Now provide the response and nothing else.
| I think you're right that atmospheric effects are an issue. This is easiest to see if you picture the situation in a non-rotating reference frame. In that case, just after the bullet is fired it is stationary in space. However, it is inside a 4km radius rotating habitat, and the rim of the habitat is moving relative to it at exactly the speed of a speeding bullet. That means the air is moving past it at that speed as well. So the situation is analogous to a single bullet in a wind tunnel, exposed to 200 m/s wind speeds. The bullet is stationary initially but it's not going to stay that way for long. The bullet has aerodynamics on its side (it's pointing into the wind and designed to travel far), but given the size and speed of the habitat it will take a couple of minutes to complete a full revolution, and that's really more than enough time for the wind to start the bullet moving, which will cause it to crash into the side due to its inertia. (For someone inside the habitat, in the rotating reference frame, that corresponds to the bullet slowing down and falling.) On the other hand, if the shooter aims high it might be possible for this effect to be canceled out. The bullet wouldn't be stationary but would still end up back at its starting position. I don't know anything about guns, but in the rotating reference frame it has to travel about 25 km around the whole rim, so you would need one that's capable of that kind of range. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/666035', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/313889/']} | jdg_72906 |
stackexchange | llm_judgeable_groundtruth_similarity | 6732351 |
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 implement a quiz application. The application loads the questions with ajax one by one. When a user clicks the 'to next question' button his/her answer is saved in cache. But when I debug, cache list is always null... This code creates the first cache array: public static void viewQuiz(@Required String user, @Required String test) { if(validation.hasErrors()) { flash.error("Hoop kullanıcı lazım…"); index(); } else{ TestClass selectedTest = TestClass.find("title", test).first(); List<String> choiceList = new ArrayList<String>(); session.put("testID", selectedTest.id); Cache.set("choices", choiceList, "30mn"); render(); } } And this code is trying to save the answers one by one: public static void question(@Required Long id, String answer){ Long testId = Long.parseLong(session.get("testID")); TestClass test = TestClass.findById(testId); List<Question> questList = Question.find("test_id", test.id.intValue()).fetch(); Question quest = questList.get(id.intValue()); if(answer != null){ List<String> choiceList= Cache.get("choices",List.class); choiceList.add(id.intValue(), answer); Cache.set("choices", choiceList, "30mn"); } int count = questList.size()-1; render(quest, count, id);} And this code is the html view of the second: #{extends 'main.html' /}#{set title:'question.html' /}<script type="text/javascript"> var questionId = ${id}; $('#nextButton').click(function(){ $('#questionDiv').html('<p><img id = "loaderGif" src="public/images/loading.gif"/></p>'); $('#questionDiv').load("/test/" + ++questionId); }); $('#endButton').click(function(){ $('#questionDiv').html('<p><img id = "loaderGif" src="public/images/loading.gif"/></p>'); $('#questionDiv').load("/result"); }); </script> <legend>Soru ${id+1}</legend><p>&{quest.question}</p>#{list items:quest.choices, as:'choice'} <p><input type="radio" name = "answer" id = "answer" size="30" value="${choice}"/>&{choice}</p>#{/list}#{if id < count}<input id = "nextButton" name="nextButton" type="button" value="İleri"/>#{/if}#{else}<input id = "endButton" name="endButton" type="button" value="Bitti"/>#{/else}
Now provide the response and nothing else.
| Don't use the cache to 'store' objects. Either store it in the session or create a new model to store the answers. Generally, you cannot expect the cache to retain the objects you put into; it's a cache, not a store. To quote from the Play! website: http://www.playframework.org/documentation/1.2.2/cache It is important to understand that the cache contract is clear: when you put data in a cache, you can’t expect that data to remain there forever. In fact you shouldn’t. A cache is fast, but values expire, and the cache generally exists only in memory (without persistent backup). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6732351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/819013/']} | jdg_72907 |
stackexchange | llm_judgeable_groundtruth_similarity | 3500910 |
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 there exists the same question with answer anywhere, plz delete this one, i didn't find one. If $f$ is continuous on $\Bbb R$ and uniformly continuous on every $(a,b)$ so it is also uniformly continuous on $\Bbb R$ I think the statement is correct. My attempt: I think it is not true, since it can be that in every interval $(a,b)$ i can have a different gradient, which is constant for every interval, therefore, every interval has a finite $\delta > 0$ but with infinity number of intervals, each one may have a bigger gradient, in this case, i wont find $\delta > 0$ which is not dependent on $x$ . Therefore, the statment is not correct for every $f$ . Do i correct? Thank you.
Now provide the response and nothing else.
| The statement is false. Consider $f(x) = x^2$ . Observe $f$ is continuous on $\mathbb{R}$ and \begin{align}|x^2-y^2|\leq |x+y||x-y|\leq 2\max(|a|, |b|)|x-y|\end{align} for all $x, y \in (a, b)$ , i.e. $f$ is uniformly continuous on $(a, b)$ . But is clear that $f$ is not uniformly continuous on $\mathbb{R}$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3500910', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/651938/']} | jdg_72908 |
stackexchange | llm_judgeable_groundtruth_similarity | 27246003 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently, I found lots of deadlock errors in my application. Mysql2::Error: Deadlock found when trying to get lock; try restarting transaction: INSERT INTO `products`.... the code as below: After user has been created, I will add some products to user. I don't understand why deadlock happened. class User < ActiveRecord::Base after_create :add_products has_many :products, :dependent => :destroy def self.create_user User.create!(.......) end def add_products Product.add(self, "product_name", 10) end .....endclass Product < ActiveRecord::Base belongs_to :user def self.add(user, product_name, amount) transaction do product = user.products.find_by_product_name(product_name) if product product.increment :amount, amount product.save! else product = self.create! user_id: user.id, product_name: product_name, amount: amount end end product endend I didn't find the root cause, can anyone give me some advice? Thanks in advance!!!
Now provide the response and nothing else.
| My guess is that you are using InnoDB and probably doing concurrent insertions. To trace and understand the cause, check out these articles: MySQL deadlocks with concurrent inserts How can I configure MySQL Innodb to handle 1000s of inserts per hour? One way to fix the issue is to retry like it is shown in the code below: def add_products retries = 0 begin Product.add(self, "product_name", 10) rescue ActiveRecord::StatementInvalid => ex if ex.message =~ /Deadlock found when trying to get lock/ #ex not e!! retries += 1 raise ex if retries > 3 ## max 3 retries sleep 10 retry else raise ex end endend Or, there are some gems like transaction_retry to handle MySQL deadlocks. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27246003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1805902/']} | jdg_72909 |
stackexchange | llm_judgeable_groundtruth_similarity | 23302759 |
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 make class visible-lg not to move the span to a new line? The following HTML renders as one line: <p>Device is:<span>Unknown</span></p> However , the following HTML renders Large on the line below Device is : <p>Device is:<span class="visible-lg">Large</span></p>
Now provide the response and nothing else.
| Update for Bootstrap v3.2.0 This is now natively solved in Bootstrap v3.2.0 with this commit According to the responsive classes documentation : As of v3.2.0, the .visible- - classes for each breakpoint come in three variations, one for each CSS display property value listed below: Group of classes | CSS display .visible-*-block | display: block; .visible-*-inline | display: inline; .visible-*-inline-block | display: inline-block; So in your case, you'd want to use: <p>Device is:<span class=" visible-lg-inline ">Large</span></p> Original for Bootstrap v3.0 In Bootstrap 3.0, all visible and hidden responsive classes use display:block !important; You'll have to override that if you want to display elements inline: @media (min-width: 1200px) { span.visible-lg { display: inline !important }} Working Demo in jsFiddle For a more robust approach, here is a library that adds extension classes for each display type Other Instances Asked about on Stackoverflow: Bootstrap3 .visible-* .hidden-* display inline Reported in Bootstrap Issues: #4929 - Responsive utility classes may cause unexpected wrapping #7808 - Using display inherit in responsive utilities causes elements to be wrongly displayed #8500 - responsive class usage with inline element #8869 - responsive .hidden-* classes change from display block to inline-block #10263 - visible-xs makes display=block even for inline elements | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23302759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1390930/']} | jdg_72910 |
stackexchange | llm_judgeable_groundtruth_similarity | 49749786 |
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 confusing of using exception: IllegalStateException vs UnsupportedOperationException . I have a delete method which in some cases do not allow to use: let's say when the caller has a valid data on it. Then I should give an exception info to user that he is doing an invalid operation now. So, which exception should I throw? IllegalStateException or UnsupportedOperationException . I know I can give the detail message using any of them, but I still want to know which one is better in my case. From JavaDoc: IllegalStateException: Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation. UnsupportedOperationException: Thrown to indicate that the requested operation is not supported.
Now provide the response and nothing else.
| UnsupportedOperationException should be used as the method is not supported at all while IllegalStateException should be used as the method is supported but that in the current state, it is not legal. The Iterator classes are good candidates to illustrate the difference between these two exceptions. Iterator implements remove() in a default method by throwing a UnsupportedOperationException : public interface Iterator<E> { ... default void remove() { throw new UnsupportedOperationException("remove"); } ...} The method is indeed never supported by implementations that don't override this method to support it. About implementations, we can see that the Iterator implementation used by the ArrayList class overrides remove() to support it. So UnsupportedOperationException is not thrown any longer. On the other hand, we can also see that the method throws an IllegalStateException if you invoke it while you never invoked next() to make progress the iterator to the next element : private class Itr implements Iterator<E> { ... public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } ... }} The method is so supported by this implementation but if you invoke it in a illegal state, an IllegalStateException is thrown. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49749786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9254461/']} | jdg_72911 |
stackexchange | llm_judgeable_groundtruth_similarity | 16210363 |
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 use Moq to make some tests for Entity Framework Code First classes. I'm very new to Moq and mocking techniques and I wonder if it's possible to easily do a test that I will describe below. I searched through the web for some solutions, but most are based on repository pattern, which I want to avoid. I have ITestEntities interface for context public interface ITestEntities{ IDbSet<Order> Orders { get; } IDbSet<Product> Products { get; } IDbSet<User> Users { get; }} Then context public class TestEntities : DbContext, ITestEntities{ public TestEntities() : base("name=TestEntities") { } public virtual IDbSet<Order> Orders { get; set; } public virtual IDbSet<Product> Products { get; set; } public virtual IDbSet<User> Users { get; set; }} A controller and an action to test public class HomeController : Controller{ private ITestEntities db; public HomeController() { db = new TestEntities(); } public HomeController(ITestEntities db) { this.db = db; } public ActionResult Index() { var count = db.Users.Count(); ViewBag.count = count; return View(count); } } And finally a NUnit test using Moq [Test]public void ModelValueShouldBeTwo(){ var mockUsers = new Mock<IDbSet<User>>(); mockUsers.Setup(m => m.Count()).Returns(2); var mockDB = new Mock<ITestEntities>(); mockDB.Setup(db => db.Users).Returns((IDbSet<User>)mockUsers); var controller = new HomeController((ITestEntities)mockDB); var view = controller.Index(); Assert.IsInstanceOf<ViewResult>(view); Assert.AreEqual(((ViewResult)view).Model, 2);} The problem is with this line: mockUsers.Setup(m => m.Count()).Returns(2); . When running this test I get following error: System.NotSupportedException : Expression references a method that does not belong to the mocked object: m => m.Count<User>() I think this is due to .Count() being a static method so it cannot be mocked by Moq. Is there a way to test this simple action using Moq and not using full-fledged repository pattern, which as I understand should anyway have this .Count() part hardcoded into some method to be testable... Maybe I just use the mocks in a wrong way? Because I have impression that this should be quite simple and possible with EF Code First.
Now provide the response and nothing else.
| If you are mocking the test entities you don't need to mock any further down the chain Something like this should do (although, I 'm not at an IDE so may need some tweaking) Update to include new InMemoryDbSet [Test]public void ModelValueShouldBeTwo(){ //Build test users var mockUsers = new InMemoryDbSet<User>(){ new User(), new User()}; var mockDB = new Mock<ITestEntities>(); //Set up mock entities to returntest users. mockDB.Setup(db => db.Users).Returns(mockUsers); var controller = new HomeController((ITestEntities)mockDB); var view = controller.Index(); Assert.IsInstanceOf<ViewResult>(view); Assert.AreEqual(((ViewResult)view).Model, 2);} This will mean the extension methods will simply work off of the test data you have supplied. See below for a good article on mocking dbset http://geekswithblogs.net/Aligned/archive/2012/12/12/mocking-or-faking-dbset.aspx | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16210363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/219547/']} | jdg_72912 |
stackexchange | llm_judgeable_groundtruth_similarity | 3011715 |
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 Rails application server that is listening on port 9000, and is being called through haproxy. All my redirects from that server are being redirected back through port 9000, when they should be sent back on port 80. I am using a combination of haproxy + nginx + passenger. Is there a way to make sure all redirects are being sent through port 80, regardless of what port the actual server is listening on? I don't care if its a haproxy, nginx, Passenger, or Rails change. I just need to make sure most requests unless specified otherwise, are sent back to port 80. Thanks!
Now provide the response and nothing else.
| Like elektronaut indicated, this is probably something that should be handled in your proxy's configuration. That said, ActiveSupport::UrlFor#url_for has some information that might be useful. Take a look at http://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/url_for.rb What I think it boils down to is passing two arguments into your url_for and/or link_to calls. First is the :port => 123 argument, the second is :only_path => false so that it generates the full link including domain, port, etc. So when generating a link, you might do: link_to 'test', root_url(:port => 80, :only_path => false) and when creating a custom url you might do: url_for :controller => 'test', :action => 'index', :port => 80, :only_path => false For a redirect: redirect_to root_url(:port => 80, :only_path => false) I hope this helps, and if it doesn't, can you be more specific about how you generating your URLs, what rails is generating for you, and what you would like it to generate. Update: I wasn't aware of this, but it seems you can set defaults for the URL's rails generates with url_for, which is used by everything else that generates links and/or URLs. There is a good write up about it here: http://lucastej.blogspot.com/2008/01/ruby-on-rails-how-to-set-urlfor.html Or to sum it up for you: Add this to your application_controler.rb def default_url_options(options) { :only_path => false, :port => 80 }end and this: helper_method :url_for The first block sets defaults in the controllers, the second causes the url_for helper to use the one found in the controllers, so the defaults apply to that as well. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3011715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59220/']} | jdg_72913 |
stackexchange | llm_judgeable_groundtruth_similarity | 21431459 |
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 access the post data sent from VB.net in PHP. But the POST data seems to be empty. I don't know much about vb.net. vb.net code Imports System.NetImports System.TextImports System.IOImports System.Net.NetworkInformationImports System.Net.SocketsImports Microsoft.Win32Imports System.Security.CryptographyImports System.Net.SecurityPublic Class frmRegistrationDim xx As IntegerDim yy As IntegerPrivate Sub txtPhoneNo_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtPhoneNo.KeyPress Select Case e.KeyChar Case "0" To "9" Case vbBack Case Else e.KeyChar = "" End SelectEnd SubPrivate Function UrlSend(ByRef url As String) Dim reader As StreamReader Dim resUri As String Dim req As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest) Try Dim Res As HttpWebResponse = req.GetResponse() Dim response As HttpWebResponse response = req.GetResponse resUri = response.ResponseUri.AbsoluteUri reader = New StreamReader(response.GetResponseStream()) resUri = reader.ReadToEnd() Return resUri Catch ex As Exception Return ex.Message End TryEnd Function'Function Send(ByRef url As String, ByVal key As String) As String' Dim TID = key' Try' Dim request As WebRequest = WebRequest.Create(url)' request.Method = "POST"' Dim byteArray As Byte() = Encoding.UTF8.GetBytes(TID)' request.ContentType = "application/x-www-form-urlencoded"' request.ContentLength = byteArray.Length' Dim dataStream As Stream = request.GetRequestStream()' dataStream.Write(byteArray, 0, byteArray.Length)' dataStream.Close()' Dim response As WebResponse = request.GetResponse()' dataStream = response.GetResponseStream()' Dim reader As New StreamReader(dataStream)' Dim responseFromServer As String = reader.ReadToEnd()' reader.Close()' dataStream.Close()' response.Close()' Return responseFromServer' Catch ex As Exception' If Ping_Internet("www.google.com") = 1 Then' MsgBox("Server not responding. Please try later.")' End If' Me.Close()' End' Return DBNull.Value.ToString' End Try'End FunctionPublic Function Ping_Internet(ByVal Activeurl As String) As Integer Dim contact As String Try contact = My.Settings("TollFree").ToString Dim strip = System.Net.Dns.GetHostEntry(Activeurl).AddressList(0).ToString Dim ping As New System.Net.NetworkInformation.Ping If ping.Send(strip).Status = IPStatus.Success Then Return 1 Else MsgBox("You are not connected to the Internet. If you are unable to get connected, contact us for help on our toll-free number(" & contact & ") at any time. ") End End If Catch ex As Exception MsgBox("You are not connected to the Internet. If you are unable to get connected, contact us for help on our toll-free number(" & contact & ") at any time. ") End End Try Return 0End FunctionFunction Domain_Check(ByVal emailid As String) As Boolean If emailid.Contains("@") Then Dim Domain As String() = emailid.Split("@") Dim br As Boolean Try Dim ipHost As IPHostEntry = Dns.GetHostEntry(Domain(1)) br = True Return br Catch se As SocketException br = False Return br End Try Else Return False End IfEnd FunctionFunction IsValidEmailFormat(ByVal s As String) As Boolean Try Dim a As New System.Net.Mail.MailAddress(s) Catch Return False End Try If Domain_Check(s) = True Then Return True End If Return TrueEnd FunctionPrivate Sub pnlOk_Click(sender As System.Object, e As System.EventArgs) Handles pnlOk.Click If txtName.Text = "" Then MsgBox("Please Enter Your Name!") txtName.Focus() Exit Sub ElseIf txtPhoneNo.Text = "" Then MsgBox("Please Enter Your Phone Number!") txtPhoneNo.Focus() Exit Sub ElseIf IsValidEmailFormat(txtEmail.Text.ToString.Trim) = False Then MsgBox("Please Enter a Valid Email Id!") txtEmail.Focus() Exit Sub ElseIf txtKey.Text = "" Then MsgBox("Please Enter Product Key Which Was Provided In Your Mail!") txtKey.Focus() Exit Sub End If Dim url = My.Settings("checkkey").ToString Dim key = "rqtoken=" & txtEmail.Text.Trim & "|" & txtKey.Text.Trim Dim resp = UrlSend(url & "?" & key).ToString.Trim If resp = "OK" Then Setregistry() Else MsgBox(resp) End IfEnd SubPrivate Sub Setregistry() Try If WinVersion() Then Registry.LocalMachine.CreateSubKey("SOFTWARE\Microsoft\Windows\Services") End If Dim Fullmsg As String = txtName.Text.Trim & "|" & txtPhoneNo.Text.Trim & "|" & txtEmail.Text.Trim & "|" & txtKey.Text.Trim My.Computer.Registry.SetValue("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Services", "xxxxxxx", AESEncrypt(Fullmsg), Microsoft.Win32.RegistryValueKind.String) Application.Restart() Catch ex As Exception MsgBox(ex.ToString) End TryEnd SubPublic Function AESEncrypt(ByVal PlainText As String) As String Dim InitialVector As String = "CanEncryption123" If (String.IsNullOrEmpty(PlainText)) Then Return "" Exit Function End If Dim InitialVectorBytes As Byte() = Encoding.ASCII.GetBytes(InitialVector) Dim PlainTextBytes As Byte() = Encoding.UTF8.GetBytes(PlainText) Dim KeyBytes As Byte() = {Convert.ToByte(170), Convert.ToByte(89), Convert.ToByte(62), Convert.ToByte(253), Convert.ToByte(87), Convert.ToByte(232), Convert.ToByte(224), Convert.ToByte(53), Convert.ToByte(148), Convert.ToByte(2), Convert.ToByte(68), Convert.ToByte(185), Convert.ToByte(49), Convert.ToByte(60), Convert.ToByte(133), Convert.ToByte(82), Convert.ToByte(136), Convert.ToByte(27), Convert.ToByte(239), Convert.ToByte(160), Convert.ToByte(91), Convert.ToByte(67), Convert.ToByte(207), Convert.ToByte(233)} Dim SymmetricKey As RijndaelManaged = New RijndaelManaged() SymmetricKey.Mode = CipherMode.CBC Dim CipherTextBytes As Byte() = Nothing Using Encryptor As ICryptoTransform = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes) Using MemStream As New MemoryStream() Using CryptoStream As New CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write) CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length) CryptoStream.FlushFinalBlock() CipherTextBytes = MemStream.ToArray() MemStream.Close() CryptoStream.Close() End Using End Using End Using SymmetricKey.Clear() Return Convert.ToBase64String(CipherTextBytes)End FunctionPrivate Sub pnlCancel_Click(sender As System.Object, e As System.EventArgs) Handles pnlCancel.Click txtName.Text = "" txtPhoneNo.Text = "" txtEmail.Text = "" txtKey.Text = "" txtName.Focus()End SubPublic Function WinVersion() As Boolean Dim ver = Environment.OSVersion.Version.Major If ver > 5 Then Return True Else Return False End IfEnd FunctionPrivate Sub pnlOk_MouseEnter(sender As Object, e As System.EventArgs) Handles pnlOk.MouseEnter, pnlOk.MouseLeave If pnlOk.Tag = 1 Then pnlOk.BackgroundImage = My.Resources.ok_bttn_hover pnlOk.Tag = 2 ElseIf pnlOk.Tag = 2 Then pnlOk.BackgroundImage = My.Resources.ok_bttn pnlOk.Tag = 1 End IfEnd SubPrivate Sub pnlCancel_MouseEnter(sender As Object, e As System.EventArgs) Handles pnlCancel.MouseEnter, pnlCancel.MouseLeave If pnlCancel.Tag = 1 Then pnlCancel.BackgroundImage = My.Resources.cancel_bttn_hover pnlCancel.Tag = 2 ElseIf pnlCancel.Tag = 2 Then pnlCancel.BackgroundImage = My.Resources.cancel_bttn pnlCancel.Tag = 1 End IfEnd SubPrivate Sub pcbMin_Click(sender As System.Object, e As System.EventArgs) Handles pcbMin.Click Me.WindowState = FormWindowState.MinimizedEnd SubPrivate Sub pcbCross_Click(sender As System.Object, e As System.EventArgs) Handles pcbCross.Click EndEnd SubPrivate Sub pnlPan_MouseHover(sender As Object, e As System.EventArgs) Handles pnlPan.MouseHover xx = Windows.Forms.Cursor.Position.X - Me.Left yy = Windows.Forms.Cursor.Position.Y - Me.TopEnd SubPrivate Sub pnlPan_MouseMove(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles pnlPan.MouseMove If e.Button = Windows.Forms.MouseButtons.Left Then Me.Left = Windows.Forms.Cursor.Position.X - xx Me.Top = Windows.Forms.Cursor.Position.Y - yy Else xx = Windows.Forms.Cursor.Position.X - Me.Left yy = Windows.Forms.Cursor.Position.Y - Me.Top End IfEnd SubPrivate Sub Label3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label3.ClickEnd SubEnd Class<?xml version="1.0" encoding="utf-8" ?><configuration><configSections> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" > <section name="Reg_Scan.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" /> </sectionGroup></configSections><system.diagnostics> <sources> <!-- This section defines the logging configuration for My.Application.Log --> <source name="DefaultSource" switchName="DefaultSwitch"> <listeners> <add name="FileLog"/> <!-- Uncomment the below section to write to the Application Event Log --> <!--<add name="EventLog"/>--> </listeners> </source> </sources> <switches> <add name="DefaultSwitch" value="Information" /> </switches> <sharedListeners> <add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/> <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log --> <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> --> </sharedListeners></system.diagnostics><userSettings> <xxx_xxxx.My.MySettings> <setting name="TollFree" serializeAs="String"> <value /> </setting> <setting name="checkkey" serializeAs="String"> <value>http://www.xxxx.com/xxxx.php</value> </setting> </xxx_xxxx.My.MySettings></userSettings> Php code <?phpif($_POST){$email = $_POST["emailid"];$key = $_POST["key"];try {$conn = new PDO('mysql:host=localhost;dbname=xxx_xxx_xx', 'xxxxx', 'xxxxxx');$stmt = $conn->prepare("SELECT * FROM customer WHERE email=:email");$stmt->bindValue(':email', $email);$stmt->execute();$rows = $stmt->fetch(PDO::FETCH_OBJ);if ($rows > 0) {if ( $rows->license_key == $key ){echo 'OK'} else {echo 'Invalid License KeyPlease check your license key or Contact Support [email protected]';}} else {echo 'Invalid Email IDPlease check your Email ID or Contact Support [email protected]';}} catch(PDOException $e) {echo 'ERROR: ' . $e->getMessage();}}?> The php code is working fine as I tested it with an HTML form. Need help in finding why the vb.net form is not sending any post data.
Now provide the response and nothing else.
| Yes, you can create an AMI from an EC2 instance within a CloudFormation template by implementing a Custom Resource that calls the CreateImage API on create (and calls the DeregisterImage and DeleteSnapshot APIs on delete). Since AMIs can sometimes take a long time to create, a Lambda-backed Custom Resource will need to re-invoke itself if the wait has not completed before the Lambda function times out. Here's a complete example: Description: Create an AMI from an EC2 instance.Parameters: ImageId: Description: Image ID for base EC2 instance. Type: AWS::EC2::Image::Id # amzn-ami-hvm-2016.09.1.20161221-x86_64-gp2 Default: ami-9be6f38c InstanceType: Description: Instance type to launch EC2 instances. Type: String Default: m3.medium AllowedValues: [ m3.medium, m3.large, m3.xlarge, m3.2xlarge ]Resources: # Completes when the instance is fully provisioned and ready for AMI creation. AMICreate: Type: AWS::CloudFormation::WaitCondition CreationPolicy: ResourceSignal: Timeout: PT10M Instance: Type: AWS::EC2::Instance Properties: ImageId: !Ref ImageId InstanceType: !Ref InstanceType UserData: "Fn::Base64": !Sub | #!/bin/bash -x yum -y install mysql # provisioning example /opt/aws/bin/cfn-signal \ -e $? \ --stack ${AWS::StackName} \ --region ${AWS::Region} \ --resource AMICreate shutdown -h now AMI: Type: Custom::AMI DependsOn: AMICreate Properties: ServiceToken: !GetAtt AMIFunction.Arn InstanceId: !Ref Instance AMIFunction: Type: AWS::Lambda::Function Properties: Handler: index.handler Role: !GetAtt LambdaExecutionRole.Arn Code: ZipFile: !Sub | var response = require('cfn-response'); var AWS = require('aws-sdk'); exports.handler = function(event, context) { console.log("Request received:\n", JSON.stringify(event)); var physicalId = event.PhysicalResourceId; function success(data) { return response.send(event, context, response.SUCCESS, data, physicalId); } function failed(e) { return response.send(event, context, response.FAILED, e, physicalId); } // Call ec2.waitFor, continuing if not finished before Lambda function timeout. function wait(waiter) { console.log("Waiting: ", JSON.stringify(waiter)); event.waiter = waiter; event.PhysicalResourceId = physicalId; var request = ec2.waitFor(waiter.state, waiter.params); setTimeout(()=>{ request.abort(); console.log("Timeout reached, continuing function. Params:\n", JSON.stringify(event)); var lambda = new AWS.Lambda(); lambda.invoke({ FunctionName: context.invokedFunctionArn, InvocationType: 'Event', Payload: JSON.stringify(event) }).promise().then((data)=>context.done()).catch((err)=>context.fail(err)); }, context.getRemainingTimeInMillis() - 5000); return request.promise().catch((err)=> (err.code == 'RequestAbortedError') ? new Promise(()=>context.done()) : Promise.reject(err) ); } var ec2 = new AWS.EC2(), instanceId = event.ResourceProperties.InstanceId; if (event.waiter) { wait(event.waiter).then((data)=>success({})).catch((err)=>failed(err)); } else if (event.RequestType == 'Create' || event.RequestType == 'Update') { if (!instanceId) { failed('InstanceID required'); } ec2.waitFor('instanceStopped', {InstanceIds: [instanceId]}).promise() .then((data)=> ec2.createImage({ InstanceId: instanceId, Name: event.RequestId }).promise() ).then((data)=> wait({ state: 'imageAvailable', params: {ImageIds: [physicalId = data.ImageId]} }) ).then((data)=>success({})).catch((err)=>failed(err)); } else if (event.RequestType == 'Delete') { if (physicalId.indexOf('ami-') !== 0) { return success({});} ec2.describeImages({ImageIds: [physicalId]}).promise() .then((data)=> (data.Images.length == 0) ? success({}) : ec2.deregisterImage({ImageId: physicalId}).promise() ).then((data)=> ec2.describeSnapshots({Filters: [{ Name: 'description', Values: ["*" + physicalId + "*"] }]}).promise() ).then((data)=> (data.Snapshots.length === 0) ? success({}) : ec2.deleteSnapshot({SnapshotId: data.Snapshots[0].SnapshotId}).promise() ).then((data)=>success({})).catch((err)=>failed(err)); } }; Runtime: nodejs4.3 Timeout: 300 LambdaExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: {Service: [lambda.amazonaws.com]} Action: ['sts:AssumeRole'] Path: / ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole - arn:aws:iam::aws:policy/service-role/AWSLambdaRole Policies: - PolicyName: EC2Policy PolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Action: - 'ec2:DescribeInstances' - 'ec2:DescribeImages' - 'ec2:CreateImage' - 'ec2:DeregisterImage' - 'ec2:DescribeSnapshots' - 'ec2:DeleteSnapshot' Resource: ['*']Outputs: AMI: Value: !Ref AMI | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21431459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647351/']} | jdg_72914 |
stackexchange | llm_judgeable_groundtruth_similarity | 13590518 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Getting Django to send an email is nicely explained here using standard settings as shown below. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'EMAIL_HOST = "mail.mysmtpserver.somewhere"#EMAIL_PORTEMAIL_HOST_USER = "my@login"EMAIL_HOST_PASSWORD = "mypassword"#EMAIL_USE_TLS = True Then using django.core.mail.EmailMessage to send it of. How ever, what if you are running multiple sites and need each of these to send email through their own SMTP server (or just different login in the same SMTP server)? Searching for a EmailBackend like this or a way to do it with the current backend did not produce any satisfactory results.
Now provide the response and nothing else.
| If you want to override the provided settings you can just create your own connection and provide it to send_email or EmailMessage from django.core.mail import get_connection, send_mailfrom django.core.mail.message import EmailMessage# TODO: Insert clever settings mechanismmy_host = ''my_port = 587my_username = ''my_password = ''my_use_tls = Trueconnection = get_connection(host=my_host, port=my_port, username=my_username, password=my_password, use_tls=my_use_tls) send_mail('diditwork?', 'test message', 'from_email', ['to'], connection=connection)# orEmailMessage('diditwork?', 'test message', 'from_email', ['to'], connection=connection).send(fail_silently=False) Update: Make sure to close the connection after use, @michel.iamit answer points to code showing the connection is cached for smpt. @dhackner answer shows how to automatically close a connection using with statement. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13590518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/679281/']} | jdg_72915 |
stackexchange | llm_judgeable_groundtruth_similarity | 52290198 |
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 using three.js for graphical web project. I have many circles and it spread out like this. I wonder that, if distance between object and camera getting far, Can object's opacity to lower?(or fade out) Also if distance getting close, set object's opacity to higher(or fade in) I searched it in docs( https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene ), but there is no clear description. Is there any solution about this? Thanks.
Now provide the response and nothing else.
| Changing the opacity when the camera gets closer to an object is not possible with the default materials of three.js . But it's not hard to enhance the fragment shader of a material with the following line of code in order to achieve the desired effect: gl_FragColor.a *= pow( gl_FragCoord.z, f ); I have enhanced MeshNormalMaterial via onBeforeCompile() in the following demo. The idea is to gradually lower the opacity if objects come closer to the camera. You can control this transition process with the variable f . A high value means objects sooner start to get transparent. let camera, scene, renderer;init();animate();function init() { camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 50; scene = new THREE.Scene(); const geometry = new THREE.BoxBufferGeometry(2, 2, 2); const material = new THREE.MeshNormalMaterial({ transparent: true }); material.onBeforeCompile = function(shader) { shader.fragmentShader = shader.fragmentShader.replace( 'gl_FragColor = vec4( packNormalToRGB( normal ), opacity );', [ 'gl_FragColor = vec4( packNormalToRGB( normal ), opacity );', 'gl_FragColor.a *= pow( gl_FragCoord.z, 50.0 );', ].join('\n') ); }; for (let i = 0; i < 1000; i++) { const object = new THREE.Mesh(geometry, material); object.position.x = Math.random() * 80 - 40; object.position.y = Math.random() * 80 - 40; object.position.z = Math.random() * 80 - 40; object.rotation.x = Math.random() * 2 * Math.PI; object.rotation.y = Math.random() * 2 * Math.PI; object.rotation.z = Math.random() * 2 * Math.PI; object.scale.x = Math.random() + 0.5; object.scale.y = Math.random() + 0.5; object.scale.z = Math.random() + 0.5; scene.add(object); } renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); new THREE.OrbitControls(camera, renderer.domElement);}function animate() { requestAnimationFrame(animate); renderer.render(scene, camera);} body { margin: 0;} <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script><script src="https://cdn.jsdelivr.net/npm/[email protected]/examples/js/controls/OrbitControls.js"></script> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52290198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9328497/']} | jdg_72916 |
stackexchange | llm_judgeable_groundtruth_similarity | 110401 |
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:
A bullet looses (1/n)th of its velocity passing through one plank. The number of such planks that are required to stop the bullet can be? Logically, to me the answer seems to be infinity, as always a fraction of velocity will get reduced. But in my book the answer is n^2/(2n-1) (that comes from energy balance). What is correct?
Now provide the response and nothing else.
| Ayush: Isn't the question telling that the bullet always loses 1/n th of its velocity no matter which plank? Based on the answer provided, it seems the writer wanted you to assume that the energy loss per plank is constant. This is not the same as the bullet losing $1/n^\text{th}$ of its velocity per plank (however, the fact that the question does not mention this assumption arguably makes the question ambiguous). With this assumption, the energy loss becomes$$\Delta E=\frac{1}{2}mv^2-\frac{1}{2}m\left(v-\frac{v}{n}\right)^2$$and the number of planks $N$ becomes$$N=\frac{\frac{1}{2}mv^2}{\Delta E}=\frac{n^2}{2n-1}.$$ Otherwise, if you assume that the bullet loses $1/n^\text{th}$ of its velocity per plank, then the answer is $N=\infty$. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/110401', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/45446/']} | jdg_72917 |
stackexchange | llm_judgeable_groundtruth_similarity | 6940499 |
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 simple model which looks like this: class Group(models.Model): name = models.CharField(max_length = 100, blank=False) I would expect this to throw an integrity error, but it does not: group = Group() # name is an empty string heregroup.save() How can I make sure that the name variable is set to something non-empty? I.e to make the database reject any attempts to save an empty string?
Now provide the response and nothing else.
| From the Django docs in this case, your name will be stored as an empty string, because the null field option is False by default. if you want to define a custom default value, use the default field option. name = models.CharField(max_length=100, blank=False, default='somevalue') On this page, you can see that the blank is not database-related. Update: You should override the clean function of your model, to have custom validation, so your model def will be: class Group(models.Model): name = models.CharField(max_length=100, blank=False) def clean(self): from django.core.exceptions import ValidationError if self.name == '': raise ValidationError('Empty error message') Or you can replace ValidationError to something else. Then before you call group.save() call group.full_clean() which will call clean() Other validation related things are here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6940499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3608/']} | jdg_72918 |
stackexchange | llm_judgeable_groundtruth_similarity | 22284502 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a posterior p(Θ|D) over some parameters Θ, one can define the following: Highest Posterior Density Region: The Highest Posterior Density Region is the set of most probable values of Θ that, in total, constitute 100(1-α) % of the posterior mass. In other words, for a given α, we look for a p * that satisfies: and then obtain the Highest Posterior Density Region as the set: Central Credible Region: Using the same notation as above, a Credible Region (or interval) is defined as: Depending on the distribution, there could be many such intervals. The central credible interval is defined as a credible interval where there is (1-α)/2 mass on each tail . Computation: For general distributions, given samples from the distribution, are there any built-ins in to obtain the two quantities above in Python or PyMC ? For common parametric distributions (e.g. Beta, Gaussian, etc.) are there any built-ins or libraries to compute this using SciPy or statsmodels ?
Now provide the response and nothing else.
| From my understanding "central credible region" is not any different from how confidence intervals are calculated; all you need is the inverse of cdf function at alpha/2 and 1-alpha/2 ; in scipy this is called ppf ( percentage point function ); so as for Gaussian posterior distribution: >>> from scipy.stats import norm>>> alpha = .05>>> l, u = norm.ppf(alpha / 2), norm.ppf(1 - alpha / 2) to verify that [l, u] covers (1-alpha) of posterior density: >>> norm.cdf(u) - norm.cdf(l)0.94999999999999996 similarly for Beta posterior with say a=1 and b=3 : >>> from scipy.stats import beta>>> l, u = beta.ppf(alpha / 2, a=1, b=3), beta.ppf(1 - alpha / 2, a=1, b=3) and again: >>> beta.cdf(u, a=1, b=3) - beta.cdf(l, a=1, b=3)0.94999999999999996 here you can see parametric distributions that are included in scipy; and I guess all of them have ppf function; As for highest posterior density region, it is more tricky, since pdf function is not necessarily invertible; and in general such a region may not even be connected; for example, in the case of Beta with a = b = .5 ( as can be seen here ); But, in the case of Gaussian distribution, it is easy to see that "Highest Posterior Density Region" coincides with "Central Credible Region"; and I think that is is the case for all symmetric uni-modal distributions ( i.e. if pdf function is symmetric around the mode of distribution) A possible numerical approach for the general case would be binary search over the value of p* using numerical integration of pdf ; utilizing the fact that the integral is a monotone function of p* ; Here is an example for mixture Gaussian: [ 1 ] First thing you need is an analytical pdf function; for mixture Gaussian that is easy: def mix_norm_pdf(x, loc, scale, weight): from scipy.stats import norm return np.dot(weight, norm.pdf(x, loc, scale)) so for example for location, scale and weight values as in loc = np.array([-1, 3]) # mean valuesscale = np.array([.5, .8]) # standard deviationsweight = np.array([.4, .6]) # mixture probabilities you will get two nice Gaussian distributions holding hands: [ 2 ] now, you need an error function which given a test value for p* integrates pdf function above p* and returns squared error from the desired value 1 - alpha : def errfn( p, alpha, *args): from scipy import integrate def fn( x ): pdf = mix_norm_pdf(x, *args) return pdf if pdf > p else 0 # ideally integration limits should not # be hard coded but inferred lb, ub = -3, 6 prob = integrate.quad(fn, lb, ub)[0] return (prob + alpha - 1.0)**2 [ 3 ] now, for a given value of alpha we can minimize the error function to obtain p* : alpha = .05from scipy.optimize import fminp = fmin(errfn, x0=0, args=(alpha, loc, scale, weight))[0] which results in p* = 0.0450 , and HPD as below; the red area represents 1 - alpha of the distribution, and the horizontal dashed line is p* . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22284502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283296/']} | jdg_72919 |
stackexchange | llm_judgeable_groundtruth_similarity | 32198081 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Yesterday during debugging something strange happened to me and I can't really explain it: So maybe I am not seeing the obvious here or I misunderstood something about decimals in .NET but shouldn't the results be the same?
Now provide the response and nothing else.
| decimal is not a magical do all the maths for me type. It's still a floating point number - the main difference from float is that it's a decimal floating point number, rather than binary . So you can easily represent 0.3 as a decimal (it's impossible as a finite binary number), but you don't have infinite precision. This makes it work much closer to a human doing the same calculations, but you still have to imagine someone doing each operation individually. It's specifically designed for financial calculations, where you don't do the kind of thing you do in Maths - you simply go step by step, rounding each result according to pretty specific rules. In fact, for many cases, decimal might work much worse than float (or better, double ). This is because decimal doesn't do any automatic rounding at all. Doing the same with double gives you 22 as expected, because it's automatically assumed that the difference doesn't matter - in decimal , it does - that's one of the important points about decimal . You can emulate this by inserting manual Math.Round s, of course, but it doesn't make much sense. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32198081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3827069/']} | jdg_72920 |
stackexchange | llm_judgeable_groundtruth_similarity | 2920415 |
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:
Solve the integral equation $$y(t) = e^t \bigg(1+ \int_0^t e^{-\tau}\ y(\tau) d \tau \bigg)$$ The apporach that stands out to me is using the convolution theorem and laplace transforms. Im able to arrive at the expression $$y(t) = e^t + e^t*y(t)$$ But Im unsure what do next. From my understanding you can't factor out $e^t$ in this case?
Now provide the response and nothing else.
| "The normal equations always have a solution" is the same as saying "the column space of $A^T$ is contained in the column space of $A^T A$". One way to see this is to note that the reverse containment is clearly true, and then to show that the rank of $A^T A$ is the same as the rank of $A$. This is closely related to the "four fundamental subspaces theorem"; if you're not aware of this result, pick up Gilbert Strang's book. They do not always have a unique solution, and indeed they do not when $A$ has deficient column rank. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2920415', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/398209/']} | jdg_72921 |
stackexchange | llm_judgeable_groundtruth_similarity | 4839797 |
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 can I check that a string matches a certain format? For example, how can I check that a string matches the format of an IP address, proxy address (or any custom format)? I found this code but I am unable to understand what it does. Please help me understand the match string creation process. string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\. ([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$"; //create our Regular Expression object
Now provide the response and nothing else.
| Regex matching is made simple: Regex r = new Regex(@"your_regexp");if (r.Match(whatever).Success){ // Do_something} This code will invoke some actions if whatever string matches you_regexp regular expression. So what are they, these regular expressions (the same as regex or regexp abbrevation)? They're nothing but string patterns, designed to use as filters for other strings. Let's assume you have a lot of HTTP headers and you want to get GET moofoo HTTP/1.1 only. You may use string.Contains(other_string) method, but regexps make this process more detailed, error-free, flexible and handy. Regexp consists of blocks, which may be used for replacement in the future. Each block definnes which symbols the entire string can contain at some position. Blocks let you to define these symbols or use patterns to ease your work. Symbols, which may be or may not be in the current string position are determined as follows: if you sure of these symbols MUST be there, just use them "as is". In our example, this matches HTTP word - this is always present in HTTP headers. if you know all possible variations, use | (logic OR ) operator. Note: all variants must be enclosed by block signs - round brackets . Read below for details. In our case this one matches GET word - this header could use GET , POST , PUT or DELETE words. if you know all possible symbol ranges, use range blocks : for example, literals could be determined as [a-z] , [\w] or [[:alpha:]] . Square brackets are the signs of range blocks . They must be used with count operator. This one is used to define repetitions . E.g. if your words/symbols should be matched once or more , you should define that using: ? (means 'could be present and could be not') + (stands for 'once or more') * (stands for 'zero or more') {A,} (stands for 'A or more') {A,B} (means 'not less than A and not greater than B times') {,B} (stands for 'not more than B') if you know which symbol ranges must not be present , use NOT operator ( ^ ) within range, at the very beginning: [^a-z] is matched by 132==? while [^\d] is matched by abc==? ( \d defines all digits and is equal to [0-9] or [[:digit:]] ). Note: ^ is also used to determine the very beginning of entire string if it is not used within range block: ^moo matches moofoo and not foomoo . To finish the idea, $ matches the very ending of entire string: moo$ would be matched with foomoo and not moofoo . if you don't care which symbol to match, use star: .* is the most commonly-used pattern to match any number of any symbols. Note: all blocks should be enclosed by round brackets ( (phrase) is a good block example). Note: all non-standard and reserved symbols (such as tab symbol \t , round brackets ( and ) , etc.) should be escaped (e.g. used with back-slash before symbol representation: \( , \t, , \. ) if they do not belong to any block and should be matched as-is. For example, in our case there are two escape-sequences within HTTP/1.1 block: \/ and \. . These two should be matched as-is. Using all the text before i've typed for nearly 30 minutes, let's use it and create a regexp to match our example HTTP header: (GET|POST|PUT|DELETE) will match HTTP method \ will match <SP> symbol (space as it defined in HTTP specification) HTTP\/ would help us to math HTTP requests only (\d+\.\d+) will match HTTP version (this will match not 1.1 only, but 12.34 too) ^ and $ will be our string border-limiters Gathering all these statements together will give us this regexp: ^(GET|POST|PUT|DELETE)\ HTTP\/(\d+\.\d+)$ . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4839797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430167/']} | jdg_72922 |
stackexchange | llm_judgeable_groundtruth_similarity | 6806177 |
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 more of a logic question. I have a checkbox on a webpage and I store its value from the servlet request parameters in a Boolean object (Java). The logic is, if the request parameter for the checkbox is not null, make the object true, otherwise it's null. When the page is called again, it marks the checkbox as "checked" if its stored value is true. this.checkbox = (servlet.getParameter("checkbox")!=null && servlet.getParameter("checkbox").contentEquals("on"))?true:null; The problem starts when I persist that checkbox object. I first populate the page with the persisted data and then fill it with the servlet values. If the checkbox value is stored as true in the database, and the user unchecks it on the page and submits it, since the servlet parameter for the checkbox becomes null, I am unable to make the checkbox null. So the checkbox always show the persisted value since its never gets overwritten. So can anyone suggest some logic change in how I am filling the object value?
Now provide the response and nothing else.
| The only valid test for checkbox is to see whether getParameter() returns null or not. If the return value is null it's unchecked, otherwise it's checked. Note, that checked attribute should be present if you want the checkbox be checked on the first page presentation and should not be present at all if you want it unchecked. The parameter value should always be checked , as in the example below. <label> <input type="checkbox" id="cb_id" name="cb_id" value="cb_id_value" checked="checked" /> My label</label> For this example, you may have this logic in your servlet processing code: HTTPServetRequest request = ...;boolean cbState = request.getParameter( "cb_id" ) != null; Note, that if the checkbox is checked by the user in the above example getParameter will return "cb_id_value" , but because you usually have a single checkbox with a dedicated name you don't have to check the value. BTW, I've noticed in your example that you are using servlet to getParameter . I hope that in your system it is a moniker for HTTPServletRequest . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6806177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/483893/']} | jdg_72923 |
stackexchange | llm_judgeable_groundtruth_similarity | 35721 |
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:
There was a general election where I live yesterday and the television network started calling out winners long before all ballots were opened. They turned out right on all accounts, and I'm not really surprised they did. I know that statistics are absolutely viable. Still, I'm curious. Assuming: we have opened $i$ out of $j$ ballots; we have $n$ candidates whose current scores are $c_1, c_2, c_3, ... c_n$; How can we calculate the certainty with which the leading candidate is the winner?
Now provide the response and nothing else.
| The main difficulty in practice is not the statistical uncertainty that a fluke streak of luck would have given one candidate more votes. The main difficulty, by an order of magnitude or more, is that the ballots which have been opened are almost never an unbiased sample of the votes cast. If you ignore this effect, you get the famous error "Dewey Defeats Truman," which occurred with a large biased sample. In practice, voters who favor one candidate versus another are not equally distributed by region, by whether they work during the day, or by whether they would be deployed overseas hence would vote by absentee ballots. These are not small differences. I think what news organizations do now is to break the population into groups and use the results to estimate how each group voted (including turnout). These may be based on models and prior assumptions based on previous elections, not just the data from this election. These may not take into account oddities such as the butterfly ballots of Palm Beach. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/35721', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/13856/']} | jdg_72924 |
stackexchange | llm_judgeable_groundtruth_similarity | 1230669 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
On Windows, subprocess.Popen.terminate calls win32's TerminalProcess . However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed?
Now provide the response and nothing else.
| By using psutil : import psutil, osdef kill_proc_tree(pid, including_parent=True): parent = psutil.Process(pid) children = parent.children(recursive=True) for child in children: child.kill() gone, still_alive = psutil.wait_procs(children, timeout=5) if including_parent: parent.kill() parent.wait(5)me = os.getpid()kill_proc_tree(me) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1230669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55246/']} | jdg_72925 |
stackexchange | llm_judgeable_groundtruth_similarity | 46389220 |
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 my render method I have component <DatePicker selected={this.state.startDate} onChange={this.handleChange()}/> handleChange is following handleChange: function (e) { var that = this; console.log(e.target.value) return function () { that.setState({ startDate: e.target.value }); }}, By when I try to load page with this component, I get error Cannot read property 'target' of undefined What am I doing wrong ?
Now provide the response and nothing else.
| The problem is that you are invoking the function in this line: onChange={this.handleChange()} All you have to do is simply pass the function as a value to onChange without invoking it. onChange={this.handleChange} When you use parenthesis you'd be invoking a function/method instead of binding it with an event handler. Compare the following two examples: //invokes handleChange() and stores what the function returns in testA.const testA = this.handleChange() vs //stores the function itself in testB. testB be is now a function and may be invoked - testB();const testB = this.handleChange | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46389220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4730700/']} | jdg_72926 |
stackexchange | llm_judgeable_groundtruth_similarity | 14831096 |
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 very new to C++ and QT. Basically, I just done Java stuff, but we're being thrown in C++ for a module, in which we have to design a Zork game UI. The way I am planning to create the Room object is have the Room constructed with a roomnum.long, .short and .name for the long desc, short desc and name. For the first room, I'm just going to load the file directly for the moment until I get onto objects etc properly. However, I can't seem to get the file written into a text label. The return "restart game etc" does get written on button press, but not the contents of the file. The Rooms folder is in the same folder as the source file (islandmain.cpp in this case) Any ideas? void TheIslandMain::on_startButton_clicked(){ ui->roomDesc->setText(readFirstRoom("/Rooms/room1.long")); ui->roomDesc->setWordWrap(true);}QString TheIslandMain::readFirstRoom(QString filename){ QFile mFile(filename); if (!mFile.open(QFile::ReadOnly | QFile::Text)) { qDebug() << "Could not open file for reading Line 31"; return "Could not load file. Please restart game."; } QTextStream in(&mFile); QString fileInput = in.readAll(); qDebug() << fileInput; mFile.close(); return fileInput;}
Now provide the response and nothing else.
| Calling virtual functions in a constructor is recognised as a bad thing to do . During base class construction of a derived class object, the type of the object is that of the base class. Not only do virtual functions resolve to the base class, but the parts of the language using runtime type information (e.g., dynamic_cast (see Item 27) and typeid) treat the object as a base class type. So your instantiation of b invokes the a constructor. That calls foo() , but it's the foo() on a that gets called. And that (of course) is undefined. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14831096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1701266/']} | jdg_72927 |
stackexchange | llm_judgeable_groundtruth_similarity | 410322 |
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've got a project with an HTTP API which returns data from a database. The layers it goes through to get to the API look like this: DB -> Repository -> Controller I'm looking to restrict the results which are returned based on the permissions of the requester. Should this be included in the repository layer, or the controller layer and why?
Now provide the response and nothing else.
| Ideally, if you really require a high level of security, the DB itself should not return any data for which the requester does not have the permission. So the answer in this case would be "neither" - the DB itself should provide an adequate security model, know about the permissions of a specific requester and restrict the data. However, most real world applications of today implement their own user/role/permission model, which makes it hard to implement the security model easily inside the DB. So I see two possible ways to define the reponsibilities: Approach 1 is to keep as much business logic out of the repositories. In this case, the repos should only to provide the tools for restricting the returned result sets, but don't know which permissions the requester has. So here, the Controller might be responsible for evaluating the permissions. This may be feasible if there are only a few places in code where permissions have influence on the result sets of DB queries. Approach 2 is to restrict the result sets directly in the repos. That approach makes sense if there are a lot of different places in the system from which the repositories are called and reused, and all of them should obey to the same permission model which involves returning different result sets. Note that approach 2 can be implemented by splitting the repos into two different layers: one generic layer without any knowledge about the permissions, and one layer on top (maybe by "decorated" repos, or "proxy repos"), which implements the security model: DB -> Generic Repositories -> Secured Repositories -> Controller You need to decide for yourself if the kind of security requirements justifies this additional layering (and maybe further layers, as it was suggested in a comment), which comes for the price of more complexity. There is no "one-size-fits-all" solution to this, one has to make such design decisions deliberate with the overall system in mind. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/410322', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/366047/']} | jdg_72928 |
stackexchange | llm_judgeable_groundtruth_similarity | 86154 |
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 have been looking through other parametric equations questions and am still unsure where to start with this one. I am given two functions: f[t_] = {16.2 - 7 t + t^2, 13 t - 2 t^2};g[t_] = {26 - 13.1 t + 2 t^2, 23 - 6 t + t^2}; How do I show where these two parametric paths cross? How would I simplify these two sets? Thank you!
Now provide the response and nothing else.
| If they don't need to cross at the same $t$, then you can solve Solve[f[t1] == g[t2], {t1, t2}] since they are polynomials. Otherwise, you might use FindRoot . This yields a set of four solutions. You can then plug these pairs of t1 and t2 back into your expressions for f and g to get the actual points where the curves cross. | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/86154', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/30230/']} | jdg_72929 |
stackexchange | llm_judgeable_groundtruth_similarity | 3366635 |
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 would like to know if there is a way to let the program continue after an exception is thrown. For example: Try line 1 line 2 line 3 line 4 ' (here the exception is thrown and jumps to the catch) line 5 ' <-- I would like the program to continue its execution, logging the error line 6 Catch ex as Exception log(ex.tostring)End Try
Now provide the response and nothing else.
| If you're doing something that you know how to recover from or that isn't vital, you're supposed to wrap just that line in the try/catch with a specific catch.e.g. Try line 1 line 2 line 3 Try line 4 ' (here the exception is throw and jumps to the catch) Catch iox as IOException ' or whatever type is being thrown 'log it End Try line 5 ' <-- I would like the program to continue its execution after logging the error line 6 Catch ex as Exception log(ex.tostring)End Try | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3366635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/333838/']} | jdg_72930 |
stackexchange | llm_judgeable_groundtruth_similarity | 44754 |
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 am trying to solve $$u_t=\frac{1}{4}u_{xx}$$ $-\infty<x<\infty,\: t>0$ With the initial condition $u(x,0)=\phi(x)$ where $$\phi(x)= \left\{ \begin{array}{lr} 1 & |x|<1\\ 0 & |x|\geq 1 \end{array} \right.$$ So I initially typed in my piecewise function like this ϕ[x_] := Piecewise[{{1, Abs[x]<1}, {0, Abs[x] >= 1}}] But I have also tried this, (are they both valid, or is just one, or is neither?) ϕ[x_] := Piecewise[{{1, -1 < x < 1}, {0, x >= 1 || x <= -1}}] Then, following the mathematica examples I tried to solve the differential equation: pde = D[u[x, t], t] - 1/4 D[u[x, t], {x, 2}] == 0soln = DSolve[{pde, u[x, 0] == ϕ[x]}, u[x, t], {x, t}] Which outputs a bunch of weird stuff, not the solution (I think) I was expecting. If my math is correct I think the solution to this would involve the error function. Any tips to where I might be going wrong would be aprreciated!
Now provide the response and nothing else.
| new one This seems to be quite fast ( didn't test with yours ) sc[{n_String}] := n;sc[s_] := StringJoin[StringDrop[Most[s], -1]] <> Last[s]sc /@ Split[testLines, StringMatchQ[#, "*\\"] &] old one StringJoin @@@ ( Split[testLines, StringMatchQ[#, "*\\"] &] /. s : {Repeated[_String, {2, ∞}]} :> StringReplace[s, "\\" -> ""]) {"foo", "barbazquux", "wongle\\ bongle", "wingle", "pringleprongle", "blort"} Notice that this is Split not SplitBy . Important difference because from adjacent elements we only test former one. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/44754', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9691/']} | jdg_72931 |
stackexchange | llm_judgeable_groundtruth_similarity | 9746675 |
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 app that revolves around the device's GPS and the information that comes from it. It is important that the location data be accurate and up-to-date. I know that the device is limited by its GPS and the GPS's limits, but I was wondering if there is anything I can do to tweak/improve the performance of the iPhone GPS, particularly in the speed area. Because location updates lag about 3-5 seconds behind the real-time location of the device, the velocity reported by the location manager also lags that far behind the real-time value. In my case, that is simply too long. I understand that there might not be anything I can do, but has anyone had any success in improving the responsiveness of the iPhone GPS? Every little bit makes a difference. Edit 1: My location manager is inside a singleton class, as Apple recommends. Inside SingletonDataController.m: static CLLocationManager* locationManager;locationManager = [CLLocationManager new];locationManager.distanceFilter = kCLDistanceFilterNone;locationManager.headingFilter = kCLHeadingFilterNone;if(([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging) || ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateFull)) { locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;} else { locationManager.desiredAccuracy = kCLLocationAccuracyBest;}[sharedSingleton setLocationManager:locationManager];[locationManager release]; Inside MapView.m (where the location manager is actually used): - (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil { //setup [SingletonDataController sharedSingleton].locationManager.delegate = self; //more setup}- (void)batteryChanged { if(([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateCharging) || ([[UIDevice currentDevice] batteryState] == UIDeviceBatteryStateFull)) { [SingletonDataController sharedSingleton].locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; } else { [SingletonDataController sharedSingleton].locationManager.desiredAccuracy = kCLLocationAccuracyBest; }}- (void)viewDidLoad { //setup [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryChanged) name:UIDeviceBatteryStateDidChangeNotification object:nil]; //other setup} The data handling happens inside locationManager:didUpdateToLocation:fromLocation: . I don't believe that inefficiency here is the cause of the lag. locationManager:didUpdateToLocation:fromLocation: calls this method to update the UI: - (void)setLabels:(CLLocation*)newLocation fromOldLocation:(CLLocation*)oldLocation { //set speed label if(iterations > 0) { if(currentSpeed > keyStopSpeedFilter) { if(isFollowing) { [mapViewGlobal setRegion:MKCoordinateRegionMake([newLocation coordinate], mapViewGlobal.region.span)]; } NSString* currentSpeedString; if(isCustomary) { currentSpeedString = [[NSString alloc] initWithFormat:@"%.1f miles per hour", (currentSpeed * 2.23693629f)]; } else { currentSpeedString = [[NSString alloc] initWithFormat:@"%.1f km per hour", (currentSpeed * 3.6f)]; } [speedLabel setText:currentSpeedString]; [currentSpeedString release]; } else { speedLabel.text = @"Not moving"; } } //set average speed label if(iterations > 4 && movementIterations > 2) { NSString* averageSpeedString; if(isCustomary) { averageSpeedString = [[NSString alloc] initWithFormat:@"%.1f miles per hour", (float)((speedAverages / (long double)movementIterations) * 2.23693629f)]; } else { averageSpeedString = [[NSString alloc] initWithFormat:@"%.1f km per hour", (float)((speedAverages / (long double)movementIterations) * 3.6f)]; } [averageSpeedLabel setText:averageSpeedString]; [averageSpeedString release]; } //set elapsed time label NSInteger seconds = [[NSDate date] timeIntervalSinceDate:dataObject.locationManagerStartDate]; NSInteger minutes = seconds / 60; NSInteger hours = minutes / 60; //get remainder seconds %= 60; NSString* timeString; NSString* secondsString; NSString* minutesString; NSString* hoursString; if((seconds % 60) < 10) { secondsString = [[NSString alloc] initWithFormat:@"0%i", seconds]; } else { secondsString = [[NSString alloc] initWithFormat:@"%i", seconds]; } if((minutes % 60) < 10) { minutesString = [[NSString alloc] initWithFormat:@"0%i", minutes]; } else { minutesString = [[NSString alloc] initWithFormat:@"%i", minutes]; } if((hours % 60) < 10) { hoursString = [[NSString alloc] initWithFormat:@"0%i", hours]; } else { hoursString = [[NSString alloc] initWithFormat:@"%i", hours]; } timeString = [[NSString alloc] initWithFormat:@"%@:%@:%@", hoursString, minutesString, secondsString]; [elapsedTimeLabel setText:timeString]; [timeString release], timeString = nil; [secondsString release], secondsString = nil; [minutesString release], minutesString = nil; [hoursString release], hoursString = nil; NSString* totalDistanceString; if(isCustomary) { totalDistanceString = [[NSString alloc] initWithFormat:@"Total: %.2f mi", (float)distance * 0.000621371192f]; } else { totalDistanceString = [[NSString alloc] initWithFormat:@"Total: %.2f km", (float)distance / 1000.0f]; } [customTopBar setTitle:totalDistanceString]; [totalDistanceString release];} With a couple of NSDates and NSLogs I have found that the execution of the entire locationManager:didUpdateToLocation:fromLocation: (not just the label updating method) never takes more than about 8ms on my iPhone 4; in other words, the data handling isn't the problem.
Now provide the response and nothing else.
| OK, a couple of things could improve your lag. First of all, use kCLLocationAccuracyBestForNavigation always. There is no real battery usage difference between that and kCLLocationAccuracyBest, they both use the GPS at top speed. The main difference is in the post-processing that Apple does. Second, there is no need to filter for speed == 0. Apple already does that filtering: if your speed from the GPS drops below a certain threshold (about 4 km/h), the OS assumes you are standing still, and it substitutes the same location value for all subsequent samples. It does that until it thinks you are moving again. I assume they do that to avoid "jittering" on the map when you are standing still. In fact, speed drops to 0 already for the last real value of a sequence of "standing-still" values, so if you filter on speed == 0 than you are missing one real GPS sample. Unfortunately, they is no way to avoid that filtering and get real GPS samples. I talked to Apple about it, and their response was that they are not going to change the behaviour. kCLLocationAccuracyBestForNavigation does less aggressive filtering than kCLLocationAccuracyBest, so it's best to use that. Third, you probably are already doing this, but make sure that you call "setNeedsDisplay" on your view right from the "didUpdateFromLocation:", to make sure that the map is actually redrawn. If you do all that, you should have a lag of about 1 second. If you want to improve on the 1 second than you can try to use predictive techniques. From the last two locations, and the given speed, you can calculate where the next location is likely to be, and already display that location. I have had mixed results with that. It works well for fast movement that does not change speed suddenly, like driving a car. It works less well for slower movement like walking or biking. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9746675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/791018/']} | jdg_72932 |
stackexchange | llm_judgeable_groundtruth_similarity | 891360 |
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 implemented getEntityName method in my interceptor. I was expecting that the method will be called by Hibernate to resolve entity name of a (transient) object when I save the object. However, the method getEntityName from the interceptor was not used in the following scenarios: 1) session.saveOrUpdate was called with some entity name value. It was expected that the entity name will be overwritten by the interceptor. The interesting thing it that when I removed the entity name from save method call, the interceptor's getEntityName was used. Looks like it is only used when save is called without entity name. 2) objects in a collection were saved on cascading and the one-to-many association of the collection mapping used entity-name as reference to another class mapping. I beleive that this association's entity-name was used in cascading save similarly as in scenario 1. Can someone tell me whether it is a bug or feature in Hibernate? Below are my mappings. Version of Hibernate is 3.3.1.GA. <class name="User" table="HUBUSER"><id name="id" type="integer"> <column name="USERID"/> <generator class="sequence"> <param name="sequence">USERID</param> </generator></id>...<map cascade="all" inverse="true" name="attributes"> <key on-delete="cascade" update="false"> <column name="USERID"/> </key> <map-key column="PROPERTYKEY" type="string"/> <one-to-many class="HBAttribute" entity-name="USERPROPERTY"/></map>...</class><class discriminator-value="HBAttribute" entity-name="USERPROPERTY" name="HBAttribute" table="USERPROPERTY"><id name="id" type="integer"> <column name="USERPROPERTYID"/> <generator class="sequence"> <param name="sequence">USERPROPERTYID</param> </generator></id><discriminator column="PROPERTYKEY" type="string"/><property insert="false" name="propertyKey" not-null="false" type="string" update="false"> <column name="PROPERTYKEY"/></property><many-to-one class="User" name="hubObject" not-null="true" update="false"> <column name="USERID"/></many-to-one><!-- Subclass for USERNAME --><subclass discriminator-value="USERNAME" entity-name="USERPROPERTY_USERNAME" name="HBAttributeString"> <property name="value" not-null="false" type="string"> <column name="PROPVALCHAR"/> </property></subclass><!-- Subclass for TITL --><subclass discriminator-value="TITL" entity-name="USERPROPERTY_TITL" name="HBAttributeString"> <property name="value" not-null="false" type="string"> <column name="PROPVALCHAR"/> </property></subclass><!-- Subclass for EMAIL --><subclass discriminator-value="EMAIL" entity-name="USERPROPERTY_EMAIL" name="HBAttributeString"> <property name="value" not-null="false" type="string"> <column length="80" name="PROPVALCHAR"/> </property></subclass> Your answers/comments on this issue would be very much appriciated. --------------------UPDATED------------------------- I guess I know what the problem is. Hibernate does not use an interceptor to overwrite existing entity name on save/saveOrUpdate. Hibernate allows to use discriminators and entity-names in a class and its subclasses mappings. Discriminator is used to identify a subclass or super class mapping when a database record is fetched from a database.Then as far as I understand, based on the found subclass mapping a persistent entry (object) is created in persistent context.If the subclass has got its own entity-name this entity-name gets assigned to the persistent entry. Later wheneveryou update the persistent object this entity-name is used as a key to find the subclass mapping. Based on the above, as far as I understand, Discriminator works in one direction, when mapping database row to a java object (persistent object).However when it comes to mapping of a transient java object to a database row, only class name of the object or provided to the save (or saveOrUpdate) method entity-name is used to find subclass/super class mapping. So Discriminator here is not used (I wonder why? May be because the it is not a part of the persistent object?). In my scenario HBAttribute class mapping has got the "USERPROPERTY" entity-name and all its subclasses also have got their own entity-names ("USERPROPERTY_USERNAME", "USERPROPERTY_TITL" and "USERPROPERTY_EMAIL").The reason why I use entity-names for the subclasses is that I need to reuse the java classes of the subclass mappings. The HBAttribute class has got bidirectional association with the User class (User -> one-to-many -> HBAttribute) .In User class mapping the only way to specify referenced class mapping is to provide HBAttribute's "USERPROPERTY" entity-name in one-to-many association of the User's collection. The collection has got cascade="all" and hence all operations are expected to be cascaded to the collection's objects. And here the problem comes. I create transient object of User class and then put just created transient objects of HBAttribute class to the collection. So all objects are transient. Then when I save the User object via session.save(user) method, the objects in the attributes collection get saved on cascade. However, because the one-to-many association refers HBAttribute class mapping using "USERPROPERTY" entity-name, the entity-name gets passed to the cascading save method. The "USERPROPERTY" entity is a super class mapping, but there are subclasses with their own entity-names and Hibernate does not resolve subclasses identified by entity-names (this is actually noticed in the Hibernate's code. I guess that Hibernate developers could use Discriminator to do that in this case). Here Interceptor's getEntityName would come in handy to tell Hibernate what subclass entity-name should be used, however as the "USERPROPERTY" entity has already been set/provided by the collection mapping there is no way to overwrite it with the interceptor. My idea was to store subclass entity-names in the HBAttribute objects and use the interceptor.getEntityName to provide my the entity-names taken from the objects. Below is the code of java.org.hibernate.impl.SessionImpl.getEntityPersister which does NOT allow an interceptor to overwrite original not null entity-name. public EntityPersister getEntityPersister(final String entityName, final Object object) { errorIfClosed(); if (entityName==null) { return factory.getEntityPersister( guessEntityName( object ) ); } else { // try block is a hack around fact that currently tuplizers are not // given the opportunity to resolve a subclass entity name. this // allows the (we assume custom) interceptor the ability to // influence this decision if we were not able to based on the // given entityName try { return factory.getEntityPersister( entityName ) .getSubclassEntityPersister( object, getFactory(), entityMode ); } catch( HibernateException e ) { try { return getEntityPersister( null, object ); } catch( HibernateException e2 ) { throw e; } } }} And this is my hacked code. public EntityPersister getEntityPersister(final String entityName, final Object object) { errorIfClosed(); if (entityName==null) { return factory.getEntityPersister( guessEntityName( object ) ); } else { //even if the original entity-name is not null try to resolve //the entity-name via interceptor, if the returned entity-name // is null, then use original entity-name. String overwrittenEntityName = interceptor.getEntityName( object ); if (overwrittenEntityName != null) { return factory.getEntityPersister( overwrittenEntityName ); } else { // try block is a hack around fact that currently tuplizers are not // given the opportunity to resolve a subclass entity name. this // allows the (we assume custom) interceptor the ability to // influence this decision if we were not able to based on the // given entityName try { return factory.getEntityPersister( entityName ) .getSubclassEntityPersister( object, getFactory(), entityMode ); } catch( HibernateException e ) { try { return getEntityPersister( null, object ); } catch( HibernateException e2 ) { throw e; } } } }} Could someone more experienced in Hibernate tell me whether my change is OK and should be proposed to be included in Hibernate? Thanks,Anton
Now provide the response and nothing else.
| The PrintWindow win32 api will capture a window bitmap even if the window is covered by other windows or if it is off screen: [DllImport("user32.dll")]public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);[DllImport("user32.dll")]public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);public static Bitmap PrintWindow(IntPtr hwnd) { RECT rc; GetWindowRect(hwnd, out rc); Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb); Graphics gfxBmp = Graphics.FromImage(bmp); IntPtr hdcBitmap = gfxBmp.GetHdc(); PrintWindow(hwnd, hdcBitmap, 0); gfxBmp.ReleaseHdc(hdcBitmap); gfxBmp.Dispose(); return bmp; } The reference to RECT above can be resolved with the following class: [StructLayout(LayoutKind.Sequential)]public struct RECT{ private int _Left; private int _Top; private int _Right; private int _Bottom; public RECT(RECT Rectangle) : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom) { } public RECT(int Left, int Top, int Right, int Bottom) { _Left = Left; _Top = Top; _Right = Right; _Bottom = Bottom; } public int X { get { return _Left; } set { _Left = value; } } public int Y { get { return _Top; } set { _Top = value; } } public int Left { get { return _Left; } set { _Left = value; } } public int Top { get { return _Top; } set { _Top = value; } } public int Right { get { return _Right; } set { _Right = value; } } public int Bottom { get { return _Bottom; } set { _Bottom = value; } } public int Height { get { return _Bottom - _Top; } set { _Bottom = value + _Top; } } public int Width { get { return _Right - _Left; } set { _Right = value + _Left; } } public Point Location { get { return new Point(Left, Top); } set { _Left = value.X; _Top = value.Y; } } public Size Size { get { return new Size(Width, Height); } set { _Right = value.Width + _Left; _Bottom = value.Height + _Top; } } public static implicit operator Rectangle(RECT Rectangle) { return new Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height); } public static implicit operator RECT(Rectangle Rectangle) { return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom); } public static bool operator ==(RECT Rectangle1, RECT Rectangle2) { return Rectangle1.Equals(Rectangle2); } public static bool operator !=(RECT Rectangle1, RECT Rectangle2) { return !Rectangle1.Equals(Rectangle2); } public override string ToString() { return "{Left: " + _Left + "; " + "Top: " + _Top + "; Right: " + _Right + "; Bottom: " + _Bottom + "}"; } public override int GetHashCode() { return ToString().GetHashCode(); } public bool Equals(RECT Rectangle) { return Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom; } public override bool Equals(object Object) { if (Object is RECT) { return Equals((RECT)Object); } else if (Object is Rectangle) { return Equals(new RECT((Rectangle)Object)); } return false; }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/891360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/110311/']} | jdg_72933 |
stackexchange | llm_judgeable_groundtruth_similarity | 4430504 |
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 C++ struct and a method: struct Account{ unsigned int id; string username; ...};Account GetAccountById(unsigned int id) const { } I can return an Account struct if the account exists, but what to do if there's no account? I thought of having: An "is valid" flag on the struct (so an empty one can be returned, with that set to false) An additional "is valid" pointer (const string &id, int *is_ok) that's set if the output is valid Returning an Account* instead, and returning either a pointer to a struct, or NULL if it doesn't exist? Is there a best way of doing this?
Now provide the response and nothing else.
| You forgot the most obvious one, in C++: bool GetAccountById(unsigned int id, Account& account); Return true and fill in the provided reference if the account exists, else return false . It might also be convenient to use the fact that pointers can be null, and having: bool GetAccountById(unsigned int id, Account* account); That could be defined to return true if the account id exists, but only (of course) to fill in the provided account if the pointer is non-null. Sometimes it's handy to be able to test for existance, and this saves having to have a dedicated method for only that purpose. It's a matter of taste what you prefer having. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4430504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/540728/']} | jdg_72934 |
stackexchange | llm_judgeable_groundtruth_similarity | 1049067 |
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 recently got asked this question on an exam and I wasn't able to give a solution. If $(X,d)$ is a metric space and we define $$d'(x,y)= \frac {d(x,y)}{1+d(x,y)}$$(I've already proved that $(X,d')$ is a metric space.) Prove that $(X,d)$ is a complete metric space iff $(X,d')$ is a complete metric space.
Now provide the response and nothing else.
| You can see that $d' = {d \over 1+ d} \le {d \over 1} = d$, hence a $d$-Cauchy sequence is a $d'$-Cauchy sequence. Note that if $d'(x,y) \neq 1$, then since $d'(x,y) = { d(x,y) \over 1 + d(x,y) }$, then $d(x,y) = { d'(x,y) \over 1 - d'(x,y) }$. Now suppose $x_n$ is a $d'$-Cauchy sequence, and choose $N$ such that if $m,n \ge N$, then $d'(x_n,x_m) \le {1 \over 2}$. Then for $m,n \ge N$, we have$d(x,y) \le 2 d'(x,y)$ and so the sequence is a $d$-Cauchy sequence. If $(X,d)$ is complete, and $x_n$ is $d$-Cauchy, then there is some $x$ such that $d(x,x_n) \to 0$. Since $d' \le d$, it follows that $d'(x,x_n) \to 0$ and hence $(X,d')$ is complete. Similarly, if $(X,d')$ is complete, and $x_n$ is $d'$-Cauchy, then there is some $x$ such that $d'(x,x_n) \to 0$. Choose $N$ such that if $n \ge N$then $d'(x,x_n) \le {1 \over 2}$, then we have $d(x,x_n) \le 2 d'(x,x_n)$ andso $d(x,x_n) \to 0$ and hence $(X,d)$ is complete. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1049067', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/108169/']} | jdg_72935 |
stackexchange | llm_judgeable_groundtruth_similarity | 4537969 |
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 the pre-order traversal of a binary search tree is 6, 2, 1, 4, 3, 7, 10, 9, 11, how to get the post-order traversal?
Now provide the response and nothing else.
| You are given the pre-order traversal of the tree, which is constructed by doing: output, traverse left, traverse right. As the post-order traversal comes from a BST, you can deduce the in-order traversal (traverse left, output, traverse right) from the post-order traversal by sorting the numbers. In your example, the in-order traversal is 1, 2, 3, 4, 6, 7, 9, 10, 11. From two traversals we can then construct the original tree. Let's use a simpler example for this: Pre-order: 2, 1, 4, 3 In-order: 1, 2, 3, 4 The pre-order traversal gives us the root of the tree as 2. The in-order traversal tells us 1 falls into the left sub-tree and 3, 4 falls into the right sub-tree. The structure of the left sub-tree is trivial as it contains a single element. The right sub-tree's pre-order traversal is deduced by taking the order of the elements in this sub-tree from the original pre-order traversal: 4, 3. From this we know the root of the right sub-tree is 4 and from the in-order traversal (3, 4) we know that 3 falls into the left sub-tree. Our final tree looks like this: 2 / \1 4 / 3 With the tree structure, we can get the post-order traversal by walking the tree: traverse left, traverse right, output. For this example, the post-order traversal is 1, 3, 4, 2. To generalise the algorithm: The first element in the pre-order traversal is the root of the tree. Elements less than the root form the left sub-tree. Elements greater than the root form the right sub-tree. Find the structure of the left and right sub-trees using step 1 with a pre-order traversal that consists of the elements we worked out to be in that sub-tree placed in the order they appear in the original pre-order traversal. Traverse the resulting tree in post-order to get the post-order traversal associated with the given pre-order traversal. Using the above algorithm, the post-order traversal associated with the pre-order traversal in the question is: 1, 3, 4, 2, 9, 11, 10, 7, 6. Getting there is left as an exercise. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4537969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/420292/']} | jdg_72936 |
stackexchange | llm_judgeable_groundtruth_similarity | 14285201 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Edit Nov 2016: Node now has a built in debugger that you can start with --inspect . This answer explains it: https://stackoverflow.com/a/39901169/30946 . I'm building a mocha test in coffeescript. Right at the top of the test I have: require "../assets/js/theObject.coffee"debuggerss = new TheObject() I'd like to stop on that debugger line because the object in theObject.coffee isn't being loaded. I'm using node-inspector and it works, sorta. The process that I have is: start node-inspector run the test at the command line with mocha --compilers coffee:coffee-script ./test/theObjectTests.coffee --ui bdd -d --debug-brk go to the node-inspector page, refresh it if it is already open wait for the file theObject.coffee to be loaded, then put a breakpoint on the correct line There must be an easier way. It seems like I should be able to have a debugger running and just have it stop on that debugger line, but I'm not able to find that. I have WebStorm, which has a debugger ( this article discusses setting it up to run mocha tests, but it didn't help me), but when I start it, it fails. The command that's running in the WebStorm debug window is: "C:\Program Files\nodejs\node.exe" --debug-brk=64232 C:\Users\jcollum\AppData\Roaming\npm\_mochaC:\Users\jcollum\AppData\Roaming\npm\_mocha:2basedir=`dirname "$0"` I suspect that might be a windows specific issue. Env: Windows 7, Webstorm, node 0.8.16, mocha 1.7.4, git-bash The question: if you're starting from scratch with Mocha, what's the easiest way to get a debugger going that will stop on a debugger line easily? Easy is the keyword here. Edit: since asking this I've stopped using Windows and am working in Ubuntu. My mocha debugging process (which I use infrequently) is the same.
Now provide the response and nothing else.
| Edit, years later : the shortest path in Node 6+ is: mocha --debug-brk --inspect ./test.js coupled with the Node Inspector Manager plugin. Many weeks later, no answers. Here's the quickest path that I found. write mocha tests install node-inspector start node-inspector -- it will now be listening on 5858 start the mocha test with --debug-brk at this point the mocha test is paused on the first line open a web browser and go to localhost:5858 (optional: add a debugger line at the top of your test file, set breakpoints after it stops in that file) hit F10 to get the code to go node-inspector will stop on any line that has debugger on it. Occasionally it won't move the code file's window to the right place, so you'll have to hit F10 to get it to step to the next line and show where it's at in the file. Command line: node-inspector & mocha --compilers coffee:coffee-script/register ./test/appTests.coffee --ui bdd -d -g "should X then Y" --debug-brk | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14285201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30946/']} | jdg_72937 |
stackexchange | llm_judgeable_groundtruth_similarity | 32485 |
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:
I've always wondered how the kernel passes control to third-party code, or specifically distribution-specific code, during boot. I've dug around in GRUB's configuration files, suspecting a special parameter to be passed to the kernel to let it know what to do once it has booted successfully, but unable to find anything. This leads me to suspect there may be certain files on the root partition that the kernel looks for. I'd be grateful if someone could shed some light upon this matter. How do distributions achieve this?
Now provide the response and nothing else.
| It's hardcoded, but you can override the defaults by the kernel parameter init=... . From init/main.c : if (execute_command) { run_init_process(execute_command); printk(KERN_WARNING "Failed to execute %s. Attempting " "defaults...\n", execute_command);}run_init_process("/sbin/init");run_init_process("/etc/init");run_init_process("/bin/init");run_init_process("/bin/sh");panic("No init found. Try passing init= option to kernel. " "See Linux Documentation/init.txt for guidance."); | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/32485', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/15861/']} | jdg_72938 |
stackexchange | llm_judgeable_groundtruth_similarity | 44489657 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Couple Android O notification questions: 1) I have created a Notification Channel (see below), am calling the builder with .setChannelId() (passing in the name of the channel I created, "wakey"; and yet, when I run the app, I get a message that I've failed to post a notification to channel "null". What might be causing this? 2) I suspect the answer to #1 can be found in the "log" that it says to check, but I've checked logcat & don't see anything about notifications or channels. Where is the log that it says to look in? Here's the code I'm using to create the channel: NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);CharSequence name = context.getString(R.string.app_name);String description = "yadda yadda"int importance = NotificationManager.IMPORTANCE_DEFAULT;NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL, name, importance);channel.setDescription(description);notificationManager.createNotificationChannel(channel); Here's the code to generate the notification: Notification.Builder notificationBuilder;Intent notificationIntent = new Intent(context, BulbActivity.class);notificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); // Fix for https://code.google.com/p/android/issues/detail?id=53313PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);Intent serviceIntent = new Intent(context, RemoteViewToggleService.class);serviceIntent.putExtra(WakeyService.KEY_REQUEST_SOURCE, WakeyService.REQUEST_SOURCE_NOTIFICATION);PendingIntent actionPendingIntent = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);_toggleAction = new Notification.Action(R.drawable.ic_power_settings_new_black_24dp, context.getString(R.string.toggle_wakey), actionPendingIntent);notificationBuilder= new Notification.Builder(context) .setContentTitle(context.getString(R.string.app_name)) .setContentIntent(contentIntent) .addAction(_toggleAction);if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { notificationBuilder.setChannelId(NOTIFICATION_CHANNEL);}notificationBuilder.setSmallIcon(icon);notificationBuilder.setContentText(contentText);_toggleAction.title = actionText;int priority = getNotificationPriority(context);notificationBuilder.setPriority(priority);notificationBuilder.setOngoing(true);Notification notification = notificationBuilder.build();notificationManager.notify(NOTIFICATION_ID, notification); And here's the warning I'm getting:
Now provide the response and nothing else.
| I think I have learned a couple things that all add up to an answer: I was using an emulator device, with an image that did not include the Play Store. The version of Google Play Services on the image was not the latest, so I should have been getting a notification telling me I needed to upgrade. Since that notification didn't get applied to a channel, it didn't appear. If I set logcat in Android Studio to "No Filters" instead of "Show only selected application", then I found the logs that pointed out that the notification in question was the Play Services "update needed" notification. So, I changed to a image with the Play Store included, and it showed the notification properly (maybe the channel for that notification was to be set by the Play Store?), let me update to the latest Google Play Services, and I haven't seen that warning since. So, long story short (too late) - with Android O, if you are using Google Play Services & testing on the emulator, choose an image with the Play Store included, or ignore the toast (good luck on that one!). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44489657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1084080/']} | jdg_72939 |
stackexchange | llm_judgeable_groundtruth_similarity | 8582664 |
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 using maven and the maven-javadoc-plugin with the umlgraph-doclet to create javadoc for my project. The part from my pom: <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <inherited>false</inherited> <configuration> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.8</version> <configuration> <show>public</show> <quiet>true</quiet> <doclet>org.umlgraph.doclet.UmlGraphDoc</doclet> <docletArtifact> <groupId>org.umlgraph</groupId> <artifactId>doclet</artifactId> <version>5.1</version> </docletArtifact> <useStandardDocletOptions>true</useStandardDocletOptions> <additionalparam> -inferrel -inferdep -quiet -hide java.* -hide org.eclipse.* -collpackages java.util.* -postfixpackage -nodefontsize 9 -nodefontpackagesize 7 -attributes -types -visibility -operations -constructors -enumerations -enumconstants -views </additionalparam> </configuration> <reportSets> <reportSet> <reports> <report>aggregate</report> </reports> </reportSet> </reportSets> </plugin> </reportPlugins> </configuration> </plugin> </plugins></build> These are the errors that i get when running mvn site or alternatively dot -Tpng class.dot -o class.cli.png using the .dot files generated by the umlgraph doclet: [0] Times-Roman => "Times, REGULAR"[1] Times-Italic => "Times, REGULAR ITALIC"[2] Times-Bold => "Times, BOLD"[3] Times-BoldItalic => "Times, BOLD ITALIC"[4] AvantGarde-Book => "URW Gothic L, BOOK"[5] AvantGarde-BookOblique => "URW Gothic L, BOOK"[6] AvantGarde-Demi => "URW Gothic L, DEMI"[7] AvantGarde-DemiOblique => "URW Gothic L, DEMI"[8] Bookman-Light => "URW Bookman L, LIGHT"[9] Bookman-LightItalic => "URW Bookman L, LIGHT ITALIC"[10] Bookman-Demi => "URW Bookman L, "[11] Bookman-DemiItalic => "URW Bookman L, ITALIC"[12] Courier => "Courier, REGULAR"[13] Courier-Oblique => "Courier, REGULAR OBLIQUE"[14] Courier-Bold => "Courier, BOLD"[15] Courier-BoldOblique => "Courier, BOLD OBLIQUE"[16] Helvetica => "Helvetica, REGULAR"[17] Helvetica-Oblique => "Helvetica, REGULAR OBLIQUE"[18] Helvetica-Bold => "Helvetica, BOLD"[19] Helvetica-BoldOblique => "Helvetica, BOLD OBLIQUE"[20] Helvetica-Narrow => "Helvetica, REGULAR"[21] Helvetica-Narrow-Oblique => "Helvetica, REGULAR OBLIQUE"[22] Helvetica-Narrow-Bold => "Helvetica, BOLD"[23] Helvetica-Narrow-BoldOblique => "Helvetica, BOLD OBLIQUE"[24] NewCenturySchlbk-Roman => "Century Schoolbook L, ROMAN"[25] NewCenturySchlbk-Italic => "Century Schoolbook L, REGULAR ITALIC"[26] NewCenturySchlbk-Bold => "Century Schoolbook L, BOLD"[27] NewCenturySchlbk-BoldItalic => "Century Schoolbook L, BOLD ITALIC"[28] Palatino-Roman => "URW Palladio L, ROMAN"[29] Palatino-Italic => "URW Palladio L, REGULAR ITALIC"[30] Palatino-Bold => "URW Palladio L, BOLD"[31] Palatino-BoldItalic => "URW Palladio L, BOLD ITALIC"[32] Symbol => "Impact, "[33] ZapfChancery-MediumItalic => "URW Chancery L, ITALIC"[34] ZapfDingbats => "Dingbats, REGULAR" Not all Font in that list are used in the .dot file, only Helvetica is used there. I'm using linux. I can provide you the .dot file i used for testing.Another observation of mine: When running in terminal, not every run shows these error. Average every 3rd run goes without them. Output when running with -v : dot - graphviz version 2.28.0 (20111204.1018)libdir = "/usr/lib/graphviz"Activated plugin library: libgvplugin_pango.so.6Using textlayout: textlayout:cairoUsing render: cairo:cairoUsing device: png:cairo:cairoActivated plugin library: libgvplugin_dot_layout.so.6Using layout: dot:dot_layoutThe plugin configuration file: /usr/lib/graphviz/config6 was successfully loaded. render : cairo dot fig gd map ps svg tk vml vrml xdot layout : circo dot fdp neato nop nop1 nop2 osage patchwork sfdp twopi textlayout : textlayout device : bmp canon cmap cmapx cmapx_np dot eps fig gd gd2 gif gv ico imap imap_np ismap jpe jpeg jpg pdf plain plain-ext png ps ps2 svg svgz tif tiff tk vml vmlz vrml wbmp x11 xdot xlib loadimage : (lib) eps gd gd2 gif jpe jpeg jpg png ps svgfontname: "Helvetica" resolved to: (ps:pango Helvetica, REGULAR) (PangoCairoFcFont) "Arial, Regular" /usr/share/fonts/TTF/Arialtbg.ttfnetwork simplex: 3 nodes 2 edges maxiter=2147483647 balance=1network simplex: 3 nodes 2 edges 0 iter 0.00 secnetwork simplex: 1 nodes 0 edges maxiter=2147483647 balance=1network simplex: 1 nodes 0 edges 0 iter 0.00 secmincross: pass 0 iter 0 trying 0 cur_cross 0 best_cross 0mincross: pass 0 iter 0 trying 0 cur_cross 0 best_cross 0mincross G: 0 crossings, 0.00 secs.network simplex: 6 nodes 6 edges maxiter=2147483647 balance=2network simplex: 6 nodes 6 edges 1 iter 0.00 secroutesplines: 2 edges, 6 boxes 0.00 secUsing render: cairo:cairoUsing device: png:cairo:cairodot: allocating a 1162K cairo image surface (781 x 381 pixels) Anybody knows how to fix or suppress them? Its annoying to get over 2k lines of these error every site-generation.
Now provide the response and nothing else.
| Javascript supports closures, so the anonymous function you wrote will be able to access xhttp and msg from the enclosing doRequest() scope. If wanted to do this explicitly (say, if you want to define the callback function somewhere else in the code and reuse it), you could create a function that creates the callbacks. This also allows you to alias the variables to be accessible with different names (like x and m ): function createCallback(x, m) { return function() { /* Do whatever */ };} and then in doRequest() , do xhttp.onreadystatechange = createCallback(xhttp, msg); If all you wanted to do was 'rename' the variables, you can do this inline and anonymously: xhttp.onreadystatechange = (function(x, m) { return function() { /* Do stuff */ }})(xhttp, msg); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8582664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1094486/']} | jdg_72940 |
Subsets and Splits