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 | 16751614 |
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 tried to debug this, but cannot figure out why it isn't working. This is the logcat output: 05-25 17:28:39.251: E/AndroidRuntime(1008): FATAL EXCEPTION: main05-25 17:28:39.251: E/AndroidRuntime(1008): java.lang.NoClassDefFoundError: com.actionbarsherlock.widget.SuggestionsAdapter05-25 17:28:39.251: E/AndroidRuntime(1008): at com.actionbarsherlock.widget.SearchView.updateSearchAutoComplete(SearchView.java:1132)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.actionbarsherlock.widget.SearchView.setSearchableInfo(SearchView.java:370)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.liamwli.spotify.spotifycommunity.MainActivity.onCreateOptionsMenu(MainActivity.java:153)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.actionbarsherlock.app.SherlockActivity.onCreatePanelMenu(SherlockActivity.java:184)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.actionbarsherlock.ActionBarSherlock.callbackCreateOptionsMenu(ActionBarSherlock.java:559)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.actionbarsherlock.internal.ActionBarSherlockNative.dispatchCreateOptionsMenu(ActionBarSherlockNative.java:65)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.actionbarsherlock.app.SherlockActivity.onCreateOptionsMenu(SherlockActivity.java:149)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.app.Activity.onCreatePanelMenu(Activity.java:2498)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:407)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:769)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:201)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.view.Choreographer.doCallbacks(Choreographer.java:562)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.view.Choreographer.doFrame(Choreographer.java:531)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.os.Handler.handleCallback(Handler.java:725)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.os.Handler.dispatchMessage(Handler.java:92)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.os.Looper.loop(Looper.java:137)05-25 17:28:39.251: E/AndroidRuntime(1008): at android.app.ActivityThread.main(ActivityThread.java:5229)05-25 17:28:39.251: E/AndroidRuntime(1008): at java.lang.reflect.Method.invokeNative(Native Method)05-25 17:28:39.251: E/AndroidRuntime(1008): at java.lang.reflect.Method.invoke(Method.java:525)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)05-25 17:28:39.251: E/AndroidRuntime(1008): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)05-25 17:28:39.251: E/AndroidRuntime(1008): at dalvik.system.NativeStart.main(Native Method) I tried disabling proguard, in case that was the issue, but no luck. Line 153 of my class is: searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); Could anyone assist in this issue?
Now provide the response and nothing else.
| For this particular case, where each executable has a single source file with .c extension, all you need is a one line Makefile: all: ex1 ex3 The built-in default rules for make then work already: $ makecc -O2 -pipe ex1.c -o ex1cc -O2 -pipe ex3.c -o ex3 Behind the scene, make is using the POSIXly mandated built-in single suffix rule .c: $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $< Vary the command to your liking with make CC=gcc CFLAGS=-O2 LDFLAGS=-s and similar. Trivia of the day: in fact, if you are willing to name the targets when invoking make , you can use an empty or even run without any Makefile: $ make -f /dev/null CC=gcc CFLAGS=-O2 LDFLAGS=-s ex1 ex3gcc -O2 -s ex1.c -o ex1gcc -O2 -s ex3.c -o ex3$ rm -f Makefile ex1 ex3$ make CC=gcc CFLAGS=-O2 LDFLAGS=-s ex1 ex3gcc -O2 -s ex1.c -o ex1gcc -O2 -s ex3.c -o ex3 Make magic! As a rule of thumb, don't reinvent the wheel (or rules), use the rules that are already there. It simplifies your and make's life a lot. This makes for small and sexy makefiles to impress the ladies with :-) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16751614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1124470/']} | jdg_382241 |
stackexchange | llm_judgeable_groundtruth_similarity | 57449 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I get a String like: XXXXXXXXX Its length is fixed and 9. I need to get an char array like: char array[9] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; ... from there on my sketch processes this array. Maybe someone has an idea on how to achieve this. I thought about a for-statement to store every single letter in a string array. Then another for-statement to build an char array with the hex presentation of each string. Seems to be a bit complicated though I think. Really appreciate your help. EDIT: What I need to do: Separate the string into letters / figures. Change every single letter to its HEX representation. Build a char Array out of the HEX values. Example: 123 (String) 0x310x320x33 (String or whatever ...) {0x31,0x32,0x33} (Char-Array) This is what I need!
Now provide the response and nothing else.
| Sounds like the following string.toCharArray(buf, len) is what you want. as exampled String stringOne = "123456789";char charBuf[50];stringOne.toCharArray(charBuf, 50) ;Serial.println(stringOne);for (int i = 0; i < 9; i++) { Serial.print(" 0x"); Serial.print(charBuf[i], HEX);}Serial.println(); yields: 1234567890x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 as each contents of charBuf is an uint8_t, regardless of how it is printed. Unless you are asking for each element of the array to be another string of the ASCII representation of the HEX. or are you asking to have a char array of "0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39" | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/57449', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/18086/']} | jdg_382242 |
stackexchange | llm_judgeable_groundtruth_similarity | 13332327 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
can anyone tell me why this code is not running as expected $(document).ready(function () { $('#search_box').on('paste keyup change', 'input', function () { alert("hi"); } }); }); the code is working in another page, when i copied it its not working .I know it has to be simple but I dont get it.
Now provide the response and nothing else.
| You are trying to cast the value of ob[0] and not ob itself. You need to cast your ob first to int[] and then use it on index [0] . ((int[])ob)[0] = 5; Note: - Parenthesis matters. But why would you like to do something like this? If you don't want to hardcode values, and want to take it at runtime, then you should follow something mentioned by @HotLicks in comments. Object ob = new int[5];int[] tempArr = (int [])ob;for (int i = 0; i < tempArr.length; i++) { tempArr[i] = i;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13332327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1788616/']} | jdg_382243 |
stackexchange | llm_judgeable_groundtruth_similarity | 12125076 |
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 serialize an object and then deserialize it after sending its data to a client program. Here's an example of how the object's inheritance works. The object I'm serializing and deserializing is person. Living -> Animal -> NPC -> Person -> Child Living, Animal, and NPC do not implement Serializable. I can not change those three classes. Person and Child do implement Serializable. Person and Living are also abstract classes. I can serialize a Person (who is a Child) just fine and send it, but when I attempt to deserialize a Person (who is a Child), I get an InvalidClassException on Child, saying "no valid constructor". Why is this happening? Must Living, Animal, and NPC all implement Serializable?
Now provide the response and nothing else.
| Good explanation is done in answers for following question Deserializing an ArrayList. no valid constructor Long story short - you need no-arg constructor for first nonserializable super class of your class, NPC in your case. If you don't have an access to NPC and it doesn't contain no-arg constructor - then you can add one more 'fake' class to hierarchy which will choose the correct one. E.g. class SomeClass extends NPC {// will be called during deserializationpublic SomeClass(){// call custom constructor of NPCsuper(null);}}class Person extends SomeClass implements Serializable {// ..} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12125076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/870147/']} | jdg_382244 |
stackexchange | llm_judgeable_groundtruth_similarity | 550585 |
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 need to a evaluate the following integral$$I=\int_0^\infty\frac{\ln(x+4)}{\sqrt{x\,(x+3)\,(x+4)}}dx.$$ Both Mathematica and Maple failed to evaluate it in a closed form, and lookups of the approximate numeric value $4.555919963334436...$ in ISC+ and WolframAlpha did not return plausible closed form candidates either. Does anybody by any chance have an idea if a closed form exists for this integral, and what it could be?
Now provide the response and nothing else.
| Here is my solution: Part 1 Let $$I(a)=\int_0^\infty\frac{\log(1+x^2 )}{\sqrt{(1+x^2 )(a^2+x^2 )}}dx\tag{1}$$for $a>1$.Then rewrite the integral as$$\begin{align*}I(a) &= \frac{1}{2}\int_1^\infty\frac{\log x}{\sqrt{x(x-1)(x+a^2-1)}}dx\quad x \mapsto \sqrt{x-1} \\&= \frac{1}{2}\text{Re}\int_0^\infty\frac{\log x}{\sqrt{x(x-1)(x+a^2-1)}}dx \\&= 2 \text{Re}\int_0^\infty \frac{\log x}{\sqrt{(x^2-1)(x^2+a^2-1)}}dx\quad x\mapsto x^2\\ &\stackrel{\color{blue}{[1]}}{=} \text{Re} \left( -i K(a)\log\left(i\sqrt{a^2-1}\right)\right) \\&= \text{Re} \left( K(a)\left( \frac{\pi}{2}-\frac{i}{2}\log(a^2-1)\right)\right)\end{align*}$$where $K(k)$ denotes the complete elliptic integral of the first kind . Furthermore, it is known that$$K(k)=\frac{K\left(\frac{1}{k} \right)+iK'\left(\frac{1}{k} \right)}{k} \quad k>1$$Thus, we obtain$$\begin{align*}I(a)&= \text{Re} \left\{ \frac{K\left(\frac{1}{a} \right)+iK'\left(\frac{1}{a} \right)}{a}\left( \frac{\pi}{2}-\frac{i}{2}\log(a^2-1)\right)\right\} \\&= \frac{\pi}{2a}K\left(\frac{1}{a} \right)+\frac{\log(a^2-1)}{2a}K'\left(\frac{1}{a}\right)\tag{2}\end{align*}$$ Part 2 Now, we turn our attention back to the original problem. $$\begin{align*}\int_0^\infty\frac{\log(x+4)}{\sqrt{x\,(x+3)\,(x+4)}}dx &=2 \int_0^\infty \frac{\log(4+x^2)}{\sqrt{(3+x^2)(4+x^2)}}dx \quad x\mapsto x^2 \\&= 4\int_0^\infty \frac{\log(4+4x^2)}{\sqrt{(3+4x^2)(4+4x^2)}}dx \quad x\mapsto 2x \\&= 2\int_0^\infty \frac{2\log(2)+\log(1+x^2)}{\sqrt{(4x^2+3 )(1+x^2)}}dx \tag{3}\end{align*}$$The first integral is straightforward and it's value is$$\int_0^\infty \frac{1}{\sqrt{(4x^2+3)(1+x^2)}}dx\stackrel{\color{blue}{[2]}}{=} \frac{1}{2}K\left(\frac{1}{2} \right)$$And the second integral can be evaluated as follows:$$\begin{align*}&\; \int_0^\infty \frac{\log(1+x^2)}{\sqrt{(4x^2+3 )(1+x^2)}}dx \\ &= \int_0^\infty \frac{\log(1+x^2)-2\log(x)}{\sqrt{(4+3x^2 )(1+x^2)}}dx\quad x\mapsto 1/x \\&\stackrel{\color{blue}{[1]}}{=}\frac{1}{\sqrt{3}}\int_0^\infty \frac{\log(1+x^2)}{\sqrt{\left(x^2+\frac{4}{3} \right)(1+x^2)}}dx+\frac{1}{2}\log\left(\frac{\sqrt{3}}{2} \right)K\left( \frac{1}{2}\right) \\&= \frac{1}{\sqrt{3}}I\left(\frac{2}{\sqrt{3}} \right)+\frac{1}{2}\log\left(\frac{\sqrt{3}}{2} \right)K\left( \frac{1}{2}\right) \\&\stackrel{\color{blue}{\text{eq }(2)}}{=} \frac{1}{\sqrt{3}}\left(\frac{\pi\sqrt{3}}{4}K\left(\frac{\sqrt{3}}{2}\right) -\frac{\log(3)\sqrt{3}}{4}K\left(\frac{1}{2}\right)\right)+\frac{1}{2}\log\left(\frac{\sqrt{3}}{2} \right)K\left( \frac{1}{2}\right) \\&= \frac{\pi}{4}K\left(\frac{\sqrt{3}}{2}\right)-\frac{\log 2}{2}K\left(\frac{1}{2} \right)\end{align*}$$Substituting everything in equation $(3)$, we get$$\int_0^\infty\frac{\log(x+4)}{\sqrt{x\,(x+3)\,(x+4)}}dx=K\left(\frac{\sqrt3}2\right)\frac\pi2+K\left(\frac12\right)\log(2)$$ Explanations $\color{blue}{[1]}$ Refer to equation $(7.13)$ of this paper . $\color{blue}{[2]}$ In general, we have$$\int_0^\infty \frac{1}{\sqrt{(1+x^2)(a^2+x^2)}}dx=\begin{cases}\displaystyle\frac{1}{a}K' \left(\frac{1}{a} \right)\quad \text{if }a>1 \\ K'(a) \quad \text{if } 0<a<1\end{cases}$$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/550585', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76878/']} | jdg_382245 |
stackexchange | llm_judgeable_groundtruth_similarity | 4297933 |
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 read this line in a book:-"When we ask the C++ implementation to run a program, it does so by calling this function." And I'm wondering about what "C++ implementation" means or what it specifically is. Help!?
Now provide the response and nothing else.
| "C++ implementation" means the compiler plus linker plus standard libraries plus the system that the program actually runs on. Everything except your source, basically. An implementation is something that implements the C++ standard. So the book is not saying that any particular thing calls your function. Rather, that whole bundle, or some part(s) of it, will ensure that main is called. In practice, this means that your compiled executable contains some system-specific startup code, followed by initializers for static objects, followed by a call to your main function. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4297933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463356/']} | jdg_382246 |
stackexchange | llm_judgeable_groundtruth_similarity | 72399551 |
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 set the window size in MAUI? Background info: I only care about Windows for this application - I chose MAUI so I could use Blazor for a desktop application. For some reason the default window size is massive (takes up almost all of my 1440p screen space). The application I'm making only needs about 600x600. Having a way to make the window size fixed would also be helpful although I'm happy to have the app simply be responsive.
Now provide the response and nothing else.
| Updated for Maui GA (I'll add to that discussion too): #if WINDOWSusing Microsoft.UI;using Microsoft.UI.Windowing;using Windows.Graphics;#endifnamespace YourAppNameHere;public partial class App : Application{ const int WindowWidth = 400; const int WindowHeight = 300; public App() { InitializeComponent(); Microsoft.Maui.Handlers.WindowHandler.Mapper.AppendToMapping(nameof(IWindow), (handler, view) => {#if WINDOWS var mauiWindow = handler.VirtualView; var nativeWindow = handler.PlatformView; nativeWindow.Activate(); IntPtr windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(nativeWindow); WindowId windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(windowHandle); AppWindow appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId); appWindow.Resize(new SizeInt32(WindowWidth, WindowHeight));#endif }); MainPage = new MainPage(); } ... OR if want to base it on requested dimensions of MainPage, before appending handler could do: MainPage = new MainPage(); var width = (int)MainPage.WidthRequest; var height = (int)MainPage.HeightRequest; then use those dimensions (probably add some padding to get whole window size, because MainPage is client area). NOTE: I was testing for Windows, so in the drop-down at upper-left of source text editor pane, I had selected ... (net6.0-windows10.0.19041.0) . That's why I did not notice that I needed #if around the using s, to avoid errors on Android etc. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/72399551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2350981/']} | jdg_382247 |
stackexchange | llm_judgeable_groundtruth_similarity | 3676938 |
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 interested in making a game using html and javascript. I was wondering if it really is that much faster drawing in html5 and javascript than it is with images and div's in html and javascript. Example of a game using html and javascript that works nicely: http://scrabb.ly/ Example of a game using html5 and javascript that works nicely: http://htmlchess.sourceforge.net/demo/example.html
Now provide the response and nothing else.
| I've run a bunch of numbers on HTML-made drawing versus Canvas-made drawing. I could make a huge post about the benefits of each, but I will give some of the relevant results of my tests to consider for your specific application: I made Canvas and HTML test pages, both had movable "nodes." Canvas nodes were objects I created and kept track of in Javascript. HTML nodes were <div> s, though they could be <image> or <video> too. I added 100,000 nodes to each of my two tests. They performed quite differently: The HTML test tab took forever to load (timed at slightly under 5 minutes, chrome asked to kill the page the first time). Chrome's task manager says that tab is taking up 168MB. It takes up 12-13% CPU time when I am looking at it, 0% when I am not looking. The Canvas tab loaded in one second and takes up 30MB. It also takes up 13% of CPU time all of the time, regardless of whether or not one is looking at it. Dragging on the HTML page is smoother, which I suppose is expected, since the current setup is to redraw EVERYTHING every 30 milliseconds in the Canvas test. There are plenty of optimizations to be had for Canvas for this. (canvas invalidation being the easiest, also clipping regions, selective redrawing, etc.. just depends on how much you feel like implementing) Video on the HTML page, while I am not moving objects, is actually perfectly smooth . On canvas the video is always slow, since I am redrawing constantly because I turned off my drawing canvas invalidation. There is of course plenty of room for improvement. Drawing/loading alone is far faster in Canvas and has far more room for optimizations, too (ie, excluding things that are off-screen is very easy). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3676938', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146807/']} | jdg_382248 |
stackexchange | llm_judgeable_groundtruth_similarity | 1614316 |
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:
Problem: Prove that if 53 points are chosen from a $13\times 13$ grid then there will necessarily exist a rectangle whose vertices are among the 53 points chosen. My try: I am guessing we have to use Pigeonhole principle. I have observed that at least one of the 13 rows will contain at least 5 lattice points. But I can't proceed further. Also, I observed that it's enough to prove that the number of non rectangle quadrilaterals is less than $\dbinom {53}{4}$. But it turns out that this is not true. So please help.
Now provide the response and nothing else.
| Let's count, chosen one column, how many different pairs of points we can have in that column: this is $ {13 \choose 2}=78.$ Call $a_i$ the number of points that appear in one column, we have that$$a_1+a_2+...+a_{13}=53.$$In the column $i$ there are $a_i \choose 2$ different column-pairs of points, if we prove that$${a_1 \choose 2}+{a_2 \choose 2}+...+{a_{13} \choose 2}>78$$we are done. Now $${a_1 \choose 2}+{a_2 \choose 2}+...+{a_{13} \choose 2}=\frac{a_1^2+...+a_{13}^2-53}{2}.$$But we have also that$$ \frac{a_1^2+...+a_{13}^2}{13}\ge\frac{(a_1+...+a_{13})^2}{13^2}=\frac{53^2}{13^2}$$ hence $a_1^2+...+a_{13}^2\ge216$ and so$${a_1 \choose 2}+{a_2 \choose 2}+...+{a_{13} \choose 2}\ge81>78.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1614316', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/238932/']} | jdg_382249 |
stackexchange | llm_judgeable_groundtruth_similarity | 31915018 |
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 source string is: # Python 3.4.3s = r'abc123d, hello 3.1415926, this is my book' and here is my pattern: pattern = r'-?[0-9]+(\\.[0-9]*)?|-?\\.[0-9]+' however, re.search can give me correct result: m = re.search(pattern, s)print(m) # output: <_sre.SRE_Match object; span=(3, 6), match='123'> re.findall just dump out an empty list: L = re.findall(pattern, s)print(L) # output: ['', '', ''] why can't re.findall give me the expected list: ['123', '3.1415926']
Now provide the response and nothing else.
| There are two things to note here: re.findall returns captured texts if the regex pattern contains capturing groups in it the r'\\.' part in your pattern matches two consecutive chars, \ and any char other than a newline. See findall reference : If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match. Note that to make re.findall return just match values , you may usually remove redundant capturing groups (e.g. (a(b)c) -> abc ) convert all capturing groups into non-capturing (that is, replace ( with (?: ) unless there are backreferences that refer to the group values in the pattern (then see below) use re.finditer instead ( [x.group() for x in re.finditer(pattern, s)] ) In your case, findall returned all captured texts that were empty because you have \\ within r'' string literal that tried to match a literal \ . To match the numbers, you need to use -?\d*\.?\d+ The regex matches: -? - Optional minus sign \d* - Optional digits \.? - Optional decimal separator \d+ - 1 or more digits. See demo Here is IDEONE demo : import res = r'abc123d, hello 3.1415926, this is my book'pattern = r'-?\d*\.?\d+'L = re.findall(pattern, s)print(L) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31915018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5107029/']} | jdg_382250 |
stackexchange | llm_judgeable_groundtruth_similarity | 59949 |
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:
How to track Initialization step by step? Any tricky solution is ok. One condition, x should be DynamicModule variable. DynamicModule[{x}, Dynamic[x], Initialization :> ( x = 1; Pause@1; x = 2; Pause@1; x = 3; )] I want the progress to be reflected in Dynamic[x] .
Now provide the response and nothing else.
| By default, DynamicModule uses SynchronousInitialization -> True . This causes the initialization to be performed on the preemptive link, disabling any updates to the front-end. In particular, print statements, cell creation and dynamic box updates will all be deferred until the initialization completes. If we wish to monitor that initialization within the notebook itself, we must turn off synchronous initialization. If we do so, then any of a number of strategies are possible, such as... ... using Monitor to watch x change within a temporary cell: DynamicModule[{x}, Dynamic[x], SynchronousInitialization -> False, Initialization :> Monitor[x = 1; Pause@1; x = 2; Pause@1; x = 3, x]] ... or CellPrint to watch x change within a permanent cell: DynamicModule[{x}, Dynamic[x], SynchronousInitialization -> False, Initialization :> (CellPrint@Dynamic@x; x = 1; Pause@2; x = 2; Pause@2; x = 3)] ... or even simply using Print to print out some intermediate information: DynamicModule[{x}, Dynamic[x], SynchronousInitialization -> False, Initialization :> (x = 1; Print@"1st"; Pause@2; x = 2; Print@"2nd"; Pause@2; x = 3)] We can even monitor the initialization of x from within the DynamicModule by overriding the default UpdateInterval -> Infinity on Dynamic : DynamicModule[{x}, Dynamic[x, UpdateInterval -> 0], SynchronousInitialization -> False, Initialization :> (x = 1; Pause@1; x = 2; Pause@1; x = 3), UnsavedVariables :> {x}] It is necessary to add x to the list of UnsavedVariables because without it the value of x will not be seen to change dynamically when the output cell is re-initialized in a new front-end session. For Debugging Purposes If debugging messages are our goal, and if it is not acceptable to perform asynchronous initialization for some reason, then a simple solution would be to write logging messages to an external file. That file could then be monitored in real-time using an external utility like tail . It is possible, if ambitious, to use Mathlink to send debugging messages to a second front-end. See, for example, the chat application in this this question . Personally, I think this is overkill. I would probably spend the time getting the DynamicModule to work with asynchronous initialization instead. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/59949', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5478/']} | jdg_382251 |
stackexchange | llm_judgeable_groundtruth_similarity | 4163 |
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 F and G are functors between two arbitrary categories C and D, does a natural transformation η from F to G always exists? What is the condition for its existence? Thanks and regards!
Now provide the response and nothing else.
| For a natural transformation $\eta$ to exist between $F$ and $G$, you need for each object $C$ of C a morphism in $D$ $\eta(C)\colon F(C)\to G(C)$. So for an easy example in which no natural transformation exists, take D to be a category with two objects, $A$ and $B$, and in which the only arrows are $1_A\colon A\to A$ and $1_B\colon B\to B$ (the two identity arrows). Take your favorite category C with at least one object, and let $F$ be the functor that maps every object of C to $A$ and every arrow of C to $1_A$, and take $G$ to be the functor that maps every object of C to $B$ and every arrow of C to $1_B$. Then there can be no natural transformation form $F$ to $G$, since there are no morphisms from $F(C)$ to $G(C)$ for any $C$ in C. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4163', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1281/']} | jdg_382252 |
stackexchange | llm_judgeable_groundtruth_similarity | 352258 |
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:
Similar to this question I a am interested in completely ignoring a drive, but in my case it is one drive which is exposed to the system as a SCSI drive. I have two drives from 21 drives in the server failing and failing: [2524080.689492] scsi 0:0:90900:0: Direct-Access ATA ST3000DM001-1CH1 CC43 PQ: 0 ANSI: 6[2524080.689502] scsi 0:0:90900:0: SATA: handle(0x000d), sas_addr(0x5003048001f298cf), phy(15), device_name(0x0000000000000000)[2524080.689506] scsi 0:0:90900:0: SATA: enclosure_logical_id(0x5003048001f298ff), slot(3)[2524080.689594] scsi 0:0:90900:0: atapi(n), ncq(y), asyn_notify(n), smart(y), fua(y), sw_preserve(y)[2524080.690671] sd 0:0:90900:0: tag#1 CDB: Test Unit Ready 00 00 00 00 00 00[2524080.690680] mpt2sas_cm0: sas_address(0x5003048001f298cf), phy(15)[2524080.690683] mpt2sas_cm0: enclosure_logical_id(0x5003048001f298ff),slot(3)[2524080.690686] mpt2sas_cm0: handle(0x000d), ioc_status(success)(0x0000), smid(17)[2524080.690695] mpt2sas_cm0: request_len(0), underflow(0), resid(0)[2524080.690698] mpt2sas_cm0: tag(65535), transfer_count(0), sc->result(0x00000000)[2524080.690701] mpt2sas_cm0: scsi_status(check condition)(0x02), scsi_state(autosense valid )(0x01)[2524080.690704] mpt2sas_cm0: [sense_key,asc,ascq]: [0x06,0x29,0x00], count(18)[2524080.690728] sd 0:0:90900:0: Attached scsi generic sg0 type 0[2524080.691269] sd 0:0:90900:0: [sdb] 5860533168 512-byte logical blocks: (3.00 TB/2.73 TiB)[2524080.691285] sd 0:0:90900:0: [sdb] 4096-byte physical blocks[2524111.163712] sd 0:0:90900:0: attempting task abort! scmd(ffff880869121800)[2524111.163722] sd 0:0:90900:0: tag#2 CDB: Mode Sense(6) 1a 00 3f 00 04 00[2524111.163729] scsi target0:0:90900: handle(0x000d), sas_address(0x5003048001f298cf), phy(15)[2524111.163733] scsi target0:0:90900: enclosure_logical_id(0x5003048001f298ff), slot(3)[2524111.442310] sd 0:0:90900:0: device_block, handle(0x000d)[2524113.442331] sd 0:0:90900:0: device_unblock and setting to running, handle(0x000d)[2524114.939280] sd 0:0:90900:0: task abort: SUCCESS scmd(ffff880869121800)[2524114.939358] sd 0:0:90900:0: [sdb] Write Protect is off[2524114.939366] sd 0:0:90900:0: [sdb] Mode Sense: 00 00 00 00[2524114.939444] sd 0:0:90900:0: [sdb] Asking for cache data failed[2524114.939501] sd 0:0:90900:0: [sdb] Assuming drive cache: write through[2524114.940380] sd 0:0:90900:0: [sdb] Read Capacity(16) failed: Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK[2524114.940387] sd 0:0:90900:0: [sdb] Sense not available.[2524114.940566] sd 0:0:90900:0: [sdb] Read Capacity(10) failed: Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK[2524114.940570] sd 0:0:90900:0: [sdb] Sense not available.[2524114.940778] sd 0:0:90900:0: [sdb] Attached SCSI disk[2524114.984489] mpt2sas_cm0: removing handle(0x000d), sas_addr(0x5003048001f298cf)[2524114.984494] mpt2sas_cm0: removing : enclosure logical id(0x5003048001f298ff), slot(3)[2524134.939383] mpt2sas_cm0: log_info(0x31111000): originator(PL), code(0x11), sub_code(0x1000)[2524134.940116] mpt2sas_cm0: removing handle(0x000e), sas_addr(0x5003048001f298d0)[2524134.940122] mpt2sas_cm0: removing enclosure logical id(0x5003048001f298ff), slot(4)[2524153.940404] scsi 0:0:90902:0: Direct-Access ATA ST3000DM001-1CH1 CC43 PQ: 0 ANSI: 6[2524153.940418] scsi 0:0:90902:0: SATA: handle(0x000d), sas_addr(0x5003048001f298cf), phy(15), device_name(0x0000000000000000)[2524153.940423] scsi 0:0:90902:0: SATA: enclosure_logical_id(0x5003048001f298ff), slot(3)[2524153.940699] scsi 0:0:90902:0: atapi(n), ncq(y), asyn_notify(n), smart(y), fua(y), sw_preserve(y)[2524153.942194] sd 0:0:90902:0: tag#0 CDB: Test Unit Ready 00 00 00 00 00 00[2524153.942205] mpt2sas_cm0: sas_address(0x5003048001f298cf), phy(15)[2524153.942208] mpt2sas_cm0: enclosure_logical_id(0x5003048001f298ff),slot(3)[2524153.942212] mpt2sas_cm0: handle(0x000d), ioc_status(success)(0x0000), smid(12)[2524153.942214] mpt2sas_cm0: request_len(0), underflow(0), resid(0)[2524153.942217] mpt2sas_cm0: tag(65535), transfer_count(0), sc->result(0x00000000)[2524153.942220] mpt2sas_cm0: scsi_status(check condition)(0x02), scsi_state(autosense valid )(0x01)[2524153.942223] mpt2sas_cm0: [sense_key,asc,ascq]: [0x06,0x29,0x00], count(18)[2524153.942361] sd 0:0:90902:0: Attached scsi generic sg0 type 0[2524153.942833] sd 0:0:90902:0: [sdb] 5860533168 512-byte logical blocks: (3.00 TB/2.73 TiB)[2524153.942840] sd 0:0:90902:0: [sdb] 4096-byte physical blocks[2524154.190159] scsi 0:0:90903:0: Direct-Access ATA ST3000DM001-1CH1 CC43 PQ: 0 ANSI: 6[2524154.190174] scsi 0:0:90903:0: SATA: handle(0x0022), sas_addr(0x5003048001ec55ed), phy(13), device_name(0x0000000000000000)[2524154.190179] scsi 0:0:90903:0: SATA: enclosure_logical_id(0x5003048001ec55ff), slot(1)[2524154.190368] scsi 0:0:90903:0: atapi(n), ncq(y), asyn_notify(n), smart(y), fua(y), sw_preserve(y)[2524154.191634] sd 0:0:90903:0: tag#1 CDB: Test Unit Ready 00 00 00 00 00 00[2524154.191639] mpt2sas_cm0: sas_address(0x5003048001ec55ed), phy(13)[2524154.191642] mpt2sas_cm0: enclosure_logical_id(0x5003048001ec55ff),slot(1)[2524154.191645] mpt2sas_cm0: handle(0x0022), ioc_status(success)(0x0000), smid(12)[2524154.191648] mpt2sas_cm0: request_len(0), underflow(0), resid(0)[2524154.191651] mpt2sas_cm0: tag(65535), transfer_count(0), sc->result(0x00000000)[2524154.191654] mpt2sas_cm0: scsi_status(check condition)(0x02), scsi_state(autosense valid )(0x01)[2524154.191657] mpt2sas_cm0: [sense_key,asc,ascq]: [0x06,0x29,0x00], count(18)[2524154.191800] sd 0:0:90903:0: Attached scsi generic sg3 type 0[2524154.192211] sd 0:0:90903:0: [sdd] 5860533168 512-byte logical blocks: (3.00 TB/2.73 TiB)[2524154.192219] sd 0:0:90903:0: [sdd] 4096-byte physical blocks This is in our case an old server we have decided not to upgrade/fix. And I am now thinking about even not removing old drives out, just leaving them in, making array smaller, and disabling them. The array is not full, and we are using it only as an additional backup location for some other servers. So, me being lazy and not wanting to go to a server room, is there a way to just disable those drives and move on? :-) More information about the system: lspci -nn -v -s 05:00.0 : 05:00.0 Serial Attached SCSI controller [0107]: LSI Logic / Symbios Logic SAS2308 PCI-Express Fusion-MPT SAS-2 [1000:0087] (rev 05) Subsystem: LSI Logic / Symbios Logic SAS2308 PCI-Express Fusion-MPT SAS-2 [1000:3020] Flags: bus master, fast devsel, latency 0, IRQ 29 I/O ports at 7000 [size=256] Memory at df640000 (64-bit, non-prefetchable) [size=64K] Memory at df600000 (64-bit, non-prefetchable) [size=256K] Expansion ROM at df500000 [disabled] [size=1M] Capabilities: [50] Power Management version 3 Capabilities: [68] Express Endpoint, MSI 00 Capabilities: [d0] Vital Product Data Capabilities: [a8] MSI: Enable- Count=1/1 Maskable- 64bit+ Capabilities: [c0] MSI-X: Enable+ Count=16 Masked- Capabilities: [100] Advanced Error Reporting Capabilities: [1e0] #19 Capabilities: [1c0] Power Budgeting <?> Capabilities: [190] #16 Capabilities: [148] Alternative Routing-ID Interpretation (ARI) Kernel driver in use: mpt3sas Kernel modules: mpt3sas lsscsi -v : [0:0:3:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdc dir: /sys/bus/scsi/devices/0:0:3:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:2/end_device-0:0:2/target0:0:3/0:0:3:0][0:0:6:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdf dir: /sys/bus/scsi/devices/0:0:6:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:5/end_device-0:0:5/target0:0:6/0:0:6:0][0:0:7:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdg dir: /sys/bus/scsi/devices/0:0:7:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:6/end_device-0:0:6/target0:0:7/0:0:7:0][0:0:8:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdh dir: /sys/bus/scsi/devices/0:0:8:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:7/end_device-0:0:7/target0:0:8/0:0:8:0][0:0:11:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdi dir: /sys/bus/scsi/devices/0:0:11:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:10/end_device-0:0:10/target0:0:11/0:0:11:0][0:0:12:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdj dir: /sys/bus/scsi/devices/0:0:12:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:11/end_device-0:0:11/target0:0:12/0:0:12:0][0:0:13:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdk dir: /sys/bus/scsi/devices/0:0:13:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:12/end_device-0:0:12/target0:0:13/0:0:13:0][0:0:15:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdl dir: /sys/bus/scsi/devices/0:0:15:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:14/end_device-0:0:14/target0:0:15/0:0:15:0][0:0:16:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdm dir: /sys/bus/scsi/devices/0:0:16:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:15/end_device-0:0:15/target0:0:16/0:0:16:0][0:0:18:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdn dir: /sys/bus/scsi/devices/0:0:18:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:17/end_device-0:0:17/target0:0:18/0:0:18:0][0:0:20:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdo dir: /sys/bus/scsi/devices/0:0:20:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:19/end_device-0:0:19/target0:0:20/0:0:20:0][0:0:21:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdp dir: /sys/bus/scsi/devices/0:0:21:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:20/end_device-0:0:20/target0:0:21/0:0:21:0][0:0:22:0] enclosu LSI CORP SAS2X36 0717 - dir: /sys/bus/scsi/devices/0:0:22:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:21/end_device-0:0:21/target0:0:22/0:0:22:0][0:0:23:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdq dir: /sys/bus/scsi/devices/0:0:23:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:1/expander-0:1/port-0:1:1/end_device-0:1:1/target0:0:23/0:0:23:0][0:0:24:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdr dir: /sys/bus/scsi/devices/0:0:24:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:1/expander-0:1/port-0:1:2/end_device-0:1:2/target0:0:24/0:0:24:0][0:0:25:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sds dir: /sys/bus/scsi/devices/0:0:25:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:1/expander-0:1/port-0:1:3/end_device-0:1:3/target0:0:25/0:0:25:0][0:0:26:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdt dir: /sys/bus/scsi/devices/0:0:26:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:1/expander-0:1/port-0:1:4/end_device-0:1:4/target0:0:26/0:0:26:0][0:0:28:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdu dir: /sys/bus/scsi/devices/0:0:28:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:1/expander-0:1/port-0:1:6/end_device-0:1:6/target0:0:28/0:0:28:0][0:0:30:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdw dir: /sys/bus/scsi/devices/0:0:30:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:1/expander-0:1/port-0:1:8/end_device-0:1:8/target0:0:30/0:0:30:0][0:0:31:0] disk ATA ST3000DM001-1CH1 CC43 /dev/sdx dir: /sys/bus/scsi/devices/0:0:31:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:1/expander-0:1/port-0:1:9/end_device-0:1:9/target0:0:31/0:0:31:0][0:0:34:0] enclosu LSI CORP SAS2X28 0717 - dir: /sys/bus/scsi/devices/0:0:34:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:1/expander-0:1/port-0:1:12/end_device-0:1:12/target0:0:34/0:0:34:0][0:0:25856:0]disk ATA ST3000DM001-1CH1 CC43 /dev/sda dir: /sys/bus/scsi/devices/0:0:25856:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:14357/end_device-0:0:14357/target0:0:25856/0:0:25856:0][0:0:98760:0]disk ATA ST3000DM001-1CH1 CC43 - dir: /sys/bus/scsi/devices/0:0:98760:0 [/sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0/port-0:0/expander-0:0/port-0:0:60931/end_device-0:0:60931/target0:0:98760/0:0:98760:0][2:0:0:0] disk ATA PLEXTOR PX-128M5 1.00 /dev/sdy dir: /sys/bus/scsi/devices/2:0:0:0 [/sys/devices/pci0000:00/0000:00:1f.2/ata2/host2/target2:0:0/2:0:0:0] lsscsi -Hv : [0] mpt2sas dir: /sys/class/scsi_host//host0 device dir: /sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0/host0[1] ahci dir: /sys/class/scsi_host//host1 device dir: /sys/devices/pci0000:00/0000:00:1f.2/ata1/host1[2] ahci dir: /sys/class/scsi_host//host2 device dir: /sys/devices/pci0000:00/0000:00:1f.2/ata2/host2[3] ahci dir: /sys/class/scsi_host//host3 device dir: /sys/devices/pci0000:00/0000:00:1f.2/ata3/host3[4] ahci dir: /sys/class/scsi_host//host4 device dir: /sys/devices/pci0000:00/0000:00:1f.2/ata4/host4[5] ahci dir: /sys/class/scsi_host//host5 device dir: /sys/devices/pci0000:00/0000:00:1f.2/ata5/host5[6] ahci dir: /sys/class/scsi_host//host6 device dir: /sys/devices/pci0000:00/0000:00:1f.2/ata6/host6 smp_discover /dev/bsg/expander-0:0 : phy 0:S:attached:[500605b00507dd20:03 i(SSP+STP+SMP)] 6 Gbps phy 1:S:attached:[500605b00507dd20:02 i(SSP+STP+SMP)] 6 Gbps phy 2:S:attached:[500605b00507dd20:01 i(SSP+STP+SMP)] 6 Gbps phy 3:S:attached:[500605b00507dd20:00 i(SSP+STP+SMP)] 6 Gbps phy 12:U:attached:[5003048001f298cc:00 t(SATA)] 6 Gbps phy 13:U:attached:[5003048001f298cd:00 t(SATA)] 6 Gbps phy 14:U:attached:[5003048001f298ce:00 t(SATA)] 6 Gbps phy 17:U:attached:[5003048001f298d1:00 t(SATA)] 6 Gbps phy 19:U:attached:[5003048001f298d3:00 t(SATA)] 6 Gbps phy 20:U:attached:[5003048001f298d4:00 t(SATA)] 6 Gbps phy 21:U:attached:[5003048001f298d5:00 t(SATA)] 6 Gbps phy 22:U:attached:[5003048001f298d6:00 t(SATA)] 6 Gbps phy 23:U:attached:[5003048001f298d7:00 t(SATA)] 6 Gbps phy 25:U:attached:[5003048001f298d9:00 t(SATA)] 6 Gbps phy 26:U:attached:[5003048001f298da:00 t(SATA)] 6 Gbps phy 27:U:attached:[5003048001f298db:00 t(SATA)] 6 Gbps phy 28:U:attached:[5003048001f298dc:00 t(SATA)] 6 Gbps phy 29:U:attached:[5003048001f298dd:00 t(SATA)] 6 Gbps phy 31:U:attached:[5003048001f298df:00 t(SATA)] 6 Gbps phy 32:U:attached:[5003048001f298e0:00 t(SATA)] 6 Gbps phy 33:U:attached:[5003048001f298e1:00 t(SATA)] 6 Gbps phy 34:U:attached:[5003048001f298e2:00 t(SATA)] 6 Gbps phy 35:U:attached:[5003048001f298e3:00 t(SATA)] 6 Gbps phy 36:D:attached:[5003048001f298fd:00 V i(SSP+SMP) t(SSP)] 6 Gbps
Now provide the response and nothing else.
| The very high SCSI device numbers ( scsi 0:0:90903:0 ) show that there's a problem in this case that the hardware keeps dropping & re-initializing the drive. The MPT SAS hardware does most of the re-initializing itself here, so we can't entirely control that from the Kernel. Separately, you mention having 21 drives, so they are probably behind one or more SAS expanders. The question then becomes, it is possible, in software, to disable a port on a SAS expander? If the expander actually supports it (I think it was optional in the standard), then yes! The package in question is smp_utils . sg3_utils will also be helpful). What you want is: Figure out the expander device per the manpage above (probably ls /dev/bsg/expand* ) Confirm the faulty disks are attached to the phys from the dmesg: smp_discover /dev/bsg/expander-... . Disable the PHYs, in the form of smp_phy_control --phy=NN --op=di /dev/bsg/expander-... . Expanded for your case: smp_phy_control --phy=13 --op=di /dev/bsg/expander-0:0smp_phy_control --phy=15 --op=di /dev/bsg/expander-0:0 The phy numbers were already in your output: 13 , 15 , but you might want to confirm them using smp_discover . | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/352258', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/14710/']} | jdg_382253 |
stackexchange | llm_judgeable_groundtruth_similarity | 47331 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It's my understanding of observational astronomy that the size of a telescope limits its effective angular resolution, which is why scientists needed to use radio telescopes all over the globe to look at the M87 black hole and Sagittarius A*. For the sake of convenience, let's define a "good picture" as at least 100-by-100 pixels, and assume that all neutron stars have a diameter of 20 km. With this assumption, the nearest known neutron star is PSR J0108−1431 , at 424 light years away. This gives our neutron star an angular diameter of $2.9\times10^{-13}$ degrees, so the image would need a resolution of $2.9\times10^{-15}$ degrees per pixel. How big would a telescope need to be to see this accurately?
Now provide the response and nothing else.
| The angular resolution is just $\sim \lambda/D$ (in radians), where $\lambda$ is the wavelength and $D$ is the telescope diameter (or the size of an interferometer). So plug in the numbers you like. To resolve the optical emission (say $\lambda = 500$ nm) at the angular power you specify would require $ D =10^{10}$ m. EDIT: Here is my working. A 20000 m diameter neutron star at a distance of 424 light years (= $4.01\times 10^{18}$ m), subtends an angle of $5\times 10^{-15}$ radians. To resolve this into 100 pixels requires a resolution of $5\times 10^{-17}$ radians. Then $D = \lambda/5\times 10^{-17} = 10^{10}$ m. | {} | {'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/47331', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/42435/']} | jdg_382254 |
stackexchange | llm_judgeable_groundtruth_similarity | 49098 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I have a function that looks something like this: float function(){ float x = SomeValue; return x / SomeOtherValue;} At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this: float function(){ float x = SomeValue; cout << x; return x / SomeOtherValue;} and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing? (If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.)
Now provide the response and nothing else.
| Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register). When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases. See the MSDN documentation on VC++ floating point switches . You could try compiling with /fp:strict and seeing what happens. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2147/']} | jdg_382255 |
stackexchange | llm_judgeable_groundtruth_similarity | 10147075 |
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 the following API definition I need to be able to filter Events by Product Alias. Given that an Event belongs to a Job and a Job belongs to a Product I'm not sure how to spec that. api.py: class ProductResource(ModelResource): class Meta: queryset = Product.objects.all() resource_name = 'product' allowed_methods = ['get'] excludes = ['created_at','updated_at'] filtering = { 'alias': ALL }class EnvironmentResource(ModelResource): class Meta: queryset = Environment.objects.all() resource_name = 'environment' allowed_methods = ['get'] excludes = ['created_at','updated_at']class JobResource(ModelResource): product = fields.ForeignKey(ProductResource, 'product') class Meta: queryset = Job.objects.all() resource_name = 'job' allowed_methods = ['get'] excludes = ['created_at','updated_at']class EventResource(ModelResource): environment = fields.ForeignKey(EnvironmentResource, 'environment',full=True) job = fields.ForeignKey(JobResource, 'job',full=True) class Meta: queryset = Event.objects.all() resource_name = 'event' allowed_methods = ['get'] excludes = ['created_at','updated_at'] filtering = { HOW DO I FILTER BY PRODUCT ALIAS???? }
Now provide the response and nothing else.
| Given the following filtering specs: # In EventResourcefiltering = { 'job' : ALL_WITH_RELATIONS}# In JobResourcefiltering = { 'product' : ALL_WITH_RELATIONS}# In ProductResourcefiltering = { 'alias' : ALL} You should be able to do: /api/events/job__product__alias=something | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10147075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131875/']} | jdg_382256 |
stackexchange | llm_judgeable_groundtruth_similarity | 25560629 |
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 can think of several reasons why HashMap s with integer keys are much better than SparseArray s: The Android documentation for a SparseArray says "It is generally slower than a traditional HashMap ". If you write code using HashMap s rather than SparseArray s your code will work with other implementations of Map and you will be able to use all of the Java APIs designed for Maps. If you write code using HashMap s rather than SparseArray s your code will work in non-android projects. Map overrides equals() and hashCode() whereas SparseArray doesn't. Yet whenever I try to use a HashMap with integer keys in an Android project, IntelliJ tells me I should use a SparseArray instead. I find this really difficult to understand. Does anyone know any compelling reasons for using SparseArray s?
Now provide the response and nothing else.
| SparseArray can be used to replace HashMap when the key is a primitive type.There are some variants for different key/value types, even though not all of them are publicly available. Benefits are: Allocation-free No boxing Drawbacks: Generally slower, not indicated for large collections They won't work in a non-Android project HashMap can be replaced by the following: SparseArray <Integer, Object>SparseBooleanArray <Integer, Boolean>SparseIntArray <Integer, Integer>SparseLongArray <Integer, Long>LongSparseArray <Long, Object>LongSparseLongArray <Long, Long> //this is not a public class //but can be copied from Android source code In terms of memory, here is an example of SparseIntArray vs HashMap<Integer, Integer> for 1000 elements: SparseIntArray : class SparseIntArray { int[] keys; int[] values; int size;} Class = 12 + 3 * 4 = 24 bytes Array = 20 + 1000 * 4 = 4024 bytes Total = 8,072 bytes HashMap : class HashMap<K, V> { Entry<K, V>[] table; Entry<K, V> forNull; int size; int modCount; int threshold; Set<K> keys Set<Entry<K, V>> entries; Collection<V> values;} Class = 12 + 8 * 4 = 48 bytes Entry = 32 + 16 + 16 = 64 bytes Array = 20 + 1000 * 64 = 64024 bytes Total = 64,136 bytes Source: Android Memories by Romain Guy from slide 90. The numbers above are the amount of memory (in bytes) allocated on heap by JVM.They may vary depending on the specific JVM used. The java.lang.instrument package contains some helpful methods for advanced operations like checking the size of an object with getObjectSize(Object objectToSize) . Extra info is available from the official Oracle documentation . Class = 12 bytes + (n instance variables) * 4 bytes Array = 20 bytes + (n elements) * (element size) Entry = 32 bytes + (1st element size) + (2nd element size) | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/25560629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3973077/']} | jdg_382257 |
stackexchange | llm_judgeable_groundtruth_similarity | 12024706 |
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 my astonishment, this compiles: const char* c_str(){ static const char nullchar = '\0'; return nullchar;} and it introduced a bug in my code. Thankfully, I caught it. Is this intentional by C++, or a compiler bug? Is there a reason why the data type is actively ignored? It worked in Visual C++ 2010 and GCC , but I don't understand why it should work, given the obvious data type mismatch. (The static isn't necessary, either.)
Now provide the response and nothing else.
| As you've defined it, nullchar is an integer constant expression with the value 0. The C++03 standard defines an null pointer constant as: "A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates tozero." To make a long story short, your nullchar is a null pointer constant, meaning it can be implicitly converted and assigned to essentially any pointer. Note that all those elements are required for that implicit conversion to work though. For example, if you had used '\1' instead of '\0' , or if you had not specified the const qualifier for nullchar , you wouldn't get the implicit conversion -- your assignment would have failed. Inclusion of this conversion is intentional but widely known as undesirable. 0 as a null pointer constant was inherited from C. I'm fairly sure Bjarne and most of the rest of the C++ standard committee (and most of the C++ community in general) would dearly love to remove this particular implicit conversion, but doing so would destroy compatibility with a lot of C code (probably close to all of it). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12024706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541686/']} | jdg_382258 |
stackexchange | llm_judgeable_groundtruth_similarity | 1110057 |
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 2 applications: Manager UI - Which should be able to create a user with all its fields (username, email, age etc.) and display them. Core component - which only need the UserId and Username field, and need to be very performant. It also shouldn't be able to write to the database. It seems I need 2 different models, one for the UI application and a second one for the core component. When I create the 1st model, life's good. But when I try to create the 2nd model, I get all the unneccessary fields. If I try to delete them - I manage to do that only for the nullable fields, but not for the required ones (which is only required for saving, actually). Here's what I get: "Column Users.email in table Users must be mapped: It has no default value and is not nullable." Setting the "email" field as private getter & setter will not solve my issue, since I don't want to store the value at all on the entity (and fetch the field from the database) - as I said, this application needs to be as performant as possible. I believe that if I could somehow set the model as read-only, it will solve this, but it's only a hunch (and I couldn't find a way to do that - is therer?) Any help would be appreciated.Thanks,Nir.
Now provide the response and nothing else.
| I had this exact problem where I was animating the tab bar and navigation bar off the bottom and top of the screen respectively, leaving a 49px high white space where the tab bar was. It turns out that the reason my new "fullscreen" view wasn't actually filling the space was because I was adding the fullscreen view as a subview of the navigation controller's view, which itself was a child of the tab bar controller. To fix it, I simply added the new fullscreen view (in your case the view with all the text) as a subview of the UITabBarController's view. [[[self tabBarController] view] addSubview:yourTextView]; Then all you need to do is make sure that your subview's frame is 480 x 320px and it should fill the screen (including the area that was previously the mysterious white space) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1110057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112189/']} | jdg_382259 |
stackexchange | llm_judgeable_groundtruth_similarity | 191725 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $X$ be a smooth projective irreducible curve defined over an algebraically closed field $\mathbb{K}$ (of arbitrary characteristic), and let $p\in X$ be a closed point. Denote by $\mathcal{O}_p(X)$ the local ring of rational functions which are regular at $p$. Then, is it true that the completion of $\mathcal{O}_p(X)$ (with respect to its maximal ideal) is isomorphic to the ring $\mathbb{K}[[x]]$ of formal power series in one variable ? I think that it should follow from Cohen theorem, but I cannot find a reference for this. Most of the results on this are in commutative ring theory books (for example Matsumura) but not really in the language of algebraic geometry. Can someone please give me a reference? I need this result in a research article. Thanks in advance.
Now provide the response and nothing else.
| Let me expand and generalize my comments above. We can prove the following Proposition. Let $X$ be a projective scheme of dimension $n$ which is defined over an algebraically closed field $k$. If $p \in X$ is a closed, regular point and $\mathcal{O}_{X, \, p}$ is the local ring of $X$ at $p$, then there is an isomorphism $$\widehat{\mathcal{O}}_{X, \, p}= k[[x_1, \ldots, x_n]].$$ Proof. The ring $\mathcal{O}_{X, \, p}$ is a Noetherian regular local ring of dimension $n$, whose residue field is $k$ since $p \in X$ is a closed point and $k$ is algebraically closed. Therefore its $\mathfrak{m}$-adic completion $\widehat{\mathcal{O}}_{X, \,p}$ is a Noetherian complete regular ring with the same residue field and the same dimension, see Atiyah-MacDonald: Introduction to Commutative Algebra , Proposition 10.15, Theorem 10.26, Corollary 11.19, Proposition 11.24. By Cohen structure theorem it follows that $\widehat{\mathcal{O}}_{X, \,p}$ is a formal power series over its residue field. Since its dimension is $n$, this implies that it is isomorphic to $k[[x_1, \ldots, x_n]]$ and we are done. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/191725', 'https://mathoverflow.net', 'https://mathoverflow.net/users/23758/']} | jdg_382260 |
stackexchange | llm_judgeable_groundtruth_similarity | 6833914 |
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 clean information in a form after submit so that it does not show this error after a page refresh? See image (from chrome): The dialog has the text: The page that you're looking for used information that you entered. Returning to that page might cause any action you took to be repeated. Do you want to continue? I want this dialog not to appear.
Now provide the response and nothing else.
| Edit: It's been a few years since I originally posted this answer, and even though I got a few upvotes, I'm not really happy with my previous answer, so I have redone it completely. I hope this helps. When to use GET and POST : One way to get rid of this error message is to make your form use GET instead of POST . Just keep in mind that this is not always an appropriate solution (read below). Always use POST if you are performing an action that you don't want to be repeated, if sensitive information is being transferred or if your form contains either a file upload or the length of all data sent is longer than ~2000 characters . Examples of when to use POST would include: A login form A contact form A submit payment form Something that adds, edits or deletes entries from a database An image uploader (note, if using GET with an <input type="file"> field, only the filename will be sent to the server, which 99.73% of the time is not what you want.) A form with many fields (which would create a long URL if using GET) In any of these cases, you don't want people refreshing the page and re-sending the data. If you are sending sensitive information, using GET would not only be inappropriate, it would be a security issue ( even if the form is sent by AJAX ) since the sensitive item (e.g. user's password) is sent in the URL and will therefore show up in server access logs. Use GET for basically anything else. This means, when you don't mind if it is repeated, for anything that you could provide a direct link to, when no sensitive information is being transferred, when you are pretty sure your URL lengths are not going to get out of control and when your forms don't have any file uploads. Examples would include: Performing a search in a search engine A navigation form for navigating around the website Performing one-time actions using a nonce or single use password (such as an "unsubscribe" link in an email). In these cases POST would be completely inappropriate. Imagine if search engines used POST for their searches. You would receive this message every time you refreshed the page and you wouldn't be able to just copy and paste the results URL to people, they would have to manually fill out the form themselves. If you use POST : To me, in most cases even having the "Confirm form resubmission" dialog pop up shows that there is a design flaw. By the very nature of POST being used to perform destructive actions, web designers should prevent users from ever performing them more than once by accidentally (or intentionally) refreshing the page. Many users do not even know what this dialog means and will therefore just click on "Continue". What if that was after a "submit payment" request? Does the payment get sent again? So what do you do? Fortunately we have the Post/Redirect/Get design pattern. The user submits a POST request to the server, the server redirects the user's browser to another page and that page is then retrieved using GET. Here is a simple example using PHP: if(!empty($_POST['username'] && !empty($_POST['password'])) { $user = new User; $user->login($_POST['username'], $_POST['password']); if ($user->isLoggedIn()) { header("Location: /admin/welcome.php"); exit; } else { header("Location: /login.php?invalid_login"); }} Notice how in this example even when the password is incorrect , I am still redirecting back to the login form. To display an invalid login message to the user, just do something like: if (isset($_GET['invalid_login'])) { echo "Your username and password combination is invalid";} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6833914', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/854712/']} | jdg_382261 |
stackexchange | llm_judgeable_groundtruth_similarity | 12264 |
Below is a question asked on the forum ai.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you actually decide what reward value to give for each action in a given state for an environment? Is this purely experimental and down to the programmer of the environment? So, is it a heuristic approach of simply trying different reward values and see how the learning process shapes up? Of course, I understand that the reward values have to make sense, and not just put completely random values, i.e. if the agent makes mistakes then deduct points, etc. So, am I right in saying it's just about trying different reward values for actions encoded in the environment and see how it affects the learning?
Now provide the response and nothing else.
| In Reinforcement Learning (RL), a reward function is part of the problem definition and should: Be based primarily on the goals of the agent. Take into account any combination of starting state $s$ , action taken $a$ , resulting state $s'$ and/or a random amount (a constant amount is just a random amount with a fixed value having probability 1). You should not use other data than those four things, but you also do not have to use any of them. This is important, as using any other data stops your environment from being a Markov Decision Process (MDP). Given the first point, as direct and simple as possible. In many situations this is all you need. A reward of +1 for winning a game, 0 for a draw and -1 for losing is enough to fully define the goals of most 2-player games. In general, have positive rewards for things you want the agent to achieve or repeat, and negative rewards for things you want the agent to avoid or minimise doing. It is common for instance to have a fixed reward of -1 per time step when the objective is to complete a task as fast as possible. In general, reward 0 for anything which is not directly related to the goals. This allows the agent to learn for itself whether a trajectory that uses particular states/actions or time resources is worthwhile or not. Be scaled for convenience. Scaling all rewards by a common factor does not matter at a theoretical level, as the exact same behaviour will be optimal. In practice you want the sums of reward to be easy to assess by yourself as you analyse results of learning, and you also want whatever technical solution you implement to be able to cope with the range of values. Simple numbers such as +1/-1 achieve that for basic rewards. Ideally, you should avoid using heuristic functions that reward an agent for interim goals or results, as that inserts your opinion about how the problem should be solved into the system, and may not in fact be optimal given the goals. In fact you can view the purpose of value-based RL is learning a good heuristic function (the value function) from the more sparse reward function. If you already had a good heuristic function then you may not need RL at all. You may need to compare very different parts of the outcome in a single reward function. This can be hard to balance correctly, as the reward function is a single scalar value and you have to define what it means to balance between different objectives within a single scenario. If you do have very different metrics that you want to combine then you need to think harder about what that means: Where possible, flatten the reward signal into the same units and base your goals around them. For instance, in business and production processes if may be possible to use currency as the units of reward and convert things such as energy used, transport distance, etc., into that currency. For highly negative/unwanted outcomes, instead of assigning a negative reward, consider whether a constraint on the environment is more appropriate. You may have opinions about valid solutions to the environment that you want the agent to use. In which case you can extend or modify the system of rewards to reflect that - e.g. provide a reward for achieving some interim sub-goal, even if it is not directly a result that you care about. This is called reward shaping , and can help in practical ways in difficult problems, but you have to take extra care not to break things. There are also more sophisticated approaches that use multiple value schemes or no externally applied ones, such as hierarchical reinforcement learning or intrinsic rewards. These may be necessary to address more complex "real life" environments, but are still subject of active research. So bear in mind that all the above advice describes the current mainstream of RL, and there are more options the deeper you research the topic. Is this purely experimental and down to the programmer of the environment. So, is it a heuristic approach of simply trying different reward values and see how the learning process shapes up? Generally no. You should base the reward function on the analysis of the problem and your learning goals. And this should be done at the start, before experimenting with hyper-parameters which define the learning process. If you are trying different values, especially different relative values between different aspects of a problem, then you may be changing what it means for the agent to behave optimally. That might be what you want to do, because you are looking at how you want to frame the original problem to achieve a specific behaviour. However, outside of inverse reinforcement learning , it is more usual to want an optimal solution to a well-defined problem, as opposed to a solution that matches some other observation that you are willing to change the problem definition to meet. So, am I right in saying it's just about trying different reward values for actions encoded in the environment and see how it affects the learning? This is usually not the case. Instead, think about how you want to define the goals of the agent. Write reward functions that encapsulate those goals. Then focus on changes to the agent that allow it to better learn how to achieve those goals. Now, you can do it the way round, as you suggest. But what you are doing, in that case, is changing the problem definition, and seeing how well a certain kind of agent can cope with solving each kind of problem. | {} | {'log_upvote_score': 4, 'links': ['https://ai.stackexchange.com/questions/12264', 'https://ai.stackexchange.com', 'https://ai.stackexchange.com/users/25360/']} | jdg_382262 |
stackexchange | llm_judgeable_groundtruth_similarity | 1203082 |
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 ran into a a site that injects a "Read More: " line at the end of any text that you highlight and copy from it's pages. I've never seen this before, and without severely digging into their code, I can't find the code that does this. Anyone know how this is done? Example: http://peaceful-parenting.suite101.com/article.cfm/how_to_keep_kids_from_climbing_on Copy a paragraph of text, and paste it into another application, and there will be a "read more" line afterwards.
Now provide the response and nothing else.
| Suite101 is using a 3rd party service called Tynt . Tynt's JavaScript snippet is located at http://tcr.tynt.com/javascripts/Tracer.js I explored the source for you (with some help from the Online JavaScript beautifier ). So here's what's happening: the code activates on events like mouseup, mousedown, and copy (in the startListeningForTraces function) if the user selected a range of text, then it: creates the HTML for an attribution link, plus optional CC license URL appends this HTML to the selection, placing it inside a zero-size <div> (to keep it invisible on-screen) reports what was copied back to Tynt's servers Tynt's code does a tremendous amount of work to make this work seamlessly across browsers. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1203082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12382/']} | jdg_382263 |
stackexchange | llm_judgeable_groundtruth_similarity | 6126065 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While programming in C++ with Qt what includes should I make? Just 2 includes #include <QtCore>#include <QtGui> or #include <QWidget>#include <QDialog>#include <QList>#include <QKeyEvent>#include <QObject> for every class? Thanks!
Now provide the response and nothing else.
| Include only the definitions of the classes you need - anything else isn't just lazy, it's extremely wasteful and to my mind bad style. Including QtGui (which itself includes QtCore) will lead to adding about 350(!) header files to your compilation, when in your example you only needed 6. Compiling will take longer, and when someone tries to maintain your app and is browsing your files they won't be able to infer from just the includes what exactly it is each file/class is trying to do - they'll have to read the entire source to get an idea. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6126065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_382264 |
stackexchange | llm_judgeable_groundtruth_similarity | 2711522 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was curious to know what would happen if I assign a negative value to an unsigned variable. The code will look somewhat like this. unsigned int nVal = 0;nVal = -5; It didn't give me any compiler error. When I ran the program the nVal was assigned a strange value! Could it be that some 2's complement value gets assigned to nVal ?
Now provide the response and nothing else.
| For the official answer - Section 4.7 conv.integral "If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2 n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). —end note ] This essentially means that if the underlying architecture stores in a method that is not Two's Complement (like Signed Magnitude, or One's Complement), that the conversion to unsigned must behave as if it was Two's Complement. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2711522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166012/']} | jdg_382265 |
stackexchange | llm_judgeable_groundtruth_similarity | 40381 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As an American, I have been watching the Brexit proceedings with some confusion. To all appearances, British politicians do not want to compromise, and the European leaders do not want to compromise. This suggests that a no-deal Brexit will occur on the 12th of April (Friday). Given the dire warnings about the dangers of a no-deal Brexit, I would have expected people to be taking precautions, such as stockpiling food or medicine. Why is that not happening? Are the deleterious effects of a no-deal Brexit longer term rather than shorter term? Or is everyone assuming that some kind of deal will be struck at the last minute?
Now provide the response and nothing else.
| Given the dire warnings about the dangers of a no-deal Brexit, I would have expected people to be taking precautions, such as stockpiling food This is happening, from the FT (February 2019) : But the closely watched purchasing managers’ index compiled by IHS Markit/CIPS on Friday showed concrete evidence that stockpiling was becoming widespread — particularly in the food and drink, clothing, chemical and plastics, and electrical and electronics sectors — and was being implemented at more larger companies than small ones. or medicine. Same here, from the Guardian ( first quote , second quote ): The government is in talks with drug companies about funding the extra costs of stockpiling and flying in vital medicines in the event of a no-deal Brexit, the health secretary has revealed. Patients should consider stockpiling their own drugs if it looks likely the UK will leave the EU with no deal, the pharmaceuticals industry has said, telling MPs that such a scenario could be “catastrophic” for medicine supplies and necessitate emergency powers. Why is that not happening? Are the deleterious effects of a no-deal Brexit longer term rather than shorter term? There are many effects, both in the long term and in the short term. The stockpiling is actually only a band-aid solution, especially with regard to fresh food one can only stockpile for a few weeks (or less), according to the BBC : Fresh food - which cannot be stockpiled - is the biggest concern. A vegetable shortage last year, driven by bad weather in southern Europe, highlighted this dependence, and led to a flurry of pictures on social media of empty supermarket shelves. The thing with most food (and other importers, like manufacturing plants ) coming into the UK is that it works with so-called just-in-time deliveries, from the BBC : The UK's supply chains work on a "just in time" basis, meaning stock is delivered daily, not stored for long periods in warehouses. [...] To illustrate the complexity, Paul Martin, UK head of retail at consultancy KPMG, says 290 trucks come through Dover each day just supplying citrus fruits. He says any level of disruption, such as trucks needing to pass extra inspections, is likely to have an impact. One of the 'problems' here is that UK imports rely heavily on the Dutch Port of Rotterdam. Indeed, many imports to the UK from Asia go via Rotterdam. Or to quote Mark Dijk, the Port's external affairs manager (as cited by the Independent ): “We are also a hub for the UK. All the deep-sea ships from China are coming into Rotterdam, and their goods are then going into shallow water ships to the UK,” Or is everyone assuming that some kind of deal will be struck at the last minute? No, as pointed out by Fizz, there are no-deal preparations going on on both sides of the Channel. And those preparations have been going on for a while now. | {} | {'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/40381', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/14403/']} | jdg_382266 |
stackexchange | llm_judgeable_groundtruth_similarity | 4857592 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Are there any cases where str() throws an exception in Python?
Now provide the response and nothing else.
| Yes, it can fail for custom classes: >>> class C(object):... def __str__(self):... return 'oops: ' + oops...>>> c = C()>>> str(c)NameError: global name 'oops' is not defined It can even fail for some of the built-in classes, such as unicode : >>> u = u'\xff'>>> s = str(u)UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0:ordinal not in range(128) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4857592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212555/']} | jdg_382267 |
stackexchange | llm_judgeable_groundtruth_similarity | 55370851 |
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 missing something here with the validation how to add types validation? Having error "element 'children' implicitly has an 'any' type". import * as React from 'react';import Button from './Styles';const Button1 = ({ children, ...props }) => ( <Button {...props}>{children}</Button>);Button1.propTypes = {};export default Button1;
Now provide the response and nothing else.
| Edit 2022:with react 18, FC no longer provides children, so you have to type it yourself, and you can drop FC: import React, { ReactNode } from "react";interface Props { children?: ReactNode // any props that come into the component}const Button1 = ({ children, ...props }: Props) => ( <Button {...props}>{children}</Button>); Yes you are missing a type for Props as whole, which means typescript sees it as any and your ts rules dont allow it. You have to type your props as: import React, { FC } from "react";interface Props { // any props that come into the component}const Button1: FC<Props> = ({ children, ...props }) => ( <Button {...props}>{children}</Button>); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/55370851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3876861/']} | jdg_382268 |
stackexchange | llm_judgeable_groundtruth_similarity | 1796376 |
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 am trying to show that the sphere $S^2$ and $\mathbb{R}^2$ are not homeomorphic.I understand that you can't 'compress' a 3D shape into a 2D plane but I don't know how I would express this formally. $S^2 = \{(x, y, z) ∈ \mathbb{R}^3: x^2 + y^2 + z^2 = 1\}$ As always, any help is appreciated!
Now provide the response and nothing else.
| Homeomorphism will preserve any "topological" property of spaces - in particular, $S^2$ is compact and $\mathbb R^2$ is not, so they can't be homeomorphic. In fact, the image of a compact space under a continuous map is compact, so there is not even a surjective continuous map $S^2 \to \mathbb R^2$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1796376', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/277397/']} | jdg_382269 |
stackexchange | llm_judgeable_groundtruth_similarity | 623171 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I made and built the following circuit. It measures current of an AC square wave of roughly ~19 V.The uController calculates a running average of 5 samples every millisecond. If the average exceeds tollerance (which you can set with the potentiometer) the power is cut off for 5 seconds and a red LED will light up. It will automatically re-apply power after 5 seconds. The square wave is led through the diodes so that both negative and positive cycles flow through the same MOSFET and through the 2 shunt resistors. The purpose is to split a large circuit which can suffer from physical short circuits into smaller circuits. If one of the circuits suffer from a short, the others remain unaffected (the 5 ms is fast enough). Some loads may draw peak currents of ~1.8 A which are to be ignored. That is what the average calculation is for. This circuit lacks current limiting. It is designed with AC IN being 3 A or lower. I now have the problem that somebody wants to use this circuit with a 7 A power supply. I am not sure if my 2 A diodes will survive 7 A for 5 ms. I can alter the software of the prototype to react instantly if more than 3 A is measured in a single sample. And I will increase the sample rate to whatever maximum frequency is possible. I believe I can reduce the short time to 0.1 ms. But I am yet to dive in the attiny's datasheet to see what is achievable. I figured it may be better to limit the current in the first place. I would like to know how I can incorporate a current limiting circuit of ~1.5 A in my circuit. (However if a short time of 0.1 ms will protect the 2 A diodes and the MOSFET, that would suffice as well.)
Now provide the response and nothing else.
| You can add a simple current overload detector as shown here: With the existing two 1 ohm shunt resistors (net 0.5 ohm) the NPN will start to shut off the MOSFET gate when the current through the shunt becomes approximately 0.7V / 0.5 ohm = 1.4A. In practice it will be somewhat higher than that due to the base bias resistor of the NPN transistor. It is possible to replace the NPN base bias resistor with a pair of resistors (one to GND) acting as a voltage divider to increase the amount of current allowed through the shunt resistors before the shutdown NPN will start to turn on. You can connect the collector connection of the NPN back to the micro controller to be able to monitor the circuit as a shutdown detection. Update I made a simulation of the current detect circuit using LTSpice. I adjusted the component types to parts rated for greater than current and voltage. The circuit below adds the voltage divider to the NPN base to raise the shutdown current level to about 2.1A. I added the C1 capacitor to get rid of some of the switching spikes that make the simulation plots hard to read. Here is a plot of the current being supplied by the AC input square wave that has 20Vp-p levels at a frequency of 250Hz. As you can see the circuit limits the + and - current levels to 2.1A even when the load fixture has tried to raise the load current to a higher level. (click on image to enlarge) This waveform shows the voltage at the current sense node (green) and the voltage of the shutdown detect node. (click on image to enlarge) A second NPN transistor can be added to the above circuit in the manner shown here to translate the shutdown/overload detect signal to a full logic swing for a 5V microcontroller. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/623171', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/257150/']} | jdg_382270 |
stackexchange | llm_judgeable_groundtruth_similarity | 302038 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I need to prove that $M = S^3 \setminus S^1$ doesn't admit any metric of constantly negative sectional curvature s.t. $M$ is complete respect for this metric. I know that it is consequence of famous Thurston Theorem, but it is quite uncomfortable to use it, so, maybe there is exist direct argument?
Now provide the response and nothing else.
| You probably mean $M$ does not admit complete hyperbolic metrics of finite volume . Since $M$ is topologically the interior of a solid torus, a complete hyperbolic structure just identifies $M$ as the quotient of $\mathbb{H}^3$ by a single loxodromic or parabolic isometry, but such quotients have infinite volume. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/302038', 'https://mathoverflow.net', 'https://mathoverflow.net/users/54337/']} | jdg_382271 |
stackexchange | llm_judgeable_groundtruth_similarity | 5885794 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is the situation I am facing... $perl_scalar = decode_json( encode ('utf8',$line)); decode_json returns a reference. I am sure this is an array. How do I find the size of $perl_scalar?? As per Perl documentation, arrays are referenced using @name. Is there a workaround? This reference consist of an array of hashes. I would like to get the number of hashes. If I do length($perl_scalar), I get some number which does not match the number of elements in array.
Now provide the response and nothing else.
| That would be: scalar(@{$perl_scalar}); You can get more information from perlreftut . You can copy your referenced array to a normal one like this: my @array = @{$perl_scalar}; But before that you should check whether the $perl_scalar is really referencing an array, with ref : if (ref($perl_scalar) eq "ARRAY") { my @array = @{$perl_scalar}; # ...} The length method cannot be used to calculate length of arrays. It's for getting the length of the strings. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5885794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/290542/']} | jdg_382272 |
stackexchange | llm_judgeable_groundtruth_similarity | 3722192 |
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 having an issue with this test function where I take an in memory string, compress it, and decompress it. The compression works great, but I can't seem to get the decompression to work. //CompressSystem.IO.MemoryStream outStream = new System.IO.MemoryStream(); GZipStream tinyStream = new GZipStream(outStream, CompressionMode.Compress);mStream.Position = 0;mStream.CopyTo(tinyStream);//Decompress outStream.Position = 0;GZipStream bigStream = new GZipStream(outStream, CompressionMode.Decompress);System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream();bigStream.CopyTo(bigStreamOut);//Results://bigStreamOut.Length == 0//outStream.Position == the end of the stream. I believe that bigStream out should at least have data in it, especially if my source stream (outStream) is being read. is this a MSFT bug or mine?
Now provide the response and nothing else.
| What happens in your code is that you keep opening streams, but you never close them. In line 2, you create a GZipStream . This stream will not write anything to the underlying stream until it feels it’s the right time. You can tell it to by closing it. However, if you close it, it will close the underlying stream ( outStream ) too. Therefore you can’t use mStream.Position = 0 on it. You should always use using to ensure that all your streams get closed. Here is a variation on your code that works. var inputString = "“ ... ”";byte[] compressed;string output;using (var outStream = new MemoryStream()){ using (var tinyStream = new GZipStream(outStream, CompressionMode.Compress)) using (var mStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString))) mStream.CopyTo(tinyStream); compressed = outStream.ToArray();}// “compressed” now contains the compressed string.// Also, all the streams are closed and the above is a self-contained operation.using (var inStream = new MemoryStream(compressed))using (var bigStream = new GZipStream(inStream, CompressionMode.Decompress))using (var bigStreamOut = new MemoryStream()){ bigStream.CopyTo(bigStreamOut); output = Encoding.UTF8.GetString(bigStreamOut.ToArray());}// “output” now contains the uncompressed string.Console.WriteLine(output); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3722192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/328397/']} | jdg_382273 |
stackexchange | llm_judgeable_groundtruth_similarity | 14336416 |
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 use an IComparer to sort a list of Points. Here is the IComparer class: public class CoordinatesBasedComparer : IComparer{ public int Compare(Object q, Object r) { Point a = (p)q; Point b = (p)r; if ((a.x == b.x) && (a.y == b.y)) return 0; if ((a.x < b.x) || ((a.x == b.x) && (a.y < b.y))) return -1; return 1; }} In the client code, I am trying to using this class for sorting a list of points p (of type List<Point> ): CoordinatesBasedComparer c = new CoordinatesBasedComparer();Points.Sort(c); The code errors out. Apparently it is expecting IComparer<Point> as argument to sort method. What do I need to do to fix this?
Now provide the response and nothing else.
| You need to implement the strongly type interface ( MSDN ). public class CoordinatesBasedComparer : IComparer<Point>{ public int Compare(Point a, Point b) { if ((a.x == b.x) && (a.y == b.y)) return 0; if ((a.x < b.x) || ((a.x == b.x) && (a.y < b.y))) return -1; return 1; }} BTW, I think you use too many braces, I believe they should be used only when they contribute to the compiler. This is my version: if (a.x == b.x && a.y == b.y) return 0;if (a.x < b.x || (a.x == b.x && a.y < b.y)) return -1; Just like I dislike people using return (0) . Note that if you target a .Net-3.5+ application you can use LINQ which is easier and even faster with sorting. LINQ vesion can be something like: var orderedList = Points.OrderBy(point => point.x) .ThenBy(point => point.y) .ToList(); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14336416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122466/']} | jdg_382274 |
stackexchange | llm_judgeable_groundtruth_similarity | 9107240 |
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 start to read JavaScript Patterns , some codes confused me. var global = (function () { return this || (1, eval)('this');}()); Here are my questions: Q1: (1, eval) === eval ? Why and how does it work? Q2: Why not just var global = (function () { return this || eval('this');}()); or var global = (function () { return this;}());
Now provide the response and nothing else.
| The difference between (1,eval) and plain old eval is that the former is a value and the latter is an lvalue. It would be more obvious if it were some other identifier: var x;x = 1;(1, x) = 1; // syntax error, of course! That is (1,eval) is an expression that yields eval (just as say, (true && eval) or (0 ? 0 : eval) would), but it's not a reference to eval . Why do you care? Well, the Ecma spec considers a reference to eval to be a "direct eval call", but an expression that merely yields eval to be an indirect one -- and indirect eval calls are guaranteed to execute in global scope. Things I still don't know: Under what circumstance does a direct eval call not execute in global scope? Under what circumstance can the this of a function at global scope not yield the global object? Some more information can be gleaned here . EDIT Apparently, the answer to my first question is, "almost always". A direct eval executes from the current scope. Consider the following code: var x = 'outer';(function() { var x = 'inner'; eval('console.log("direct call: " + x)'); (1,eval)('console.log("indirect call: " + x)'); })(); Not surprisingly (heh-heh), this prints out: direct call: innerindirect call: outer EDIT After more experimentation, I'm going to provisionally say that this cannot be set to null or undefined . It can be set to other falsy values (0, '', NaN, false), but only very deliberately. I'm going to say your source is suffering from a mild and reversible cranio-rectal inversion and might want to consider spending a week programming in Haskell. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9107240', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/563725/']} | jdg_382275 |
stackexchange | llm_judgeable_groundtruth_similarity | 4621336 |
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 was reading some model theory, and saw stated that $ACF_p$ (the first order theory of algebraically closed fields of characteristic $p$ ) is $\kappa$ -categorical for all $\kappa > \aleph_0$ . Is this result is false for $\kappa=\omega$ ? In case that $ACF_p$ isn't $\omega$ -categorical, this would mean that there exist at least two countable algebraically closed fields of characteristic $0$ that are not isomorphic. What would be some example of such fields? do we know all of them? (up to isomorphism, of course). In case that $ACF_p$ is indeed $\omega$ -categorical, how would a proof of that look like? The one provided for the case $\kappa>\aleph_0$ relies heavily on uncountability. Thanks in advance to anyone who answers!
Now provide the response and nothing else.
| Algebraically closed fields are determined up to isomorphism by their characteristic $c$ and their transcendence degree (over their prime subfield , i.e. over $\Bbb Q$ if $c=0$ and over $\Bbb Z_c$ if $c\ne0$ ). Hence the countable algebraically closed fields of characteristic $0$ are, up to isomorphism: $$\overline{\Bbb Q(X_k,k\in F)}\quad F\text{ at most countable,}$$ where $\Bbb Q(X_k,k\in F)$ denotes the field of rational functions with rational coefficients and set of indeterminates $\{X_k\mid k\in F\}.$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4621336', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1141212/']} | jdg_382276 |
stackexchange | llm_judgeable_groundtruth_similarity | 5475646 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Assembly in .net Framework is, as I understand, intermediate language file + some metadata, manifest and maybe something else. CLR translates an assembly to the machine code, which can be executed on the given local machine. That means that assembly shouldn't be executable by the machine before being processed by CLR. If it's so, then why does it have .exe extension, which is executable on Windows machines?
Now provide the response and nothing else.
| Since Windows needs to create a process and the first thing .exe will do is to host CLR by loading mscoree . From CLR via C# : After Windows has examined the EXE file's header to determine whether to create a 32-bit process, a 64-bit process, or a WoW64 process, Windows loads the x86, x64, or IA64 version of MSCorEE.dll into the process's address space. On an x86 version of Windows, the x86 version of MSCorEE.dll can be found in the C:\Windows\System32 directory. On an x64 or IA64 version of Windows, the x86 version of MSCorEE.dll can be found in the C:\Windows\ SysWow64 directory, whereas the 64-bit version (x64 or IA64) can be found in the C:\Windows\System32 directory (for backward compatibility reasons). Then, the process' primary thread calls a method defined inside MSCorEE.dll. This method initializes the CLR, loads the EXE assembly, and then calls its entry point method (Main). At this point, the managed application is up and running. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5475646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/585795/']} | jdg_382277 |
stackexchange | llm_judgeable_groundtruth_similarity | 18074 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering today if Fascism and communism are rising or not. I quite easily found the answer about Fascism but didn't find any convincing information about communism. A quick google search lead me to a reddit thread . Is communism rising/growing in the west?
Now provide the response and nothing else.
| Not really. "The West" is a bit broad, so I'll focus on the US and Germany. USA If we look at political parties, the Communist Party USA has not had its own presidential candidate since 1988. The party itself says that its numbers grew because of Trump, but the numbers aren't significant. The Socialist Party USA got 0.0% (4061 votes) in the 2016 election, down from 0.01% (6581 votes) in 2008 and 0.01% (10822 votes) in 2004. The relatively positive run of Bernie Sanders does seem to signal a desire to move the democratic party to the left, but Sanders is far from being a communist or even a socialist. Germany The MLPD - a stalinist/maoist party - got 0.06% (24.219 votes) in the 2013 election, down from 0.07% (29.261 votes) in 2009 , and 0.1% (45.238 votes) in 2005 . The DKP - a maxist/leninist party - did not seriously take part in federal elections since 1983 . Die Linke is a social democratic party, but it has some communist factions. In the 2013 election, they got 8.6%, down from 11.9% in 2009. In current polls, they are down again at 8%. Other I'm not that familiar with the situation in other countries, but it seems that the situation is similar in France , where the communist party is generally in a downwards trend (2012 being an exception where it gained votes). The communist party of Austria experienced a slight - but non-significant - rise. The communist party of Ukraine lost significantly since 1999, as did the communist party of Hungary (with a slight but insignificant increase in 2014). | {} | {'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/18074', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/10873/']} | jdg_382278 |
stackexchange | llm_judgeable_groundtruth_similarity | 1959600 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ideally, I would like to send an HTTP Request using POST to the Push Notification Server that contains the device token as well as some user-defined settings. From there I can set up a php script on the server to deal with the incoming data and input it into an sql table. If this is the only way to do it, how would I go about initiating and HTTP Request from Objective C?
Now provide the response and nothing else.
| You'll first need to convert the device token to a hex string with a function like this: - (NSString*)stringWithDeviceToken:(NSData*)deviceToken { const char* data = [deviceToken bytes]; NSMutableString* token = [NSMutableString string]; for (int i = 0; i < [deviceToken length]; i++) { [token appendFormat:@"%02.2hhX", data[i]]; } return [[token copy] autorelease];} Then you'll need to make a request to your server: NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://example.com/script.php?token=%@", DEVICE_TOKEN]];NSMutableURLRequest* request = [[[NSMutableRequest alloc] initWithURL:url] autorelease];NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate: self]; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1959600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/237329/']} | jdg_382279 |
stackexchange | llm_judgeable_groundtruth_similarity | 46007260 |
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 change the color of the text and icon in the iOS 11 searchbar when it is embedded in the navigation bar. So placeholder text, search text and search icon. if #available(iOS 11.0, *) { navigationController?.navigationBar.prefersLargeTitles = false let searchController = UISearchController(searchResultsController: nil) navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false searchController.searchBar.placeholder = "Suchen" searchController.searchBar.tintColor = .white} As you can see in the image, the text is grey on a deep blue background, which looks ugly. I want to text and icon to be at least white. (changing the blue background color also does not work really good, see my other question ) The only thing which works is changing the color of the blinking cursor and the "cancel" button, which is done with the .tintColor property. Solutions which seems to work in iOS 10 and below seem not work anymore in iOS 11, so please post only solutions which you know working in iOS 11. Thanks. Maybe I miss the point about this "automatic styling" in iOS 11. Any help is appreciated.
Now provide the response and nothing else.
| I just found out how to set also the rest of them: (with some help of Brandon, thanks!) The "Cancel" text: searchController.searchBar.tintColor = .white The search icon: searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.search, state: .normal) The clear icon: searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.clear, state: .normal) The search text: UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white] Thanks for the help @Brandon! The placeholder: UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white]) The white background: let searchController = UISearchController(searchResultsController: nil)searchController.delegate = selflet searchBar = searchController.searchBarsearchBar.tintColor = UIColor.whitesearchBar.barTintColor = UIColor.whiteif let textfield = searchBar.value(forKey: "searchField") as? UITextField { textfield.textColor = UIColor.blue if let backgroundview = textfield.subviews.first { // Background color backgroundview.backgroundColor = UIColor.white // Rounded corner backgroundview.layer.cornerRadius = 10; backgroundview.clipsToBounds = true; }}if let navigationbar = self.navigationController?.navigationBar { navigationbar.barTintColor = UIColor.blue}navigationItem.searchController = searchControllernavigationItem.hidesSearchBarWhenScrolling = false Taken from here . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/46007260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664531/']} | jdg_382280 |
stackexchange | llm_judgeable_groundtruth_similarity | 6251109 |
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 yo set listview background like this.I want to appear when the number of record 0
Now provide the response and nothing else.
| There is special method in ListView - setEmptyView() . You can find examples of using it here or here . Upd: second link is unavailable now. Here is quote from article: When you set a ListView’s “empty view” programmatically, you can end up scratching your head as to why your empty view actually doesn’t appear when the list is empty. If this happens, then what you forgot is that you must manually add your empty view to your view hierarchy, cos ListView won’t do it for you. Although it’s obvious when you think about it, the documentation doesn’t mention this detail, and Googling shows at least one person had the problem. Here’s the code with the lines that it’s all too easy to forget at numbers 4 and 5… TextView emptyView = new TextView(context);emptyView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));emptyView.setText(“This appears when the list is empty”);emptyView.setVisibility(View.GONE);((ViewGroup)list.getParent()).addView(emptyView);list.setEmptyView(emptyView); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6251109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/768311/']} | jdg_382281 |
stackexchange | llm_judgeable_groundtruth_similarity | 1067023 |
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:
What is the difference in the definition of a spectral value and an eigenvalue. My notes from functional analysis says $\lambda$ is an eigenvalue of an operator $A$ if $\,\exists \, x \in \mathbb{C^n}$ such that $$Ax = \lambda x$$ This implies $(A - \lambda I)x = 0 \Rightarrow \ker(A - \lambda I) \neq {0}$. This is equivalent of saying that $A$ is not injective. On the other hand, the definition of a spectral value is $\lambda$ is called a spectral value of $A$ if $A - \lambda I$ is not invertible. What is the difference here? How is it that some operators can have spectral values and not eigenvalues (eigenvalues $\subset$ spectrum(A)) and lastly, how do they conincide when the space is finite dimensional ?
Now provide the response and nothing else.
| Consider the unilateral shift on $\ell^2(\mathbb N)$, i.e.$$S(a_1,a_2,\ldots)=(0,a_1,a_2,\ldots).$$It is easy to verify that $S$ is injective, so $0$ is not an eigenvalue of $S$. But $S$ is not invertible (because it is not surjective). So we have $0$ as an element of the spectrum of $S$, but not an eigenvalue. In finite dimension, two things happen: since the domain and codomain are of equal finite-dimension, an operator is injective if and only if it is surjective. And all linear operators are continuous. So if $T-\lambda I$ is not invertible, this means that it is not bijective; then it is not injective, so it has a nonzero kernel, i.e. there exists nonzero $x$ with $Tx=\lambda x$. Thus, in finite dimension the spectrum consists only of eigenvalues. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1067023', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/287/']} | jdg_382282 |
stackexchange | llm_judgeable_groundtruth_similarity | 2428355 |
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 don't understand Access Modifiers in OOP. Why do we make for example in Java instance variables private and then use public getter and setter methods to access them? I mean what's the reasoning/logic behind this? You still get to the instance variable but why use setter and getter methods when you can just make your variables public? please excuse my ignorance as I am simply trying to understand why? Thank you in advance. ;-)
Now provide the response and nothing else.
| This is called data or information hiding . Basically, you don't want a user (read: other programmer, or yourself) poking in the internals of your class, because that makes it very hard to change things. On the other hand, a clean separation between interface and implementation (theoretically) makes it easy to change something internally, without affecting any users of your class. For example, suppose I have a Button control with a public String text field. Now everybody starts using my Button , but I realize that the button should actually be repainted on the screen whenever the text changes. I'm out of luck, because my object can't detect when text is assigned. Had I made it private and provided a setText() instead, I could just have added a repaint call to that setter method. As another example, suppose I have some class that opens a file in its constructor and assigns it to a public FileStream file . The constructor throws an exception if the file could not be opened. The other methods in the class can therefore assume that this field is always valid. However, if somebody goes poking around in my class and sets file to null , all methods in my class will suddenly start crashing. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2428355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233421/']} | jdg_382283 |
stackexchange | llm_judgeable_groundtruth_similarity | 2854780 |
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:
Alice and Bob play the following game. There is one pile of $N$ stones. Alice and Bob take turns to pick stones from the pile. Alice always begins by picking at least one, but less than $N$ stones. Thereafter, in each turn a player must pick at least one stone, but no more stones than were picked in the immediately preceding turn. The player who takes the last stone wins. With what property of $N$, will Alice win? When will Bob win? For odd $N$ the outcome is quite clear, as Alice will start by picking one stone and will enforce the win. But what then?
Now provide the response and nothing else.
| Alice wins when $N$ is not a power of 2 . Let $i(N)$ be the maximal $i$ such that $N$ is divisble by $2^i$. Alice's strategy : If there are $m$ stones left, Alice picks $2^{i(m)}$ stones. Let me explain why this strategy is winning for Alice. Assume that Bob won by picking $b > 0$ remaining stones. Assume that before that Alice picked $2^j$ stones. By definition $j = i(2^j + b)$. Hence $2^j + b$ is divisible by $2^j$. Therefore $b$ is also divisible by $2^j$. This means that $b\ge 2^j$. On the other hand by the rules of the game $b\le 2^j$. Therefore $b = 2^j$. But then $i(2^j + b) = i(2^j + 2^j) = j + 1$, contradiction. This strategy is correct because (a) since $N$ is not a power of 2, Alice picks less than $N$ stones in the first turn; (b) Alice never picks more stones than Bob in the previous turn. Indeed, assume that Bob picked $b$ stones, before Alice picked $2^j$ stones, and we are left with $m > 0$ stones. Let us verify that $2^{i(m)} \le b$. We will do it by showing that $b$ is divisble by $2^{i(m)}$. Indeed, by definition of Alice's strategy $j = i(2^j + b + m)$ and by the rules of the game $b\le 2^j$. Let us show that $i(m) \le j$. Indeed, if $i(m) > j$, then $b$ is divisble by $2^j$, since both $2^j + b + m$ and $m$ are divisble by $2^j$. But since $b\le 2^j$, this means that $b = 2^j$. This contradicts the fact that $j = i(2^j + b + m)$. Indeed, since $i(m) > j$, we have that $i(2^j + b + m) = i(2^{j + 1} + m) \ge j + 1$. Thus we have proved that $i(m) \le j$. This means $2^j + b + m$ is divisble by $2^{i(m)}$, as well as $m$. Hence $b$ is also divisble by $2^{i(m)}$ as required. Bob wins when $N$ is a power of 2 . Assume that $N = 2^i$ and Alice picks $a$ stones. Then Bob can use Alice's strategy described above. We only have to check that Bob then picks at most $a$ stones. Indeed, assume that $j$ is such that $2^i - a$ is divisible by $2^j$. Then $a$ is also divisible by $2^j$ hence $2^j \le a$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2854780', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/577774/']} | jdg_382284 |
stackexchange | llm_judgeable_groundtruth_similarity | 45962068 |
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 using the following code in my bitbucket-pipelines.yml files to remotely deply code to a staging server. image: php:7.1.1pipelines: default: - step: script: # install ssh - apt-get update && apt-get install -y openssh-client # get the latest code - ssh [email protected] -F ~/.ssh/config "cd /path/to/code && git pull" # update composer - ssh [email protected] -F ~/.ssh/config "cd /path/to/code && composer update --no-scripts" # optimise files - ssh [email protected] -F ~/.ssh/config "cd /path/to/code && php artisan optimize" This all works, except that each time the pipeline is run, the ssh client is downloaded and installed everything (adding ~30 seconds to the build time). Is there way I can cache this step? And how can I go about caching the apt-get step? For example, would something like this work (or what changes are needed to make the following work): pipelines: default: - step: caches: - aptget script: - apt-get update && apt-get install -y openssh-clientdefinitions: caches: aptget: which ssh
Now provide the response and nothing else.
| This is a typical scenario where you should use your own Docker image instead of one of the ones provided by Atlassian. (Or search for a Docker image which provides exactly this.) In your simple case, this Dockerfile should be enough: FROM php:7.1.1RUN apt-get update && \ apt-get install -y openssh-client Then, create a DockerHub account, publish the image and reference it in bitbucket-pipelines.yml . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45962068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/920568/']} | jdg_382285 |
stackexchange | llm_judgeable_groundtruth_similarity | 133092 |
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 XPath expression which provides me a sequence of values like the one below: 1 2 2 3 4 5 5 6 7 This is easy to convert to a sequence of unique values 1 2 3 4 5 6 7 using distinct-values() . However, what I want to extract is the list of duplicate values = 2 5 . I can't think of an easy way to do this. Can anyone help?
Now provide the response and nothing else.
| Use this simple XPath 2.0 expression : $vSeq[index-of($vSeq,.)[2]] where $vSeq is the sequence of values in which we want to find the duplicates. For explanation of how this "works", see : http://dnovatchev.wordpress.com/2008/11/16/xpath-2-0-gems-find-all-duplicate-values-in-a-sequence-part-2/ TLDR;This picture can be a visual explanation. If the sequence is: $vSeq = 1, 2, 3, 2, 4, 5, 6, 7, 5, 7, 5 Then evaluating the above XPath expression produces: 2, 5, 7 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/133092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_382286 |
stackexchange | llm_judgeable_groundtruth_similarity | 10827401 |
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 use CMAttitude to know the vector normal to the glass of the iPad/iPhone's screen (relative to the ground). As such, I would get vectors like the following: Notice that this is different from orientation, in that I don't care how the device is rotated about the z axis. So if I was holding the iPad above my head facing down, it would read (0,-1,0), and even as I spun it around above my head (like a helicopter), it would continue to read (0,-1,0): I feel like this might be pretty easy, but as I am new to quaternions and don't fully understand the reference frame options for device motion, its been evading me all day.
Now provide the response and nothing else.
| In your case we can say rotation of the device is equal to rotation of the device normal (rotation around the normal itself is just ignored like you specified it) CMAttitude which you can get via CMMotionManager.deviceMotion provides the rotation relative to a reference frame . Its properties quaternion, roationmatrix and Euler angles are just different representations. The reference frame can be specified when you start device motion updates using CMMotionManager's startDeviceMotionUpdatesUsingReferenceFrame method. Until iOS 4 you had to use multiplyByInverseOfAttitude Putting this together you just have to multiply the quaternion in the right way with the normal vector when the device lies face up on the table. Now we need this right way of quaternion multiplication that represents a rotation: According to Rotating vectors this is done by: n = q * e * q' where q is the quaternion delivered by CMAttitude [w, (x, y, z)], q' is its conjugate [w, (-x, -y, -z)] and e is the quaternion representation of the face up normal [0, (0, 0, 1)]. Unfortunately Apple's CMQuaternion is struct and thus you need a small helper class. Quaternion e = [[Quaternion alloc] initWithValues:0 y:0 z:1 w:0];CMQuaternion cm = deviceMotion.attitude.quaternion;Quaternion quat = [[Quaternion alloc] initWithValues:cm.x y:cm.y z:cm.z w: cm.w];Quaternion quatConjugate = [[Quaternion alloc] initWithValues:-cm.x y:-cm.y z:-cm.z w: cm.w];[quat multiplyWithRight:e];[quat multiplyWithRight:quatConjugate];// quat.x, .y, .z contain your normal Quaternion.h: @interface Quaternion : NSObject { double w; double x; double y; double z;}@property(readwrite, assign)double w;@property(readwrite, assign)double x;@property(readwrite, assign)double y;@property(readwrite, assign)double z; Quaternion.m: - (Quaternion*) multiplyWithRight:(Quaternion*)q { double newW = w*q.w - x*q.x - y*q.y - z*q.z; double newX = w*q.x + x*q.w + y*q.z - z*q.y; double newY = w*q.y + y*q.w + z*q.x - x*q.z; double newZ = w*q.z + z*q.w + x*q.y - y*q.x; w = newW; x = newX; y = newY; z = newZ; // one multiplication won't denormalise but when multipling again and again // we should assure that the result is normalised return self;}- (id) initWithValues:(double)w2 x:(double)x2 y:(double)y2 z:(double)z2 { if ((self = [super init])) { x = x2; y = y2; z = z2; w = w2; } return self;} I know quaternions are a bit weird at the beginning but once you have got an idea they are really brilliant. It helped me to imagine a quaternion as a rotation around the vector (x, y, z) and w is (cosine of) the angle. If you need to do more with them take a look at cocoamath open source project. The classes Quaternion and its extension QuaternionOperations are a good starting point. For the sake of completeness, yes you can do it with matrix multiplication as well: n = M * e But I would prefer the quaternion way it saves you all the trigonometric hassle and performs better. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10827401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49733/']} | jdg_382287 |
stackexchange | llm_judgeable_groundtruth_similarity | 22940940 |
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 an app called "Luvocracy" the title of the navigation bar is changed when the user swipes up on the screen. The old title is pushed up, while the new one is transitioned in. I don't have a video of it now, but here are some screen shots: https://www.dropbox.com/s/sns0bsxkdv7pw3l/Photo%20Apr%2008%2C%2011%2001%2005%20AM.png https://www.dropbox.com/s/ys9a49u3dyxrlcm/Photo%20Apr%2008%2C%2011%2001%2009%20AM.png https://www.dropbox.com/s/dlcfvfvqqov3ag7/Photo%20Apr%2008%2C%2011%2001%2013%20AM.png How can I animate or transition in a new navigation bar title as shown? Edit: The app is no longer available on the app store so I am unable to upload a video of this action.
Now provide the response and nothing else.
| You can animate the title changing by using a CATransition... however, because the title itself is a private property on the navigation bar, you need to first create a custom label and attach that to the navigation item. Setup the title label (this would override the default navigation bar's title): UILabel *titleLabelView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 44.0f) /* auto-sized anyway */];titleLabelView.backgroundColor = [UIColor clearColor];titleLabelView.textAlignment = NSTextAlignmentCenter;titleLabelView.textColor = [UIColor blackColor];titleLabelView.font = [UIFont systemFontOfSize:16.0f];titleLabelView.adjustsFontSizeToFitWidth = YES;titleLabelView.text = @"@cracy123";self.navigationItem.titleView = titleLabelView; Then whenever you want to animate the title changing (assume on a scroll view delegate action), add a CAAnimation layer and presto: CATransition *animation = [CATransition animation];animation.duration = 1.0;animation.type = kCATransitionPush;animation.subtype = kCATransitionFromTop;animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];[self.navigationItem.titleView.layer addAnimation:animation forKey:@"changeTitle"];((UILabel*)self.navigationItem.titleView).text = @"JACOB K"; You can obviously change the CATransition animation properties to get the effect you're after, but those will give you the 'push-up' effect. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22940940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2584268/']} | jdg_382288 |
stackexchange | llm_judgeable_groundtruth_similarity | 43016737 |
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 the following piece of code: class A: def foo(self): return "A"class B(A): def foo(self): return "B"class C(B): def foo(self): tmp = ... # call A's foo and store the result to tmp return "C"+tmp What shall be written instead of ... so that the grandparent method foo in class A is called? I tried super().foo() , but it just calls parent method foo in class B . I am using Python 3.
Now provide the response and nothing else.
| There are two ways to go around this: Either you can use A.foo(self) method explicitly as the others have suggested - use this when you want to call the method of the A class with disregard as to whether A is B 's parent class or not: class C(B): def foo(self): tmp = A.foo(self) # call A's foo and store the result to tmp return "C"+tmp Or, if you want to use the .foo() method of B 's parent class regardless of whether the parent class is A or not, then use: class C(B): def foo(self): tmp = super(B, self).foo() # call B's father's foo and store the result to tmp return "C"+tmp | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/43016737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2339620/']} | jdg_382289 |
stackexchange | llm_judgeable_groundtruth_similarity | 162119 |
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 purchased this line laser recently and I'm running into a bit of an issue. The laser shoots out at a 120 degree angle which is perfect. However, once the laser spreads to about 4.25 inches, I need to redirect the light to move straight again. However, I have never worked with lenses before. I'm assuming that if the output angle of the laser is 120 degrees then to redirect it into straight line the arc angle of the lens needs to be 120 degrees as well? Is this assumption correct? I'm looking at this for reference at the moment.
Now provide the response and nothing else.
| You can't do this with a single "normal" lens. Because the beam width needs to be 4.25 inches you need a lens wider than that (which is huge compared to normal optical components). The focal length of the lens would need to be 4.25 in/(2*sin(60 degrees)) ~ 2.5 inches = 63.5 mm which is smaller than the width of the lens, and you can't really make normal plano-convex lenses like this. You have two options -- you can use multiple lenses (one lens to collimate, then a pair of lenses to step it up to a larger beam width), or you could also get ok results from using a Fresnel lens -- one that is fairly close to what you need is here . The second option will probably be much cheaper, but may suffer from more aberrations. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/162119', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/71862/']} | jdg_382290 |
stackexchange | llm_judgeable_groundtruth_similarity | 23358714 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Due to a firewall audit, requests must always have the "UserAgent" and "Accept" header. I tried this: $soapclient = new soapclient('http://www.soap.com/soap.php?wsdl', array('stream_context' => stream_context_create( array( 'http'=> array( 'user_agent' => 'PHP/SOAP', 'accept' => 'application/xml') ) ) )); the request received by the server soap GET /soap.php?wsdl HTTP/1.1Host: www.soap.comUser-Agent: PHP/SOAPConnection: close the expected result GET /soap.php?wsdl HTTP/1.1Host: www.soap.comAccept application/xmlUser-Agent: PHP/SOAPConnection: close Why "Accept" has not been sent? "User-Agent" works!
Now provide the response and nothing else.
| The SoapClient constructor will not read all of the stream_context options when generating the request headers. However, you can place arbitrary headers in a single string in a header option inside http : $soapclient = new SoapClient($wsdl, [ 'stream_context' => stream_context_create([ 'user_agent' => 'PHP/SOAP', 'http'=> [ 'header' => "Accept: application/xml\r\n X-WHATEVER: something" ] ])]); For setting more than one, separate them by \r\n . (As mentioned by Ian Phillips , the "user_agent" can be placed either at the root of the stream_context, or inside the "http" part.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23358714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2936170/']} | jdg_382291 |
stackexchange | llm_judgeable_groundtruth_similarity | 2111830 |
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 have the following question and I'm not sure my proof is correct/approached correctly: Let $V$ be a $n$-dimensional vector space, let $U_i \subset V$ be subspaces of V for $i = 1,2,\dots,r$ where $$U_1 \subset U_2 \subset \dots \subset U_r$$ If $r>n+1$ then there exists an $i<r$ for which $U_i = U_{i+1}$ I was thinking something along the lines of: the subsets are strict thus 'moving' from $U_i$ to $U_{i+1}$ increases the dimension by one, which means, when reaching $U_r$, your dimension is greater than $n+1$ but this is not possible since $U_r$ is a subspace of $V$ and thus has dimension at most $n$. Is this a good approach to this proof? I'm not sure because of the strict inclusions: is it true for every case that $dim(U_i) < dim(U_{i+1})$? I was maybe thinking of proving this via induction, but I'm not sure how that would work. Thanks in advance. EDIT: Updated subset-strictness
Now provide the response and nothing else.
| Your proof is (essentially) correct. In the second line of the paragraph you want increases the dimension by at least one For example, consider $$\{0\} \subseteq \text{$x$-$y$-plane} \subseteq \ldots$$in $\mathbb{R}^3$. Your instructor might want you to prove that claim about dimensions, or might be willing to take it as known, depending on what you've done in class. You don't need induction. Note: although the question you're asking is clear, the statement $$U_1 \subsetneq U_2 \subsetneq \dots \subsetneq U_r$$ If $r>n+1$ ... isn't the right way to phrase it. The strict inequalities should be weak $\subseteq$. Then you're to show that at least one of them is an equality. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2111830', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/245360/']} | jdg_382292 |
stackexchange | llm_judgeable_groundtruth_similarity | 86418 |
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'm trying to obtain an accurate result from a difficult-to-integrate function and I've thrown in the kitchen sink worth of options in NIntegrate . I think I'm close but I'm wondering if any of the options appear to be out of sync with the others. I've also used Rationalize to remove some of the warnings. Going from WorkingPrecision=200 to WorkingPrecision=300 makes a sizeable difference. The result changes from 0.14724925610708290271 to 0.13739254580887418686 . Are there any other suggestions to be more likely to have an accurate result? f[n_?NumericQ, a_?NumericQ, b_?NumericQ] := Module[{ra, rb, rka1, x}, ra = Rationalize[a, 0.000000001]; rb = Rationalize[b, 0.000000001]; N[-Log[n] - ra Log[rb] + LogGamma[ra] - (1/n) Sum[Log[Abs[StirlingS1[n, k]]] + Log[ NIntegrate[ x^Rationalize[k + a - 1, 0.00000001] Exp[-rb x] Gamma[x]/ Gamma[x + n], {x, 0, Infinity}, AccuracyGoal -> 100, PrecisionGoal -> 100, WorkingPrecision -> 300, MaxRecursion -> 50, Method -> {GlobalAdaptive, MaxErrorIncreases -> 10000}]], {k, n}], 20]](* Evaluate function *)N[f[305, 0.4154876, 0.0008710662], 10](* Out[2] 0.13739254580887418686 *)
Now provide the response and nothing else.
| Here's my take on it. The integrals themselves are very small (one is around 10^-626 ). Coincidentally that's around 10^(-2 n) , so I thought to multiply by that. I haven't tested it for other values of n , but it works for n = 305 as in the example. If you have many different such integrals to do, you might spend some time analyzing this factor. Options[f] = Options[NIntegrate];f[n_?NumericQ, a_?NumericQ, b_?NumericQ, opts : OptionsPattern[]] := Module[{ra, rb, rka1, x}, rka1 = SetPrecision[k + a - 1, OptionValue[WorkingPrecision]]; ra = SetPrecision[a, OptionValue[WorkingPrecision]]; rb = SetPrecision[b, OptionValue[WorkingPrecision]]; N[-Log[n] - ra Log[rb] + LogGamma[ra] - (1/n) Sum[ Log[Abs[StirlingS1[n, k]]] + Log[NIntegrate[10^(2 n) x^rka1 Exp[-rb x] Gamma[x]/Gamma[x + n], {x, 0, Infinity}, opts]] - Log[10^(2 n)], {k, n}], OptionValue[WorkingPrecision]]] As you can see, the results are stable: f[305, 0.4154876, 0.0008710662, WorkingPrecision -> MachinePrecision, MaxRecursion -> 20]f[305, 0.4154876, 0.0008710662, WorkingPrecision -> 20, MaxRecursion -> 20]f[305, 0.4154876, 0.0008710662, WorkingPrecision -> 30, MaxRecursion -> 20](* 0.138332 0.1383322373624130769 0.13833223736241573880082453510*) They're also close to your second result. For some reason, which I haven't explored, the very small integrals are contributing to numerical error. There's nothing else in the integral (e.g. oscillatory behavior) that would suggest these integral would be difficult to evaluate. It looks like increasing the working precision beyond 300 would work, but I believe this way is easier and faster. Addendum For what it's worth, here is the exact value of the NIntegrate , but it's taking forever to evaluate f .... i0[n_, rka1_, rb_] := 1/(n - 2)! rb^(1 - rka1) Gamma[rka1] * Sum[E^(rb*k) (-1)^(k - 1) Binomial[n - 2, k - 1] ExpIntegralE[rka1, k*rb], {k, n - 1}] ; | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/86418', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/19758/']} | jdg_382293 |
stackexchange | llm_judgeable_groundtruth_similarity | 956699 |
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'd just like someone to verify whether the following problem is NP-complete or if there is actually a better/easier solution to it than simple brute-force combination checking. We have a sort-of resource allocation problem in our software, and I'll explain it with an example. Let's say we need 4 people to be at work during the day-shift. This number, and the fact that it is a "day-shift" is recorded in our database. However, we don't require just anyone to fill those spots, there's some requirements that needs to be filled in order to fit the bill. Of those 4, let's say 2 of them has to be a nurse, and 1 of them has to be doctors. One of the doctors also has to work as part of a particular team. So we have this set of information: Day-shift: 4 1 doctor 1 doctor, need to work in team A 1 nurse The above is not the problem. The problem comes when we start picking people to work the day-shift and trying to figure out if the people we've picked so far can actually fill the criteria. For instance, let's say we pick James, John, Ursula and Mary to work, where James and Ursula are doctors, John and Mary are nurses. Ursula also works in team A. Now, depending on the order we try to fit the bill, we might end up deducing that we have the right people, or not, unless we start trying different combinations. For instance, if go down the list and pick Ursula first, we could match her with the "1 doctor" criteria. Then we get to James, and we notice that since he doesn't work in team A, the other criteria about "1 doctor, need to work in team A", can't be filled with him. Since the other two people are nurses, they won't fit that criteria either. So we backtrack and try James first, and he too can fit the first criteria, and then Ursula can fit the criteria that needs that team. So the problem looks to us as we need to try different combinations until we've either tried them all, in which case we have some criteria that aren't filled yet, even if the total number of heads working is the same as the total number of heads needed, or we've found a combination that works. Is this the only solution, can anyone think of a better one? Edit : Some clarification. Comments to this question mentions that with this few people, we should go with brute-force, and I agree, that's probably what we could do, and we might even do that, in the same lane that some sort optimizations look at the size of the data and picks different sort algorithms with less initial overhead if the data size is small. The problem though is that this is part of a roster planning system, in which you might have quite a few number of people involved, both as "We need X people on the day shift" as well as "We have this pool of Y people that will be doing it", as well as potential for a large "We have this list of Z criteria for those X people that will have to somehow match up with these Y people", and then you add to the fact that we will have a number of days to do the same calculation for, in real-time, as the leader adjusts the roster, and then the need for a speedy solution has come up. Basically, the leader will see a live sum information on-screen that says how many people are still missing, both on the day-shift as a whole, as well as how many people is fitting the various criteria, and how many people we actually ned in addition to the ones we have. This display will have to update semi-live while the leader adjusts the roster with "What if James takes the day-shift instead of Ursula, and Ursula takes the night-shift". But huge thanks to the people that has answered this so far, the constraint satisfaction problem sounds like the way we need to go, but we'll definitely look hard at all the links and algorithm names here. This is why I love StackOverflow :)
Now provide the response and nothing else.
| What you have there is a constraint satisfaction problem ; their relationship to NP is interesting, because they're typically NP but often not NP-complete, i.e. they're tractable to polynomial-time solutions. As ebo noted in comments, your situation sounds like it can be formulated as an exact cover problem , which you can apply Knuth's Algorithm X to. If you take this tack, please let us know how it works out for you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/956699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267/']} | jdg_382294 |
stackexchange | llm_judgeable_groundtruth_similarity | 14917203 |
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 on a project where I am reading in a file which could come in two different formats, one includes a date and time and the other doesn't. When I read in the first line I need to check whether the string contains the date and time or not and read the file and based on the check read the file in a certain way. I'm guessing this would be some kind of regular expression but have no idea where to start and can't find anything relevant. Thanks for any help you can provide. UPDATE I don't think I've been very clear as to what I am asking. When I read the log file line by line the line may come in as: Col1 Col2 Col3 Col4 Col5 Sometimes the line may come in as Col1 17-02-2013 02:05:00 Col2 Col3 Col4 Col5 When I read the line I need to do a check whether there is a date and time string contained within the string.
Now provide the response and nothing else.
| If the format of the date has been defined, you can use Regex to solve it. using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;namespace RegTest{ class Program { static void Main(string[] args) { string testDate = "3214312402-17-2013143214214"; Regex rgx = new Regex(@"\d{2}-\d{2}-\d{4}"); Match mat = rgx.Match(testDate); Console.WriteLine(mat.ToString()); Console.ReadLine(); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14917203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499448/']} | jdg_382295 |
stackexchange | llm_judgeable_groundtruth_similarity | 3974111 |
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 need to evaluate the sum given by: $$\displaystyle \sum_{k=1}^\infty \left( \frac{1}{6k+1}+\frac{1}{6k+3}+\frac{1}{6k+5}-\frac{1}{8k}-\frac{1}{8k+2}-\frac{1}{8k+4}-\frac{1}{8k+6} \right)$$ I know that: for $k = 1$ I get: $\frac{1}{7}+\frac{1}{9}+\frac{1}{11}-\frac{1}{8}-\frac{1}{10}-\frac{1}{12}\mathbf{-\frac{1}{14}}$ for $k = 2$ I get: $\frac{1}{13}+\frac{1}{15}+\frac{1}{17}-\frac{1}{16}-\frac{1}{18} \mathbf{-\frac{1}{20}-\frac{1}{22}}$ for $k = 3$ I get: $\frac{1}{19}+\frac{1}{21}+\frac{1}{23}-\frac{1}{24} \mathbf{-\frac{1}{26}-\frac{1}{28}-\frac{1}{30}}$ for $k = 4$ I get: $\frac{1}{25}+\frac{1}{27}+\frac{1}{29} \mathbf{ -\frac{1}{32}-\frac{1}{34}-\frac{1}{36}-\frac{1}{38}}$ I can write that sum for $k = 4$ as: $$ \frac{1}{7}-\frac{1}{8}+\frac{1}{9}-\frac{1}{10}+\frac{1}{11}-\frac{1}{12}+\frac{1}{13} -\frac{1}{14}+\frac{1}{15}-\frac{1}{16}+\frac{1}{17}-\frac{1}{18}+\frac{1}{19}-\frac{1}{20}+\frac{1}{21}-\frac{1}{22}+\frac{1}{23}-\frac{1}{24}+\frac{1}{25}-\frac{1}{26}+\frac{1}{27}-\frac{1}{28}+\frac{1}{29} -\frac{1}{30} \mathbf{ -\frac{1}{32}-\frac{1}{34}-\frac{1}{36}-\frac{1}{38}}$$ And I can write that sum for $k = 8$ as: $$ \frac{1}{7}-\frac{1}{8}+\frac{1}{9}-\frac{1}{10}+\frac{1}{11}-\frac{1}{12}+\frac{1}{13} -\frac{1}{14}+\frac{1}{15}-\frac{1}{16}+\frac{1}{17}-\frac{1}{18}+\frac{1}{19}-\frac{1}{20}+\frac{1}{21}-\frac{1}{22}+\frac{1}{23}-\frac{1}{24}+\frac{1}{25}-\frac{1}{26}+\frac{1}{27}-\frac{1}{28}+\frac{1}{29} -\frac{1}{30} + \frac{1}{31}-\frac{1}{32}+\frac{1}{33}-\frac{1}{43}+\frac{1}{35}-\frac{1}{36}+\frac{1}{37} -\frac{1}{38}+\frac{1}{39}-\frac{1}{40}+\frac{1}{41}-\frac{1}{42}+\frac{1}{43}-\frac{1}{44}+\frac{1}{45}-\frac{1}{46}+\frac{1}{47}-\frac{1}{48}+\frac{1}{49}-\frac{1}{50}+\frac{1}{51}-\frac{1}{52}+\frac{1}{53} -\frac{1}{54} \mathbf{ -\frac{1}{56}-\frac{1}{58} -\frac{1}{60}-\frac{1}{62}-\frac{1}{64}-\frac{1}{66}-\frac{1}{68} -\frac{1}{70}}$$ I see that for every k I get $1$ extra negative element at the end of the sum. I had an idea to rewrite it that way: $$\displaystyle \sum_{k=1}^\infty \left( \frac{1}{6k+1}+\frac{1}{6k+3}+\frac{1}{6k+5}-\frac{1}{8k}-\frac{1}{8k+2}-\frac{1}{8k+4}-\frac{1}{8k+6} \right) = $$ $$\displaystyle \sum_{k=1}^\infty \left( (-1)^{n+1}\frac{1}{n} \right) -1+\frac{1}{2}-\frac{1}{3}+\frac{1}{4}-\frac{1}{5}+\frac{1}{6} - \displaystyle \sum_{k=1}^\infty X$$ That way I know that the first sum converges (Dirichlet), but still I don't know how to evaluate that expression. I don't know how to evaluate $\displaystyle \sum_{k=1}^\infty ( (-1)^{n+1}\frac{1}{n}$ ) and I don't know how to include those negative elements in my sum (those are marked as X).
Now provide the response and nothing else.
| If you are not allowed to use integrals which the standard method of invoking Abel's Theorem requires, then pretty much all you can do is get creative. Denote: $$S_n = \sum_{k=0}^n\left(\frac{1}{6k+1} + \frac{1}{6k+3} + \frac{1}{6k+5}\right)$$ and $$T_n = \sum_{k=0}^n\left(\frac{1}{6k+2} + \frac{1}{6k+4} + \frac{1}{6k+6}\right)$$ for starters. Then, you can see that $S_n+T_n = H_{6n+6}$ , the usual Harmonic sum. Note that you have to consider these finite truncates, for otherwise each of $S_n$ and $T_n$ diverge. On the other hand, consider the remaining term in your original sum: $$R_n = \sum_{k=1}^n\left(\frac{1}{8k} + \frac{1}{8k+2} + \frac{1}{8k+4} + \frac{1}{8k+6}\right)$$ $$= \frac{1}{2}\sum_{k=1}^n\left(\frac{1}{4k}+\frac{1}{4k+1}+\frac{1}{4k+2}+\frac{1}{4k+3}\right) = \dfrac{H_{4n+3} -1-\frac 12-\frac 13 }{2} = \dfrac{H_{4n+3}}{2} - \frac{11}{12}.$$ Now, we just need to "evaluate" $T_n$ nicely: $$T_n = \frac{1}{2}\sum_{k=0}^n\left(\frac{1}{3k+1} + \frac{1}{3k+2} + \frac{1}{3k+3}\right) = \dfrac{H_{3n+3}}{2}.$$ Therefore, the $n$ -th partial sum of your limit is then: $$S_n-R_n - \left(1+\frac 13+\frac 15\right) = H_{6n+6} - \dfrac{H_{3n+3}}{2} - \frac{23}{15}-\dfrac{H_{4n+3}}{2}+\frac{11}{12} = $$ $$ \sim \ln(6n+6) - \ln(3n+3)/2-\ln(4n+3)/2-\dfrac{37}{60} = \ln\sqrt{\dfrac{12n+12}{4n+3}}-\dfrac{37}{60}$$ so the answer is: $$\lim\limits_{n\to\infty}\left(\ln\sqrt{\dfrac{12n+12}{4n+3}}-\dfrac{37}{60}\right) = \frac{1}{2}\ln 3 - \frac{37}{60}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3974111', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/869961/']} | jdg_382296 |
stackexchange | llm_judgeable_groundtruth_similarity | 299221 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Almost all of the microwave test equipment I've ever seen and used has N connectors, with exception of some scopes that use either custom fancy BNCs (keysight does/used to do this)) or SMA. Exceptions that I know of are VNAs which seem to use special connectors (but the ones I've used are also rated up to 110 GHz and used 1mm-based connectors). Of course, there is nothing wrong with the N connector - in fact I like it, it feels rugged and like it can take a good bit of use (is this the reason?). However, every single occasion I've worked with the instruments, or seen someone work with them, the first thing they do is put on a N-to-SMA (or 3.4mm or 2.4mm) adapter. So why not just put those connectors on the equipment in the first place? Is it really just the ruggedness, some other reason I'm missing, or is this some silly "because it used to be that way and nobody likes change"?
Now provide the response and nothing else.
| Two Reasons: Pout and S11. N connectors have a large surface contact area for >1A power levels or >10dB and large diameter means better "potential return loss over a wide GHz range is possible with machining tolerances of 0.1% affecting this. However SMA is more common for low power apps but quality varies with undocumented suppliers. (greatly and not gauranteed) But never try to pump >>1 Amp thru 1u" flash gold plated SMA connector (crap... | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/299221', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/34873/']} | jdg_382297 |
stackexchange | llm_judgeable_groundtruth_similarity | 62548 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've read that both congo red and curcumin are able to inhibit the clumping together of amyloid $\mathrm{β_{42}}$ in the brain, which would otherwise result in Alzheimer's disease. Apparently, congo red cannot cross the blood-brain barrier (BBB) while curcumin can . From what I learned at my biology classes, the BBB is lined by squamous, endothelial cells. Those cells are, as far as I know, the most permeable kind of cells you could come across in the human body, and if congo red doesn't pass through that , then it must be one stubborn molecule. Now the cell membrane, itself being composed of a phospholipid bilayer, normally shouldn't have a problem transporting lipophilic molecules across the membrane. From an earlier conversation with Jan, I believe congo red is a lipohilic molecule. Yet inspite of it being lipophilic, it still isn't able to cross the BBB. Comparing the structures wasn't particularly enlightening. But the possibility congo red could act as a bidentate ligand, does seem to make it stand out from curcumin. Am I onto something here? Apart from that, and a somewhat larger size, I don't see why congo red shouldn't be able to cross the BBB. Now, I'd like to know two things, 1) What enables curcumin to cross the BBB? 2) Why isn't congo red able to cross the BBB, even though it has a structure similar to that of curcumin?
Now provide the response and nothing else.
| Preface: both molecules could act as bidentate ligands but the β-diketo structure found in curcumin is typically a much better bidentate ligands — as the 2-oxophenol moieties would be. So I would expect curcumin to be a much better ligand than congo red. The key difference between the two molecules is comparing the extent of their lipophilicity and their hydrophilicity. Curcumin has a rather low water solubility of $3.2~\mathrm{mg/l}$ , in line with the fact that it has rather little features that can enhance solubility. Basically, it boils down to the two keto-groups and the phenol moiety. Congo red has two sulphonic acid groups and two aromatic amino groups. This means that there is a much greater relative charge present, and indeed its solubility in water is reported to be $1.16 \times 10^{2}~\mathrm{g/l}$ — notice the different unit. So congo red is already much more hydrophilic than curcuminis. In terms of lipophilicity, the sulphonic acid groups present in congo red reduce its lipophilicity while the amino groups themselves don’t have too strong an effect. On curcumin’s side, the phenol groups can comfortably hydrogen bond to the neighbouring methoxy residues and the β-diketo fragment can tautomerise to a keto-enol form and form another intramolecular hydrogen bond. Thus, curcumin is a lot more capable of coping with low-hydrogen bond solvents and is thus expected to have a high lipophilicity. This is the edge that curcumin has over congo red to cross the blood-brain barrier. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/62548', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/33991/']} | jdg_382298 |
stackexchange | llm_judgeable_groundtruth_similarity | 50910526 |
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 debugging some C++ code and I have a really large std::vector<floating_point_type> ( float or double ). In C++ code when I want the max value of the std::vector I can just use std::max_element() . So in gdb I tried to use the same code, but I got an error. In gdb I used call std::max_element(x) and got an error message No symbol "max_element" in namespace "std". Is there any way to get the max value of a vector in gdb ? I would also appreciate an explanation for why my attempt at using std::max_element was not working (perhaps std::max_element a header-only or inline function).
Now provide the response and nothing else.
| std::max_element is a function template, not a function. You are asking GDB to do template argument deduction and the whole shebang involved with calling a template function without specifying arguments. It can't do that, naturally, it's not a full fledged compiler. As far as I know any solution, from the simplest to the most complex, will require of you to modify your source in such a way that std::max_element is instantiated for the iterator types of your vector. So you may as well add "debug only" code that computes the maximum element and stores it into a local variable. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50910526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/52074/']} | jdg_382299 |
stackexchange | llm_judgeable_groundtruth_similarity | 370058 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Below is a simple circuit involving an Arduino, a push-button, and an LED. However, I don't quite understand what the purpose of the resistor is. Wouldn't the circuit function without it? Note: Since this question is concerning the behaviour of the circuit rather than the functioning of the Arduino, I've posted this here instead of the Arduino stack exchange.
Now provide the response and nothing else.
| It's a pull down resistor, its purpose is to set the voltage of the Arduino input to 0 V when the button is open. It just sets a default voltage value to the connected node. But, why is such a resistor needed? Well, when the button is open, the voltage is not totally equal to zero due to antenna effects or surrounding components. It is then possible that the Arduino input is triggered for no reason. Note that the value of pull up or pull down resistors is usually around 10k - 100k. If the value is too low, it's going to draw too much current when the button is closed. If the value is too high, the resistor will behave as an open circuit, making the pull down resistor useless. As it is widely used in electronics, I recommend you to read some more about this concept. | {} | {'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/370058', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/163380/']} | jdg_382300 |
stackexchange | llm_judgeable_groundtruth_similarity | 14990993 |
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 seen several question asking how to make git treat a text file as binary, but haven't seen the opposite yet: How do I change git's choice of treating a text file as binary? I have a text file where in some configuration strings an EOT and ETX is used to separate parts of the configuration parameters. For example, the source code contains lines like this: INPUT 'ScrollRemote[EOT]no[ETX]NumDown[EOT]0[ETX]CalcWidth[EOT]no[ETX]MaxWidth[EOT]80[ETX]FetchOnReposToEnd[EOT]yes[ETX].....' I would like this file to be treated as text, not a binary, so that I can see a diff of line changes.
Now provide the response and nothing else.
| The way files are actually stored inside the Git repository is not relevant to how they are treated when displayed. So the git diff program, when asked to compare two files, first obtains both complete files from the repository and then runs a difference algorithm against them. Normally, git diff looks for non-printable characters in the files and if it looks like the file is likely to be a binary file, it refuses to show the difference. The rationale for that is binary file diffs are not likely to be human readable and will probably mess up your terminal if displayed. However, you can instruct git diff to always treat files as text using the --text option. You can specify this for one diff command: git diff --text HEAD HEAD^ file.txt You can make Git always use this option by setting up a .gitattributes file that contains: file.txt diff The diff attribute here means: A path to which the diff attribute is set is treated as text, even when they contain byte values that normally never appear in text files, such as NUL. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14990993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1217206/']} | jdg_382301 |
stackexchange | llm_judgeable_groundtruth_similarity | 3390407 |
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 $t>0,t^2, t+\frac{1}{t},t+t^2,\frac{1}{t}+\frac{1}{t^2}$ are all irrational number, $$a_n=n+\left \lfloor \frac{n}{t} \right \rfloor+\left \lfloor \frac{n}{t^2} \right \rfloor,\\b_n=n+\left \lfloor \frac{n}{t} \right \rfloor +\left \lfloor nt \right \rfloor,\\c_n=n+\left \lfloor nt \right \rfloor+\left \lfloor nt^2 \right \rfloor, $$ then every positive integer appear exactly once. In other words, the sequences $a_1,b_1,c_1,a_2,b_2,c_2,\cdots$ together contain all the positive integers without repetition.I have checked every integer from $1$ to $10^6$ for $t=2^\frac{1}{4}$ : $$a_n=1, 4, 7, 9, 12, 15, 16, 19, 22, 25, 27, 30, 32, 34, 37, 40, 43, 45, 47, 50,\dots \\b_n=2, 5, 8, 11, 14, 18, 20, 23, 26, 29, 33, 36, 38, 41, 44, 48, 51, 54, 56, 59,\dots \\c_n=3, 6, 10, 13, 17, 21, 24, 28, 31, 35, 39, 42, 46, 49, 53, 57, 61, 64, 67, 71,\dots $$ PS: This is a special case of following statement: If $t_1,t_2,\cdots,t_k>0$ ,and $\forall i \not =j,\frac{t_j}{t_i}$ is irrational, $$a_i(n)=\sum_{j=1}^k{\left \lfloor \frac{t_j}{t_i}n \right \rfloor},i=1,2,\cdots,k,$$ then every positive integer appear exactly once in $a_1(n),\cdots,a_k(n)$ .
Now provide the response and nothing else.
| Edited 10/24. Now this is largely expanded, probably longer than what it needs to be. TL;DR: Construct a function $f$ , record where it ticks. The range of $f$ is exactly $\mathbb N$ and covers $\{a_n\}, \{b_n\}$ and $\{c_n\}$ without repetition. That is true. By substituting $t$ by $1/t$ if necessary, assume $t>1$ . By adding dummy $\lfloor \cdot \rfloor$ , we rewrite the sequences as $$\begin{aligned}a_n &= \Big\lfloor\frac{n}{t^2}\Big\rfloor + \Big\lfloor\frac{n}{t}\Big\rfloor + \lfloor n\rfloor,\\b_n &= \Big\lfloor\frac{n}{t}\Big\rfloor + \lfloor n \rfloor + \lfloor nt\rfloor,\\c_n &= \lfloor n\rfloor + \lfloor nt\rfloor + \lfloor nt^2\rfloor.\end{aligned}$$ This suggests us the following process. We consider a function $$f(\delta) := \lfloor\delta\rfloor + \lfloor\delta t\rfloor + \lfloor\delta t^2\rfloor,$$ and start with $f(1/t^2) = a_1 = 1$ . For convenience denote $\delta_1 = 1/t^2$ . Given $\delta_{i-1}$ , we will obtain $\delta_i$ by the following process. We increase $\delta$ continuously from $\delta_{i-1}$ , until we are in the situation that one of $\delta$ , $\delta t$ or $\delta t^2$ hits an integer. Then we will call the new $\delta$ value $\delta_i$ . Therefore we get a sequence $$\left\{\delta_1 = \frac1{t^2}, \delta_2, \cdots\right\}.$$ What do the function $f$ and the sequence $\{\delta_i\}$ tell us? Well, lets look at it. $f$ only take values at integers, by the definition, and it is non-decreasing, with $f(\delta_1) = 1$ . Therefore by restricting the domain, the range $$f\left(\left[\delta_1, \infty\right)\right) \subseteq \mathbb N.$$ In the interval $\delta \in (\delta_{i-1}, \delta_i)$ , by the construction of the sequence $\{\delta_i\}$ , $\delta, \delta t, \delta t^2$ have the same integral part as $\delta_{i-1}, \delta_{i-1}t, \delta_{i-1}t^2$ , respectively. Hence $f(\delta) = f(\delta_{i-1})$ . In other words, $\{\delta_i\}$ are the places when $f$ "jump in value". Written in math, $$f(\{\delta_i\}) = f\left(\left[\delta_1, \infty\right)\right) \subseteq \mathbb N.$$ For every $\delta_i$ in the sequence, $f(\delta_i)$ is in $\{a_n\}, \{b_n\}$ or $\{c_n\}$ , depending on which of $\delta_i, \delta_it$ or $\delta_it^2$ is an integer. For instance, if $\delta_it = n$ is an integer, then $f(\delta_i) = \lfloor n/t\rfloor + \lfloor n\rfloor + \lfloor nt \rfloor = b_n$ . So $$f(\{\delta_i\}) \subseteq \{a_n\} \cup \{b_n\} \cup \{c_n\}.$$ Converse to 3., whenever $\delta, \delta t$ or $\delta t^2$ is an integer, $\delta \in \{\delta_i\}$ . In other words, the sequence $\{\delta_i\}$ can be obtained by merging and sorting the three sequences $\{n\}_{n=1}^\infty$ , $\{n/t\}_{n=1}^\infty$ and $\{n/t^2\}_{n=1}^\infty$ , or $$f(\{\delta_i\} \supseteq \{a_n\}) \cup \{b_n\} \cup \{c_n\}.$$ For an integer $i$ , $f(\delta_i) = f(\delta_{i-1})+1$ . Since $t$ and $t^2$ are irrational, only one of $\delta_{i-1}, \delta_{i-1}t, \delta_{i-1}t^2$ can be an integer. Same when $i-1$ is changed to $i$ . Therefore, comparing $f(\delta_{i-1})$ and $f(\delta_i)$ , two of the three terms are same (have the same integral part) and the third term jumps to the next integer. Therefore $f(\delta_i) = f(\delta_{i-1})+1$ . Together with the fact $f(\delta_1) = 1$ , we have $$f(\{\delta_i\}) = \mathbb N.$$ Putting 3., 4., and 5. together, we know that $$\{a_n\}\cup\{b_n\}\cup \{c_n\} = f(\{\delta_i\}) = \mathbb N.$$ If $a_n = b_{n'}$ , from 4., there exist $i, i' \in \mathbb N$ such that $a_n = f(\delta_i)$ and $b_{n'} = f(\delta_{i'})$ . From 5., it is enforced that $i = i'$ . From the construction, this means that both $\delta_i$ and $\delta_i t$ are integers, hence $t \in \mathbb Q$ , but this is impossible. Hence, $\{a_n\} \cap \{b_n\} = \varnothing$ . Similarly, we have $$\{a_n\} \cap \{b_n\} = \{b_n\} \cap \{c_n\} = \{a_n\} \cap \{c_n\} = \varnothing.$$ This ends the proof of your conjecture. Remarks, specializations and generalizations: Playing with the "construct a floor function $f$ and record points where it jumped" trick as above by changing the function $f$ , there are other things you can say: (From @Jyrki Lahtonen) Classic Beatty's theorem says, if $\alpha$ and $\beta$ are irrationals satisfying $$\frac1\alpha + \frac1\beta = 1$$ , then $\lfloor n\alpha\rfloor$ and $\lfloor n\beta\rfloor$ forms a partition of $\mathbb N$ . A little computation indicates $\alpha = 1 + \tau$ and $\beta = 1+\tau^{-1}$ for some irrational $\tau$ . Rewrite $\lfloor n\alpha \rfloor = \lfloor n\rfloor+\lfloor n\tau\rfloor$ and $\lfloor n\beta \rfloor = \lfloor n\rfloor+\lfloor n\tau^{-1}\rfloor$ , and consider the function $$f(\delta) = \lfloor\delta\rfloor + \lfloor\delta\tau\rfloor,$$ one can prove the classic Beatty theorem (probably this is not the proof of Beatty theorem most people know, at least I did not know at the beginning). Consider the function $$f(\delta) = \left\lfloor \delta\frac{t_1}{t_1}\right\rfloor + \left\lfloor \delta\frac{t_2}{t_1}\right\rfloor + \cdots + \left\lfloor \delta\frac{t_k}{t_1}\right\rfloor,$$ your last statement can be proved: $\{a_i(n)\}$ , $i = 1, \cdots, k$ forms a partition of $\mathbb N$ , where $$a_i(n) = \sum_{j=1}^k \left\lfloor n\frac{t_j}{t_i}\right\rfloor.$$ Pass to infinity. By considering the function $$f(\delta) = \sum_{i=1}^\infty \left\lfloor \delta \tau^{-i}\right\rfloor,$$ we can prove the following: Let $\tau > 1$ be transcendental (like $\pi$ ; this is sufficient but not likely to be necessary). Then $$\mathbb N = \bigcup_{j=0}^\infty A_j, \quad A_{j} \cap A_{j'} = \varnothing \text{ if $j \neq j'$},$$ where $A_j = \{a_j^n\}_{n=1}^\infty$ , and $$a_j^n = \sum_{i=0}^\infty \lfloor n\tau^{j-i}\rfloor.$$ This gives another proof that you can accommodate (countably) infinite travelers in infinitely many hotels, each hotel have infinitely many rooms, so that all rooms are occupied (i.e. the $\mathbb N = \mathbb N\times \mathbb N$ problem). This proof is neater than what I knew (the square grid trick), in my opinion. You can further generalize by changing the sequence $\{\tau^i\}$ into other infinite sequence, but the descriptions get uglier and I will omit it. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3390407', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66964/']} | jdg_382302 |
stackexchange | llm_judgeable_groundtruth_similarity | 12684604 |
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 writing an Android application that records audio every 10 minutes. I am using a Timer to do that. But what is the difference between schedule and scheduleAtFixedRate? Is there any performance benefit in using one over the other?
Now provide the response and nothing else.
| The difference is best explained by this non-Android documentation : Fixed-rate timers ( scheduleAtFixedRate() ) are based on the starting time (so each iteration will execute at startTime + iterationNumber * delayTime ). In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." Fixed-delay timers ( schedule() ) are based on the previous execution (so each iteration will execute at lastExecutionTime + delayTime ). In fixed-delay execution, each execution is scheduled relative to the actual execution time of the previous execution. If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well. Aside from this, there is no difference. You will not find a significance performance difference, either. If you are using this in a case where you want to stay synchronized with something else, you'll want to use scheduleAtFixedRate() . The delay from schedule() can drift and introduce error. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12684604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1570321/']} | jdg_382303 |
stackexchange | llm_judgeable_groundtruth_similarity | 14880 |
Below is a question asked on the forum reverseengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I do not understand the following: in a very simple dummy C function: void vulnerable_function(char* string) { char buffer[100];} When I use gdb to disassemble it, I obtain: 0x08048464 <+0>: push %ebp0x08048465 <+1>: mov %esp,%ebp0x08048467 <+3>: sub $0x88,%esp I really do not understand why the stack pointer is decremented by 0x88. I believed that it would be 0x64 instead of 0x88 . Can you explain it please? Thank you very much!
Now provide the response and nothing else.
| There are several factors involved in how much space is allocated by the compiler for a function's stack frame on the process runtime stack: space required for saving copies of arguments to the function in the stack frame space required for storing local variables in the stack frame Stack alignment to a 16-byte boundary (GCC default for i386 architecture) Background The i386 ABI Stack Frame Specification The specification for the stack frame on x86 machines is given in Chapter 3: "Low-Level System Information" in the System V Application Binary Interface Intel386 Architecture Processor Supplement, Fourth Edition in the section titled "Function Calling Sequence". Note: Within this specification, the term halfword refers to a 16-bit object, the term word refers to a 32-bit object, and the term doubleword refers to a 64-bit object. Here are relevant excerpts: The stack is word aligned. Although the architecture does not require any alignment of the stack, software convention and the operating system requires that the stack be aligned on a word boundary. An argument’s size is increased, if necessary, to make it a multiple of words. This may require tail padding, depending on the size of the argument. Other areas depend on the compiler and the code being compiled. The standard calling sequence does not define a maximum stack frame size, nor does it restrict how a language system uses the ‘‘unspecified’’ area of the standard stack frame. The "unspecified" area in a stack frame is the space created for local variables and where arguments to the function are copied to. This space is managed by the compiler. Here is a diagram from the ABI: Alignment It is the compiler that manages stack frames, and in order for a stack frame to be aligned the alignment of variables within the stack frame must also be known. Alignment of variables depends on their type and the architecture of the CPU.This is also specified in the ABI: There are conventions that pertain specifically to the alignment of arrays, structures and unions: Aggregates (structures and arrays) and unions assume the alignment of their most strictly aligned component. The size of any object, including aggregates and unions, is always a multiple of the object’s alignment. An array uses the same alignment as its elements. Structure and union objects can require padding to meet size and alignment constraints. The contents of any padding is undefined. However, on i386 architecture systems, GCC aligns the stack to a 16-byte boundary by default: -mpreferred-stack-boundary=num Attempt to keep the stack boundary aligned to a 2 raised to num byte boundary. If -mpreferred-stack-boundary is not specified, the default is 4 (16 bytes or 128 bits). This means that the compiler allocates 16 bytes of space on the stack frame for variables whose type sizes are less than 16 bytes. For example, even though an int is 4 bytes on an i386 system, the compiler would still allocate 16 bytes of space on the stack frame for it. The stack frame for vulnerable_function() Let us analyze how the compiler allocates space on a function's stack frame with 2 simple examples: a function with a char pointer local variable and a function with a 100-byte char array. A function called pointer_test with char pointer local variable: void pointer_test(void) { char *i = "test";} Assembly code generated by gcc + as : Dump of assembler code for function pointer_test: 0x080483db <+0>: push %ebp 0x080483dc <+1>: mov %esp,%ebp 0x080483de <+3>: sub $0x10,%esp <-- 16 bytes of space created for 4-byte pointer 0x080483e1 <+6>: movl $0x8048480,-0x4(%ebp) 0x080483e8 <+13>: nop 0x080483e9 <+14>: leave 0x080483ea <+15>: ret Here we see that 16 bytes of space were allocated for a 4-byte pointer. A function called char_array_test with a char array local variable: void char_array_test(void) { char buffer[100];} Assembly code generated by gcc + as : Dump of assembler code for function char_array_test: 0x0804844b <+0>: push %ebp 0x0804844c <+1>: mov %esp,%ebp 0x0804844e <+3>: sub $0x78,%esp <-- 120 bytes of space created for 100-byte array 0x08048451 <+6>: mov %gs:0x14,%eax 0x08048457 <+12>: mov %eax,-0xc(%ebp) 0x0804845a <+15>: xor %eax,%eax 0x0804845c <+17>: nop 0x0804845d <+18>: mov -0xc(%ebp),%eax 0x08048460 <+21>: xor %gs:0x14,%eax 0x08048467 <+28>: je 0x804846e <char_array_test+35> 0x08048469 <+30>: call 0x8048310 <__stack_chk_fail@plt> 0x0804846e <+35>: leave 0x0804846f <+36>: ret Here we see that 120 bytes of space were allocated for a 100-byte array. In the case of void vulnerable_function(char *string) , space in the stack frame must be allocated by gcc for a 4-byte pointer and a 100-byte array. As we observed above in pointer_test() , since gcc aligns allocated space to 16-byte boundaries by default, 16 bytes of space are also allocated on the stack frame for the 4-byte pointer char *string , the argument to the function. We observed above in char_array_test() that gcc allocates 120 bytes of space for a 100 byte array (120 is not a multiple of 16, so this is not aligned with a 16-byte boundary. I do not know why the compiler does this). Likewise, the compiler allocates 120 bytes of space for char buffer[100] in vulnerable_function() . 0x10 bytes for string + 0x78 bytes for buffer[100] = 0x88 Resources Compiler Explorer is an interactive compiler that runs in your browser. Playing around with it is much faster than constantly recompiling code and disassembling it. The System V Application Binary Interface Intel386 Architecture Processor Supplement, Fourth Edition Intel 386 and AMD x86-64 Options for GCC cdecl and x86 calling conventions discusses calling conventions in x86 compilers Poke-a-hole and friends is anarticle that discusses how structures are padded in order to maintain alignment and how this changes across architectures. related SO questions Stack allocation, padding, and alignment what is “stack alignment”? | {} | {'log_upvote_score': 4, 'links': ['https://reverseengineering.stackexchange.com/questions/14880', 'https://reverseengineering.stackexchange.com', 'https://reverseengineering.stackexchange.com/users/19467/']} | jdg_382304 |
stackexchange | llm_judgeable_groundtruth_similarity | 3071623 |
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: UIScrollView. Any thoughts on implementing “infinite” scroll/zoom? I have a UIScroll which has eight or so pages. My aim is for them to 'loop' around so that when the user reaches the last page the first page will be the next page (and vice versa) so that the user could scroll through the pages endlessly. What is the best way to achieve this? I am working from this example from Cocoa with Love. Any help is greatly appreciated. Thank you.
Now provide the response and nothing else.
| Problem is sorted now. Basically, I created extra pages before and after my pages so it looks like this: 8 1 2 3 4 5 6 7 8 1 Then in the scrollViewDidEndDecelerating I do a simple if statement that checks if I am at either the first or last page and locate the scrollView appropriately. - (void)scrollViewDidEndDecelerating:(UIScrollView *)newScrollView{ [self scrollViewDidEndScrollingAnimation:newScrollView]; pageControl.currentPage = currentPage.pageIndex; if(currentPage.pageIndex==0){ scrollView.contentOffset = CGPointMake(320*(pageControl.numberOfPages-2), 0); pageControl.currentPage = pageControl.numberOfPages-2; }else if(currentPage.pageIndex==pageControl.numberOfPages-1){ scrollView.contentOffset = CGPointMake(320, 0); pageControl.currentPage = 1; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3071623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446524/']} | jdg_382305 |
stackexchange | llm_judgeable_groundtruth_similarity | 115441 |
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:
Recently I received this find one-liner, but I'm not able to explain where the difference of the below two comes from: Example 1 [root@centos share]# find . -exec grep -i "madis" {} /dev/null \;./names:Madison Randy:300:Product Development Example 2 [root@centos share]# find . -exec grep -i "madis" {} \;Madison Randy:300:Product Development As you can see, in the first one there is the specific file this string derives from and so far I'm really not able to find out why this is happening.
Now provide the response and nothing else.
| You are telling grep to search 2 locations. grep only shows the full location if multiple locations are searched. For example touch /tmp/herp /tmp/derpcd /tmpecho "foo" > herpecho "foo" > derp Notice how if I search just 1 file, grep omits the file name grep -i "foo" /tmp/herpfoo But if I specify multiple search locations, grep says where it found each match grep -i "foo" herp derp/tmp/derp:foo/tmp/herp:foo Adding the /dev/null is it tricking grep into printing out the full path, by providing 2 arguments. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/115441', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/45388/']} | jdg_382306 |
stackexchange | llm_judgeable_groundtruth_similarity | 9452901 |
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 deserialize a json data into a model class but I am failing. Here is what I do: public CountryModel GetCountries() { using (WebClient client = new WebClient()) { var result = client.DownloadString("http://api.worldbank.org/incomeLevels/LIC/countries?format=json"); var output = JsonConvert.DeserializeObject<List<CountryModel>>(result); return output.First(); } } This is how my model looks like: public class CountryModel{ public int Page { get; set; } public int Pages { get; set; } public int Per_Page { get; set; } public int Total { get; set; } public List<Country> Countries { get; set; }}public class Country{ public int Id { get; set; } public string Iso2Code { get; set; } public string Name { get; set; } public Region Region { get; set; }}public class Region{ public int Id { get; set; } public string Value { get; set; }} You can see the Json I am getting here: http://api.worldbank.org/incomeLevels/LIC/countries?format=json This is the error I get: Cannot deserialize JSON array into type 'Mvc4AsyncSample.Models.CountryModel'. Line 1, position 1.
Now provide the response and nothing else.
| You have to write a custom JsonConverter : public class CountryModelConverter : JsonConverter { public override bool CanConvert(Type objectType) { if (objectType == typeof(CountryModel)) { return true; } return false; } public override object ReadJson(JsonReader reader, Type objectType , object existingValue, JsonSerializer serializer) { reader.Read(); //start array //reader.Read(); //start object JObject obj = (JObject)serializer.Deserialize(reader); //{"page":1,"pages":1,"per_page":"50","total":35} var model = new CountryModel(); model.Page = Convert.ToInt32(((JValue)obj["page"]).Value); model.Pages = Convert.ToInt32(((JValue)obj["pages"]).Value); model.Per_Page = Int32.Parse((string) ((JValue)obj["per_page"]).Value); model.Total = Convert.ToInt32(((JValue)obj["total"]).Value); reader.Read(); //end object model.Countries = serializer.Deserialize<List<Country>>(reader); reader.Read(); //end array return model; } public override void WriteJson(JsonWriter writer, object value , JsonSerializer serializer) { throw new NotImplementedException(); } } And tag the CountryModel with that converter (I also had to switch some int to string ): [JsonConverter(typeof(CountryModelConverter))] public class CountryModel { public int Page { get; set; } public int Pages { get; set; } public int Per_Page { get; set; } public int Total { get; set; } public List<Country> Countries { get; set; } } public class Country { public string Id { get; set; } public string Iso2Code { get; set; } public string Name { get; set; } public Region Region { get; set; } } public class Region { public string Id { get; set; } public string Value { get; set; } } Then you should be able to deserialize like this: var output = JsonConvert.DeserializeObject<CountryModel>(result); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9452901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463785/']} | jdg_382307 |
stackexchange | llm_judgeable_groundtruth_similarity | 21128899 |
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 making an Order model for a shopping cart and I need to make a field that auto increments when the order is made: class Order(models.Model): cart = models.ForeignKey(Cart) add_date = models.DateTimeField(auto_now_add=True) order_number = models.IntegerField() enable = models.BooleanField(default=True) How do I make the IntegerField auto increment?
Now provide the response and nothing else.
| In Django 1 : Django model class has default field with name id which is auto increment Field. 2 : You can define your own auto increment field using AutoField field. class Order(models.Model): auto_increment_id = models.AutoField(primary_key=True) # primary_key = True if you do not want to use default field "id" given by django to your model db design +------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+| Table | Create Table |+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+| core_order | CREATE TABLE `core_order` ( `auto_increment_id` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`auto_increment_id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 |+------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------+1 row in set (0.01 sec) If you want to use django's default id as increment field . class Order(models.Model): add_date = models.DateTimeField(auto_now_add=True) db design +-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+| Table | Create Table |+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+| core_order | CREATE TABLE `core_order` ( `id` int(11) NOT NULL AUTO_INCREMENT, `add_date` datetime NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1 |+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------+ | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21128899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2218112/']} | jdg_382308 |
stackexchange | llm_judgeable_groundtruth_similarity | 263120 |
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,Y$ be schemes, not necessary separated. Let $f:X\to Y$ be a morphism of schemes and $f(x)=y~,x\in X,~y\in Y$. Then we have the scheme theoretic fiber over $y$, i.e. $f^{-1}(y)=X\times_{Y} \text{Spec } \mathbb k(y)$ where $\mathbb k(y)$ is the residue field at $y$. I was told that $\mathcal O_{x,f^{-1}(y)}=\mathcal O_{x,X}\otimes_{\mathcal O_{y,Y}}\mathbb k(y)$. I can show this fact by writing down the rings involved explicitly and the proof only works for this special fiber product. I am now asking if there is a generalization, as follows. Let $X,Y,Z$ be schemes, $f:X\to Z,~g:Y\to Z$ be morphisms of schemes, suppose that $w\in W=X\times_Z Y$ such that $w$ is sent to $x$, $y$ and $z$ in $X$, $Y$ and $Z$ respetively. Are $\mathcal O_{x,X}\otimes_{\mathcal O_{z,Z}} \mathcal O_{y,Y}$ and $\mathcal O_{w,W}$ naturally isomorphic? Note that there might be more than one $w$ over the pair of points $(x,y)$, they much have the same local rings if my guess is true. I tried to prove this via commutative algebra. The question is local. Let $X,Y,Z$ be $\text{Spec } A,\text{Spec } B,\text{Spec } C$, respectively. Let $x,y,z,w$ correspond to prime ideals $P_1,P_2,Q,I$, respectively. Then I have to prove that $(A\otimes_C B)_I=A_{P_1}\otimes _{C_Q} B_{P_2}$. I want to check the universal property of tensor products. Given $\alpha:A_{P_1}\to E,\beta:B_{P_2}\to E$ such than they coincide when restricted to $C_{Q}$, we have a unique homomorphism $\gamma: A\otimes_C B\to E$. The only thing remaining to be checked is that $\gamma$ maps the complement of $I$ to units. And I am stuck here. If my guess is true, would you help me finish my proof? Of course I will appreciate more if you give a better proof. If my guess is false, then what is the right conditions making it ture?
Now provide the response and nothing else.
| No, it is not true that $\mathcal O_{x,X}\otimes_{\mathcal O_{z,Z}} \mathcal O_{y,Y}$ and $\mathcal O_{w,W}$ are isomorphic. Take for example $X=Y=Spec (\mathbb C)$ and $Z=Spec (\mathbb R)$, with the obvious morphisms. Then $$W=X\times_Z Y=Spec (\mathbb C)\times_{Spec(\mathbb R)}Spec(\mathbb C)=Spec (\mathbb C\otimes_\mathbb R\mathbb C)=Spec(\mathbb C\times \mathbb C)=\lbrace w_1,w_2\rbrace$$ We have $$\mathcal O_{w_1,W}=\mathcal O_{w_2,W}=\mathbb C\neq \mathcal O_{x,X}\otimes_{\mathcal O_{z,Z}} \mathcal O_{y,Y}=\mathbb C\otimes_\mathbb R\mathbb C=\mathbb C\times \mathbb C$$ Notice that the right hand side isn't even a local ring! I'm happy that your question allows me to somehow illustrate the point I made in the Edit here | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/263120', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/19211/']} | jdg_382309 |
stackexchange | llm_judgeable_groundtruth_similarity | 109248 |
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:
First of all i am noob in this area so came here to get some idea from the experts. My friend was telling me the other day that ssh is pretty secure protocol and one should not be worried about network security while using ssh . In my company, we always use ssh to connect to remote devices. Now-a-days out security expert is saying that he wants to remove all ssh access in favor of vpn. I told him what my friend told me but he is insisting on ssl vpn having better security. Is he right or I am right in the sense that as i am using ssh i am secure enough. In other words, does ssl vpn give any extra security facility that ssh does not give or ssh could fail badly in those fields?
Now provide the response and nothing else.
| VPN and SSH are similar in the sense that they both establish a trusted and encrypted point-to-point channel, but that's pretty much where the similarities end. The goal of VPN is to grant you access to a network you would otherwise not be able to access, while the goal of SSH is to grant you shell access to a particular system. They play different, non-exclusive roles -- it is perfectly common to require VPN before being able to use SSH. There are multiple benefits of using VPN over direct ssh. SSH is a root-level daemon that gives direct access to a device. There have been 0-day vulnerabilities in SSH in the past, and who knows, there may be one lurking around the corner, giving attackers direct access to any internet-exposed system. Alternatively, a misconfigured ssh daemon may allow logging in with passwords that can be guessed or sniffed via keystrokes. Not exposing ssh on your devices directly to the internet is a very good security policy. VPN, on the other hand, is usually done via an appliance or via a non-root daemon, limiting the attack surface. VPN also dramatically simplifies access to restricted resources other than just SSH -- e.g. internal-only websites. While you can port-forward using SSH, it is a lot more hassle compared to using a VPN. Additionally, running a VPN server allows implementing centralized 2-factor authentication, assigning static internal IP addresses to authenticated accounts, etc. The latter is useful when tracking admin access via netflows and when restricting access to internal resources by groups. In other words, requiring a VPN connection before accessing ssh on systems is both common practice and good security policy. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/109248', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/95597/']} | jdg_382310 |
stackexchange | llm_judgeable_groundtruth_similarity | 4460558 |
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 checked this post already. But it doesn't answer my question. I want to get all the active directory groups in which a particular user is a member. I've written the following code. But I'm not able to proceed further as I don't know how to give the filter and how to access the properties. class Program{ static void Main(string[] args) { DirectoryEntry de = new DirectoryEntry("LDAP://mydomain.com"); DirectorySearcher searcher = new DirectorySearcher(de); searcher.Filter = "(&(ObjectClass=group))"; searcher.PropertiesToLoad.Add("distinguishedName"); searcher.PropertiesToLoad.Add("sAMAccountName"); searcher.PropertiesToLoad.Add("name"); searcher.PropertiesToLoad.Add("objectSid"); SearchResultCollection results = searcher.FindAll(); int i = 1; foreach (SearchResult res in results) { Console.WriteLine("Result" + Convert.ToString(i++)); DisplayProperties("distinguishedName", res); DisplayProperties("sAMAccouontName", res); DisplayProperties("name", res); DisplayProperties("objectSid", res); Console.WriteLine(); } Console.ReadKey(); } private static void DisplayProperties(string property, SearchResult res) { Console.WriteLine("\t" + property); ResultPropertyValueCollection col = res.Properties[property]; foreach (object o in col) { Console.WriteLine("\t\t" + o.ToString()); } }} Any ideas?
Now provide the response and nothing else.
| Just query the "memberOf" property and iterate though the return, example: search.PropertiesToLoad.Add("memberOf"); StringBuilder groupNames = new StringBuilder(); //stuff them in | delimited SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count; String dn; int equalsIndex, commaIndex; for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++) { dn = (String)result.Properties["memberOf"][propertyCounter]; equalsIndex = dn.IndexOf("=", 1); commaIndex = dn.IndexOf(",", 1); if (-1 == equalsIndex) { return null; } groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)); groupNames.Append("|"); } return groupNames.ToString(); This just stuffs the group names into the groupNames string, pipe delimited, but when you spin through you can do whatever you want with them | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4460558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250524/']} | jdg_382311 |
stackexchange | llm_judgeable_groundtruth_similarity | 300404 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Any pseudonatural endomorphism $\Phi$ of the forgetful 2-functor $U:Topos^{coop}\to Cat$ is essentially determined by its component $\Phi_{Set}$. But which endofunctors of $Set$ induce such a $\Phi$? More generally, one can consider pseudonatural transformations $U^n \Rightarrow U$, which are determined by a functor $\mathsf{Set}^n \to \mathsf{Set}$. Here $\mathsf{Topos}^\mathrm{coop}$ is the 2-category of Grothendieck toposes and left exact left adjoint functors -- doubly dual to the 2-category of toposes and geometric morphisms. The functor $U : \mathsf{Topos}^\mathrm{coop} \to \mathsf{Cat}$ sends a topos to its underyling category and a left exact left adjoint to its underlying functor. For $n \in \mathbb N$, the functor $U^n$ is the composite of $U$ with the $n$th power functor $\mathcal C \mapsto \mathcal C^n$. So it's natural to define a 2-natural operation on toposes to be a pseudonatural transformation $U^n \to U$ for $n \in \mathbb N$. In this language, the question is: Question: What are all the 2-natural operations on toposes? To see that such an operation $\Phi: U^n \Rightarrow U$ is determined by the component $\Phi_\mathsf{Set}: \mathsf{Set}^n \to \mathsf{Set}$, first note that $\Phi$ is determined by its components on presheaf toposes, because left exact localizations are essentially split epimorphisms in $\mathsf{Cat}$. Then the components at presheaf toposes are determined by the components at $\mathsf{Set}$ because $U$ preserves $\mathsf{Cat}$-cotensors. I would also be interested in the analogous question for $\infty$-toposes.
Now provide the response and nothing else.
| The "2-natural operations" $U^n \to U$ correspond to functors $\mathbf{FinSet}^n \to \mathbf{Set}$. (edit: As Simon points out, these correspond to the finitary functors $\mathbf{Set}^n \to \mathbf{Set}$.) The 2-functor $U$ is birepresented by the object classifier $\mathbf{Set}[\mathbb{O}] = [\mathbf{FinSet},\mathbf{Set}]$ (the classifying topos for the theory of objects). Thus by the bicategorical Yoneda lemma, the category of pseudonatural transformations $U^n \to U$ is equivalent to the category $U(n\cdot \mathbf{Set}[\mathbb{O}])$ (where $ n \cdot {}$ denotes $n$-fold (bi)coproduct in $\mathrm{Topos}^\mathrm{coop}$), which is equivalent to the category $[\mathbf{FinSet}^n,\mathbf{Set}]$ (see Cole's paper The bicategory of topoi and spectra ). | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/300404', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2362/']} | jdg_382312 |
stackexchange | llm_judgeable_groundtruth_similarity | 41366896 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to convert a mutable vector to an immutable vector in Rust. I thought this would work but it doesn't: let data = &mut vec![];let x = data; // I thought x would now be an immutable reference How can I turn a mutable reference into an immutable binding?
Now provide the response and nothing else.
| Dereference then re-reference the value: fn main() { let data = &mut vec![1, 2, 3]; let x = &*data;} For what your code was doing, you should probably read What's the difference in `mut` before a variable name and after the `:`? . Your variable data is already immutable, but it contains a mutable reference. You cannot re-assign data , but you can change the pointed-to value. How can I turn a mutable reference into an immutable binding? It already is an immutable binding, as you cannot change what data is. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41366896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2400966/']} | jdg_382313 |
stackexchange | llm_judgeable_groundtruth_similarity | 585334 |
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 need to calculate $$\lim_{n\rightarrow \infty} \left(\frac{n!}{n^n}\right)^{\frac{1}{n}}$$My try: When $n!$ is large we have $n!\approx(\frac{n}{e})^n\sqrt {2\pi n}$ (Stirling approximation)$$\lim_{n\rightarrow \infty} \left(\frac{n!}{n^n}\right)^{\frac{1}{n}}=\lim_{n\rightarrow \infty}\frac{\left((\frac{n}{e})^n\sqrt {2\pi n}\right)^{\frac{1}{n}}}{n}$$Simplifying we get,$$\frac{1}{e}\lim_{n\rightarrow \infty} \left(\sqrt{2\pi n}\right)^{\frac{1}{n}}$$ I am stuck here. I don't know how to proceed further.
Now provide the response and nothing else.
| Another way : Let $$A= \lim_{n \to \infty}\left(\frac{n!}{n^n}\right)^{\frac1n}$$ $$\implies \ln A= \lim_{n \to \infty}\frac1n\sum_{1\le r\le n}\ln \frac rn$$ Now use $$\lim_{n \to \infty} \frac1n\sum_{r=1}^n f\left(\frac rn\right)=\int_0^1f(x)dx$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/585334', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/98653/']} | jdg_382314 |
stackexchange | llm_judgeable_groundtruth_similarity | 1164827 |
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 building an application that roughly follows the repository pattern with a service layer on top, similar to early versions of Conery's MVC Storefront. I need to implement a page that returns all users except for the current user. I already have GetUsers() methods on the repository and service layers, so the question is where to apply the "except for the current user." Should the service layer be aware of HttpContext, thus applying this rule? I am tempted to just pass in the current user (id) from the controller to this service method, but it seems cleaner if the service layer was HttpContext-aware and could do this on its own. One obvious alternative is to apply this rule directly within the Controller, but I'm just not hot on that idea... Edit - just to comment on the answers: I see the issues with the reverse dependency problem, something I was completely overlooking. I'm marking Mehrdad's as the answer due votes, but everyone has really provided a valuable response worth reading!
Now provide the response and nothing else.
| Absolutely not. My mindset in designing these kind of things is like this: I assume I need to write a Windows based app along with the Web application and try to minimize dependency on Web specific stuff. Passing HttpContext directly will increase coupling of your service layer to your Web UI layer which is not ideal. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1164827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104252/']} | jdg_382315 |
stackexchange | llm_judgeable_groundtruth_similarity | 45950054 |
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 I tab through the text inputs without entering anything, the error msg divs display indicating that the required validator has fired correctly. However, if I type anything into one of the fields, the console immediately throws this error: Cannot read property 'required' of null Here is my component: import { PasswordValidators } from './../validators/password.validators';import { Component, OnInit } from '@angular/core';import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';@Component({ selector: 'app-changepassword-form', templateUrl: './changepassword-form.component.html', styleUrls: ['./changepassword-form.component.css']})export class ChangepasswordFormComponent { form; constructor(fb: FormBuilder) { this.form = fb.group({ newPassword: ['', Validators.required], confirmPassword: ['', Validators.required] }) } get newPassword() { return this.form.get('newPassword'); } get confirmPassword() { return this.form.get('confirmPassword'); }} and HTML: <form [formGroup]="form"> <div class="form-group"> <label for="newPassword">New Password</label> <input formControlName="newPassword" id="newPassword" type="text" class="form-control"> <div class="alert alert-danger" *ngIf="newPassword.touched && newPassword.errors.required"> Required </div> </div> <div class="form-group"> <label for="confirmPassword">Confirm Password</label> <input formControlName="confirmPassword" id="confirmPassword" type="text" class="form-control"> <div class="alert alert-danger" *ngIf="confirmPassword.touched && confirmPassword.errors.required"> Required </div> </div> <p><button class="btn btn-primary">Submit</button></p></form>
Now provide the response and nothing else.
| That error is coming from this: *ngIf="newPassword.touched && newPassword.errors.required" When you put in a value, there is no longer an errors collection so checking newPassword.errors.required generates that Cannot read property 'required' of null error. Try something like this instead: *ngIf="newPassword.touched && newPassword.errors?.required" As an example, mine looks like this: <div class="col-md-8"> <input class="form-control" id="productNameId" type="text" placeholder="Name (required)" required minlength="3" [(ngModel)] = product.productName name="productName" #productNameVar="ngModel" /> <span class="help-block" *ngIf="(productNameVar.touched || productNameVar.dirty || product.id !== 0) && productNameVar.errors"> <span *ngIf="productNameVar.errors.required"> Product name is required. </span> <span *ngIf="productNameVar.errors.minlength"> Product name must be at least three characters. </span> </span> </div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45950054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/641361/']} | jdg_382316 |
stackexchange | llm_judgeable_groundtruth_similarity | 27296359 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After upgrading Xcode to 6.1.1, there's one project I just can't open anymore. It happens while "Loading xxx...". Here's the dump: Process: Xcode [9343]Path: /Applications/Xcode.app/Contents/MacOS/XcodeIdentifier: com.apple.dt.XcodeVersion: 6.1.1 (6611)Build Info: IDEFrameworks-6611000000000000~4App Item ID: 497799835App External ID: 810788292Code Type: X86-64 (Native)Parent Process: ??? [1]Responsible: Xcode [9343]User ID: 503Date/Time: 2014-12-04 09:13:16.198 -0500OS Version: Mac OS X 10.10.2 (14C68k)Report Version: 11Anonymous UUID: 4D866B4F-CB26-6063-CCCD-E67B869C790DSleep/Wake UUID: AFB5AAC7-3418-4089-9431-D5F33891A437Time Awake Since Boot: 12000 secondsTime Since Wake: 1100 secondsCrashed Thread: 10 Dispatch queue: IBPlatformToolRequestQueue.IBCocoaTouchFramework-EightAndLaterException Type: EXC_CRASH (SIGABRT)Exception Codes: 0x0000000000000000, 0x0000000000000000Application Specific Information:ProductBuildVersion: 6A2008aUNCAUGHT EXCEPTION (IBAssertionFailure): ASSERTION FAILURE: [item ibBaselineCount] >= 1Reason: An item that references the first attribute must have multiple baselinesFile: /SourceCache/IBAutolayoutFoundationIOS/IDEInterfaceBuilder-6254/AutolayoutFoundation/Model/IBAutolayoutCommon.m:221Method: CGFloat IBLayoutAttributeValueOfAttributeForItemInCoordinateSpaceOfItem(IBLayoutAttribute, NSObject<IBAutolayoutItem> *__strong, NSObject<IBAutolayoutItem> *__strong, IBUserInterfaceLayoutDirection)UserInfo: { IBAbstractPlatformToolExceptionBacktrace = " 0. CoreFoundation 0x000000010e8d9f1d __exceptionPreprocess\n 1. libobjc.A.dylib 0x000000010d5c0bb7 objc_exception_throw\n 2. CoreFoundation 0x000000010e8d9b79 -[NSException raise]\n 3. IBAutolayoutFoundation 0x000000010cc7cb9a IBLayoutAttributeValueOfAttributeForItemInCoordinateSpaceOfItem\n 4. IBAutolayoutFoundation 0x000000010ccaef34 -[IBLayoutConstraint roundingAdjustmentWithUserInterfaceLayoutDirection:]\n 5. IBAutolayoutFoundation 0x000000010cc8f1c3 -[IBAutolayoutEngine _attemptToAddConstraint:toView:returningConstraintsOrConstraintAbstractionsMakingSystemOverConstrained:constraintsOrAbstractionsForRepresentedConstraintsBlock:]\n 6. IBAutolayoutFoundation 0x000000010cc8f43d -[IBAutolayoutEngine attemptToAddConstraint:toView:returningConstraintsMakingSystemOverConstrained:]\n 7. IBAutolayoutFoundation 0x000000010cc63009 +[IBAutolayoutArbiter attemptToAddConstraint:byModifyingLayoutEngine:mutuallyExclusiveConstraintBreakageStrategy:mutableConstraintsToAdd:mutableConstraintsToRemove:]\n 8. IBAutolayoutFoundation 0x000000010cc8d6be -[IBAutolayoutEngine performEngineBootstrappingConstraintAdditionOperationForAddingConstraint:]\n 9. IBAutolayoutFoundation 0x000000010cc8dc44 __90-[IBAutolayoutEngine iterateViewsAndGenerateRepresentedConstraintsAndMapToRealConstraints]_block_invoke662\n 10. CoreFoundation 0x000000010e813a45 __NSDictionaryEnumerate\n 11. IBAutolayoutFoundation 0x000000010cc8d9c6 -[IBAutolayoutEngine iterateViewsAndGenerateRepresentedConstraintsAndMapToRealConstraints]\n 12. IBAutolayoutFoundation 0x000000010cc882f3 -[IBAutolayoutEngine initWithArbitrationUnit:options:]\n 13. IBAutolayoutFoundation 0x000000010cc6e818 -[IBAutolayoutArbitrationUnit computeStatus]\n 14. ??? 0x000000010b0987a5 [IBCocoaTouchTool computeAutolayoutStatusForRequest:document:]\n 15. IBFoundation 0x000000010cde08ef __80-[IBMessageReceiveChannel deliverMessage:toTarget:withArguments:context:result:]_block_invoke\n 16. IBFoundation 0x000000010cde0686 -[IBMessageReceiveChannel deliverMessage:toTarget:withArguments:context:result:]\n 17. IBFoundation 0x000000010cde0350 __88-[IBMessageReceiveChannel runBlockingReceiveLoopNotifyingQueue:notifyingTarget:context:]_block_invoke\n 18. libdispatch.dylib 0x0000000111ed5af4 _dispatch_client_callout\n 19. libdispatch.dylib 0x0000000111ec2e95 _dispatch_barrier_sync_f_slow_invoke\n 20. libdispatch.dylib 0x0000000111ed5af4 _dispatch_client_callout\n 21. libdispatch.dylib 0x0000000111ec1265 _dispatch_main_queue_callback_4CF\n 22. CoreFoundation 0x000000010e841fe9 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__\n 23. CoreFoundation 0x000000010e804eeb __CFRunLoopRun\n 24. CoreFoundation 0x000000010e804486 CFRunLoopRunSpecific\n 25. Foundation 0x000000010d17db42 -[NSRunLoop(NSRunLoop) runMode:beforeDate:]\n 26. IBFoundation 0x000000010cdbf955 -[IBAbstractPlatformTool startServingReceiveChannel:]\n 27. IBFoundation 0x000000010cdbfa2f -[IBAbstractPlatformTool startServingSocket:]\n 28. IBFoundation 0x000000010cdbfcf2 +[IBAbstractPlatformTool main]\n 29. ??? 0x000000010b0cae90 [IBViewRenderer .cxx_destruct]\n 30. libdyld.dylib 0x0000000111f06145 start";}Hints: NoneBacktrace: 0 0x00007fff91dae654 __exceptionPreprocess (in CoreFoundation) 1 0x00000001018f7274 DVTFailureHintExceptionPreprocessor (in DVTFoundation) 2 0x00007fff9497f76e objc_exception_throw (in libobjc.A.dylib) 3 0x00007fff91dae209 -[NSException raise] (in CoreFoundation) 4 0x000000010bc8c9d9 -[IBAbstractMessageChannelToolProxy _errorByAddingAdditionalCrashInformationToError:orRaiseIfNeededOnFailure:shouldRaiseOnFailures:waitForCrashLog:] (in IDEInterfaceBuilderKit) 5 0x000000010bc8c8fd -[IBAbstractMessageChannelToolProxy errorByAddingAdditionalCrashInformationToError:orRaiseIfNeededOnFailure:] (in IDEInterfaceBuilderKit) 6 0x000000011054c06e (in IDEInterfaceBuilderCocoaTouchIntegration) 7 0x00000001105413d3 (in IDEInterfaceBuilderCocoaTouchIntegration) 8 0x000000010ba8d51d -[IBPlatformToolRequester processRequests] (in IDEInterfaceBuilderKit) 9 0x000000010192dc9c __DVTDispatchAsync_block_invoke (in DVTFoundation) 10 0x00007fff94d8d323 _dispatch_call_block_and_release (in libdispatch.dylib) 11 0x00007fff94d88c13 _dispatch_client_callout (in libdispatch.dylib) 12 0x00007fff94d8c365 _dispatch_queue_drain (in libdispatch.dylib) 13 0x00007fff94d8decc _dispatch_queue_invoke (in libdispatch.dylib) 14 0x00007fff94d8b6b7 _dispatch_root_queue_drain (in libdispatch.dylib) 15 0x00007fff94d99fe4 _dispatch_worker_thread3 (in libdispatch.dylib) 16 0x00007fff96cac637 _pthread_wqthread (in libsystem_pthread.dylib) 17 0x00007fff96caa40d start_wqthread (in libsystem_pthread.dylib)abort() calledApplication Specific Signatures:IBAssertionFailureApplication Specific Backtrace 1:0 CoreFoundation 0x00007fff91dae66c __exceptionPreprocess + 1721 DVTFoundation 0x00000001018f7274 DVTFailureHintExceptionPreprocessor + 1942 libobjc.A.dylib 0x00007fff9497f76e objc_exception_throw + 433 CoreFoundation 0x00007fff91dae209 -[NSException raise] + 94 IDEInterfaceBuilderKit 0x000000010bc8c9d9 -[IBAbstractMessageChannelToolProxy _errorByAddingAdditionalCrashInformationToError:orRaiseIfNeededOnFailure:shouldRaiseOnFailures:waitForCrashLog:] + 1785 IDEInterfaceBuilderKit 0x000000010bc8c8fd -[IBAbstractMessageChannelToolProxy errorByAddingAdditionalCrashInformationToError:orRaiseIfNeededOnFailure:] + 986 IDEInterfaceBuilderCocoaTouchIntegration 0x000000011054c06e IBUISegmentConfiguration + 48127 IDEInterfaceBuilderCocoaTouchIntegration 0x00000001105413d3 IBIsObjectIllegalCocoaTouchOutletEndPoint + 106998 IDEInterfaceBuilderKit 0x000000010ba8d51d -[IBPlatformToolRequester processRequests] + 11619 DVTFoundation 0x000000010192dc9c __DVTDispatchAsync_block_invoke + 10610 libdispatch.dylib 0x00007fff94d8d323 _dispatch_call_block_and_release + 1211 libdispatch.dylib 0x00007fff94d88c13 _dispatch_client_callout + 812 libdispatch.dylib 0x00007fff94d8c365 _dispatch_queue_drain + 110013 libdispatch.dylib 0x00007fff94d8decc _dispatch_queue_invoke + 20214 libdispatch.dylib 0x00007fff94d8b6b7 _dispatch_root_queue_drain + 46315 libdispatch.dylib 0x00007fff94d99fe4 _dispatch_worker_thread3 + 9116 libsystem_pthread.dylib 0x00007fff96cac637 _pthread_wqthread + 72917 libsystem_pthread.dylib 0x00007fff96caa40d start_wqthread + 13 Thread 0:: Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x00007fff9730d136 __psynch_cvwait + 10 1 com.apple.Foundation 0x00007fff979cb220 -[NSCondition waitUntilDate:] + 343 2 com.apple.Foundation 0x00007fff979c10d8 -[NSConditionLock lockWhenCondition:beforeDate:] + 232 3 com.apple.dt.IBFoundation 0x00000001082c8ea6 -[IBSemaphore decrementWithTimeout:] + 179 4 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010ba8ccea -[IBPlatformToolRequester waitForRequestWithID:timeout:] + 352 5 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb8f6f6 -[IBDocumentAutolayoutManager autolayoutStatusForArbitrationUnitContainingObject:] + 200 6 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb903ea -[IBDocumentAutolayoutManager isItemMisplaced:] + 69 7 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb90a4b __61-[IBDocumentAutolayoutManager itemsWithCleanAutolayoutStatus]_block_invoke + 42 8 com.apple.dt.IBFoundation 0x00000001082598cd -[NSSet(IBSetAdditions) ib_setByFilteringUsingBlock:] + 246 9 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb909f0 -[IBDocumentAutolayoutManager itemsWithCleanAutolayoutStatus] + 145 10 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb829a7 -[IBDocumentAutolayoutManager preserveCleanAutolayoutStatusDuring:] + 55 11 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb6b59c -[IBDocument preserveCleanAutolayoutStatusDuring:] + 7912 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bd2c9be -[IBResourceManager synchronizeObjectPropertyValuesWithVariantContext] + 11213 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bd29de7 __66-[IBResourceManager setupVariantContextWithContainerRepositories:]_block_invoke + 87014 com.apple.dt.IDEKit 0x0000000102ef7cac -[IDEMediaResourceVariantContext registerVariantContextObserverWithOptions:block:] + 19415 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bd299a0 -[IBResourceManager setupVariantContextWithContainerRepositories:] + 49316 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bd29f4b -[IBResourceManager setResourceProvidingContainer:] + 19617 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb45d77 -[IBDocument setResourceProvidingContainer:] + 7918 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb449eb -[IBDocument refreshWorkspaceSourcedContent] + 12019 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bb44cbe -[IBDocument registerWorkspaceDocument:forEditorViewController:] + 27120 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010ba2fa3b -[IBAbstractDocumentEditor viewDidInstall] + 16621 com.apple.dt.IDE.IDEInterfaceBuilderKit 0x000000010bd7ebb8 -[IBStoryboardDocumentEditor viewDidInstall] + 5122 com.apple.dt.DVTKit 0x0000000101f4240f -[DVTViewController _didInstallContentView:] + 24423 com.apple.dt.DVTKit 0x0000000101d458bc -[DVTControllerContentView _viewDidInstall] + 33024 com.apple.dt.DVTKit 0x0000000101d4516c -[DVTControllerContentView viewDidMoveToWindow] + 9725 com.apple.AppKit 0x00007fff904a0997 -[NSView _setWindow:] + 327426 com.apple.AppKit 0x00007fff9049dc83 -[NSView addSubview:] + 46327 com.apple.AppKit 0x00007fff9054aea3 -[NSView setSubviews:] + 94728 com.apple.dt.DVTKit 0x0000000101d379a1 -[DVTBorderedView setContentView:] + 19329 com.apple.dt.IDEKit 0x0000000102928f43 -[IDEEditorContext _setEditorView] + 32430 com.apple.dt.IDEKit 0x0000000102ae75eb -[IDEEditorContext setupNewEditor:] + 94631 com.apple.dt.IDEKit 0x0000000102ae91f2 __91-[IDEEditorContext _openNavigableItem:documentExtension:document:shouldInstallEditorBlock:]_block_invoke + 131132 com.apple.dt.IDEKit 0x000000010293c01b -[IDEEditorContext _performBlockInsideReentrantGuard:] + 13233 com.apple.dt.IDEKit 0x000000010293be6e -[IDEEditorContext _openNavigableItem:documentExtension:document:shouldInstallEditorBlock:] + 352134 com.apple.dt.IDEKit 0x000000010296f805 -[IDEEditorContext _openNavigableItem:withContentsOfURL:documentExtension:shouldInstallEditorBlock:] + 171335 com.apple.dt.IDEKit 0x0000000102aeace0 -[IDEEditorContext _notifyDelegateAndOpenNavigableItem:withContentsURL:documentExtensionIdentifier:locationToSelect:annotationRepresentedObject:stateDictionary:annotationWantsIndicatorAnimation:exploreAnnotationRepresentedObject:highlightSelection:skipSubDocumentNavigationUnlessEditorIsReplaced:] + 365236 com.apple.dt.IDEKit 0x0000000102aec74b -[IDEEditorContext _notifyDelegateAndOpenEditorHistoryItem:previousHistoryItemOrNil:skipSubDocumentNavigationUnlessEditorIsReplaced:] + 95537 com.apple.dt.IDEKit 0x0000000102ae82a7 -[IDEEditorContext _openEditorHistoryItem:previousHistoryItemOrNil:skipSubDocumentNavigationUnlessEditorIsReplaced:] + 38138 com.apple.dt.IDEKit 0x000000010296d9fe -[IDEEditorContext _openEditorHistoryItem:updateHistory:] + 34639 com.apple.dt.IDEKit 0x000000010296cc01 -[IDEEditorContext _openEditorHistoryItemFromStateSaving:] + 44840 com.apple.dt.IDEKit 0x00000001029a217d -[IDEEditorBasicMode _setPersistentRepresentation:forIdentifier:] + 51941 com.apple.dt.IDEKit 0x0000000102db60be __60-[IDEEditorModeViewController _setPersistentRepresentation:]_block_invoke + 8442 com.apple.CoreFoundation 0x00007fff91ce3536 __53-[__NSArrayI enumerateObjectsWithOptions:usingBlock:]_block_invoke + 7043 com.apple.CoreFoundation 0x00007fff91ce3469 -[__NSArrayI enumerateObjectsWithOptions:usingBlock:] + 29744 com.apple.dt.IDEKit 0x00000001029688ce -[IDEEditorModeViewController _setPersistentRepresentation:] + 20145 com.apple.dt.IDEKit 0x00000001029686d1 -[IDEEditorModeViewController revertStateWithDictionary:] + 17046 com.apple.dt.DVTFoundation 0x000000010177797b -[DVTStateToken _pullStateFromDictionary:] + 32747 com.apple.dt.DVTFoundation 0x000000010177779d -[DVTStateToken pullStateFromRepository] + 16848 com.apple.dt.IDEKit 0x0000000102948f18 -[IDEViewController revertState] + 4849 com.apple.dt.IDEKit 0x0000000102922bc0 -[IDEEditorArea _updateStateSavingRegistrations] + 44250 com.apple.dt.IDEKit 0x000000010294b48f -[IDEEditorArea _refreshEditorContextsAndPreserveCurrentEditorHistoryStack:] + 70551 com.apple.dt.IDEKit 0x0000000102b27d0a __31-[IDEEditorArea viewDidInstall]_block_invoke + 42952 com.apple.dt.DVTFoundation 0x00000001019081ab __73-[DVTObservingBlockToken observeValueForKeyPath:ofObject:change:context:]_block_invoke183 + 8353 com.apple.dt.DVTFoundation 0x0000000101883d78 DVTInvokeWithStrongOwnership + 7554 com.apple.dt.DVTFoundation 0x00000001017375fc -[DVTObservingBlockToken observeValueForKeyPath:ofObject:change:context:] + 32855 com.apple.Foundation 0x00007fff9799aa93 NSKeyValueNotifyObserver + 38256 com.apple.Foundation 0x00007fff97999c68 NSKeyValueDidChange + 46357 com.apple.Foundation 0x00007fff9799e7cd -[NSObject(NSKeyValueObserverNotification) didChangeValueForKey:] + 11858 com.apple.dt.IDEFoundation 0x0000000102335a12 __81-[IDEWorkspace _finishLoadingAsynchronously:shouldUpgradeFromSimpleFilesFocused:]_block_invoke + 32159 com.apple.dt.IDEFoundation 0x0000000102335c6a __81-[IDEWorkspace _finishLoadingAsynchronously:shouldUpgradeFromSimpleFilesFocused:]_block_invoke321 + 5960 com.apple.Foundation 0x00007fff97ace108 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK__ + 761 com.apple.Foundation 0x00007fff979ba725 -[NSBlockOperation main] + 9762 com.apple.Foundation 0x00007fff979993bc -[__NSOperationInternal _start:] + 65363 com.apple.Foundation 0x00007fff97998fc3 __NSOQSchedule_f + 18464 libdispatch.dylib 0x00007fff94d88c13 _dispatch_client_callout + 865 libdispatch.dylib 0x00007fff94d94cbf _dispatch_main_queue_callback_4CF + 86166 com.apple.CoreFoundation 0x00007fff91d01c79 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 967 com.apple.CoreFoundation 0x00007fff91cbe30f __CFRunLoopRun + 215968 com.apple.CoreFoundation 0x00007fff91cbd858 CFRunLoopRunSpecific + 29669 com.apple.HIToolbox 0x00007fff8fcc52df RunCurrentEventLoopInMode + 23570 com.apple.HIToolbox 0x00007fff8fcc505a ReceiveNextEventCommon + 43171 com.apple.HIToolbox 0x00007fff8fcc4e9b _BlockUntilNextEventMatchingListInModeWithFilter + 7172 com.apple.AppKit 0x00007fff90488cf1 _DPSNextEvent + 96473 com.apple.AppKit 0x00007fff904884a0 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 19474 com.apple.dt.DVTKit 0x0000000101e5e6fd -[DVTApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 23775 com.apple.AppKit 0x00007fff9047c463 -[NSApplication run] + 59476 com.apple.AppKit 0x00007fff90467914 NSApplicationMain + 183277 libdyld.dylib 0x00007fff9496e5c9 start + 1 While I see the problem originates from IB (An item that references the first attribute must have multiple baselines), I have no clue what to try and change in my storyboard file, which is rather big. Anyone had the same fate? Any ideas?
Now provide the response and nothing else.
| I found a solution, it's kind of weird.I've followed dimzak adviced and clear the cache: curl --noproxy localhost -XPOST "http://localhost:9200/_cache/clear" Then I used filtering instead of querying as Olly suggested: { "size": 0, "query": { "filtered": { "query": { "term": { "referer": "www.xx.yy.fr" } }, "filter" : { "range": { "@timestamp": { "from": "2014-10-04T00:00", "to": "2014-10-05T00:00" } } } } }, "aggs": { "interval": { "date_histogram": { "field": "@timestamp", "interval": "0.5h" }, "aggs": { "what": { "cardinality": { "field": "host" } } } } }} I cannot give you both the ansxwer, I think dimzak deserves it best, but thumbs up to you two guys :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27296359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3294226/']} | jdg_382317 |
stackexchange | llm_judgeable_groundtruth_similarity | 44102483 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently, in my ModelFactory.php, I have: $factory->define(App\Reply::class, function (Faker\Generator $faker) { return [ 'thread_id' => 1, 'user_id' => 1, 'body' => $faker->paragraph ];}); I would like to generate a random user_id from one of the user ID's already stored in the user table. I'm stumped because I don't know the way to display data output to code properly, and I was wondering how I would be able to allow Laravel to choose a random user ID and insert into the database. Thank you! :)
Now provide the response and nothing else.
| Try the below. use App\User; // Assuming this is your User Model class with namespace.$factory->define(App\Reply::class, function (Faker\Generator $faker) { return [ 'thread_id' => 1, 'user_id' => User::all()->random()->id, 'body' => $faker->paragraph ];}); Remember that this gets all the user data from your table and then choses an id randomly. So if your table has huge amount of data, it is not recommended. Instead, in your Test Case, you can create a new User (via its own factory) and assign the id to the Reply object generated from the above factory. Alternately, you can query for a specific user in the above factory definition. 'user_id' => User::where('username', 'like', '[email protected]')->get()->random()->id If you have a test user set up in your DB this will avoid pulling all the user data. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44102483', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/520733/']} | jdg_382318 |
stackexchange | llm_judgeable_groundtruth_similarity | 43296231 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So, I am new to Android Studio. I'm following an online course step by step.I'm using ParseServer on AWS. I've managed to get my appId, etc. and can connect with a Java SSH Client directly from my browser. My app can successfully store information in the ParseServer, but I can't access the parse dashboard. When I try to it asks me to enter my username and password -- which I don't have. I've found a file (in bitnami terminal) and I think that I should maybe make myself an account in here? # /home/bitnami/apps/parse/.forever/config.json{ "root": "/opt/bitnami/apps/parse/.forever", "pidPath": "/opt/bitnami/apps/parse/.forever/pids", "sockPath": "/opt/bitnami/apps/parse/.forever/sock", "loglength": 100, "logstream": false, "columns": [ "uid", "command", "script", "forever", "pid", "id", "logfile", "uptime" ]}
Now provide the response and nothing else.
| From the Windows Run dialog: The following command starts PowerShell in a console window with the default size and then resizes the window to 100 columns x 50 rows: powershell -noexit -command "[console]::WindowWidth=100; [console]::WindowHeight=50; [console]::BufferWidth=[console]::WindowWidth" Note: powershell -noexit -command "mode con cols=100 lines=50" works in principle, but has the unfortunate side effect that you lose any scroll-back buffer (the buffer height is set to the window height). The command uses the [console] ( System.Console ) .NET type to set the window width and height, and additionally sets the buffer width to the same value as the window width, so as to ensure that no horizontal scroll bar appears. From an existing console window: If you run the above command from an existing Command Prompt or PowerShell console, the new PowerShell session starts in the current window, and therefore resizes the current window. Here's how to open a new window : from a Command Prompt ( cmd.exe ): use start : start powershell -noexit -command "[console]::windowwidth=100; [console]::windowheight=50; [console]::bufferwidth=[console]::windowwidth" from a PowerShell console window: use Start-Process (note the single quotes around the argument list): start-process powershell '-noexit -command "[console]::windowwidth=100; [console]::windowheight=50; [console]::bufferwidth=[console]::windowwidth"' If you don't want to resize the window after it has opened with the default size: The commands above run after the new window has been created with the default size, which can be visually disruptive. To prevent that, you have two options: Create a shortcut file that targets powershell.exe , configure its properties to set the desired size, then run the shortcut file ( *.lnk ) to open the window. As papo points out, you can also preset the window size for PowerShell instances you invoke via the Start Menu, via the Win-X shortcut menu, or via File Explorer's File > Open Windows Powershell command that way, by modifying the preexisting underlying shortcut file : [1] "$env:AppData\Microsoft\Windows\Start Menu\Programs\Windows PowerShell\Windows PowerShell.lnk" Change the default window size to your liking, but note that this then applies to all PowerShell sessions started with just the executable name (or path): Interactively: Press Win+R and submit just powershell Open the new window's system menu, select Properties and configure the window size as desired. Future windows launched the same way will have the same size. Programmatically: Console window properties are stored in the registry at HKEY_CURRENT_USER\Console , with the REG_DWORD value WindowSize containing the window size, and ScreenBufferSize containing the buffer size: Key HKEY_CURRENT_USER\Console ( HKCU:\Console ) contains the overall defaults. Subkeys, such as %SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe , contain overrides for specific executables / window titles. Important : These settings do not apply to console windows started via shortcut files ( .lnk ) ; the latter dynamically inherit the overall console defaults directly from HKEY_CURRENT_USER\Console (not from any subkeys) - except for CodePage on Windows 10 (not sure about Windows 8/8.1), and except for values later overridden via the Properties dialog, which are saved directly in the file . Subkeys inherit values from their parent, which complicates setting values for subkeys - see below for an example. Setting powershell.exe window-size defaults programmatically: The following PSv5+ snippet sets the default window size for powershell.exe -launched console windows to 100 columns by 50 rows. Note that the fact that screen buffer values are inherited from the overall default settings, stored directly in HKCU:\Console , adds complexity. # Determine the target registry key path.$keyPath = 'HKCU:\Console\%SystemRoot%_System32_WindowsPowerShell_v1.0_powershell.exe'# Get the existing key or create it on demand.$key = Get-Item $keyPath -ErrorAction SilentlyContinueif (-not $key) { $key = New-Item $keyPath }# Determine the new size values.[uint32] $cols = 100; [uint32] $lines = 50# Convert to a DWORD for writing to the registry.[uint32] $dwordWinSize = ($cols + ($lines -shl 16))# Note: Screen *buffer* values are inherited from # HKCU:\Console, and if the inherited buffer width is larger# than the window width, the window width is apparently set to # the larger size.# Therefore, we must also set the ScreenBufferSize value, passing through# its inherited height value while setting its width value to the same# value as the window width.[uint32] $dwordScreenBuf = Get-ItemPropertyValue HKCU:\Console ScreenBufferSize -EA SilentlyContinueif (-not $dwordScreenBuf) { # No buffer size to inherit. # Height is 3000 lines by default. # Note that if we didn't set this explicitly, the buffer height would # default to the same value as the window height. $dwordScreenBuf = 3000 -shl 16 }# Set the buffer width (low word) to the same width as the window# (so that there's no horizontal scrolling).$dwordScreenBuf = $cols + (($dwordScreenBuf -shr 16) -shl 16)# Write the new values to the registry.Set-ItemProperty -Type DWord $key.PSPath WindowSize $dwordWinSizeSet-ItemProperty -Type DWord $key.PSPath ScreenBufferSize $dwordScreenBuf [1] papo further states, "[That the] Win+X Menu actually starts this lnk (will error if missing), which is weird, as Win+X has its own shortcuts: "$env:LOCALAPPDATA\Microsoft\Windows\WinX\Group3" , which are ignored. (Win10 1809). PS started from Explorer's > File will still work if this link is removed, but will use defaults from registry." | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43296231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7837603/']} | jdg_382319 |
stackexchange | llm_judgeable_groundtruth_similarity | 1437250 |
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 connect to an edirectory 8.8 server running LDAP. How would I go about doing that in .Net? Can I still use the classes in System.DirectoryService such as DirectoryEntry and DirectorySearcher or are they AD specific? Do I need to specify the "Connection String" any differently? I am trying something like the code below but it doesn't seem to work... DirectoryEntry de = new DirectoryEntry ("LDAP://novellBox.sample.com","admin","password",AuthenticationTypes.None);DirectorySearcher ds = new DirectorySearcher(de);var test = ds.FindAll(); Any ideas?
Now provide the response and nothing else.
| Well, I think your connection string is missing a bit - specifying just the server name isn't good enough - you also need to specify a "starting point" for your search. In AD, this would typically be something like the "Users" container in your domain, which you'd specify like this in LDAP parlance: LDAP://novellBox.sample.com/cn=Users,dc=YourCompany,dc=com Not sure how LDAP compliant the newer versions of eDirectory are - but that should work since in theory, it's standard LDAP regardless of the implementation :-) But then again: only in theory, there's no difference between theory and practice..... There's also a System.DirectoryServices.Protocols namespace which offers low-level LDAP calls directly - and that's definitely not tied to AD at all, but it's really quite low-level..... There's also a Novell C# LDAP library but I've never tried it and can't say how complete or capable it is. It might give you some clues, though! Also see this other Stackoverflow question about Novell, LDAP and C# - it might give you additional info. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1437250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/79339/']} | jdg_382320 |
stackexchange | llm_judgeable_groundtruth_similarity | 2519807 |
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 do something like this: property = 'name'value = Thing()class A: setattr(A, property, value) other_thing = 'normal attribute' def __init__(self, etc) #etc.......... But I can't seem to find the reference to the class to get the setattr to work the same as just assigning a variable in the class definition. How can I do this?
Now provide the response and nothing else.
| You'll need to use a metaclass for this: property = 'foo'value = 'bar'class MC(type): def __init__(cls, name, bases, dict): setattr(cls, property, value) super(MC, cls).__init__(name, bases, dict)class C(object): __metaclass__ = MCprint C.foo | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2519807', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1236375/']} | jdg_382321 |
stackexchange | llm_judgeable_groundtruth_similarity | 19100106 |
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 having few doubts about the local/our scope in Perl. I read a lot of documentation, but I am still in confusion is there. Following are the confusions What is local scope? what I read is -> local copies the value of global variable, change the value, user will use it and outside the block it will retain the global value Confusion -> my does the same thing. Only benefit I see is that some variables like $package::var cannot be declared with my scope but can be declared with local scope. What else for local What is "global" variable? What I read is -> Its scope is within the package. Basically we put the global variable in @EXPORT array and use it or append the namespace with it to use in other packages. I doubt -> Again if we declare variable with my scope in main only then we can access the variable throughout the package. Is that right? Is it possible to add the my scoped variables in @EXPORT array and use it in another packages? I think global variables are declared with our keyword. Is there any other way to do so? This question may look repetitive, but I am confused.
Now provide the response and nothing else.
| In terms of scoping, there are three kinds of variables in Perl. Lexical variables are lexically scoped, which means they are only visible in the current lexical scope (basically file or block). Package variables, on the other hand, can be used using their qualified form (e.g. $Foo::x ) from anywhere in the interpreter, and they can be used without qualification by any code that shares the variable's package. Certain package variables are visible without qualification anywhere in the interpreter. These include punctuation vars and a few named vars such as @ARGV and STDOUT . For example, $x refers to $Foo::x when in package Foo and $Bar::x when in package Bar (assuming no lexical var named $x is in scope), but $_ always refers to $::_ . Variables are destroyed when they are no longer referenced. Lexical variables are usually destroyed when the lexical scope is exited. Package variables are usually destroyed when the program exits. Here are ways to create variable. my and state create a lexical variable. our creates a lexical variable that is aliased to the variable of the same name in the current package. In other words, our $x; is equivalent to my \$x = \$Foo::x; when in package Foo . Package variables are created on use. local doesn't create any variables. It simply backs up a variable until the current lexical scope is destroyed. It is restored from its backed-up value at that point. my does the same thing. No. local does not change the scope of a variable. While a lexical variable is only visible in a lexical scope, a localized package variable is still visible across the entire interpreter. $x = 123;sub foo { print "$x\n"; }{ local $x = 456; foo(); } # 456foo(); # 123 $x = 123;sub foo { print "$x\n"; }{ my $x = 456; foo(); } # 123foo(); # 123 What else for local local is primarily used to approximate the functionality of my for variables that cannot otherwise be declared lexically. Historically, that was all variables. Since 5.6, only punctuation variables cannot be declared lexically. What is "global" variable? A global variable is a variable that can seen globally. All package variables can be seen by any code in the interpreter, so they're all global. Or are they? To see them from other packages, you need to qualify them. Are $x and $Foo::x the same variable? To some, global variables refers to the set of package variables you can use unqualified. It means that package changes the set of global variables. And since the package directive is usually used on a file-basis, that means file-level lexicals are also effectively global by this definition. And they are indeed called that sometimes. But if the package changes the set of variables that are global, then they're not really global, are they? So think some people, which only consider punctuation variables (e.g. $_ ) and the few named variables that can be used unqualified from anywhere ( *::STDOUT ) to be global. In short, it's a pretty useless term. Is it possible to add the my scoped variables in @EXPORT array and use it in another packages? No. @EXPORT is used by Exporter. Exporter would not be able to find anything but package symbols (since files are compiled in fresh lexical scopes), so @EXPORT must only contain package symbols. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19100106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1336962/']} | jdg_382322 |
stackexchange | llm_judgeable_groundtruth_similarity | 12761445 |
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: GetImageSize() not returning FALSE when it should i currently have a filter system as follows: // Check to see if the type of file uploaded is a valid image typefunction is_valid_type($file){ // This is an array that holds all the valid image MIME types $valid_types = array("image/jpg", "image/JPG", "image/jpeg", "image/bmp", "image/gif", "image/png"); if (in_array($file['type'], $valid_types)) return 1; return 0;} but i have been told that it is better to check the filetype myself, how would i use the getimagesize() to check the filetype in a similar way?
Now provide the response and nothing else.
| getimagesize() returns an array with 7 elements. The index 2 of the array contains one of the IMAGETYPE_XXX constants indicating the type of the image. The equivalent of the function provided using getimagesize() would be function is_valid_type($file){ $size = getimagesize($file); if(!$size) { return 0; } $valid_types = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP); if(in_array($size[2], $valid_types)) { return 1; } else { return 0; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12761445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1644770/']} | jdg_382323 |
stackexchange | llm_judgeable_groundtruth_similarity | 780427 |
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:
Find the integral $$\int\dfrac{\sin x}{\sqrt{2}+\sin x+\cos x} \, dx$$ My idea: since$$\sin x+\cos x=\sqrt{2}\sin(x+\dfrac{\pi}{4})$$so $$\int\dfrac{\sin x}{\sqrt{2}+\sin x +\cos x} \, dx=\int\dfrac{\sin x}{\sqrt{2}(1+\sin (x+\dfrac{\pi}{4})} \, dx$$But then I don't know how to continue. Thank you
Now provide the response and nothing else.
| Hint: lab bhattacharjee's Weierstrass substitution hint is very appropriate of course, but it would be nice if more of the algebra tedium could be obviated. Try, $$\int\dfrac{\sin{x}}{\sqrt{2}+\sin{x}+\cos{x}}dx=\frac{1}{\sqrt{2}}\int\dfrac{\sin{x}}{1+\sin{(x+\dfrac{\pi}{4})}}dx\\=\frac{1}{\sqrt{2}}\int\dfrac{\sin{(\phi-\frac{\pi}{4})}}{1+\sin{\phi}}d\phi\\=\frac{1}{2}\int\dfrac{\sin{\phi}-\cos{\phi}}{1+\sin{\phi}}d\phi$$ Now use the Weierstrass substitution. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/780427', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']} | jdg_382324 |
stackexchange | llm_judgeable_groundtruth_similarity | 42076 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Correct me if I am wrong, but if we count sunsets by the center of the Sun apparently crossing the horizon then the Sun is supposed to set every day at latitudes under the arctic circle. (Yes if you count in the disc then adjust by 0.27 degrees.) I was playing around with PyEphem (a python library that claims an approximately 1 arcsecond accuracy), and found that according to it the sun stays up for a couple of days even under it ( $66.2<90-23.4$ ). Can someone explain what is going on? I created this simple plot to illustrate the issue. The left panel shows the whole period while the right panel shows that the problem is not that the data is under sampled. The plot goes from 2021-06-13 00:12:58.085383+00:00 to 2021-06-28 23:54:05.880661+00:00 . And one more example: Kuusamo is a city at 65°58′N 29°11′E and apparently it also has a few days when the sun doesn't set: LINK1 LINK2
Now provide the response and nothing else.
| From the PyEphem Quick Reference Guide : Rising and setting are sensitive to atmospheric refraction at thehorizon, and therefore to the observer’s temp and pressure; set thepressure to zero to turn off refraction. It seems likely that, if you're using the default settings, the result returned is including atmospheric refraction, giving the results you would expect to see at the location, where the sun is visible even though a direct line to the disc of the sun would put it below the horizon. Image is from " What is Refraction of Light " by By Konstantin Bikos and Aparna Kher at timeanddate.com | {} | {'log_upvote_score': 7, 'links': ['https://astronomy.stackexchange.com/questions/42076', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/38570/']} | jdg_382325 |
stackexchange | llm_judgeable_groundtruth_similarity | 86884 |
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:
When running a bash script, I would like to be able to tell if it is running within a screen . Is this possible? I want this so that .bashrc can set the colour of the command prompt depending on whether the sessions is started within a screen or not. Discovered this link once mine was answered: How can I tell whether I'm in a screen?
Now provide the response and nothing else.
| Typically, $STY will be set. So: if [ -n "$STY" ]; then echo "I'm most likely running under screen"fi $STY is typically what you need to talk to your screen . That is used to construct the path of the Unix domain socket used to control screen (something like /var/run/screen/S-$USER/$STY . Now, that won't work for instance if from that screen, you ssh to another machine. The shell started there won't have $STY in its environment, and that wouldn't be of any use to it anyway, since it wouldn't be able to access the Unix domain sockets on your machine. However, it is possible to query the terminal with an escape sequence to determine its type: if [ -t 1 ] && [ -t 0 ]; then s=$(stty -g) stty -icanon -echo min 0 time 3 printf '\033[>c' type=$(dd count=1 2> /dev/null) stty "$s" case $type in (*'>83;'*) echo "this is screen" esacfi Another approach, as suggested by @val0x00ff is to check the value of the $TERM environment variable. That value is meant to tell applications what type of terminal they're talking to. It is set by screen to something that starts with screen (as screen can implement different variants of terminals). $TERM is passed accross rlogin , rsh , telnet , ssh . It's not as guaranteed to work as the above but is simpler and less intrusive. case $TERM in (screen*) echo "I'm more than likely running in screen"esac Like for the previous solution, you may be running in screen , but you may not be able to issue commands to it with screen -X for instance. However note, that you can pass commands using escape sequences (though it's not enabled by default for security reasons). | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/86884', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/45220/']} | jdg_382326 |
stackexchange | llm_judgeable_groundtruth_similarity | 20585729 |
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 any way I can detect if the output from my Node.js script is being piped to something other then the terminal? I would like some way of detecting if this is happening: node myscript.js | less Or if this is happening: node myscript.js
Now provide the response and nothing else.
| The easiest way would be process.stdout.isTTY (0.8 +): $ node -p -e "Boolean(process.stdout.isTTY)"true$ node -p -e "Boolean(process.stdout.isTTY)" | catfalse (example from the official documentation) Alternatively you can use the tty module for finer grained control: if (require('tty').isatty(1)) { // terminal} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20585729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/477792/']} | jdg_382327 |
stackexchange | llm_judgeable_groundtruth_similarity | 492030 |
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 basically want to go from this: .├── Alan Walker│ ├── Different World│ │ ├── 01 Intro.mp3│ │ ├── 02 Lost Control.mp3│ │ └── cover.jpg│ └── Same World│ ├── 01 Intro.mp3│ └── 02 Found Control.mp3├── Aurora│ └── Infections Of A Different Kind Step 1│ ├── 01 Queendom.lrc│ ├── 02 Forgotten Love.lrc│ └── 03 Gentle Earthquakes.mp3└── Guns N' Roses └── Use Your Illusion I ├── 01 Right Next Door To Hell.lrc ├── 01 Right Next Door To Hell.mp3 ├── 02 Dust N' Bones.lrc └── 02 Dust N' Bones.mp3 to this: .├── Alan Walker - Different World│ ├── 01 Intro.mp3│ ├── 02 Lost Control.mp3│ └── cover.jpg├── Alan Walker - Same World│ ├── 01 Intro.mp3│ └── 02 Found Control.mp3├── Aurora - Infections Of A Different Kind Step 1│ ├── 01 Queendom.lrc│ ├── 02 Forgotten Love.lrc│ └── 03 Gentle Earthquakes.mp3└── Guns N' Roses - Use Your Illusion I ├── 01 Right Next Door To Hell.lrc ├── 01 Right Next Door To Hell.mp3 ├── 02 Dust N' Bones.lrc └── 02 Dust N' Bones.mp3 None of the existing solutions I could find included renaming the directory itself. It'd be great to be able to do this with zmv, but I can't figure out how to.
Now provide the response and nothing else.
| Something like this maybe? #!/bin/shfor topdir in */; do topdir_name=$( basename "$topdir" ) for subdir in "$topdir"/*/; do subdir_name=$( basename "$subdir" ) newdir="$topdir_name - $subdir_name" if mkdir "$newdir"; then mv "$subdir"/* "$newdir" rmdir "$subdir" fi done rmdir "$topdir"done This goes through all the top-level directories in the current directory (the band names). For each such directory, it goes through its subdirectories (the album names). For each pair of band name and album name, a new directory is created and the files from the subdirectory are moved to it. The album subdirectories are removed when they have been processed, as are the original band top-level directories. The rmdir calls will fail if any directory contains hidden filenames or if any of the new directories failed to be created. This is totally untested code. Run it on a backed-up copy of your files. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/492030', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/283419/']} | jdg_382328 |
stackexchange | llm_judgeable_groundtruth_similarity | 43890035 |
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 get recaptcha callback working with vue.js in a component. The captcha itself does work, but not the callback that I define in the data-callback attribute. I've tried everything I could think of, but I still get the ReCAPTCHA couldn't find user-provided function: dothisthat error. Here is the component <script> function dothisthat (){ alert(312); }</script><template> <div class="well main-well"> <h4>Captcha</h4> <p class="small">You must complete the captcha to finish your booking.</p> <div id="captcha-wrapper"> <div class="g-recaptcha" :data-sitekey="captchaKey" data-callback="dothisthat"></div> </div> </div></template><script> function dothisthat (){ alert(123); } import * as filters from '../../../filters'; import Translation from '../../../Translation'; export default { name: 'Captcha', props: { }, computed: { captchaKey: function() { return this.$store.getters.captcha; } }, methods: { dothisthat: function(){ return function() { console.log("123"); }; } }, mounted(){ function dothisthat() { alert(123); } $(function() { function dothisthat() { alert(123); } }); } }</script> Not one of the dothisthat functions are getting called. What am I doing wrong?
Now provide the response and nothing else.
| I came across this problem too and it took me 2 days to solve it. So I will provide here a general answer for integrating recaptcha with vue.js from scratch step by step, to be an easy guide for people who will be in the same situation in the future (I am supposing vue-cli is used here). Note: I am using here the invisible recaptcha but the process is pretty similar to the normal one Step 1: add the recaptcha javascript api to your index.html index.html <script src="https://www.google.com/recaptcha/api.js" async defer></script> Step 2: make a component called Recaptcha or whatever you want to call it (making a component will make your code easier to read, easier to maintain and easier to add recaptcha to more than one page if you need) Recaptcha.vue <template> <div id="g-recaptcha" class="g-recaptcha" :data-sitekey="sitekey"> </div></template><script>export default { data () { return { sitekey: '6LfAEj0UAAAAAFTGLqGozrRD8ayOy*********', widgetId: 0 } }, methods: { execute () { window.grecaptcha.execute(this.widgetId) }, reset () { window.grecaptcha.reset(this.widgetId) }, render () { if (window.grecaptcha) { this.widgetId = window.grecaptcha.render('g-recaptcha', { sitekey: this.sitekey, size: 'invisible', // the callback executed when the user solve the recaptcha callback: (response) => { // emit an event called verify with the response as payload this.$emit('verify', response) // reset the recaptcha widget so you can execute it again this.reset() } }) } } }, mounted () { // render the recaptcha widget when the component is mounted this.render() }}</script> Step 3: Import the recaptcha component and add it to your page (parent component). page.vue <template> <div> <h1>Parent component (your page)</h1> <button @click="executeRecaptcha">execute recaptcha</button> <!-- listen to verify event emited by the recaptcha component --> <recaptcha ref="recaptcha" @verify="submit"></recaptcha> </div></template><script>import Recaptcha from 'recaptcha'export default { components: { Recaptcha }, methods: { // send your recaptcha token to the server to verify it submit (response) { console.log(response) }, // execute the recaptcha widget executeRecaptcha () { this.$refs.recaptcha.execute() } }}</script> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43890035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2209644/']} | jdg_382329 |
stackexchange | llm_judgeable_groundtruth_similarity | 371401 |
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:
Say I have a method A which calls a method B and does one additional thing. The B method behaves differently in 10 different cases and I have a broad unit test describing it. And now I want to test my method A. What is the best practice to do that? Should I run the same test with all 10 cases for method A to make sure that proper method is run? It sounds like an overkill. Or maybe I should test only one of that cases? But there's a risk that in future I'll write some method which will be quite similar to B and there will occure a bug which won't be detected by the test. Or maybe there are some ways of checking that my B method was fired just by registering its name? Maybe that's quite simple problem, but I'm new in unit testing and I haven't found any clear answer.
Now provide the response and nothing else.
| You're question isn't completely clear to me, so I'm making the following assumptions: Method A and B are both "public", Method B has 10 execution paths through it and 10 test cases covering those paths, Method A calls B via at least one of its execution paths. There are paths through B that are not used by A . Also, I'm going to have to ignore "But there's a risk that in future I'll write some method which will be quite similar to B and there will occur a bug which won't be detected by the test" as I don't see how it's related to either your question or testing A and B . The first thing I'd say is do not try to mock B, unless you absolutely have to . This is a classic testing newbie mistake that many folk make. You only want to isolate A from B if the latter has side-effects or is slow. If you mock out B , you'll simply be testing A against the mock functionality, rather than B 's real functionality and you'll miss bugs as a result. The next thing to ask yourself is, can you repurpose some of those B test cases to have them test A and B together? So if you have four paths through B that are used by A , test those paths via testing A . There's a huge caveat here though. Bear in mind that each of those tests will then tightly couple itself to existing functionality of A and B . If you later change A to have that functionality itself for example, you could end up not testing that part of B . Or changes might break tests just because the test is now brittle, not because you broke functionality, etc. As ever, there's a balance to be had between principle (test everything!) and pragmatism (I've got to ship this one day for there to be value in what I'm doing). | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/371401', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/281400/']} | jdg_382330 |
stackexchange | llm_judgeable_groundtruth_similarity | 19517245 |
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 created a method that will send an email with information to customers. However, the email looks awful cus there is no style to it. I can't apply the style to the email for some reason. I have tried to google it, and there is a lot on how to solve this in code behind, but that's not my issue. I must place the css code in the Html body, since it must be displayed for the client when he opens the email. So my question is, how do I add css to the html code above? I have tried doing: <div style='...'></div> and this does not work Any help on how to solve this is appreciated. Below some of my code. I have shortened it, for readability. string HtmlBody = @"<div style='float: right'> <h3>Faktura</h3> <br /> Navn:<asp:Label ID='navn' runat='server' Text='%Navn%'/> <br /> Adresse:<asp:Label ID='adresse' runat='server' Text='%Adresse%'/> <br /> Postnr:<asp:Label ID='postnummer' runat='server' Text='%Postnr%'/> <br /> Land:<asp:Label ID='land' runat='server' Text='Danmark' /> <br /> Tlf: <asp:Label ID='tlfnummer' runat='server' Text='%Tlf%' /> <br /> Mail: <asp:Label ID='email' runat='server' Text='%Email%' /> <br /> <div style='float: right'> <p>Dato</p> </div> <hr /> <br /> <table style='background-color: #c00764'> <tr> <td><b>Fakturanr:</b></td> <td>%fakturanr%</td> </tr> <tr> <td><b>Ordrenr:</b></td> <td>%Ordrenr%</td> </tr> </table></div>"; Here are some of my info on the mail part MailMessage mailMsg = new MailMessage();mailMsg.IsBodyHtml = true;mailMsg.Priority = MailPriority.Normal;var smtpValues = GetSmtpValues();var smtpCredentials = GetNetworkCredentials();SmtpClient smptClient = new SmtpClient(smtpValues.Key, smtpValues.Value);smptClient.EnableSsl = true;smptClient.Credentials = new NetworkCredential(smtpCredentials.Key, smtpCredentials.Value);//Send mailsmptClient.Send(mailMsg);
Now provide the response and nothing else.
| Here are some tips: Don't place CSS inside the HEAD tags in HTML Email. When you code a web page, you traditionally place the CSS code in between the HEAD tags, above your content. But when HTML emails are viewed in browser-based email apps (like YahooMail!, Gmail, Hotmail, etc), those applications strip out the HEAD and BODY tags by default. We recommend that you place your CSS code inline to your content (Note: browser-based email apps also strip out your BODY tag, so any background colors or BODY settings should be handled with a 100% wide TABLE "wrapper" around your email. Or we suggest that you take a look at our Automatic CSS-inliner feature.). It should look something like this: <span style=" font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #BBBBBB;">Your content here....</span> Use inline CSS. Referencing CSS files on your server like this is not very reliable: <link href="http://www.yourdomain.com/style.css" rel="stylesheet" type="text/css"> You should use inline CSS (as specified above).Add a space in front of CSS lines. We've noticed that some email servers (not MailChimp's, but your recipients') like to strip out any lines that begin with periods (.) This can ruin your CSS. So, the workaround is to add a space in front of any CSS that begins with a dot, such as: .title {font-size:22px;}.subTitle {font-size:15px;} This is, of course, only needed if you're not able to place CSS code inline to your content. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19517245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1960836/']} | jdg_382331 |
stackexchange | llm_judgeable_groundtruth_similarity | 13201334 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For all you "duplicate" fanatics, there is a similar question on SO right here . The difference is that I paint a vivid example that I can not understand the output of. The documentation for JspWriter and PrintWriter says there are two differences: 1. JspWriter can throw exceptions, PrintWriter should not do so. 2. JspWriter uses a PrintWriter behind the scene, but since by default JSP pages are buffered, the PrintWriter won't be created until the buffer is flushed - whatever that mean in the context of a JSP page. I'm not sure I've understood this last part. Consider this JSP page: <%@page import="java.io.PrintWriter"%><%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JspWriter versus PrintWriter</title> </head> <body> <p>I should be row one.</p> <% out.println("<p>JspWriter said: I should be the second row.</p>"); PrintWriter pw = response.getWriter(); pw.println("<p>PrintWriter said: I should be the third row.</p>"); %> <p>I should be the fourth row.</p> </body></html> It produces the following output: PrintWriter said: I should be the third row.I should be row one.JspWriter said: I should be the second row.I should be the fourth row. As you can see, the JspWriter outputs his string to the browser were I expected it to. But PrintWriter outputs his string before all else is sent to the browser. If we examine the source code sent to the browser, the PrintWriter's string is sent as the very first line, before the DOCTYPE declaration. So in the example above, exactly what happens?
Now provide the response and nothing else.
| The explanation is in your own question: JspWriter uses a PrintWriter behind the scene, but since by default JSP pages are buffered, the PrintWriter won't be created until the buffer is flushed This means that what is written to the JspWriter is buffered, and once this buffer is flushed (either because the buffer is full, or because the JSP has reached the end of its execution), the contents is written to the response's PrintWriter. So the flow of your example is the following one: static HTML code until the scriptlet: written to the in-memory buffer out.println(...): written to the in-memory buffer pw.println(...): written to the response static HTML code until the end of the JSP: written to the in-memory buffer flush of the in-memory buffer: all it contains is written to the response | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13201334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1268003/']} | jdg_382332 |
stackexchange | llm_judgeable_groundtruth_similarity | 42773318 |
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 polymorphic association ( belongs_to :resource, polymorphic: true ) where resource can be a variety of different models. To simplify the question assume it can be either a Order or a Customer . If it is a Order I'd like to preload the order, and preload the Address . If it is a customer I'd like to preload the Customer and preload the Location . The code using these associations does something like: <%- @issues.each do |issue| -%><%- case issue.resource -%><%- when Customer -%><%= issue.resource.name %> <%= issue.resource.location.name %><%- when Order -%><%= issue.resource.number %> <%= issue.resource.address.details %><%- end -%> Currently my preload uses: @issues.preload(:resource) However I still see n-plus-one issues for loading the conditional associations: SELECT "addresses".* WHERE "addresses"."order_id" = ...SELECT "locations".* WHERE "locations"."customer_id" = ...... What's a good way to fix this? Is it possible to manually preload an association?
Now provide the response and nothing else.
| You can do that with the help of ActiveRecord::Associations::Preloader class. Here is the code: @issues = Issue.all # Or whatever queryActiveRecord::Associations::Preloader.new.preload(@issues.select { |i| i.resource_type == "Order" }, { resource: :address })ActiveRecord::Associations::Preloader.new.preload(@issues.select { |i| i.resource_type == "Customer" }, { resource: :location }) You can use different approach when filtering the collection. For example, in my project I am using group_by groups = sale_items.group_by(&:item_type)groups.each do |type, items| conditions = case type when "Product" then :item when "Service" then { item: { service: [:group] } }endActiveRecord::Associations::Preloader.new.preload(items, conditions) You can easily wrap this code in some helper class and use it in different parts of your app. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42773318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/370858/']} | jdg_382333 |
stackexchange | llm_judgeable_groundtruth_similarity | 55878225 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
operable program or batch file.npm ERR! code ELIFECYCLEnpm ERR! errno 1npm ERR! [email protected] start: `electron .`npm ERR! Exit status 1npm ERR!npm ERR! Failed at the [email protected] start script.npm ERR! This is probably not a problem with npm. There is likely additional logging output above.npm ERR! A complete log of this run can be found in:
Now provide the response and nothing else.
| To add/remove items from the toolbar, you need the toolbar delegate: NSToolbarDelegate. Here is a template for the implementation I'm using (probably more than you want). Boilerplate code to create toolbar items of various types: struct ToolbarIdentifiers { static let mainToolbar = NSToolbar.Identifier(stringLiteral: "MainToolbar") static let navGroupItem = NSToolbarItem.Identifier(rawValue: "NavGroupToolbarItem") static let shareItem = NSToolbarItem.Identifier(rawValue: "ShareToolBarItem") static let addItem = NSToolbarItem.Identifier(rawValue: "AddToolbarItem") static let statusItem = NSToolbarItem.Identifier(rawValue: "StatusToolbarItem") static let filterItem = NSToolbarItem.Identifier(rawValue: "FilterToolbarItem") static let sortItem = NSToolbarItem.Identifier(rawValue: "SortToolbarItem") static let cloudUploadItem = NSToolbarItem.Identifier(rawValue: "UploadToolbarItem") static let cloudDownloadItem = NSToolbarItem.Identifier(rawValue: "DownloadToolbarItem") static let leftButtonItem = NSToolbarItem.Identifier(rawValue: "leftButtonToolbarItem") static let rightButtonItem = NSToolbarItem.Identifier(rawValue: "rightButtonToolbarItem") static let hideShowItem = NSToolbarItem.Identifier(rawValue: "hideShowToolbarItem")}// Base toolbar item type, extended for segmented controls, buttons, etc.struct ToolbarItem { let identifier: NSToolbarItem.Identifier let label: String let paletteLabel: String let tag: ToolbarTag let image: NSImage? let width: CGFloat let height: CGFloat let action: Selector? weak var target: AnyObject? var menuItem: NSMenuItem? = nil // Needs to be plugged in after App has launched. let group: [ToolbarItem] init(_ identifier: NSToolbarItem.Identifier, label: String = "", tag: ToolbarTag = .separator, image: NSImage? = nil, width: CGFloat = 38.0, height: CGFloat = 28.0, action: Selector? = nil, target: AnyObject? = nil, group: [ToolbarItem] = [], paletteLabel: String = "") { self.identifier = identifier self.label = label self.paletteLabel = paletteLabel self.tag = tag self.width = width self.height = height self.image = image self.action = action self.target = target self.group = group }}// Image button -- creates NSToolbarItemextension ToolbarItem { func imageButton() -> NSToolbarItem { let item = NSToolbarItem(itemIdentifier: identifier) item.label = label item.paletteLabel = label item.menuFormRepresentation = menuItem // Need this for text-only to work item.tag = tag.rawValue let button = NSButton(image: image!, target: target, action: action) button.widthAnchor.constraint(equalToConstant: width).isActive = true button.heightAnchor.constraint(equalToConstant: height).isActive = true button.title = "" button.imageScaling = .scaleProportionallyDown button.bezelStyle = .texturedRounded button.tag = tag.rawValue button.focusRingType = .none item.view = button return item }}// Segmented control -- creates NSToolbarItemGroup containing multiple instances of NSToolbarItemextension ToolbarItem { func segmentedControl() -> NSToolbarItemGroup { let itemGroup = NSToolbarItemGroup(itemIdentifier: identifier) let control = NSSegmentedControl(frame: NSRect(x: 0, y: 0, width: width, height: height)) control.segmentStyle = .texturedSquare control.trackingMode = .momentary control.segmentCount = group.count control.focusRingType = .none control.tag = tag.rawValue var items = [NSToolbarItem]() var iSeg = 0 for segment in group { let item = NSToolbarItem(itemIdentifier: segment.identifier) items.append(item) item.label = segment.label item.tag = segment.tag.rawValue item.action = action item.target = target control.action = segment.action // button & container send to separate handlers control.target = segment.target control.setImage(segment.image, forSegment: iSeg) control.setImageScaling(.scaleProportionallyDown, forSegment: iSeg) control.setWidth(segment.width, forSegment: iSeg) control.setTag(segment.tag.rawValue, forSegment: iSeg) iSeg += 1 } itemGroup.paletteLabel = paletteLabel itemGroup.subitems = items itemGroup.view = control return itemGroup }}// Text field -- creates NSToolbarItem containing NSTextFieldextension ToolbarItem { func textfieldItem() -> NSToolbarItem { let item = NSToolbarItem(itemIdentifier: identifier) item.label = "" item.paletteLabel = label item.tag = tag.rawValue let field = NSTextField(string: label) field.widthAnchor.constraint(equalToConstant: width).isActive = true field.heightAnchor.constraint(equalToConstant: height).isActive = true field.tag = tag.rawValue field.isSelectable = false item.view = field return item }}// Menu item -- creates an empty NSMenuItem so that user can click on the label// definitely a work-around till we implement the menusextension ToolbarItem { mutating func createMenuItem(_ action: Selector) { let item = NSMenuItem() item.action = action item.target = target item.title = label item.tag = tag.rawValue self.menuItem = item }}/* * Create specialized toolbar items with graphics, labels, actions, etc * Encapsulates implementation-specific details in code, because the table-driven version was hard to read. */struct InitializeToolbar {}extension InitializeToolbar { static func navGroupItem(_ action: Selector, segmentAction: Selector, target: AnyObject) -> ToolbarItem { var group = [ToolbarItem]() group.append(ToolbarItem(NSToolbarItem.Identifier(rawValue: "BackToolbarItem"), label: "Prev", tag: .navPrev, image: NSImage(named: NSImage.goBackTemplateName), action: segmentAction, target: target)) group.append(ToolbarItem(NSToolbarItem.Identifier(rawValue: "FwdToolbarItem"), label: "Next", tag: .navNext, image: NSImage(named: NSImage.goForwardTemplateName), action: segmentAction, target: target)) let item = ToolbarItem(ToolbarIdentifiers.navGroupItem, tag: .navGroup, width: 85, height: 28, action: action, target: target, group: group, paletteLabel: "Navigation") return item }}extension InitializeToolbar { static func hideShowItem(_ action: Selector, segmentAction: Selector, target: AnyObject) -> ToolbarItem { var group = [ToolbarItem]() group.append(ToolbarItem(NSToolbarItem.Identifier(rawValue: "HideLeftItem"), label: "", tag: .leftButton, image: NSImage(named: "leftButton"), action: segmentAction, target: target)) group.append(ToolbarItem(NSToolbarItem.Identifier(rawValue: "HideRightItem"), label: "", tag: .rightButton, image: NSImage(named: "rightButton"), action: segmentAction, target: target)) let item = ToolbarItem(ToolbarIdentifiers.hideShowItem, tag: .hideShow, width: 85, height: 28, action: action, target: target, group: group, paletteLabel: "Hide/Show") return item }}extension InitializeToolbar { static func addItem(_ action: Selector, target: AnyObject) -> ToolbarItem { let item = ToolbarItem(ToolbarIdentifiers.addItem, label: "Add", tag: .add, image: NSImage(named: NSImage.addTemplateName), action: action, target: target) return item }}extension InitializeToolbar { static func shareItem(_ action: Selector, target: AnyObject) -> ToolbarItem { let item = ToolbarItem(ToolbarIdentifiers.shareItem, label: "Share", tag: .share, image: NSImage(named: NSImage.shareTemplateName), action: action, target: target) return item }}extension InitializeToolbar { static func filterItem(_ action: Selector, target: AnyObject) -> ToolbarItem { let item = ToolbarItem(ToolbarIdentifiers.filterItem, label: "Filter", tag: .filter, image: NSImage(named: "filter"), action: action, target: target) return item }}extension InitializeToolbar { static func sortItem(_ action: Selector, target: AnyObject) -> ToolbarItem { let item = ToolbarItem(ToolbarIdentifiers.sortItem, label: "Sort", tag: .sort, image: NSImage(named: "sort"), action: action, target: target) return item }}extension InitializeToolbar { static func cloudDownloadItem(_ action: Selector, target: AnyObject) -> ToolbarItem { let item = ToolbarItem(ToolbarIdentifiers.cloudDownloadItem, label: "Down", tag: .cloudDownload, image: NSImage(named: "cloudDownload"), action: action, target: target) return item }}extension InitializeToolbar { static func cloudUploadItem(_ action: Selector, target: AnyObject) -> ToolbarItem { let item = ToolbarItem(ToolbarIdentifiers.cloudUploadItem, label: "Up", tag: .cloudUpload, image: NSImage(named: "cloudUpload"), action: action, target: target) return item }}extension InitializeToolbar { static func leftButtonItem(_ action: Selector, target: AnyObject) -> ToolbarItem { let item = ToolbarItem(ToolbarIdentifiers.leftButtonItem, label: "", tag: .leftButton, image: NSImage(named: "leftButton"), action: action, target: target) return item }}extension InitializeToolbar { static func rightButtonItem(_ action: Selector, target: AnyObject) -> ToolbarItem { let item = ToolbarItem(ToolbarIdentifiers.rightButtonItem, label: "", tag: .rightButton, image: NSImage(named: "rightButton"), action: action, target: target) return item }}extension InitializeToolbar { static func textItem() -> ToolbarItem { return ToolbarItem(ToolbarIdentifiers.statusItem, label: "Watch This Space", tag: .status, width: 300, height: 24) }} Here is the toolbar class, which implements the initializer and delegate: /* * Initializer builds a specialized toolbar. */enum ToolbarTag: Int { case separator = 1 case navGroup case navPrev case navNext case add case share case filter case sort case cloudDownload case cloudUpload case leftButton case rightButton case hideShow case status}class Toolbar: NSObject, NSToolbarDelegate, Actor { var actorDelegate: ActorDelegate? var identifier: NSUserInterfaceItemIdentifier? var toolbarItemList = [ToolbarItem]() var toolbarItemIdentifiers: [NSToolbarItem.Identifier] { return toolbarItemList.map({ $0.identifier }) } var toolbarDefaultItemList = [ToolbarItem]() var toolbarDefaultItemIdentifiers: [NSToolbarItem.Identifier] { return toolbarDefaultItemList.map({ $0.identifier }) } // Delegate toolbar actions @objc func controlSentAction(_ sender: Any) { guard let control = sender as? NSControl else { return } guard let tag = ToolbarTag(rawValue: control.tag) else { return } actorDelegate?.actor(self, initiator: control, tag: tag, obj: nil) } @objc func segmentedControlSentAction(_ sender: Any) { guard let segmented = sender as? NSSegmentedControl else { return } guard let tag = ToolbarTag(rawValue: segmented.tag(forSegment: segmented.selectedSegment)) else { return } actorDelegate?.actor(self, initiator: segmented, tag: tag, obj: nil) } // These don't get called at the moment @objc func toolbarItemSentAction(_ sender: Any) { ddt("toolbarItemSentAction") } @objc func menuSentAction(_ sender: Any) { ddt("menuSentAction") } // Toolbar initialize init(_ window: Window) { super.init() identifier = Identifier.View.toolbar let toolbar = NSToolbar(identifier: ToolbarIdentifiers.mainToolbar) toolbar.centeredItemIdentifier = ToolbarIdentifiers.statusItem // Build the initial toolbar // Text field toolbarItemList.append(ToolbarItem(.flexibleSpace)) toolbarItemList.append(InitializeToolbar.textItem()) toolbarItemList.append(ToolbarItem(.flexibleSpace)) // Show/Hide toolbarItemList.append(InitializeToolbar.hideShowItem(#selector(toolbarItemSentAction), segmentAction: #selector(segmentedControlSentAction), target: self)) // Save initial toolbar as default toolbarDefaultItemList = toolbarItemList // Also allow these, just to demo adding toolbarItemList.append(InitializeToolbar.cloudDownloadItem(#selector(controlSentAction), target: self)) toolbarItemList.append(InitializeToolbar.sortItem(#selector(controlSentAction), target: self)) toolbar.allowsUserCustomization = true toolbar.displayMode = .default toolbar.delegate = self window.toolbar = toolbar } deinit { ddt("deinit", caller: self) }}/* * Implement NSToolbarDelegate */extension Toolbar { // Build toolbar func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? { guard let item = toolbarItemList.firstIndex(where: { $0.identifier == itemIdentifier }) else { return nil } switch toolbarItemList[item].identifier { case ToolbarIdentifiers.navGroupItem, ToolbarIdentifiers.hideShowItem: return toolbarItemList[item].segmentedControl() case ToolbarIdentifiers.addItem, ToolbarIdentifiers.shareItem, ToolbarIdentifiers.sortItem, ToolbarIdentifiers.filterItem, ToolbarIdentifiers.cloudUploadItem, ToolbarIdentifiers.cloudDownloadItem, ToolbarIdentifiers.leftButtonItem, ToolbarIdentifiers.rightButtonItem: return toolbarItemList[item].imageButton() case ToolbarIdentifiers.statusItem: return toolbarItemList[item].textfieldItem() default: return nil } } // end of toolbar func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return toolbarDefaultItemIdentifiers; } func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return toolbarItemIdentifiers } func toolbarSelectableItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { return [] } func toolbarWillAddItem(_ notification: Notification) { } func toolbarDidRemoveItem(_ notification: Notification) { }} // End of extension Initial Toolbar: Customization drop-down, which Cocoa does for you: After adding cloud button: Hope this is helpful. Added to clarify 4/28/2019: My Toolbar class is not an NSToolbar subclass. Its initializer gets passed a reference to the window, so that at the end it sets the window's toolbar to the toolbar it creates: init(_ window: Window) { super.init() identifier = Identifier.View.toolbar**** stuff removed for clarity **** let toolbar = NSToolbar(identifier: ToolbarIdentifiers.mainToolbar) toolbar.allowsUserCustomization = true toolbar.displayMode = .default toolbar.delegate = self window.toolbar = toolbar } Perhaps this is confusing semantics, but it creates the toolbar and acts as the toolbar delegate, as you can see in the extension. The "Actor" protocol is part of my coordination framework, not important to constructing the toolbar itself. I would have had to include the entire demo app to show that, and I assume that you have your own design for passing toolbar actions to your controllers/models. This app is Xcode 10.2/Swift 5, although I don't think it uses any new Swift 5 features. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55878225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8539104/']} | jdg_382334 |
stackexchange | llm_judgeable_groundtruth_similarity | 2506773 |
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$ be a non-zero real number such that $x + \frac{1}{x}$ is an integer. Prove that $\forall n\in \mathbb{N}$ the number $x + \frac{1}{x}$ is also an integer. Attempt at solution using induction: base case: $n = 1$ then $x^n + \frac{1}{x^n} = x + \frac{1}{x}$ which is an integer Inductive assumption: Assume that for some $k\in \mathbb{N} : x^k + \frac{1}{x^k}$ We have to show that $ x^{k+1} + \frac{1}{x^{k+1}}$ is an integer. $$ x^{k+1} + \frac{1}{x^{k+1}} = x^k\cdot x + \frac{1}{x^k\cdot x} = \frac{(x^k\cdot x)\cdot (x^k\cdot x)+1}{x^k\cdot x}$$ I can't find a way to seperate $x$ and $\frac{1}{x}$ from the term so I can use the inductive assumption. Edit: I don't think that this question should count as a duplicate since the linked question is asking to specifically solve another problem and one of the answers of that question utilize the proof from this question in their answer but that question itself is different and not related to this question since that question can be solved without using this proof as other answers of that question don't include it.
Now provide the response and nothing else.
| $$x^{k+1} + \dfrac 1 {x^{k+1}} = \left( x^k + \dfrac 1 {x^k} \right) \left( x + \dfrac 1 x \right) - \left( x^{k-1} + \dfrac 1 {x^{k-1}} \right)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2506773', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/416818/']} | jdg_382335 |
stackexchange | llm_judgeable_groundtruth_similarity | 1898325 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We started using VS 2010 and were very happy with it, so we converted our project into a 2010 solution (still .net 3.5) and continued our development in 2010. However, we are getting a lot of bugs recently and want to go back to 2008. The solution files have changed (new projects and files added everywhere), but everything is still in .net 3.5. I was wondering if there is an easy way to migrate back to 2008.
Now provide the response and nothing else.
| Depending on if they kept the solution file structure similar between 2008 and 2010, you just need to create an empty solution file in 2008 and look at the top identifier line in it, and copy it into the other solution file. I however doubt they kept it the same since they were integrating a number of features into solution files. You would be better off to create a new blank solution in 2008 and use "Add existing project" to reimport them. As long as you dont have any custom "solution" wide references this will work (no solution folders, server setups, etc). It is probably the fastest and most direct route. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1898325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24351/']} | jdg_382336 |
stackexchange | llm_judgeable_groundtruth_similarity | 45154180 |
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 train a GAN in Keras. My final target is BEGAN, but I'm starting with the simplest one. Understanding how to freeze weights properly is necessary here and that's what I'm struggling with. During the generator training time the discriminator weights might not be updated. I would like to freeze and unfreeze discriminator alternately for training generator and discriminator alternately. The problem is that setting trainable parameter to false on discriminator model or even on its' weights doesn't stop model to train (and weights to update). On the other hand when I compile the model after setting trainable to False the weights become unfreezable . I can't compile the model after each iteration because that negates the idea of whole training. Because of that problem it seems that many Keras implementations are bugged or they work because of some non-intuitive trick in old version or something.
Now provide the response and nothing else.
| I've tried this example code a couple months ago and it worked: https://github.com/fchollet/keras/blob/master/examples/mnist_acgan.py It's not the simplest form of GAN, but as far as I remembered, it's not too difficult to remove the classification loss and turn the model into a GAN. You don't need to turn on/off the discriminator's trainable property and recompile. Simply create and compile two model objects, one with trainable=True ( discriminator in the code) and another one with trainable=False ( combined in the code). When you're updating the discriminator, call discriminator.train_on_batch() . When you're updating the generator, call combined.train_on_batch() . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45154180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6183527/']} | jdg_382337 |
stackexchange | llm_judgeable_groundtruth_similarity | 4531941 |
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 piece of code: for element in json[referenceElement].keys(): When I run that code, I get this error: TypeError: unhashable type: 'dict' What is the cause of that error and what can I do to fix it?
Now provide the response and nothing else.
| From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!). >>> d1, d2 = {}, {}>>> d1[d2] = 1Traceback (most recent call last): File "<input>", line 1, in <module>TypeError: unhashable type: 'dict' You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys() . With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4531941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/490774/']} | jdg_382338 |
stackexchange | llm_judgeable_groundtruth_similarity | 24948082 |
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 using the wahoo fitness API and it defines the following objective-C enum: typedef enum{ /** No active connection. */ WF_SENSOR_CONNECTION_STATUS_IDLE, /** The connection is in process of being established. */ WF_SENSOR_CONNECTION_STATUS_CONNECTING, /** The sensor connection is established and active. */ WF_SENSOR_CONNECTION_STATUS_CONNECTED, /** The connection was interrupted (usually occurs when fisica is disconnected). */ WF_SENSOR_CONNECTION_STATUS_INTERRUPTED, /** The connection is in process of being disconnected. */ WF_SENSOR_CONNECTION_STATUS_DISCONNECTING,} WFSensorConnectionStatus_t; I can't find a way to use it in swift. I first tried to do a switch/case on it without success. I am at a point I just want to carry on and tried the following: var connState : WFSensorConnectionStatus_t = WF_SENSOR_CONNECTION_STATUS_IDLE...if( connState == WF_SENSOR_CONNECTION_STATUS_IDLE){ But it does not compile: 'WFSensorConnectionStatus_t' is not convertible to 'NSObject' Any workaround? I read to use WFSensorConnectionStatus_t.WF_SENSOR_CONNECTION_STATUS_IDLE or WF_SENSOR_CONNECTION_STATUS_IDLE.value but it does not work in xcode beta-4.
Now provide the response and nothing else.
| The workaround to use .value to get the underlying integer doesn't work anymore as of Beta 4, as you said. Unfortunately an enum is not transferrable to Swift from Objective-C, it needs to be an NS_ENUM . I have the same setup as you in a project where I need the enum from an Objective-C framework and use it in Swift. The workaround I did was to create an Objective-C category that contains an NS_ENUM and there I transfer the values from the framework enum to my own NS_ENUM . Import the category in your bridging header and you should be able to use the enum as you normally would do. Something like this: typedef NS_ENUM(NSUInteger, ConnectionStatus) { ConnectionStatusIdle}- (ConnectionStatus)connectionStatus { if [self getConnectionStatus] == WF_SENSOR_CONNECTION_STATUS_IDLE { return ConnectionStatusIdle }} Then you should be able to use it like this: switch myObject.connectionStatus() { case .Idle: // do something break} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24948082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/291108/']} | jdg_382339 |
stackexchange | llm_judgeable_groundtruth_similarity | 569270 |
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 am writing a shell script to download the latest version of some software. After I parse the output of curl I go through several steps to find the exact version string (at the moment of writing this is 0.65.3 ): (In all code samples below, > is my prompt. Output from Bash 3.2 or Zsh is on a line without a > prefix.) > url="https://github.com/gohugoio/hugo/releases/latest"> latest=$(curl --silent --head "$url" | grep Location)> tag=$(echo "$latest" | cut -d'/' -f8)> version=$(echo "${tag//v}")> echo "hugo_${version}_Linux-64bit.tar.gz"_Linux-64bit.tar.gz The output I expected was hugo_0.65.3_Linux-64bit.tar.gz , but in the output of the call to echo with the quoted string it seems the bytes following ${version} have been used to overwrite the bytes at the beginning of the quoted string. Here I use two different quoted strings to clarify what is happening: > echo "hugo_${version}test"test_0.65.3> echo "hugo_${version}lorem ipsum dolor sit amet"lorem ipsum dolor sit amet I get the same unexpected result if I do this: > version=$(echo "${tag:1}")> echo "hugo_${version}_Linux-64bit.tar.gz"_Linux-64bit.tar.gz But, I get the expected result if I do this: > version=0.65.3hugo_0.65.3_Linux-64bit.tar.gz This last result is what is required, but of course it makes my script static rather than dynamic, and thus not very useful to me. How can I get the desired result without hard-coding the value of $version in my script?
Now provide the response and nothing else.
| The line returned by curl ends with carriage-return line-feed. (MS-dos line ending). The line-feed is removed by the Unix tools, however this leaves a carriage-return at the end. Fix this line to use dos2unix (and quote your argument to echo , avoiding the bugs described in BashPitfalls #14 ): version="$(echo "${tag//v}" | dos2unix)" ...or, using the shell's built-in syntax to enact both changes at once: version=${tag//[$'v\r']/} dos2unix does make some other changes (like adding a trailing newline after the last line of text, which UNIX requires but DOS does not), but none of them matter for a single-line string like this. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/569270', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/366680/']} | jdg_382340 |
Subsets and Splits