SYNTHETIC-1
Collection
A collection of tasks & verifiers for reasoning datasets
•
5 items
•
Updated
•
10
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 | 5664094 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Postgresql allows adding comments to objects such as tables. For example I've added a comment to table "mytable" by using this SQL command: COMMENT ON TABLE mytable IS 'This is my table.'; My question is:If I want to use a SQL-command to get all tables along with their respective comment - how would I do this? What would be the appropriate query for this? Thanks in advance!Cheers!
Now provide the response and nothing else.
| All comments are stored in pg_description To get the comments on a table, you need to join it to pg_class As an alternative you can also use the function obj_description() to retrieve this information: SELECT obj_description(oid)FROM pg_classWHERE relkind = 'r' Edit In psql you can simply use the \d+ command to show all tables including their comments. Or use the \dd command to show all comments in the system | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5664094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/621258/']} | jdg_69841 |
stackexchange | llm_judgeable_groundtruth_similarity | 366863 |
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:
I was doing some work in scipy and a conversation came up w/a member of the core scipy group whether a non-negative discrete random variable can have a undefined moment. I think he is correct but do not have a proof handy. Can anyone show/prove this claim? (or if this claim is not true disprove) I don't have an example handy if the discrete random variable has support on $\mathbb{Z}$ but it seems that some discretized version of the Cauchy distribution should serve as an example to get an undefined moment. The condition of non-negativity (perhaps including $0$) is what seems to make the problem challenging (at least for me).
Now provide the response and nothing else.
| Let the CDF $F$ equal $1-1/n$ at the integers $n=1,2,\ldots,$ piecewise constant everywhere else, and subject to all criteria to be a CDF. The expectation is $$\int_{0}^\infty (1-F(x))\mathrm{d}x = 1/2 + 1/3 + 1/4 + \cdots$$ which diverges. In this sense the first moment (and therefore all higher moments) is infinite. (See remarks at the end for further elaboration.) If you're uncomfortable with this notation, note that for $n=1,2,3,\ldots,$ $${\Pr}_{F}(n) = \frac{1}{n} - \frac{1}{n+1.}$$ This defines a probability distribution since each term is positive and $$\sum_{n=1}^\infty {\Pr}_{F}(n) = \sum_{n=1}^\infty \left(\frac{1}{n} - \frac{1}{n+1}\right) = \lim_{n\to \infty} 1 - \frac{1}{n+1} = 1.$$ The expectation is $$\sum_{n=1}^\infty n\,{\Pr}_{F}(n) = \sum_{n=1}^\infty n\left(\frac{1}{n} - \frac{1}{n+1}\right) =\sum_{n=1}^\infty \frac{1}{n+1} = 1/2 + 1/3 + 1/4 + \cdots$$ which diverges. This way of expressing the answer it makes it clear that all solutions are obtained by such divergent series. Indeed, if you would like the distribution to be supported on some subset of the positive values $x_1, x_2, \ldots, x_n, \ldots,$ with probabilities $p_1, p_2, \ldots$ summing to unity, then for the expectation to diverge the series which expresses it, namely $$(a_n) = (x_n p_n),$$ must have divergent partial sums. Conversely, every divergent series $(a_n)$ of non-negative numbers is associated with many discrete positive distributions having divergent expectation. For instance, given $(a_n)$ you could apply the following algorithm to determine sequences $(x_n)$ and $(p_n)$ . Begin by setting $q_n = 2^{-n}$ and $y_n = 2^n a_n$ for $n=1, 2, \ldots.$ Define $\Omega$ to be the set of all $y_n$ that arise in this way, index its elements as $\Omega=\{\omega_1, \omega_2, \ldots, \omega_i, \ldots\},$ and define a probability distribution on $\Omega$ by $$\Pr(\omega_i) = \sum_{n \mid y_n = \omega_i}q_n.$$ This works because the sum of the $p_n$ equals the sum of the $q_n,$ which is $1,$ and $\Omega$ has at most a countable number of positive elements. As an example, the series $(a_n) = (1, 1/2, 1, 1/2, \ldots)$ obviously diverges. The algorithm gives $$y_1 = 2a_1 = 2;\ y_2 = 2^2 a_2 = 2;\ y_3 = 2^3 a_3 = 8; \ldots$$ Thus $$\Omega = \{2, 8, 32, 128, \ldots, 2^{2n+1},\ldots\}$$ is the set of odd positive powers of $2$ and $$p_1 = q_1 + q_2 = 3/4;\ p_2 = q_3 + q_4 = 3/16;\ p_3 = q_5 + q_6 = 3/64; \ldots$$ About infinite and non-existent moments When all the values are positive, there is no such thing as an "undefined" moment: moments all exist, but they can be infinite in the sense of a divergent sum (or integral), as shown at the outset of this answer. Generally, all moments are defined for positive random variables, because the sum or integral that expresses them either converges absolutely or it diverges (is "infinite.") In contrast to that, moments can become undefined for variables that take on positive and negative values, because--by definition of the Lebesgue integral--the moment is the difference between a moment of the positive part and a moment of the absolute value of the negative part. If both those are infinite, convergence is not absolute and you face the problem of subtracting an infinity from an infinity: that does not exist. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/366863', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/150025/']} | jdg_69842 |
stackexchange | llm_judgeable_groundtruth_similarity | 750765 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to have a bare git repository stored on a (windows) network share. I use linux, and have the said network share mounted with CIFS. My coleague uses windows xp, and has the network share automounted (from ActiveDirectory, somehow) as a network drive. I wonder if I can use the repo from both computers, without concurrency problems. I've already tested, and on my end I can clone ok, but I'm afraid of what might happen if we both access the same repo (push/pull), at the same time. In the git FAQ there is a reference about using network file systems (and some problems with SMBFS), but I am not sure if there is any file locking done by the network/server/windows/linux - i'm quite sure there isn't. So, has anyone used a git repo on a network share, without a server, and without problems? Thank you, Alex PS: I want to avoid using an http server (or the git-daemon), because I do not have access to the server with the shares. Also, I know we can just push/pull from one to another, but we are required to have the code/repo on the share for back-up reasons. Update: My worries are not about the possibility of a network failure. Even so, we would have the required branches locally, and we'll be able to compile our sources. But, we usually commit quite often, and need to rebase/merge often. From my point of view, the best option would be to have a central repo on the share (so the backups are assured), and we would both clone from that one, and use it to rebase. But, due to the fact we are doing this often, I am afraid about file/repo corruption , if it happens that we both push/pull at the same time. Normally, we could yell at each other each time we access the remote repo :), but it would be better to have it secured by the computers/network. And, it is possible that GIT has an internal mechanism to do this (since someone can push to one of your repos, while you work on it), but I haven't found anything conclusive yet. Update 2: The repo on the share drive would be a bare repo, not containing a working copy.
Now provide the response and nothing else.
| Git requires minimal file locking, which I believe is the main cause of problems when using this kind of shared resource over a network file system. The reason it can get away with this is that most of the files in a Git repo--- all the ones that form the object database--- are named as a digest of their content, and immutable once created. So there the problem of two clients trying to use the same file for different content doesn't come up. The other part of the object database is trickier-- the refs are stored in files under the "refs" directory (or in "packed-refs") and these do change: although the refs/* files are small and always rewritten rather than being edited. In this case, Git writes the new ref to a temporary ".lock" file and then renames it over the target file. If the filesystem respects O_EXCL semantics, that's safe. Even if not, the worst that could happen would be a race overwriting a ref file. Although this would be annoying to encounter, it should not cause corruption as such: it just might be the case that you push to the shared repo, and that push looks like it succeeded whereas in fact someone else's did. But this could be sorted out simply by pulling (merging in the other guy's commits) and pushing again. In summary, I don't think that repo corruption is too much of a problem here--- it's true that things can go a bit wrong due to locking problems, but the design of the Git repo will minimise the damage. (Disclaimer: this all sounds good in theory, but I've not done any concurrent hammering of a repo to test it out, and only share them over NFS not CIFS) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/750765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73593/']} | jdg_69843 |
stackexchange | llm_judgeable_groundtruth_similarity | 27505 |
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:
Background: It is well known that the quantum mechanics of $n$ identical particles living on $\mathbb{R}^3$ can be obtained from the geometric quantization of the cotangent bundle of the manifold $M^n = \frac{\mathbb{R}^{3n}-\Delta}{S_n}$, where $\Delta$ is the set of coincidences and $S_n$ is the permutation group of $n$ elements acting naturally on the individual copies of $\mathbb{R}^3$, please see, for example, Souriau: Structure of dynamical systems . $T^*M^n$ is multiply connected with $\pi_1(T^*M^n) = S_n$. Given the canonical symplectic structure on $T^*M^n$,the set of inequivalent quantizations has a one to one correspondence to the set of character representations of the fundamental group $\mathrm{Hom}(\pi_1(M^n), U(1))= \mathbb{Z}_2$ corresponding to the identity and the parity characters. Thesequantizations correspond exactly to the pre-quantization of bosons and fermions. The boson and fermion Fock spaces modeled on$\mathrm{L}^2(R^3)$ emerge as the quantization of Hilbert spaces corresponding to these two possibilities. Many authors pointed out that the removal of the coincidence set from the configuration space may seem not to be physically well motivated. The standard reasoning for this choice is that without the removal, the configuration space becomes an orbifold rather than a manifold. Some authors indicate also that without the removal, the configuration space is simply connected thus does allow only Bose quantization (Please, see for example the reprinted article by Y.S. Wu in Fractional statistics and anyon superconductivity By Frank Wilczek . My question: Are there any known treatments or results of the problem of geometric quantization of the configuration space as an orbifold (without the removal of the coincidence set), in terms of orbifold line bundles, etc.?Partial results or special cases are welcome. Does this quantization allow the possibility of Fermi statistics?
Now provide the response and nothing else.
| Often, instead of $\mathbf{R}^{3n}/S_n$, you may want to resolve the singularity. Let me explain a toy model where that resolution appears naturally. Consider $n$ identical particles on $\mathbf{C}$ with the configuration space $M^n=(\mathbf{C}^n-\Delta)/S_n$. You can think of this space as the space of unordered eigenvalues of $n\times n$ matrices over $\mathbf{C}$, i.e. $M^n=Mat_n(\mathbf{C})^{diag}/GL_n(\mathbf{C})$, where $Mat_n(\mathbf{C})^{diag}$ is the space of diagonalizable matrices with distinct eigenvalues and $GL_n(\mathbf{C})$ acts by conjugation. A heuristic argument (which is precise when the action of $G$ is nice) shows that $T^*(M/G)\cong T^*M//G$, where $//$ is the Hamiltonian reduction. In my case, there is a well-known compactification of $T^*M^n$ called the Calogero-Moser space $C_n$ obtained by the Hamiltonian reduction of $T^* Mat_n(\mathbf{C})$ along some orbit. Cotangent bundles have natural quantizations (functions are replaced by differential operators on the base and the Hilbert space is just $L^2$ functions on the base), and the quantization of the Calogero-Moser space $C_n$ is obtained by a procedure called the quantum Hamiltonian reduction from the quantization of $T^*Mat_n(\mathbf{C})$. For a reference, see Etingof's lectures http://arxiv.org/abs/math/0606233v4 . In particular, see proposition 2.6. Note, that he is more precise than I am, and so considers the action by $PGL_n(\mathbf{C})$ since it does not have any center. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/27505', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2190/']} | jdg_69844 |
stackexchange | llm_judgeable_groundtruth_similarity | 2016206 |
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 out the DateTime.TryParseExact method, and I have come over a case that I just don't get. I have some formats and some subjects to parse that each should match one of the formats perfectly: var formats = new[] { "%H", "HH", "Hmm", "HHmm", "Hmmss", "HHmmss", };var subjects = new[] { "1", "12", "123", "1234", "12345", "123456", }; I then try to parse them all and print out the results: foreach(var subject in subjects){ DateTime result; DateTime.TryParseExact(subject, formats, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result); Console.WriteLine("{0,-6} : {1}", subject, result.ToString("T", CultureInfo.InvariantCulture));} I get the following: 1 : 01:00:0012 : 12:00:00123 : 00:00:001234 : 12:34:0012345 : 00:00:00123456 : 12:34:56 And to my question... why is it failing on 123 and 12345? Shouldn't those have become 01:23:00 and 01:23:45? What am I missing here? And how can I get it to work as I would expect it to? Update: So, seems like we might have figured out why this is failing sort of. Seems like the H is actually grabbing two digits and then leaving just one for the mm , which would then fail. But, does anyone have a good idea on how I can change this code so that I would get the result I am looking for? Another update: Think I've found a reasonable solution now. Added it as an answer. Will accept it in 2 days unless someone else come up with an even better one. Thanks for the help!
Now provide the response and nothing else.
| Ok, so I think I have figured this all out now thanks to more reading, experimenting and the other helpful answers here. What's happening is that H , m and s actually grabs two digits when they can, even if there won't be enough digits for the rest of the format. So for example with the format Hmm and the digits 123 , H would grab 12 and there would only be a 3 left. And mm requires two digits, so it fails. Tadaa . So, my solution is currently to instead use just the following three formats: var formats = new[] { "%H", "Hm", "Hms", }; With the rest of the code from my question staying the same, I will then get this as a result: 1 : 01:00:0012 : 12:00:00123 : 12:03:001234 : 12:34:0012345 : 12:34:05123456 : 12:34:56 Which I think should be both reasonable and acceptable :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2016206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39321/']} | jdg_69845 |
stackexchange | llm_judgeable_groundtruth_similarity | 416850 |
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:
Can a permutation matrix ($P$) be used to change the rank of another matrix ($M$)?Is there any literature to this effect, or to the contrary? I've tried a few small examples and the resulting matrix ($M_2$) seems to always have the same rank as the input matrix ($M$) $M_2 = M P$
Now provide the response and nothing else.
| Hint: The rank of a matrix is the number of linearly independent row vectors, or of linearly independent column vectors. Now think about what a permutation matrix does to the row or column vectors in the matrix if you multiply it from left or right. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/416850', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38972/']} | jdg_69846 |
stackexchange | llm_judgeable_groundtruth_similarity | 62545 |
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:
Is there any way to find out what I just killed? $ ps -A -o pid,cmd | grep someApp | grep -v grep2802 python someApp.py$ sudo kill 2302$ EDIT: To clarify, I need to know what PID 2302 was before I killed it. The ps line is to give context as to how I killed 2302 when I don't even know what it was.
Now provide the response and nothing else.
| There is no general way to know, but you may have clues. You sent a TERM signal, not a KILL signal, so that left the program the opportunity to run a signal handler. It might not have died at all, or it might have left a log entry somewhere. Check whether the process is still running ( ps 2302 ), and if not, check your system logs. There is a log of all processes if you have process accounting enabled. This is available on Linux through GNU acct , but with most distributions the package is not installed by default. If process accounting is enabled, run lastcomm (you may need to be root) to see the recently killed processes (latest first). With lastcomm , only the command name is tracked, not the PID or the arguments; you'll have to figure out which process it is by circumstantial matching. Under Linux, lastcomm shows the date the process exited but only with a granularity of 1 minute, and there is an X flag after the command name if the command was killed by a signal. GNU acct tracks more information, including the process ID, but the lastcomm command doesn't display it: you have to run dump-acct , which unfortunately does not indicate whether a command was killed by a signal. dump-acct /var/log/account/pacct | awk -F '|' '$10 ~ / *2302($| )/' There are other subsystems that can log processes, such as Linux's audit, but they are usually not configured to do so. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/62545', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/9760/']} | jdg_69847 |
stackexchange | llm_judgeable_groundtruth_similarity | 349524 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my SQL Server backend for my app, I want to create history tables for a bunch of my key tables, which will track a history of changes to the rows. My entire application uses Stored Procedures, there is no embedded SQL.The only connection to the database to modify these tables will be through the application and the SP interface.Traditionally, shops I've worked with have performed this task using triggers. If I have a choice between Stored Procedures and Triggers, which is better?Which is faster?
Now provide the response and nothing else.
| Triggers. We wrote a GUI (internally called Red Matrix Reloaded ) to allow easy creation/management of audit logging triggers. Here's some DDL of the stuff used: The AuditLog table CREATE TABLE [AuditLog] ( [AuditLogID] [int] IDENTITY (1, 1) NOT NULL , [ChangeDate] [datetime] NOT NULL CONSTRAINT [DF_AuditLog_ChangeDate] DEFAULT (getdate()), [RowGUID] [uniqueidentifier] NOT NULL , [ChangeType] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [TableName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [FieldName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [OldValue] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [NewValue] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Username] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [Hostname] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL , [AppName] [varchar] (128) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [UserGUID] [uniqueidentifier] NULL , [TagGUID] [uniqueidentifier] NULL , [Tag] [varchar] (8000) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ) Trigger to log inserts CREATE TRIGGER LogInsert_Nodes ON dbo.NodesFOR INSERTAS/* Load the saved context info UserGUID */DECLARE @SavedUserGUID uniqueidentifierSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)FROM master.dbo.sysprocessesWHERE spid = @@SPIDDECLARE @NullGUID uniqueidentifierSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'IF @SavedUserGUID = @NullGUIDBEGIN SET @SavedUserGUID = NULLEND /*We dont' log individual field changes Old/New because the row is new. So we only have one record - INSERTED*/ INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue, NewValue) SELECT getdate(), --ChangeDate i.NodeGUID, --RowGUID 'INSERTED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName '', --FieldName i.ParentNodeGUID, --TagGUID i.Caption, --Tag null, --OldValue null --NewValue FROM Inserted i Trigger to log Updates CREATE TRIGGER LogUpdate_Nodes ON dbo.NodesFOR UPDATE AS/* Load the saved context info UserGUID */DECLARE @SavedUserGUID uniqueidentifierSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)FROM master.dbo.sysprocessesWHERE spid = @@SPIDDECLARE @NullGUID uniqueidentifierSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'IF @SavedUserGUID = @NullGUIDBEGIN SET @SavedUserGUID = NULLEND /* ParentNodeGUID uniqueidentifier */ IF UPDATE (ParentNodeGUID) BEGIN INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue, NewValue) SELECT getdate(), --ChangeDate i.NodeGUID, --RowGUID 'UPDATED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName 'ParentNodeGUID', --FieldName i.ParentNodeGUID, --TagGUID i.Caption, --Tag d.ParentNodeGUID, --OldValue i.ParentNodeGUID --NewValue FROM Inserted i INNER JOIN Deleted d ON i.NodeGUID = d.NodeGUID WHERE (d.ParentNodeGUID IS NULL AND i.ParentNodeGUID IS NOT NULL) OR (d.ParentNodeGUID IS NOT NULL AND i.ParentNodeGUID IS NULL) OR (d.ParentNodeGUID <> i.ParentNodeGUID) END /* Caption varchar(255) */ IF UPDATE (Caption) BEGIN INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue, NewValue) SELECT getdate(), --ChangeDate i.NodeGUID, --RowGUID 'UPDATED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName 'Caption', --FieldName i.ParentNodeGUID, --TagGUID i.Caption, --Tag d.Caption, --OldValue i.Caption --NewValue FROM Inserted i INNER JOIN Deleted d ON i.NodeGUID = d.NodeGUID WHERE (d.Caption IS NULL AND i.Caption IS NOT NULL) OR (d.Caption IS NOT NULL AND i.Caption IS NULL) OR (d.Caption <> i.Caption) END.../* ImageGUID uniqueidentifier */IF UPDATE (ImageGUID)BEGIN INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue, NewValue) SELECT getdate(), --ChangeDate i.NodeGUID, --RowGUID 'UPDATED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName 'ImageGUID', --FieldName i.ParentNodeGUID, --TagGUID i.Caption, --Tag (SELECT Caption FROM Nodes WHERE NodeGUID = d.ImageGUID), --OldValue (SELECT Caption FROM Nodes WHERE NodeGUID = i.ImageGUID) --New Value FROM Inserted i INNER JOIN Deleted d ON i.NodeGUID = d.NodeGUID WHERE (d.ImageGUID IS NULL AND i.ImageGUID IS NOT NULL) OR (d.ImageGUID IS NOT NULL AND i.ImageGUID IS NULL) OR (d.ImageGUID <> i.ImageGUID)END Trigger to log Delete CREATE TRIGGER LogDelete_Nodes ON dbo.NodesFOR DELETEAS/* Load the saved context info UserGUID */DECLARE @SavedUserGUID uniqueidentifierSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)FROM master.dbo.sysprocessesWHERE spid = @@SPIDDECLARE @NullGUID uniqueidentifierSELECT @NullGUID = '{00000000-0000-0000-0000-000000000000}'IF @SavedUserGUID = @NullGUIDBEGIN SET @SavedUserGUID = NULLEND /*We dont' log individual field changes Old/New because the row is new. So we only have one record - DELETED*/ INSERT INTO AuditLog( ChangeDate, RowGUID, ChangeType, Username, HostName, AppName, UserGUID, TableName, FieldName, TagGUID, Tag, OldValue,NewValue) SELECT getdate(), --ChangeDate d.NodeGUID, --RowGUID 'DELETED', --ChangeType USER_NAME(), HOST_NAME(), APP_NAME(), @SavedUserGUID, --UserGUID 'Nodes', --TableName '', --FieldName d.ParentNodeGUID, --TagGUID d.Caption, --Tag null, --OldValue null --NewValue FROM Deleted d And in order to know which user in the software did the update, every connection "logs itself onto SQL Server" by calling a stored procedure: CREATE PROCEDURE dbo.SaveContextUserGUID @UserGUID uniqueidentifier AS/* Saves the given UserGUID as the session's "Context Information" */IF @UserGUID IS NULLBEGIN PRINT 'Emptying CONTEXT_INFO because of null @UserGUID' DECLARE @BinVar varbinary(128) SET @BinVar = CAST( REPLICATE( 0x00, 128 ) AS varbinary(128) ) SET CONTEXT_INFO @BinVar RETURN 0ENDDECLARE @UserGUIDBinary binary(16) --a guid is 16 bytesSELECT @UserGUIDBinary = CAST(@UserGUID as binary(16))SET CONTEXT_INFO @UserGUIDBinary/* To load the guid back DECLARE @SavedUserGUID uniqueidentifierSELECT @SavedUserGUID = CAST(context_info as uniqueidentifier)FROM master.dbo.sysprocessesWHERE spid = @@SPIDselect @SavedUserGUID AS UserGUID*/ Notes Stackoverflow code format removes most blank lines - so formatting sucks We use a table of users, not integrated security This code is provided as a convience - no critisism of our design selection allowed. Purists might insist that all logging code should be done in the business layer - they can come here and write/maintain it for us. blobs cannot be logged using triggers in SQL Server (there is no "before" version of a blob - there is only what is). Text and nText are blobs - which makes notes either unloggable, or makes them varchar(2000)'s. the Tag column is used as an arbitrary text to identify the row (e.g. if a customer was deleted, the tag will show "General Motors North America" in the audit log table. TagGUID is used to point to the row's "parent". For example logging InvoiceLineItems points back to the InvoiceHeader . This way anyone searching for audit log entries related for a specific invoice will find the deleted "line items" by the line item's TagGUID in the audit trail. sometimes the "OldValue" and "NewValue" values are written as a sub-select - to get a meaningful string. i.e." OldValue: {233d-ad34234..}NewValue: {883-sdf34...} is less useful in the audit trail than: OldValue: Daimler ChryslerNewValue: Cerberus Capital Management Final note : Feel free to not do what we do. This is great for us, but everyone else is free to not use it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/349524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24126/']} | jdg_69848 |
stackexchange | llm_judgeable_groundtruth_similarity | 9615706 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Is destructor called if SIGINT or SIGSTP issued? My code like this: #include <iostream>#include <signal.h>#include <cstdlib>void handler(int) { std::cout << "will exit..." << std::endl; exit(0);}class A {public: A() {std::cout << "constructor" << std::endl;} ~A() {std::cout << "destructor" << std::endl;}};int main(void) { signal(SIGINT, &handler); A a; for (;;); return 0;} When I pressed Ctrl-C, it printed: constructor^Cwill exit... There is no "destructor" printed.So, how can I exit cleanly?
Now provide the response and nothing else.
| With difficulty. Already, the code you've written has undefinedbehavior; you're not allowed to output to a stream in a signal handler;for that matter, you're not allowed to call exit either. (I'm basingmy assertions here on the Posix standard. In pure C++, all you'reallowed to do is assign to a variable of sig_atomic_t type.) In a simple case like your code, you could do something like: sig_atomic_t stopFlag = 0;voidhandler( int ){ stopFlag = 1;}intmain(){ signal( SIGINT, &handler ); A a; while ( stopFlag == 0 ) { } std::cout << "will exit..." << std::endl; return 0;} Depending on the application, you may be able to do something like this,checking the stopFlag at appropriate places. But generally, if youtry this, there will be race conditions: you check stopFlag beforestarting an interuptable system call, then do the call; the signalarrives between the check and the call, you do the call, and it isn'tinterrupted. (I've used this technique, but in an application where theonly interruptable system call was a socket read with a very shorttimeout.) Typically, at least under Posix, you'll end up having to create a signalhandling thread; this can then be used to cleanly shut down all of theother threads. Basically, you start by setting the signal mask to blockall signals, then in the signal handling thread, once started, set it toaccept the signals you're interested in and call sigwait() . Thisimplies, however, that you do all of the usual actions necessary for aclean shutdown of the threads: the signal handling thread has to knowabout all other threads, call pthread_cancel on them, etc., and you'recompiler has to generate the correct code to handle pthread_cancel , oryou need to develop some other means of ensuring that all threads arecorrectly notified. (One would hope, today, that all compilers handle pthread_cancel correctly. But one never knows; doing so hassignificant runtime cost, and is not usually needed.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9615706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1105178/']} | jdg_69849 |
stackexchange | llm_judgeable_groundtruth_similarity | 7451761 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is what I want the output to look like: Employee Emp# Manager Mgr# BLAKE 7698 KING 7839 CLARK 7782 KING 7839 JONES 7566 KING 7839 MARTIN 7654 BLAKE 7698 ALLEN 7499 BLAKE 7698 TURNER 7844 BLAKE 7698 JAMES 7900 BLAKE 7698 WARD 7521 BLAKE 7698 FORD 7902 JONES 7566 SMITH 7369 FORD 7902 SCOTT 7788 JONES 7566 ADAMS 7876 SCOTT 7788 MILLER 7934 CLARK 7782 Here's what I got: SQL> SELECT ename, empno, (SELECT ename FROM EMP WHERE empno = mgr)AS MANAGER, mgr from emp order by empno; ENAME EMPNO MANAGER MGR ---------- ---------- ---------- ---------- SMITH 7369 7902 ALLEN 7499 7698 WARD 7521 7698 JONES 7566 7839 MARTIN 7654 7698 BLAKE 7698 7839 CLARK 7782 7839 SCOTT 7788 7566 KING 7839 TURNER 7844 7698 ADAMS 7876 7788 ENAME EMPNO MANAGER MGR ---------- ---------- ---------- ---------- JAMES 7900 7698 FORD 7902 7566 MILLER 7934 7782 I can't find why the manager field is blank. Here's the table: SQL> select empno, ename, job,deptno, mgr from emp; EMPNO ENAME JOB DEPTNO MGR ---------- ---------- --------- ---------- ---------- 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7839 7782 CLARK MANAGER 10 7839 7566 JONES MANAGER 20 7839 7654 MARTIN SALESMAN 30 7698 7499 ALLEN SALESMAN 30 7698 7844 TURNER SALESMAN 30 7698 7900 JAMES CLERK 30 7698 7521 WARD SALESMAN 30 7698 7902 FORD ANALYST 20 7566 7369 SMITH CLERK 20 7902 EMPNO ENAME JOB DEPTNO MGR ---------- ---------- --------- ---------- ---------- 7788 SCOTT ANALYST 20 7566 7876 ADAMS CLERK 20 7788 7934 MILLER CLERK 10 7782 14 rows selected.
Now provide the response and nothing else.
| This is a classic self-join, try the following: SELECT e.ename, e.empno, m.ename as manager, e.mgrFROM emp e, emp mWHERE e.mgr = m.empno And if you want to include the president which has no manager then instead of an inner join use an outer join in Oracle syntax: SELECT e.ename, e.empno, m.ename as manager, e.mgrFROM emp e, emp mWHERE e.mgr = m.empno(+) Or in ANSI SQL syntax: SELECT e.ename, e.empno, m.ename as manager, e.mgrFROM emp e LEFT OUTER JOIN emp m ON e.mgr = m.empno | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7451761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/770022/']} | jdg_69850 |
stackexchange | llm_judgeable_groundtruth_similarity | 3960548 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the second line? (Seen while answering another question.) int * x = new int [1] ;int * y = new (x) int; After the second line x and y have the same value (point to a same place). What's the difference between y = x and the second line? Is it like a constructor or something?
Now provide the response and nothing else.
| It's placement new . It constructs a new int in the memory pointed to by x . If you try: int * x = new int [1];*x = 5;std::cout << *x << std::endl;int * y = new (x) int;*y = 7;std::cout << *x << std::endl; the output will be: 57 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3960548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2308801/']} | jdg_69851 |
stackexchange | llm_judgeable_groundtruth_similarity | 34610421 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I wrote a program to calculate the PI number with Leibniz formula: [ I wrote a for-loop with type of initialization is "int" , the loop works fine but when i changed the initialization type to "long" the result is changed. This only happens when the loop times over a billion. This makes the "int - loop" calculates PI more accurate than "long - loop". I don't know why this happens. Please help me to understand this issue. Thanks! and here is my code. public static void main(String[] args) { double result1 = 0; double result2 = 0; double sign = 1; for (int i = 0; i <= 1607702095; i++) { result1 += sign/(2 * i + 1); sign *= -1; } sign = 1; for (long j = 0; j <= 1607702095; j++) { result2 += sign/(2 * j + 1); sign *= -1; } System.out.println("result1 " + result1 * 4); System.out.println("result2 " + result2 * 4); System.out.println("pi " + Math.PI);} And the result is: result1 3.141592653576877result2 3.1415926529660116pi 3.141592653589793
Now provide the response and nothing else.
| Actually, your first loop would have int overflow in the calculation of (2 * i + 1) when i is large enough, so I wouldn't rely on the output of it. The second loop, on the other hand, produces a more correct output, since (2 * j + 1) doesn't overflow, since it performs long multiplication. This makes the "int - loop" calculates PI more accurate than "long - loop" That's probably just a coincidence, since the calculations in the int loop overflow. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34610421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5747353/']} | jdg_69852 |
stackexchange | llm_judgeable_groundtruth_similarity | 18877580 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the following snippet: "12-18" -Contains "-" You’d think this evaluates to true , but it doesn't. This will evaluate to false instead. I’m not sure why this happens, but it does. To avoid this, you can use this instead: "12-18".Contains("-") Now the expression will evaluate to true. Why does the first code snippet behave like that? Is there something special about - that doesn't play nicely with -Contains ? The documentation doesn't mention anything about it.
Now provide the response and nothing else.
| The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections. From the documentation you linked to: -Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value. In the example you provided you're working with a collection containing just one string item. If you read the documentation you linked to you'll see an example that demonstrates this behaviour: Examples: PS C:\> "abc", "def" -Contains "def"TruePS C:\> "Windows", "PowerShell" -Contains "Shell"False #Not an exact match I think what you want is the -Match operator: "12-18" -Match "-" Which returns True . Important: As pointed out in the comments and in the linked documentation , it should be noted that the -Match operator uses regular expressions to perform text matching. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18877580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/770270/']} | jdg_69853 |
stackexchange | llm_judgeable_groundtruth_similarity | 614485 |
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:
There has been quite some debate amongst users with different backgrounds about the usage of the word photon . [ 1 , 2 ] The most apparent disagreement was on whether a photon has a wavelength. I don't want to start a discussion about which viewpoint is more correct, because quantum optics is clearly only a sub-field of the standard model. Instead I would like to understand what additional predictions about photons the standard model allows to make and how one can construct the properties of the quantum optics' photon from it. In the quantum optics community a photon is a quantum of excitation of an electromagnetic (EM) mode. The mode is a solution of (the relativistic) Maxwell's equations. Therefore asking about the wavelength of a photon boils down to the wavelength of the EM mode. The mode doesn't need to be a plane wave. Now the particle physics perspective – I don't know much about it, but there were some statements which confused me: Photons are point particles without a wavelength. Moreover, the entity quantum optics people term "photon" is a composite particle or quasiparticle . I especially wonder how the absence of a wavelength does not contradict the explanation of diffraction experiments. The diffraction of a quantum optics' photon follows quite naturally from the fact that the EM mode is different in the presence of e.g. a grating compared to without the grating. But how are the wave-like properties modelled in particle physics? Please note that I'm not asking about the wave-particle duality, but about the apparent contradiction of the mentioned statements with interference phenomena.
Now provide the response and nothing else.
| The models that describe photons used in quantum optics and in particle physics are one and the same: the Standard Model of particle physics (often replaceable with just its quantum electrodynamics component) as encased within the formalism of quantum field theory. Moreover, the definition of photons (more specifically, single-photon states of the field) are identical in both fields. To be unambiguous: in both quantum optics and particle physics, photons need not have a well-defined wavelength. The definition you give, a photon is a quantum of excitation of an electromagnetic (EM) mode; the mode is a solution of (the relativistic) Maxwell's equations, is essentially right. Quantum electrodynamics builds on top of the classical Maxwell equations, by building creation and annihilation operators $\hat a_q$ and $\hat a_q^\dagger$ associated with each mode (indexed by $q$ ), and it provides us with number operators for each mode, $\hat n_q=\hat a_q^\dagger \hat a_q$ , and a global number operator, $$\hat N = \sum \!\!\!\!\!\!\!\!\!\; \int\limits_q \ \hat a_q^\dagger \hat a_q.$$ Single-photon states of the field are the eigenstates of $\hat N$ with eigenvalue $1$ . Some of those states are also eigenstates of one of the individual $\hat n_q$ for a mode $q$ which has a well-defined frequency (resp. wavelength, momentum, but also possibly e.g. orbital angular momentum), in which case the photon itself will have a well-defined frequency (resp. wavelength, momentum, OAM). If that premise is not fulfilled, then the photon does not have that well-defined quantity. In other words, your quote Therefore asking about the wavelength of a photon boils down to the wavelength of the EM mode is not wrong as such, but it seems to implicitly assume that "asking about the wavelength of the EM mode" will always have a well-defined answer and (with frequency, wavelength, momentum, OAM, etc) the answer is sometimes yes but also sometimes no. For full clarity, the answer you linked to is dead wrong. There is no semantic confusion. What can happen is that some phenomenological particle physicists in older generations, trained in the consequences of the QFT framework but not necessarily in its full mathematical generality, can sometimes fail to appreciate the full breadth of generality of the consequences of the QFT formalism. There's a lot of value in the traditional perspectives of phenomenological particle physics, but when their conclusions are in conflict with the mathematical formalism of QFT that underlies the theory, then the conclusions drawn from those perspectives are wrong. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/614485', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/169454/']} | jdg_69854 |
stackexchange | llm_judgeable_groundtruth_similarity | 9441892 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here's my situation:I have been working on an ASP.NET MVC 3 application for a while. It has a database (built out of a db project; I'm going db-first) for which I have an edmx model and then a set of POCOs. My entities have plural names in the database and POCOs have singular names. Everything maps nicely without a problem. Or used to until I added a new table (called TransactionStatuses). Now all of the old entities still work but the new one does not. When I try to eagerly load it together with a related entity: var transactions = (from t in db.Transactions.Include(s => s.TransactionStatus) //TransactionStatus - navigation property in Transactions to TransactionStatuses where t.CustomerID == CustomerID select t).ToList(); I get Invalid object name 'dbo.TransactionStatus'. I even did a simpler test: List<TransactionStatus> statuses = db.TransactionStatuses.ToList(); = same result. I have updated (and even re-created) edmx from the db and have gone through it back and forth trying to figure out what is different about the mapping for dbo.TransactionStatus* es * which trips the whole thing up. If somebody can point me in the direction of a fix it'd be wonderful. P.S. Turning off pluralisation is not an option, thanks. Update : I figured it out - my answer below.
Now provide the response and nothing else.
| This is probably happening because even though the intention was to use the Database First flow, in actual fact the application is using Code First to do the mapping. Let me explain a bit more because this can be confusing. :-) When using Database First with the EF Designer and the DbContext templates in Visual Studio three very important things happen. First, the new Entity Data Model wizard adds a connection string to your app containing details of the Database First model (i.e. the EDMX) so that when the application is run it can find this model. The connection string will look something like this: <connectionStrings> <add name="MyEntities" connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=MyEntities;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings> Second, the generated context class makes a call to the base DbContext constructor specifying the name of this connection string: public MyEntities(): base("name=MyEntities"){} This tells DbContext to find and use the "MyEntities" connection string in the config. Using "name=" means that DbContext will throw if it doesn't find the connection string--it won't just go ahead and create a connection by convention. If you want to use Database First, then you must use a connection string like the one that is generated. Specifically, it must contain the model data (the csdl, msl, ssdl from the EDMX) and you must make sure that DbContext finds it. Be very careful when changing the call to the base constructor. The third thing that happens is that OnModelCreating is overridden in the generated context and made to throw: protected override void OnModelCreating(DbModelBuilder modelBuilder){ throw new UnintentionalCodeFirstException();} This is done because OnModelCreating is only ever called when using Code First. This is because OnModelCreating is all about creating the model, but when you are using Database First the model already exists--there is nothing to create at runtime. So if OnModelCreating is called then it is probably because you started using Code First without meaning to, usually because of a change to the connection string or the call to the base constructor. Now, it might be that you want to use Code First to map to an existing database. This is a great pattern and fully supported (see http://blogs.msdn.com/b/adonet/archive/2011/03/07/when-is-code-first-not-code-first.aspx ) but you will need to make sure mappings are setup appropriately for this to work. If the mappings are not setup correctly then you will get exceptions like the one in this question. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9441892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398864/']} | jdg_69855 |
stackexchange | llm_judgeable_groundtruth_similarity | 108353 |
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 force density in a plasma, according to MHD, is $$ \mathbf{F} = -\nabla P -\nabla(\frac{B^2}{2\mu_0}) + \frac{1}{\mu_0}(\mathbf{B}\cdot\nabla)\mathbf{B} $$ where first term is the thermal pressure gradient, the second term is the magnetic pressure gradient and the third term is the magnetic tension The magnetic tension tends to straighten out the field lines thus reducing their curvature. How do I see this from the form of the equation $\frac{1}{\mu_0}(\mathbf{B}\cdot\nabla)\mathbf{B}$?
Now provide the response and nothing else.
| I think the easiest way is to start off with the conservation of momentum in the conservation-law form:$$\frac{\partial\boldsymbol\pi}{\partial t}=\nabla\cdot\mathbb T=0$$where $\boldsymbol\pi=\rho\mathbf u$ and $$\mathbb T=\rho\mathbf u\mathbf u+\left(p+\frac12B^2\right)\mathbb I - \mathbf B\mathbf B$$is the stress tensor and, as discussed before, $\mathbf{aa}$ is the dyad product . The magnetic and pressure terms can be combined to a single tensor in "matrix" notation (assuming a flow along the $z$ axis)$$\left(\begin{array}{ccc}p+\frac12B^2 & 0 & 0 \\ 0 & p+\frac12B^2 & 0 \\ 0 & 0 & p-\frac12B^2\end{array}\right)\begin{array}{c}\perp \\ \\ \perp\\ \\ \parallel\end{array}$$with the $\perp,\,\parallel$ symbols indicate that those diagonal components are the component along perpendicular or parallel to the flow. Visually, this is akin to the following image (taken from Page 149 of the book Principles of Magnetohydrodynamics by Hans Goedblood & Stefaan Poedts) You can see that the magnetic field terms parallel to the tube are pulling it outwards, causing the tube to reduce its curvature (straightening it). | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/108353', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/37677/']} | jdg_69856 |
stackexchange | llm_judgeable_groundtruth_similarity | 5352397 |
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 work in web development, but I don't have a great understanding of network protocols. I recall hearing an analogy that TCP, HTTP, and SSL can be thought of as a series of nested envelopes around the actual request content. I also have a fuzzy idea TCP consists of packets, which are verified on the other end. But I'm sort of picturing the HTTP request being chopped into packets, too... So basically, I don't understand this stuff well at all. Can anybody give a good overview of this? Also, is there a beginner-friendly book or other resource that you'd recommend?
Now provide the response and nothing else.
| Since I asked this question, I've learned more about this topic, so I'll take a crack at answering it myself. The easiest way to picture the protocol stack is as a letter, wrapped in a series of envelopes. Each envelope has a different role in getting the letter to its recipient, and envelopes are added and removed as needed along the journey. The Application Layer The letter itself is an application-layer request. For example, you've typed "StackOverflow.com" in your browser and pressed enter. Your browser needs to ask the StackOverflow server for its home page. So it writes a letter saying, "Dear StackOverflow, would you please send me your home page?" If the writer of the letter is your browser, the recipient of the letter is the web server program running on StackOverflow. The browser wants the web server to "write back" with a response in the form of a web page. Both the browser and server are applications - programs running on specific computers. Because browsers speak HTTP, that's what it uses to make the request: the letter says something like "GET http://stackoverflow.com ". The browser also writes down any cookie information it got from StackOverflow last time ("remember me? You told me my login ID was X") and adds some miscellaneous labeled information called "headers" (things like "I'm Firefox" and "I can accept HTML or text" and "it's OK with me if you compress the content with gzip"). All that information will help the server know how to personalize or customize its response. At that point, the browser is basically done. It hands this letter to the operating system and says, "would you please send this for me?" The OS says, "Sure." It then does some work to connect to StackOverflow (more on that in a minute), then tells the browser, "I'm working on it. By the way, here's a little mail bin I made for you, called a socket. When I hear back from StackOverflow, I'll put its letter in there and you can read it just like a file." The browser then happily awaits the response. The IP layer To send the request from the browser to StackOverflow, the operating system has to do several things. First, it has to look up the address for StackOverflow.com - specifically, the IP address. It does this using DNS (which I won't go into here). Once it knows the IP address, it will know how to wrap the request in one of the "envelopes" called the IP layer. Why do we need the IP layer? Well, once upon a time, we didn't. Why we need IP Have you ever seen an old movie where someone makes a phone call by asking the operator to connect them? The operator would physically connect the wire from Person #1's house to the wire for Person #2's house. Before the protocol stack was invented, connecting computers was a lot like that phone call: you needed a dedicated wire from point to point. So, for example, if the computer scientists at Stanford wanted to exchange data with the ones at Harvard, they'd pay a bunch of money to rent a dedicated wire between the two places (a "leased line"). Any data that went into one end came out reliably at the other end. However, this was very expensive: imagine paying for a separate line for every place you want to connect to! People realized that this wouldn't scale up. We needed a way to have a network that was shared by all users, like a giant spiderweb of wires spread out all over the map. That way, each user would only need one connection to the network and could reach any other user through it. But that presented a problem. If everyone's communications went on the same lines, how would the data get to the right place? Imagine a bunch of letters dumped on a conveyor belt. Obviously, every letter needs to be addressed to someone, or else they can't be delivered. That's the basic idea of IP: every machine needs to have an IP address that uniquely identifies it. Messages are placed in IP packets, which are like envelopes with addresses and return addresses. So, once the OS has looked up the IP address for Stackoverflow.com, it puts the HTTP request in an IP envelope. If it's a "long letter", too big for one envelope, the OS cuts it into pieces and puts it in several IP envelopes. Each envelope says something like "FROM: (your IP address); TO: (The Server's IP address." Like the HTTP request, the IP packet has some other miscellaneous header information, which we won't go into here, but the basic idea is just "to" and "from." So, at this point, the letter is ready to go, right? The messiness of IP Not quite. This letter could easily get lost! See, with IP, we no longer have a dedicated line from place to place. If we did, we'd be sure that our letters were getting delivered: as long as the line wasn't broken, everything would go through. But with IP, everyone's packets get dumped onto conveyor belts and carried along. The belts lead to little sorting stations, called "routers". If you imagine the routers like physical mail centers, you could picture one in, say, New York City. "Here's a letter headed for Mexico City. I don't know exactly how to get there, but the station in Houston should be able to get it closer, so I'll send it there. Ah, here's a letter that's going to Atlanta. I'll send it to Charlotte; they should be able to forward it a step closer." Generally this system works OK, but it's not as reliable as having your own dedicated line. Nearly anything could happen en route: a conveyor belt could break or catch fire, and everything on it could be lost. Or one could get bogged down for a while, so that its packets are delivered very late. Besides that, because these conveyor belts and stations are used by everyone, nobody's letters get treated specially. So what happens if a router gets more letters than it can possibly handle? For a while, it can stack them in a corner (maybe in RAM), but eventually, it runs out of space. What it does then may seem shocking: it starts throwing them away. Yep. That's it. You might think that it would at least be kind enough to send back a note to you, saying, "sorry, we couldn't deliver your letter." But it doesn't. If you think about it, if the router is overwhelmed, it's probably because there's too much traffic on the lines already. Adding apology notes would only make the problem worse. So it throws away your packet and doesn't bother telling anyone. Obviously, this is a problem for our HTTP request. We need it to get there, and we need the response to get back reliably, too. To make sure it gets there, we want some kind of "delivery confirmation" service. For that, we'll wrap another envelope around our HTTP request before putting into IP packets. That layer is called TCP. TCP TCP stands for "transfer control protocol." It exists to control what would otherwise be a messy, error-prone delivery process. As implied before, TCP lets us add some "delivery confirmation" to this messy delivery system. Before we wrap our HTTP request in IP packets, we first put it into TCP packets. Each one gets a number: packet 1 of 5, 2 of 5, etc. (The numbering scheme is actually more complicated and counts bytes rather than packets, but let's ignore that for now.) The basic idea of TCP is this: First, the client and server - in this case, your operating system and the StackOverflow server's operating system - do a "handshake" to establish a "connection". Both words needs quotes because the "handshake" is actually a few messages back and forth, proving that packets can get successfully there and back, and the "connection" is really nothing more than each side deciding that they'll keep track of the packets flowing between them. Next, they send packets back and forth; the client maybe requesting a web page, and the server maybe sending it back (in as many packets as that takes). As one side receives packets, it sends back confirmation messages, saying "so far I've received your packets up to packet 100" and so forth. If one party sends packets and doesn't hear a confirmation for a while, it will assume they were lost and re-send them. (Getting confirmations when things arrive at the other end is better than getting error reports when a router drops things along the way for a couple of reasons. One is that confirmations go back over a working connection, whereas errors would further clog a non-working connection. Another is that we don't have to trust the intermediary routers to do the right thing; the client and server are the ones who care most about this particular conversation, so they're the ones who take charge of being sure that it works.) Besides making sure that all the data gets to the other end, TCP also makes sure that the received data gets put back into the right order before handing it up the stack, in case earlier packets got resent and arrived later, or packets in the middle took a longer route, or whatever. That's basically it - having this kind of delivery confirmation makes the unreliable IP network reliable. Why wasn't it built straight into IP? UDP Well, confirmation has a drawback: it makes things slower. If something is missed, it must be repeated. In some cases, that would be a waste of time, because what you really want is a real-time connection. For example, if you're having a phone conversation over IP, or you're playing a real-time game over the internet, you want to know what's happening right now , even if it means you miss a bit of what happened a second ago. If you stop to repeat things, you'll fall out of sync with everyone else. In cases like that, you can use a cousin of TCP called UDP, which doesn't re-send lost packets. UDP stands for "user datagram protocol", but many people think of it as "unreliable data protocol". That's not an insult; sometimes reliability is less important than staying current. Since both of these are valid use cases, it makes sense that the IP protocol stayed neutral on the issue of reliability; those who use it can choose whether to add reliability or not. Both TCP and UDP add one other important piece of information to the request: a port number. Port numbers Remember, our original request is comes from a browser and is going to a web server program. But the IP protocol only has addresses that specify computers, not the applications running on them. The machine with StackOverflow's web server may also have other server programs that are listening for requests: a database server, an FTP server, etc. When that machine gets the request, how will it know which program should handle it? It will know because the TCP request has a port number on it. This is just a number, nothing fancy, but by convention, certain numbers are interpreted to mean certain things. For example, using a port number of 80 is a conventional way of saying "this is a request for a web server." Then the server machine's operating system will know to hand that request to the web server program and not, say, the FTP server program. When the TCP packets start streaming back to your computer, they will also have a port number, to let your machine know which program to give the response to. That number will vary based on the socket that your machine created initially. Wait, what's a socket? Sockets Remember earlier when the browser asked the OS to send the request? The OS said it would set up a "mail bin" for any response it got back. That bin is called a socket. You can think of a socket sort of like a file. A file is an interface that the OS provides. It says, "you can read and write data here, and I will take care of figuring out how to actually store it on the hard drive or USB key or whatever." The thing that uniquely identifies a file is the combination of path and filename. In other words, you can only have one file located in the same folder with the same name. Similarly, a socket is an interface the OS provides. It says, "you can write requests here and read responses." The thing that uniquely identifies a socket is the combination of four things: Destination IP Destination Port Source IP Source Port So, you can only have one socket on a system with the same combination of all of those. Notice that you could easily have several sockets open to the same destination IP and port - say, StackOverflow's web server - as long as they all have different source ports. The OS will guarantee that they do by choosing an arbitrary source port for each request, which is why you can have several tabs or several browsers all requesting the same web site simultaneously without anything getting confused; the packets coming back all say which port on your computer they're headed for, which lets the OS know "ah, this packet is for tab 3 in Firefox" or whatever. Summing up so far We've been thinking of the protocols as a series of envelops wrapped around the letter. In our example, the letter was an HTTP request, which got wrapped in TCP, then in IP. The IP packets get sent to the right destination computer. That computer removes the IP "envelope" and finds a TCP packet inside. The TCP packet has a port number, which lets the operating system know which port to collect its information in. It replies saying that it got that packet, and it puts its contents (the HTTP request) into the correct socket for the appropriate program to read from. When that program writes a reponse to the socket, the OS sends it back to the requester. So our "stack" is: An HTTP request (a "letter"). This is the application layer. Wrapped in TCP packets ("envelopes"). This is the transport layer. Wrapped in IP packets ("envelopes"). This is the IP layer. It's important to understand that this stack is totally customizable. All of these "protocols" are just standard ways of doing things. You can put anything you want inside of an IP packet if you think the receiving computer will know what to do with it, and you can put anything you want inside a TCP or UDP packet if you think the receiving application will know what to do with it. You could even put something else inside your HTTP request. You could say that some JSON data in there is the "phone number exchange protocol," and as long as both ends know what to do with it, that's fine, and you've just added a higher-level protocol. Of course, there's a limit to how "high" you can go in the stack - that is, you can put a smaller envelope inside HTTP, and a smaller one inside that, etc, but eventually you won't have any room to go smaller; you won't have any bits for actual content. But you can easily go "lower" in the stack; you can wrap more "envelopes" around the existing ones. Other protocol layers Once common "envelope" to wrap around IP is Ethernet. For example, when your computer decides to send IP packets to Google, it wraps them up as we've described so far, but to send them, it gives them to your network card. The network card may then wrap the IP packets in Ethernet packets (or token ring packets, if you've got an antique setup), addressing them to your router and sending them there. Your router removes those Ethernet "envelopes", checks the IP address, decides who the next closest router is, wraps another Ethernet envelope addressed to that router, and sends the packet along. Other protocols could be wrapped as well. Maybe two devices are only connected wirelessly, so they wrap their Ethernet packets in a Wi-Fi or Bluetooth or 4G protocol. Maybe your packets need to cross a village with no electricity, so someone physically prints the packets on paper with numbered pages, rides them across town on a bicycle, and scans them into another computer in the order of the page numbers. Voila! A print-to-OCR protocol. Or maybe, I don't know, TCP over carrier pigeon would be better. Conclusion The protocol stack is a beautiful invention, and it works so well that we generally take it for granted. It is a great example of abstracting functionality: each layer has its own work to do and can rely on others to deal with the rest. The application layer is only concerned with applications talking to each other: "Firefox wants to talk to the web server at StackOverflow.com." The transport layer is only concerned with getting a stream of packets delivered correctly from one app to another: "all the packets from port 123 on machine 1 need to get to port 80 on machine 2". The IP layer is only concerned with routing individual packets: "this packet needs to get to the following IP address." The link layer is only concerned with getting packets from one waypoint to the next: "this ethernet packet needs to get from the network card to the router." The physical layer is only concerned with signal transmission: "these pulses need to be sent over this wire." (Although these layer terms are borrowed from OSI , OSI was actually a competing standard to TCP/IP, and included things like the "session layer" and "presentation layer" that TCP/IP doesn't use. OSI was intended to be a more sane and standardized alternative to the scrappy hacked-together TCP/IP stack, but while it was still being discussed, TCP/IP was already working and was widely adopted.) Because the layers can be mixed and matched as needed, the stack is flexible enough to accommodate nearly any use we can think of, so it's probably going to be around for a long time. And hopefully now you can appreciate it a bit more. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5352397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4376/']} | jdg_69857 |
stackexchange | llm_judgeable_groundtruth_similarity | 23748572 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is a way to initialize Numeric vector with NA values like. NumericVector x(10,NumericVector::get_na()) is there any similar way to initialize a matrix to NA values?
Now provide the response and nothing else.
| Here is a version that does not waste memory. #include <Rcpp.h>using namespace Rcpp ;// [[Rcpp::export]]NumericMatrix na_matrix(int n){ NumericMatrix m(n,n) ; std::fill( m.begin(), m.end(), NumericVector::get_na() ) ; return m ;} FWIW, in Rcpp11 , you can use some more expressive syntax: NumericMatrix m(n,n, NA) ; Thanks to this constructor | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23748572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1377976/']} | jdg_69858 |
stackexchange | llm_judgeable_groundtruth_similarity | 459522 |
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:
Suppose that the matrix $A$ is not diagonalizable. Show that for all $\epsilon>0$, there exists a diagonalizable matrix $A_{\epsilon}$ such that $||A-A_{\epsilon}||_{2}<\epsilon$. Can anyone help me prove this or give a hint?
Now provide the response and nothing else.
| This follows straight from the Schur decomposition. Let $A = U T U^*$ be nondiagonalizable. Here, $U$ is unitary and $T$ is triangular, with the elements $t_{ij}$. Let $\varepsilon_i$, $i = 1,\dots,n$ be such that $$t_{ii} + \varepsilon_i \ne t_{jj} + \varepsilon_j, \quad \text{for all $i \ne j$}$$ and $|\varepsilon_i|$ sufficiently small. I leave it to you to show that this can always be done. Define $T' := T + \operatorname{diag}(\varepsilon_1, \dots, \varepsilon_n)$ and $A_\varepsilon := U T' U^*$. Obviously, all eigenvalues of $A_\varepsilon$ are distinct, so $A_\varepsilon$ is diagonalizable. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/459522', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/88734/']} | jdg_69859 |
stackexchange | llm_judgeable_groundtruth_similarity | 2132639 |
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 missing something essential in my understanding of matrices as linear mappings (or matrices in general). To explain, I think I have a decent intuition for columnspace of a matrix. Basically, the columnspace can be thought of as the set of points other than the origin which can be mapped by the matrix of a linear mapping (I like to think of matrices in general as linear mappings). What I have trouble with is the significance and geometric interpretation of the rowspace of a matrix. By the definition, I can see that the rowspace and columnspace are analagous; the rowspace is merely the columnspace of the transpose of the matrix of the linear mapping. However, I cannot explain this anymore intuitively than above. To quote Albert Einstein, "if you don't understand it simply, you don't understand it well enough". I am looking for a simple explanation (or geometric interpretation that will contribute to my imagination of linear mappings). How would you explain this concept? To give you some context, I ran into problems when my course started to discuss the following: For an $n \times n$ matrix $P$, the following are equivalent: (1) The columns of $P$ form an orthonormal basis for $\mathbb{R}^n$ (2) $P^T = P^{-1}$ (3) The rows of $P$ form an orthonormal basis for $\mathbb{R}^n$. I understand the algebra perfectly, but I seek a level of intuition so that I would not need to fiddle around with algebra to discover these facts. How would you explain the above concepts intuitively or geometrically, without the need for algebra to make a case? Many thanks in advance.
Now provide the response and nothing else.
| As Ted Shifrin states in his comment to your question, the rowspace of a real matrix is the orthogonal complement of its nullspace. In fact, we have the following relationships for any (not necessarily square) real matrix $A$ : $$\mathscr{C}(A^T)=\mathscr{N}(A)^\perp \\ \mathscr{N}(A^T)=\mathscr{C}(A)^\perp.$$ There is an equivalent pair of statements about a linear map, its adjoint map and annihilators of subspaces. One consequence of these relationships is that the rowspace of a matrix is a maximal-dimension subspace of the domain for which the linear map defined by the matrix is injective. Another possible way to view the rowspace is as the space of representative elements of the quotient space $\mathbb R^m/\mathscr{N}(A)$ , where $m$ is the number of columns of $A$ . In light of this, the rowspace of a matrix can be considered the “natural” preimage of its column space. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2132639', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/338817/']} | jdg_69860 |
stackexchange | llm_judgeable_groundtruth_similarity | 71850 |
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 I prove that the Cartesian product of two countable sets is also countable?
Now provide the response and nothing else.
| In your answer you use Cantor's pairing function. It is an important function indeed. However using Cantor-Bernstein's theorem we only need to find an injection from $\mathbb N\times\mathbb N$ into $\mathbb N$. A useful example is: $$f(m,n) = 2^m\cdot 3^n$$ If $f(m,n)=f(l,k)$ then by the fundamental theorem of arithmetics we have that $m=l, n=k$. We now can find an injection $g\colon\mathbb N\to\mathbb N\times\mathbb N$, for example $g(n)=(0,n)$. Now Cantor-Bernstein's theorem tells us that if $f\colon A\to B$ and $g\colon B\to A$ are two injective functions, then there is a bijection from $A$ into $B$. From this to $\mathbb N^k$ being countable, you can either go with induction, as you suggested, or map $(m_1,\ldots,m_k)$ to $p_1^{m_1}\cdot\ldots p_k^{m_k}$, where $p_i$ is the $i$-th prime number. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/71850', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12510/']} | jdg_69861 |
stackexchange | llm_judgeable_groundtruth_similarity | 6667201 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to define a two-dimensional array without an initialized length like this: Matrix = [][] But this gives an error: IndexError: list index out of range
Now provide the response and nothing else.
| You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this"list comprehension". # Creates a list containing 5 lists, each of 8 items, all set to 0w, h = 8, 5Matrix = [[0 for x in range(w)] for y in range(h)] #You can now add items to the list: Matrix[0][0] = 1Matrix[6][0] = 3 # error! range... Matrix[0][6] = 3 # valid Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index". print Matrix[0][0] # prints 1x, y = 0, 6 print Matrix[x][y] # prints 3; be careful with indexing! Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix. | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/6667201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838242/']} | jdg_69862 |
stackexchange | llm_judgeable_groundtruth_similarity | 19197471 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I get the current date in MS-SQL Server 2008 R2? The format of the column in my database is DATETIME and dates are stored in the following format: +++++++++++++ Vrdate ++++++++++| || 2012-11-18 00:00:00.000 || 2012-11-19 00:00:00.000 || 2013-11-18 00:00:00.000 || 2012-12-01 00:00:00.000 || 2010-10-09 00:00:00.000 || 2012-11-11 00:00:00.000 || |+++++++++++++++++++++++++++++++ I searched but wasn't able to find the way to get the date in this format (i.e. which has the time associated with it in 00:00:00.00 ). I found GETDATE() function but that provides the current time along with the date as well, what I want is get the date in the following format: CurrentDate 00:00:00.00 How may I get this?
Now provide the response and nothing else.
| SELECT CAST(GETDATE() AS DATE) Returns the current date with the time part removed. DATETIME s are not "stored in the following format". They are stored in a binary format. SELECT CAST(GETDATE() AS BINARY(8)) The display format in the question is independent of storage. Formatting into a particular display format should be done by your application. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19197471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1931097/']} | jdg_69863 |
stackexchange | llm_judgeable_groundtruth_similarity | 17339461 |
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 define a macro for unifying all fonts in my app: #define EXO_REGULAR_FONT(size) [UIFont fontWithName:@"Exo-Regular" size:size] and than using this macro like this: myLabel.font = EXO_REGULAR_FONT(15); But the compiler give me this error: (there is an arrow under 15). Any ideas to resolve ? Thanks
Now provide the response and nothing else.
| Change the name of your parameter: #define EXO_REGULAR_FONT(theFontSize) [UIFont fontWithName:@"Exo-Regular" size:theFontSize] From GCC manual : When the macro is expanded, each use of a parameter in its body is replaced by the tokens of the corresponding argument So when your macro is expanded, it inserts this in your code, hence the compilation error: [UIFont fontWithName:@"Exo-Regular" 15:15] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17339461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1006113/']} | jdg_69864 |
stackexchange | llm_judgeable_groundtruth_similarity | 111326 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In "The Potts model and the Tutte Polynomial", D.J.A. Welsh and C. Merino claim on pg. 1135, equation 18, that,\begin{align*}\sum_{i=0}^{n-1}f_i t^i = t^{n-1}T_G(1+\frac{1}{t},1)\end{align*}where $T_G(x,y)$ is the Tutte polynomial of some graph $G$ and $f_i$ denotes the number of forests of $G$ with exactly $i$ edges. Their paper is available online here . Welsh and Merino do not give any citations or proof for this claim. Does anyone know of such a proof? Also, is there a more explicit formula for $f_i$ in terms of $T_G(x,y)$? EDIT: I noticed recently that something must be wrong with the claimed formula because if $G$ is the disjoint union of $n$ isolated vertices, then $T_G(x,y) = 1$, so the righthand side becomes $t^{n-1}$; however the lefthand side is $1$. Implicitly Welsh and Merino are assuming that $G$ is connected or I do not know what is meant by the "size" of a forest.
Now provide the response and nothing else.
| Here are two quick ways of proving this: (1) Notice that one of the many equivalent definitions of the Tutte polynomial says$$T_G(x,y)=\sum_{A\subset E}(x-1)^{k(A)-k(E)}(y-1)^{k(A)+|A|-|V|}$$Where $A$ runs through subsets of the edges of $G$, and the function $k(A)$ measures the number of components of the graph $(V,A)$. Here you only need consider the terms where $k(A)+|A|=|V|$, which happens precisely when $(A,V)$ is a forest! (2) Remember that the Tutte polynomial satisfies the deletion-contraction relation$$T_{G}(x,y)=T_{G/e}(x,y)+T_{G-e}(x,y),$$when $e$ is neither a loop nor a bridge. So you only need to show that the generating function of forests of a graph also satisfies this recurrence, as well as the "initial conditions" that it agrees with $t^{|E|-1}T_G(1+\frac{1}{t},1)$ for $G$ a tree. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/111326', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25028/']} | jdg_69865 |
stackexchange | llm_judgeable_groundtruth_similarity | 1498605 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $x,y,z$ be positive real numbers such that $x^2y^2+y^2z^2+z^2x^2\ge x^2y^2z^2$. Find the minimum value of$$\frac{x^2y^2} {z^3(x^2+y^2)}+\frac {y^2z^2} {x^3(y^2+z^2)}+\frac {z^2x^2} {y^3(z^2+x^2)}$$I'm pretty sure that the answer would be $\frac {\sqrt {3}} {2}$, when all parameters are $\sqrt {3}$. But I couldn't prove it after some hours of thinking. So can anyone help me?Any help would be welcome.Thanks:D.
Now provide the response and nothing else.
| Let$$a=\dfrac{1}{x},b=\dfrac{1}{y},c=\dfrac{1}{z},a^2+b^2+c^2\ge 1$$Use Cauchy-Schwarz $$\sum_{cyc}\dfrac{x^2y^2}{z^3(x^2+y^2)}=\sum_{cyc}\dfrac{c^3}{(a^2+b^2)}\ge \dfrac{(a^2+b^2+c^2)^2}{c(a^2+b^2)+a(b^2+c^2)+b(c^2+a^2)}$$since$$c(a^2+b^2)+a(b^2+c^2)+b(c^2+a^2)\le\dfrac{2}{3}(a+b+c)(a^2+b^2+c^2)\le\dfrac{2}{\sqrt{3}}(a^2+b^2+c^2)^{\frac{3}{2}}$$so$$LHS\ge \dfrac{\sqrt{3}}{2}\sqrt{a^2+b^2+c^2}\ge\dfrac{\sqrt{3}}{2}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1498605', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/280974/']} | jdg_69866 |
stackexchange | llm_judgeable_groundtruth_similarity | 1272454 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have the following code which update a field of a struct using reflection. Since the struct instance is copied into the DynamicUpdate method, it needs to be boxed to an object before being passed . struct Person{ public int id;}class Test{ static void Main() { object person = RuntimeHelpers.GetObjectValue(new Person()); DynamicUpdate(person); Console.WriteLine(((Person)person).id); // print 10 } private static void DynamicUpdate(object o) { FieldInfo field = typeof(Person).GetField("id"); field.SetValue(o, 10); }} The code works fine. Now, let's say I don't want to use reflection because it's slow. Instead, I want to generate some CIL directly modifying the id field and convert that CIL into a reusable delegate (say, using Dynamic Method feature). Specially, I want to replace the above code with s/t like this: static void Main(){ var action = CreateSetIdDelegate(typeof(Person)); object person = RuntimeHelpers.GetObjectValue(new Person()); action(person, 10); Console.WriteLine(((Person)person).id); // print 10}private static Action<object, object> CreateSetIdDelegate(Type t){ // build dynamic method and return delegate} My question: is there any way to implement CreateSetIdDelegate excepts from using one of the following techniques? Generate CIL that invoke the setter using reflection (as the 1st code segment in this post). This makes no sense, given the requirement is to get rid of reflection, but it's a possible implementation so I just mention. Instead of using Action<object, object> , use a custom delegate whose signature is public delegate void Setter(ref object target, object value) . Instead of using Action<object, object> , use Action<object[], object> with the 1st element of the array being the target object. The reason I don't like 2 & 3 is because I don't want to have different delegates for the setter of object and setter of struct (as well as not wanting to make the set-object-field delegate more complicated than necessary, e.g. Action<object, object> ). I reckon that the implementation of CreateSetIdDelegate would generate different CIL depending whether the target type is struct or object, but I want it to return the same delegate offering the same API to user.
Now provide the response and nothing else.
| EDIT again : This works structs now. There's a gorgeous way to do it in C# 4, but you'll have to write your own ILGenerator emit code for anything before that. They added an ExpressionType.Assign to the .NET Framework 4. This works in C# 4 (tested): public delegate void ByRefStructAction(ref SomeType instance, object value);private static ByRefStructAction BuildSetter(FieldInfo field){ ParameterExpression instance = Expression.Parameter(typeof(SomeType).MakeByRefType(), "instance"); ParameterExpression value = Expression.Parameter(typeof(object), "value"); Expression<ByRefStructAction> expr = Expression.Lambda<ByRefStructAction>( Expression.Assign( Expression.Field(instance, field), Expression.Convert(value, field.FieldType)), instance, value); return expr.Compile();} Edit: Here was my test code. public struct SomeType{ public int member;}[TestMethod]public void TestIL(){ FieldInfo field = typeof(SomeType).GetField("member"); var setter = BuildSetter(field); SomeType instance = new SomeType(); int value = 12; setter(ref instance, value); Assert.AreEqual(value, instance.member);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1272454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17815/']} | jdg_69867 |
stackexchange | llm_judgeable_groundtruth_similarity | 20657 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Some people say that it's awful that humans eat animals. They feel that it's barbaric, because you're killing life and then on top of that, you're eating it, and that you should eat vegetation instead. But isn't vegetation life too? Personally, I see no difference between animals and veg as all life has cells, dna etc So my question is, is it possible for humans to live healthy long lives without eating any type of life, i.e no animals, no plants, no cells (dead or alive) etc? If it is possible, how would it be done?
Now provide the response and nothing else.
| The answer to your question is yes it is certainly possible. At one time it was thought that there was something special about "organic" chemicals which meant that they could not be artificially synthesised out of fundamental elements. In 1828 Frederick Wöhler synthesised urea (CO(NH 2 ) 2 ) which is often taken as the first demonstration that the organic v inorganic distinction was not a sound one (for more on this see the Wikipedia article on Wöhler synthesis . As far as we know all essential human nutrients can be synthesised from inorganic ingredients, even complex molecules such as Vitamin B 12 . Other contributors have pointed out that organic pathways for synthesising our food have evolved over long periods to be very efficient - at least in the conditions prevailing on Earth. You haven't ruled out copying biochemical pathways using chemicals that are entirely of inorganic origin. Anyone trying to do this seriously could create glucose (for example) by artificially creating enzymes (perhaps via artificial DNA) to do the job. The thing is that we already have self-replicating and repairing machines to do that already (plants). There might be circumstances when we needed to use artificial synthesis. I can think of two science-fiction stories that deal with this question, the first of which goes into some detail: The Moon is Hell by John W. Campbell, in which astronauts are stranded on the moon and forced to make food from what they find there. Technical Error by Arthur C. Clarke, in which a man is accidentally rotated through the fourth dimension. His employers contemplate the difficulty caused by the "handedness" of many biological molecules meaning they would have to artificially synthesise many of his foods. It may be that a future expedition to Mars (say) might have to think about these things. A little searching fails to come up with standard inorganic syntheses of glucose and similar substances. The reason for this is almost certainly because it is so easy to use organic inputs. Glucose is easily made by the hydrolysis of starch. Starch is very common and cheap. Even l-glucose is usually made out of organically derived precursors (or sometimes even using d-glucose). UPDATE: sources etc One problematic question is: where do you get your input for making nutrients? As others have pointed out, exactly where to draw the line is difficult. This problem starts in defining what is alive in the first place. Do you count viruses (which can go down to a few thousand base pairs of RNA) or satellite viruses (STobRV has only 359 base pairs) or prions? In a sense these are "just" very large molecules. But then really simple bacteria are not many orders of magnitude more complex. As an aside most systems of ethics that do not permit eating meat do not make an alive/non-alive distinction, choosing some other aspect such as sentience, though Jainism comes close to doing so. The second problem is, if we reject living things as sources of food, how far removed from those living things are we allowed to get? You say no cells in any state including "dead". That would exclude (say) fruit even though most fruits are expressly created by plants in order to be eaten (and in some cases must be eaten) - something that vegans, jains, fruitarians and others would be happy with eating. If we could use dead material things would be much easier. But would you also include hydrocarbons (coal, oil, gas) which were once living organisms? If you do, then you are in difficulty because terrestrial carbon is recycled through the biosphere. All CO2 was (to a close approximation) once a part of a living thing. If you take that position then of course you are going to have to go off-planet to find your source chemicals and your problem becomes very much harder. I was assuming that you were restricting yourself to consuming cells that retain some of their cell structure but had not completely degraded. If that is where you draw the line then there are ample sources of raw materials on earth. Genetic modification is much more science fiction though not entirely impossible. Some nutrients could be made by humans without much difficulty. Our inability to manufacture vitamin C is down to one missing enzyme (L-gulono-gamma-lactone oxidase) which is present in most vertebrates (I think of mammals only guinea pigs, humans and some bats are unable to synthesise it). You could certainly imagine some very careful genetic modification changing humans so they no longer need to consume vitamin C. But photosynthesis would be much harder. Chloroplasts (which do the job in most plants) are really a very primitive form of life living in plant cells which may independently reproduce (and for that reason might be excluded by you - they aren't "cells" but they have membranes). They could easily end up in conflict with our mitochondria (since intracellular conflict between organelles is possible) and you would need to do enormous amounts of work to make human cells co-operate with them properly. More in keeping with your theme would be adding photosynthetic systems directly to human cells along with a suite of enzymes to manufacture all the things we cannot. That is of course in principle scientifically possible (since plants do it) but much harder than it looks. Living systems are very complicated and small changes can have unexpected consequences. Even very minor genetic modifications are problematic. The human autotroph is likely to be some way off. | {} | {'log_upvote_score': 7, 'links': ['https://biology.stackexchange.com/questions/20657', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/668/']} | jdg_69868 |
stackexchange | llm_judgeable_groundtruth_similarity | 248548 |
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:
Gödel's ontological proof is a formal argument for God's existence by the mathematician Kurt Gödel. Can someone please explain what are the symbols in the proof and elaborate about its flow: $$\begin{array}{rl} \text{Ax. 1.} & \left\{P(\varphi) \wedge \Box \; \forall x[\varphi(x) \to \psi(x)]\right\} \to P(\psi) \\ \text{Ax. 2.} & P(\neg \varphi) \leftrightarrow \neg P(\varphi) \\ \text{Th. 1.} & P(\varphi) \to \Diamond \; \exists x[\varphi(x)] \\ \text{Df. 1.} & G(x) \iff \forall \varphi [P(\varphi) \to \varphi(x)] \\ \text{Ax. 3.} & P(G) \\ \text{Th. 2.} & \Diamond \; \exists x \; G(x) \\ \text{Df. 2.} & \varphi \text{ ess } x \iff \varphi(x) \wedge \forall \psi \left\{\psi(x) \to \Box \; \forall y[\varphi(y) \to \psi(y)]\right\} \\ \text{Ax. 4.} & P(\varphi) \to \Box \; P(\varphi) \\ \text{Th. 3.} & G(x) \to G \text{ ess } x \\ \text{Df. 3.} & E(x) \iff \forall \varphi[\varphi \text{ ess } x \to \Box \; \exists y \; \varphi(y)] \\ \text{Ax. 5.} & P(E) \\ \text{Th. 4.} & \Box \; \exists x \; G(x) \end{array} $$ Does it prove both existence and uniqueness? Edit: these are modal logic symbols.
Now provide the response and nothing else.
| The modal operator $\square$ refers to necessity; its dual, $\lozenge$, refers to possibility. (A sentence is necessarily true iff it isn't possible for it to be false, and vice versa.) $P(\varphi)$ means that $\varphi$ is a positive (in the sense of "good") property; I'll just transcribe it as "$\varphi$ is good". I'll write out the argument colloquially, with the loss of precision that implies. In particular, the words "possible" and "necessary" are vague, and you need to understand modal logic somewhat to follow their precise usage in this argument. Axiom $1$: If $\varphi$ is good, and $\varphi$ forces $\psi$ (that is, it's necessarily true that anything with property $\varphi$ has property $\psi$), then $\psi$ is also good. Axiom $2$: For every property $\varphi$, exactly one of $\varphi$ and $\neg\varphi$ is good. (If $\neg\varphi$ is good, we may as well say that $\varphi$ is bad.) Theorem $1$ (Good Things Happen): If $\varphi$ is good, then it's possible that something exists with property $\varphi$. Proof of Theorem $1$: Suppose $\varphi$ were good, but necessarily nothing had property $\varphi$. Then property $\varphi$ would, vacuously, force every other property; in particular $\varphi$ would force $\neg\varphi$. By Axiom $1$, this would mean that $\neg\varphi$ was also good; but this would then contradict Axiom $2$. Definition $1$: We call a thing godlike when it has every good property. Axiom $3$: Being godlike is good. Theorem $2$ (No Atheism): It's possible that something godlike exists. Proof of Theorem $2$: This follows directly from Theorem $1$ applied to Axiom $3$. Definition $2$: We call property $\varphi$ the essence of a thing $x$ when (1) $x$ has property $\varphi$, and (2) property $\varphi$ forces every property of $x$. Axiom $4$: If $\varphi$ is good, then $\varphi$ is necessarily good. Theorem $3$ (God Has No Hair): If a thing is godlike, then being godlike is its essence. Proof of Theorem $3$: First note that if $x$ is godlike, it has all good properties (by definition) and no bad properties (by Axiom $2$). So any property that a godlike thing has is good, and is therefore necessarily good (by Axiom $4$), and is therefore necessarily possessed by anything godlike. Definition $3$: We call a thing indispensable when something with its essence (if it has an essence) must exist. Axiom $5$: Being indispensable is good. Theorem $4$ (Yes, Virginia): Something godlike necessarily exists. Proof of Theorem $4$: If something is godlike, it has every good property by definition. In particular, it's indispensable, since that's a good property (by Axiom $5$); so by definition something with its essence, which is just "being godlike" (by Theorem $3$), must exist. In other words, if something godlike exists, then it's necessary for something godlike to exist. But by Theorem $2$, it's possible that something godlike exists; so it's possible that it's necessary for something godlike to exist; and so it is, in fact, necessary for something godlike to exist. QED. Convinced? | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/248548', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24403/']} | jdg_69869 |
stackexchange | llm_judgeable_groundtruth_similarity | 4197357 |
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 just started working at a company that doesn't have any kind of source control. I brought up that we might need to get some sort of source control going and one of my co-workers suggested that we use SharePoint. I think he likes the idea because we already use sharepoint he is a big SharePoint guy. I came up with some reasons as to why we shouldn't do this. SharePoint isn't designed to be a source control tool for code. There are better (and still free) tools for the job You can't do automated deploys with sharepoint (to my knowledge) It won't integrate with any IDEs (to my knowledge) Is there anything else I should include when i'm pleading my case?
Now provide the response and nothing else.
| Why using sharepoint as a sorce control is stupid idea: Performance of sharepoint is much worse than any Source Control Tools for example Team Foundation Server or SVN Sharepint doesn't allow to compare different historical versions of the same file SharePoint dosen't allow for branching, merging and labeling. Sharepoint doesn't link changes in set of files as a one change (this is very helpful if you want to track the changes) As far as I know SP doesn't allow to have different versions of whole project in the same time. SharePoint dosen't have customized gui to manage source control code. Sharepoint doesn't allow to link requirements with code changes. For example TFS links work items with check ins. This is also very helpful if you want to track your business requirements and code changes. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4197357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226897/']} | jdg_69870 |
stackexchange | llm_judgeable_groundtruth_similarity | 35830 |
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:
Lets say we have a circuit with a voltage source and a 5 ohm resistor. The voltage source is 20 v and so the current flowing is 4 amperes (according to ohms law). Now, we add a short wire in parallel to the resistor (you can think of it as having a resistor whose resistance is 0 cpne ted in parallel with the first resistor. Finding the current flowing in each wire is hard since as you can see, we first need the equivalent resistance. The equivalent resistance is (1/((1/5)+(1/0))) and it turns out to be 0. Now using the current divider formula, each current yields 0 ampere which is wrong. Thanks
Now provide the response and nothing else.
| If the equivalent resistance is zero then there's also no voltage across it, per Ohm's Law. Then the current though the resistor is 0 V/ 5 Ω = 0 A. The current through the wire can't be calculated this way since 0 V/ 0 Ω is undefined. Then the current will depend on the source's internal resistance. If that's 1 µΩ for instance the current will be 20 V/ 0.000001 Ω = 20 MA. If the source has zero resistance current will be infinite. Either way, applying this to the current divider formula gives for the resistor path: \$ I_R = I_{tot} \dfrac{R_{tot}}{R} = I_{tot} \dfrac{0 \Omega}{5 \Omega} = 0 A \$ For the wire we get again \$ I_W = I_{tot} \dfrac{R_{tot}}{R_W} = I_{tot} \dfrac{0 \Omega}{0 \Omega} = undefined \$ And we'll have to look at the external conditions to see how high the current is. Edit "Undefined sounds crazy to me" It is, and mathematicians aren't happy with it either, but there's no other way. Any real thing you try leads to contradictions. Even the 0 volt that I claimed. (I know, I lied, but that was because otherwise I'd get dizzy. Ah, what the heck, let's go for dizziness.) The voltage across the wire||resistor is \$ V = \dfrac{R_{PSU}}{R || R_W + R_{PSU}} 20 V = \dfrac{0 \Omega}{0 \Omega + 0 \Omega} 20 V = undefined \$ I can't help it. But let's for the sake of argument say it's 10 V. 0 V didn't get us anywhere, and it has to be between 0 V and 20 V. Then the current through the resistor is 10 V/ 5 Ω = 2 A. The current through the wire is 10 V/ 0 Ω = \$\infty\$ A. If we apply KCL: \$ I_{tot} = I_R + I_W \$ That's \$ \infty A = 2 A + \infty A \$ So far so good. But if we want t0 find \$I_R\$ from this we'll see that we can't! Despite the fact that we know it's 2 A. Let's try: \$ I_R = \infty A - \infty A = undefined\$ Yeah, right, I always say undefined. Why would it be, if we know the result? OK, you're asking for it. So suppose \$ \infty - \infty = 2 \$ Now we know that \$\infty\$ + \$\infty\$ = \$\infty\$, so \$ (\infty + \infty) - \infty = 2 \$ or \$ \infty + (\infty - \infty) = 2 \$ The value between the brackets is 2, that was our assumption. Then \$ \infty + 2 = 2 \$ Subtract 2 from both sides, and \$ \infty = 0 \$ which obviously isn't true. So our assumption was false. Now you can try with any number instead of 2 you'll always end up with a contradiction. So that's how we end up with undefined stuff and a dizzy head. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/35830', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/8769/']} | jdg_69871 |
stackexchange | llm_judgeable_groundtruth_similarity | 21140815 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is my current PS1: $ echo $PS1\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]\n\$ I have installed git bash completion and it isn't showing the current branch in my command prompt. I think this needs to be edited but I've got no idea what to change to make it show the current branch. Note that I like the colors and general structure (i.e. with $ on its own line), so I'd like to keep that if possible.
Now provide the response and nothing else.
| Modify the prompt string and add $(__git_ps1 " (%s)") somewhere. For example, try typing this into Bash: export PS1="\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]$(__git_ps1 ' (%s)')\n\$" Once you find something you like, add that line to one of Bash's startup files, e.g. $HOME/.bashrc . The source for git-prompt.sh is well-commented and worth browsing if you're curious about other options. Note that you may have to manually source path/to/git-prompt.sh before this will work. If so, add this line to your config file as well, above the export PS1 bit. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21140815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157971/']} | jdg_69872 |
stackexchange | llm_judgeable_groundtruth_similarity | 10710446 |
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 seems like it should be an easy fix, but so far a solution has eluded me. I have a single column csv file with non-ascii chars saved in utf-8 that I want to read in and store in a list. I'm attempting to follow the principle of the "Unicode Sandwich" and decode upon reading the file in: import codecsimport csvwith codecs.open('utf8file.csv', 'rU', encoding='utf-8') as file:input_file = csv.reader(file, delimiter=",", quotechar='|')list = []for row in input_file: list.extend(row) This produces the dread 'codec can't encode characters in position, ordinal not in range(128)' error. I've also tried adapting a solution from this answer , which returns a similar error def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs): csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs) for row in csv_reader: yield [unicode(cell, 'utf-8') for cell in row]filename = 'inputs\encode.csv'reader = unicode_csv_reader(open(filename))target_list = []for field1 in reader: target_list.extend(field1) A very similar solution adapted from the docs returns the same error. def unicode_csv_reader(utf8_data, dialect=csv.excel): csv_reader = csv.reader(utf_8_encoder(utf8_data), dialect) for row in csv_reader: yield [unicode(cell, 'utf-8') for cell in row]def utf_8_encoder(unicode_csv_data): for line in unicode_csv_data: yield line.encode('utf-8')filename = 'inputs\encode.csv'reader = unicode_csv_reader(open(filename))target_list = []for field1 in reader: target_list.extend(field1) Clearly I'm missing something. Most of the questions that I've seen regarding this problem seem to predate Python 2.7, so an update here might be useful.
Now provide the response and nothing else.
| Your first snippet won't work. You are feeding unicode data to the csv reader, which (as documented) can't handle it. Your 2nd and 3rd snippets are confused. Something like the following is all that you need: f = open('your_utf8_encoded_file.csv', 'rb')reader = csv.reader(f)for utf8_row in reader: unicode_row = [x.decode('utf8') for x in utf8_row] print unicode_row | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10710446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1012040/']} | jdg_69873 |
stackexchange | llm_judgeable_groundtruth_similarity | 601840 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working on a lighting project for a van build out. I'm using 12 V car batteries that are solar-powered. I know that I can use WS2811 strips that are 12 V strips and power them directly off the car batteries, but I'm curious if I can instead use two 5 V WS2812 strips, and wire them in parallel to split the voltage across two LED strips. Since 12 V/2 = 6 V, I guess it should be close enough to not blow out the 5 V LED strips. Am I understanding it correctly?
Now provide the response and nothing else.
| Nope. 5V things in parallel still needs 5V. You must mean series which would require 10V. And 12V divided to two series LED strips will be 6V per strip, which will be beyond absolute maximum voltage rating for a WS2812 LED so they will blow up. Even if it did not blow up, one of them would reference the data pin to 0V and the another one to 6V so you can't control them with a single controller, you would need two separate controllers. And they would only have 6V per strip if they always consume the same amount of current, which won't happen in real life. It is not possible. And I just realized this is a product usage question which has nothing to do with electrical engineering. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/601840', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/166623/']} | jdg_69874 |
stackexchange | llm_judgeable_groundtruth_similarity | 159590 |
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:
Space is a very low temperature environment, however it also has an extremely small number of particles per unit volume. This leads me to believe that, contrary to popular portrayals of heat loss in space, there would be very little heat loss due to conduction on a hypothetical spaceship in deep space. If you were put into space and provided with food, water, heat, and protected from the pressure would the spaceship cool due to head radiating away from the ship?
Now provide the response and nothing else.
| Let's start by assuming you're in the shade, so you're not receiving any radiation (apart from the cosmic microwave background, which I think we can ignore). The amount of heat per unit area that you radiate is given by Stefan's law : $$ J = \varepsilon \sigma T^4 \tag{1} $$ The emissivity of human skin is allegedly 0.98 , and the area of skin of an adult male is around 2m$^2$, so feeding in $T = $37ºC gives us a total radiated power of about a kilowatt. The power produced by an adult male is about 120W , so at body temperature you're going to lose about 880W. To work out what temperature you would cool to we just take equation (1), feed in $J = $60W/m$^2$ and we get $T = $180K. This would be fatal. What's interesting is to see what happens when you're in direct sunlight. At the orbit of the earth the radiation from the Sun is around 1.4kW/m$^2$ . Since only half your skin would be illuminated, you would be losing a kW and gaining 1.4kW for a net gain of 400W. To work out your equilibrium temperature we just feed $J = $1400W/m$^2$ into equation (1) and we get $T = $396K, which would again be fatal. The distance from the Sun where the heat you radiate would exactly balance the heat you receive can be worked out using the inverse square law. If $r_E$ is the radius of Earth's orbit and $r$ is the thermal balance radius we get: $$ \frac{r^2}{r_E^2} = \frac{1400}{1000} $$ or: $$ r = 1.18r_E $$ | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/159590', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/3982/']} | jdg_69875 |
stackexchange | llm_judgeable_groundtruth_similarity | 1789 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have $n$ discrete samples of a seismic signal $y[n]$: I want to find local maxima in the signal. A naive test for if $y[n]$ is a maximum would be:$$y[n]: maxima \textbf{ if } y[n] > y[n-1] \textbf{ and } y[n] > y[n+1]$$ However the maxima are probably located in between samples, e.g. there may be a maximum at $i=4.25$. In order to find maxima in between samples I believe that I need to interpolate $y[n]$. How do I find maxima using interpolation ? What form of interpolation should I use ? As you can see my signal is not very noisy, however it would be good if the method also did a bit of filtering so that the maxima exceed a treshold and have a certain width (no spikes). My biggest problem however is just to find peaks in between samples.Any suggestions for a good way to do this ? Thanks in advance for any answers!
Now provide the response and nothing else.
| Getting a sub-sample resolution A very cheap (in terms of code size) solution is just to upsample your signal. In matlab, this can be done with interp(y ,ratio) . A slightly more complicated solution consists in naively detecting peaks ; and for each peak, fitting a parabola through y[peak - 1], y[peak], y[peak + 1] ; then using the point at which this parabola is maximal as the true peak position. Regarding peak detection A bunch of techniques which help: As suggested by Hilmar, convolving the signal by a Gaussian or Hann window, the width of which is roughly equal to half the minimum interval you want to see between detected peaks. Since temporal accuracy seems essential to your application, make sure that you take into account the time delay introduced by the filtering, though! Subtract to your signal a median filtered version of itself (with a fairly large observation window) ; and divide the result by a standard-deviation filtered version of itself. This gets rid of trends and allows the thresholds to be expressed in units of standard deviations. For peak-picking, I formulate that using a "top-hat" filter. Define the top-hat filtered version of your signal as yt[n] = max(y[n - W], y[n - W + 1], ..., y[n + W - 1], y[n + W]) ; and use as peaks the points where y[n] == yt[n] and y[n] > threshold. All this can be very efficiently implemented in Matlab with a few passes of nlfilter. | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/1789', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/697/']} | jdg_69876 |
stackexchange | llm_judgeable_groundtruth_similarity | 6636793 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Lets say I have the following scenarios: int i = 10;short s = 5;if (s == i){ do stuff...} else if (s < i) { do stuff...} When C does the comparison does it convert the smaller data type, in this case short to int or does it convert the data type on the right to the data type on the left?In this case int to short?
Now provide the response and nothing else.
| This is governed by the usual arithmetic conversions . For simple cases, the general rule of thumb is that the type with "less" precision is converted to match the type with "more" precision, but it gets somewhat complex once you start mixing signed and unsigned . In C99, this is described by section 6.3.1.8, which I include here for your convenience: First, if the corresponding real type of either operand is long double , the other operand is converted, without change of type domain, to a type whose corresponding real type is long double . Otherwise, if the corresponding real type of either operand is double , the other operand is converted, without change of type domain, to a type whose corresponding real type is double . Otherwise, if the corresponding real type of either operand is float , the other operand is converted, without change of type domain, to a type whose corresponding real type is float . Otherwise, the integer promotions are performed on both operands. Then the following rules are applied to the promoted operands: If both operands have the same type, then no further conversion is needed. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank. Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type. Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type. Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type. I've highlighted the part that applies to your particular example. The concept of integer conversion rank is defined in section 6.3.1.1, and it basically describes what you might expect (that types with less precision have a lower rank than types with more precision). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6636793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/668427/']} | jdg_69877 |
stackexchange | llm_judgeable_groundtruth_similarity | 19219 |
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 box contain $A$ white and $B$ black balls and $C$ balls are drawn, then the expected value of the number of white balls drawn is ? The answer is $\large \frac{ca}{a+b}$. How to approach this one?
Now provide the response and nothing else.
| These calculations are often made clearer by using indicator random variables. For $1\leq i\leq C$, define $Z_i$ by setting $Z_i=1$ if the $i$th ball drawn is white and $Z_i=0$ otherwise. Then the total number of white balls is $\sum_{i=1}^C Z_i$ and by linearity of expectation we have$$ E(\mbox{ white balls })=E\left(\sum_{i=1}^C Z_i\right)=\sum_{i=1}^C E(Z_i).$$ The expectation of an indicator random variable is just the probability of the event it indicates, so $E(Z_i)=P(i\mbox{th ball is white})=A/(A+B)$. Therefore we find that $$ E(\mbox{ white balls })=\sum_{i=1}^C E(Z_i)={C A\over A+B}.$$ Notice that we did not need to calculate the probability of getting one, two, three, etc. white balls. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/19219', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2109/']} | jdg_69878 |
stackexchange | llm_judgeable_groundtruth_similarity | 70635 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
A closed oriented Riemannian manifold with negative sectional curvatures has the property that all its geodesics have Morse index zero. Is there a known counterexample to the "converse": if (M,g) is a closed oriented Riemannian manifold (Edit: assumed to be nondegenerate) all of whose geodesics have Morse index zero then M admits a (possibly different) metric g' with negative sectional curvatures? Edit: Motivation for asking this (admittedly naive) question is that Viterbo/Eliashberg have proved that a manifold with a negatively curved metric cannot be embedded as a Lagrangian submanifold of a uniruled symplectic manifold. Actually their proof only seems to use the existence of a nondegenerate metric all of whose geodesics have Morse index zero. I wondered if that was known to be strictly weaker.
Now provide the response and nothing else.
| As mentioned by Rbega the question should be amended to ask whether it's true that a closed manifold $M$ without conjugate points admits a metric of non-positive (rather than negative) curvature (otherwise a torus is an obvious counterexample). In that form this is a well-known open problem. The exponential map at any point is a universal covering of $M$ and the geodesics in $\tilde M$ are unique. This does show that $M$ is aspherical but that is a long way from admitting a metric of nonpositive curvature. There are some partial results suggesting that fundamental groups of manifolds without conjugate points share some properties of fundamental groups of nonpositively curved manifolds.In particular, there is a result of Croke and Shroeder that if the metric is analytic then any abelian subgroup of $\pi_1(M)$ is embedded quasi-isometrically. By the following observation of Bruce Kleiner the analyticity condition can be removed: Croke and Schroeder show that even without assuming analyticity for any $\gamma\in\pi_1(M)$ its minimal displacement $d_\gamma$ satisfies $d_{\gamma^n}=nd_\gamma$ for any $n\ge1$. This then implies that $d_\gamma=\lim_{n\to\infty} d(\gamma^nx,x)/n$ for any $x\in\tilde M$. This in turn implies that the restriction of $d$ to an abelian subgroup $H \simeq \mathbb Z^n$ extends to a norm on $\mathbb R^n$. This implies that $H$ is quasi-isometrically embedded. This result implies for example that nonflat nilmanifolds cannot admit metrics without conjugate points and more generally that every solvable subgroup of the fundamental group of a manifold without conjugate points is virtually abelian. But it's unlikely that any such manifold admits a metric of non-positive curvature. It is more probable that its fundamental group must satisfy some weaker condition such as semi-hyperbolicity but even that is completely unclear. The natural bicombing on $\tilde M$ given by geodesics need not satisfy the fellow traveler property (at least there is no clear reason where it should come from). So it might be worth trying to look for counterexamples and the first place I would look is among groups that are semi-hyperbolic but not $CAT(0)$. Specifically, any $CAT(0)$ group has the property that centralizers of non-torsion elements virtually split. This need not hold in a semi-hyperbolic group with the simplest example given by any nontrivial circle bundle over closed surfaces of genus $>1$. To be even more specific one can take the unit tangent bundle $T^1(S_g)$ to a hyperbolic surface. Note however that it's known that a closed homogenous manifold without conjugate points is flat so if there is a metric without conjugate points on $T^1(S_g)$ it can not be homogeneous. Edit: Actually, this last remark is irrelevant as $T^1(S_g)$ can not admit any homogeneous metrics at all. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/70635', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10839/']} | jdg_69879 |
stackexchange | llm_judgeable_groundtruth_similarity | 12965167 |
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 array: myarray = [ ['usa','primary', 'john'], ['france','primary', 'lira'], ['usa', 'secondary', 'steve'], ['germany', 'primary', 'jeff'], ['france', 'secondary', 'ben']] I want to convert it to an array of hash like: [ {:country => 'usa', :primary => 'john', :secondary => 'steve'}, {:country => 'france', :primary => 'lira', :secondary => 'ben'}, {:country => 'germany', :primary => 'jeff', :secondary => ''}] I can do it by looping through the array and putting the values into a hash for "primary". How can I add "secondary" to the existing hash that may already be inserted into the array?
Now provide the response and nothing else.
| With a bit of Higher order programming: myarray.reduce({}) do |accu, (country, func, name)| accu[country] ||= {} accu[country][func.to_sym] = name accu end.map{|k, h| h[:country] = k; h} Explanation: Reduce will take an accumulator, in this case we start with an empty hash and go through the array. We match the triples in the array to the variables country, func, name . Since we want to group things by country we create that as our first Hash key. It should contain a hash so we make sure that is corresponds to an array with accu[country] ||= {} . Then we add our key value pair converting func to a symbol. Finally we return our modified accumulator that will be passed to the next iteration. This will return a data structure like this: {"usa"=>{:primary=>"john", :secondary=>"steve"}, "france"=>{:primary=>"lira", :secondary=>"ben"}, "germany"=>{:primary=>"jeff"}} Now we need to transform it into a array of hashes rather than a big hash. We do this by calling map on it and in the process we add country as a key to the hash. Now one thing that the algorithm above doesn't do is to check for missing values, resp. it doesn't guarantee that both :primary and :secondary are present. You can do that by modifying the map to this: .map do |k, h| h[:country] = k h[:primary] ||= "" h[:secondary] ||= "" hend | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12965167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1560470/']} | jdg_69880 |
stackexchange | llm_judgeable_groundtruth_similarity | 50941 |
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:
It was said such real objects of famous topological surfaces were plotted by the cooperation between mathematician Richard Palais and artist Luc Benard, and published as the cover page of Science magazine (issue on Sept 22 in 2006) : The cover page of Science , Sept 22, 2006 Comments by Rachel Thomas How to create such surfaces with the same color, rendering, lighting and opacity effects via Mathematica? ( answers with only similar rendering results for these surfaces one by one are also acceptable if the same rendering effects as the samples are too difficult to realize ) Another similar question with anwser can be seen from this link: another topological surface example with answer Surface information are : Klein bottle; symmetric 4-noid; breather surface; Boy surface; Sievert-Enneper surface. It was said these surfaces in the figure were created via 3D-XplorMath software. EDITS: unfortunately it is voted as on hold ; but I personally believe Mathematica's rendering should be powerful enough to realize such effects( at least more powerful than the open source 3D-XplorMath The author on MathOverflow ); Here I add two of the surfaces obtained and rendered which are already good enough; There are documents on these surfaces from this link: documents on surfaces There are five different surfaces; I have found four of them; but only three as below look beautiful; so I will not post others here; Clear["Global`*"]; (* Sievert-Enneper surface *)ϕ := -u/Sqrt[c + 1] + ArcTan[Tan[u] Sqrt[c + 1]]a := 2/(c + 1 - c Sin[v]^2 Cos[u])r := a Sqrt[(c + 1) (1 + c Sin[u]^2)] Sin[v]/Sqrt[c]Clear[x, y, z, p]; p = ParametricPlot3D[{x = r Cos[ϕ] - 2, y = r Sin[ϕ], z = ((Log[Tan[v/2]] + a (c + 1) Cos[v])/Sqrt[ c])} /. {c -> .4}, {u, -Pi/2, Pi/2}, {v, 0, Pi}, PlotPoints -> {30, 30}, PlotStyle -> Directive[Opacity[0.65], LightPurple, Specularity[White, 20]], Mesh -> None, RegionFunction -> Function[{x, y, z}, Abs[z] < 2.2], Axes -> False, Boxed -> False]
Now provide the response and nothing else.
| Concerning the comment about creating the surfaces, sure: Mathematica is one of the best tools available for that. Here's the Klein bottle , for example. ParametricPlot3D[{ (3 + Cos[v/2]*Sin[u] - Sin[v/2]*Sin[2 u])*Cos[v], (3 + Cos[v/2]*Sin[u] - Sin[v/2]*Sin[2 u])*Sin[v], Sin[v/2]*Sin[u] + Cos[v/2]*Sin[2 u]}, {u, -Pi, Pi}, {v, 0, 2 Pi}, Axes -> None, ColorFunction -> (Blend[{Purple, Pink, Lighter@Orange}, Mean[{#1, #2, #3}]] &), Boxed -> False, Mesh -> None, PlotStyle -> Directive[Specularity[1, 20], [email protected]]] Rendering is not Mathematica's strong suit, though. Sure, you could make it do whatever you want if you are willing to write enough code and wait long enough for it to compute, but it would make a lot more sense to model these in Mathematica and then export them in your favorite 3D format for rendering in more appropriate software. My personal preference is Rhino3D . Edits Breather surface From here : r := 1 - b^2;w := Sqrt[r];denom := b*((w*Cosh[b*u])^2 + (b*Sin[w*v])^2)breather = {-u + (2*r*Cosh[b*u]*Sinh[b*u])/ denom, (2*w*Cosh[b*u]*(-(w*Cos[v]*Cos[w*v]) - Sin[v]*Sin[w*v]))/ denom, (2*w*Cosh[b*u]*(-(w*Sin[v]*Cos[w*v]) + Cos[v]*Sin[w*v]))/ denom}ParametricPlot3D[ Evaluate[breather /. b -> 0.4], {u, -13.2, 13.2}, {v, -37.4, 37.4}, PlotRange -> All, PlotPoints -> {60, 150}] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/50941', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9851/']} | jdg_69881 |
stackexchange | llm_judgeable_groundtruth_similarity | 35670229 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have a string, say, "The quick brown fox jumps over the lazy dog" , and there's a list [1, 8, 14, 18, 27] indicates where to cut the string. What I expect to get is a list that contains parts of the cut string. For this example, the output should be: ['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog'] My intuitive and naive way is to simply write a for loop, remember the previous index, slice the string and append the slice to output. _str="The quick brown fox jumps over the lazy dog"cut=[1, 8, 14, 18, 27]prev=0out=[]for i in cut: out.append(_str[prev:i]) prev=iout.append(_str[prev:]) Is there any better way?
Now provide the response and nothing else.
| Here's how I would do it: >>> s = "The quick brown fox jumps over the lazy dog">>> l = [1, 8, 14, 18, 27]>>> l = [0] + l + [len(s)]>>> [s[x:y] for x,y in zip(l, l[1:])]['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog'] Some explanation: I'am adding 0 to the front and len(s) to the end of the list, such that >>> zip(l, l[1:])[(0, 1), (1, 8), (8, 14), (14, 18), (18, 27), (27, 43)] gives me a sequence of tuples of slice indices. All that's left to do is unpack those indices in a list comprehension and generate the slices you want. edit: If you really care about the memory footprint of this operation, because you deal with very large large strings and lists often of times, use generators all the way and build your list l such that it includes the 0 and len(s) in the first place. For Python 2: >>> from itertools import izip, tee>>> s = "The quick brown fox jumps over the lazy dog">>> l = [0, 1, 8, 14, 18, 27, 43]>>> >>> def get_slices(s, l):... it1, it2 = tee(l)... next(it2)... for start, end in izip(it1, it2):... yield s[start:end]... >>> list(get_slices(s,l))['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog'] For Python 3: zip does what izip did in Python 2 (see Python 3.3 version) For Python 3.3+ with the yield from syntax: >>> from itertools import tee>>> s = "The quick brown fox jumps over the lazy dog">>> l = [0, 1, 8, 14, 18, 27, 43]>>> >>> def get_slices(s, l):... it1, it2 = tee(l)... next(it2)... yield from (s[start:end] for start, end in zip(it1, it2))... >>> list(get_slices(s,l))['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog'] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35670229', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5215536/']} | jdg_69882 |
stackexchange | llm_judgeable_groundtruth_similarity | 1345890 |
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've seen a few questions posted before about mine, but this is a bit different. The original form of the question can be found here: http://librarun.org/book/10452/159 . It says that prove by contradiction that $f(x)=\sin\left(\frac{1}{x}\right)$ has no limit value as $x$ $\rightarrow$ $0$. I attempted to take $$x=\frac{1}{n\pi}$$ in which case $f(x)=0$ for every integer $n$. After, I write $x$ as follows $$x=\frac{1}{\frac{\pi}{2}+n\pi}$$ in which case we have $f(x)=1$ or $-1$ for every integer $n$. How do I proceed from here? Note that until this question writer did not mention about inifinite limits and limits of composite functions and sequences.
Now provide the response and nothing else.
| If it is not true that "for every $\epsilon > 0$ there is some $\delta > 0$ such that if $0 < |x-a| < \delta$ then $|f(x) - L| < \epsilon$", then $$\color{blue}{\text{ there is some } \epsilon > 0 \text{ such that for every }\delta > 0 \text{ there is some } x \text{ which satisfies } \\0 < |x - a| < \delta \text{ but not } |f(x) - L| < \epsilon}$$ So for your limit with $f(x) = \sin(1/x)$, suppose we want to show it does not approach $0$ near $0$, consider $\epsilon = 1/2$ and note that for every $\delta > 0$ there is some $x$ with $0 < |x - 0| < \delta$ but not $|\sin(1/x) - 0| < 1/2$. Namely, $x = 1/(\pi/2 + 2\pi n )$ which satisfies $0 < |x-0| < \delta$ for some sufficiently large $n$. More generally, any limit $L$ must lie in the interval $[-1,1]$ as that is the range of the function $\sin$. For any such $L \in [-1,1]$, there is some $x$ with $0 < |x - 0| < \delta$ but not $|\sin(1/x) - L| < 1/2$, namely $$x = \frac{1}{\arcsin(L) \pm \pi/2 + 2\pi n}$$for some sufficiently large $n$ and the appropriate choice of sign. (The easiest way to see this might be to look at the graphs of $y = \left|\sin(x) - \sin(x \pm \pi/2)\right|$.) Added: Explicitly For $L \in [0,1]$ choose the $-$ sign, i.e.,$$x = \frac{1}{\arcsin(L) - \pi/2 + 2\pi n}$$ Then $$|f(x) - L| = |-\cos(\arcsin(L))-L| = \sqrt{1 - L^2} + L$$ which has minimum value of $1$ on the domain $[0,1]$. For $L \in [-1,0)$, chose the $+$ sign. Then $$|f(x) - L| = |\cos(\arcsin(L)) - L| = \sqrt{1-L^2} - L$$ which likewise has minimum of $1$ on $[-1,0)$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1345890', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211697/']} | jdg_69883 |
stackexchange | llm_judgeable_groundtruth_similarity | 39680320 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use LLDB within Xcode 8 to debug very basic STL. I used to be able to print a vector like this: p myvector[0] to see whatever was in the first vector index. Now when I do that, I get this error: error: Couldn't lookup symbols: __ZNSt3__16vectorI9my_classNS_9allocatorIS1_EEEixEm Instead, I have to type this: p myvector.__begin_[0] in order to get any output. I tried importing the libcxx.py and unordered_multi.py scripts from the LLDB svn repository but that doesn't seem to change anything. Has anyone been able to get any useful output from LLDB with libc++?
Now provide the response and nothing else.
| [] is an operator method on std::vector , so to print the expression you want, lldb would have to be able to call the [] method. The problem here is that the STL on OS X is aggressive about inlining everything it can, and not wasting space producing out of line copies of the same functions. That's great for optimized code, but not so good for debugging because it leaves the debugger with no [] operator to call. That's the error message you are seeing. If you just want to see the elements in this vector, you can use the lldb "STL data formatters" to do this work for you. They know how most STL types are laid out, and can print the elements of most container types. For instance: (lldb) expr my_vec[0]error: Couldn't lookup symbols: __ZNSt3__16vectorI3FooNS_9allocatorIS1_EEEixEm but: (lldb) expr my_vec(std::__1::vector<Foo, std::__1::allocator<Foo> >) $0 = size=2 { [0] = (var1 = 10, var2 = 20) [1] = (var1 = 10, var2 = 20)} There is also another command "frame variable" which can inspect static objects, and hooks into the data formatters. It can't call functions and do other more complex expression parser tasks, but it does know how to use the STL data formatters to retrieve individual elements: (lldb) frame var my_vec[1](Foo) my_vec[1] = (var1 = 10, var2 = 20) You can even use frame var's -L option to locate the elements of the vector, and then you can cast the address to pass it to other functions: (lldb) frame var -L my_vec[1]0x0000000100100348: (Foo) my_vec[1] = {0x0000000100100348: var1 = 100x000000010010034c: var2 = 20}(lldb) expr printf("%d\n", ((class Foo *) 0x0000000100100348)->var1)10(int) $3 = 3 Another way to work around this for debugging - if you are using C++11 - is by putting: template class std::vector<MyClass> in your code somewhere. That will instruct the compiler to emit out-of-line copies of all the template functions for this specialization. That isn't a great general solution, and you only want to do it for debug builds, but it does let you call these functions and use them in complex expressions. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39680320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57662/']} | jdg_69884 |
stackexchange | llm_judgeable_groundtruth_similarity | 6865261 |
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 creating an Outlook 2010 add-in and have added a context menu to my ribbon for idMso="contextMenuMailItem". On click, I would like to remove a category but in the click event handler, when I cast ctl.Context to MailItem, it's always null. public bool btnRemoveCategory_IsVisible(Office.IRibbonControl ctl){ MailItem item = ctl.Context as MailItem; //Always null if (item != null) return (item != null && HasMyCategory(item)); else return false;} Does anyone know what's going on here? Thanks!
Now provide the response and nothing else.
| The following link might provide you with some insight: http://msdn.microsoft.com/en-us/library/ff863278.aspx The "context" of the control gives you the corresponding Outlook object that you are customizing (for example an Inspector object). From there you'll need to reference the context object's CurrentItem property to get the MailItem. For example, public bool btnRemoveCategory_IsVisible(Office.IRibbonControl ctl){ var item = ctl.Context as Inspector; var mailItem = item.CurrentItem as MailItem; if (item != null) return (item != null && HasMyCategory(item)); else return false;} Hopefully, this helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6865261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239837/']} | jdg_69885 |
stackexchange | llm_judgeable_groundtruth_similarity | 743243 |
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:
In a triangle $ABC$ $2a^2+4b^2+c^2=4ab+2ac$ then the numerical value of $cos B$ equals ? ($a,b,c$ are sides opposite to angles $A,B,C$) I tried to use cosine rule , but couldn't adjust terms accordingly, using the given equation. Any hints / Solutions are welcome. Answer: $7/8$
Now provide the response and nothing else.
| $$2a^2+4b^2+c^2=4ab+2ac\iff (a-2b)^2+(a-c)^2=0$$ Now sum of squares of two real numbers is zero, so each must be individually zero.Hence $a=c=2b$. Then$$\cos B=\frac{a^2+c^2-b^2}{2ac}=\frac{4b^2+4b^2-b^2}{8b^2}=\frac{7}{8}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/743243', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/86694/']} | jdg_69886 |
stackexchange | llm_judgeable_groundtruth_similarity | 21236774 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We currently have a page setup that has no filters/facet/queries applied. It is a listing of all content (using a pager). The filter query is something like *:* (anything from any field). I can't figure out how the content is being sorted though. It says it's by "relevancy", but what does that mean when you're selecting everything? I did some quick testing. It does not appear to be sorted by the date the content is modified, or entered into the index.
Now provide the response and nothing else.
| Querying for *:* is also called a MatchAllDocsQuery . According to the SO question How are results ordered in solr in a "match all docs" query it will return the docs in the same order as they were stored in the index. Be aware that if you update an existing document, it get's deleted and recreated. As such it would appear at the end of such a search afterwards. There are (at least) two threads in Lucene's Nabble I am aware of that are interesting on this topic http://lucene.472066.n3.nabble.com/Result-order-when-score-is-the-same-td2816127.html gets really interesting around here http://lucene.472066.n3.nabble.com/Result-order-when-score-is-the-same-tp2816127p2817766.html http://lucene.472066.n3.nabble.com/Result-ordering-for-Wildcard-Prefix-queries-or-ConstantScoreQueries-td492687.html | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21236774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1004232/']} | jdg_69887 |
stackexchange | llm_judgeable_groundtruth_similarity | 15753102 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using the sqlalchemy package in python. I have an operation that takes some time to execute after I perform an autoload on an existing table. This causes the following error when I attempt to use the connection: sqlalchemy.exc.OperationalError: (OperationalError) (2006, 'MySQL server has gone away') I have a simple utility function that performs an insert many: def insert_data(data_2_insert, table_name): engine = create_engine('mysql://blah:blah123@localhost/dbname') # Metadata is a Table catalog. metadata = MetaData() table = Table(table_name, metadata, autoload=True, autoload_with=engine) for c in mytable.c: print c column_names = tuple(c.name for c in mytable.c) final_data = [dict(zip(column_names, x)) for x in data_2_insert] ins = mytable.insert() conn = engine.connect() conn.execute(ins, final_data) conn.close() It is the following line that times long time to execute since 'data_2_insert' has 677,161 rows. final_data = [dict(zip(column_names, x)) for x in data_2_insert] I came across this question which refers to a similar problem. However I am not sure how to implement the connection management suggested by the accepted answer because robots.jpg pointed this out in a comment: Note for SQLAlchemy 0.7 - PoolListener is deprecated, but the same solution can be implemented using the new event system . If someone can please show me a couple of pointers on how I could go about integrating the suggestions into the way I use sqlalchemy I would be very appreciative. Thank you.
Now provide the response and nothing else.
| I think you are looking for something like this: from sqlalchemy import exc, eventfrom sqlalchemy.pool import [email protected]_for(Pool, "checkout")def check_connection(dbapi_con, con_record, con_proxy): '''Listener for Pool checkout events that pings every connection before using. Implements pessimistic disconnect handling strategy. See also: http://docs.sqlalchemy.org/en/rel_0_8/core/pooling.html#disconnect-handling-pessimistic''' cursor = dbapi_con.cursor() try: cursor.execute("SELECT 1") # could also be dbapi_con.ping(), # not sure what is better except exc.OperationalError, ex: if ex.args[0] in (2006, # MySQL server has gone away 2013, # Lost connection to MySQL server during query 2055): # Lost connection to MySQL server at '%s', system error: %d # caught by pool, which will retry with a new connection raise exc.DisconnectionError() else: raise If you wish to trigger this strategy conditionally, you should avoid use of decorator here and instead register listener using listen() function: # somewhere during app initializationif config.check_connection_on_checkout: event.listen(Pool, "checkout", check_connection) More info: Connection Pool Events Events API | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15753102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/668624/']} | jdg_69888 |
stackexchange | llm_judgeable_groundtruth_similarity | 15873172 |
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 show the image its going to the left most position of the div. i know its not a good question but i unable to solve this so posted. Actually i am dynamically adding html tags. I am adding a having 2 anchor and 3 images in which 2 are visible and one is in visible. when you click on any one of that two image third image will show . but when in click the image its showing the third image but in the left most side of the div. but i have placed that image beside the two image. i want to show that image beside that two image. how to do this? you can see my problem here http://postimg.org/image/685puy931/ i am not using any float :left any where.(seen in firebug). Please help i searched tried with position absolute and inline its not working. Thanks in advance [EDIT] showData += "<div style='margin:3px;display: inline-block;padding-right:20px;'>"; showData += "<a style='text-decoration: none' href=\"" + userProfileURL + "\" title='KLMS User Profile of " + fullName + " ' onmousedown=\"javascript:StoreClickedData(" + userId + ",'" + userInput + "','" + names[i] + "')\" title='" + tooltipTitle + "'> <img src='UserControls/ThumbNail/ThumbnailConverter.ashx?FilePath=" + imageURL + "&height=18&width=18' /> </a> "; showData += "<a href=\"" + gpsUserProfile + "\" onmousedown=\"javascript:StoreClickedData(" + userId + ",'" + userInput + "','" + names[i] + "')\" title='" + tooltipTitle + "'>" + fullName + "</a>"; if (isPresent) { showData += " <a href=\"" + emailId + "\" title='Mail To " + fullName + " ' onmousedown=\"javascript:StoreClickedAndLunchQuickFeedBack(" + userId + ",'" + userInput + "','" + names[i] + "','imgQuickfd" + imageId + "')\" class='smallIcon' style=\"background-image:url(Images/email.png);\" > </a>"; if (userDetails[userData.Skype_ID] != "null") { showData += " <a href=\"" + skypeId + "\" title='Chat With " + fullName + "' onmousedown=\"javascript:StoreClickedAndLunchQuickFeedBack(" + userId + ",'" + userInput + "','" + names[i] + "','imgQuickfd" + imageId + "')\" class='smallIcon' style=\"background-image:url(" + skypeName + ");\" > </a>"; } showData += "<i id='imgQuickfd" + imageId + "' style='display:none; cursor: pointer;position: absolute !important;' title='Quick Feedback To" + fullName + " ' onclick=\"javascript:StoreQuickFeedback('" + userLoginName + "','" + names[i] + "','imgQuickfd" + imageId + "')\" class=\"icon-thumbs-up glowed \"></i>"; } showData += "</div>"; [/EDIT] View Source: <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head id="head"><title>MFS Search Engine</title><link href="CSS/CustomGoogleSearch.css" rel="stylesheet" /><meta charset="utf-8" /><link href="bootstrap/css/bootstrap.css" rel="stylesheet" /></head><body><form name="form" method="post" action="CustomGoogleSearch.aspx?query=html5" id="form"><div><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTQwMjc4OTQzN2RkRYBvMG1HTB0LNjZv1HE0hZ95t08=" /></div><script type="text/javascript">//<![CDATA[var theForm = document.forms['form'];if (!theForm) {theForm = document.form;}function __doPostBack(eventTarget, eventArgument) {if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit();}}//]]></script><script src="/klms /WebResource.axd?d=YGVs8XyAWsEiLGuJ16c33zJSRK4YrDPiOWmkBO0Qq98589H5pLaw70AyFUVa3BleRpWNySSr ltpIawWYHK6tn8jtCeo1&t=634656060808104849" type="text/javascript"></script><script src="/klms/WebResource.axd?d=rGkGTBKKUfifja4ZbpHfden_7XF4hf_qIjcSz4LqV8J7RmM4b5zUIgiT0uuMpRtVNMa-zLKNmfsh-e7Fd8RqdBTlqhM1&t=634656060808104849" type="text/javascript"></script><div><input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /><input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /><input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWBgLFvND9DQKIiKT4AQK4gogyAvjE9ooCAoLplowDAt3Q4McN/MAodltIcChy5WGQ8XeHsiQlCY8=" /></div> <noscript> <div class="jsEnable"> <a href="https://support.google.com/adsense/bin/answer.py?hl=en& answer=12654">How To Enable</a> <span>JavaScript is needed for this site (which is currently disabled in your browser). Please enable JavaScript.</span> </div> </noscript> <input type="hidden" name="hdnUserId" id="hdnUserId" value="595" /> <input type="hidden" name="hdnUserName" id="hdnUserName" value="Annapurnap" /> <input type="hidden" name="hdnRowCount" id="hdnRowCount" value="10" /> <input type="hidden" name="hdnAPIServerName" id="hdnAPIServerName" value="http://203.129.204.51:8080/collective-intellegenc" /> <input type="hidden" name="hdnSolrServerName" id="hdnSolrServerName" value="http://203.129.204.51:8080/solr" /><script type="text/javascript">//<![CDATA[WebForm_AutoFocus('searchInput');//]]></script></form><form id="formResult"> <div class="span18" id="divContent" style="width: 97%"> <div style="width: 100%; margin-top: -10px" class="inline"> <img id="imgGoogleCustomImage" class="googleCustomImage" style="float: right; margin-top: 0.25%" src="http://www.google.com/cse/images/google_custom_search_smwide.gif" /> <a href="/FeedbackList.aspx" style="float: right; padding-right: 5%;">*Feedback List </a> </div> <div id="divSearch" class="searchDiv"> <img src="Images/KLMS.png" id="imgLogo" /> <div> <div id="divTextBox"> <input type="search" name="q" size="31" id="searchInput" class="span6" autofocus="autofocus" autocomplete="off" /> </div> <div id="divButton"> <input type="button" id="btnSearch" name="sa" class="btn btn-primary span2" value="Search" onclick="Search();" /> </div> </div> </div> <div id="divResult" style="display: none; padding-top: 5%"> <div class="divItem" style="float: left; margin-right: 1%; display: none;"> <fieldset class="well" id="fieldsetItem"> <legend class="legend">Content that can help</legend> <div id="searchResultItem"> </div> <div id="divLinkPaging"></div> </fieldset> </div> <aside style="float: left; width: 99%"> <fieldset class="well" id="fieldsetPerson"> <legend class="legend">Persons who can help</legend> <div id="searchResultPerson"> </div> </fieldset> </aside> </div> <div id="divGoogleResult"> </div> <script src="JS/Plugins/jquery-1.8.2.min.js"></script> <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <!--[if IE]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script src="JS/Plugins/paging.js"></script> <script src="https://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/Collection.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/Solr.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/ConnectServer.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/UserConnection_UsabilityScore_UserSearch.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/FixedSet.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/VariableSet.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/ShowCollectiveIntelligenceData.js"></script> <script type="text/javascript" src="JS/Collective%20Intelligence/StoreSearchQuery.js"></script> </div></form>
Now provide the response and nothing else.
| Finding articulation vertices is an application of DFS. In a nutshell, Apply DFS on a graph. Get the DFS tree. A node which is visited earlier is a "parent" of those nodes which are reached by it and visited later. If any child of a node does not have a path to any of the ancestors of its parent, it means that removing this node would make this child disjoint from the graph. There is an exception: the root of the tree. If it has more than one child, then it is an articulation point, otherwise not. Point 3 essentially means that this node is an articulation point. Now for a child, this path to the ancestors of the node would be through a back-edge from it or from any of its children. All this is explained beautifully in this PDF . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15873172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1926138/']} | jdg_69889 |
stackexchange | llm_judgeable_groundtruth_similarity | 8106765 |
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 use strtok to read in a first and last name and seperate it. How can I store the names where I can use them idependently in two seperate char arrays? #include <stdio.h>#include <string.h>int main (){ char str[] ="test string."; char * test; test = strtok (str," "); while (test != NULL) { printf ("%s\n",test); test= strtok (NULL, " "); } return 0;}
Now provide the response and nothing else.
| Here is my take at a reasonably simple tokenize helper that stores results in a dynamically growing array null-terminating the array keeps the input string safe (strtok modifies the input string, which is undefined behaviour on a literal char[], at least I think in C99) To make the code re-entrant, use the non-standard strtok_r #include <stdio.h>#include <string.h>#include <stdlib.h>char** tokenize(const char* input){ char* str = strdup(input); int count = 0; int capacity = 10; char** result = malloc(capacity*sizeof(*result)); char* tok=strtok(str," "); while(1) { if (count >= capacity) result = realloc(result, (capacity*=2)*sizeof(*result)); result[count++] = tok? strdup(tok) : tok; if (!tok) break; tok=strtok(NULL," "); } free(str); return result;}int main (){ char** tokens = tokenize("test string."); char** it; for(it=tokens; it && *it; ++it) { printf("%s\n", *it); free(*it); } free(tokens); return 0;} Here is a strtok -free reimplementation of that (uses strpbrk instead): char** tokenize(const char* str){ int count = 0; int capacity = 10; char** result = malloc(capacity*sizeof(*result)); const char* e=str; if (e) do { const char* s=e; e=strpbrk(s," "); if (count >= capacity) result = realloc(result, (capacity*=2)*sizeof(*result)); result[count++] = e? strndup(s, e-s) : strdup(s); } while (e && *(++e)); if (count >= capacity) result = realloc(result, (capacity+=1)*sizeof(*result)); result[count++] = 0; return result;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8106765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/271534/']} | jdg_69890 |
stackexchange | llm_judgeable_groundtruth_similarity | 47803002 |
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 something which is an awful lot like a list comprehension in Python, except that it shares mutable state between iterations. Is there any way to do it with a list comprehension? def f(x): """ 5-bit LFSR """ return (x >> 1) ^ (0x12*(x&1))def batch(f, x, n): result = [x] for _ in xrange(1,n): x = f(x) result.append(x) return resultbatch(f, 1, 5) which returns [1, 18, 9, 22, 11] . Here the important thing is the batch function, not f(x) which is here just a simple example to illustrate the issue. Alternatively I could implement using a generator: def batch(f, x, n): yield x for _ in xrange(1,n): x = f(x) yield xlist(batch(f, 1, 5)) But it smells a little awkward. What I'm looking for is something like this... batch = [??? for _ in xrange(n)]
Now provide the response and nothing else.
| Is there any way to do it with a list comprehension? What I'm looking for is something like this... batch = [??? for _ in xrange(n)] Sure, no problem: >>> x = 1>>> n = 5>>> [prev.append(f(prev[0])) or prev.pop(0) for prev in [[x]] for _ in xrange(n)][1, 18, 9, 22, 11] Note: This is a bad idea. (I pretty much only did this because user2357112 said there is no way) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47803002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44330/']} | jdg_69891 |
stackexchange | llm_judgeable_groundtruth_similarity | 93549 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
It is easy to visualize some Morse functions on surfaces (such as the torus) via the height function, but this seemingly doesn't work for 3-manifolds. I am looking for an explicit one on the 3-torus $\mathbb{T}^3$. In paritcular: It is true that every nice-enough 3-manifold admits a self-indexing Morse function $f:M\to[0,3]$ (with unique maximum and minimum), and from this we get a Heegaard diagram, with splitting surface $\Sigma=f^{-1}(\frac{3}{2})$. Now apparently, a converse also holds, so that given a Heegaard decomposition we can read off a self-indexing Morse function ( edit: perhaps multiple Morse functions, as per Ryan Budney's comment). With the known Heegaard decomposition of $\mathbb{T}^3$ (handlebodies $N$ and $\mathbb{T}^3-N$ for a small neighborhood $N$ about the generating 1-complex $S^1\cup S^1\cup S^1\subset\mathbb{T}^3$, and splitting surface $\partial N$), what is the corresponding Morse function? I can't write one down.
Now provide the response and nothing else.
| The Morse function on $(S^1)^3$ that gives the genus 3 Heegaard splitting (the standard one) is basically just a smoothed "distance from the 1-skeleton function". So if you think of $S^1$ as the unit circle in $\mathbb C$, then $$f : (S^1)^3 \to \mathbb R$$ is given by $$f(z_1,z_2,z_3) = |z_1-1|^2 + |z_2-1|^2 + |z_3-1|^2$$ where we're taking the norm/modulus squared of vectors in $\mathbb C$ in the above formula. The critical points are 8 triples $(z_1,z_2,z_3)$ of the form $(\pm 1, \pm 1, \pm 1)$, so you have the minimum $(1,1,1)$, maximum $(-1,-1,-1)$, index 1 critical points $(-1,1,1), (1,-1,1), (1,1,-1)$ and index two (the negatives of the index one critical points). If you really demand self-indexing then you'll need the function $\frac{f(z_1,z_2,z_3)}{4}$ | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/93549', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12310/']} | jdg_69892 |
stackexchange | llm_judgeable_groundtruth_similarity | 34296002 |
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 UIbutton created in code in an NSObject class which controls a game in a UIViewController class. The button works fine throughout most of the game, but at a certain point I want the button to fadein/out. Once the fadein/out starts animating the button is no longer interactive. I have set the .AllowUserInteraction option, but still no luck. I am stumped on this one, so any help much appreciated! Class GameController: NSObject {var gameView: UIView!var nextButton: UIButton!func gameViewSetUp() { // create the nextButton let imageNextButton = UIImage(named: "rightArrow") as UIImage? self.nextButton = UIButton(type: .Custom) nextButton.frame = CGRectMake(ScreenWidth-100,ScreenHeight-250,60,60) nextButton.setTitle("", forState: UIControlState.Normal) nextButton.setImage(imageNextButton, forState: .Normal) nextButton.contentMode = .ScaleAspectFill nextButton.backgroundColor = UIColor.clearColor() nextButton.layer.cornerRadius = 5.0 nextButton.layer.borderWidth = 2.5 nextButton.layer.borderColor = UIColor.clearColor().CGColor nextButton.addTarget(self, action: "nextPressed", forControlEvents: .TouchUpInside) nextButton.userInteractionEnabled = true gameView.addSubview(nextButton)func playStageX() { nextButtonWink() }}func nextButtonWink() { UIView.animateWithDuration(1.5, delay: 0, options: [.AllowUserInteraction, .Repeat, .CurveEaseInOut, .Autoreverse], animations: { // self.nextButton.userInteractionEnabled = true // I tried this as well but no impact. self.nextButton.alpha = 0 }, completion: nil)}class GameViewController: UIViewController {private var controller: GameControllerrequired init?(coder aDecoder: NSCoder) { controller = GameController() super.init(coder: aDecoder)}override func viewDidLoad() { super.viewDidLoad() let gameView = UIView(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight)) self.view.addSubview(gameView) controller.gameView = gameView }
Now provide the response and nothing else.
| Take out self.nextButton.alpha = 0 to test this out, I believe that button events will not fire when alpha is zero. When it comes to animations, the actual object's alpha will get set to zero before the animation starts, and what you are seeing is like a rendered interactive screenshot of your view as it animates If that is the case, then you need to set the alpha to something like 0.0100000003 or override the button to be interactive at alpha 0 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34296002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4727468/']} | jdg_69893 |
stackexchange | llm_judgeable_groundtruth_similarity | 11773820 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using wysihtml5 wysiwyg editor. The problem is that image src attribute and link href attribute are stripped from html. At server I am already getting stripped html. How I can fix this problem? I am using advanced.js rulest. With all rules. Editor UPDATE 1 Well editor.getValue and jquery().val() for textarea give same values on form submit. means that form should be sent correctly. But I'v watched POST request which is sent from the browser. and it is without URLs. Something wrong. UPDATE 2 If I remove from ruleset everything connected with img, nevertheless it works inproperly. UPDATE 3 In response to Marrowmaw comment. I am expecting: <a href="http://domain.com/" title="Link: http://domain.com">Link</a> But I get <a href="" title="Link: Null">Link</a> UPDATE 4 <div id="wysihtml5-toolbar" style="display: none;"> <button class="btn" data-wysihtml5-command="bold"> {{ "Bold"|trans }} </button> <button class="btn" data-wysihtml5-command="italic"> {{ "Italic"|trans }} </button> <button class="btn" data-wysihtml5-command="createLink"> {{ "Link"|trans }}/{{ "Unlink"|trans }} </button> <button class="btn" data-wysihtml5-command="insertUnorderedList"> * </button> <button class="btn" data-wysihtml5-command="insertOrderedList"> 1,2,3 </button> <button class="btn" data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1"> {{ "Heading"|trans }} </button> <button class="btn" data-wysihtml5-command="insertImage"> {{ "Image"|trans }} </button> <div data-wysihtml5-dialog="createLink" style="display: none;"> <label> {{ "Link"|trans }}: <input data-wysihtml5-dialog-field="href" value="http://"> </label> <a data-wysihtml5-dialog-action="save">{{ "Save"|trans }}</a> <a data-wysihtml5-dialog-action="cancel">{{ "Cancel"|trans }}</a> </div> <!-- Dialog --> <div data-wysihtml5-dialog="insertImage" style="display: none;"> <label> URL: <input data-wysihtml5-dialog-field="src" value="http://"> </label> <label> Alternative text: <input data-wysihtml5-dialog-field="alt" value=""> </label> <label> {{ "Align"|trans }}: <select data-wysihtml5-dialog-field="className"> <option value="">{{ "default"|trans }}</option> <option value="wysiwyg-float-left">{{ "left"|trans }}</option> <option value="wysiwyg-float-right">{{ "right"|trans }}</option> </select> </label> <a data-wysihtml5-dialog-action="save">{{ "Save"|trans }}</a> <a data-wysihtml5-dialog-action="cancel">{{ "Cancel"|trans }}</a> </div> </div> <form action="{{ path('###_save_homepage') }}" method="POST" > <textarea id="wysihtml5-textarea" placeholder="{{ "Enter your text"|trans }}..." autofocus name="homepage" style="width:700px;height:400px;"> {{ homepage|raw }} </textarea> <input type="submit" value="{{ "Save"|trans }}" class="btn" /> </form> And JS init: <script type="text/javascript">jQuery(document).ready(function(){ var editor = new wysihtml5.Editor("wysihtml5-textarea", { // id of textarea element toolbar: "wysihtml5-toolbar", // id of toolbar element parserRules: wysihtml5ParserRules // defined in parser rules set }); });</script>
Now provide the response and nothing else.
| Try taking a look at the wysihtml5-x.x.x.js file you are referencing. They decided that they would only allow absolute URLs (in the name of guarding against XSS). The code below essentially allows you to take any value if you are comfortable with that trade off. Ctrl-F for "var attributeCheckMethods" and make the following changes -- source : var attributeCheckMethods = {url: (function() { /*var REG_EXP = /^https?:\/\//i;*/ return function(attributeValue) { /*if (!attributeValue || !attributeValue.match(REG_EXP)) { return null;*/ if (!attributeValue) { return ""; } /*return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); });*/ var parser = document.createElement('a'); parser.href = attributeValue; if ( parser.protocol == 'http:' || parser.protocol == 'https:' || parser.protocol == 'ftp:' ) return attributeValue; };})(), | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11773820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/737629/']} | jdg_69894 |
stackexchange | llm_judgeable_groundtruth_similarity | 50992188 |
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 wish to get rid of a lot of my repo's old history, so I did a shallow clone to get the last 50 commits only: git clone --depth=50 https://my.repo That worked OK, but when I create a new Gitlab repo and try to push it I get an error: git remote remove origingit remote add origin https://my.repogit push -u origin --all[...] ! [remote rejected] master -> master (shallow update not allowed) But I only want these 50 commits to be in my new repo's history. How can I tell git that it should just treat these 50 commits as the only commits in the new repo?
Now provide the response and nothing else.
| Here's what I ended up doing - it worked perfectly. Note that I was moving from my old host (Bitbucket) to my new one (Gitlab). My comments are above the commands: # First, shallow-clone the old repo to the depth we want to keepgit clone --depth=50 https://[email protected]/....git# Go into the directory of the clonecd clonedrepo# Once in the clone's repo directory, remove the old origingit remote remove origin# Store the hash of the oldest commit (ie. in this case, the 50th) in a varSTART_COMMIT=$(git rev-list master|tail -n 1)# Checkout the oldest commit; detached HEADgit checkout $START_COMMIT# Create a new orphaned branch, which will be temporarygit checkout --orphan temp_branch# Commit the initial commit for our new truncated history; it will be the state of the tree at the time of the oldest commit (the 50th)git commit -m "Initial commit"# Now that we have that initial commit, we're ready to replay all the other commits on top of it, in order, so rebase master onto it, except for the oldest commit whose parents don't exist in the shallow clone... it has been replaced by our 'initial commit'git rebase --onto temp_branch $START_COMMIT master# We're now ready to push this to the new remote repo... add the remote...git remote add origin https://gitlab.com/....git# ... and push. We don't need to push the temp branch, only master, the beginning of whose commit chain will be our 'initial commit'git push -u origin master After that, I did a fresh clone of the new repo and I got just the master branch with the 50 most recent commits - exactly what I wanted! :-) Commit history has gone from 250MB to 50MB. Woot. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50992188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178757/']} | jdg_69895 |
stackexchange | llm_judgeable_groundtruth_similarity | 972775 |
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:
Some time ago I asked How to find $\displaystyle{\int}_0^1\frac{\ln^3(1+x)\ln x}x\mathrm dx$ .Thanks to great effort of several MSE users, we now know that\begin{align}\int_0^1\frac{\ln^3(1+x)\,\ln x}xdx=&\,\frac{\pi^2}3\ln^32-\frac25\ln^52+\frac{\pi^2}2\zeta(3)+\frac{99}{16}\zeta(5)\\&\,-\frac{21}4\zeta(3)\ln^22-12\operatorname{Li}_4\!\left(\tfrac12\right)\ln2-12\operatorname{Li}_5\!\left(\tfrac12\right)\tag1\end{align}Now, a natural follow-up to that question is to bump the power of the logarithm and to ask: Question: What is a closed form for the next integral? $$I=\int_0^1\frac{\ln^3(1+x)\,\ln^2x}xdx\tag2$$ I think it is likely that $I$ has a closed form, because there are several very similar integrals having known closed forms:$$\int_0^1\frac{\ln^2(1+x)\,\ln^2x}xdx=\frac{\pi^2\,\zeta(3)}3-\frac{29\,\zeta(5)}8\tag3$$ $$\int_0^1\frac{\ln^3(1-x)\,\ln^2x}xdx=12\zeta^2(3)-\frac{23\pi^6}{1260}\tag4$$ \begin{align}\int_0^1\frac{\ln^3(1+x)\,\ln^2x}{x^2}dx=&\,\frac{3\zeta(3)}2+2\pi^2\zeta(3)+\frac{3\zeta(5)}2-\frac{21\zeta(3)}2\ln^22\\&\,-\frac{63\zeta(3)}2\ln2+\frac{23\pi^4}{60}-\frac{4\ln^52}5-\frac{3\ln^42}2\\&\,-4\ln^32+\frac{2\pi^2}3\ln^32+\frac{3\pi^2}2\ln^22-24\operatorname{Li}_5\!\left(\tfrac12\right)\\&\,-36\operatorname{Li}_4\!\left(\tfrac12\right)-24\operatorname{Li}_4\!\left(\tfrac12\right)\ln2\tag5\end{align}
Now provide the response and nothing else.
| I will be using the following results:$$2\sum^\infty_{n=1}\frac{H_n}{n^q}=(q+2)\zeta(q+1)-\sum^{q-2}_{j=1}\zeta(j+1)\zeta(q-j)\tag1$$$$\sum^\infty_{n=1}\frac{H_n}{n^22^n}=\zeta(3)-\frac{\pi^2}{12}\ln{2}\tag2$$$$\sum^\infty_{n=1}\frac{H_n}{n^32^n}={\rm Li}_4\left(\tfrac{1}{2}\right)+\frac{\pi^4}{720}-\frac{1}{8}\zeta(3)\ln{2}+\frac{1}{24}\ln^4{2}\tag3$$\begin{align}\sum^\infty_{n=1}\frac{H_n}{n^42^n}=&2{\rm Li}_5\left(\tfrac{1}{2}\right)+\frac{1}{32}\zeta(5)+{\rm Li}_4\left(\tfrac{1}{2}\right)\ln{2}-\frac{\pi^4}{720}\ln{2}+\frac{1}{2}\zeta(3)\ln^2{2}\\&-\frac{\pi^2}{12}\zeta(3)-\frac{\pi^2}{36}\ln^3{2}+\frac{1}{40}\ln^5{2}\tag4\end{align}Proofs of $(1)$, $(2)$ and $(4)$ can be found here , here and here respectively. Unfortunately, there has not been a mathematically sound proof of $(3)$ on MSE as of now. Using $\mathcal{I}$ to denote the integral in question,\begin{align}\mathcal{I}&=-\int^1_0\frac{\ln^3{x}\ln^2(1+x)}{1+x}{\rm d}x\\&=-\int^2_1\frac{\ln^2{x}\ln^3(x-1)}{x}{\rm d}x\\&=\underbrace{-\int^1_\frac{1}{2}\frac{\ln^2{x}\ln^3(1-x)}{x}{\rm d}x}_{\mathcal{I}_1}\underbrace{+3\int^1_{\frac{1}{2}}\frac{\ln^3{x}\ln^2(1-x)}{x}}_{\mathcal{I}_2}\underbrace{-3\int^1_{\frac{1}{2}}\frac{\ln^4{x}\ln(1-x)}{x}{\rm d}x}_{\mathcal{I}_3}-\frac{1}{6}\ln^6{2}\end{align}For $\mathcal{I}_1$, integration by parts gives$$\mathcal{I}_1=\frac{1}{3}\ln^6{2}-\int^1_\frac{1}{2}\frac{\ln^3{x}\ln^2(1-x)}{1-x}{\rm d}x$$On the other hand, $x\mapsto1-x$ yields$$\mathcal{I}_1=-\int^\frac{1}{2}_0\frac{\ln^3{x}\ln^2(1-x)}{1-x}{\rm d}x$$Combining these two equalities, we have\begin{align}\mathcal{I}_1&=\frac{1}{6}\ln^6{2}-\frac{1}{2}\int^1_0\frac{\ln^3{x}\ln^2(1-x)}{1-x}{\rm d}x\\&=\frac{1}{6}\ln^6{2}-\frac{1}{2}\frac{\partial^5\beta}{\partial a^3\partial b^2}(1,0^+)\\&=\frac{1}{6}\ln^6{2}-\frac{1}{2}\left[\frac{1}{b}+\mathcal{O}(1)\right]\left[\left(12\zeta^2(3)-\frac{23\pi^6}{1260}\right)b+\mathcal{O}(b^2)\right]_{b=0}\\&=\frac{23\pi^6}{2520}-6\zeta^2(3)+\frac{1}{6}\ln^6{2}\end{align}Even with the help of Wolfram Alpha, evaluating that fifth derivative was horribly unpleasant to say the least. As for $\mathcal{I}_2$,\begin{align}\mathcal{I}_2=&6\sum^\infty_{n=1}\frac{H_n}{n+1}\int^1_\frac{1}{2}x^n\ln^3{x}\ {\rm d}x\\=&6\sum^\infty_{n=1}\frac{H_n}{n+1}\frac{\partial^3}{\partial n^3}\left(\frac{1}{n+1}-\frac{1}{(n+1)2^{n+1}}\right)\\=&\color{#E2062C}{-\sum^\infty_{n=1}\frac{36H_n}{(n+1)^5}}+\color{#FF4F00}{\sum^\infty_{n=1}\frac{36H_n}{(n+1)^52^{n+1}}}+\color{#00A000}{\sum^\infty_{n=1}\frac{36\ln{2}H_n}{(n+1)^42^{n+1}}}+\color{#21ABCD}{\sum^\infty_{n=1}\frac{18\ln^2{2}H_n}{(n+1)^32^{n+1}}}\\&+\color{#6F00FF}{\sum^\infty_{n=1}\frac{6\ln^3{2}H_n}{(n+1)^22^{n+1}}}\\=&\color{#E2062C}{-\frac{\pi^6}{35}+18\zeta^2(3)}+\color{#FF4F00}{\sum^\infty_{n=1}\frac{36H_n}{n^52^{n}}-36{\rm Li}_6\left(\tfrac{1}{2}\right)}+\color{#00A000}{36{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{9}{8}\zeta(5)\ln{2}}\\&+\color{#00A000}{36{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}-\frac{\pi^4}{20}\ln^2{2}+18\zeta(3)\ln^3{2}-3\pi^2\zeta(3)\ln{2}-\pi^2\ln^4{2}+\frac{9}{10}\ln^6{2}}\\&+\color{#21ABCD}{\frac{\pi^4}{40}\ln^2{2}-\frac{9}{4}\zeta(3)\ln^3{2}+\frac{3}{4}\ln^6{2}}+\color{#6F00FF}{\frac{3}{4}\zeta(3)\ln^3{2}-\ln^6{2}}\\=&\sum^\infty_{n=1}\frac{36H_n}{n^52^{n}}-36{\rm Li}_6\left(\tfrac{1}{2}\right)-\frac{\pi^6}{35}+36{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{9}{8}\zeta(5)\ln{2}+36{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}\\&-\frac{\pi^4}{40}\ln^2{2}+18\zeta^2(3)-3\pi^2\zeta(3)\ln{2}+\frac{33}{2}\zeta(3)\ln^3{2}-\pi^2\ln^4{2}+\frac{13}{20}\ln^6{2}\end{align}For $\mathcal{I}_3$,\begin{align}\mathcal{I}_3=&3\sum^\infty_{n=1}\frac{1}{n}\int^1_\frac{1}{2}x^{n-1}\ln^4{x}\ {\rm d}x\\=&3\sum^\infty_{n=1}\frac{1}{n}\frac{\partial^4}{\partial n^4}\left(\frac{1}{n}-\frac{1}{n2^n}\right)\\=&\sum^\infty_{n=1}\left(\frac{72}{n^6}-\frac{72}{n^62^n}-\frac{72\ln{2}}{n^52^n}-\frac{36\ln^2{2}}{n^42^n}-\frac{12\ln^3{2}}{n^32^n}-\frac{3\ln^4{2}}{n^22^n}\right)\\=&-72{\rm Li}_6\left(\tfrac{1}{2}\right)+\frac{8\pi^6}{105}-72{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}-36{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}\\&-\frac{21}{2}\zeta(3)\ln^3{2}+\frac{3\pi^2}{4}\ln^4{2}-\frac{1}{2}\ln^6{2}\end{align}Thus\begin{align}\color{#BF00FF}{\mathcal{I}=}&\color{#BF00FF}{36\sum^\infty_{n=1}\frac{H_n}{n^52^n}-108{\rm Li}_6\left(\tfrac{1}{2}\right)+\frac{143\pi^6}{2520}-36{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{9}{8}\zeta(5)\ln{2}-\frac{\pi^4}{40}\ln^2{2}}\\&\color{#BF00FF}{+12\zeta^2(3)-3\pi^2\zeta(3)\ln{2}+6\zeta(3)\ln^3{2}-\frac{\pi^2}{4}\ln^4{2}+\frac{3}{20}\ln^6{2}}\end{align}We note that\begin{align}\zeta(\bar{5},1)=&\frac{1}{24}\int^1_0\frac{\ln^4{x}\ln(1+x)}{1+x}{\rm d}x\\=&\frac{1}{24}\int^2_1\frac{\ln{x}\ln^4(x-1)}{x}{\rm d}x\\=&-\frac{1}{24}\int^1_\frac{1}{2}\frac{\ln{x}\ln^4(1-x)}{x}{\rm d}x+\frac{1}{6}\int^1_\frac{1}{2}\frac{\ln^2{x}\ln^3(1-x)}{x}{\rm d}x-\frac{1}{4}\int^1_\frac{1}{2}\frac{\ln^3{x}\ln^2(1-x)}{x}{\rm d}x\\&+\frac{1}{6}\int^1_\frac{1}{2}\frac{\ln^4{x}\ln(1-x)}{x}{\rm d}x+\frac{1}{144}\ln^6{2}\\=&\underbrace{-\frac{1}{24}\int^\frac{1}{2}_0\frac{\ln^4{x}\ln(1-x)}{1-x}{\rm d}x}_{\mathcal{J}}-3\sum^\infty_{n=1}\frac{H_n}{n^52^n}+7{\rm Li}_6\left(\tfrac{1}{2}\right)-\frac{17\pi^6}{5040}+{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}\\&-\frac{3}{32}\zeta(5)\ln{2}-{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}+\frac{\pi^4}{480}\ln^2{2}-\frac{1}{2}\zeta^2(3)+\frac{\pi^2}{4}\zeta(3)\ln{2}-\frac{19}{24}\zeta(3)\ln^3{2}\\&+\frac{\pi^2}{24}\ln^4{2}-\frac{17}{360}\ln^6{2}\end{align}since we have already derived the values of the last three integrals. For the remaining integral,\begin{align}\mathcal{J}=&\frac{1}{24}\sum^\infty_{n=1}H_n\frac{\partial^4}{\partial n^4}\left(\frac{1}{(n+1)2^{n+1}}\right)\\=&\sum^\infty_{n=1}\frac{H_n}{(n+1)^52^{n+1}}+\sum^\infty_{n=1}\frac{\ln{2}H_n}{(n+1)^42^{n+1}}+\sum^\infty_{n=1}\frac{\ln^2{2}H_n}{2(n+1)^32^{n+1}}+\sum^\infty_{n=1}\frac{\ln^3{2}H_n}{6(n+1)^22^{n+1}}\\&+\sum^\infty_{n=1}\frac{\ln^4{2}H_n}{24(n+1)2^{n+1}}\\=&\sum^\infty_{n=1}\frac{H_n}{n^52^n}-{\rm Li}_6\left(\tfrac{1}{2}\right)+{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{1}{32}\zeta(5)\ln{2}+{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}-\frac{\pi^4}{720}\ln^2{2}\\&+\frac{1}{2}\zeta(3)\ln^3{2}-\frac{\pi^2}{12}\zeta(3)\ln{2}-\frac{\pi^2}{36}\ln^4{2}+\frac{1}{40}\ln^6{2}+\frac{\pi^4}{1440}\ln^2{2}-\frac{1}{16}\zeta(3)\ln^3{2}\\&+\frac{1}{48}\ln^6{2}+\frac{1}{48}\zeta(3)\ln^3{2}-\frac{1}{36}\ln^6{2}+\frac{1}{48}\ln^6{2}\\=&\sum^\infty_{n=1}\frac{H_n}{n^52^n}-{\rm Li}_6\left(\tfrac{1}{2}\right)+{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}+\frac{1}{32}\zeta(5)\ln{2}+{\rm Li}_4\left(\tfrac{1}{2}\right)\ln^2{2}-\frac{\pi^4}{1440}\ln^2{2}\\&+\frac{11}{24}\zeta(3)\ln^3{2}-\frac{\pi^2}{12}\zeta(3)\ln{2}-\frac{\pi^2}{36}\ln^4{2}+\frac{7}{180}\ln^6{2}\\\end{align}Hence we can express $\zeta(\bar{5},1)$ as\begin{align}\zeta(\bar{5},1)=&-2\sum^\infty_{n=1}\frac{H_n}{n^52^n}+6{\rm Li}_6\left(\tfrac{1}{2}\right)-\frac{17\pi^6}{5040}+2{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}-\frac{1}{16}\zeta(5)\ln{2}+\frac{\pi^4}{720}\ln^2{2}\\&-\frac{1}{2}\zeta^2(3)-\frac{1}{3}\zeta(3)\ln^3{2}+\frac{\pi^2}{6}\zeta(3)\ln{2}+\frac{\pi^2}{72}\ln^4{2}-\frac{1}{120}\ln^6{2}\end{align}This implies that\begin{align}\sum^\infty_{n=1}\frac{H_n}{n^52^n}=&3{\rm Li}_6\left(\tfrac{1}{2}\right)-\frac{1}{2}\zeta(\bar{5},1)-\frac{17\pi^6}{10080}+{\rm Li}_5\left(\tfrac{1}{2}\right)\ln{2}-\frac{1}{32}\zeta(5)\ln{2}+\frac{\pi^4}{1440}\ln^2{2}\\&-\frac{1}{4}\zeta^2(3)-\frac{1}{6}\zeta(3)\ln^3{2}+\frac{\pi^2}{12}\zeta(3)\ln{2}+\frac{\pi^2}{144}\ln^4{2}-\frac{1}{240}\ln^6{2}\end{align}Plucking this back into the original integral, we get another form in terms of $\zeta(\bar{5},1)$\begin{align}\color{#BF00FF}{\mathcal{I}=}&\color{#BF00FF}{-\frac{\pi^6}{252}-18\zeta(\bar{5},1)+3\zeta^2(3)}\end{align}This is as close to a "closed form" as I can get. The sheer number of cancellations involved in the last step makes me think that my answer could be roundabout and inefficient. Note that no known simple closed form for $\zeta(\bar{5},1)$ exists, implying that closed forms for higher power integrals are unlikely to exist as well. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/972775', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/75621/']} | jdg_69896 |
stackexchange | llm_judgeable_groundtruth_similarity | 21706436 |
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 class ( MyFacade ) that I injected parameter(s) with Ninject : class MyFacade{ IDemoInterface demo; public MyFacade(IDemoInterface demo) { this.demo = demo; } public void MyMethod() { Console.WriteLine(demo.GetInfo()); }} Of course, I have to setup the Ninject to inject the appropiate implementation of my parameter ( IDemoInterface ) I know, I can instantiate MyFacade object by doing kernel.Get<MyFacade>(); without setting anything else. Currently my facade doesn't have an interface (because it is my only implementation, maybe I will add its interface for standard proposes) if I want to make this facade singlenton, I know two ways: create a empty constructor and pass a parameter by doing this kernel.Get<IDemoInterface>(); or by setup Ninject like: kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope(); The second one look a better approach, but do you know any other way to setup it in a singleton way?
Now provide the response and nothing else.
| When setting up your bindings, you need to bind your dependencies. It is always better to setup your dependencies in your bindings, as opposed to doing a kernel.Get<T>() in a constructor. You are using IOC, so leverage the framework you are using to do the injection for you. In your second example binding, what you are missing is binding in your IDemoInterface . Your bindings should look like this: //bind the dependency to the implementation.kernel.Bind<IDemoInterface>().To<DemoInterface>();//since you bound your dependency, ninject should now have // all the dependencies required to instantiate your `MyFacade` object.kernel.Bind<MyFacade>().To<MyFacade>().InSingletonScope(); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21706436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/480700/']} | jdg_69897 |
stackexchange | llm_judgeable_groundtruth_similarity | 58747303 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to Unit and e2e test my applications as much as possible and my goal is a coverage of 101%. Problem right now with my setup is, that the @Column decorator from typeorm uses an arrow function to set a default value like the current timestamp on a database update. This arrow function is not covered with jest test coverage. Message is: statement not covered I run the code coverage with: jest --coverage .My versions: "jest": "^24.9.0","typeorm": "^0.2.20" Jest configuration within package.json: { "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "rootDir": "src", "testRegex": ".spec.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "coverageDirectory": "../build/coverage", "testEnvironment": "node", "coverageThreshold": { "global": { "branches": 80, "functions": 80, "lines": 80, "statements": -10 } } },} My entity looks like this: import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';@Entity()export class Role { @PrimaryGeneratedColumn() id: number; @Column() tenantId: number; @Column({ type: 'timestamp', update: false, default: () => 'CURRENT_TIMESTAMP()' }) createdAt: Date; @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP()', onUpdate: 'CURRENT_TIMESTAMP()' }) updatedAt: Date;} Coverage for this entity: (to post an image i need 10 reputation -.-): https://i.ibb.co/FYQgstP/Screenshot-2019-11-07-11-46-45.png
Now provide the response and nothing else.
| I ran into a similar issue with GraphQL decorators. As all of these are functions, what you can do is create a file that holds all of the functions you'll be using, name them, and export them, so that you can actually test them as well and get the coverage with Jest. (The tests should literally be something like expect(namedFunction).toBe('CURRENT_TIMESTAMP()') or very similar. For an example you can see my function here and my tests here . EDIT 11/03/2020 The code examples are no more. That being said, you can do things like export const returnString = () => String;@Query(returnString) for GraphQL. A test for this would look like expect(returnString()).toBe(String); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58747303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2291097/']} | jdg_69898 |
This is a subset of the task data used to construct SYNTHETIC-1. You can find the full collection here