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
5426908
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 got a ndarray of floating point values in numpy and I want to find the unique values of this array. Of course, this has problems because of floating point accuracy...so I want to be able to set a delta value to use for the comparisons when working out which elements are unique. Is there a way to do this? At the moment I am simply doing: unique(array) Which gives me something like: array([ -Inf, 0.62962963, 0.62962963, 0.62962963, 0.62962963, 0.62962963]) where the values that look the same (to the number of decimal places being displayed) are obviously slightly different. Now provide the response and nothing else.
Another possibility is to just round to the nearest desirable tolerance: np.unique(a.round(decimals=4)) where a is your original array. Edit: Just to note that my solution and @unutbu's are nearly identical speed-wise (mine is maybe 5% faster) according to my timings, so either is a good solution. Edit #2: This is meant to address Paul's concern. It is definitely slower and there may be some optimizations one can make, but I'm posting it as-is to demonstrate the stratgey: def eclose(a,b,rtol=1.0000000000000001e-05, atol=1e-08): return np.abs(a - b) <= (atol + rtol * np.abs(b))x = np.array([6.4,6.500000001, 6.5,6.51])y = x.flat.copy()y.sort()ci = 0U = np.empty((0,),dtype=y.dtype)while ci < y.size: ii = eclose(y[ci],y) mi = np.max(ii.nonzero()) U = np.concatenate((U,[y[mi]])) ci = mi + 1print U This should be decently fast if there are many repeated values within the precision range, but if many of the values are unique, then this is going to be slow. Also, it may be better to set U up as a list and append through the while loop, but that falls under 'further optimization'.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5426908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1912/']}
jdg_375341
stackexchange
llm_judgeable_groundtruth_similarity
3917288
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 struggling with this which apparently is a very simple effect but incredibly haven't found any intutitive way for doing it in Android. I have a ListView and I managed to customize the background images so the selected item gets highlighted by getting a new background drawable. This I do creating a new style where I set the android:listSelector attribute to point a StateListDrawable where I have specified which drawables to use for every state. However each ListView item is a LinearLayout where i have two TextViews. My goal is to be able to change the text color of these child views whenever the parent is selected or pressed, at the same time as the background drawable does. I know there is a ColorStateList but haven't been succesful setting that up. Has anybody succeed getting something like this to work? Thanks. Now provide the response and nothing else.
Neither of these are possible answers when your ListView is compromised of a layout that has multiple views. You need to set your child views to: android:duplicateParentState="true" Now you can use the methods others have described above to declare your TextViews' colors using a selector such as: android:textColor="@drawable/my_row_selector" and I'm sure you're aware, but the selector can be as simple as: <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:color="@color/white" /> <item android:color="@color/black" /></selector> As you can see, @color values are allowed. Hope this helps. Also - android:state_pressed is used in conjunction with the AdapterView.OnItemClickListener.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3917288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/473619/']}
jdg_375342
stackexchange
llm_judgeable_groundtruth_similarity
625
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a relationship between the Turing Machine and the Lambda calculus - or did they just happen to arise about the same time? Now provide the response and nothing else.
The lambda calculus is older than Turing's machine model, apparently dating from the period 1928-1929 (Seldin 2006), and was invented to encapsulate the notion of a schematic function that Church needed for a foundational logic he devised. It was not invented to capture the general notion of computable function, and indeed a weaker typed version would have served his purposes better. It seems to be incidental to the purpose of that the calculus Church invented turned out to be Turing complete, although later Church used the lambda calculus as his foundation for what he called the effectively computable functions (1936), which Turing appealed to in his paper. Church's simple theory of types (1940) provides a more moderate, typed theory of functions that suffices to express the syntax of higher-order logic but does not express all recursive functions. This theory can be seen as being more in tune with Church's original motivation. References Church (1936). An unsolvable problem in elementary number theory. American Journal of Mathematics 58:345—363. Church (1940). A formulation of the simple theory of types . Journal of Symbolic Logic 5(2):56—68. Seldin (2006). The logic of Curry and Church . In Handbook of the History of Logic, vol.5: Logic from Russell to Church , p. 819—874. North-Holland: Amsterdam. Note This answer is substantially revised due to objections by Kaveh and Sasho. I recommend the Wikipedia timeline that Kaveh suggested, History of the Church–Turing thesis , which has some choice quotes from seminal articles.
{}
{'log_upvote_score': 6, 'links': ['https://cstheory.stackexchange.com/questions/625', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/608/']}
jdg_375343
stackexchange
llm_judgeable_groundtruth_similarity
111263
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm configuring a Cisco 3640 and it's not saving simple things like my hostname. I've tried with 'wr' and 'copy running-config startup-config'. Also erased the configuration but no luck. There's no error whatsoever when running the above commands. Is my flash bad?Anyway I can debug this more thoroughly? Thanks! Now provide the response and nothing else.
It sounds like you have a configuration register at the wrong setting. For instance, setting: confreg 0x2142 at an rommon will boot the router to a fresh/default mode. Trying entering config-register 0x2102 from an enable prompt to got back to booting from your configuration
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/111263', 'https://serverfault.com', 'https://serverfault.com/users/34329/']}
jdg_375344
stackexchange
llm_judgeable_groundtruth_similarity
6583352
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 wud u get the next row in the following example? (i am trying to print the next three row/column values of the rowId provided) function printRowData(rowId){ var row=document.getElementById(rowId); for(i=0; i<3 ; i++) { var column=row.getElementsByTagName("td"); alert(column[0].innerText); //now i want to move to the next row...something like row=row.next()????? }} Now provide the response and nothing else.
If you just want the next row, and not subsequent rows, you can do this: var next = row.parentNode.rows[ row.rowIndex + 1 ]; So your code could look like this: function printRowData(rowId) { var row=document.getElementById(rowId); var idx = row.rowIndex; for(i=0; i<4 ; i++) { if( row ) { alert(row.cells[0].innerText); var row = row.parentNode.rows[ ++idx ]; } }} From the current row, it gets the .parentNode , then from that, it accesses the rows collection, and increments the .rowIndex property of the original row to select the next. This takes care of white space issues. Notice also that instead of getElementsByTagName , I replaced it with row.cells , which is a collection of the cells in the row. EDIT: Forgot to include the rows property after parentNode . It was included in the description though. Fixed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6583352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/808536/']}
jdg_375345
stackexchange
llm_judgeable_groundtruth_similarity
2370434
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This problem is not readily reproducible in a simple example here but was wondering if anyone has any experience and tips, here is the issue: using Entity Framework have many points in application where (1) data is written to some entity table e.g. Customer, (2) data is written to history table both of these actions use Entity Framework, HOWEVER, they use different contexts these actions need to be both in one transaction : i.e. if one fails to write, the other should not write, etc. I can wrap them with a TransactionScope, like this: using (TransactionScope txScope = new TransactionScope()) { ...} but this gives me: Microsoft Distributed Transaction Coordinator (MSDTC) is disabled for network transactions. Our database admin has told me that MSDTC is disabled by choice and can not be installed . Hence I am making changes trying to create my own EntityConnection with a MetadataWorkspace with the idea that each context will use the same EntityConnection . However, this is proving near impossible trying to get it to work, e.g. currently I continue to get the above error even though theoretically both contexts are using EntityConnection. It's difficult to understand where/why Entity Framework is requiring the MSDTC for example. Has anyone gone down this road before, have experience or code examples to share? Now provide the response and nothing else.
Well, the problem is quite easy. If you are using sql server 2008 you should not have that problem because you have promotable transaction, and as .NET knows that you are using the same persistence store (the database) it wont promote it to DTC and commit it as local. look into promotable transaction with sql server 2008. As far as I know Oracle is working in its driver to support promotable transactions, but I do not know the state, MS oracle driver does not support it. http://www.oracle.com/technology/tech/windows/odpnet/col/odp.net_11.1.0.7.20_twp.pdf If you are using a driver that do not support promotable transactions it is impossible for .NET to use local transaction doing two connections. You should change your architecture or convince the database admin for installing MSDTC.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2370434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4639/']}
jdg_375346
stackexchange
llm_judgeable_groundtruth_similarity
37306672
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just installed Visual Studio Code 1.1.1 on a Windows 7 machine. When I right-click on a folder, "Open With Code" does not appear. Now provide the response and nothing else.
Copied from Right click on Windows folder and open with Visual Studio Code Create file vsCodeOpenFolder.reg with this content (If you didn't choose the default installation path then you need to adjust the paths in this file): Windows Registry Editor Version 5.00 ; Open files [HKEY_CLASSES_ROOT\*\shell\Open with VS Code] @="Edit with VS Code" "Icon"="C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe,0" [HKEY_CLASSES_ROOT\*\shell\Open with VS Code\command] @="\"C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe\" \"%1\"" ; This will make it appear when you right click ON a folder ; The "Icon" line can be removed if you don't want the icon to appear [HKEY_CLASSES_ROOT\Directory\shell\vscode] @="Open Folder as VS Code Project" "Icon"="\"C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe\",0" [HKEY_CLASSES_ROOT\Directory\shell\vscode\command] @="\"C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe\" \"%1\"" ; This will make it appear when you right click INSIDE a folder ; The "Icon" line can be removed if you don't want the icon to appear [HKEY_CLASSES_ROOT\Directory\Background\shell\vscode] @="Open Folder as VS Code Project" "Icon"="\"C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe\",0" [HKEY_CLASSES_ROOT\Directory\Background\shell\vscode\command] @="\"C:\\Program Files (x86)\\Microsoft VS Code\\Code.exe\" \"%V\"" Double click it to create the registry entries. If the "Open with Code" doesn't appear in the Explorer's context menu then you should restart your system. If you're running the 64-bit or Insiders version of VS Code, change the path accordingly. ie. C:\\Users\\[user_name]\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37306672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1864541/']}
jdg_375347
stackexchange
llm_judgeable_groundtruth_similarity
37225031
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 service which must return person by some properties. And I see two strategies for naming these methods: The first one: getPersonById(int id)getPersonByBirthDate(Date date)getPersonByBirthDateAndSex(Date date,Sex sex)getPersonByNameAndSex(String name,Sex sex)getPersonByBirthDateAndNameAndSex(Date date,String name,Sex sex)etc.. or applying overloading rules do the following: getPerson(int id)getPerson(Date date)getPerson(Date date,Sex sex)getPerson(String name,Sex sex)getPerson(Date date,String name,Sex sex) Which is right according to java naming convention? Now provide the response and nothing else.
Independent of the overloading question your design suffers from combinatorial API explosion: You start to introduce methods for all possible combinations of search criterions. An alternative would be to introduce a builder which collects criterions and in the end returns the person. Example: queryPerson().byId(5).run(); queryPerson().byName("John").bySex(Sex.MALE).run(); queryPerson().bySex(Sex.FEMALE).run(); And the service API now only has a nice queryPerson() method.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37225031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5057736/']}
jdg_375348
stackexchange
llm_judgeable_groundtruth_similarity
7455982
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 application where huge number of threads are expected to iterate over set of string values and try to match it's own data with the data available in the list. I am looking for following use case: Vector is initialized with few elements of type std::string. (Lets say object name is strList). strList will get initialized at the time of application startup. All threads will iterate over strList to see if it's value matches with atleast one element of strList. No thread will ever try to modify strList and it will be strictly used as readonly object. So could you please tell me if concurrent reads are thread-safe on vector object. I am using RHEL 6 and gcc version is 4.5.x Now provide the response and nothing else.
YES for the scenario you mention, it is perfectly Thread Safe. Actually, STL is not a correct way of referring it. It is the C++ Standard Library . The C++03 Standard does not talk about concurrency at all, So the concurrency aspect is left out as an implementation detail for compilers. So the documentation that comes with your compiler is where one should look to for answers related to concurrency. Most of the STL implementations are not thread safe as such. But for concurrent reads of same object from multiple threads most implementations of STL are indeed thread safe. References: MSDN says: A single object is thread safe for reading from multiple threads. For example, given an object A, it is safe to read A from thread 1 and from thread 2 simultaneously. The Dinkumware STL-Documentation says: Multiple threads can safely read the same container object. (There are nunprotected mutable subobjects within a container object.) GCC Documentation says: We currently use the SGI STL definition of thread safety, which states: The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses. So from the above, Yes it is thread safe in GCC to have concurrent reads of same object from multiple threads. Note: GCC's Standard Library is a derivative of SGI's STL code.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7455982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/512656/']}
jdg_375349
stackexchange
llm_judgeable_groundtruth_similarity
334887
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 now studying algebraic topology (still at the beginning). I am now studying identification spaces, adjunction spaces,... As I still don't know how these concepts are going to be used, I think I am getting a bit less interested. I would like you to present to me interesting theorems about identification maps or theorems (not necessarily about identification maps) which are easier to understand, prove using the concept of identification maps. I think good examples of these would keep me motivated. I am not looking for basic facts such as the composition of two identification maps is an identification map or other easy facts. I realize that this question might be ambiguous, thus I don't mind deleting it if I don't get a response Now provide the response and nothing else.
A common source of (particularly nice) identification spaces comes from group actions on topological spaces. Given any set $X$ and a group $G$, a group action of $G$ on $X$ is a function from $G\times X\rightarrow X$, denoted by $(g,x) \mapsto g\cdot x$ which is required to satisfy two axioms: $e\cdot x = x$ where $e\in G$ is the identity element and $x\in X$ is anything. $(gh)\cdot x = g\cdot(h\cdot x)$ In the case where $X$ is a topological space, we further require that for every $g\in G$, the function $\phi_g:X\rightarrow X$ given by $\phi_g(x) = g\cdot x$ be a homeomorphism. Now, we can define an equivalence relation on $X$ by the following: $$x\sim y \iff g\cdot x = y \text{ for some } g\in G.$$ Bullet point 1 tells us that $\sim$ is reflexive. Using $g^{-1}$ shows that $\sim$ is symmetric, and bullet point 2 tells us that $\sim$ is transitive. All that together just means that $\sim$ really is an equivalence relation. One can then consider the identification set $X/\sim$. It turns out, if $X$ is a topological space, the condition that all of the $\phi_g$ functions are homeomorphism is exactly what we need in order to put a topology on $X/\sim$ in such a way that the natural projection $\pi:X\rightarrow X/\sim$ is continuous. What are some examples of this? For starters, every example (except for the sphere) in Thomas Andrews's first paragraph is of this form for an action of $G = \mathbb{Z}$ or $\mathbb{Z}^2$ on $X=\mathbb{R}^2$. His second paragraph is also of this form for $G = \mathbb{Z}$ and $X=\mathbb{R}$. But there are many more examples. If you've seen covering spaces, the fundamental group of a space acts on its universal covering, giving back the space as the quotient. An example of this: $G=\mathbb{Z}/2\mathbb{Z}$ acts on the sphere $S^n$ and the quotient is $\mathbb{R}P^n$. Relatedly, $G = S^1$ (thought of as the group of unit complex numbers) acts on $S^{2n+1}$ with quotient $\mathbb{C}P^n$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/334887', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29267/']}
jdg_375350
stackexchange
llm_judgeable_groundtruth_similarity
20090235
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On page 34 of the book "Linux System Programming" the following example of correctly handling partial reads with a while loop for blocking reads is given ssize_t ret;while (len != 0 && (ret = read(fd, buf, len)) != 0) { if (ret == -1) { if (errno == EINTR) continue; perror("read"); break; } len -= ret; buf += ret;} On the next page it gives the following example for nonblocking reads. Does this example need to be wrapped in a while loop to handle the possibility of partial reads? char buf[BUFSIZ];ssize_t nr;start:nr = read(fd, buf, BUFSIZ);if (nr == -1) { if (errno == EINTR) goto start; /* oh shush */ if (erron == EAGAIN) /* resubmit later */ else /* error */} Now provide the response and nothing else.
When you do TableQuery[T] you are in fact calling TableQuery.apply , which is actually a macro . The body of this macro tries to instantiate T , but in your case T has become an (unknown) type parameter that the compiler does not know how to instantiate. The problem is similar to trying to compile this: def instantiate[T]: T = new T// Does not compile ("class type required but T found") The net effect is that TableQuery.apply can only be used on concrete types. You could work around that using a type class to capture the call to TableQuery.apply (at the point where the concrete type is known) along with an implicit macro to provide an instance of this type class. Then you would have something like: abstract class TableUtils[T <: Table[A] : TableQueryBuilder, A] { val tableQuery = BuildTableQuery[T]} Where TableQueryBuilder is the type class and BuildTableQuery is an alternate version of TableQuery.apply that will forward to the TableQueryBuilder instance to perform the actual instantiation. I've added an implementation as part of another answer here . It will be much easier (if less convenient) to just declare tableQuery as an abstract value and define it in every concrete derived class of TableUtils : abstract class TableUtils[T <: Table[A] , A] { val tableQuery: TableQuery[T, T#TableElementType] // define here your helper methods operating on `tableQuery`}object Coolers extends TableUtils[Coolers, Cooler] { val tableQuery = TableQuery[Coolers]}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20090235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/782220/']}
jdg_375351
stackexchange
llm_judgeable_groundtruth_similarity
45107505
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 table which contains data like the following: Item Date Customer------------------------------apple 01/01/2017 aapple 01/01/2017 aapple 02/01/2017 bapple 05/01/2017 capple 06/01/2017 bapple 06/01/2017 dapple 07/01/2017 capple 09/01/2017 abanana 01/01/2017 bbanana 02/01/2017 a What I need is a summary grouped by day and item of how many UNIQUE customers bought that item in the WEEK of that day (i.e. day +- 3 days), as well as on the day itself. It should look like this: Item Date Weekly Customers Daily Customers----------------------------------------------------------- apple 01/01/2017 2 1 apple 02/01/2017 3 1 apple 05/01/2017 3 1 apple 06/01/2017 4 2 apple 07/01/2017 4 1 apple 09/01/2017 4 1 banana 01/01/2017 2 1 banana 02/01/2017 2 1 I've managed to summarise by item, day, unique Daily Customers with the following which I think is correct: SELECT item as 'Item', boughtDate as 'Date', COUNT(DISTINCT(customer)) as 'Daily Customers'FROM tbl1 GROUP BY Item, Date I'm really stumped with how to take each distinct item + day combo and get the total unique customers for the week that day is in (3 days either side of that day) and join it with these results. I've been playing with some loops and CTEs but I seem to have problems with none of the values being unique in any given field. I am sure there is a simple way of doing this that I am just not thinking of? Now provide the response and nothing else.
This will happen if the given good and bad revision are not direct descendants of each other. Let's assume a repository like this (using exemplary names for the commits): * dffa2 good-commit* b38f4 a2* cc19f a1| * d1f17 bad-commit| * fbd1f b2| * f66cc b1|/* 09f66 merge-base-commit What "merge base" means As the message uses the term "merge base", it might be helpful to understand that term to understand the message. A "merge base" of two or more commits is the latest commit which is a parent of all of those commits. Therefore if those commits would be merged, all changes between the "merge base" and those commits will be merged together. Every commit which is a parent of "merge base" is not relevant to the merge, it already is a parent of all involved commits. Understanding the bisect The described message will happen in a case like this: $ git bisect start$ git bisect good good-commit$ git bisect bad bad-commitBisecting: a merge base must be tested[09f66] merge-base-commit What bisecting does is to find the commit which introduced a problem (leading to a bad state), which in this case could lead to a problem: Bug was not introduced between good-commit and bad-commit Assume that the error existed in merge-base-commit. In this case it will not be possible to find the commit that introduced the bug in the difference between good-commit and bad-commit. Instead one of the commits a1 , a2 and good-commit solves the problem, which is exactly what will happen if you decide the merge base to be bad: $ git bisect badThe merge base merge-base-commit is bad.This means the bug has been fixed between 09f66 and [dffa2]. Problem was introduced between merge-base-commit and bad-commit On the other hand if the merge base is good, the problem was introduced in b1 , b2 or bad-commit . bisect will then continue between merge-base-commit and bad-commit , picking the commit in the middle between those commits and testing if that one is good: $ git bisect goodBisecting: 0 revisions left to test after this (roughly 1 step)[fbd1f] b2
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45107505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8308777/']}
jdg_375352
stackexchange
llm_judgeable_groundtruth_similarity
12203380
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 implementing a filter in Haskell, i.e. a program that I can call from the command-line as follows: $ cat inputfile.txt | myFilter > outputfile.txt When running the program on a file of about 80 MB, I get a stack overflow(Stack space overflow: current size 8388608 bytes.). I am using GHC Version 6.12.3 under cygwin. I think the problem comes from the sort function that I am using in the program, but after I have been looking for the problem for three days I have no clue how to solve this so I would like if someone could give me a hint. Here are the essential details about my program. My filter program reads standard input into a string, splits it into lines and parses each line into a record of some type Event data Event = ... which is an instance of Ord instance Ord Event where x < y = ... so that I can sort events using the built-in sort function. Splitting into lines and parsing the events (one event per line) is performed by a function p :: String -> [Event] which internally uses the standard function lines . I also have a function g that groups events: g :: [Event] -> [[Event]] g uses some criteria that are not relevant here; each group can contain at most 4 events. I sort each group of events (represented as a list) using sort (i.e., all events inside each group get sorted), and finally format the all event groups as a string using a function f :: [[Event]] -> String The main function looks as follows: main = interact (f . (map sort) . g . p) As said, running this program on a file of about 80 MB gives a stack overflow. If I replace the sort function with the following function (a naive quick sort implementation): mySort :: [Event] -> [Event]mySort [] = []mySort (e:es) = let h = [j | j <- es, j < e] t = [j | j <- es, e < j] in (mySort h) ++ [e] ++ (mySort t)main = interact (f . (map mySort) . g . p) I have no stack overflow! If in the function mySort I replace the definition of t with the following: t = [j | j <- es, e <= j] i.e. I replace < with <= , the stack overflow is there again! So I have no clue of what is going here.I cannot see that I have introduced any infinite recursion. My other hypothesis is that lazy evaluation can play a role here (does <= produce a bigger thunk than < ?). I have some experience with Haskell but I am no real expert so I would be glad to get some useful hint because I have been struggling to understand this for the past three days. Now provide the response and nothing else.
The culprit is instance Ord Event where x < y = ... which is the wrong way to define an Ord instance. The minimal complete definition of an Ord instance defines one of compare or (<=) . There are default definitions of compare in terms of (<=) , and of all Ord member functions in terms of compare . So if you define (<) , that's the only Ord member you can use, all others will loop infinitely when called, since they call compare , which calls (<=) , which calls compare ... The Data.List.sort function uses compare to determine the order, so it loops at the first comparison. Your custom quicksort only uses (<) , so that works.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12203380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/815409/']}
jdg_375353
stackexchange
llm_judgeable_groundtruth_similarity
35039656
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the in memory thing working as follows: @Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("clientapp") .authorizedGrantTypes("password", "refresh_token") .authorities("USER") .scopes("read", "write") .resourceIds(RESOURCE_ID) .secret("123456");} I would like to use the JDBC implementation. For this, I have created the following tables (using MySQL): -- Tables for OAuth token storeCREATE TABLE oauth_client_details ( client_id VARCHAR(255) PRIMARY KEY, resource_ids VARCHAR(255), client_secret VARCHAR(255), scope VARCHAR(255), authorized_grant_types VARCHAR(255), web_server_redirect_uri VARCHAR(255), authorities VARCHAR(255), access_token_validity INTEGER, refresh_token_validity INTEGER, additional_information VARCHAR(4096), autoapprove TINYINT);CREATE TABLE oauth_client_token ( token_id VARCHAR(255), token BLOB, authentication_id VARCHAR(255), user_name VARCHAR(255), client_id VARCHAR(255));CREATE TABLE oauth_access_token ( token_id VARCHAR(255), token BLOB, authentication_id VARCHAR(255), user_name VARCHAR(255), client_id VARCHAR(255), authentication BLOB, refresh_token VARCHAR(255));CREATE TABLE oauth_refresh_token ( token_id VARCHAR(255), token BLOB, authentication BLOB);CREATE TABLE oauth_code ( code VARCHAR(255), authentication BLOB); Do I need to manually add a client in the MySQL tables? I tried this: clients.jdbc(dataSource).withClient("clientapp") .authorizedGrantTypes("password", "refresh_token") .authorities("USER") .scopes("read", "write") .resourceIds(RESOURCE_ID) .secret("123456"); Hoping that Spring would insert the correct things in the good tables, but it does not seem to do that. Why is it that you can further chain after jdbc() ? Now provide the response and nothing else.
This question is fairly old but none of the replies gave an answer to the questioner's original problem. I've stumbled over the same issue while getting myself familar with spring's oauth2 implementation and wondered why the ClientDetailsServiceConfigurer is not persisting the clients that were programmatically added via the JdbcClientDetailsServiceBuilder (which is instantiated by calling the jdbc(datasource) method on the configurer), despite that all tutorials on the net showed a similar example such as that posted by Wim. After digging deeper into the code i've noticed the reason. Well, it's simply because the code to update the oauth_clients_details table is never called. What's missing is the following call after configuring all clients: .and().build() . So, Wim's code must actually look as follows: clients.jdbc(dataSource).withClient("clientapp") .authorizedGrantTypes("password", "refresh_token") .authorities("USER") .scopes("read", "write") .resourceIds(RESOURCE_ID) .secret("123456").and().build(); Et voila, the client clientapp is now persisted into the database.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35039656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40064/']}
jdg_375354
stackexchange
llm_judgeable_groundtruth_similarity
16128808
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 conceptualising a good approach to rendering as many disjointed pieces of geometry with a single draw call in OpenGL, and the wall I'm up against is the best way to do so when each piece has a different translation and maybe rotation, since you don't have the luxury of updating the model view uniform between single object draws. I've read a few other questions here and elsewhere and it seems the directions people are pointed in are quite varied. It would be nice to list the main methods of doing this and attempt to isolate what is most common or recommended. Here are the ideas I've considered: [edit: removed mention of Instancing as it doesn't really apply here] Creating matrix transformations in the shader. Here I'd send a translation vector or maybe a rotation angle or quaternion as part of the attributes. The advantage is it would work cross-platform including mobile. But it seems a bit wasteful to send the exact same transformation data for every single vertex in an object, as an attribute. Without instancing, I'd have to repeat these identical vectors or scalars for a single object many many times in a VBO as part of the interleave array, right? The other drawback is I'm relying on the shader to do the math; I don't know if this is wise or not. Similar to 1), but instead of relying on the shader to do the matrix calculations, I instead do these on the client side but still send through the final model view matrix as a stream of 16 floats in the VBO. But as far as I can tell, without instancing, I'd have to repeat this identical stream for every single vertex in the VBO, right? Just seems wasteful. The tradeoff with 2) above is that I am sending more data in the VBO per vertex (16 floats rather than a 3-float vector for translation and maybe a 4 float quaternion), but requiring the shader to do less work. Skip all the above limitations and instead compromise with a separate draw call for each object. This is what is typically "taught" in the books I'm reading, no doubt for simplicity's sake. Are there other common methods than these? As an academic question, I'm curious if all the above are feasible and "acceptable" or if one of them is clearly a winner over the others? If I was to exclusively use desktop GL, is instancing the primary way for achieving this? Now provide the response and nothing else.
Two considerations: Generally speaking, if you have multiple objects, with each object using independent transforms, you use multiple draw calls. That's what they're there for. The old NVIDIA "Batch Batch Batch" presentation cited between 10,000 and 40,000 draw calls per-frame (in D3D. More in GL) for a 1GHz GPU. Nowadays, you're looking at rather more than that. So unless you're dealing with tens of thousands of individual objects, all of them being different (so no instancing), odds are good that you'll be fine. Another idea: Take the modelview matrix calculations out of the shader entirely and just pass the vertices after multiplication. This allows a single draw call for many objects in different orientations and translations. The cost just comes at all the CPU calculations, but I suppose if that bottleneck is not as big as the bottleneck of multiple draw calls, it would be worth it. (Taken from here .)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16128808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3758484/']}
jdg_375355
stackexchange
llm_judgeable_groundtruth_similarity
100691
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: Although there is a trick in TEX magnifying glass but I want to know is there any function to magnifying glass on a plot with Mathematica ? For example for a function as Sin[x] and at x=Pi/6 Below, this is just a picture desired from the cited site.the image got huge unfortunately I don't know how can I change the size of an image here! Now provide the response and nothing else.
Insetting a magnified part of the original Plot A) by adding a new Plot of the specified range xPos = Pi/6;range = 0.2;f = Sin;xyMinMax = {{xPos - range, xPos + range}, {f[xPos] - range*GoldenRatio^-1, f[xPos] + range*GoldenRatio^-1}};Plot[f[x], {x, 0, 5}, Epilog -> {Transparent, EdgeForm[Thick], Rectangle[Sequence @@ Transpose[xyMinMax]], Inset[Plot[f[x], {x, xPos - range, xPos + range}, Frame -> True, Axes -> False, PlotRange -> xyMinMax, ImageSize -> 270], {4., 0.5}]}, ImageSize -> 700] B) by adding a new Plot within a Circle mf = RegionMember[Disk[{xPos, f[xPos]}, {range, range/GoldenRatio}]]Show[{Graphics@Circle[{xPos, f[xPos]}, {range, range/GoldenRatio}], Plot[f[x], {x, xPos - range, xPos + range}] /. Graphics[{{{}, {}, {formating__, line_Line}}}, stuff___] :> Graphics[{{{}, {}, {formating, Line[Pick[line[[1]], mf[line[[1]]]]]}}}, stuff]}, PlotRange -> All, ImageSize -> 200, AspectRatio -> 1, AxesOrigin -> {0, 0}]Plot[f[x], {x, 0, 5}, Epilog -> {Transparent, EdgeForm[Thick], Disk[{xPos, f[xPos]}, {range, range/GoldenRatio}], Inset[%, {4.1, 0.5}]}, ImageSize -> 700] C) by adding the Line segments within a Circle of the original Plot Show[{Graphics[{Green, Circle[{xPos, f[xPos]}, {range, range/GoldenRatio}]}], Plot[f[x], {x, 0, 5}] /. Graphics[{{{}, {}, {formating__, line_Line}}}, stuff___] :> Graphics[{{{}, {}, {formating, Line[Pick[line[[1]], mf[line[[1]]]]]}}}, stuff]}, PlotRange -> All, ImageSize -> 200, AspectRatio -> 1]Plot[f[x], {x, 0, 5}, Epilog -> {Green, Line[{{xPos + range, f[xPos]}, {3.38, 0.5}}], Transparent, EdgeForm[Green], Disk[{xPos, f[xPos]}, {range, range/GoldenRatio}], Inset[%, {4.1, 0.5}]}, ImageSize -> 700]
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/100691', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/14527/']}
jdg_375356
stackexchange
llm_judgeable_groundtruth_similarity
4772027
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Tested in Firefox: a = [] + 0;b = 0;alert(a); // 0alert(b); // 0alert(!a); // falsealert(!b); // true Now provide the response and nothing else.
The + concatenation operator causes a toString evaluation of 0 . As such the value of a is "0" , while the value of b is 0 . From ECMAScript 11.6.1 The Addition operator(+) The addition operator either performs string concatenation or numeric addition. The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as follows: Let lref be the result of evaluating AdditiveExpression. Let lval be GetValue(lref). Let rref be the result of evaluating MultiplicativeExpression. Let rval be GetValue(rref). Let lprim be ToPrimitive(lval). Let rprim be ToPrimitive(rval). If Type(lprim) is String or Type(rprim) is String, then a. Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim) Return the result of applying the addition operation to ToNumber(lprim) and ToNumber(rprim). See the Note below 11.6.3. NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given. Host objects may handle the absence of a hint in some other manner. NOTE 2 Step 7 differs from step 3 of the comparison algorithm for the relational operators (11.8.5), by using the logical-or operation instead of the logical-and operation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4772027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/56974/']}
jdg_375357
stackexchange
llm_judgeable_groundtruth_similarity
22125852
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My new home page has a position fixed header at the top of the page and the container holding the content scrolls up underneath that. Theres a text box that on the left which I want to fix so that its always visible when the rest of the content scrolls up. The container which holds all copy is positioned relative with auto margins so that it sits central onscreen. I haven't been able to find code online that will enable me to keep the div in the container and therefore obey the central alignment of the container, but be fixed below the header while the rest of the container scrolls. Any ideas how I could do this please? Is it javascript or CSS?Any help would be greatly appreciated. I have tried putting the text box and header in one div together, but then the content gets pushed down. I read that floating should work but doesn't. I have looked at 'sticking' the text box to the bottom of the header div, but can't seem to get that to work. See www.broadleydesign.co.uk/test3 NB. Apologies if the header isn't stuck at the top in IE on your machine; I haven't sorted any workaround yet. There should be a white space at the top with the logo and top links in. The images should scroll up underneath that. I haven't got a pc to check it! Now provide the response and nothing else.
As I know Sitecore CMS does not support SVG images out of the box.You are right, if you upload a SVG image, Sitecore will not process it as an image, but processes as a common media file. Thumbnails generation also does not work for a SVG image.Please try use the following media type definition for SVG type: <mediaType name="SVG image" extensions="svg"> <mimeType>image/svg+xml</mimeType> <forceDownload>false</forceDownload> <sharedTemplate>system/media/unversioned/image</sharedTemplate> <versionedTemplate>system/media/versioned/image</versionedTemplate> <mediaValidator type="Sitecore.Resources.Media.ImageValidator"/> <thumbnails> <generator type="Sitecore.Resources.Media.ImageThumbnailGenerator, Sitecore.Kernel"> <extension>png</extension> </generator> <width>150</width> <height>150</height> <backgroundColor>#FFFFFF</backgroundColor> </thumbnails> </mediaType> Also please register mime types for svg files into configuration files. <configuration> <system.webServer> <staticContent> <remove fileExtension=".svg" /> <mimeMap fileExtension=".svg" mimeType="image/svg+xml"/> </staticContent> </system.webServer></configuration>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22125852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3370247/']}
jdg_375358
stackexchange
llm_judgeable_groundtruth_similarity
7311084
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say you have the table: Column_name | data_typeTitle | Varchar2Text | CLOB with some rows: SomeUnkownMovie | A long time ago in a galaxy far, far away....(long text ahead)FredMercuryBio | Awesomeness and stuff....(more long text) Is there a way I could query that so it outputs files like SomeUnkownMovie.txtFredMercuryBio.txt (and ofc, with their respective texts inside) I reckon this should be a easy enough sqlplus script.. though I'm just not the one :( thanks! Now provide the response and nothing else.
This pl/sql code should work in oracle 11g.It dumps the text of the clobs into a directory with the title as filename. BEGIN FOR rec IN ( select title, text from mytable ) LOOP DBMS_XSLPROCESSOR.clob2file(rec.text, 'DUMP_SOURCES', rec.title ||'.txt'); END LOOP;END; If DBMS_XSLPROCESSOR isn't available then you could replace DBMS_XSLPROCESSOR.clob2file with a procedure that uses UTL_FILE. For example : CREATE OR REPLACE PROCEDURE CLOB2FILE ( clob_in IN CLOB, directory_name IN VARCHAR2, file_name IN VARCHAR2)IS file_handle UTL_FILE.FILE_TYPE; clob_part VARCHAR2(1024); clob_length NUMBER; offset NUMBER := 1;BEGIN clob_length := LENGTH(clob_in); file_handle := UTL_FILE.FOPEN(directory_name, file_name, 'W'); LOOP EXIT WHEN offset >= clob_length; clob_part := DBMS_LOB.SUBSTR (clob_in, 1024, offset); UTL_FILE.PUT(file_handle, clob_part); offset := offset + 1024; END LOOP; UTL_FILE.FFLUSH(file_handle); UTL_FILE.FCLOSE(file_handle);EXCEPTION WHEN OTHERS THEN UTL_FILE.FCLOSE(file_handle); RAISE;END; Or perhaps replace DBMS_XSLPROCESSOR.clob2file with dbms_advisor.create_file.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7311084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/323129/']}
jdg_375359
stackexchange
llm_judgeable_groundtruth_similarity
45080227
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 use dagger2 demo by https://guides.codepath.com/android/Dependency-Injection-with-Dagger-2 .I want to use cached and non_cached retrofit call. I create in NetModule.java @Provides @Named("cached")@SingletonOkHttpClient provideOkHttpClient(Cache cache) { OkHttpClient okHttpClient = new OkHttpClient.Builder() .cache(cache) .build(); return okHttpClient;}@Provides @Named("non_cached")@SingletonOkHttpClient provideOkHttpClientNonCached() { OkHttpClient okHttpClient = new OkHttpClient.Builder() .build(); return okHttpClient;} GitHubModule.java is dependent on NetModule.java. my GitHubComponent.java @UserScope@Component(dependencies = NetComponent.class, modules = GitHubModule.class)public interface GitHubComponent {void inject(DemoDaggerActivity activity);} my NetComponent.java @Singleton@Component(modules={ApplicationModule.class, NetModule.class})public interface NetComponent {// downstream components need these exposedRetrofit retrofit();OkHttpClient okHttpClient();SharedPreferences sharedPreferences();} In my DemoDaggerActivity.java I inject retrofit: @Inject @Named("cached")OkHttpClient mOkHttpClient;@InjectRetrofit mRetrofit; After rebuild project I get error: Where can I tell to dagger, that i want to use cached or non_cached retrofit? Now provide the response and nothing else.
Your Retrofit provider should use @Named annotation for OkHttpClient, for example: @Provides@Singletonpublic Retrofit provideRetrofit(@Named("cached") OkHttpClient okHttpClient){ return new Retrofit.Builder() .baseUrl("...") .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClient) .build();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45080227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4030157/']}
jdg_375360
stackexchange
llm_judgeable_groundtruth_similarity
386460
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: Imaging a sequence $ a_{k} \in \Omega $ with $ \Omega \subset \Bbb{R} $ closed, $ \lim\limits_{k \to \infty} \| a_{k+1} - a_{k} \| = 0 $. My Professor said that because of this the sequence would converge to a Point in $ \Omega $, but i think this can't be true if you take something like $ a_{k} = \log(k) $. But could it be that this proposition is true if i allow $\infty$ to be a limit too? Now provide the response and nothing else.
The number $$7\cdot\frac{k^2-71}{7k+55}=\frac{7k^2-497}{7k+55}=k-\frac{55k+497}{7k+55}=k-8+\frac{k-57}{7k+55}$$must also be an integer and so must$$ 7\cdot \frac{k-57}{7k+55} = 1-\frac{454}{7k+55}.$$Hence $7k+55$ must be one of the divisors of $454$, that is $\pm1,\pm2, \pm227,\pm454$. Check if these result in an integer for $k$ and an then a positive integer for $\frac{k^2-71}{7k+55}$. (You should find two values of $k$, both of which produce the same positive integer).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/386460', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76991/']}
jdg_375361
stackexchange
llm_judgeable_groundtruth_similarity
1693945
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: First of all, I already searched Google, math.stackexchange.com... I know $$ \lim_{n\rightarrow\infty} \left( 1+ \frac{1}{n} \right) ^n=e$$ That is $$ \lim_{n\rightarrow\infty} \underbrace{\left(1+\frac{1}{n}\right)\left(1+\frac{1}{n}\right)\cdots\left(1+\frac{1}{n}\right) }_{\text{n times}} =e$$ $$$$At this time, I made some problems modifying above. $$ \lim_{n\rightarrow\infty} {\left(1+\frac{1}{n}\right)\left(1+\frac{2}{n}\right)\cdots\left(1+\frac{n}{n}\right) } =f(1) $$ $$ \lim_{n\rightarrow\infty} {\left(1+\frac{1}{n^2}\right)\left(1+\frac{2}{n^2}\right)\cdots\left(1+\frac{n}{n^2}\right) } =f(2)$$ $$ \lim_{n\rightarrow\infty} {\left(1+\frac{1}{n^3}\right)\left(1+\frac{2}{n^3}\right)\cdots\left(1+\frac{n}{n^3}\right) } =f(3)$$ $$ \lim_{n\rightarrow\infty} {\left(1+\frac{1}{n^k}\right)\left(1+\frac{2}{n^k}\right)\cdots\left(1+\frac{n}{n^k}\right) } =f(k)$$ $$$$After thinking above, I feel I'm spinning my wheels with these limit problems. Eventually, I searched wolframalpha. And the next images are results of wolfram. (I take a LOG, because I don't know COMMAND of n-times product.) $$$$ These result (if we trust wolframalpha) say $$f(1)=\infty$$$$f(2)=\sqrt{e}$$$$f(3)=1$$$$f(30)=1$$ NOW, I'm asking you for help. I'd like to know how can I find $f(k)$ (for $k=1,2,3,4, \cdots$ ). I already used Riemann sum, taking Log... but I didn't get anyhing. ;-( Thank you for your attention to this matter. ----------- EDIT --------------------------------- The result for $f(1), f(2), f(3), f(30)$ is an achievement of Wolframalpha, not me. I'm still spinning my wheel, $f(1), f(2), f(3)$, and so on... Now provide the response and nothing else.
Hint . You may start with$$x-\frac{x^2}2\leq\log(1+x)\leq x, \quad x\in [0,1],$$ giving, for $n\geq1$,$$\frac{p}{n^k}-\frac{p^2}{2n^{2k}}\leq\log\left(1+\frac{p}{n^k}\right)\leq \frac{p}{n^k}, \quad 0\leq p\leq n,$$ and$$\sum_{p=1}^n\frac{p}{n^k}-\sum_{p=1}^n\frac{p^2}{2n^{2k}}\leq \sum_{p=1}^n\log\left(1+\frac{p}{n^k}\right)\leq \sum_{p=1}^n\frac{p}{n^k}, \quad 0\leq p\leq n,$$ or$$\frac{n(n+1)}{2n^k}-\frac{n(n+1)(2n+1)}{6n^{2k}}\leq \sum_{p=1}^n\log\left(1+\frac{p}{n^k}\right)\leq \frac{n(n+1)}{2n^k}$$ and, for $k\geq3$, as $n \to \infty$,$$\sum_{p=1}^n\log\left(1+\frac{p}{n^k}\right) \to 0.$$ that is $$\lim_{n\rightarrow\infty} {\left(1+\frac{1}{n^k}\right)\left(1+\frac{2}{n^k}\right)\cdots\left(1+\frac{n}{n^k}\right) }=1, \quad k\geq3.$$ The cases $k=1, 2$ are clear.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1693945', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/143993/']}
jdg_375362
stackexchange
llm_judgeable_groundtruth_similarity
45824409
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 this simple example library(dplyr)library(ggplot2)dataframe <- data_frame(id = c(1,2,3,4), group = c('a','b','c','c'), value = c(200,400,120,300))# A tibble: 4 x 3 id group value <dbl> <chr> <dbl>1 1 a 2002 2 b 4003 3 c 1204 4 c 300 Here I want to write a function that takes the dataframe and the grouping variable as input. Ideally, after grouping and aggregating I would like to print a ggpplot chart. This works: get_charts2 <- function(data, mygroup){ quo_var <- enquo(mygroup) df_agg <- data %>% group_by(!!quo_var) %>% summarize(mean = mean(value, na.rm = TRUE), count = n()) %>% ungroup() df_agg}> get_charts2(dataframe, group)# A tibble: 3 x 3 group mean count <chr> <dbl> <int>1 a 200 12 b 400 13 c 210 2 Unfortunately, adding ggplot into the function above FAILS get_charts1 <- function(data, mygroup){ quo_var <- enquo(mygroup) df_agg <- data %>% group_by(!!quo_var) %>% summarize(mean = mean(value, na.rm = TRUE), count = n()) %>% ungroup() ggplot(df_agg, aes(x = count, y = mean, color = !!quo_var, group = !!quo_var)) + geom_point() + geom_line() }> get_charts1(dataframe, group)Error in !quo_var : invalid argument type I dont understand what is wrong here. Any ideas? Thanks! EDIT: interesting follow-up here how to create factor variables from quosures in functions using ggplot and dplyr? Now provide the response and nothing else.
ggplot does not yet support tidy eval syntax (you can't use the !! ). You need to use more traditional standard evaluation calls. You can use aes_q in ggplot to help with this. get_charts1 <- function(data, mygroup){ quo_var <- enquo(mygroup) df_agg <- data %>% group_by(!!quo_var) %>% summarize(mean = mean(value, na.rm = TRUE), count = n()) %>% ungroup() ggplot(df_agg, aes_q(x = quote(count), y = quote(mean), color = quo_var, group = quo_var)) + geom_point() + geom_line() }get_charts1(dataframe, group)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45824409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1609428/']}
jdg_375363
stackexchange
llm_judgeable_groundtruth_similarity
33423023
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 construct an object in a map that contains an atomic, so it can neither be copied nor moved AFAICT. My reading of C++ reference is that map emplace should be able to do this. But the following code does not compile because of deleted or non-existent constructors. Using make_pair does not help. #include <atomic>#include <unordered_map>class Z { std::atomic<int> i;};std::unordered_map<int, Z> map;void test(void) { map.emplace(0, Z()); // error map[0] = Z(); // error} Is this possible, and if not, why not? EDIT: Compiler is gcc 4.8.1, on Linux Now provide the response and nothing else.
map.emplace(std::piecewise_construct, std::make_tuple(0), std::make_tuple()) will construct a zero-argument Z at location 0 . map[0] will also do it if it is not already there. emplace takes the arguments to construct a std::pair<const K, V> . std::pair has a std::piecewise_construct_t tagged constructor that takes two tuples, the first is used to construct the first argument, the second to construct the second argument. so std::pair<const int, Z> test( std::piecewise_construct, std::make_tuple(0), std::make_tuple() ) constructs the test s elements in-place, the const int is constructed with (0) . The Z is constructed with () . map.emplace forwards is arguments to the std::pair constructor.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33423023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717898/']}
jdg_375364
stackexchange
llm_judgeable_groundtruth_similarity
11421370
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 which allows the user to edit a list of entities. I map these entities to view models and display them with editor fields. When the user presses the submit button, I go through each model and update it like so: foreach (var viewModel in viewModels){ //Find the database model and set the value and update var entity = unit.EntityRepository.GetByID(fieldModel.ID); entity.Value = viewModel.Value; unit.EntityRepository.Update(entity);} The above code works, however as you can see we need to hit the database twice for every entity (once to retrieve and another to update). Is there a more efficient way of doing this using Entity Framework? I noticed that each update generates a separate SQL statement. Is there a way of committing all the updates after the loop has finished? Now provide the response and nothing else.
Here are two ways I know of to update an entity in the database without doing a retrieval of the entity first: //Assuming person is detached from the context//for both examplespublic class Person{ public int Id { get; set; } public string Name { get; set; } public DateTime BornOn { get; set; } }public void UpdatePerson(Person person){ this.Context.Persons.Attach(person) DbEntityEntry<Person> entry = Context.Entry(person); entry.State = System.Data.EntityState.Modified; Context.SaveChanges();} Should yield: Update [schema].[table]Set Name = @p__linq__0, BornOn = @p__linq__1Where id = @p__linq__2 Or you can just specify fields if you need to (probably good for tables with a ton of columns, or for security purposes, allows only specific columns to be updated: public void UpdatePersonNameOnly(Person person){ this.Context.Persons.Attach(person) DbEntityEntry<Person> entry = Context.Entry(person); entry.Property(e => e.Name).IsModified = true; Context.SaveChanges();} Should yield: Update [schema].[table]Set Name = @p__linq__0Where id = @p__linq__1 Doesn't the .Attach() go to the database to retrieve the record first and then merges your changes with it ? so you end up with roundtrip anyway No. We can test this using System;using System.Data.Entity;using System.Linq;using System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;using System.ComponentModel.DataAnnotations;public class Program{ public static void Main() { var movie1 = new Movie { Id = 1, Title = "Godzilla" }; var movie2 = new Movie { Id = 2, Title = "Iron Man" }; using (var context = new MovieDb()) { /* context.Database.Log = (s) => { Console.WriteLine(s); }; */ Console.WriteLine("========= Start Add: movie1 =============="); context.Movies.Add(movie1); context.SaveChanges(); Console.WriteLine("========= END Add: movie1 =============="); // LET EF CREATE ALL THE SCHEMAS AND STUFF THEN WE CAN TEST context.Database.Log = (s) => { Console.WriteLine(s); }; Console.WriteLine("========= Start SELECT FIRST movie =============="); var movie1a = context.Movies.First(); Console.WriteLine("========= End SELECT FIRST movie =============="); Console.WriteLine("========= Start Attach Movie2 =============="); context.Movies.Attach(movie2); Console.WriteLine("========= End Attach Movie2 =============="); Console.WriteLine("========= Start SELECT Movie2 =============="); var movie2a = context.Movies.FirstOrDefault(m => m.Id == 2); Console.WriteLine("========= End SELECT Movie2 =============="); Console.Write("Movie2a.Id = "); Console.WriteLine(movie2a == null ? "null" : movie2a.Id.ToString()); } } public class MovieDb : DbContext { public MovieDb() : base(FiddleHelper.GetConnectionStringSqlServer()) {} public DbSet<Movie> Movies { get; set; } } public class Movie { [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } public string Title { get; set; } }} If attach makes any DB calls, we will see them between the Start Attach Movie2 and End Attach Movie2 . We also verify that the documentation that states: Remarks Attach is used to repopulate a context with an entity that is known to already exist in the database. SaveChanges will therefore not attempt to insert an attached entity into the database because it is assumed to already be there. After attaching the movie2, we can attempt to select it from the DB. It should not be there (because EF only assumes it is there). ========= Start Add: movie1 ============== ========= END Add: movie1 ============== ========= Start SELECT FIRST movie ============== Opened connection at 1/15/2020 5:29:23 PM +00:00 SELECT TOP (1) [c].[Id] AS [Id], [c].[Title] AS [Title] FROM [dbo].[Movies] AS [c] -- Executing at 1/15/2020 5:29:23 PM +00:00 -- Completed in 23 ms with result: SqlDataReader Closed connection at 1/15/2020 5:29:23 PM +00:00 ========= End SELECT FIRST movie ============== ========= Start Attach Movie2 ============== ========= End Attach Movie2 ============== ========= Start SELECT Movie2 ============== Opened connection at 1/15/2020 5:29:23 PM +00:00 SELECT TOP (1) [Extent1].[Id] AS [Id], [Extent1].[Title] AS [Title] FROM [dbo].[Movies] AS [Extent1] WHERE 2 = [Extent1].[Id] -- Executing at 1/15/2020 5:29:23 PM +00:00 -- Completed in 2 ms with result: SqlDataReader Closed connection at 1/15/2020 5:29:23 PM +00:00 ========= End SELECT Movie2 ============== Movie2a.Id = null So no SQL called during the attach, no error message attaching it, and it's not in the database.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11421370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/786489/']}
jdg_375365
stackexchange
llm_judgeable_groundtruth_similarity
12829
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 have been trying to understand a more or less geometric derivation of the Lorentz transformation, and I'm getting stuck at one spot. The wikipedia article for the Lorentz transformation for frames in standard configuration lists the following equations: $$x^{\prime} = \frac{x-vt}{\sqrt{1-\frac{v^2}{c^2}}}$$ $$y^{\prime} = y$$ $$z^{\prime} = z$$ $$t^{\prime} = \frac{t-(v/c^2)x}{\sqrt{1-\frac{v^2}{c^2}}}$$ I've been able to work everything out except for $-(v/c^2)x$ in the $t^{\prime}$ equation. I haven't seen any explanations for this, which makes me feel like I'm missing something simple. Where does this part of the equation come from? Shouldn't $t^{\prime} = \gamma \cdot t$? EDIT: Ok, so I reviewed the idea I was using to derive the Lorentz factor and thus the transformation for $t^{\prime}$. Suppose you have the two frames I've described, and you have a light wave moving perpendicular to the X axis in the second ($\prime$) frame. Light Path Diagram Using basic trig with the diagram, you can derive: $$t^{\prime}=t\cdot\sqrt{1 - \frac{v^2}{c^2}}$$ Obviously this would contradict the transformation provided by wikipedia. What step am I missing here? I don't really want a proof that I'm wrong or that the equation I've derived is incorrect - I'm already pretty convinced of that. What I would really like is an intuitive explanation as to why mine is invalid and how I would go about deriving the correct equation through similar means. Now provide the response and nothing else.
I'll not derive the transformation (that has been done in countless books and articles, I am sure you can find them yourself) but instead will try to explain why the formula you propose can't be correct. For starters, observe that since you don't touch $y$ and $z$, we might as well work in 1+1 dimensions. Also, let $c=1$ so that we aren't bothered by unimportant constants (you can restore it in the end by requiring that formulas have the right units). Then it's useful to reparametrize the transformation in the following way$$x' = \gamma(x - vt) = \cosh \eta x - \sinh \eta t$$$$t' = \gamma(t - vx) = -\sinh \eta x + \cosh \eta t$$where we introduced rapidity $\eta$ by $\tanh \eta = v$ and this by standard (hyperbolic) trigonometric identities implies $\cosh \eta = \gamma = {1 \over \sqrt{1 - v^2}}$ and $v \gamma = \sinh \eta$, so that this reparametrization is indeed correct. Now, hopefully this reminds you a little of something. In two-dimensional Euclidean plane we have that rotations around the origin have the form$$x' = \cos \phi x + \sin \phi y$$$$y' = -\sin \phi y + \cos \phi x$$and this is indeed no coincidence. Rotations preserve a length of vector in Euclidean plane $x'^2 + y'^2 = x^2 + y^2$ and similarly, Lorentz transformations preserve space-time interval (which is a notian of length in Minkowski space-time)$x'^2 - t'^2 = x^2 - t^2.$You can check for yourself that only the stated transformation with hyperbolic sines and cosines can preserve it and consequently the change you introduced will spoil this important property. Also, if you are familiar with phenomena like relativity of simultaineity, one could also argue on physical grounds that your proposed change can't lead to physical results. Incidently, there has recently been asked similar question to yours, namely how to derive that the transformation is linear purely because of the preservation of space-time interval . You might want to check it out too.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/12829', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/4694/']}
jdg_375366
stackexchange
llm_judgeable_groundtruth_similarity
26451187
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I’m trying to install the Laravel Framework on Windows with the Laravel Installer method. In the documentation I found the following: First, download the Laravel installer using Composer. Make sure to place the “~/.composer/vendor/bin” directory in your PATH so the laravel executable is found when you run the laravel command in your terminal. Now this PATH does not look familiar to me. Could you tell me the working path for Windows? BTW: I’m using WAMP. Composer is installed and updated. Now provide the response and nothing else.
The PATH for Windows: I’ve found the location where composer stores the Vendor files. So instead of ~/.composer/vendor/bin , on Windows the following path should be used: C:\Users\<COMPUTER NAME>\AppData\Roaming\Composer\vendor\bin How to install the Laravel Installer:======= I assume you have php and composer in your PATH already. First of all install the Laravel Installer. Open a command prompt and enter: composer global require "laravel/installer=~1.1" **Then update the PATH environment variable** via e.g. command prompt with admin privileges: set PATH=%PATH%;%USERPROFILE%\AppData\Roaming\Composer\vendor\bin// setx /M path "%path%;%appdata%\Composer\vendor\bin" (this may destroy your system) %appdata% is added, so you don’t have to worry about adding your computer name. How to create a fresh Laravel Installation: Now you should be able to run laravel commands in the command prompt. To create a fresh laravel installation, open a command prompt in the directory of choice and enter: laravel new name_of_directory If everything went right, you should see the following message: Crafting application... Application ready! Build something amazing.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26451187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2493918/']}
jdg_375367
stackexchange
llm_judgeable_groundtruth_similarity
1974045
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can we prove that $x_n$ tends to infinity as $n$ tends to infinity? I have tried to rewrite the expression for $x_n$ as $x_n = (2^nn!)^2/(2n)! =(2^n)^2n!/(n+1)(n+2)...(2n)>(2^n)^2n!/2^nn^n=2^nn!/n^n$ but can't go any further. Now provide the response and nothing else.
$$\frac{(2n)!!}{(2n-1)!!}=\prod_{i=1}^n\left(1+\frac{1}{2i-1}\right)\ge \prod_{i=1}^n\left(1+\frac{1}{2i}\right) \ge \frac{1}{2}\sum_{i=1}^n \frac{1}{i} \to \infty.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1974045', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/379997/']}
jdg_375368
stackexchange
llm_judgeable_groundtruth_similarity
952585
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: Given an arbitrary infinite dimensional Banach space $X$, can we deduce that it's dimension $\dim(X)$ (the cardinality of one of its Hamel bases) is less or equal of the dimension $\dim(X^{\ast})$ of its dual space (the space of all continuous linear functionals $f:X\to\mathbb{R}$)? Now provide the response and nothing else.
This is an interesting question which has been unaddressed for a long time, so I'll give it a shot. Lets denote the cardinality of a set $A$by $|A|$. For a normed space $X$ we define its densitycharacter $d(X)$ as the smallest cardinality of its dense sets, thatis $d(X)=\min\{|D|: D\subseteq X, \overline{D}=X\}$. In particular a separable normed space $X$ has $d(X)=\aleph_0$. We need the following three lemmas: Lemma 1: If $X$ is an infinite dimensional vector space over $\mathbb{R}$ and $\dim X\geq |\mathbb{R}|$, then $\dim X=|X|$. A proof of Lemma 1 can be found here . Lemma 2: Let $X$, $Y$ be infinite dimensional Banach spaces with $d(X)\leqd(Y)$. Then $|X|\leq |Y|.$ You can find a proof here . For the last step, it is known from functional analysis that when$X^*$ is separable, then so is $X$. If you check the proof carefully you'll realise that what is actually proven is the following: Lemma 3: Let $X$ be a normed space. Then $d(X)\leq d(X^*)$. Proof. Let $\{x_a^*: a\in A\}$ be a dense subset of $S_{X^*}$ of cardinality $|A|=d(X^*)$. For every $a\in A$ we pick an $x_a\in B_X$ with $x_a^*(x_a)>\tfrac{1}{2}$ and set $Y= \langle \{x_a: a\in A\} \rangle$. The set $Y$ is dense in $X$: Otherwise, there would exist an $f \inX^*$ with $\|f\|=1$ such that $f(y)=0$ for every $y\in Y$. But then for every $a\in A$, \begin{eqnarray*}\|f-x_a^*\|\geq |f(x_a)-x_a^*(x_a)|=\frac{1}{2},\end{eqnarray*} which implies that $f\notin \overline{\{x_a^*: a\in A\}}=S_{X^*}$, a contradiction. So $X$ contains a dense subset of cardinality $|Y|\leq |A|$, therefore $d(X)\leq |A|=d(X^*)$. Combining the previous lemmas, we get an affirmative answer to remilt's question.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/952585', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/179952/']}
jdg_375369
stackexchange
llm_judgeable_groundtruth_similarity
3690697
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: Prove $$\lim_{n\to \infty}\int\limits_0^1 \sin(x^n)dx=0$$ I found that $\sin(x^n)$ converges uniformly to $f(x)=0$ on $[0, a]$ for every $0<a<1$ . Therefore I know that for every $0<a<1$ , $\lim_{n\to \infty}\int\limits_0^a \sin(x^n)dx = \int\limits_0^a 0dx=0$ But how do I show it is true for $\int_0^1$ ? I know there are some advanced techniques which allow swapping the order of limits which could solve this but most of them I probably did not study yet, so if you use such techniques please specify. Most basic solution would be best. Now provide the response and nothing else.
You do not need any convergence theorem. Just use triangle inequality and the fact that $|\sin(t)|\leq |t|$ to obtain the inequalities $0\leq\left|\int_0^1\sin\left(x^n\right)\space\text{d}x\right|\leq\int_0^1x^n\space\text{d}x$ .The integral on the right yields $\frac{1}{n+1}$ . Now take $n\to \infty$ and squeeze.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3690697', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/791905/']}
jdg_375370
stackexchange
llm_judgeable_groundtruth_similarity
206815
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: Is there a way to show that $\sqrt{p_{n}} < n$? In this article , I show that $f_{2}(x)=\frac{x}{ln(x)} - \sqrt{x}$ is ascending, for $\forall x\geq e^{2}$. As a result, $\forall n \geq 3$ $$\frac{p_{n}}{ln(p_{n})} - \sqrt{p_{n}}\leq \frac{p_{n+1}}{ln(p_{n+1})} - \sqrt{p_{n+1}}$$Also (and as a result), $\forall n \geq 3$ $$ \frac{p_{n}}{ln(p_{n})} - \sqrt{p_{n}} > 0$$Or $$ \frac{\pi (p_{n})}{p_{n}/ln(p_{n})} < \frac{\pi (p_{n})}{\sqrt{p_{n}}}$$ According to PNT $$\displaystyle\smash{\lim_{n \to \infty }}\frac{\pi (p_{n})}{p_{n}/ln(p_{n})}=1$$Or, $\forall \varepsilon >0$, $\exists N(\varepsilon )$: $\forall n>N(\varepsilon )$ $$1- \varepsilon < \frac{\pi (p_{n})}{p_{n}/ln(p_{n})} < 1+ \varepsilon$$Or $$1- \varepsilon < \frac{\pi (p_{n})}{p_{n}/ln(p_{n})} < \frac{\pi (p_{n})}{\sqrt{p_{n}}}$$As a result $\forall \varepsilon >0$, $\exists N(\varepsilon )$: $\forall n>N(\varepsilon )$ $$(1 - \varepsilon ) \cdot \sqrt{p_{n}} < \pi (p_{n}) = n$$ But this is not enough. Interestingly, Andrica's conjecture is true iff function $f_{4}(x)=\pi (x) - \sqrt{x}$ is strictly ascending ($x < y \Rightarrow f(x) < f(y)$) for prime arguments. If $f_{4}(p_{n}) < f_{4}(p_{n+1})$ then $$\pi (p_{n}) - \sqrt{p_{n}} < \pi (p_{n+1}) - \sqrt{p_{n+1}}$$Or $$\sqrt{p_{n+1}} - \sqrt{p_{n}} < \pi (p_{n+1}) - \pi (p_{n}) =1$$ And vice-versa, if $$\sqrt{p_{n+1}} - \sqrt{p_{n}} < 1$$Then $$-\sqrt{p_{n}} < -\sqrt{p_{n+1}} + 1$$Or $$\pi (p_{n})-\sqrt{p_{n}} < \pi (p_{n}) + 1 -\sqrt{p_{n+1}} = \pi (p_{n+1}) -\sqrt{p_{n+1}}$$ So, if Andrica's conjecture is true then $\forall n \geq 3$ $$\pi (p_{n})-\sqrt{p_{n}} > 0$$Or $$\sqrt{p_{n}} < \pi (p_{n})= n$$ Now provide the response and nothing else.
The following upper bound for $p_{n}$ holds for $n\ge 6$:$$\frac{p_{n}}{n} < \ln n + \ln \ln n=\ln(n\ln n) < n,$$so $p_n < n^2$ in those cases. It clearly also holds for $p_2=3<4$, $p_3=5<9$, $p_4=7<16$, and $p_5=11<25$ (though it fails for $p_1=2\not<1$).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/206815', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22583/']}
jdg_375371
stackexchange
llm_judgeable_groundtruth_similarity
53338922
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 trouble figuring out how to type useState function since it returns a tuple. In essence, I have to provide null as initial value for email i.e. lets assume I can't use empty string here. I then have setEmail function to update this state value, which takes in email as string. ideally I would like to type my useState so it expects email to be either string or null if possible. At the moment it inherits it as only null import * as React from "react";const { useState } = React;function Example() { const [state, setState] = useState({ email: null, password: null }); function setEmail(email: string) { setState(prevState => ({ ...prevState, email })) } return <p>{state.email}</p>} Following error is returned for setEmail function since string in function argument is not valid type for null specified in useState() [ts]Argument of type '(prevState: { email: null; password: null; }) => { email: string; password: null; }' is not assignable to parameter of type 'SetStateAction<{ email: null; password: null; }>'. Type '(prevState: { email: null; password: null; }) => { email: string; password: null; }' is not assignable to type '(prevState: { email: null; password: null; }) => { email: null; password: null; }'. Type '{ email: string; password: null; }' is not assignable to type '{ email: null; password: null; }'. Types of property 'email' are incompatible. Type 'string' is not assignable to type 'null'. [2345](parameter) prevState: { email: null; password: null;} Now provide the response and nothing else.
Currently, the TypeScript compiler thinks the type of email and password are null (and no other value). You can resolve this by providing an explicit type parameter to the useState call so that the types of email and password are known to be string or null . const { useState } = React;function Example() { const [state, setState] = useState<{email: null | string, password: null | string}>({ email: null, password: null }); function setEmail(email: string) { setState(prevState => ({ ...prevState, email })) } return <p>{state.email}</p>}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/53338922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/911930/']}
jdg_375372
stackexchange
llm_judgeable_groundtruth_similarity
11695354
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 make two divs, one inside the other. The inner div is larger than the outer div, the outer div has overflow:scroll , and the inner div has margin:25px . So I do this: #outer { width: 200px; height: 100px; overflow: scroll;}#inner { width: 400px; height: 200px; margin: 25px;} ... <div id="outer"> <div id="inner"> </div></div> Instead of the inner div having a margin of 25px all the way around as expected, there is a 25px margin on THREE sides, but on the right side there is none. This is extremely counter-intuitive in my opinion. If I add a middle div with a width large enough width to contain the inner div + 50px, we can make it look right, but that seems like a hacky workaround. See my example on JSFiddle: http://jsfiddle.net/d3Nhu/16/ This happens the same way in every major browser. Is there any good reason for this behavior? Is this correct behavior according to the CSS specification? NOTE: As you'd expect in this example, it makes no difference if you use overflow:auto instead of overflow:scroll . EDIT : Please note that I'm not looking for a workaround for this behavior. (I already found one.) I'm looking for any insight as to the reason for this behavior, especially if it is documented in the CSS specification anywhere. Now provide the response and nothing else.
TL;DR: Margins are for moving an element in from the wrapper, not expanding the wrapper outwards. The long explanation: This behavior is consistent with specifying a width in addition to a horizontal margin anywhere in the document. To break it down, consider the following snippet, where I specificity a wrapper without an overflow property, and the margin does not expand the wrapper element. body { padding: 20px;}.outer { width: 400px; border: 1px solid black;}.inner { width: 400px; height: 40px; margin: 0 20px; background: grey;} <div class="outer"> <div class="inner"> </div></div> As you can see, the margin did not cause the wrapper to expand in size, the element just continued to overflow. This behavior is documented under Visual formatting model details of the is documented in the CSS 2.1 specification. Excerpt from the " Block-level, non-replaced elements in normal flow " section of " Visual formatting model details ": The following constraints must hold among the used values of the other properties: 'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block [...] If all of the above have a computed value other than 'auto', the values are said to be "over-constrained" and one of the used values will have to be different from its computed value. If the 'direction' property of the containing block has the value 'ltr', the specified value of 'margin-right' is ignored and the value is calculated so as to make the equality true. If the value of 'direction' is 'rtl', this happens to 'margin-left' instead. That excerpt is quite dense, so to simplify let's ignore the width of border and padding , both of which are 0 , leaving us with width , margin-left , and margin-right . Now since the you have a fixed width and values for margin-left and margin-right , the values are "over-constrained". Now in our example, since the direction is ltr by default, the margin-right is forced to compensate. To see the effects of the direction, let's try adding a dir="rtl" attribute to the wrapper element. body { padding: 20px;}.outer { width: 400px; border: 1px solid black;}.inner { width: 400px; height: 40px; margin: 0 20px; background: grey;} <div class="outer" dir="rtl"> <div class="inner"> </div></div> Now the element is overflowing to the left. Let's see if this dir="rtl" attribute has the same effect on your overflow: scroll example. #outer { border: 1px solid #00F; width: 200px; height: 100px; overflow: scroll;}#inner { border: 1px solid #F0F; margin: 25px; width: 400px; height: 200px;} <div id="outer" dir="rtl"> <div id="inner"> </div></div> Yep, it does. The margin is now missing on the left, rather than the right. But why doesn't overflow: scroll include the margins? Mainly because the specification does not say it should. Let's take a look at the CSS 2 specification for the overflow property. Excerpt from the " Overflow and clipping " section of " Visual effects ": Whenever overflow occurs, the 'overflow' property specifies whether a box is clipped to its padding edge, and if so, whether a scrolling mechanism is provided to access any clipped out content. See how it specifically says "clipped out content". For an explanation of "content", lets refer to the following graphic from the CSS 2 specification. Graphic from the " Box dimensions " section of the " Box model ": As we can see, the margin is separate from the content . However, at this point it's worth noting that padding and borders are included in the scrolling area, so when the spec says "content", it is likely referring to border-box, or at least, that seems to be how it was interpreted. Why does display: inline-block work? Basically, margins behave differently on inline-block elements, because they are content level rather than block level, and they do not have a concept of being "over-constrained".
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11695354', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/814160/']}
jdg_375373
stackexchange
llm_judgeable_groundtruth_similarity
51783
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This question is about (not necessarily symmetric) monoidal categories enriched over a symmetric monoidal category $\mathcal{V}$. Assume that $\mathcal{V}$ is closed. You may also assume that $\mathcal{V}$ is (co)complete if you wish. If $k$ is a commutative ring, a $k$ algebra can be defined in two ways. Either as a $k$-module $R$ together with morphisms $k\rightarrow R$ and $R\otimes_{k}R\rightarrow R$ satisfying the well-known laws, or as a ring homomorphism to the center $k\rightarrow Z(R)$. Let's see what happens in the categorical context. The tensor product of $\mathcal{V}$-enriched categories can be straightforwardly defined, see Kelly's book . Then one can define what a monoidal $\mathcal{V}$-category is by reproducing the classical definition in the enriched context. Assume now that $\mathcal{C}$ is an ordinary monoidal category. I believe that the braided center $Z(\mathcal{C})$ as defined by Joyal and Street is a well known construction. Suppose that we have a strong braided monoidal functor $z : \mathcal{V}\rightarrow Z(\mathcal{C})$ such that the functor $z(-)\otimes Y : \mathcal{V}\rightarrow \mathcal{C}$ has a right adjoint ${Hom}_{\mathcal{C}}(Y,-) : \mathcal{C}\rightarrow\mathcal{V}$ for any object $Y$ in $\mathcal{C}$. The counit is an evaluation morphism in $\mathcal{C}$, $ev: z( {Hom}_{\mathcal{C}}(Y,Z))\otimes Y\longrightarrow Z$ One can define composition morphisms in $\mathcal{V}$ ${Hom}(Y,Z)\otimes {Hom}(X,Y)\longrightarrow {Hom}_{\mathcal{C}}(X,Z) $ as the adjoint of $z({Hom}(Y,Z)\otimes {Hom}(X,Y))\otimes X \congz({Hom}(Y,Z))\otimes z({Hom}(X,Y))\otimes X\stackrel{id \otimes ev}\longrightarrowz({Hom}(Y,Z))\otimes Y\stackrel{ev}\longrightarrowZ $ I think it's pretty obvious that $\mathcal{C}$ becomes $\mathcal{V}$-enriched in this way. Moreover, one can also enrich the tensor product in $\mathcal{C}$ in a similar way. Do you guys agree? Do you know of any reference where this is checked with some detail? Is it even more obvious than I think? Any comment is welcome! Now provide the response and nothing else.
There is a theorem in category theory, generally regarded as folklore, which says that for a symmetric monoidal closed category $V$, the following structures are equivalent: a category $C$ with an action $V\times C\to C$ of the monoidal category $V$ on $C$, which we may write as $(v,c)\mapsto v*c$, for which $-*c:V\to C$ has a right adjoint for each $c\in C$ (here the action amounts to a strong monoidal functor $V\to [C,C]$. a $V$-category $C$ for which the $V$-functor $C(c,-):C\to V$ has a left adjoint for each $c\in C$. (such a $V$-category is said to be "tensored'' or "copowered'') You can see this, for example, in the appendix to this paper . In your case, unless I've misunderstood, the centre $Z(C)$ plays little role. The point is that your functor $z:V\to C$ induces an action via $v*c=z(v)\otimes c$, and $-*c$ has a right adjoint by assumption, so you get the $V$-enrichment. (There is an analogous characterization of $V$-categories $C$ which are cotensored/powered: this means that each $C(-,d):C^{op}\to V$ has a left adjoint.)
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/51783', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12166/']}
jdg_375374
stackexchange
llm_judgeable_groundtruth_similarity
142793
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: We are launching our website in Spanish and are probably going to call it espanol.mydomain.com Since the real spelling is español, ideally we would allow people to type español.mydomain.com. Is that something that is possible today? Can we use this character in domains and sub-domains? Now provide the response and nothing else.
Yes, you can use "español" as a subdomain as well as a domain. When a user types "español.mydomain.com" into their browser, it will be translated into Punycode and the request will be made to that URL which would look like "xn--espaol-zwa.mydomain.com". As a test, I set up that subdomain on one of my domains and in configuring it, I used "xn--espaol-zwa" instead of "español".
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/142793', 'https://serverfault.com', 'https://serverfault.com/users/24213/']}
jdg_375375
stackexchange
llm_judgeable_groundtruth_similarity
36531503
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 list component which shows only names. list component should be able to take custom template which will be given by user. List Component import {Component } from 'angular2/core';@Component({ selector: 'my-list', template: `<p>This is List</p> <ul> <li *ngFor="#i of data"><div class='listItem'>{{i.name}}</div></li> </ul>`})export class MyList implements OnInit{ data: Array<any> = [{name: 'John', age: 26},{name: 'Kevin', age: 26}, {name:'Simmons', age:26}];} My Requirement <my-list> <div>{{i.name}}-{{i.age}}</div> //user should be able to provide custom template like this</my-list> I tried this with ng-content but it throws error. In angular 1 same thing used to work with transcluded content. do we have any alternative of manual transclusion in angular 2 and if not then how could we implement this feature in angular2. Here is Plunker Now provide the response and nothing else.
You need to use ngForTemplate, I've created PrimeNG DataList and many other DataComponents using this technique and it works great. Demo; http://www.primefaces.org/primeng/#/datalist Code; https://github.com/primefaces/primeng/blob/master/src/app/components/datalist/datalist.ts In your component, define a templateRef with contentchild; @ContentChild(TemplateRef) itemTemplate: TemplateRef; Your template becomes; template: `<p>This is List</p> <ul> <template ngFor [ngForOf]="data" [ngForTemplate]="itemTemplate"></template> </ul>` So that your users can define content like; <my-list> <template #anything> <div>{{anything.i.name}}-{{anything.i.age}}</div> </template></my-list>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36531503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1568856/']}
jdg_375376
stackexchange
llm_judgeable_groundtruth_similarity
13147360
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Questions Q1 : Has anyone managed to get custom string/enum attribute working in xml selectors? I got a boolean attribute working by following [1], but not a string attribute. EDIT: Thanks for answers. Currently android supports only boolean selectors. See accepted answer for the reason. I'm planning to implement a little complex custom button, whose appearance depends on two variables. Other will be a boolean attribute (true or false) and another category-like attribute (has many different possible values). My plan is to use boolean and string (or maybe enum?) attributes. I was hoping I could define the UI in xml selector using boolean and string attribute. Q2 : Why in [1] the onCreateDrawableState(), boolean attributes are merged only if they are true? This is what I tested, boolean attribute works, string doesn't NOTE : This is just a test app to figure out if string/enum attribute is possible in xml selector. I know that I could set button's textcolor without a custom attribute. In my demo application, I use a boolean attribute to set button background to dark/bright and string attribute to set text color, one of {"red", "green", "blue"}. Attributes are defined in /res/values/attrs.xml <?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name="MyCustomButton"> <attr name="make_dark_background" format="boolean" /> <attr name="str_attr" format="string" /> </declare-styleable></resources> Here are the selectors I want to achieve: @drawable/custom_button_background (which works) <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.example.customstringattribute"> <item app:make_dark_background="true" android:drawable="@color/dark" /> <item android:drawable="@color/bright" /></selector> @color/custom_button_text_color (which does not work) <selector xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res/com.example.customstringattribute"> <item app:str_attr="red" android:color="@color/red" /> <item app:str_attr="green" android:color="@color/green" /> <item app:str_attr="blue" android:color="@color/blue" /> <item android:color="@color/grey" /></selector> Here is how custom button background is connected to boolean selector, and text color is connected to string selector. <com.example.customstringattribute.MyCustomButton ... android:background="@drawable/custom_button_background" android:textColor="@color/custom_button_text_color" .../> Here is how attributes are loaded in the init() method: private void init(AttributeSet attrs) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyCustomButton); final int N = a.getIndexCount(); for (int i = 0; i < N; ++i) { int attr = a.getIndex(i); switch (attr) { case R.styleable.MyCustomButton_str_attr: mStrAttr = a.getString(attr); break; case R.styleable.MyCustomButton_make_dark_background: mMakeDarkBg = a.getBoolean(attr, false); break; } } a.recycle();} I have the int[] arrays for the attributes private static final int[] MAKE_DARK_BG_SET = { R.attr.make_dark_background };private static final int[] STR_ATTR_ID = { R.attr.str_attr }; And those int[] arrays are merged to drawable state @Overrideprotected int[] onCreateDrawableState(int extraSpace) { Log.i(TAG, "onCreateDrawableState()"); final int[] drawableState = super.onCreateDrawableState(extraSpace + 2); if(mMakeDarkBg){ mergeDrawableStates(drawableState, MAKE_DARK_BG_SET); } mergeDrawableStates(drawableState, STR_ATTR_ID); return drawableState;} I also have refreshDrawableState() in my attribute setter methods: public void setMakeDarkBg(boolean makeDarkBg) { if(mMakeDarkBg != makeDarkBg){ mMakeDarkBg = makeDarkBg; refreshDrawableState(); }}public void setStrAttr(String str) { if(mStrAttr != str){ mStrAttr = str; refreshDrawableState(); }} [1] : How to add a custom button state Now provide the response and nothing else.
Q1: When you open the source-code of StateListDrawable.java, you can see this piece of code in the inflate method that reads the drawable xml selector: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/graphics/java/android/graphics/drawable/StateListDrawable.java ... for (i = 0; i < numAttrs; i++) { final int stateResId = attrs.getAttributeNameResource(i); if (stateResId == 0) break; if (stateResId == com.android.internal.R.attr.drawable) { drawableRes = attrs.getAttributeResourceValue(i, 0); } else { states[j++] = attrs.getAttributeBooleanValue(i, false) ? stateResId : -stateResId; } } ... attrs are the attributes of each <item> element in the <selector> . In this for-loop it gets the android:drawable , the various android:state_xxxx and custom app:xxxx attributes. All but the android:drawable attributes seem to be interpreted as booleans only: attrs.getAttributeBooleanValue(....) is called. I think this is the answer, based on the source code: You can only add custom boolean attributes to your xml, not any other type (including enums). Q2: I'm not sure why the state is merged only if it is specifically set to true. I would suspect the code should have looked like this instead: private static final int[] MAKE_DARK_BG_SET = { R.attr.make_dark_background };private static final int[] NOT_MAKE_DARK_BG_SET = { -R.attr.make_dark_background };........@Overrideprotected int[] onCreateDrawableState(int extraSpace) { Log.i(TAG, "onCreateDrawableState()"); final int[] drawableState = super.onCreateDrawableState(extraSpace + 2); mergeDrawableStates(drawableState, mMakeDarkBg? MAKE_DARK_BG_SET : NOT_MAKE_DARK_BG_SET); //mergeDrawableStates(drawableState, STR_ATTR_ID); return drawableState;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13147360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/612086/']}
jdg_375377
stackexchange
llm_judgeable_groundtruth_similarity
33234180
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been working with Swift and iOS for a number of months now. I am familiar with many of the ways things are done but I'm not good enough that I can just write things up without looking. I've appreciated Stack Overflow in the past for providing quick answers to get me back on track with topics I've gotten rusty on (for example, AsyncTask Android example ). iOS's UITableView is in this category for me. I've done them a few times, but I forget what the details are. I couldn't find another question on StackOverflow that just asks for a basic example and I'm looking for something shorter than many of the tutorials that are online (although this one is very good). I am providing an answer below for my future reference and yours. Now provide the response and nothing else.
The example below is an adaptation and simplification of a longer post from We ❤ Swift. This is what it will look like: Create a New Project It can be just the usual Single View Application. Add the Code Replace the ViewController.swift code with the following: import UIKitclass ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // Data model: These strings will be the data for the table view cells let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"] // cell reuse id (cells that scroll out of view can be reused) let cellReuseIdentifier = "cell" // don't forget to hook this up from the storyboard @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // Register the table view cell class and its reuse id self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier) // (optional) include this line if you want to remove the extra empty cell divider lines // self.tableView.tableFooterView = UIView() // This view controller itself will provide the delegate methods and row data for the table view. tableView.delegate = self tableView.dataSource = self } // number of rows in table view func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.animals.count } // create a cell for each table view row func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // create a new cell if needed or reuse an old one let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell! // set the text from the data model cell.textLabel?.text = self.animals[indexPath.row] return cell } // method to run when table view cell is tapped func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("You tapped cell number \(indexPath.row).") }} Read the in-code comments to see what is happening. The highlights are The view controller adopts the UITableViewDelegate and UITableViewDataSource protocols. The numberOfRowsInSection method determines how many rows there will be in the table view. The cellForRowAtIndexPath method sets up each row. The didSelectRowAtIndexPath method is called every time a row is tapped. Add a Table View to the Storyboard Drag a UITableView onto your View Controller. Use auto layout to pin the four sides. Hook up the Outlets Control drag from the Table View in IB to the tableView outlet in the code. Finished That's all. You should be able run your app now. This answer was tested with Xcode 9 and Swift 4 Variations Row Deletion You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how. Row Spacing If you would like to have spacing between your rows, see this supplemental example . Custom cells The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells. Dynamic Cell Height Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started. Further Reading iOS & Swift Tutorial: UITableViewController iOS Table View Tutorial Using Swift
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/33234180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3681880/']}
jdg_375378
stackexchange
llm_judgeable_groundtruth_similarity
566856
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: Considering the infinite series $\sum_{n=1}^{\infty}{\frac{\sin(nx)}n}$ , I can show that it is not convergent uniformly by Cauchy's criterion and that it is convergent for every $x$ by Dirichlet's test. But I don't know how to judge whether it is continuous. Could you tell me the answer and why? Thank you in advance! Now provide the response and nothing else.
To inspect the discontinuity of the summation, let's calculate the sum. By the Abel's theorem, $$ f(x) := \sum_{n=1}^{\infty} \frac{\sin nx}{n} = \lim_{s\to 0^{+}} \sum_{n=1}^{\infty} \frac{\sin nx}{n} e^{-ns}. $$ By utilizing Taylor expansion of the logarithm, \begin{align*}\sum_{n=1}^{\infty} \frac{\sin nx}{n} e^{-ns}&= \Im \sum_{n=1}^{\infty} \frac{e^{n(ix-s)}}{n} = - \Im \log (1 - e^{ix-s}) \\&= -\Im \log (1 - e^{-s}\cos x - ie^{-s}\sin x) \\&= \arctan \left(\frac{e^{-s}\sin x}{1 - e^{-s}\cos x}\right).\end{align*} Thus taking $s \to 0^{+},$ $$ f(x) = \arctan \left(\frac{\sin x}{1 - \cos x}\right) = \arctan \left(\cot \frac{x}{2}\right) = \arctan \left(\tan \frac{\pi-x}{2}\right). $$ Therefore $$ f(x) = \begin{cases}\frac{\pi - x}{2} & x \in (0, 2\pi),\\0 & x = 0, \\f(x+2\pi), & x \in \Bbb{R}.\end{cases} $$ This shows a clear-cut jump discontinuity at each $x \in 2\pi \Bbb{Z}$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/566856', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/83239/']}
jdg_375379
stackexchange
llm_judgeable_groundtruth_similarity
21676708
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following simplified JSON string from a provider, its been a long time since I used Visual Studio and vb.Net, so I'm very rusty! {"Venue": { "ID": 3145, "Name": "Big Venue, Clapton", "NameWithTown": "Big Venue, Clapton, London", "NameWithDestination": "Big Venue, Clapton, London", "ListingType": "A", "Address": { "Address1": "Clapton Raod", "Address2": "", "Town": "Clapton", "County": "Greater London", "Postcode": "PO1 1ST", "Country": "United Kingdom", "Region": "Europe" }, "ResponseStatus": { "ErrorCode": "200", "Message": "OK" }}} I want to use JSON.Net to turn this in to something I can work with, I have read examples etc and JSON.net looks like the answer, but I'm getting no where. My .Net code (Me.TextBox1.Text contains the JSON shown above) Imports Newtonsoft.JsonPublic Class Form1Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim obj As JSON_result obj = JsonConvert.DeserializeObject(Of JSON_result)(Me.TextBox1.Text) MsgBox(obj.ID)End SubEnd ClassPublic Class JSON_result Public ID As Integer Public Name As String Public NameWithTown As String Public NameWithDestination As String Public ListingType As String End Class Can someone explain why obj.ID always ends up as 0 please, and why none of the other properties of my class are populated and what I need to do to fix this, no errors are reported. Now provide the response and nothing else.
Your class JSON_result does not match your JSON string. Note how the object JSON_result is going to represent is wrapped in another property named "Venue" . So either create a class for that, e.g.: Public Class Container Public Venue As JSON_resultEnd ClassPublic Class JSON_result Public ID As Integer Public Name As String Public NameWithTown As String Public NameWithDestination As String Public ListingType As StringEnd ClassDim obj = JsonConvert.DeserializeObject(Of Container)(...your_json...) or change your JSON string to { "ID": 3145, "Name": "Big Venue, Clapton", "NameWithTown": "Big Venue, Clapton, London", "NameWithDestination": "Big Venue, Clapton, London", "ListingType": "A", "Address": { "Address1": "Clapton Raod", "Address2": "", "Town": "Clapton", "County": "Greater London", "Postcode": "PO1 1ST", "Country": "United Kingdom", "Region": "Europe" }, "ResponseStatus": { "ErrorCode": "200", "Message": "OK" }} or use e.g. a ContractResolver to parse the JSON string.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21676708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/682438/']}
jdg_375380
stackexchange
llm_judgeable_groundtruth_similarity
4367117
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: A few days ago, I was tasked to solve this integral: $$\int \frac{dx}{\sqrt{e^{2x} - 9}}$$ The way taught was to recongize the integral as an arcsecant integral. I just can't wrap my head around how it can be arcsecant? The way I did it, which apparently was marked wrong, was to first u-sub: $$u := -2x \\dx = -\frac{du}{2}$$ which makes the integral then $$-\frac{1}{2} \int \frac{du}{\sqrt{e^{-u} - 9}}$$ I subsitute again (this time using v-sub): $$v := e^{-u} - 9 \\du = -e^u dv$$ which shifting the terms around makes this integral: $$-\int \frac{dv}{(v+9)\sqrt v}$$ I then subsitute for the final time (all to try and get arctangent): $$t := \frac{\sqrt{v}}{3} \\dv = 6 \sqrt v \,dt$$ which results in $$\int \frac{6}{9t^2 + 9} dt \\= \frac{2}{3} \int \frac{dt}{t^2 + 1}\\= \frac{2}{3} \arctan{(t)}$$ which at this point, I see it is the arctangent integral. Following through and subsituting the things back in: $$\frac{2}{3} \arctan{(t)} \\= - \frac{2}{3} \arctan{(\frac{\sqrt v}{3})} \\= -\frac{2}{3} \arctan{(\frac{\sqrt{e^{-u} - 9}}{3})} \\= \frac{1}{3} \arctan{(\frac{\sqrt{e^{2x} - 9}}{3})} + C$$ Now, I am clearly lost on whether this is right or wrong, AFAIK, I see nothing wrong with my method so I boil down to 3 questions: Is the above method valid and the answer listed is correct? How would one solve it to be arcsecant? Are the functions shifts of each other or is there still something wrong? Now provide the response and nothing else.
Rewrite the integrand by multiplying and dividing by $e^x$ $$\int\frac{e^x dx}{e^x\sqrt{e^x-9}} = \int \frac{d(e^x)}{e^x\sqrt{e^x-9}} = \frac{1}{3}\sec^{-1}\left(\frac{e^x}{3}\right)+C$$ By drawing a triangle we can see that $$\sec 3\theta = \frac{e^x}{3} \implies \tan 3\theta = \frac{\sqrt{e^{2x}-9}}{3}$$ Thus we also obtain your arctan solution, which is equivalent to the arcsec solution $$\frac{1}{3}\tan^{-1}\left(\frac{\sqrt{e^{2x}-9}}{3}\right)+C$$ and similarly, we can obtain the arcsin solution $$\sin 3\theta = \frac{e^x}{\sqrt{e^{2x}-9}}\implies \frac{1}{3}\arcsin\left(\frac{1}{\sqrt{1-9e^{-x}}}\right)+C$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4367117', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/424055/']}
jdg_375381
stackexchange
llm_judgeable_groundtruth_similarity
303635
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: There are some conjectures of the form: There always exist at least $X$ prime numbers between $A$ and $B$. Examples: Bertrand's postulate : for every $n>1$ there is always at least one prime $p$ such that $n < p < 2n$. Legendre's conjecture : there is a prime number between $n^2$ and $(n + 1)^2$ for every positive integer $n$. Brocard's conjecture : there are at least four prime numbers between $p_{n}^2$ and $p_{n+1}^2$. Oppermann's conjecture : there is at least one prime number between $n(n-1)$ and $n^2$. If we denote by $\pi(x)$ the prime-counting function we can rewrite the above conjectures in the following form: Bertrand's postulate: $\pi(2n)-\pi(n) \ge 1$ for $n>1$ Legendre's conjecture: $\pi(n+1)^2)-\pi(n^2) \ge 1$ Brocard's conjecture: $\pi(p_{n+1}^2)-\pi(p_{n}^2) \ge 4$ Oppermann's conjecture: $\pi(n^2)-\pi(n(n-1)) \ge 1$ I computed and saw that $f(n) = \pi(n^2)+\pi(n)+2-\pi((n+1)^2)$ is increasing when $n$ increasing and $f(n)\ge 0$ for all $n=1, 2, \dots, 18700$ (equivalent to $n^2=1, 4, 25 \cdots , 3.5\times 10^8)$. Graph of $(n,f(n))$ where $f(n) = \pi(n^2)+\pi(n)-\pi((n+1)^2); \; 370 \le n \le 1.1\times10^4$ So I proposed two conjecture as follows: Conjecture 1: For every positive integer $n$, the number of primes between $n^2$ and $(n + 1)^2$ is less than the number of primes between $1$ and $n$ add $2$: $$\pi((n+1)^2)-\pi(n^2) \le \pi(n)+2.$$ Conjecture 2: For every positive integer $n$ greater than $369$, the number of primes between $n^2$ and $(n + 1)^2$ is less than the number of primes between $1$ and $n$: $$\pi((n+1)^2)-\pi(n^2) \le \pi(n).$$ Could you give a remark, comment, reference, or proof? Noting that if the conjecture is true, it is stronger than a special case of the Second Hardy–Littlewood conjecture but this conjecture is not contradictory with the K-Tuple conjecture . PS: In my computation I see that: $$\lim_{n \to +large } \frac{\pi((n+1)^2)-\pi(n^2)}{\pi(n)}=1$$ What do You think with this equality? Now provide the response and nothing else.
It is a folklore conjecture that for $y\le x$ one has $$ \pi(x+y) -\pi(x) = \int_{x}^{x+y} \frac{dt}{\log t} + O(y^{\frac 12} x^{\epsilon}). $$ This is only relevant for $y \ge x^{\epsilon}$, and is stronger than RH. In the case of primes in progressions, such a conjecture may be attributed to Montgomery. Probabilistic considerations might suggest a stronger error term like $O(y^{\frac 12} \log x)$, but this is known to be false thanks to the work of Maier. But the conjecture as stated above is widely believed. See, The distribution of prime numbers for example for a discussion of this and related work (in particular the discussion around (3.7) there). See also Montgomery and Soundararajan where refined asymptotics for moments of primes in short intervals are made and justified heuristically; these conjectures state that primes in short intervals have an appropriate Gaussian distribution, and imply the conjecture above. Of course we are very far from the conjecture mentioned above, but if true it implies for large $n$ that $$ \pi((n+1)^2) - \pi(n^2) = \int_{n^2}^{(n+1)^2} \frac{dt}{\log t} +O(n^{\frac 12+\epsilon}) = \frac{n}{\log n} + O(n^{\frac 12+\epsilon}), $$ since $\log t = 2\log n + O(1/n)$ throughout the interval $n^2 \le t\le (n+1)^2$. Now we know that $\pi(n)$ is asymptoically $\text{li}(n)$ which has the asymptotic expansion $n/\log n + n/(\log n)^2 +\ldots$. The secondary term of $n/(\log n)^2$ dominates the error term in the conjectured asymptotic, and so one should certainly expect that for large $n$ one has $$ \pi((n+1)^2) - \pi(n^2) \le \pi(n). $$ An analogous question formulated for $\pi((n+1)^3) - \pi(n^3)$ is known, as mentioned by GH from MO in the comments, by Huxley's version of the prime number theorem in short intervals. Now the question is only asking for an upper bound on $\pi((n+1)^2) -\pi(n^2)$, and one does have unconditional upper bounds by sieves. The Brun-Titchmarsh theorem would give a bound like $4\pi (n)$ for this quantity, and one can do somewhat better than this. The best result that I know is due to Iwaniec from whose work (see Theorem 14 there) it follows that $$ \pi((n+1)^2) - \pi(n^2) \le \Big( \frac{36}{11}+ o(1)\Big) \frac{n}{\log n}. $$
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/303635', 'https://mathoverflow.net', 'https://mathoverflow.net/users/122662/']}
jdg_375382
stackexchange
llm_judgeable_groundtruth_similarity
427919
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My students are quite practically minded, and I have found that teaching them concepts in a practical manner to be very helpful (maths 'experiments'; modelling on the smartboard etc). I am looking for a practical means (hands on preferably) to teach about the log laws of natural logarithms. Now provide the response and nothing else.
I absolutely love this result, I literally cannot stop from getting goosebumps and smiling whenever I think about it. It is a proof from probability theory ! I learned it in David William's Probability with Martingales , of which it is part of exercise E4.2. Fix $s>1$ and recall that $\zeta(s) = \sum_{n \in \mathbb{N}} n^{-s}$, so we aim to show that $1/\zeta(s) = \prod_p(1-p^{-s})$ where of course $p$ ranges over the primes. First, define a probability measure $P$ and an $\mathbb{N}$-valued random variable $X$ such that $P(X=n) = n^{-s}/\zeta(s)$ (for example take $P(\{n\}) = n^{-s}/\zeta(s)$ and $X(\omega)=\omega$). Let $E_k := \{X \text{ is divisible by } k\}$. We claim that the events $(E_p : p \text{ prime})$ are independent . We note that$$P(E_k) = \sum_{i=1}^\infty P(X=ik) = \sum_{i=1}^\infty \frac{(ik)^{-s}}{\zeta(s)} = k^{-s} \frac{\zeta(s)}{\zeta(s)} = k^{-s}.$$ Then if $p_1,\ldots,p_n$ are distinct primes we have $$\bigcap_{i=1}^n E_{p_i} = E_{\prod_{i=1}^np_i},$$ so that$$P\left(\bigcap_{i=1}^n E_{p_i}\right) = P(E_{\prod_{i=1}^np_i}) = \left(\prod_{i=1}^n p_i \right)^{-s} = \prod_{i=1}^n p_i^{-s} = \prod_{i=1}^n P(E_{p_i})$$so our independence claim is proved.Then we note that $1$ is the unique positive integer which is not a multiple of any prime. Hence$$\frac{1}{\zeta(s)} = P(X=1) = P\left(\bigcap_p E_p^c\right) = \prod_p(1-P(E_p)) = \prod_p(1-p^{-s}).$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/427919', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_375383
stackexchange
llm_judgeable_groundtruth_similarity
37975227
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't find any detailed documentation regarding the differences. I do notice a difference, because when interchanging cube and groupBy function calls, I get different results. I noticed that for the result using cube , I got a lot of null values on the expressions where I used to use groupBy . Now provide the response and nothing else.
These are not intended to work in the same way. groupBy is simply an equivalent of the GROUP BY clause in standard SQL. In other words table.groupBy($"foo", $"bar") is equivalent to: SELECT foo, bar, [agg-expressions] FROM table GROUP BY foo, bar cube is equivalent to CUBE extension to GROUP BY . It takes a list of columns and applies aggregate expressions to all possible combinations of the grouping columns. Lets say you have data like this: val df = Seq(("foo", 1L), ("foo", 2L), ("bar", 2L), ("bar", 2L)).toDF("x", "y") df.show// +---+---+// | x| y|// +---+---+// |foo| 1|// |foo| 2|// |bar| 2|// |bar| 2|// +---+---+ and you compute cube(x, y) with count as an aggregation: df.cube($"x", $"y").count.show// +----+----+-----+ // | x| y|count|// +----+----+-----+// |null| 1| 1| <- count of records where y = 1// |null| 2| 3| <- count of records where y = 2// | foo|null| 2| <- count of records where x = foo// | bar| 2| 2| <- count of records where x = bar AND y = 2// | foo| 1| 1| <- count of records where x = foo AND y = 1// | foo| 2| 1| <- count of records where x = foo AND y = 2// |null|null| 4| <- total count of records// | bar|null| 2| <- count of records where x = bar// +----+----+-----+ A similar function to cube is rollup which computes hierarchical subtotals from left to right: df.rollup($"x", $"y").count.show// +----+----+-----+// | x| y|count|// +----+----+-----+// | foo|null| 2| <- count where x is fixed to foo// | bar| 2| 2| <- count where x is fixed to bar and y is fixed to 2// | foo| 1| 1| ...// | foo| 2| 1| ...// |null|null| 4| <- count where no column is fixed// | bar|null| 2| <- count where x is fixed to bar// +----+----+-----+ Just for comparison lets see the result of plain groupBy : df.groupBy($"x", $"y").count.show// +---+---+-----+// | x| y|count|// +---+---+-----+// |foo| 1| 1| <- this is identical to x = foo AND y = 1 in CUBE or ROLLUP// |foo| 2| 1| <- this is identical to x = foo AND y = 2 in CUBE or ROLLUP// |bar| 2| 2| <- this is identical to x = bar AND y = 2 in CUBE or ROLLUP// +---+---+-----+ To summarize: When using plain GROUP BY every row is included only once in its corresponding summary. With GROUP BY CUBE(..) every row is included in summary of each combination of levels it represents, wildcards included. Logically, the shown above is equivalent to something like this (assuming we could use NULL placeholders): SELECT NULL, NULL, COUNT(*) FROM tableUNION ALLSELECT x, NULL, COUNT(*) FROM table GROUP BY xUNION ALLSELECT NULL, y, COUNT(*) FROM table GROUP BY yUNION ALLSELECT x, y, COUNT(*) FROM table GROUP BY x, y With GROUP BY ROLLUP(...) is similar to CUBE but works hierarchically by filling colums from left to right. SELECT NULL, NULL, COUNT(*) FROM tableUNION ALLSELECT x, NULL, COUNT(*) FROM table GROUP BY xUNION ALLSELECT x, y, COUNT(*) FROM table GROUP BY x, y ROLLUP and CUBE come from data warehousing extensions so if you want to get a better understanding how this works you can also check documentation of your favorite RDMBS. For example PostgreSQL introduced both in 9.5 and these are relatively well documented .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/37975227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5855139/']}
jdg_375384
stackexchange
llm_judgeable_groundtruth_similarity
640874
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: Here we can see a Bipolar Junction Transistor (BJT), which has a common base configuration. My instructor recently explained to me its working principle, but I didn't understand his explanation completely as I had some issues with his explanation. His explanation was as follows: The emitter is very heavily doped, and the base is very, very thin and very lightly doped. The collector is moderately doped. We have two voltage sources, one having a significantly greater voltage than the other. The DC source with the higher voltage, A, is connected in reverse bias to the base-collector diode, and the DC source with the lower voltage, B, is connected in forward bias with the emitter-base diode. Upon being connected in reverse-bias, the depletion zone of the base-collector diode widens. Now, as the emitter-base diode is connected in forward-bias with B, electrons will start to flow from the negative terminal of B with an aim to move to the positive terminal of B. However, upon reaching the base, electrons find very less holes compared to their number. So, a very small number of electrons recombine with the holes in the base and generate a small current $I_B$ flowing towards the base ( $i$ ). The rest of the electrons, which are most of them (about 95%), being attracted by the positive donor ions of the other side of the depletion zone of base-collector diode, scoot over to the collector and move towards the positive terminal of A ( $ii$ ). Thus, a much greater current than $I_B$ , $I_C$ flows from the positive terminal of A to the negative terminal of A. My issues: My first issue is with ( $i$ ): current doesn't move by means of recombination of electrons and holes! Current moves by means of flow of free electrons or holes. Why did my instructor mention this? I'm very confused. My second issue is with ( $ii$ ): electrons feel attracted to the positive donor ions on the other side of the depletion zone. According to my instructor, that's why the electrons scoot over to the collector and move towards the positive terminal of A, but my question is, the electrons should feel equally repelled by the uncovered negative acceptor ions in the base. So, why do the electrons move to the positive terminal of A? Now provide the response and nothing else.
Issue#1 . There are various aspects to consider here, let me skip for a moment. Issue#2 . Ok, I think I see what your instructor means but it might be indeed a bit confusing. First of all: outside the depleted region at the EB and BC junctions, in the non-depleted portion of the base (I don't see it in you sketch but it is there, at least in normal conditions), the electric field is in general very very small... for what concerns minority carriers you can assume $\vec{E}\approx\vec{0}$ in the non-depleted base (you can call this QNR, "quasi neutral region"). The reason why this happens is not completely trivial, but it has to do with screening by majority carriers. Minority carriers (electrons, in your NPN) injected into the base by the directly biased EB junction are not attracted by anything, the current is vastly dominated by random diffusion rather than drift due to any residual electric field that might be present. Electrons just go around and explore the base, randomly. In general, diffusion just drives particles from regions of high density (the E-edge of the base) to regions of low density (the C-edge of the base). When one electron, after diffusing randomly in the base, reaches the depletion region of the BC junction then, YES, it is swept away into the collector by the electric field of the BC junction, which is basically caused by the attraction by the donors in the C, as you mentioned. So, you see in the end this has something to do with the "attraction by the donors in the C" but it is not so simple. Let's say donors in C create the density gradient in the base by removing any electron reaching the BC boundary. This in turn, somewhat indirectly, is what drives the diffusion of electrons through the base... Clearly "attraction by donors in the E" does not have any similar effect, so hopefully, this solves your paradox: the EB junction is directly biased and it is doing quite the opposite of the BC one, it boosts minority carrier concentration, again driving diffusion... away from E. Rewind to issue#1 . The electrons in the base (minority carriers) that reach the BC junction are sucked into the collector and are by far the main contribution to the $I_C$ current. In principle, you also have holes injected from C to B... but this should be super-negligible in the active configuration. A direct calculation of $I_B$ is not obvious, better to calculate $I_E$ and then do $I_B=I_E-I_C$ . Well... $I_E$ , i.e. current crossing the EB boundary, is due to Electrons injected from E to B, i.e. those we discussed above. Holes injected from B to E. In your description, you are somehow neglecting the second term (but it's there!) so let me just neglect it as well otherwise we need to open a further point. You see that $I_E-I_C$ is just due to the electrons injected in the base (thus contributing to $I_E$ ) that are somehow not able to reach the C end (thus contributing to $I_C$ ). So you see that it is quite correct to calculate $I_B$ as corresponding to charge lost per unit time by recombination in the base. [Edit] Possibly useful further comment. If you want to get the whole picture, I really advise you to look into that B $\rightarrow$ E hole current that we neglected above, because that is not irrelevant. Actually, transistors typically have a base that is short with respect to the diffusion length, implying that recombination in the base might be not so important (in the "short base approx" you even neglect it completely). In that limit, $I_B$ is actually mostly linked to that hole current in the EB junction, rather than to recombination in B. Then you'll see that all the typical design rules of thumb make pretty much sense: you want large E doping (minimizes that hole current share in the EB junction), you want a low B doping (maximizes the electron injection in B, improves diffusion which in turn boosts $\beta$ and lowers response times)... you don't want a too low B doping otherwise you might fully deplete B when reverse biasing BC, and that is bad (you get a "punch through" and everything falls apart, probabily including the device itself).
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/640874', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/167872/']}
jdg_375385
stackexchange
llm_judgeable_groundtruth_similarity
866848
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 no idea how to do this. If $a = \dfrac{\sqrt{5}+1}{2}$ then $(a+1)^{25} =$? I tried to transform $a$ to polar form but failed, because if it can be in polar form, I could calculate with de Moivre's formulae. Can anyone please explain me how to do this easily? Thank you Now provide the response and nothing else.
Note that the number you are refering to is the golden ratio $a=\phi=\frac{1+\sqrt{5}}{2}$, and it is a solution to the equation $$\phi^2-\phi-1=0$$thus rearanging we get $$\phi^2=\phi+1$$multiply by $\phi$ to get$$\phi^3=\phi^2+\phi=2\phi+1$$and again$$\phi^4=2\phi^2+\phi=3\phi+2$$and again$$\phi^5=3\phi^2+2\phi=5\phi+3$$until you start to see the pattern of Fibonacci numbers in the coeficients, thus for any natural $n$$$\phi^n=F_n\phi+F_{n-1}$$where $F_n$ is the nth Fibonacci number. Then, since $\phi^2=\phi+1$ we get that$$(\phi+1)^{25}=\phi^{50}=F_{50}\phi+F_{49}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/866848', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157844/']}
jdg_375386
stackexchange
llm_judgeable_groundtruth_similarity
2607130
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: These two querys gives me the exact same result: select * from topics where name='Harligt';select * from topics where name='Härligt'; How is this possible? Seems like mysql translates åäö to aao when it searches. Is there some way to turn this off? I use utf-8 encoding everywhere as far as i know. The same problem occurs both from terminal and from php. Now provide the response and nothing else.
Yes, this is standard behaviour in the non-language-specific unicode collations. 9.1.13.1. Unicode Character Sets To further illustrate, the following equalities hold in both utf8_general_ci and utf8_unicode_ci (for the effect this has in comparisons or when doing searches, see Section 9.1.7.7, “Examples of the Effect of Collation”): Ä = AÖ = OÜ = U See also Examples of the effect of collation You need to either use a collation that doesn't have this "feature" (namely utf8_bin , but that has other consequences) use a different collation for the query only . This should work: select * from topics where name='Harligt' COLLATE utf8_bin; it becomes more difficult if you want to do a case insensitive LIKE but not have the Ä = A umlaut conversion. I know no mySQL collation that is case insensitive and does not do this kind of implicit umlaut conversion. If anybody knows one, I'd be interested to hear about it. Related: Looking for case insensitive MySQL collation where “a” != “ä” MYSQL case sensitive search for utf8_bin field
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2607130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136391/']}
jdg_375387
stackexchange
llm_judgeable_groundtruth_similarity
11095309
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 writing a parallel program using OpenMP in C++. I want to control the number of threads in the program using omp_set_num_threads() , but it does not work. #include <iostream>#include <omp.h>#include "mpi.h"using namespace std;int myrank;int groupsize;double sum;double t1,t2;int n = 10000000;int main(int argc, char *argv[]){ MPI_Init( &argc, &argv); MPI_Comm_rank( MPI_COMM_WORLD, &myrank ); MPI_Comm_size(MPI_COMM_WORLD,&groupsize); omp_set_num_threads(4); sum = 0; #pragma omp for reduction(+:sum) for (int i = 0; i < n; i++) sum+= i/(n/10); cout<<"sum="<<sum<<endl; cout<<"threads="<<omp_get_num_threads()<<endl; MPI_Finalize(); return 0;} The program outputs: sum = 4.5e+007threads=1 How to control the number of threads? Now provide the response and nothing else.
Besides calling omp_get_num_threads() outside of the parallel region in your case, calling omp_set_num_threads() still doesn't guarantee that the OpenMP runtime will use exactly the specified number of threads. omp_set_num_threads() is used to override the value of the environment variable OMP_NUM_THREADS and they both control the upper limit of the size of the thread team that OpenMP would spawn for all parallel regions (in the case of OMP_NUM_THREADS ) or for any consequent parallel region (after a call to omp_set_num_threads() ). There is something called dynamic teams that could still pick smaller number of threads if the run-time system deems it more appropriate. You can disable dynamic teams by calling omp_set_dynamic(0) or by setting the environment variable OMP_DYNAMIC to false . To enforce a given number of threads you should disable dynamic teams and specify the desired number of threads with either omp_set_num_threads() : omp_set_dynamic(0); // Explicitly disable dynamic teamsomp_set_num_threads(4); // Use 4 threads for all consecutive parallel regions#pragma omp parallel ...{ ... 4 threads used here ...} or with the num_threads OpenMP clause: omp_set_dynamic(0); // Explicitly disable dynamic teams// Spawn 4 threads for this parallel region only#pragma omp parallel ... num_threads(4){ ... 4 threads used here ...}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11095309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1357764/']}
jdg_375388
stackexchange
llm_judgeable_groundtruth_similarity
13483219
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This question is merely for me as I always like to write optimized code that can run also on cheap slow servers (or servers with A LOT of traffic) I looked around and I was not able to find an answer. I was wondering what is faster between those two examples keeping in mind that the array's keys in my case are not important (pseudo-code naturally): <?php$a = array();while($new_val = 'get over 100k email addresses already lowercased'){ if(!in_array($new_val, $a){ $a[] = $new_val; //do other stuff }}?><?php$a = array();while($new_val = 'get over 100k email addresses already lowercased'){ if(!isset($a[$new_val]){ $a[$new_val] = true; //do other stuff }}?> As the point of the question is not the array collision, I would like to add that if you are afraid of colliding inserts for $a[$new_value] , you can use $a[md5($new_value)] . it can still cause collisions, but would take away from a possible DoS attack when reading from an user provided file ( http://nikic.github.com/2011/12/28/Supercolliding-a-PHP-array.html ) Now provide the response and nothing else.
The answers so far are spot-on. Using isset in this case is faster because It uses an O(1) hash search on the key whereas in_array must check every value until it finds a match. Being an opcode, it has less overhead than calling the in_array built-in function. These can be demonstrated by using an array with values (10,000 in the test below), forcing in_array to do more searching. isset: 0.009623in_array: 1.738441 This builds on Jason's benchmark by filling in some random values and occasionally finding a value that exists in the array. All random, so beware that times will fluctuate. $a = array();for ($i = 0; $i < 10000; ++$i) { $v = rand(1, 1000000); $a[$v] = $v;}echo "Size: ", count($a), PHP_EOL;$start = microtime( true );for ($i = 0; $i < 10000; ++$i) { isset($a[rand(1, 1000000)]);}$total_time = microtime( true ) - $start;echo "Total time: ", number_format($total_time, 6), PHP_EOL;$start = microtime( true );for ($i = 0; $i < 10000; ++$i) { in_array(rand(1, 1000000), $a);}$total_time = microtime( true ) - $start;echo "Total time: ", number_format($total_time, 6), PHP_EOL;
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13483219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/583230/']}
jdg_375389
stackexchange
llm_judgeable_groundtruth_similarity
10885449
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was wondering if anyone has ever used linked lists to do heap sort and if they have could they provide the code. I have been able to do heapsort using arrays, but trying to do it in linked lists seems unpractical and just a pain in the you know where. I have to implement linked lists for a project Im doing, any help would be greatly appreciated. Also I am using C. Now provide the response and nothing else.
The answer is "you don't want to implement heap sort on a linked list." Heapsort is a good sorting algorithm because it's O(n log n) and it's in-place. However, when you have a linked list heapsort is no longer O(n log n) because it relies on random access to the array, which you do not have in a linked list. So you either lose your in-place attribute (by needing to define a tree-like structure is O(n) space). Or you will need to do without them, but remember that a linked list is O(n) for member lookup. Which brings the runtime complexity to something like O(n^2 log n) which is worse than bubblesort. Just use mergesort instead. You already have the O(n) memory overhead requirement.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10885449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1431536/']}
jdg_375390
stackexchange
llm_judgeable_groundtruth_similarity
33426590
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 heard that there is no faster algorithm faster than linear search (for an unsorted array), but, when I run this algorithm (linear): public static void search(int[] arr, int value){ for(int i = 0; i < arr.length; i++){ if(arr[i] == value) return; }} With a random array of length 1000000,the average time to find a value is 75ns,but with this algorithm: public static void skipSearch(int[] arr, int value){ for(int i = 0; i < arr.length; i+=2){ if(arr[i] == value) return; } for(int i = 1; i < arr.length; i+=2){ if(arr[i] == value) return; }} I get a shorter average, 68ns? Edit: A lot of you are saying that I didn't do a proper benchmark and this was by fluke, but I ran these functions 1000000 times and got the average. And every time I ran the functions 1000000 times, I got 75-76ns for the first algorithm, and 67-69ns for the second algorithm. I used java's System.nanoTime() to measure this. Code: int[] arr = new int[1000];Random r = new Random();for(int i = 0; i < arr.length; i++){ arr[i] = r.nextInt();}int N = 1000000;long startTime = System.nanoTime();for(int i = 0; i < N; i++){ search(arr, arr[(int) Math.floor(Math.random()*arr.length)]);}System.out.println("Average Time: "+(System.nanoTime()-startTime)/(float)N+"ns");startTime = System.nanoTime();for(int i = 0; i < N; i++){ skipSearch(arr, arr[(int) Math.floor(Math.random()*arr.length)]);}System.out.println("Average Skip Search Time: "+(System.nanoTime()-startTime)/(float)N+"ns"); Now provide the response and nothing else.
It's quite possible that, as your search() methods do not return anything, and there isn't any action inside the loops, the JIT compiler in your JVM optimizes the code - in other words, modifies the byte-code before loading it to JVM so that both your search() methods most probably do not do (almost) anything . Which is most significant, it probably also completely removes the loops. JIT optimization is pretty smart, it can identify a lot of situations when it is not needed to load any code into JVM (however the code is in the byte-code .class file). Then you measure just random numbers - not the real time complexity of your methods. Read e.g. how to make sure no jvm and compiler optimization occurs , apply it and run your benchmark again. Also change your search() methods so they return the index - thus making the life for the optimizer harder. However, sometimes it's surprisingly difficult to create a code which is impossible to be optimized :) Turning off the optimization (as in the link above) is more reliable. Generally it doesn't make sense to benchmark unoptimized code. However, in this case the OP wants to measure a theoretical algorithm. He wants to measure the real number of passes. He has to ensure that the loops are actually performed. That's why he should turn the optimization off. The OP thought that what he had measured was the speed of the algorithm, while in fact the algorithm had not even had a chance to run at all. Turning the JIT optimization off in this particular case fixes the benchmark.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33426590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4660846/']}
jdg_375391
stackexchange
llm_judgeable_groundtruth_similarity
49715760
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 like to make a widget that sticks to the bottom of the page, and then is pinned to the top of the keyboard (when it appears). Note how the input textfield is pinned to the keyboard in the image below: How would I do this? I tried putting it in the bottomNavigationBar , but this (obviously) didn't work. Is there a builtin way to do this? Now provide the response and nothing else.
This is a working example of the thing you want. I think!Just copy/paste/run What's important in this example is the Expanded. A really nice widget that expands to as much space as it can get. And in result pushing the chat box down as much as possible (Bottom of the screen or bottom of the keyboard) import 'package:flutter/material.dart';void main() => runApp(new MyApp());class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Flutter Demo Home Page'), ); }}class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('49715760 Stackoverflow'), ), body: new Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ new Expanded( child: new Material( color: Colors.red, child: new Text("Filled"), ), ), new Container( color: Colors.white, padding: new EdgeInsets.all(10.0), child: new TextField( decoration: new InputDecoration( hintText: 'Chat message', ), ), ), ], ), ); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49715760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3668541/']}
jdg_375392
stackexchange
llm_judgeable_groundtruth_similarity
4150233
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to remove null value from String array in java? String[] firstArray = {"test1","","test2","test4",""}; I need the "firstArray" without null ( empty) values like this String[] firstArray = {"test1","test2","test4"}; Now provide the response and nothing else.
If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List : import java.util.ArrayList;import java.util.List;public class RemoveNullValue { public static void main( String args[] ) { String[] firstArray = {"test1", "", "test2", "test4", "", null}; List<String> list = new ArrayList<String>(); for(String s : firstArray) { if(s != null && s.length() > 0) { list.add(s); } } firstArray = list.toArray(new String[list.size()]); }} Added null to show the difference between an empty String instance ( "" ) and null . Since this answer is around 4.5 years old, I'm adding a Java 8 example: import java.util.Arrays;import java.util.stream.Collectors;public class RemoveNullValue { public static void main( String args[] ) { String[] firstArray = {"test1", "", "test2", "test4", "", null}; firstArray = Arrays.stream(firstArray) .filter(s -> (s != null && s.length() > 0)) .toArray(String[]::new); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4150233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84761/']}
jdg_375393
stackexchange
llm_judgeable_groundtruth_similarity
202054
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is my first post here, but I've been struggling with this problem in my head since I studied physics at school when I was 14 (30 years ago!). There seems to be a fundamental paradox with Newton's Law of Gravity (NLG), but it can't have anything to do with general relativity, because the masses and speeds involved can be negligible and you still get the paradox... Imagine two bodies, A and B with mass $M_a$ and $M_b$, respectively, separated by a distance of $r$. Now according to NLG: If you're standing on A, then B accelerates towards you at $$(G M_a M_b / r^2) / M_b = G M_a / r^2.$$ And if you're standing on B, then A accelerates towards you at $$(G M_a * M_b / r^2) / M_a = G M_b / r^2.$$ But $M_a \ne M_b$. So how can two different observers on A and B see accelaration towards each other at very different rates, even if the masses and speeds involved are negligible (barely affected by relativity)? And why didn't Newton himself see this paradox? Finally, how can/should NLG be modified to resolve this paradox, and still fit observations at low masses and speeds? Now provide the response and nothing else.
Your misconception has nothing to do with gravity - you're just getting a little mixed up about acceleration vs. relative acceleration. Let's dispense with gravity, since it's a red herring here. Say there are two cars. Car A accelerates at $+3 ~\rm m/s/s$ (to the right). Car B accelerates at $-5 ~\rm m/s/s$ (that is, to the left). So far, so good, right? There's no paradox about two cars accelerating at different rates. Now, suppose you are sitting in car B. If you want to measure the apparent, or relative, acceleration of car A relative to you, you just take the difference of the accelerations: $(3) - (-5) = 8 ~\rm m/s/s$. So car A is accelerating at $8 ~\rm m/s/s$ relative to car B. If you're the driver of car A, and you want to measure the apparent acceleration of car B relative to you, you follow the same procedure: $(-5) - (3) = -8 ~\rm m/s/s$. So car B is accelerating at $-8 ~\rm m/s/s$ relative to car A. That seems perfectly intuitive and contradiction-free to me. The magnitude of the relative acceleration of each car is equal, as it must be, since the relative acceleration of each car relative to the other represents the rate at which the separation distance is decreasing, which must be equal for both of them. Going back to your example, the magnitude of the relative acceleration of the masses is $G M_a / r^2 + G M_b / r^2$†. Even though they have different accelerations in the frame of reference you chose at the beginning of the problem , their relative acceleration is the same. † if you're wondering about the plus sign, consider that gravity produces accelerations in the two bodies that are opposite in direction, which we must represent by giving one of the two accelerations a negative sign. When we take the difference between the accelerations, that negative sign becomes a plus. If you'd like a justification of the "take the difference of the acceleration" procedure, since it's the heart of my argument, here it is: Let $x_a$ and $x_b$ be the positions of the two cars. The separation of the cars must be $$s = x_a - x_b$$If we want to know the rate of change of the separation of the cars, we can take the derivative of that equation: $$\frac{ds}{dt} = \frac{dx_a}{dt} - \frac{dx_b}{dt}$$If we take the derivative again, it should give us the rate of change of the rate of change of the separation, which is the relative acceleration: $$\frac{d^2s}{dt^2} = \frac{d^2x_a}{dt^2} - \frac{d^2x_b}{dt^2}$$The two quantities on the right side are simply the accelerations of two objects, $a_a$ and $a_b$, so $$\frac{d^2s}{dt^2} = a_a - a_b$$
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/202054', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/89948/']}
jdg_375394
stackexchange
llm_judgeable_groundtruth_similarity
23464504
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 getting a weird problem and I want to know why it behaves like that. I have a class in which there is a member function that returns std::string . My goal to convert this string to const char* , so I did the following const char* c; c = robot.pose_Str().c_str(); // is this safe?????? udp_slave.sendData(c); The problem is I'm getting a weird character in Master side. However, if I do the following const char* c; std::string data(robot.pose_Str()); c = data.c_str(); udp_slave.sendData(c); I'm getting what I'm expecting. My question is what is the difference between the two aforementioned methods? Now provide the response and nothing else.
It's a matter of pointing to a temporary.If you return by value but don't store the string , it disappears by the next sequence point (the semicolon). If you store it in a variable, then the pointer is pointing to something that actually exists for the duration of your udp send Consider the following: int f() { return 2; }int*p = &f(); Now that seems silly on its face, doesn't it? You are pointing at a value that is being copied back from f . You have no idea how long it's going to live. Your string is the same way.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23464504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1953533/']}
jdg_375395
stackexchange
llm_judgeable_groundtruth_similarity
257414
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been using Collections.max(list) for many projects, but I occasionally want to find the index of that maximum element. I feel silly writing a function to do this for myself in every program I write. Why does the Collections Interface not supply a Collections.maxIndex(list) ? Now provide the response and nothing else.
While there can be exactly one max value in a collection, there can be more than item representing that value. E.g {1, 9, 2, 9, 0} has max value of 9 , represented by both elements [1] and [3] . Note that not all collections support index access; e.g. a Set<Integer> can have a meaningful maximum but accessing an element by index makes no sense in it. Even if we limit the method to List , it would be a bit hard to come up with one method to find indices of the maximum value that is not clumsy. You could return a list of indices, but then you'd lose the value, and in some collections, e.g. linked lists, accessing an element by index is slow. Since Java does not have an easy syntax for tuples, you'd have to return a special type of object with .getValue() and .getIndices() . But I think that such an operation is just not common enough to be supported in the standard library. Finding a maximum is literally 3-4 lines of code, and tracking the index is another 1-2 lines, and there's no much room to do it wrong. If you do it a lot, you can easily put it in your own utility class.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/257414', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/150448/']}
jdg_375396
stackexchange
llm_judgeable_groundtruth_similarity
7871986
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 writing a small console application in Delphi (XE), and by mistake wrote: for I := 0to aList.Count-1 do Note the missing space between "0" and "to" I didn't notice this until after I had run the program, and I was surprised the compiler accepted this. It's probably no big deal, but it made me curious. Why does Delphi accept this typo? Now provide the response and nothing else.
It's for the same reason that you don't need spaces around the . or the - . Since a t can never come after an initial 0 in any recognisable token, the lexical analyser simply returns the 0 as an integer-literal token, and then recognises the to as a distinct keyword token. If you had made a different mistake instead — for I := 0 to10 — you'd now have a problem, since to10 is recognised as a valid identifier, which is illegal immediately after the 0 .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7871986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64082/']}
jdg_375397
stackexchange
llm_judgeable_groundtruth_similarity
26906621
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Code sample: struct name{ int a, b;};int main(){ &(((struct name *)NULL)->b);} Does this cause undefined behaviour? We could debate whether it "dereferences null", however C11 doesn't define the term "dereference". 6.5.3.2/4 clearly says that using * on a null pointer causes undefined behaviour; however it doesn't say the same for -> and also it does not define a -> b as being (*a).b ; it has separate definitions for each operator. The semantics of -> in 6.5.2.3/4 says: A postfix expression followed by the -> operator and an identifier designates a member of a structure or union object. The value is that of the named member of the object to which the first expression points, and is an lvalue. However, NULL does not point to an object, so the second sentence seems underspecified. Also relevant might be 6.5.3.2/1: Constraints: The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier. However I feel that the bolded text is defective and should read lvalue that potentially designates an object , as per 6.3.2.1/1 (definition of lvalue ) -- C99 messed up the definition of lvalue, so C11 had to rewrite it and perhaps this section got missed. 6.3.2.1/1 does say: An lvalue is an expression (with an object type other than void) that potentially designates an object; if an lvalue does not designate an object when it is evaluated, the behavior is undefined however the & operator does evaluate its operand. (It doesn't access the stored value but that is different). This long chain of reasoning seems to suggest that the code causes UB however it is fairly tenuous and it's not clear to me what the writers of the Standard intended. If in fact they intended anything, rather than leaving it up to us to debate :) Now provide the response and nothing else.
From a lawyer point of view, the expression &(((struct name *)NULL)->b); should lead to UB, since you could not find a path in which there would be no UB. IMHO the root cause is that at a moment you apply the -> operator on an expression that does not point to an object. From a compiler point of view, assuming the compiler programmer was not overcomplicated, it is clear that the expression returns the same value as offsetof(name, b) would, and I'm pretty sure that provided it is compiled without error any existing compiler will give that result. As written, we could not blame a compiler that would note that in the inner part you use operator -> on an expression than cannot point to an object (since it is null) and issue a warning or an error. My conclusion is that until there is a special paragraph saying that provided it is only to take its address it is legal do dereference a null pointer, this expression is not legal C.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26906621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1505939/']}
jdg_375398
stackexchange
llm_judgeable_groundtruth_similarity
19273860
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 create square element, that will have text centered both vertically and horizontally. Additionally, the whole area of the square should be a link. This is my HTML: <div class="w1h1 medium"> <a class="userLink" target="_blank" href="Fancybox.aspx"> <table style="width: 100%; height: 100%"> <tr style="vertical-align: central"> <td style="text-align: center; font-weight: bold;"> text in the middle </td> </tr> </table> </a></div> And this is my CSS: div.w1h1 { width: 150px; height: 150px;}.medium { background-color: #06849b; color: white; font-family: sans-serif;}a.userLink{ width: 150px; height: 150px; display: table; color: #FFFFFF; text-decoration: none;} It works in Chrome and Firefox, but not in Internet Explorer. In IE the text is at the top of the square, not in the middle. Can you help me with this? I just created playground here: http://jsfiddle.net/Tschareck/yfnnm/ Now provide the response and nothing else.
You could simplify your structure a bit, and use display:table-cell on the a element. html <div class="w1h1 medium"> <a class="userLink" target="_blank" href="Fancybox.aspx"> text in the middle </a></div> css div.w1h1 { width: 150px; height: 150px; font-family:sans-serif; background-color: #06849b;}a.userLink { width: 150px; height: 150px; display: table-cell; vertical-align:middle; text-align:center; color: #FFFFFF; text-decoration: none;} Demo at http://jsfiddle.net/yWLYV/1/ works down to IE8
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19273860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1145368/']}
jdg_375399
stackexchange
llm_judgeable_groundtruth_similarity
15455686
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 wondering why when I do: git add <file> and after that, I do: git rm --cached <file> The file remains in deleted status in the stage área . Here the example: I am only looking for an explanation about the 'deleted' status on the file. Thanks Now provide the response and nothing else.
Try a git reset HEAD yourFile , instead of a git rm --cached . A mixed reset will remove your file from the index, without removing it from the working tree. See " Undo ' git add ' before commit ". In your case, a git stash would need to precede the git reset , and then a git stash pop would restore your changes in progress, after the reset. Regarding the ' deleted ' status after a git rm --cached , that command registers in the index the deletion of the file, which is why you see it recorded as 'deleted' for the next commit. The OP Ferpega insists : I am asking why the deleted status is there as resulting of git rm --cached because this command should has the same behavior than git reset HEAD <file> as you can see in git rm . Well, no, a git rm has not the same behavior as a [ git reset][8] . Both will affect the index, but: one (the git rm ) will record a file for deletion on the next commit, hence the ' deleted ' status, the other ( git reset ) will copy HEAD to the index, resetting said index back to what the file was in HEAD.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15455686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357618/']}
jdg_375400
stackexchange
llm_judgeable_groundtruth_similarity
122394
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The group-algebra of an abelian group is commutative, so we can consider the spectrum of this algebra. Are there any information about the abelian group that we can obtain from such considerations? That is to say, could we study abelian groups by considering the spectrum and the scheme of its group-algebra? Since I know nothing about the subject, any reference is mostly welcomed. Thanks in advance. P.S. I also posted in mathmatics stack exchange Here. Now provide the response and nothing else.
The spectrum of the group algebra of a commutative group is called a diagonalizable group scheme. This is defined in SGA 3 Exposé VIII Section 1. Several geometric characterizations of group-theoretic properties are given in Proposition 2.1. A lot more is written in later sections, such as material on principal homogeneous spaces, quotients of affine schemes by diagonalizable group schemes, and representability of restriction of scalars. If that isn't enough for you, Exposés 9-11 are about group schemes that are locally-on-the-base isomorphic to diagonalizable group schemes.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/122394', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11059/']}
jdg_375401
stackexchange
llm_judgeable_groundtruth_similarity
6314007
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 sanitize a filename. I would like to know of a way to remove all decimals from a files name except the last one. I need to keep the last one because the extension follows that. EXAMPLE: abc.def.ghij-klmnop.q234.mp3 This file should look like abcdefghij-klmnopq234.mp3 Some extensions are longer than 3 characters. Now provide the response and nothing else.
You can use a regex with a positive lookahead. Like this: $withdots = 'abc.def.ghij-klmnop.q234.mp3';$nodots = preg_replace('/\.(?=.*\.)/', '', $withdots); After executing the above, $nodots will contain abcdefghij-klmnopq234.mp3 . The regular expression is basically saying match all periods that are followed by another period. So the last period won't match. We replace all matches with an empty string, and we're left with the desired result.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6314007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684516/']}
jdg_375402
stackexchange
llm_judgeable_groundtruth_similarity
7076128
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: val map1 = Map(1 -> 9 , 2 -> 20)val map2 = Map(1 -> 100, 3 -> 300) I want to merge them, and sum the values of same keys. So the result will be: Map(2->20, 1->109, 3->300) Now I have 2 solutions: val list = map1.toList ++ map2.toListval merged = list.groupBy ( _._1) .map { case (k,v) => k -> v.map(_._2).sum } and val merged = (map1 /: map2) { case (map, (k,v)) => map + ( k -> (v + map.getOrElse(k, 0)) )} But I want to know if there are any better solutions. Now provide the response and nothing else.
Scalaz has the concept of a Semigroup which captures what you want to do here, and leads to arguably the shortest/cleanest solution: scala> import scalaz._import scalaz._scala> import Scalaz._import Scalaz._scala> val map1 = Map(1 -> 9 , 2 -> 20)map1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 9, 2 -> 20)scala> val map2 = Map(1 -> 100, 3 -> 300)map2: scala.collection.immutable.Map[Int,Int] = Map(1 -> 100, 3 -> 300)scala> map1 |+| map2res2: scala.collection.immutable.Map[Int,Int] = Map(1 -> 109, 3 -> 300, 2 -> 20) Specifically, the binary operator for Map[K, V] combines the keys of the maps, folding V 's semigroup operator over any duplicate values. The standard semigroup for Int uses the addition operator, so you get the sum of values for each duplicate key. Edit : A little more detail, as per user482745's request. Mathematically a semigroup is just a set of values, together with an operator that takes two values from that set, and produces another value from that set. So integers under addition are a semigroup, for example - the + operator combines two ints to make another int. You can also define a semigroup over the set of "all maps with a given key type and value type", so long as you can come up with some operation that combines two maps to produce a new one which is somehow the combination of the two inputs. If there are no keys that appear in both maps, this is trivial. If the same key exists in both maps, then we need to combine the two values that the key maps to. Hmm, haven't we just described an operator which combines two entities of the same type? This is why in Scalaz a semigroup for Map[K, V] exists if and only if a Semigroup for V exists - V 's semigroup is used to combine the values from two maps which are assigned to the same key. So because Int is the value type here, the "collision" on the 1 key is resolved by integer addition of the two mapped values (as that's what Int's semigroup operator does), hence 100 + 9 . If the values had been Strings, a collision would have resulted in string concatenation of the two mapped values (again, because that's what the semigroup operator for String does). (And interestingly, because string concatenation is not commutative - that is, "a" + "b" != "b" + "a" - the resulting semigroup operation isn't either. So map1 |+| map2 is different from map2 |+| map1 in the String case, but not in the Int case.)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7076128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']}
jdg_375403
stackexchange
llm_judgeable_groundtruth_similarity
54570788
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to get values from input fields put in to span elements. The input fields each have an id, those are in the array "tekstvelden". The spans each have a class, those are in the array "spans" function getValue(elementId) { return document.getElementById(elementId).value;};function schrijfVerhaal() { var tekstvelden = ['znw', 'bvn', 'bvn2', 'held', 'prinses']; var spans = ['znwT', 'bvnT', 'bvn2T', 'heldT', 'prinsesT']; tekstvelden.forEach(function(item, index) { var inhoudVeld = getValue(item); var spanClass = spans[index]; document.getElementsByClassName(spanClass).innerHTML = inhoudVeld; });}; Now provide the response and nothing else.
As I can see you're using Lombok . You think that you're not creating toString method, but Lombok doesn't think so. The @Data annotation causes generation of toString method. From Lombok documentation: @Data is a convenient shortcut annotation that bundles the features of @ToString , @EqualsAndHashCode , @Getter / @Setter and @RequiredArgsConstructor together: In other words, @Data generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans: getters for all fields, setters for all non-final fields, and appropriate toString, equals and hashCode implementations that involve the fields of the class, and a constructor that initializes all final fields, as well as all non-final fields with no initializer that have been marked with @NonNull , in order to ensure the field is never null. So Lombok created toString method for you which leads to infinite recursion. You can fix it by: @Data@ToString(exclude = "players")public class Team { // ...} Or: @Datapublic class Team { @OneToMany(mappedBy = "team") @ToString.Exclude private List<Player> players;} Worth to mention, if you still need include players in the Team 's toString representation, try to disassemble the @Data annotation and add only the parts you really need. Then define your own toString method.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54570788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11027505/']}
jdg_375404
stackexchange
llm_judgeable_groundtruth_similarity
49291121
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: New to this so please correct me if I am doing something wrong. I have a multiple image upload form that I cannot quite get to work in the way that I want it. Every time I upload an image it assigns the image a new name. I want to keep the name the same as the original. Any suggestions? Here is my code. <?phpif (isset($_POST['submit'])) { $j = 0; //Variable for indexing uploaded image $target_path = "images/"; //Declaring Path for uploaded imagesfor ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array $validextensions = array("jpeg", "jpg", "JPEG", "JPG", "png", "PNG"); //Extensions which are allowed $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) $file_extension = end($ext); //store extensions in the variable $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image $j = $j + 1;//increment the number of uploaded images according to the files in array if (($_FILES["file"]["size"][$i] < 300000000) //Approx. 100kb files can be uploaded. && in_array($file_extension, $validextensions)) { if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>'; } else {//if file was not moved. echo $j. ').<span id="error">please try again!.</span><br/><br/>'; } } else {//if file size and file type was incorrect. echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>'; } }} ?> I understand that this md5(uniqid()) is where it assigns the new id. I have tried lots of ways to stop this behaviour, but everything that I try just removes the name altogether. I would appreciate any help that is given, but please be aware that I am very new to PHP. Thanks Now provide the response and nothing else.
You do not need to specify the type ( "S" ) in your ExpressionAttributeValues because you are using the DynamoDB DocumentClient. Per the documentation : The document client simplifies working with items in Amazon DynamoDB by abstracting away the notion of attribute values. This abstraction annotates native JavaScript types supplied as input parameters, as well as converts annotated response data to native JavaScript types. It's only when you're using the raw DynamoDB object via new AWS.DynamoDB() that you need to specify the attribute types (i.e., the simple objects keyed on "S" , "N" , and so on). With DocumentClient , you should be able to use params like this: const params = { TableName: 'quotient-quotes', FilterExpression: '#cat = :cat', ExpressionAttributeNames: { '#cat': 'category', }, ExpressionAttributeValues: { ':cat': category, },}; Note that I also moved the field name into an ExpressionAttributeNames value just for consistency and safety. It's a good practice because certain field names may break your requests if you do not.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49291121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9494952/']}
jdg_375405
stackexchange
llm_judgeable_groundtruth_similarity
242217
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: The amplitudes of 2 SHM are scalors. When we combine the two SHM eq.(lying along the same line), the resultant expression becomes of amplitudes treated as vectors and the phase angle between them as the angle b/w the vectors. How can we add them vectorically if they are not vectors but scalors? Now provide the response and nothing else.
But what exactly is the physical meaning of reactive power? Essentially, reactive power is the component of power that has zero time average. For example, consider a load consisting of a resistance $R$ in parallel with an inductance $L$ driven by a source with voltage $v_S(t) = V_S\cos \omega t$ Clearly, the source current is $$i_S(t) = \frac{V_S}{R}\cos \omega t + \frac{V_S}{\omega L}\sin\omega t$$ Thus, the instantaneous power delivered by the source is $$p_S(t) = v_S\cdot i_S = \frac{(V_S)^2}{R}\cos^2 \omega t + \frac{(V_S)^2}{\omega L}\sin \omega t\cos \omega t$$ Carefully note that the first term is never negative which is to say that the flow of energy described by this term is always from source to load or never from load to source. However, the second term is positive over half of a cycle and negative the remaining half of a cycle. That is, this term describes energy that flows back and forth, in equal measure, between the source and load. Take the time average of the power over a period: $$\langle p_S\rangle = \frac{\omega}{\pi}\int_0^{\frac{\omega}{\pi}} p_S(\tau)\:\mathrm{d}\tau = \frac{1}{2}\frac{(V_S)^2}{R}$$ and see that only the first term has a non-zero time average; the second term does not contribute to the time average energy flow. In the context of phasor analysis, the real power (the real part of the complex power) is equal to the time average of the instantaneous power. The reactive power (the imaginary part of the complex power) is (proportional to) the amplitude of the second term in the instantaneous power. And this is the physical meaning of reactive power; it is a measure of the energy flow back and forth between source and load.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/242217', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/81224/']}
jdg_375406
stackexchange
llm_judgeable_groundtruth_similarity
28290163
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 replace my code with rx-java. (It is very small code.) It is finished and it works. But I want to know... Is it a good Rx style? If not good, please indicate bad point Below is my code that is api handling. before Random r = new Random();boolean apiResult = r.nextBoolean(); // it represents api result. ex. {"result": true} or {"result": false}if (apiResult == true) { // do something System.out.println("result:" + "success");} else { // do something System.out.println("result:" + "failure");} after Random r = new Random();Observable<Boolean> apiResultStream = Observable.create(new OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { // emit true or false subscriber.onNext(r.nextBoolean()); }}).cache(1);// I used filter for split. Is it Rx style?// success if true emitted.Observable<Boolean> successStream = apiResultStream .filter(aBoolean -> aBoolean == true); // here// failure if false emitted.Observable<Boolean> failureStream = apiResultStream .filter(aBoolean -> aBoolean == false); // here// success flowsuccessStream .flatMap(aBoolean -> Observable.just("success")) // and do something .subscribe(aString -> System.out.println("result:" + aString));// failure flowfailureStream .flatMap(aBoolean -> Observable.just("failure")) // and do something. // I want to keep subscriber. .subscribe(aString -> System.out.println("result:" + aString)); EDIT I almost replaced. thanks for good comment. (but I have a few non-replaced code. It have many callback and if statement.) I want to avoid 'callback hell'. The key is different result type between 'callSuccessApi' and 'callFailureApi' before rx // callback hell!callApi(new Callback<Result>(){ @Override public void success(Result result) { if (result.Response == true) { callSuccessApi(new Callback<ResultSuccess>(){ @Override public void success(ResultSuccess result) { // and more callbacks... } } } else { // result.Response == false callFailureApi(new Callback<ResultFailure>(){ @Override public void success(ResultFailure result) { // and more callbacks... } } } }} after with rx(avoid callback hell! Is it a good Rx style?) // change 1st api to observable.(I changed other api to observable)Observable<Result> apiResultStream = Observable.create(new OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { callApi(new Callback<Result>(){ @Override public void success(Result result) { subscriber.onNext(result); } }); }}).cache(1); // ensure same Observable<Result> for success and failure.// I used filter for split. Is it Rx style?// success if result.response == true.Observable<ResultSuccess> successStream = apiResultStream .filter(result -> result.response == true); // here// failure if result.response == false.Observable<ResultFailure> failureStream = apiResultStream .filter(result -> result.response == false); // here// success flow. callSuccessApi return Observable<ResultSuccess>successStream .flatMap(result -> callSuccessApi(result)) // and more api call with flatMap... .subscribe(resultSuccessN -> System.out.println("result:" + resultSuccessN.toString()));// failure flow. callFailureApi return Observable<ResultFailure>failureStream.flatMap(resultFailure -> callFailureApi(result)) // and more api call with flatMap... .subscribe(resultFailureN -> System.out.println("result:" + resultFailureN.toString())); sorry for my poor English and long question. Updated My Code I got 2 important information in this question.(thank you @Tomáš Dvořák, @Will whether it is a good way to go depends on the particular situation. There's nothing wrong with using an if statement within an map / flatmap / subscribe. updated code Observable<Result> apiResultStream = Observable.create(new OnSubscribe<Boolean>() { @Override public void call(Subscriber<? super Boolean> subscriber) { callApi(new Callback<Result>() { @Override public void success(Result result) { subscriber.onNext(result); } }); } }); // In this case, I used 'if' for simply and cleanly. apiResultStream .subscribe(result -> { if (result.response == true) { callSuccessApi(); // this line looks like 'callback'. but I used this for simply and cleanly. } else { callFailureApi(); } }); Now provide the response and nothing else.
There are loads of ways of doing this and it really depends on your use case. In general I wouldn't want to split into 2 streams, as that makes your code less readable. Also, I'm not sure what benefit you get from the flatMap call. There's nothing wrong with doing if stuff within a map call. Here are a few options: 1 - For adding logging (a bit like your print lines), I use doOnEach() apiResultStream .doOnEach(next -> { if (next) logger.info("Logging true " + next); else logger.info(Logging false " + next); }) .subscribe(.... 2 - The work you're doing is part of your stream, and you're going to want to do more work on the stream later - use map apiResultStream .map(next -> { if (next) doSomeCallWithNextWhenTrue(next); else doSomeCallwithNextWhenFalse(next); }) .subscribe(... 3 - If this is work you want to do at the end of the pipeline - IE after all transformational or other stream like work has completed, then do it in the subscribe call. apiResultStream .subscribe(next -> { if (next) doSomeCallWithNextWhenTrue(next); else doSomeCallwithNextWhenFalse(next); }); The problem is - with such a simple use case, it's difficult to suggest the best option, but I appreciate that in learning Rx, working out how to do conditional statements can seem confusing. In general, I just use map or flatMap when I'm calling another method that returns an Observable and do my logic in there. Update Still not sure why you're splitting your streams. Unless you start getting clever with different threads, the first subscribe call is going to block the second which is probably not what you want. Also, if you don't call subscribe more than once, then you don't need the cache() call. There's nothing wrong with using an if statement within an map / flatmap / subscribe . Especially if it makes your code more readable. I would do the following: apiResultStream .flatMap(result -> { if (result.response == true) { return callSuccessApi(result) } else { return callFailureApi(result) }) //Do any more calls you need .subscribe(... So much cleaner. I'm a bit confused by your System.out.println calls in subscribe. Is this there for debug or logging purposes? If so, just do that within the above flatMap in the if statement. Hope this helps, Will
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28290163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4335583/']}
jdg_375407
stackexchange
llm_judgeable_groundtruth_similarity
30638632
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 my element : <dom-module id="x-el"> <p class="special-paragraph">first paragraph</p> <content></content></dom-module> and I use it like <x-el> <p class="special-paragraph">second paragraph</p></x-el> in my imperative part: Polymer({ is: 'x-el', ready: function () { /* this will select all .special-paragraph in the light DOM e.g. 'second paragraph' */ Polymer.dom(this).querySelectorAll('.special-paragraph'); /* this will select all .special-paragraph in the local DOM e.g. 'first paragraph' */ Polymer.dom(this.root).querySelectorAll('.special-paragraph'); /* how can I select all .special-paragraph in both light DOM and local DOM ? */ }}); Is it possible to do that using Polymer built-in's ?Or should I use the default DOM api ? Now provide the response and nothing else.
Polymer does not provide a helper function or abstraction that will list nodes both from the light and local DOMs. If you require this functionality, you can use this.querySelector(selector) . On a side note, aside from the Polymer.dom(this.root).querySelectorAll(selector) method, Polymer also provides the $$ utility function which helps in accessing members of an element's local DOM. This function is used as follows: <dom-module id="my-element"> <template> <p class="special-paragraph">...</p> <content></content> </template></dom-module><script> Polymer({ is: 'my-element', ready: { this.$$('.special-paragraph'); // Will return the <p> in the local DOM } });</script> Note that, unlike querySelectorAll , the $$ function only returns one element: the first element in the local DOM which matches the selector.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30638632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/773595/']}
jdg_375408
stackexchange
llm_judgeable_groundtruth_similarity
593683
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Sometimes it's quite confusing when it comes to determining how to answer a probability question. Confusions always arise as of whether I should multiply/add or make conditional the probabilities. For example the following: Consider influenza epidemics for two parent heterosexual families.Suppose that the probability is 15% that at least one of the parentshas contracted the disease. The probability that the father hascontracted influenza is 10% while that the mother contracted thedisease is 9%. What is the probability that both contracted influenzaexpressed as a whole number percentage? Let P(F) = Probability that father catches it; P(M) for mother. I thought the P(both catch it) = P(F)P(M), but the answer is P(at least 1 catch it)= P(F)+P(M)-P(F AND M) and solve for P(F AND M). My first question is that: I find it particularly difficult to differentiate between addition or multiplication rule when it comes to probabilities from independent events. My second question is that: I'm also thinking if I'm to use P(at least 1 catch it)= P(F)+P(M)-P(F AND M), I would have make something like: P(at least 1 catch it)= P(F)P(NOT M)+P(M)P(NOT F)+P(F AND M). But it seems the P(F AND M) from two cases are not equivalent? Aren't these 2 expressions representing the same thing? My third question, even when I calculate P(at least 1 catch it) = 1-P(both not catching it) = 1-P(NOT F)*P(NOT M), P(at least 1 catch it) does not equal to .15 given in the question. What's wrong with my calculation? Are there any rules in governing which approach to use when solving a probability problem? Now provide the response and nothing else.
Let's follow up on GlenB's advice and make those Venn diagrams . We do this below with the heterosexual stereotype colours representing mother sick with red/pink and dad sick with blue. With the two variables mother and father you can create 4 different disjoint situations. father sick and not mom sicknot father sick and mom sick father sick and mom sicknot father sick and not mom sick It is with those 4 situations that you can perform additive computations. Intuitively you want to figure out how much the two situations mom sick and father sick overlap (those two may not need to be jisjoint) Your formula but the answer is P(at least 1 catch it)= P(F)+P(M)-P(F AND M) and solve for P(F AND M) Stems from the following algebra You can compare it to a situation with 4 unknowns (the area's/probability of the 4 disjoint pieces) and you try to figure out the values by means of 4 equations. You know mom sick0.09 = P(mom sick & not dad sick) + P(mom sick & dad sick) dad sick 0.10 = P(mom sick & dad sick) + P(not mom sick & dad sick) one or more sick 0.15 = P(mom sick & dad sick) + P(not mom sick & dad sick) + P(mom sick & dad sick) total probability must be one 1.00 = P(mom sick & dad sick) + P(not mom sick & dad sick) + P(mom sick & dad sick) + P(not mom sick & not dad sick) One final figure to explain the product and sum rule: When events are disjoint then you can use summation $$P(A \text{ or } B) = P(A) + P(B)$$ note that 'father sick' and 'mom sick' do not meed to be disjoint events. You still get a sum of those events in your solution, but that is due to algebra where we combine multiple equations. When events are independent then you can use the product $$P(A \text{ and } B) = P(A) \cdot P(B)$$ The independence means that the ratio's of the area's/probabilities are unaffected by the other variable. In the image you see the ratio's of 'mom sick' for different states of 'dad sick' whether or not dad is sick the ratio remains the same.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/593683', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/331633/']}
jdg_375409
stackexchange
llm_judgeable_groundtruth_similarity
32791684
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 web project in Visual Studio 2015 , and a few folders in it that I need, but don't really want being pulled into Visual Studio; These are your normal folders, node_modules , bower_components , etc. Nothing fancy about them. However I cannot find a way to "ignore" or "exclude" them. In the past, I could right click a folder and simply tell it to exclude it, and it worked; But since upgrading to VS2015, that option seems completely gone. I thought perhaps it was in the .gitignore , but tampered with that to no avail. Is there some new secret to this? Now provide the response and nothing else.
I've spent quite some time looking around for how to make NPM and bower work smooth with a website-project - and the main problem is that the node_modules-folder is so deeply nested. Causes all kinds of path-too-long-issues. This is with visual studio 2015 - website project created with older Visual Studio. If the Visual Studio project type is "web application", and you have a .project-file for your web project, you should be able to right click files/folders in the solution explorer, and select "exclude". However, if your Visual Studio project type is "website", there is no .project-file - you cannot exclude files and folders from Visual Studio. The trick is to set the hidden-attribute on files or folders with windows explorer - Visual Studio will then ignore them. Don't try to set hidden recursive on all subfolders - just the "outer" folder is fine. This worked fine for me for node_modules. NPM-integration and command line NPM still works. I also removed the read-only-attribute from the folder. If possible, consider converting your project to web application. Read more here: Other stack-overflow issue about website-type projects About web application project vs. website project About excluding items
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32791684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2796614/']}
jdg_375410
stackexchange
llm_judgeable_groundtruth_similarity
27497215
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 NSDictionary, I know it only has one key and one value, how can I directly get the first value from it? thanks, Now provide the response and nothing else.
If you have a Swift Dictionary and you know you have exactly 1 key/value pair you can do this: var dict = ["aaa":"bbb"]let v = dict.values.first! If you have more than 1 key/value pair then there is no "first" value since dictionaries are unordered. If you have no key/value pairs this will crash. If you have an NSDictionary , you can use allValues.first! , but you'll have to cast the result because the value will be an AnyObject : var dict:NSDictionary = ["aaa":"bbb"]let v = dict.allValues.first! as! String or: let v = dict.allValues[0] as! String
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27497215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4362380/']}
jdg_375411
stackexchange
llm_judgeable_groundtruth_similarity
44810706
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 some variables that Angular 4 uses to be different depending on whether I am running the app on the production server or on localhost for development. How can I do this? For node.js, I use environment variables but I am not sure if it is possible to use similar environment variables for an Angular web app. What is the best way to approach setting Angular to production without explicitly setting it then deploying? Now provide the response and nothing else.
If you called the enableProdMode() method for example in your main.ts file, you can import isDevMode from @angular/core to check if the angular app is running on prod mod or not. For example import { Component, isDevMode} from '@angular/core';@Component({...})export class HomePageComponent { constructor() { if(isDevMode()){ console.log("created new HomePageComponent"); } }} Thats one way to check the app mode. But something that is closer related to environment values are the environment files generated by the angular-cli. With those files you can configurate values that will be setted depending on the mode that you start the live server/build your source. You can find more info in the following link
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44810706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1851782/']}
jdg_375412
stackexchange
llm_judgeable_groundtruth_similarity
32003754
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hi Guys, I'm trying to solved this kind of form that when I clicked the submit button in a form the output will become image/picture and all the data that are in the fields will be compiled too in the image. I would love and appreciate your kindness if you could help me to solve this kind of problem. Please check image as my sample. Now provide the response and nothing else.
@atinder answer is way to go. Here is the example of the service: app.service('StoreService',function(){ var data1={}; var data2={}; this.save=function(data1,data2){ this.data1=data1; this.data2=data2; }; this.getData1=function(){ return data1; }; this.getData2=function(){ return data2; };}); Then in first controller: .controller('firstController',function(StoreService){ ..... StoreService.save(resp.data.data1,resp.data.data2); }); In second controller: .controller('secondController',function(StoreService,$scope){ $scope.data1 = StoreService.getData1(); $scope.data2 = StoreService.getData2(); });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32003754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2737388/']}
jdg_375413
stackexchange
llm_judgeable_groundtruth_similarity
2901767
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My logcat window in Eclipse only displays the first few lines of the StackTrace for each exception. This means that I often can't see where an exception occured. Is there any way to change this setting? Now provide the response and nothing else.
If you're referring to the "...12 more lines..." part, you only see that for exceptions that were the cause of another exception. If the top part of the stack trace is the same as the earlier trace, the full set of frames is only shown for the outermost exception, and the other traces get the "..." treatment. Put another way, the chunk of a trace that isn't shown is a duplicate of a trace that appeared earlier in the exception cause chain. For example, suppose I have code where the method main() calls one() , which calls two() , and so on. four() throws an exception. two() catches it and re-throws it. The exception will look like this: java.lang.RuntimeException: re-throw at Foo.two(Foo.java:14) at Foo.one(Foo.java:7) at Foo.main(Foo.java:3) at dalvik.system.NativeStart.main(Native Method)Caused by: java.lang.RuntimeException: first at Foo.four(Foo.java:23) at Foo.three(Foo.java:19) at Foo.two(Foo.java:12) ... 3 more The "caused by" exception says "... 3 more" rather than explicitly listing one() , main() , and dalvik.system.NativeStart.main . So to get the full trace of the initial exception, you would start by reading its trace, then continue at the trace above. Note there is no overlap -- two() appears in both, but in the "first" trace it's on the call to three() , and in the "re-throw" trace it's on the throw instruction.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2901767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165495/']}
jdg_375414
stackexchange
llm_judgeable_groundtruth_similarity
1262038
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 need to replace Microsoft Word's version of single and double quotations marks ( “ ” ‘ ’ ) with regular quotes (' and ") due to an encoding issue in my application. I do not need them to be HTML entities and I cannot change my database schema. I have two options: to use either a regular expression or an associated array. Is there a better way to do this? Now provide the response and nothing else.
Considering you only want to replace a few specific and well identified characters, I would go for str_replace with an array: you obviously don't need the heavy artillery regex will bring you ;-) And if you encounter some other special characters (damn copy-paste from Microsoft Word...), you can just add them to that array whenever is necessary / whenever they are identified. The best answer I can give to your comment is probably this link: Convert Smart Quotes with PHP And the associated code (quoting that page) : function convert_smart_quotes($string) { $search = array(chr(145), chr(146), chr(147), chr(148), chr(151)); $replace = array("'", "'", '"', '"', '-'); return str_replace($search, $replace, $string); } (I don't have Microsoft Word on this computer, so I can't test by myself) I don't remember exactly what we used at work (I was not the one having to deal with that kind of input) , but it was the same kind of stuff...
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1262038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3467/']}
jdg_375415
stackexchange
llm_judgeable_groundtruth_similarity
138877
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 just starting out using sed and I intend to use it to extract IP addresses from ping output. Here's what I am trying to achieve exactly: input text: ytmti (192.188.2.3) jjggy desired output: 192.188.2.3 command I am trying: echo "ytmti (192.188.2.3) jjggy" | sed 's:\((\(192.188.2.3\))\):\2:' current output: ytmti 192.188.2.3 jjggy Note: ytmti and jjggy are really stand-ins for text like Pinging unix.stackexchange.com and with 32 bytes of data: . I think using awk might be a better solution for parsing ping output,but I would like to get accustomed to sed . Now provide the response and nothing else.
The substitution command of sed replaces all characters matched in first section with all character of second section, so you will need .* or similar and group only the part to save, like: echo " ytmti (192.188.2.3) jjggy" | sed 's:^.*(\([^)]*\).*$:\1:' Note that I use [^)]* that avoids to hardcode the IP and generalize it for any of them. It yields: 192.188.2.3
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/138877', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/72594/']}
jdg_375416
stackexchange
llm_judgeable_groundtruth_similarity
17409227
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to get my followers count number with PHP. I found this answer here: Twitter follower count number , but it is not working because API 1.0 is no longer active. I have also tried with API 1.1 using this URL: https://api.twitter.com/1.1/users/lookup.json?screen_name=google but is is showing an error(Bad Authentication data). Here is my code: $data = json_decode(file_get_contents('http://api.twitter.com/1.1/users/lookup.json?screen_name=google'), true);echo $data[0]['followers_count']; Now provide the response and nothing else.
Twitter API 1.0 is deprecated and is no longer active. With the REST 1.1 API , you need oAuth authentication to retrieve data from Twitter. Use this instead: <?php require_once('TwitterAPIExchange.php'); //get it from https://github.com/J7mbo/twitter-api-php/** Set access tokens here - see: https://dev.twitter.com/apps/ **/$settings = array('oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",'consumer_key' => "YOUR_CONSUMER_KEY",'consumer_secret' => "YOUR_CONSUMER_SECRET");$ta_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';$getfield = '?screen_name=REPLACE_ME';$requestMethod = 'GET';$twitter = new TwitterAPIExchange($settings);$follow_count=$twitter->setGetfield($getfield)->buildOauth($ta_url, $requestMethod)->performRequest();$data = json_decode($follow_count, true);$followers_count=$data[0]['user']['followers_count'];echo $followers_count;?> Parsing the XML might be easier in some cases. Here's a solution (tested): <?php $xml = new SimpleXMLElement(urlencode(strip_tags('https://twitter.com/users/google.xml')), null, true);echo "Follower count: ".$xml->followers_count;?> Hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17409227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1354378/']}
jdg_375417
stackexchange
llm_judgeable_groundtruth_similarity
7733693
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 far I have the following code: colors = ('k','r','b')ax = []for i in range(3): ax.append(plt.axes()) plt.plot(datamatrix[:,0],datamatrix[:,i],colors[i]+'o') ax[i].set(autoscale_on=True) With the autoscale_on=True option for each axis, I thought each plot should have its own y-axis limits, but it appears they all share the same value (even if they share different axes). How do I set them to scale to show the range of each datamatrix[:,i] (just an explicit call to .set_ylim() ?) And also, how can I create an offset y-axis for the third variable ( datamatrix[:,2] ) that might be required above? Thanks all. Now provide the response and nothing else.
It sounds like what you're wanting is subplots... What you're doing now doesn't make much sense (Or I'm very confused by your code snippet, at any rate...). Try something more like this: import matplotlib.pyplot as pltimport numpy as npfig, axes = plt.subplots(nrows=3)colors = ('k', 'r', 'b')for ax, color in zip(axes, colors): data = np.random.random(1) * np.random.random(10) ax.plot(data, marker='o', linestyle='none', color=color)plt.show() Edit: If you don't want subplots, your code snippet makes a lot more sense. You're trying to add three axes right on top of each other. Matplotlib is recognizing that there's already a subplot in that exactly size and location on the figure, and so it's returning the same axes object each time. In other words, if you look at your list ax , you'll see that they're all the same object . If you really want to do that, you'll need to reset fig._seen to an empty dict each time you add an axes. You probably don't really want to do that, however. Instead of putting three independent plots over each other, have a look at using twinx instead. E.g. import matplotlib.pyplot as pltimport numpy as np# To make things reproducible...np.random.seed(1977)fig, ax = plt.subplots()# Twin the x-axis twice to make independent y-axes.axes = [ax, ax.twinx(), ax.twinx()]# Make some space on the right side for the extra y-axis.fig.subplots_adjust(right=0.75)# Move the last y-axis spine over to the right by 20% of the width of the axesaxes[-1].spines['right'].set_position(('axes', 1.2))# To make the border of the right-most axis visible, we need to turn the frame# on. This hides the other plots, however, so we need to turn its fill off.axes[-1].set_frame_on(True)axes[-1].patch.set_visible(False)# And finally we get to plot things...colors = ('Green', 'Red', 'Blue')for ax, color in zip(axes, colors): data = np.random.random(1) * np.random.random(10) ax.plot(data, marker='o', linestyle='none', color=color) ax.set_ylabel('%s Thing' % color, color=color) ax.tick_params(axis='y', colors=color)axes[0].set_xlabel('X-axis')plt.show()
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7733693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143476/']}
jdg_375418
stackexchange
llm_judgeable_groundtruth_similarity
452459
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: The symbol for an inverter (logic gate) is usually the one shown below left. But I have sometimes seen the symbol shown below right. (See, for example, the last image in this answer .) What does this difference in symbols represent? Now provide the response and nothing else.
Both symbols have the equation Q = not A. The difference in symbols is conceptual, it's to aid understanding. The circle (often called a 'bubble') represents inversion. The first symbol is a classical inverter. The output changes to the inverse of the input. The second symbol is often seen as part of a larger function, where the output of this gate goes to enable or trigger some functionality, and the external line for that is active low. When one quickly scans the symbol, it's apparent which are the active low inputs, and which are active high. For instance, in this 74138 3 to 8 line decoder , some of the 'address' or enable inputs are bubbled, and some are plain. It's then very easy to scan the connections to the address bus and see which need to be low and which high to enable. It's also seen in the output decoder, where the output 'NAND' gates have all both inputs and outputs 'bubbled'/'notted', indicating active low logic. Although somebody flexing their muscles on boolean logic might be tempted to replace those output gates with positive logic NOR gates, they are conceptually better as NANDs where all inputs and outputs are active low, because the outputs become active when both inputs are active. The concept of adding bubbles at odd places in the diagram can help in designing logic where you need to change a logical diagram into one that can be implemented with the available stuff in your junk box. I frequently throw down a bunch of gates to express my desired logic function. On any line, if I add a bubble at both start and finish of the line, the function remains unaltered. However I can then see what gates 'want to' become NORs or NANDs, and flip between one type of gate and the bubbled opposite.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/452459', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/8090/']}
jdg_375419
stackexchange
llm_judgeable_groundtruth_similarity
845135
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: $$\lim_{p\rightarrow\infty}\int_0^1e^{-px}(\cos x)^2\text{d}x$$I tried to prove the integrand is uniformly convergent so that the limit and integral can be exchanged. But I failed. Any ideas? Now provide the response and nothing else.
There is no need for uniform convergence; using dominated convergence will do the job just fine. In fact, this is not uniform convergence at all (remember that the uniform convergence of a continuous function is continuous, but this is not the case, as the function it converges to has a discontinuity at $x=0$). Also, if you cannot use dominated convergence, even the squeeze theorem will do. We have$$\begin{align}0 \leq \int\limits_{0}^{1} e^{-px}(\cos(x))^{2}\;\mathrm{d}x &\leq \int\limits_{0}^{1} e^{-px}\;\mathrm{d}x \\&=\left. \frac{-e^{-px}}{p} \right|_{x=0}^{1} \\[5pt]&=\frac{1}{p} - \frac{e^{-p}}{p}\end{align}$$Now $\lim\limits_{p\rightarrow\infty}\frac{e^{-p}}{p}=0$ using L'Hopital, so this does indeed squeeze in.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/845135', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/159772/']}
jdg_375420
stackexchange
llm_judgeable_groundtruth_similarity
29166402
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 verify if a youtube video (with the id_video) is valid/exist , using the youtube api V3. That's what i do (y2oy7b4SFgE is the id of the video i test): $file_headers = @get_headers('https://www.googleapis.com/youtube/v3/videos?part=id&id=y2oy7b4SFgE&key=ma_clé_api_publique'); //exit(var_dump($file_headers));if ($file_headers[0] == 'HTTP/1.0 200 OK') { $resultat = $file_headers[0].'Goood'} else { $resultat = $file_headers[0].'PasGoood'} But i have a "code": 403,"message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed." Its working well when no referer. But when i put one, i tried with the name of my website or with the ip of my vps server, each time it doesn'work. Now provide the response and nothing else.
There are two ways I am aware of to check if a video exists using the YouTube video id. The simplest is to use the oembed url for the video. This requires no authentication and returns a 404 header when the video is invalid. You should really be doing this with curl, as depending on your setup file_get_contents may not be an option for you... $headers = get_headers('https://www.youtube.com/oembed?format=json&url=http://www.youtube.com/watch?v=' . $videoID);if(is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false){ // video exists} else { // video does not exist} The second is to use V3 of the data api . To use this method you will need to generate an api key in the developer console. $response = file_get__contents('https://www.googleapis.com/youtube/v3/videos?part=id&id=' . $videoID . '&key=' . $apiPublicKey);$json = json_decode($response);if (sizeof($json['items'])) { // video exists} else { // video does not exist}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29166402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3417911/']}
jdg_375421
stackexchange
llm_judgeable_groundtruth_similarity
49704497
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 facing difficulties to make it responsive according to various screen sizes. How to make it responsive? @override Widget build(BuildContext context) { return new Container( decoration: new BoxDecoration(color: Colors.white), child: new Stack( children: [ new Padding( padding: const EdgeInsets.only(bottom: 350.0), child: new GradientAppBar(" "), ), new Positioned( bottom: 150.0, height: 260.0, left: 10.0, right: 10.0, child: new Padding( padding: new EdgeInsets.all(10.0), child: new Card( child: new Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ const ListTile( title: const Text( 'LOGIN', textAlign: TextAlign.center, style: const TextStyle( fontSize: 16.50, fontFamily: "Helvetica", fontWeight: FontWeight.bold, color: Colors.black87, letterSpacing: 1.00, ), ), ), new ListTile( leading: const Icon(Icons.person), title: new TextField( controller: _user1, decoration: new InputDecoration( labelText: ' Enter a username'), ), ), new ListTile( leading: const Icon(Icons.person_pin), title: new TextField( controller: _pass1, decoration: new InputDecoration( labelText: ' Enter a password'), obscureText: true, ), ), ], ), ), ), ), new Positioned( bottom: 70.0, left: 15.0, right: 05.0, child: new ButtonTheme.bar( // make buttons use the appropriate styles for cards child: new ButtonBar( children: <Widget>[ new FlatButton( padding: new EdgeInsets.only(right: 13.0), child: new Text( 'REGISTER HERE', style: new TextStyle( color: Colors.black87, fontFamily: "Helvetica", fontSize: 15.00, fontWeight: FontWeight.bold), ), onPressed: () { Navigator.of(context).pushNamed('/facebook'); }, ), new FlatButton( padding: new EdgeInsets.only(right: 22.0), child: new Text( 'FORGOT PASSWORD?', style: new TextStyle( color: Colors.black87, fontFamily: "Helvetica", fontSize: 15.00, fontWeight: FontWeight.bold), ), onPressed: () { Navigator.of(context).pushNamed('/Forgot'); }, ), ], ), ), ), new Positioned( bottom: 73.0, height: 180.0, left: 20.0, right: 52.0, child: new Padding( padding: new EdgeInsets.all(0.00), child: new ButtonTheme( minWidth: 10.0, height: 20.0, padding: new EdgeInsets.only(right: 37.0), child: new ButtonBar(children: <Widget>[ new CupertinoButton( borderRadius: const BorderRadius.all(const Radius.circular(36.0)), padding: new EdgeInsets.only(left: 70.0), color: const Color(0xFF426DB7), child: new Text( " LOGIN ", style: new TextStyle( color: Colors.white, fontSize: 12.50, fontFamily: "Handwriting", fontWeight: FontWeight.w500, letterSpacing: 0.00), ), onPressed: () {}) ]), ), ), ), ], ), ); }} Now provide the response and nothing else.
Using MediaQuery class: MediaQueryData queryData;queryData = MediaQuery.of(context); MediaQuery : Establishes a subtree in which media queries resolveto the given data. MediaQueryData : Information about a piece of media (e.g., awindow). To get Device Pixel Ratio: queryData.devicePixelRatio To get width and height of the device screen: queryData.size.widthqueryData.size.height To get text scale factor: queryData.textScaleFactor Using AspectRatio class: From doc: A widget that attempts to size the child to a specific aspect ratio. The widget first tries the largest width permitted by the layoutconstraints. The height of the widget is determined by applying thegiven aspect ratio to the width, expressed as a ratio of width toheight. For example, a 16:9 width:height aspect ratio would have a value of16.0/9.0. If the maximum width is infinite, the initial width is determined by applying the aspect ratio to the maximum height. Now consider a second example, this time with an aspect ratio of 2.0and layout constraints that require the width to be between 0.0 and100.0 and the height to be between 0.0 and 100.0. We'll select a width of 100.0 (the biggest allowed) and a height of 50.0 (to match theaspect ratio). //examplenew Center( child: new AspectRatio( aspectRatio: 100 / 100, child: new Container( decoration: new BoxDecoration( shape: BoxShape.rectangle, color: Colors.orange, ) ), ),), Also you can use : LayoutBuilder FittedBox CustomMultiChildLayout
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/49704497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6584292/']}
jdg_375422
stackexchange
llm_judgeable_groundtruth_similarity
49752149
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 get a date from a JSON API which looks like this "2018-04-10T04:00:00.000Z". I want to convert it in order to obtain a Date or String object and get something like "01-04-2018" that its "dd-MM-YYYY". How can I do it? Now provide the response and nothing else.
Update: Using DateTimeFormat , introduced in java 8: The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter. Your input format looks quite standard, except the trailing Z . Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" . The trailing 'Z' is the interesting part. Usually there's time zone data here, like -0700 . So the pattern would be ...Z , i.e. without apostrophes. The output format is way more simple: "dd-MM-yyyy" . Mind the small y -s. Here is the example code: DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);String formattedDate = outputFormatter.format(date);System.out.println(formattedDate); // prints 10-04-2018 Original answer - with old API SimpleDateFormat SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");String formattedDate = outputFormat.format(date);System.out.println(formattedDate); // prints 10-04-2018
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/49752149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9605869/']}
jdg_375423
stackexchange
llm_judgeable_groundtruth_similarity
6152442
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a listview of all the contact names in the phone. I want to get the email id (if contact have one) of the contact which I click on in the listview. How can I do this? Now provide the response and nothing else.
Use the following code to get all email ids. I checked the code. It is working. public static void getContactEmails(Context context) { String emailIdOfContact = null; int emailType = Email.TYPE_WORK; String contactName = null; ContentResolver cr = context.getContentResolver(); Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (cur.getCount() > 0) { while (cur.moveToNext()) { String id = cur.getString(cur .getColumnIndex(BaseColumns._ID)); contactName = cur .getString(cur .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); // Log.i(TAG,"....contact name....." + // contactName); cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null); Cursor emails = cr.query(Email.CONTENT_URI, null, Email.CONTACT_ID + " = " + id, null, null); while (emails.moveToNext()) { emailIdOfContact = emails.getString(emails .getColumnIndex(Email.DATA)); // Log.i(TAG,"...COntact Name ...." // + contactName + "...contact Number..." // + emailIdOfContact); emailType = emails.getInt(emails .getColumnIndex(Phone.TYPE)); } emails.close(); } }// end of contact name cursor cur.close(); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6152442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/437833/']}
jdg_375424
stackexchange
llm_judgeable_groundtruth_similarity
815910
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Almost any working PHP programmer has faced having to use CURL to send raw HTTP requests, whether it's for credit card payment processing, nefarious screen scraping, or something in-between. Almost any forum where PHP programmers congregate has a large number of people who can't get the cURL functions to do what they want . When cURL isn't working for you, what troubleshooting techniques do you use to figure out why it isn't working? What weird gotchas with PHP's curl implementation have you run into? If someone asks a "HALP MY CURL IZ BROKEN" question on a forum, what are the steps you take to figure out why their request isn't working? Now provide the response and nothing else.
I find the CURLINFO_HEADER_OUT option to be very useful. <?php$curl = curl_init('http://www.php.net');curl_setopt($curl, CURLOPT_HEADERFUNCTION, 'dbg_curl_data');curl_setopt($curl, CURLOPT_WRITEFUNCTION, 'dbg_curl_data');curl_setopt($curl, CURLINFO_HEADER_OUT, true);curl_exec($curl);echo '<fieldset><legend>request headers</legend> <pre>', htmlspecialchars(curl_getinfo($curl, CURLINFO_HEADER_OUT)), '</pre></fieldset>';echo '<fieldset><legend>response</legend> <pre>', htmlspecialchars(dbg_curl_data(null)), '</pre></fieldset>';function dbg_curl_data($curl, $data=null) { static $buffer = ''; if ( is_null($curl) ) { $r = $buffer; $buffer = ''; return $r; } else { $buffer .= $data; return strlen($data); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/815910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4668/']}
jdg_375425
stackexchange
llm_judgeable_groundtruth_similarity
2528226
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: So, I have a function $$ f(x, y) = x^2-4xy+4y^2 $$ subject to constraint $$ g(x, y) = x^2+y^2 = 1 $$The task asks to find the maxima and minima values using Lagrangian. I found the gradients: $ \begin{equation} \nabla f(x, y) = (2x-4y, -4x+8y)\end{equation} $ and $ \begin{equation} \nabla g(x, y) = (2x, 2y)\end{equation} $ Solving for the system $$ \begin{cases} 2x-4y=2\lambda x \newline -4x+8y=2\lambda y \newline x^2+y^2=1 \end{cases} $$ I decided to take an eigenvalue approach to obtain values for $\lambda$:$$A=\begin{bmatrix}1-\lambda & -2\\-1\over2 & 1-\lambda\\\end{bmatrix}$$We obtain $\lambda_{1,2}=0,2$. Substituting them into our system we get:$\begin{equation} x=2y\end{equation} $ for the case of $\lambda_1=0$ and $\begin{equation} x=-2y \end{equation} $ for the case of $\begin{equation} \lambda_2=2\end{equation} $ I have no idea how to proceed from here, since I am not really getting good-looking values of $x$ and $y$. I am quite confused. Any feedback along with correction of mistakes would be highly appreciated. Now provide the response and nothing else.
You can read the binary digits of $\arccos(x)/\pi$ off the signs of $2\cos(2^kx)$, which is an easy to compute sequence defined recursively with $x_{n+1} = x_n^2-2$. More precisely, you put a $1$ digit when the product of the signs so far is negative, and a $0$ otherwise : $\begin{matrix}x_0 & -1/2 & - & - \\ x_1 &-7/4 & - & + \\ x_2 & 17/16 & + & + \\x_3 & -223/256 & - & - \end{matrix}$ Now this starts getting hard because squareing $3$ digits number is a lot of hard work, so let me roughly approximate the fractions with $2$ digit numerators and denominators. $\begin{matrix} -23/25 & & & \le x_3 \le & & & -11/13 & - & - \\ -11/8 & \le & -217/169 & \le x_4 \le & -721/625 & \le& -8/7 & - & + \\ -34/49 & \le & -34/49 & \le x_5 \le & -7/64 & \le & -7/64 & - & - \\-2 & \le & -8143/4096 & \le x_6 \le & -3646/2401 & \le & -36/25 & - & + \\4/63 & \le & 46/625 & \le x_7 \le & 2 & \le & 2 & + & + \\ \end{matrix}$ And now this is too imprecise to continue. So far I got the cumulative sign sequence $(-,+,+,-,+,-,+,+)$ and so the angle is between $(2^{-1}+2^{-4}+2^{-6})\pi$ and $(2^{-1}+2^{-4}+2^{-6}+2^{-8})\pi$ In degrees you replace $\pi$ with $180$, so those are $104.06\ldots$ and $104.77\ldots$ The recurrence follows from the addition formula : $2\cos(2x) = 2\cos^2(x)-2\sin^2(x) = 4\cos^2(x)-2 = (2\cos(x))^2-2$ Suppose you call $a_n \in [0 ; \pi]$ the angle whose cosine is $2x_n$.If $x_n\ge 0$ then $a_n \in [0 ; \pi/2] $ and then $a_{n+1} = 2a_n$, so the binary digits of $a_n/\pi$ are $.0$ followed with the binary digits of $a_{n+1}/\pi$ If $x_n \le 0$ then $a_n \in [\pi/2 ; \pi]$ and then $a_{n+1} = 2\pi-2a_n$, so the binary digits of $a_n/\pi$ are $.1$ followed with the inverted binary digits of $a_{n+1}/\pi$ Thus $a_{n+1} = \pm 2 a_n \mod {2\pi}$, and by induction, $a_n = \pm 2^n a_0 \pmod {2\pi}$ where the signdepends on the parity of the number of negative $x_k$ encountered for $0 \le k < n$. The $n$th digit is $0$ if and only if $2^n a_0 \in [0 ; \pi] \pmod {2\pi}$, which means $\pm a_n \in [0;\pi] \pmod {2\pi}$ with the same sign. But since $a_n \in [0;\pi]$, the digit is $0$ if the sign was $+$ and it is $1$ is the sign was $-$. And so the $n$th binary digit correspond to the parity of the number of negative cosines encountered for $0 \le k < n$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2528226', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/338239/']}
jdg_375426
stackexchange
llm_judgeable_groundtruth_similarity
771878
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to configure nginx on AWS Linux. I can get it working for one site, but when I try to add another I continually receive the following error: nginx: [crit] pread() "/home/ec2-user/public/sites/example.com" failed (21: Is a directory) This is my nginx.conf : user nginx;worker_processes auto;error_log /var/log/nginx/error.log;pid /var/run/nginx.pid;events { worker_connections 1024;}http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; include /home/ec2-user/public/sites/*; default_type application/octet-stream; include /etc/nginx/conf.d/*.conf; index index.html index.htm; server { listen 80 default_server; listen [::]:80 default_server; server_name localhost example.es www.example.es; root /home/ec2-user/public/sites/es-example; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } server { listen 80; listen [::]:80; server_name example.com www.example.com; root /home/ec2-user/public/sites/en-example; location / { } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }} Both directories example.com and example.es have an index.html . The permissions for both directories are as follows. -rwxr-xr-x 1 ec2-user ec2-user Any ideas? Thanks! Now provide the response and nothing else.
The problem is with this line: include /home/ec2-user/public/sites/*; The directive above is used by nginx to load/include additional configuration options. Only proper nginx configuration files should be placed under /home/ec2-user/public/sites/ If you place there also directories or site (content) files nginx won't be able to include them. Please check the nginx documentation http://nginx.org/en/docs/ngx_core_module.html#include
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/771878', 'https://serverfault.com', 'https://serverfault.com/users/350614/']}
jdg_375427
stackexchange
llm_judgeable_groundtruth_similarity
48821725
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I use xmltodict to load the xml file below I get an error:xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 1 Here is my file: <?xml version="1.0" encoding="utf-8"?><mydocument has="an attribute"> <and> <many>elements</many> <many>more elements</many> </and> <plus a="complex"> element as well </plus></mydocument> Source: import xmltodictwith open('fileTEST.xml') as fd: xmltodict.parse(fd.read()) I am on Windows 10, using Python 3.6 and xmltodict 0.11.0 If I use ElementTree it works tree = ET.ElementTree(file='fileTEST.xml') for elem in tree.iter(): print(elem.tag, elem.attrib)mydocument {'has': 'an attribute'}and {}many {}many {}plus {'a': 'complex'} Note: I might have encountered a new line problem. Note2: I used Beyond Compare on two different files. It crashes on the file that is UTF-8 BOM encoded, and works om the UTF-8 file. UTF-8 BOM is a sequence of bytes (EF BB BF) that allows the reader to identify a file as being encoded in UTF-8. Now provide the response and nothing else.
I think you forgot to define the encoding type.I suggest that you try to initialize that xml file to a string variable: import xml.etree.ElementTree as ETimport xmltodictimport jsontree = ET.parse('your_data.xml')xml_data = tree.getroot()#here you can change the encoding type to be able to set it to the one you needxmlstr = ET.tostring(xml_data, encoding='utf-8', method='xml')data_dict = dict(xmltodict.parse(xmlstr))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48821725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/294569/']}
jdg_375428
stackexchange
llm_judgeable_groundtruth_similarity
4168772
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was reading through the java.util.concurrent API , and found that CountDownLatch : A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. CyclicBarrier : A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. To me both seems equal, but I am sure there is much more to it. For example, in CoundownLatch, the countdown value could not be reset, that can happen in the case of CyclicBarrier . Is there any other difference between the two? What are the use cases where someone would want to reset the value of countdown? Now provide the response and nothing else.
One major difference is that CyclicBarrier takes an (optional) Runnable task which is run once the common barrier condition is met. It also allows you to get the number of clients waiting at the barrier and the number required to trigger the barrier. Once triggered the barrier is reset and can be used again. For simple use cases - services starting etc... a CountdownLatch is fine. A CyclicBarrier is useful for more complex co-ordination tasks. An example of such a thing would be parallel computation - where multiple subtasks are involved in the computation - kind of like MapReduce .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4168772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/379235/']}
jdg_375429
stackexchange
llm_judgeable_groundtruth_similarity
2575404
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Sorry for this dumb question on Asynchronous operations. This is how I understand it. IIS has a limited set of worker threads waiting for requests. If one request is a long running operation, it will block that thread. This leads to fewer threads to serve requests. Way to fix this - use asynchronous pages. When a request comes in, the main worker thread is freed and this other thread is created in some other place. The main thread is thus able to serve other requests. When the request completes on this other thread, another thread is picked from the main thread pool and the response is sent back to the client. 1) Where are these other threads located? Is there another thread pool? 2) IF ASP.NET likes creating new threads in this other thread pool(?), why not increase the number of threads in the main worker pool - they are all running on the same machine anyway? I don't see the advantage of moving that request to this other thread pool. Memory/CPU should be the same right? 3) If the main thread hands off a request to this other thread, why does the request not get disconnected? It magically hands off the request to another worker thread somewhere else and when the long running process completes, it picks a thread from the main worker pool and sends response to the client. I am amazed...but how does that work? Now provide the response and nothing else.
You didn't say which version of IIS or ASP.NET you're using. A lot of folks talk about IIS and ASP.NET as if they are one and the same, but they really are two components working together. Note that IIS 6 and 7 listen to an I/O completion port where they pick up completions from HTTP.sys. The IIS thread pool is used for this, and it has a maximum thread count of 256. This thread pool is designed in such a way that it does not handle long running tasks well. The recommendation from the IIS team is to switch to another thread if you're going to do substantial work, such as done by the ASP.NET ISAPI and/or ASP.NET "integrated mode" handler on IIS 7. Otherwise you will tie up IIS threads and prevent IIS from picking up completions from HTTP.sys Chances are you don't care about any of this, because you're not writing native code, that is, you're not writing an ISAPI or native handler for the IIS 7 pipeline. You're probably just using ASP.NET, in which case you're more interested in its thread pool and how it works. There is a blog post at http://blogs.msdn.com/tmarq/archive/2007/07/21/asp-net-thread-usage-on-iis-7-0-and-6-0.aspx that explains how ASP.NET uses threads. Note that for ASP.NET v2.0 and v3.5 on IIS 7 you should increase MaxConcurrentRequestsPerCPU to 5000--it is a bug that it was set to 12 by default on those platforms. The new default for MaxConcurrentRequestsPerCPU in ASP.NET v4.0 on IIS 7 is 5000. To answer your three questions: 1) First, a little primer. Only 1 thread per CPU can execute at a time. When you have more than this, you pay a penalty--a context switch is necessary every time the CPU switches to another thread, and these are expensive. However, if a thread is blocked waiting on work...then it makes sense to switch to another thread, one that can execute now. So if I have a thread that is doing a lot of computational work and using the CPU heavily, and this takes a long time, should I switch to another thread? No! The current thread is efficiently using the CPU, so switching will only incur the cost of a context switch. So if I have a thread that makes an HTTP or SOAP request to another server and takes a long time, should I switch threads? Yes! You can perform the HTTP or SOAP request asynchronously, so that once the "send" has occurred, you can unwind the current thread and not use any threads until there is an I/O completion for the "receive". Between the "send" and the "receive", the remote server is busy, so locally you don't need to be blocking on a thread, but instead make use of the async APIs provided in .NET Framework so that you can unwind and be notified upon completion. Ok, so you're #1 questions was "Where are these other threads located? Is there another thread pool?" This depends. Most code that runs in .NET Framework uses the CLR ThreadPool, which consists of two types of threads, worker threads and i/o completion threads. What about code that doesn't use CLR ThreadPool? Well, it can create its own threads, use its own thread pool, or whatever it wants because it has access to the Win32 APIs provided by the operating system. Based on what we discussed a bit ago, it really doesn't matter where the thread comes from, and a thread is a thread as far as the operating system and hardware is concerned. 2) In your second question, you state, "I don't see the advantage of moving that request to this other thread pool." You're correct in thinking that there is NO advantage to switching unless you're going to make up for that costly context switch you just performed in order to switch. That's why I gave an example of a slow HTTP or SOAP request to a remote server as an example of a good reason to switch. And by the way, ASP.NET does not create any threads. It uses the CLR ThreadPool, and the threads in that pool are entirely managed by the CLR. They do a pretty good job of determining when you need more threads. For example, that's why ASP.NET can easily scale from executing 1 request concurrently to executing 300 requests concurrently, without doing anything. The incoming requests are posted to the CLR ThreadPool via a call to QueueUserWorkItem, and the CLR decides when to call the WaitCallback (see MSDN). 3) The third question is, "If the main thread hands off a request to this other thread, why does the request not get disconnected?" Well, IIS picks up the I/O completion from HTTP.sys when the request initially arrives at the server. IIS then invokes ASP.NET's handler (or ISAPI). ASP.NET immediately queues the request to the CLR Threadpool, and returns a pending status to IIS. This pending status tells IIS that we're not done yet, but as soon as we are done we'll let you know. Now ASP.NET manages the life of that request. When a CLR ThreadPool thread invokes the ASP.NET WaitCallback (see MSDN), it can execute the entire request on that thread, which is the normal case. Or it can switch to one or more other threads if the request is what we call asynchronous--i.e. it has an asynchronous module or handler. Either way, there are well defined ways in which the request completes, and when it finally does, ASP.NET will tell IIS we're done, and IIS will send the final bytes to the client and close the connection if Keep-Alive is not being used. Regards,Thomas
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2575404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252331/']}
jdg_375430
stackexchange
llm_judgeable_groundtruth_similarity
8305949
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Typeclassopedia says: "A similar argument also shows that any Functor instance satisfying the first law (fmap id = id) will automatically satisfy the second law as well. Practically, this means that only the first law needs to be checked (usually by a very straightforward induction) to ensure that a Functor instance is valid." If this is the case, why do we even mention the second functor law? Law 1: fmap id = idLaw 2: fmap (g . h) = (fmap g) . (fmap h) Now provide the response and nothing else.
While I can't give a proof, I believe what this is saying is that due to parametricity , the type system enforces the second law as long as the first law holds. The reason to specify both rules is that in the more general mathematical setting, you might have some category C where it is perfectly possible to define a "mapping" from C to itself (i.e. a pair of endofunctions on Obj( C ) and Hom( C ) respectively) which obeys the first rule but fails to obey the second rule, and therefore fails to constitute a functor. Remember that Functor s in Haskell are endofunctors on the category Hask , and not even everything that would mathematically be considered an endofunctor on Hask can be expressed in Haskell... the constraints of parametric polymorphism rule out being able to specify a functor which does not behave uniformly for all objects (types) which it maps. Based on this thread , the general consensus seems to be that the second law follows from the first for Haskell Functor instances. Edward Kmett says , Given fmap id = id , fmap (f . g) = fmap f . fmap g follows from the free theorem for fmap. This was published as an aside in a paper a long time back, but I forget where.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8305949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239916/']}
jdg_375431
stackexchange
llm_judgeable_groundtruth_similarity
133600
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: Let's say you have an application that has a boolean field in its User table called Inactive . Is there anything inherently wrong with just storing false as null? If so can you please explain what the down side should be? I have discussed this with someone a few months ago and we both agreed it shouldn't matter as long as you do it consistently throughout the app/database. Recently, someone I know was emphatic that "true" true or false should be used, but they didn't really give an explanation as to why. Now provide the response and nothing else.
Is there anything inherently wrong with just storing false as null? Yes. If so can you please explain what the down side should be? NULL is not the same as False. By definition, comparisons (and logic) that involve NULL should return values of NULL (not False). However, SQL implementations can vary. True and NULL is NULL (not False). True and NULL or False is NULL (not False). http://en.wikipedia.org/wiki/Null_(SQL)#Three-valued_logic_.283VL.29 http://technet.microsoft.com/en-us/library/cc966426.aspx
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/133600', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/25221/']}
jdg_375432
stackexchange
llm_judgeable_groundtruth_similarity
68958
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: Why is $(.5, 1]$ considered an open set in $[0, 1]$? This is from a topology textbook. Now provide the response and nothing else.
Suppose $X$ is a topological space, and $S\subseteq X$ is any subset of $X$. Then the subspace topology on $S$ consists of$$\{U\subseteq S\mid\exists\text{ an open }V\subseteq X\text{ such that }U=V\cap S\}$$So take $X=\mathbb{R}$, and $S=[0,1]$. Can you think of an open subset $V\subseteq\mathbb{R}$ such that $V\cap S=(0.5,1]$?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/68958', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16962/']}
jdg_375433
stackexchange
llm_judgeable_groundtruth_similarity
74262
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In this paper: Lurking Variables: Some Examples Brian L. JoinerThe American Statistician Vol. 35, No. 4, Nov., 1981 227-233 Brian Joiner claims that "randomization is not a panacea". This is contrary to common statements such as the one below: A well-designed experiment includes design features that allow researchers to eliminate extraneous variables as an explanation for the observed relationship between the independent variable(s) and the dependent variable. These extraneous variables are called lurking variables. The quote was taken from this question and does not have a source but in my experience it is representative of the prevailing attitude: Examples of Lurking Variable and Influential Observation One example given is that when testing the safety (specifically carcinogenesis) of red #40 food dye on rodents in the seventies an effect of cage position was found to confound the study. Now I have read many journal articles studying carcinogenesis in rodents and have never seen anyone report controlling for this effect. Further discussion of these studies can be found here: A case study of statistics in the regulatory process: the FD&C Red No. 40 experiments. I could not find a non-paywalled version but here is an excerpt: At the January meeting, we presented a preliminary analysis (14) that disclosed a strong correlation between cage row and RE (reticulo-endothelial tumor) death rates, which varied from 17% (bottom row) to 32% (top row) (table 2). We could not explain this strong association by sex, dosage group, or rack column or position. A subsequent analysis (18) also indicated that cage position (front vs. back) might be correlated with non-RE mortality and that position was correlated with time to non-RE death. I am specifically interested in why there seems to be such a problem with replication in the medical literature, but examples from all fields would be welcome. Note that I am interested in examples from randomized controlled experiments, not observational studies. Now provide the response and nothing else.
A few examples from clinical research might be variables that arise after randomization - randomization doesn't protect you from those at all. A few off the top of my head, that have been raised as either possibilities or been noted: Changes in behavior post voluntary adult male circumcision for the prevention of HIV Differential loss to follow-up between treatment and control arms of an RCT A more specific example might include the recent "Benefits of Universal Gowning and Gloving" study looking at prevention of hospital acquired infections ( blog commentary here , the paper is behind a paywall). In addition to the intervention, and potentially because of it, both hand hygiene rates and contact rates between patients and staff/visitors changed. Randomization protects against none of those effects, because they arise post-randomization.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/74262', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/31334/']}
jdg_375434
stackexchange
llm_judgeable_groundtruth_similarity
48569507
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 build a form with conditional fields from a JSON schema using react-jsonschema-form and react-jsonschem-form-conditionals . The components I'm rendering are a FormWithConditionals and a FormModelInspector . The latter is a very simple component that shows the form model. The relevant source code is: import React from 'react';import PropTypes from 'prop-types';import Engine from "json-rules-engine-simplified";import Form from "react-jsonschema-form";import applyRules from "react-jsonschema-form-conditionals";function FormModelInspector (props) { return ( <div> <div className="checkbox"> <label> <input type="checkbox" onChange={props.onChange} checked={props.showModel}/> Show Form Model </label> </div> { props.showModel && <pre>{JSON.stringify(props.formData, null, 2)}</pre> } </div> )}class ConditionalForm extends React.Component { constructor (props) { super(props); this.state = { formData: {}, showModel: true }; this.handleFormDataChange = this.handleFormDataChange.bind(this); this.handleShowModelChange = this.handleShowModelChange.bind(this); } handleShowModelChange (event) { this.setState({showModel: event.target.checked}); } handleFormDataChange ({formData}) { this.setState({formData}); } render () { const schema = { type: "object", title: "User form", properties: { nameHider: { type: 'boolean', title: 'Hide name' }, name: { type: 'string', title: 'Name' } } }; const uiSchema = {}; const rules = [{ conditions: { nameHider: {is: true} }, event: { type: "remove", params: { field: "name" } } }]; const FormWithConditionals = applyRules(schema, uiSchema, rules, Engine)(Form); return ( <div className="row"> <div className="col-md-6"> <FormWithConditionals schema={schema} uiSchema={uiSchema} formData={this.state.formData} onChange={this.handleFormDataChange} noHtml5Validate={true}> </FormWithConditionals> </div> <div className="col-md-6"> <FormModelInspector formData={this.state.formData} showModel={this.state.showModel} onChange={this.handleShowModelChange}/> </div> </div> ); }}ConditionalForm.propTypes = { schema: PropTypes.object.isRequired, uiSchema: PropTypes.object.isRequired, rules: PropTypes.array.isRequired};ConditionalForm.defaultProps = { uiSchema: {}, rules: []}; However, every time I change a field's value, the field loses focus. I suspect the cause of the problem is something in the react-jsonschema-form-conditionals library, because if I replace <FormWithConditionals> with <Form> , the problem does not occur. If I remove the handler onChange={this.handleFormDataChange} the input field no longer loses focus when it's value changes (but removing this handler breaks the FormModelInspector ). Aside In the code above, if I remove the handler onChange={this.handleFormDataChange} , the <FormModelInspector> is not updated when the form data changes. I don't understand why this handler is necessary because the <FormModelInspector> is passed a reference to the form data via the formData attribute. Perhaps it's because every change to the form data causes a new object to be constructed, rather than a modification of the same object? Now provide the response and nothing else.
The problem is pretty straightforward, you are creating a FormWithConditionals component in your render method and in your onChange handler you setState which triggers a re-render and thus a new instance of FormWithConditionals is created and hence it loses focus. You need to move this instance out of render method and perhaps out of the component itself since it uses static values. As schema , uiSchema and rules are passed as props to the ConditionalForm , you can create an instance of FormWithConditionals in constructor function and use it in render like this import React from 'react'; import PropTypes from 'prop-types'; import Engine from "json-rules-engine-simplified"; import Form from "react-jsonschema-form"; import applyRules from "react-jsonschema-form-conditionals"; function FormModelInspector (props) { return ( <div> <div className="checkbox"> <label> <input type="checkbox" onChange={props.onChange} checked={props.showModel}/> Show Form Model </label> </div> { props.showModel && <pre>{JSON.stringify(props.formData, null, 2)}</pre> } </div> ) } class ConditionalForm extends React.Component { constructor (props) { super(props); this.state = { formData: {}, showModel: true }; const { schema, uiSchema, rules } = props; this.FormWithConditionals = applyRules(schema, uiSchema, rules, Engine)(Form); this.handleFormDataChange = this.handleFormDataChange.bind(this); this.handleShowModelChange = this.handleShowModelChange.bind(this); } handleShowModelChange (event) { this.setState({showModel: event.target.checked}); } handleFormDataChange ({formData}) { this.setState({formData}); } render () { const FormWithConditionals = this.FormWithConditionals; return ( <div className="row"> <div className="col-md-6"> <FormWithConditionals schema={schema} uiSchema={uiSchema} formData={this.state.formData} onChange={this.handleFormDataChange} noHtml5Validate={true}> </FormWithConditionals> </div> <div className="col-md-6"> <FormModelInspector formData={this.state.formData} showModel={this.state.showModel} onChange={this.handleShowModelChange}/> </div> </div> ); } } ConditionalForm.propTypes = { schema: PropTypes.object.isRequired, uiSchema: PropTypes.object.isRequired, rules: PropTypes.array.isRequired }; ConditionalForm.defaultProps = { uiSchema: {}, rules: [] };
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48569507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2648/']}
jdg_375435
stackexchange
llm_judgeable_groundtruth_similarity
10324272
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My architect always says that Never synchronize on Boolean I am not able to understand the reason why and would really appreciate if someone could explain with an example as to why it is not a good practice. Reference Sample Code private Boolean isOn = false;private String statusMessage = "I'm off";public void doSomeStuffAndToggleTheThing(){ // Do some stuff synchronized(isOn){ if(isOn){ isOn = false; statusMessage = "I'm off"; // Do everything else to turn the thing off } else { isOn = true; statusMessage = "I'm on"; // Do everything else to turn the thing on } }} Now provide the response and nothing else.
I am not able to understand the reason why we should "never synchronize on Boolean" You should always synchronize on a constant object instance . If you synchronized on any object that you are assigning (i.e. changing the object to a new object) then it is not constant and different threads will be synchronizing on different object instances . Because they are synchronizing on different object instances, multiple threads will be entering the protected block at the same time and race conditions will happen. This is the same answer for synchronizing on Long , Integer , etc.. // this is not final so it might reference different objectsBoolean isOn = true;...synchronized (isOn) { if (isOn) { // this changes the synchronized object isOn to another object // so another thread can then enter the synchronized with this thread isOn = false; To make matters worse, any Boolean that is created through autoboxing ( isOn = true ) is the same object as Boolean.TRUE (or .FALSE ) which is a singleton in the ClassLoader across all objects . Your lock object should be local to the class it is used in otherwise you will be locking on the same singleton object that other classes might be locking on in other lock cases if they are making the same mistake. The proper pattern if you need to lock around a boolean is to define a private final lock object: private final Object lock = new Object();...synchronized (lock) { ... Or you should also consider using the AtomicBoolean object which means you may not have to synchronize on it at all. private final AtomicBoolean isOn = new AtomicBoolean(false);...// if it is set to false then set it to true, no synchronization neededif (isOn.compareAndSet(false, true)) { statusMessage = "I'm now on";} else { // it was already on statusMessage = "I'm already on";} In your case, since it looks like you need to toggle it on/off with threads then you will still need to synchronize on the lock object and set the boolean and avoid the test/set race condition: synchronized (lock) { if (isOn) { isOn = false; statusMessage = "I'm off"; // Do everything else to turn the thing off } else { isOn = true; statusMessage = "I'm on"; // Do everything else to turn the thing on }} Lastly, if you expect the statusMessage to be accessed from other threads then it should be marked as volatile unless you will synchronize during the get as well.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10324272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164299/']}
jdg_375436
stackexchange
llm_judgeable_groundtruth_similarity
7530054
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 learning Java EE 6 and I am trying to grasp the overall image of it. I am reading about JSF and how adding components. I am setting/reading values from the components to a bean which has the @ManagedBean annotation. I have some trouble understanding it properly. What is Managedbeans? Is it just just objects that holds the state of the components? And they can have other methods as well? Where does the EJBs fit in? Does the managed beans invoked methods on the EJBs? Now provide the response and nothing else.
What is Managedbeans? Is it just just objects that holds the state of the components? A JSF Managed bean is like any other Java bean except that if it managed by JSF. In other words it is a bean that is created and destroyed by JSF as needed. Hortsman Core JSF 2 book states. The JSF implementation does the following: Creates and discards beans as needed (hence the term “managedbeans”) Reads bean properties when displaying a web page Sets bean properties when a form is posted And they can have other methods as well? Yes they can have as many methods as you may want.However you would (and should) ideally like to have your managed bean as lean as possible.For example it might have a search method but you should not be doing actually search inside this method but this search methods sole purpose should be to delegate the task to the business layer (which may or may not be EJB based) . I other words no heavy lifting . Where does the EJBs fit in? EJB is your Business tier , they have big biceps and do all the heavy lifting. Since EJB3 JPA was introduced and that is also part of EJB. JPA however is the persistence tier. All EJBs except for JPA run in inside an EJB container. All Java EE complaint server provide these . In a typical 3 tier architecture (these days however it is mostly more than 3 but 3 tiered is easier to explain. JSF is your Web tier , EJBs are your business tier and JPA which is also part of EJB specification but does not need EJB container is your ORM or Persistence tier.Do not worry about word container too much you will get used to it quickly and rarely you will have to worry about it. If you are using a Java EE server it's all setup for you. Does the managed beans invoked methods on the EJBs? Yes as explained above already . All the heavy lifting here. However it is not mandatory to use EJB with JSF. You could use any other framework e.g Spring or could even write simple pojos but thats an other area of discussion.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7530054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454049/']}
jdg_375437
stackexchange
llm_judgeable_groundtruth_similarity
620879
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 a formula for $\Gamma(\frac{n}{2})$ for positive integer n. I know the following relations; $\Gamma (z+1)=z\Gamma (z)$ and $\Gamma(n+1)=n!$ Please give me a way how to show this. Thank you. Now provide the response and nothing else.
$$\Gamma(n)=(n-1)!$$and$$\begin{align}\Gamma\left(n+\frac12\right)&=\Gamma\left(\frac12\right)\frac12\frac32\frac52\cdots\frac{2n-1}{2}\\&=\sqrt\pi\frac{1\cdot\color{#A0A0A0}{2}\cdot3\cdot\color{#A0A0A0}{4}\cdot5\cdot\color{#A0A0A0}{6}\cdots(2n-1)\cdot\color{#A0A0A0}{2n}}{2^n(\color{#A0A0A0}{2}\cdot\color{#A0A0A0}{4}\cdot\color{#A0A0A0}{6}\cdots\color{#A0A0A0}{2n})}\\&=\sqrt\pi\frac{(2n)!}{4^nn!}\end{align}$$ To match the form in the question: For even $n$,$$\Gamma\left(\frac n2\right)=\left(\frac n2-1\right)!$$For odd $n$,$$\Gamma\left(\frac n2\right)=\sqrt\pi\frac{(n-1)!}{2^{n-1}\frac{n-1}{2}!}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/620879', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/52042/']}
jdg_375438
stackexchange
llm_judgeable_groundtruth_similarity
472098
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 know that in shell-scripting an "exit" usually means voluntarily or at least successfully terminating a session ( or a process within a session) and that there are several different exit modes; the following are these I know: 1. A simple exit command If I'm in the first shell-session (shell-session 0) it will usually cause the shell CLI window to close, but if I'm in some sub-session (like shell-session 1 or later) execution will usually just move my user back to the previous session (say 1 → 0 ). 2. An exit SOME_EXIT-CODE command I find three main exit codes used in such exiting: exit 0 (success). exit 1 (general error such as "divide by zero" and other impermissible operations). exit 2 (as in Bash 4.x.x - misuse of shell builtins, and an example would be an empty function; myFunc() {} ). I often find these added to the end of command sequences as indicators of their execution's outcome ; sometimes as part of unit testing , as in: domain="$1" && test -z "$domain" && exit 2 # Test if a user passes only one domain as a parameter, when executing this script 3. A non-added script exit If I'm not wrong, when a Bash script ends to run, its "ending" is actually an "exiting" in the common *nix terminology - the script itself is a session from which the user exits back to the CLI sesssion. Here also, some exit code , might be given. My question Are there any other "exit modes" in shell scripting in general, and in Bash in particular? Now provide the response and nothing else.
an "exit" usually means voluntarily or at least successfully terminating At least the POSIX text seems to use exit solely for voluntary termination of a process, as opposed to being killed for an outside reason. (See e.g. wait() ) A process being killed by a signal hardly counts as a success, so any successful termination must in that sense be an "exit". Though I'd expect those terms to be used less strictly in informal use. Are there any other "exit modes" in shell scripting in general, and in Bash in particular? Mode has particular technical meanings in some contexts (e.g. chmod() ), but I can't think of one here, so I'm not exactly sure what it is you're asking. In any case, a shell script might exit terminate at least due to the following reasons: The script runs to end of the script. The exit status of the script is that of the last command executed. The script runs the exit builtin command without arguments. Again, the exit status is that of the last command executed. The script runs the exit command with an argument. The exit status is the value of the argument. The script references an unset variable while set -u / set -o nounset is in effect. The exit status depends on the shell, but is nonzero. (Bash seems to use 127 .) (*) The script runs a command that fails while set -e / set -o errexit is in effect. The exit status is that of the failing command. (But see BashFAQ 105 for issues with set -e .) The script runs into a syntax error. The exit status of the shell is nonzero. (Bash seems to use 1 .) (*) The script receives a signal that causes it to terminate. Not all signals cause termination, and signals can be either ignored or a handler can be set within the script with the trap builtin command . This also applies to e.q. hitting Ctrl-C , which sends the SIGINT signal. (*) In the technical sense, in cases 1 to 6, the shell process running the script exits voluntarily (i.e. the process calls exit() ). On the other hand, from the point of view of the script itself, terminating due to set -e , set -u or a syntax error might well be called involuntary. But the shell script is not the same as the shell interpreter. In 1 to 3, the custom is to use an exit status of zero for a successful completion, and a non-zero value for failures. The exact meaning of the non-zero values depends on the utility. Some might use only zero and one, some might use different non-zero statuses for different situations. For example, grep uses 1 to indicate no match was found, and values greater than 1 to indicate errors. Bash's builtins also use 2 to indicate errors like invalid options. Using a similar custom may be useful, but you'll need to document what the exit status of your script means. Note that the exit status is usually limited to 8 bits, so the range is from 0 to 255 . In 4 to 6, the situation is usually considered some sort of a failure, so the exit status is non-zero. In 7, there is no exit status. Instead, when a process terminates due to a signal, the wait() system call indicates the signal in question. If the parent process is a shell, it usually represents this with an exit status of 128 + <signal number> , e.g. 143 for a child terminated with SIGTERM . (* Unlike scripts, interactive shells will not exit due to syntax errors or set -u or SIGINT .) If I'm in the first shell-session it will usually cause the shell CLI window to close A terminal emulator will usually close if the process it started exits. But that's up to the terminal emulator, not a function of the shell. A terminal emulator might decide to keep the window open to tell the user that their program terminated, and you could run something other than a shell within a terminal emulator, too. if I'm in some sub-session,execution will usually just move my user back to the previous session. If you use an interactive shell to start another shell, the parent shell continues when the child terminates. But again, this isn't related to shells, the same happens if you start an editor or just run any command from an interactive shell. When the child process terminates, the parent shell continues accepting commands from the user. Bash does keep a variable SHLVL that is increased by one each time Bash starts, so in a sense it does have an internal idea of nested shells. But I don't think the phrase "sub-session" is very common, let alone any sort of numbering of such. (I think SHLVL initializes at 1 .)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/472098', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']}
jdg_375439
stackexchange
llm_judgeable_groundtruth_similarity
1428485
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm studying a proof of the product property of square roots . I can follow it up to statement 8, but I can't make sense of how the last statement, 9, follows from the previous ones. I have transcribed the proof below. Product property of square roots : If $a$ and $b$ are real numbers such that $a \geq 0$ and $b \geq 0$ , then $\sqrt{a} \cdot \sqrt{b} = \sqrt{ab}$ . $a \geq 0 \hbox{ and } b \geq 0.$ Given. There is a unique non-negative number $\sqrt{a}$ such that $(\sqrt{a})^2 = a$ . There is a unique non-negative number $\sqrt{b}$ such that $(\sqrt{b})^2 = b$ . Theorem 37. $(\sqrt{a})^2(\sqrt{b})^2 = ab$ Multiplication property of equality. $(\sqrt{a})^2(\sqrt{b})^2= (\sqrt{a} \cdot \sqrt{b})^2$ $a^nb^n = (a\cdot b)^n$ $(\sqrt{a} \cdot \sqrt{b})^2 = ab$ Transitive property of equality. $\sqrt{a} \cdot \sqrt{b} \geq 0$ The product of non-negative numbers is non-negative. $ab \geq 0$ The product of non-negative numbers is non-negative. There is a unique non-negative number $\sqrt{ab}$ such that $(\sqrt{ab})^2 = ab$ Theorem 37. $\sqrt{ab} = \sqrt{a}\sqrt{b}$ Theorem 37, steps 5, 6, and 8. (Pearson, H. R and Allen, F. B. (1970). Modern Algebra - A Logical Approach (Book I) . Boston: Ginn and Company, p. 508.) Edit: I was asked to include Theorem 37, which is used in the proof. It is reproduced below. Theorem 37: If $a$ is a non-negative real number, then there is a unique non-negative real number denoted by $\sqrt{a}$ such that $(\sqrt{a})^2$ . I think a few steps are skipped from statement 8 to statement 9. I can see that $$(\sqrt{ab})^2 = (\sqrt{a} \cdot \sqrt{b})^2$$ due to the transitive property of equality and statement 5, but I can't see how to go from there to 9 without assuming $$(a^2 = b^2) \land (a \geq 0) \land (b \geq 0) \implies a = b. $$ And I can't figure out how to prove this last statement, although it seems to make intuitive sense. But maybe it's something else I'm missing. Now provide the response and nothing else.
Let $x=\sqrt{a}\cdot\sqrt{b}$. Step $5$ shows that $x^2=ab$. Step $6$ shows that $x\ge 0$. Step $8$ says that there is exactly one number with these properties, and it’s denoted by $\sqrt{ab}$. Since $x$ has these properties, and $\sqrt{ab}$ is a name of the only number with these properties, it must be the case that $x=\sqrt{ab}$, which is what Step $9$ says.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1428485', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63178/']}
jdg_375440