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 | 13594864 |
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 1.6 installer. I've used it. It does not change my Java installation, nor say there is an older version, but it does complete the installation. I've been working with the symlinks a bit, but no matter what I do, running java -version in terminal always results in Daves-MacBook-Pro:core-server dave$ java -versionjava version "1.7.0_07"Java(TM) SE Runtime Environment (build 1.7.0_07-b10)Java HotSpot(TM) 64-Bit Server VM (build 23.3-b01, mixed mode) My application works with GAE, which does NOT use Java 1.7 at all. As such, I cannot compile my code using 1.7! I have to use 1.6, but I have failed at finding a way to remove 1.7 or otherwise force build/compiling to occur on 1.6. A final note, I am running a build tool on the command line, so changing the settings of the project in Eclipse does not seem like it will help.
Now provide the response and nothing else.
| The java , javac , etc. command line tools are sensitive to the value of the JAVA_HOME environment variable and will use 1.6 if this variable points to a 1.6 JDK. The tool /usr/libexec/java_home is your friend here. Running /usr/libexec/java_home will print out the appropriate JAVA_HOME value for the most up to date JDK on your system. This will be Java 7, but you can apply constraints using the -v flag, for example /usr/libexec/java_home -v '1.6*' will return a JAVA_HOME value for the best available 1.6 JDK on your system. You can use this value to set JAVA_HOME : export JAVA_HOME=`/usr/libexec/java_home -v '1.6*'` either as a one-off for a particular Terminal session, or permanently for all future terminal sessions by adding the above line to the .bash_profile file in your home directory. $ export JAVA_HOME=`/usr/libexec/java_home -v '1.6*'`$ java -versionjava version "1.6.0_37"Java(TM) SE Runtime Environment (build 1.6.0_37-b06-434-11M3909)Java HotSpot(TM) 64-Bit Server VM (build 20.12-b01-434, mixed mode)$ export JAVA_HOME=`/usr/libexec/java_home -v '1.7*'`$ java -versionjava version "1.7.0_09"Java(TM) SE Runtime Environment (build 1.7.0_09-b05)Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13594864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1231943/']} | jdg_381941 |
stackexchange | llm_judgeable_groundtruth_similarity | 421107 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
$\DeclareMathOperator\Aut{Aut}\DeclareMathOperator\Gal{Gal}\newcommand{\ab}{\mathrm{ab}}$ Let $G(\mathbb Q) = \Gal(\overline{\mathbb Q} / \mathbb Q)$ be the absolute Galois group. It's well-known that the abelianization $G(\mathbb Q)^{\ab}$ of $G(\mathbb Q)$ is isomorphic to $\Aut(\mathbb Q / \mathbb Z) = \widehat {\mathbb Z}^\times$ , and that the fixed field $\mathbb Q^{\ab}$ of the commutator subgroup of $G(\mathbb Q)$ may be constructed by adjoining all roots of unity to $\mathbb Q$ . Abelian Galois groups are generalized by solvable Galois groups, or more generally hypoabelian Galois groups (recall that a group is hypoabelian if its derived series stabilizes at the trivial group, possibly after transfinitely many steps). Question 1: What is the hypoabelianization of $G(\mathbb Q)$ ? Question 2: What is the fixed field of the maximal perfect normal subgroup of $G(\mathbb Q)$ ? (Recall that in general, the maximal perfect normal subgroup is the subgroup at which the derived series stabilizes, possibly after transfinitely many steps; the hypoabelianization of a group is its quotient by its maximal perfect normal subgroup.)
Now provide the response and nothing else.
| My comment , Wojowu's answer , YCor's comment , and Z. M's comment already contain everything we need. Let me provide a little more detail here. I will shift the indices by $1$ for reasons that will become apparent: Definition. Set $K_0 = \mathbf Q$ and let $K_1 = \mathbf Q(\boldsymbol \mu)$ be the field obtained by adjoining the roots of unity $\boldsymbol \mu \subseteq \bar{\mathbf Q}$ . Inductively define $K_{i+1}=K_i\big(\sqrt[\infty\ \ ]{K_i^\times}\big)$ , and set $K_\infty = \underset{\substack{\longrightarrow \\ i}}{\operatorname{colim}} K_i$ . We claim that this is the extension we're after. We first introduce some notation: Definition. Given a profinite group $G$ , its ( profinte ) derived series is the transfinite chain of closed subgroups $$G = G^{(0)} \trianglerighteq G^{(1)} \trianglerighteq \cdots \trianglerighteq G^{(\alpha)} \trianglerighteq \cdots$$ defined by $G^{(\alpha+1)} = \overline{[G^{(\alpha)},G^{(\alpha)}]}$ and $G^{(\beta)} = \bigcap_{\alpha < \beta} G^{(\alpha)}$ for any limit ordinal $\beta$ (which is already closed as each $G^{(\alpha)}$ is closed). One could alter the notation to distinguish it from the abstract derived series, but I will never use the latter (the same goes for the KroneckerβWeber theorem: it computes the topological abelianisation, not the abstract one!). Note that for any continuous surjective homomorphism $G \to H$ of profinite groups, the image of $G^{(\alpha)}$ is $H^{(\alpha)}$ . Lemma. Let $G$ be a profinite group. Then $G^{(\omega + 1)} = G^{(\omega)}$ , and this group is trivial if and only if $G$ is pro-solubleΒΉ. Proof. For any finite group $G$ , the descending chain $G^{(i)}$ stabilises after finitely many steps, so $G^{(\omega + 1)} = G^{(\omega)}$ . The same statement for profinite groups follows since any closed normal subgroup $H \trianglelefteq G$ is the intersection of the open normal subgroups $U \trianglelefteq G$ containing it. Similarly, $G^{(\omega)} = 1$ if and only if the same holds in every finite quotient $G/U$ , i.e. if and only if all $G/U$ are soluble. $\square$ Let's denote $G^{(\omega)}$ by $G^{(\infty)}$ . For $n \in \mathbf N \cup \{\infty\}$ , we will say that $G$ is $n$ -soluble if $G^{(n)} = 1$ , and we write $G^{n\text{-}\!\operatorname{sol}} = G/G^{(n)}$ for its maximal $n$ -soluble quotient (in which we omit $n$ if $n = \infty$ ). For instance, $G$ is $1$ -soluble if and only if it is abelian, and $\infty$ -soluble if and only if it is pro-soluble (equivalently, hypoabelian as profinite group). Theorem. Let $\Gamma = \Gamma_{\mathbf Q}$ be the absolute Galois group of $\mathbf Q$ . For $n \in \mathbf N \cup \{\infty\}$ , the fixed field of $\Gamma^{(n)}$ is $K_n$ (i.e. $K_n$ is the maximal pro-soluble extension of derived length $\leq n$ ); For $n \in \mathbf N \setminus \{0\}$ , the Galois group $\operatorname{Gal}(K_{n+1}/K_n) = \Gamma^{(n)}/\Gamma^{(n+1)}$ is isomorphic to $$\operatorname{Hom}_{\operatorname{cont}}\!\big(K_n^\times,\hat{\mathbf Z}(1)\big),$$ where $K^\times$ has the discrete topology and $\hat{\mathbf Z}(1) = \lim_m \boldsymbol \mu_m$ is the Tate module of $\bar{\mathbf Q}^\times$ . Proof. Statement (1) is trivial for $n=0$ , and is the KroneckerβWeber theorem for $n=1$ . Statements (1) and (2) for finite $n \geq 2$ follow inductively by Kummer theory (see the corollary below). Finally, statement (1) for $n = \infty$ follows from the statement at finite levels, since $K_\infty = \bigcup_n K_n$ and $G^{(\infty)} = \bigcap_n G^{(n)}$ . $\square$ Note also that the Galois group $\operatorname{Gal}(K_1/K_0)$ is isomorphic to $\operatorname{Aut}(\boldsymbol \mu) = \hat{\mathbf Z}^\times$ . However, explicitly computing $\operatorname{Gal}(K_{n+1}/K_n)$ in a meaninful way is pretty hard, let alone saying anything about how the various pieces fit together. Edit: After writing this answer, I became aware of the following two striking results: Theorem (Iwasawa). The Galois group $\operatorname{Gal}(K_\infty/K_1) = \Gamma^{(1)}/\Gamma^{(\infty)}$ is a free pro-soluble group $\widehat{F_\omega}^{\operatorname{sol}}$ on countably infinitely many generators. So we know that $\Gamma^{\operatorname{sol}}$ sits in a short exact sequence $$1 \to \widehat{F_\omega}^{\operatorname{sol}} \to \Gamma^{\operatorname{sol}} \to \hat{\mathbf Z}^\times \to 1.$$ I find it hard to imagine that this sequence splits as a semi-direct product (but I am more optimistic about the derived length $\leq 2$ situation). Theorem (Shafarevich). Any finite soluble group $G$ occurs as a quotient of $\operatorname{Gal}(K_\infty/\mathbf Q) = \Gamma^{\operatorname{sol}}$ . A modern reference is NeukirchβSchmidtβWingberg's Cohomology of number fields , Corollary 9.5.4 (Iwasawa) and Theorem 9.6.1 (Shafarevich). (This is a truly great book, but even at $>800$ pages it can be a bit terse at times.) We used the following general result: Lemma (Kummer theory). Let $m \in \mathbf Z_{>0}$ , and $K$ be a field of characteristic not dividing $m$ that contains $\boldsymbol \mu_m$ . The maximal abelian extension of exponent $m$ of $K$ is $L=K\big(\sqrt[m\ \ ]{K^\times}\big)$ ; The map \begin{align*} \operatorname{Gal}(L/K) = \Gamma_K^{\operatorname{ab}}/m &\to \operatorname{Hom}_{\operatorname{cont}}\!\big(K^\times,\boldsymbol \mu_m\big) = \left(K^\times/(K^\times)^m\right)^\vee \\ \sigma &\mapsto \left(a \mapsto \frac{\sigma(\sqrt[m\ \ ]{a})}{\sqrt[m\ \ ]{a}}\right) \end{align*} is an isomorphism of profinite groups, where $K^\times/(K^\times)^m$ has the discrete topology and $A^\vee$ denotes the Pontryagin dual of a locally compact abelian group $A$ . We avoid the notation $\widehat A$ for Pontryagin duals, since it clashes with the notation for profinite completions. (Note that Z. M's comment uses $(-)^\vee$ for a linear dual, which differs from my notation by a Tate twist.) Because it's not very hard, let's include a proof. Proof. For (2), by Pontryagin duality it suffices to show that the dual map \begin{align*}K^\times/(K^\times)^m &\to \operatorname{Hom}\!\big(\Gamma_K,\boldsymbol \mu_m\big) = \left(\Gamma_K^{\operatorname{ab}}/m\right)^\vee \\a &\mapsto \left(\sigma \mapsto \frac{\sigma(\sqrt[m\ \ ]{a})}{\sqrt[m\ \ ]{a}}\right)\end{align*} is an isomorphism. Note that it is well-defined since any two $m$ -th roots of $a$ differ (multiplicatively) by an element of $\boldsymbol \mu_m \subseteq K$ , on which $\sigma$ acts as the identity. Since $\boldsymbol \mu_m \subseteq K$ , the $\Gamma_K$ -module $\boldsymbol \mu_m$ has trivial action, so $\operatorname{Hom}_{\operatorname{cont}}(\Gamma_K,\boldsymbol \mu_m) = H^1(K,\boldsymbol \mu_m)$ . The Kummer sequence $$1 \to \boldsymbol \mu_m \to \mathbf G_m \stackrel{(-)^m}\to \mathbf G_m \to 1$$ and Hilbert's theorem 90 compute $K^\times/(K^\times)^m \stackrel\sim\to H^1(K,\boldsymbol \mu_m)$ via the map above. Now (1) follows since $\sigma \in \Gamma_K$ is in the kernel of $\Gamma_K \to \big(K^\times/(K^\times)^m\big)^\vee$ if and only if $\sigma$ fixes all $m$ -th roots of elements in $K$ . $\square$ Corollay. Let $K$ be a field of characteristic $0$ containing $\boldsymbol \mu$ . The maximal abelian extension of $K$ is $L=K\big(\sqrt[\infty\ \ ]{K^\times}\big)$ . The map \begin{align*} \operatorname{Gal}(L/K) &\to \operatorname{Hom}_{\operatorname{cont}}\!\big(K^\times,\hat{\mathbf Z}(1)\big) \\ \sigma &\to \left(a \mapsto \left(\frac{\sigma(\sqrt[m\ \ ]{a})}{\sqrt[m\ \ ]{a}}\right)_{m \in \mathbf Z_{>0}}\right) \end{align*} is an isomorphism of profinite groups. Proof. Take inverse limits over all $m \in \mathbf Z_{>0}$ in the lemma above, noting that the inverse limit pulls out of $\operatorname{Hom}(K^\times,-)$ . $\square$ ΒΉLinguistic footnote: soluble and solvable mean the same thing. I used to think that this is one of those BrE vs AmE things (for instance, my Oxford Advanced Learner's dictionary does not contain the word solvable at all). But I think some folks in the UK also use solvable , so it's not entirely clear to me. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/421107', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2362/']} | jdg_381942 |
stackexchange | llm_judgeable_groundtruth_similarity | 252435 |
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:
Little background I'm working on the interpretation of regression analysis but I get really confused about the meaning of r, r squared and residual standard deviation.I know the definitions: Characterizations r measures the strength and direction of a linear relationship between two variables on a scatterplot R-squared is a statistical measure of how close the data are to the fitted regression line. The residual standard deviation is a statistical term used to describe the standard deviation of points formed around a linear function, and is an estimate of the accuracy of the dependent variable being measured. ( Don't know what the units are, any information about the units here would be helpful ) (sources: here ) Question Although I "understand" the characterizations, I do understand how these terms cothert to draw a conclusion about the dataset.I will insert a little example here, maybe this can serve as a guide to answer my question ( feel free to use an example of your own!) Example This is not a howework question, however I searched in my book to get a simple example (the current dataset I'm analyzing is too complex and large to show here) Twenty plots, each 10 x 4 meters, were randomly chosen in a large field of corn. For each plot, the plant density (number of plants in the plot) and the mean cob weight (gm of grain per cob) were observed. The results are givin in the following table: (source: Statistics for the life sciences ) βββββββββββββββββ¦βββββββββββββ¦ββββ Platn density β Cob weight β ββ ββββββββββββββββ¬βββββββββββββ¬βββ£β 137 β 212 β ββ 107 β 241 β ββ 132 β 215 β ββ 135 β 225 β ββ 115 β 250 β ββ 103 β 241 β ββ 102 β 237 β ββ 65 β 282 β ββ 149 β 206 β ββ 85 β 246 β ββ 173 β 194 β ββ 124 β 241 β ββ 157 β 196 β ββ 184 β 193 β ββ 112 β 224 β ββ 80 β 257 β ββ 165 β 200 β ββ 160 β 190 β ββ 157 β 208 β ββ 119 β 224 β ββββββββββββββββββ©βββββββββββββ©βββ First I will make a scatterplot to visualize the data: So I can calculate r, R 2 and the residual standard deviation. first the correlation test: Pearson's product-moment correlationdata: X and Yt = -11.885, df = 18, p-value = 5.889e-10alternative hypothesis: true correlation is not equal to 095 percent confidence interval: -0.9770972 -0.8560421sample estimates: cor -0.9417954 and secondly a summary of the regression line: Residuals: Min 1Q Median 3Q Max -11.666 -6.346 -1.439 5.049 16.496 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 316.37619 7.99950 39.55 < 2e-16 ***X -0.72063 0.06063 -11.88 5.89e-10 ***---Signif. codes: 0 β***β 0.001 β**β 0.01 β*β 0.05 β.β 0.1 β β 1Residual standard error: 8.619 on 18 degrees of freedomMultiple R-squared: 0.887, Adjusted R-squared: 0.8807 F-statistic: 141.3 on 1 and 18 DF, p-value: 5.889e-10 So based on this test: r = -0.9417954 , R-squared: 0.887 and Residual standard error: 8.619 What do these values tell us about the dataset? (see Question )
Now provide the response and nothing else.
| Those statistics can tell you about whether there is a linear component to the relationship but not much about whether the relationship is strictly linear. A relationship with a small quadratic component can have an r^2 of 0.99. A plot of residuals as a function of predicted can be revealing. In Galileo's experiment here https://ww2.amstat.org/publications/jse/v3n1/datasets.dickey.html the correlation is very high but the relationship is clearly nonlinear. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/252435', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/133457/']} | jdg_381943 |
stackexchange | llm_judgeable_groundtruth_similarity | 37024876 |
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 setup a Tomcat 8.5.x server version in Eclipse. When I try to create a server using Eclipse GUI, I get in Eclipse Luna as choice the latest version " Apache Tomcat v8.0 ". When I select it and I browse to my Tomcat 8.5.x server, I get this blocking error message: The Apache Tomcat installation at this directory is version 8.5.0. A Tomcat 8.0 installation is expected. The same error appears when trying TomEE 7.x, which is internally based on Tomcat 8.5. In Eclipse Neon the latest version as choice is " Apache Tomcat v9.0 " and it gives the same error. There isn't even a " Apache Tomcat v8.5 " option. Is there a way to use Tomcat 8.5 and TomEE 7.x in Eclipse? How?
Now provide the response and nothing else.
| You have to patch catalina.jar , as this is version number the WTP adapter looks at. It's a quite useless check, and the adapter should allow you to start the server anyway, but nobody has though of that yet. For years and with every version of Tomcat this is always a problem. To patch you can do the following: cd [tomcat or tomee home]/lib mkdir catalina cd catalina/ unzip ../catalina.jar vim org/apache/catalina/util/ServerInfo.properties Make sure it looks like the following (the version numbers all need to start with 8.0): server.info=Apache Tomcat/8.0.0server.number=8.0.0server.built=May 11 2016 21:49:07 UTC Then: jar uf ../catalina.jar org/apache/catalina/util/ServerInfo.properties cd .. rm -rf catalina | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37024876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_381944 |
stackexchange | llm_judgeable_groundtruth_similarity | 2179427 |
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 new to EC2. I created my security credentials from this site: http://paulstamatiou.com/how-to-getting-started-with-amazon-ec2 It worked great, I rebooted and now when I try to connect I get a login/password prompt. (Which I never set up.) After several attempts I get this error: Permission denied (publickey,gssapi-with-mic). What am I doing wrong?
Now provide the response and nothing else.
| Two possibilities I can think of, although they are both mentioned in the link you referenced: You're not specifying the correct SSH keypair file or user name in the ssh command you're using to log into the server: ssh -i [full path to keypair file] root@[EC2 instance hostname or IP address] You don't have the correct permissions on the keypair file; you should use chmod 600 [keypair file] to ensure that only you can read or write the file. Try using the -v option with ssh to get more info on where exactly it's failing, and post back here if you''d like more help. [Update]: OK, so this is what you should have seen if everything was set up properly: debug1: Authentications that can continue: publickey,gssapi-with-micdebug1: Next authentication method: publickeydebug1: Trying private key: ec2-keypairdebug1: read PEM private key done: type RSAdebug1: Authentication succeeded (publickey). Are you running the ssh command from the directory containing the ec2-keypair file ? If so, try specifying -i ./ec2-keypair just to eliminate path problems. Also check "ls -l [full path to ec2-keypair]" file and make sure the permissions are 600 (displayed as rw-------). If none of that works, I'd suspect the contents of the keypair file, so try recreating it using the steps in your link. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2179427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/263786/']} | jdg_381945 |
stackexchange | llm_judgeable_groundtruth_similarity | 443221 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Multi threading could cause a racing condition if two threads are accessing the same memory slot, but why is that? From a HW point of view, if the two cores are designed the same, internal pipelines are the same, the logic gates/transistors pass electrons the same way and the speed of those electrons is a constant value then what causes the race? Theoretically speaking shouldn't the two threads access the memory slot at the exact same time down to the nano second, every time?
Now provide the response and nothing else.
| Your understanding of computer hardware is flawed. Memory is not accessed by different cores in parallel, access is regulated like traffic at a road junction. Different threads can run simultaneously on different cores but they do not access the same memory cell together. What can happen is one thread ruining the work of another thread, like overwriting a result value before it has been read by a consumer. But that would be done sequentially, threads do not "collide", hitting the same cell at the same time. Reads and writes are all performed in a very controlled manner. The race conditions software engineers speak of are not a thing at the transistor level. They are a thing at the much higher program logic level. Think using a boolean value to control access to a resource. Before one thread uses the resource it checks the value to find it is false, meaning the resource is available. So it sets the value to true, signaling to other threads the resource is now occupied, and continues to use the resource. Between the check and set operation however another thread could have checked the value and also have found it to be false. This is the race and the unpredictability. Yet access to the variable by both threads was all performed sequentially in the most orderly fashion. So we need something better than a boolean variable to regulate traffic at the software level and this can only work with hardware support. This problem cannot be solved in software alone. Modern processors support this feature, we most often call this a lock. | {} | {'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/443221', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/425242/']} | jdg_381946 |
stackexchange | llm_judgeable_groundtruth_similarity | 30222533 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Create a day-of-week column in a Pandas dataframe using Python Iβd like to read a csv file into a pandas dataframe, parse a column of dates from string format to a date object, and then generate a new column that indicates the day of the week. This is what Iβm trying: What Iβd like to do is something like: import pandas as pdimport csvdf = pd.read_csv('data.csv', parse_dates=['date']))df['day-of-week'] = df['date'].weekday()AttributeError: 'Series' object has no attribute 'weekday' Thank you for your help.James
Now provide the response and nothing else.
| Pandas 0.23+ Use pandas.Series.dt.day_name() , since pandas.Timestamp.weekday_name has been deprecated: import pandas as pddf = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})df['my_dates'] = pd.to_datetime(df['my_dates'])df['day_of_week'] = df['my_dates'].dt.day_name() Output: my_dates myvals day_of_week0 2015-01-01 1 Thursday1 2015-01-02 2 Friday2 2015-01-03 3 Saturday Pandas 0.18.1+ As user jezrael points out below, dt.weekday_name was added in version 0.18.1 Pandas Docs import pandas as pddf = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})df['my_dates'] = pd.to_datetime(df['my_dates'])df['day_of_week'] = df['my_dates'].dt.weekday_name Output: my_dates myvals day_of_week0 2015-01-01 1 Thursday1 2015-01-02 2 Friday2 2015-01-03 3 Saturday Original Answer: Use this: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.dayofweek.html See this: Get weekday/day-of-week for Datetime column of DataFrame If you want a string instead of an integer do something like this: import pandas as pddf = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})df['my_dates'] = pd.to_datetime(df['my_dates'])df['day_of_week'] = df['my_dates'].dt.dayofweekdays = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x]) Output: my_dates myvals day_of_week0 2015-01-01 1 Thurs1 2015-01-02 2 Fri2 2015-01-01 3 Thurs | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30222533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4458393/']} | jdg_381947 |
stackexchange | llm_judgeable_groundtruth_similarity | 6046008 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I'm trying to make a request to the Stack Exchange API with the following jQuery code: $.ajax({ type: 'POST', url: 'http://api.stackoverflow.com/1.1/stats', dataType: 'jsonp', success: function() { console.log('Success!'); }, error: function() { console.log('Uh Oh!'); } }); But when I open the file on my machine, in either FireFox or Chrome, and make the request, I get this error: Resource interpreted as Script but transferred with MIME type application/json.Uncaught SyntaxError: Unexpected token :Uh Oh! I don't have a clue what's going on. I know the Stack Exchange API Gzips its responses, would this cause any trouble?
Now provide the response and nothing else.
| You have to set an unconventional parameter to get the SO API to work. Rather than the conventional callback , you need to pass a jsonp parameter. Furthermore, you can't do POST with JSONP. $.ajax({ type: 'GET', url: 'http://api.stackoverflow.com/1.1/stats', dataType: 'jsonp', success: function() { console.log('Success!'); }, error: function() { console.log('Uh Oh!'); }, jsonp: 'jsonp' }); It is not possible to do cross-domain AJAX using the conventional XMLHTTPRequest. This is for security reasons (it's call the same-origin policy). There is a workaround. script tags are not subject to this restriction. This means that you can insert a script tag into the document that calls a URL. If you define a globally-accessible function in your script and tell the remote server what that function is called, the server can pass code that wraps the data to be sent in a call to that function. The difficulty you had here is with the StackOverflow API. Conventionally, you would use the callback argument in your request, to tell the server what your function is called. However, StackOverflow's API asks you to use the jsonp parameter instead. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6046008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/568420/']} | jdg_381948 |
stackexchange | llm_judgeable_groundtruth_similarity | 25047976 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Simple question but I'm struggling with it for too much time. Basically I want to split a string by \ (backslash). a = "1\2\3\4" Tried to escape the the backslash but it doesn't seem to work: print(a.split('\')) print(a.split('"\"')) print(a.split('\\')) print(a.split('"\\"')) I want to get this result: ['1','2','3','4'] Many thanks in advance
Now provide the response and nothing else.
| You have the right idea with escaping the backslashes, but despite how it looks, your input string doesn't actually have any backslashes in it. You need to escape them in the input, too! >>> a = "1\\2\\3\\4" # Note the doubled backslashes here!>>> print(a.split('\\')) # Split on '\\'['1', '2', '3', '4'] You could also use a raw string literal for the input, if it's likely to have many backslashes. This notation is much cleaner to look at (IMO), but it does have some limitations: read the docs! >>> a = r"1\2\3\4">>> print(a.split('\\'))['1', '2', '3', '4'] If you're getting a elsewhere, and a.split('\\') doesn't appropriately split on the visible backslashes, that means you've got something else in there instead of real backslashes. Try print(repr(a)) to see what the "literal" string actually looks like. >>> a = '1\2\3\4'>>> print(a)1β»β₯β¦>>> print(repr(a))'1\x02\x03\x04'>>> b = '1\\2\\3\\4'>>> print(b)1\2\3\4>>> print(repr(b))'1\\2\\3\\4' | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25047976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3184086/']} | jdg_381949 |
stackexchange | llm_judgeable_groundtruth_similarity | 3753714 |
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:
Never dealt with a derivative of these type. My approach was $$y = \log_{\sqrt[3]{x}}(7) \iff 7 = (\sqrt[3]{x})^y.$$ Then, $$\frac{d}{dx}(7) = \frac{d}{dx}\left(\sqrt[3]{x}\right)^y \Rightarrow (\sqrt[3]{x})^y = e^{\frac{y\ln(x)}{3}} $$ From here, $0 = e^u\dfrac{du}{dx}$ and $u = \dfrac{y\ln(x)}{3}.$ Thus, $$0 = \frac{du}{dx} = \frac{y}{3x} +\frac{\ln(x)}{3}\frac{dy}{dx}.$$ Which implies that $$\frac{dy}{dx}= \frac{-\log_{\sqrt[3]{x}}(7)}{x\ln(x)}.$$ Is this the correct derivative? Can I alternatively use $\log_{b}(a) = \dfrac{\ln(a)}{\ln(b)}$ , with $b = \sqrt[3]{x}$ and $a=7$ ? In that case, I arrive at $$\frac{dy}{dx}= \dfrac{-3\ln(7)}{x(\ln(x))^2}.$$
Now provide the response and nothing else.
| Yes, you are right. Simplify as follows $$y=\log_{\sqrt[3]{x}}(7)=\frac{\ln 7}{\ln (\sqrt[3]{x})}=\frac{\ln (7)}{\frac13\ln x}=\frac{3\ln (7)}{\ln x}$$ $$\therefore \frac{dy}{dx}=3\ln (7)\left(\frac{-1}{(\ln x)^2}\frac1x\right)=-\frac{3\ln (7)}{x(\ln x)^2}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3753714', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/98816/']} | jdg_381950 |
stackexchange | llm_judgeable_groundtruth_similarity | 71353 |
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 with Virtex 5 ML507 board. I'm trying to create a cosine wave of 140 MHz out of 80 MHz clock. I'm receiving the data with a clock of 80 MHz and transmitting it with this clock (through the GTX). I want to create a cosine wave so that I can multiply the data and move the signal on the frequency level. The thing is, I'm not sure I can create this cosine wave with this clock. I tried to create for example 40 MHz cosine wave and got only 2 points on it, for 20 MHz I got 4 points and so on, accordingly to nyquist theorem. I though of maybe of upsampling but I didn't get a chance to work with this block. I'm creating the cosine wave using CORDIC. Any ideas?
Now provide the response and nothing else.
| The first and third methods you show are fine, assuming the resistor is sized so that the 8 mA maximum port pin current is not exceeded. The difference between these two methods is whether the low or high side drive transistor in the processor is in series with the LED. Sometimes the low side transistors are a little more beefy, which is why you see method three more than method 1. However, either method is fine as long as you take care to not exceed the current spec for the pin. Also note that some processors have a total current spec that must not be exceeded. For example, you could have 10 pins each driving a LED at 8 mA, which would be fine individually for each pin. However, if the overall processor spec is that all I/O pins together can't source our sink more than 50 mA, for example, then you're still out of spec. Your method two is wrong as drawn. It will likely damage the LED or transistor. To fix it, add a resistor in series with the LED so that the LED current does not exceed its maximum rated value. For example, let's say the LED is rated for 20 mA max, and it drops 2.1 V in that case. With a 9 V supply, that leaves 6.9 V accross the resistor and the transistor. The saturation voltage of the transistor is probably around 200 mV, but for worst case analisys let's just say it's 0. 6.9 V / 20 mA = 345 Ξ©, so the next size up common value of 360 Ξ© would be fine. Working backwards, and this time assuming the 200 mV drop on Q1, the LED current will be 6.7 V / 360 Ξ© = 18.6 mA. Even in a side by side comparison, it will be difficult for humans to distinguish that from the brightness achieved by 20 mA thru the LED. Here is yet another method, which is useful when there is a external supply available that is a bit more than the processor voltage plus the LED drop: This uses the transistor as a switchable current sink, so the exact power voltage (9 V in your case) doesn't matter over a wide range. When the base is 0, the transistor is off and the LED is off. When the base is driven to 3.3 V by the digital output, the emitter will be about 700 mV less, or 2.6 V in this example. The current thru R1 will therefore be 2.6 V / 150 Ξ© = 17.3 mA. Since most of this current comes from the collector due to the gain of the transistor, that will be the LED current to a reasonable approximation. Note that the 9 V supply voltage didn't enter into the calculations. As long as it is above a minimum value, the transistor will sink very nearly the same current because the transistor gain changes little with collector voltage. If we give the transistor about 700 mV C-E voltage so that it is nicely in its linear region, then the supply must be at least the digital output level plus the LED drop, which comes to 5.4 V in this case. That means the "9 V" supply can vary down to about 5.4 V without effecting the operation of this circuit. The maximum allowable supply is limited by the power dissipation in the transistor. Let's say we want to keep it to 150 mW or less. 150 mW / 17.3 mA = 8.7 V, which is the maximum C-E voltage for the transistor when it is on. Since R1 will drop 2.6 V and the LED 2.1, that means the supply can't exceed 13.4 V. So this circuit will work nicely and run the LED at the same brightness even if the "9 V" supply ranges from about 5.4 to 13.4 volts. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/71353', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/24510/']} | jdg_381951 |
stackexchange | llm_judgeable_groundtruth_similarity | 630721 |
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:
This answer on opening all files in vim except [condition]: https://unix.stackexchange.com/a/149356/98426 gives an answer similar to this: find . \( -name '.?*' -prune \) -o -type f -print (I adapted the answer because my question here is not about vim) Where the negated condition is in the escaped parentheses. However, on my test files, the following find . -type f -not -name '^.*' produces the same results, but is easier to read and write. The -not method, like the -prune method, prunes any directories starting with a . (dot). I am wondering what are the edge cases where the -not and the -prune -o -print method would have different results. Findutils' infopage says the following: -not expr : True if expr is false -prune: If the file is a directory, do not descend into it. (and further explains that -o -print is required to actually exclude the top matching directory) They seem to be hard to compare this way, because -not is a test and -prune is an action, but to me, they are interchangeable (as long as -o -print comes after -prune)
Now provide the response and nothing else.
| First, note that -not is a GNU extension and is the equivalent of the standard ! operator. It has virtually no advantage over ! . The -prune predicate always evaluates to true and affects the way find walks the directory tree. If the file for which -prune is run is of type directory (possibly determined after symlink resolution with -L / -H / -follow ), then find will not descend into it. So -name 'pattern' -prune (short for -name 'pattern' -a -prune ) is the same as -name 'pattern' except that the directories whose name matches pattern will be pruned , that is find won't descend into them. -name '.?*' matches on files whose name starts with . followed by one character (the definition of which depends on the current locale) followed by 0 or more characters . So in effect, that matches . followed by one or more characters (so as not to prune . the starting directory). So that matches hidden files with the caveat that it matches only those whose name is also entirely made of characters , that is are valid text in the current locale (at least with the GNU implementation). So here, find . \( -name '.?*' -a -prune \) -o -type f -a -print Which is the same as find . -name '.?*' -prune -o -type f -print since AND ( -a , implied) has precedence over OR ( -o ). finds files that are regular (no symlink, directory, fifo, device...) and are not hidden and are not in hidden directories (assuming all file paths are valid text in the locale). find . -type f -not -name '^.*' Or its standard equivalent: find . -type f ! -name '^.*' Would find regular files whose name doesn't start with ^. . find . -type f ! -name '.*' Would find regular files whose name doesn't start with . , but would still report files in hidden directories. find . -type f ! -path '*/.*' Would omit hidden files and files in hidden directories, but find would still descend into hidden directories (any level deep) only to skip all the files in them, so is less efficient than the approach using -prune . | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/630721', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/98426/']} | jdg_381952 |
stackexchange | llm_judgeable_groundtruth_similarity | 7191325 |
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 set of 100 object.How can i get a subset of 5 objects from this set ? I'm doing this for now but it only returns me one object int size = memberSet.size(); Set<Member> randomSet = new HashSet<Member>(); int item = new Random().nextInt(size); int i = 0; for(Member mbr : memberSet) { if (i == item){ randomSet.add(mbr); } i = i + 1; }
Now provide the response and nothing else.
| List<Member> list = new LinkedList<Member>(memberSet);Collections.shuffle(list);Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5)); Full example: public static void main(String... args) { Set<Member> memberSet = new HashSet<Member>(); for (int i = 0; i < 100; i++) memberSet.add(new Member(i)); List<Member> list = new LinkedList<Member>(memberSet); Collections.shuffle(list); Set<Member> randomSet = new HashSet<Member>(list.subList(0, 5)); System.out.println(randomSet);}static class Member { final int value; public Member(int value) { this.value = value; } @Override public String toString() { return "" + value; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7191325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284237/']} | jdg_381953 |
stackexchange | llm_judgeable_groundtruth_similarity | 33242605 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Am trying to get the difference between two files even though the file looks same it shows the difference that it has empty lines in the beginning How can I remove the empty lines before doing the difference I know sed -i '/^$/d should work but it didn't worked for me is there any other way Thanks
Now provide the response and nothing else.
| This answer already provides a solution which creates a Stream out of an Enumeration : public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize( new Iterator<T>() { public T next() { return e.nextElement(); } public boolean hasNext() { return e.hasMoreElements(); } }, Spliterator.ORDERED), false); } It should be emphasized that the resulting Stream is as lazy as any other Stream , as it wonβt process any items before the terminal action has been commenced and if the terminal operation is short-circuiting, it will iterate only as many items as necessary. Still, it has room for improvement. Iβd always add a forEachRemaining method when there is a straight-forward way to process all elements. Said method will be called by the Stream implementation for most non-short-circuiting operations: public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) { return StreamSupport.stream( Spliterators.spliteratorUnknownSize( new Iterator<T>() { public T next() { return e.nextElement(); } public boolean hasNext() { return e.hasMoreElements(); } public void forEachRemaining(Consumer<? super T> action) { while(e.hasMoreElements()) action.accept(e.nextElement()); } }, Spliterator.ORDERED), false);} However, the code above is a victim of the βusing Iterator because itβs so familiarβ antipattern. The created Iterator will get wrapped into an implementation of the new Spliterator interface and provides no advantage over implementing Spliterator directly: public static <T> Stream<T> enumerationAsStream(Enumeration<T> e) { return StreamSupport.stream( new Spliterators.AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED) { public boolean tryAdvance(Consumer<? super T> action) { if(e.hasMoreElements()) { action.accept(e.nextElement()); return true; } return false; } public void forEachRemaining(Consumer<? super T> action) { while(e.hasMoreElements()) action.accept(e.nextElement()); } }, false);} On the source code level, this implementation is as simple as the Iterator -based, but eliminates the delegation from a Spliterator to an Iterator . It only requires its readers to learn about the new API. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33242605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5121339/']} | jdg_381954 |
stackexchange | llm_judgeable_groundtruth_similarity | 493771 |
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:
The man page for udev mentions in several places that certain rules options can be used to invoke 'builtin' commands, which are apparently built in to the udev program itself. However, I haven't been able to find any reference documentation that clearly explains what udev builtins are available; what they do and how they are used. I have searched the web without much success. Does anyone know if there is a reference anywhere that provides details about these builtin commands?
Now provide the response and nothing else.
| Unfortunately, this information is missing on manpages and even knowing how to read them(see below) you will find trouble on trying to find that info. However, the beauty of the opensource relies on having the power to read the sources. If you take a look at the udev-builtin.c source file inside systemd / udev repository and have basic C language knowledge , you will find the following snippet of code: A structure that maps all existing builtin types. static const struct udev_builtin *builtins[_UDEV_BUILTIN_MAX] = {#if HAVE_BLKID [UDEV_BUILTIN_BLKID] = &udev_builtin_blkid,#endif [UDEV_BUILTIN_BTRFS] = &udev_builtin_btrfs, [UDEV_BUILTIN_HWDB] = &udev_builtin_hwdb, [UDEV_BUILTIN_INPUT_ID] = &udev_builtin_input_id, [UDEV_BUILTIN_KEYBOARD] = &udev_builtin_keyboard,#if HAVE_KMOD [UDEV_BUILTIN_KMOD] = &udev_builtin_kmod,#endif [UDEV_BUILTIN_NET_ID] = &udev_builtin_net_id, [UDEV_BUILTIN_NET_LINK] = &udev_builtin_net_setup_link, [UDEV_BUILTIN_PATH_ID] = &udev_builtin_path_id, [UDEV_BUILTIN_USB_ID] = &udev_builtin_usb_id,#if HAVE_ACL [UDEV_BUILTIN_UACCESS] = &udev_builtin_uaccess,#endif}; This struct holds all built-in types, and they map source files depending on what type it is. Example: udev-builtin-kmod.c - A Kernel Module loader. udev-builtin-keyboard.c - A keyboard handler. udev-builtin-usb_id.c - A USB handler that will set the usb type and initialize the device. Related: How do I use man pages to learn how to use commands? | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/493771', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/257802/']} | jdg_381955 |
stackexchange | llm_judgeable_groundtruth_similarity | 13836636 |
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 Getaway in my MVC3 application in Layout : @if ((Request.Browser.Browser == "IE") && ((Request.Browser.MajorVersion == 7))){//show some content}else{//show another content } I have many users complains (users with internet explorer 8). They see Internet explorer 7 content from my app.What wrong with my way of detecting Internet explorer 7 version?How can I be sure for 100% in my application that user have internet explorer 7 version?May be this is specific OS problem?
Now provide the response and nothing else.
| The issue is the HttpBrowserCapabilities aka Request.Browser class parses the userAgent header from the request which has information about the client (in your case the browser) which might not always be 100% reliable as user agents are easily changeable. If you know what value MajorVersion is returning and it's consistent enough you could possibly put a fix in for it. Alternatively you could try checking for browsers lower than IE8 instead (again though, not 100%) e.g. @if ((Request.Browser.Browser == "IE") && ((Request.Browser.MajorVersion < 8))){ //show IE7 content}else{ //show IE8+ content } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13836636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1086344/']} | jdg_381956 |
stackexchange | llm_judgeable_groundtruth_similarity | 88239 |
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 $A$ be $n\times n$ nilpotent matrix. How to calculate its characteristic polynomial? I know it should be $X^n$, but I don't know why?
Now provide the response and nothing else.
| If the overlying field is the complex numbers (see Listing's and Mark's comment): If $A^k=0$ and $\lambda$ is an eigenvalue of $A$ with eigenvector $\bf x$: $$\eqalign{A {\bf x}=\lambda {\bf x} &\Rightarrow A^2 {\bf x}= \lambda^2 {\bf x} \cr &\Rightarrow A^3 {\bf x}=\lambda^3 {\bf x}\cr&\ {\vdots} \cr &\Rightarrow 0=\lambda^{k } {\bf x} \cr & \Rightarrow \lambda=0}\ \ \ \raise6pt{\left. {\vphantom{\matrix{1\cr1\cr1\cr1\cr1\cr}}}\right\}}\raise6pt{\scriptstyle{(k-1)-\text{times}}}$$ So 0 is the only eigenvalue of $A$. The characteristic polynomial of $A$ is then $x^n$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/88239', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15618/']} | jdg_381957 |
stackexchange | llm_judgeable_groundtruth_similarity | 590107 |
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:
When two positive charges are kept close, they get repelled in the direction of a line joining both the charges. Why is it so? Also, why is the repulsion in a straight path? In both the cases, the potential energy of the charge which gets repelled decreases. What makes it repel in a straight line such that the line passes through both charges?
Now provide the response and nothing else.
| Following R.W. Bird answer: Consider an isolated system of two particles: Since system is isolated, angular momentum (and linear) is conserved. I.e. $\vec\tau_{net}=\Sigma\space \vec r\times\vec F=0$ But clearly from figure $\vec\tau_{net}=\vec r\space\times\space\vec F_y\ne 0$ Thus as R.W. Bird noted, the system violates the conservation of angular momentum. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/590107', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/271983/']} | jdg_381958 |
stackexchange | llm_judgeable_groundtruth_similarity | 266648 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)? This is how far I got by now: Script receives image via HTML Form Post and is processed by the following code ...incomming_image = self.request.get("img")image = db.Blob(incomming_image)... I found mimetypes.guess_type, but it does not work for me.
Now provide the response and nothing else.
| If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data. The format for this is: Start Marker | JFIF Marker | Header Length | Identifier0xff, 0xd8 | 0xff, 0xe0 | 2-bytes | "JFIF\0" so a quick recogniser would be: def is_jpg(filename): data = open(filename,'rb').read(11) if data[:4] != '\xff\xd8\xff\xe0': return False if data[6:] != 'JFIF\0': return False return True However this won't catch any bad data in the body. If you want a more robust check, you could try loading it with PIL . eg: from PIL import Imagedef is_jpg(filename): try: i=Image.open(filename) return i.format =='JPEG' except IOError: return False | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/266648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26763/']} | jdg_381959 |
stackexchange | llm_judgeable_groundtruth_similarity | 36676274 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I recently started working on three.js and now im facing issue on textgeometry.Im using three.js version 75 and i used js/helvetiker_bold.typeface.js font. var geometry = new THREE.TextGeometry( this.txt, { size: this.textSize, height: this.textHeight, curveSegments: 3, font: this.textFont, weight: "bold", style: "normal", bevelEnabled: false}); test is not rendering because of the following issue 1 Uncaught ReferenceError: _typeface_js is not defined 2.three.min.js:889 THREE.TextGeometry: font parameter is not an instance of THREE.Font Can anyone please help me out.
Now provide the response and nothing else.
| Use this pattern to load a font and render it with TextGeometry : var loader = new THREE.FontLoader();loader.load( 'fonts/helvetiker_bold.typeface.json', function ( font ) { var textGeo = new THREE.TextGeometry( "My Text", { font: font, size: 200, height: 50, curveSegments: 12, bevelThickness: 2, bevelSize: 5, bevelEnabled: true } ); var textMaterial = new THREE.MeshPhongMaterial( { color: 0xff0000 } ); var mesh = new THREE.Mesh( textGeo, textMaterial ); mesh.position.set( x, y, z ); scene.add( mesh );} ); three.js r.82 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36676274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5757345/']} | jdg_381960 |
stackexchange | llm_judgeable_groundtruth_similarity | 1199590 |
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 whose constructor is defined as internal, which means I cannot instantiate it. While that may make sense, I would still like to do it once for debugging and research purposes. Is it possible to do so with Reflection? I know I can access Private/Internal Members, but can I call an internal constructor? Or, as the constructor does nothing important, can I use reflection to say "Look, just give me an instance of the class without calling the constructor, I'll do it's work manually"? Performance and "Stability" is not an issue here, as it's not production code. Edit: Just as clarification: Sadly, I don't control the other assembly and don't have it's source code, I merely try to understand how it works as it's documentation is next to non-existent, but I am supposed to interface with it.
Now provide the response and nothing else.
| An alternative would be to nominate the calling assembly as a "friend" assembly. Simply add this to AssemblyInfo.cs file of the assembly containing the internal constructor: [assembly: InternalsVisibleTo("Calling.Assembly")] If you don't have access to the assembly, you can also call the constructor directly (using Reflection): MyClass obj = (MyClass) typeof(MyClass).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null).Invoke(null); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1199590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91/']} | jdg_381961 |
stackexchange | llm_judgeable_groundtruth_similarity | 22255476 |
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 posting a date to an API and the required format is as follows: 2014-12-01T01:29:18 I can get the date from the model like so: Model.created_at.to_s That returns: 2014-12-01 01:29:18 -0500 How can I use Rails or Ruby to format it like the required format with the T and removing the -0500?
Now provide the response and nothing else.
| Use Model.created_at.strftime("%FT%T") where, %F - The ISO 8601 date format (%Y-%m-%d)%T - 24-hour time (%H:%M:%S) Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method: Date (Year, Month, Day): %Y - Year with century (can be negative, 4 digits at least) -0001, 0000, 1995, 2009, 14292, etc. %C - year / 100 (round down. 20 in 2009) %y - year % 100 (00..99) %m - Month of the year, zero-padded (01..12) %_m blank-padded ( 1..12) %-m no-padded (1..12) %B - The full month name (``January'') %^B uppercased (``JANUARY'') %b - The abbreviated month name (``Jan'') %^b uppercased (``JAN'') %h - Equivalent to %b %d - Day of the month, zero-padded (01..31) %-d no-padded (1..31) %e - Day of the month, blank-padded ( 1..31) %j - Day of the year (001..366)Time (Hour, Minute, Second, Subsecond): %H - Hour of the day, 24-hour clock, zero-padded (00..23) %k - Hour of the day, 24-hour clock, blank-padded ( 0..23) %I - Hour of the day, 12-hour clock, zero-padded (01..12) %l - Hour of the day, 12-hour clock, blank-padded ( 1..12) %P - Meridian indicator, lowercase (``am'' or ``pm'') %p - Meridian indicator, uppercase (``AM'' or ``PM'') %M - Minute of the hour (00..59) %S - Second of the minute (00..59) %L - Millisecond of the second (000..999) %N - Fractional seconds digits, default is 9 digits (nanosecond) %3N millisecond (3 digits) %6N microsecond (6 digits) %9N nanosecond (9 digits) %12N picosecond (12 digits) For the complete list of formats for strftime method please visit APIDock | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/22255476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2879095/']} | jdg_381962 |
stackexchange | llm_judgeable_groundtruth_similarity | 18509527 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a other version to make the first letter of each string capital and also with FALSE for flac perl? name<-"hallo"gsub("(^[[:alpha:]])", "\\U\\1", name, perl=TRUE)
Now provide the response and nothing else.
| You can try something like: name<-"hallo"paste(toupper(substr(name, 1, 1)), substr(name, 2, nchar(name)), sep="") Or another way is to have a function like: firstup <- function(x) { substr(x, 1, 1) <- toupper(substr(x, 1, 1)) x} Examples: firstup("abcd")## [1] Abcdfirstup(c("hello", "world"))## [1] "Hello" "World" | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18509527', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1461646/']} | jdg_381963 |
stackexchange | llm_judgeable_groundtruth_similarity | 759014 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I compare a floating-point number to an integer? Will the float compare to integers in code? float f; // f has a saved predetermined floating-point value to it if (f >=100){__asm__reset...etc} Also, could I... float f;int x = 100;x+=f; I have to use the floating point value f received from an attitude reference system to adjust a position value x that controls a PWM signal to correct for attitude.
Now provide the response and nothing else.
| The first one will work fine. 100 will be converted to a float, and IEE754 can represent all integers exactly as floats, up to about 2 23 . The second one will also work but will be converted into an integer first, so you'll lose precision (that's unavoidable if you're turning floats into integers). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/759014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91942/']} | jdg_381964 |
stackexchange | llm_judgeable_groundtruth_similarity | 1379346 |
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:
Note: $F$ is a class of sets. I was solving a problem in Apostol's Calculus Volume 1. It is to show that$$B-\bigcup_{A\in F} A=\bigcap_{A\in F}(B-A)\qquad\text{ and }\qquad B-\bigcap_{A\in F} A=\bigcup_{A\in F}(B-A)$$so I thought that rather than repeating the problem just with $\bigcup$ and $\bigcap$ switched, why not create the notation of a circle with one half filled in to be like $\pm$ for the big cup and cap? In other words, see the attached image. The motivation for using this particular symbol should be clear because the one with a the bottom half colored black leaves only a semicircle at the top which is kinda $\bigcap$, and similarly the one with the top half colored black leaves a semicircular segment at the bottom which looks like $\bigcup$. But of course I do not mean to say that the one with the top colored black should denote $\bigcup$, nor that the one with the bottom colored black should denote $\bigcap$; rather, I am just using the symbols in the same way as say $\pm$ and $\mp$ are used in$$\tan(a\pm b)=\frac{\tan a\pm \tan b}{1\mp \tan a\tan b},$$to write two formulas in one. I hope this makes sense, please tell me what you think. Or maybe there is already a convention for this, in which case I would like to hear about it. Thanks!
Now provide the response and nothing else.
| I'm going to assume that the ellipse has the equation $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1$$ since that's the more standard assumption. Yours has $a$ and $b$ reversed and I'm not sure if you meant it that way or if that was a typo on your part (I think it was a typo since your expression for the eccentricity matches the standard one). I'll also assume $a \ge b$. The case $b \ge a$ is handled similarly. Now imagine that you rotate the ellipse around its long axis, that is, around the $x$ axis, and focus your attention on the strip that results from rotating a small arc of the ellipse, located at $(x,y)$ before the rotation. That elliptical arc has a length $ds$ that depends on its location, so it's a function of $(x,y)$. In fact, it's not hard to show that that arc-length is given by $$ds = dx\,\sqrt{1 + (\frac{dy}{dx})^2}$$ Anyway, the strip resulting from the rotation of that little elliptical arc has a circular shape and, therefore, an area approximately equal to $$dA = 2\pi\,\mbox{radius} \times ds$$ and you can see from the figure that the radius is just $y$, so $$dA = 2\pi\,y\,ds$$ Now, given the equation at the top, we find $$\frac{2x\,dx}{a^2} + \frac{2y\,dy}{b^2} = 0$$ so $$\frac{dy}{dx} = -\frac{b^2}{a^2}\,\frac{x}{y}$$ and $$ds = \frac{1}{a^2}\,\frac{dx}{y}\,\sqrt{b^4x^2 + a^4y^2}$$ As promised, $ds$ depends on $(x,y)$. Putting all of the above together, we find $$dA = dx\,\frac{2\pi}{a^2}\,\sqrt{b^4x^2 + a^4y^2}$$ The area of the entire surface of revolution is then twice the integral of the above expression, from $x=0$ to $x=a$. Twice because we're integrating over only half the ellipse: $$A = \frac{4\pi}{a^2}\int_{x\,=\,0}^{x\,=\,a} \sqrt{b^4x^2 + a^4y^2}\,dx$$ We still need to eliminate $y$, but that's easy. From the equation at the top, we find $$y^2 = b^2 - \frac{b^2}{a^2}\,x^2$$ and then: $$A = 4\pi\,\frac{b}{a}\int_{x\,=\,0}^{x\,=\,a} \sqrt{a^2 - (\frac{a^2 - b^2}{a^2})\,x^2}\,dx$$ The quantity $$\frac{a^2 - b^2}{a^2}$$ is none other than the ellipse's eccentricity $\varepsilon$. So, finally, we have $$A = 4\pi\,\frac{b}{a}\int_{x\,=\,0}^{x\,=\,a} \sqrt{a^2 - \varepsilon^2x^2}\,dx$$ Now use the parametrisation $x = a\,\sin\theta$ (Why $\sin$ instead of $\cos$? Because it makes the math easier down below. Shouldn't it be $\cos$, though? Not necessarily. Note that $x$ is now a dummy integration variable and we can choose any substitution we want) to get $$A = 4\pi\,ab\,\int_{\theta\,=\,0}^{\theta\,=\,\pi/2} \sqrt{1 - \varepsilon^2\sin^2\theta}\,\cos\theta\,d\theta$$ Next set $\sin\phi = \varepsilon\sin\theta$ so $\cos\phi\,d\phi = \varepsilon\cos\theta\,d\theta$ and $$A = 4\pi\,\frac{ab}{\varepsilon}\,\int\cos^2\phi\,d\phi$$ (I omitted the integration limits but will get back to them below) To integrate $\cos^2\phi$, we can use the fact that $\cos(2\phi) = \cos^2\phi - \sin^2\phi = 2\cos^2\phi - 1$. Thus, $$\cos^2\phi = \frac{1 + \cos(2\phi)}{2}$$ and $$\int\cos^2\phi\,d\phi = \int\frac{1 + \cos(2\phi)}{2}\,d\phi =\frac{\phi}{2} + \frac{\sin(2\phi)}{4}$$ Now back to the integration limits. Note that $\theta = 0$ implies $\sin\phi = 0$, thus $\phi = 0$, and $\theta = \pi/2$ implies $\sin\phi = \varepsilon$, that is, $\phi = \arcsin(\varepsilon)$. Note also that $0 \le \varepsilon \le 1$ since $a \ge b$. So then we get $$A = 2\pi\,\frac{ab}{\varepsilon}\,(\phi + \frac{\sin(2\phi)}{2})\,\big|_{0}^{\arcsin(\varepsilon)} =2\pi\,\frac{ab}{\varepsilon}\,\big[\,\arcsin(\varepsilon) + \frac{\sin(2\arcsin(\varepsilon))}{2}\,\big]$$Then, using $\sin(2\phi) = 2\sin\phi\cos\phi$, we find $$A = 2\pi\,\frac{ab}{\varepsilon}\,\big(\,\arcsin(\varepsilon) + \varepsilon\sqrt{1-\varepsilon^2}\,\big)$$ Finally, using the definition of the eccentricity, we get $$A = 2\pi\,\frac{ab}{\varepsilon}\,\big(\,\arcsin(\varepsilon) + \varepsilon\,\frac{b}{a}\,\big) = 2\pi\,b^2\,\big(1 + \frac{a}{b}\,\frac{\arcsin(\varepsilon)}{\varepsilon} \,\big)$$ which is the expression you wanted to prove. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1379346', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45220/']} | jdg_381965 |
stackexchange | llm_judgeable_groundtruth_similarity | 30362 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Most antiviruses have hundreds of thousands or even millions of malware signatures and yet they scan many files in a reasonable short time with high detection rates. Even real-time scanners doesn't slow computer noticeably but provide strong protection against threats. How can scanners achieve this kind of performance? I know it could be a broad question but I wanted to get a general idea about this.
Now provide the response and nothing else.
| Antivirus detection is a feature extraction and a classification problem . A great analogy is the 20 questions game where the goal is to identify an arbitrary object by asking 20 seemingly unrelated yes/no questions. The idea behind the game is that each answer would eliminate half of the objects so it is theoretically possible to describe 2^20 (1,048,576) objects with only 20 binary features. A different analogy is how the visual cortex processes visual information.Β The brain has very simple and fast hardware for detecting and classifying an infinite number of images. Only six layers of neurons (the number of neurons is estimated at 140 million) are used to extract progressively more complex features and pass them on to the next layer. The layers interact back and forward to each other to produce abstract notions that can be verified against memory. Antivirus engines store many features of known malware in the definition file and when they scan a new file they optimize the extraction and classification (matching) of those features. Storing features also makes the detection more robust so that small changes in a piece of malware won't thwart detection. Feature extraction is also done in parallel so that resources are fully utilized. Most features are designed by humans but there are some that do not make sense by themselves, like having a null byte at the end of the file or a ratio between file size and printable text size. Those nonsensical or unintuitive features are randomly generated and tested by data mining vast quantities of files. In the end the file is described and classified by the combination of features. As a side note, the best predictor for questions being closed on Stack Exchange is whether the first letter of the question is in lower case. So when a new file is scanned, it is quickly classified into finer and finer categories and then it is matched against a small set of signatures. Each step would exclude a large number of clean files and would dictate what other features should be extracted next. The first steps are very small in terms of computing resources but they dictate which more expensive steps should be taken later. By using only a few disk reads and CPU cycles the engine can determine the file type. Let's say it is a JAR file. Using this information, it starts collecting features of the JAR file. If it's signed, then the scan is aborted. If it's not importing any functions then the scan is aborted (I'm oversimplifying here). Is it using any tricky functionality? then more features should be extracted. Does it use known vulnerable functions? Then it should be thoroughly checked for known Java exploit signatures. On-access scanning has the same principle behind but it also works like a gatekeeper. So each action (usually API call) taken by a process is being checked for and allowed or denied. Similarly, each suspicious action triggers more filters and more checks. During the checks the process or thread is waiting for the operation to complete but sometimes the whole process is actively suspended. This might look like significant overhead but once a specific action is verified, it is later cached and performed very quickly or not performed at all. The result is a performance degradation similar to having a machine a couple of percentage points slower. Check the PCMark scores for 20 AV products here . So the speed optimization comes from very little work being performed on clean looking files which constitute the overwhelming majority of scanned files. The heavy lifting work is being done only on suspicious malware-looking files for which AV might even take seconds to emulate the process or even send it to the cloud for analysis. The magic is in the progressive classification. | {} | {'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/30362', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/8396/']} | jdg_381966 |
stackexchange | llm_judgeable_groundtruth_similarity | 4625 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose $F$ has discrete Fourier transform $(a_n)$ where $a_n=0$ unless $n=2^k$ for some $k > 0$, in which case $a_n=1/k$ (or $a_n=1/k^2$ if you want: I'm happy with anything polynomial). What sort of regularity conditions does $F$ have? Is it Holder continuous, or not? To be explicit: $$F(x)=\sum_{k=1}^\infty k^{-2} \exp(ix2^k)$$ for example. More generally, I'm interested in two dimensional (discrete) Fourier transforms: is there a good reference for this sort of thing?
Now provide the response and nothing else.
| If $0 < \alpha < 1/2$ then a continuous function on the circle is $\operatorname{Lip}_\alpha$ only if the Fourier coefficients satisfy $a_n = {\rm O}( n^{-\alpha})$; this is in Katznelson's book (Chapter I, Corollary 4.6) for instance. [ EDIT (2013-07-10) : at the time I thought this was "iff" but a comment points out that I misremembered; in any case, for lacunary series such as the one in the question, a lot more is known than in the general case; see e.g. Katznelson Chapter V for the basics.] So the function you defined above isn't going to be HΓΆlder continuous for any positive exponent, even though it's clearly continuous (absolutely convergent Fourier series). Off the top of my head, I don't know of any particularly good source for the higher-dimensional stuff. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/4625', 'https://mathoverflow.net', 'https://mathoverflow.net/users/406/']} | jdg_381967 |
stackexchange | llm_judgeable_groundtruth_similarity | 11365317 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Whilst doing git svn clone -s https://svn.example.com/repo/ I received the following output: r3073 = a6132f3a937b632015e66d694250da9f606b8333 (refs/remotes/trunk)Found possible branch point: https://svn.example.com/repo/trunk => https://svn.example.com/repo/branches/v1.3, 3073W: Refspec glob conflict (ref: refs/remotes/trunk):expected path: repo/branches/trunk real path: repo/trunkContinuing ahead with repo/trunkW: Refspec glob conflict (ref: refs/remotes/trunk):expected path: repo/branches/trunk real path: repo/trunkContinuing ahead with repo/trunkW: Refspec glob conflict (ref: refs/remotes/trunk):expected path: repo/branches/trunk real path: repo/trunkContinuing ahead with repo/trunkW: Refspec glob conflict (ref: refs/remotes/trunk):expected path: repo/branches/trunk real path: repo/trunkContinuing ahead with repo/trunkfatal: Not a valid object name refs/remotes/tags/Sync Controllerscat-file commit refs/remotes/tags/Sync Controllers: command returned error: 128 Running git branch -a gives: remotes/tags/Sync%20Controllersremotes/tags/v1.1remotes/trunkremotes/v1.2 I think the problem is that "remotes/tags/Sync Controllers" != "remotes/tags/Sync%20Controllers".
Now provide the response and nothing else.
| The tag on SVN has a space in it, but the tag in git had this space converted to %20 (URL encoded). To solve it just manually add a new tag with the verbatim name: cd .git/refs/remotes/tags/mv Sync%20Controllers Sync\ Controllers Then run the git svn clone command again. (Normally you'd do this with git tag OLDTAG NEWTAG but git was not allowing me to define a tag with a space in. The tag files are simply text files containing the hash of the relevant commit.) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11365317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/141284/']} | jdg_381968 |
stackexchange | llm_judgeable_groundtruth_similarity | 51145 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to know how far a type system in a programming language can be beneficial. For example, I know that in a dependently typed programming language, we can create a Vector class incorporating size of the vector in the type signature. It is like a de-facto example. We can also write a function append using those signatures so that compiler proves resulting list's size will be the sum of the input lists. Is there a way to encode, for example, in a sorting algorithm's type signature so that compiler guarantees resulting list to be a permutation of the input list? How this can be done, if it is possible?
Now provide the response and nothing else.
| Yes, it is possible to express a precise type for a sorting routine, such that any function having that type must indeed sort the input list. While there might be a more advanced and elegant solution, I'll sketch an elementary one, only. We will use a Coq-like notation. We start by defining a predicate requiring that f: nat -> nat acts as a permutation on $0..n-1$: Definition permutation (n: nat) (f: nat -> nat): Prop := (* once restricted, its codomain is 0..n-1 *) (forall m, m < n -> f m < n) /\ (* it is injective, hence surjective *) (forall m1 m2, m1 < n -> m2 < n -> f m1 = f m2 -> m1 = m2) . A simple lemma can easily be proved. Lemma lem1: forall n f, permutation n f -> m < n -> f m < n.... (* from the def *) We define what is the $m$th element of a list having length $n$. This function requires a proof h stating that $m<n$ indeed holds. Definition nth {A} {n} (l: list A n) m (h : m < n): A :=... (* recursion over n *) Given an ordering on A , we can express that a list is sorted: Definition ordering (A: Type) := { leq: A->A->bool | (* axioms for ordering *) (forall a, leq a a = true) /\ (forall a b c, leq a b = true -> leq b c = true -> leq a c = true) /\ (forall a b, leq a b = true -> leq b a = true -> a = b) } .Definition sorted {A} {n} (o: ordering A) (l: list A n): Prop :=... Finally here's the type for a sorting algorithm: Definition mysort (A: Type) (o: ordering A) (n: nat) (l: list A n): {s: list A n | sorted o s /\ exists f (p: permutation n f), forall (m: nat) (h: m < n), nth l m h = nth s (f m) (lem1 n f p h) } :=... (* the sorting algorithm, and a certificate for its output *) The output type states that the result list s is $n$ elements long, it is sorted, and that there's a permutation of $0..n-1$ that maps the elements in the input list l to the ones in the output list s . Note that we have to invoke the lemma above to prove $f(m) < n$, which is required by nth . Note however that it is the user, i.e. the programmer, which has to prove their sorting algorithm correct. The compiler will not simply verify that the sorting is correct: all it does is checking a provided proof. Indeed, the compiler can not do much more than that: semantic properties such as "this program is a sorting algorithm" are undecidable (by Rice theorem), so we can not hope to make the proving step fully automatic. In the far, far future, we can still hope that automatic theorem provers get so smart that "most" practically used algorithms can be automatically proved correct. The Rice theorem only states that this can not be done in all cases. All we can hope for is a correct, widely applicable, but inherently incomplete system. As a final note, it is sometimes forgotten that even simple type systems are incomplete ! E.g. even in Java int f(int x) { if (x+2 != 2+x) return "Houston, we have a problem!"; return 42;} is semantically type safe (it always returns an integer), but the type checker will complain about the unreachable return. | {} | {'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/51145', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/17530/']} | jdg_381969 |
stackexchange | llm_judgeable_groundtruth_similarity | 3669932 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What I mean with "intuitive": I can handle some formulas, but since I am not a professional mathematician I am not fluent in all the lingo, so I do not know by heart what "second countable" means. If I have to look up all these terms and try to understand them, it takes so much time, that I forget what I was researching in the first place... so basic terminology is appreciated. It was previously asked whether every manifold is a metric space , but I have to admit, I did not completely understand the answers. Assuming that a manifold is second-countable, the answer is "yes" (I cannot claim I full understood the property "second countable"). My (non-completely) translation of the answer https://math.stackexchange.com/a/1530066/340174 into an intuitive explanation is I want to find the distance from $x_0$ to y, both of which are elements of the manifold. Since a manifold is locally Euclidean, I can walk a infinitely small way in an "Euclidean" manner. So, I go a small step from $x_0$ to $x_1$ and I calculate the distance I walked, which is possible, because I can just use the Euclidean distance. I walk from $x_1$ to $x_2$ until I reach y and add up all the distances to the total distance. From all the possible paths I take the one that is the shortest and that is my distance. First question: It seems intuitively obvious to me that the first three conditions of a metric apply to manifold distances, as I described it above. But how do I know that the triangular condition applies as well to the distance over a manifold? Is there an intuitive explanation in the style I tried above? Originally I would have guessed (without too much thinking) that every metric space is a manifold, but not the other way around. Since the second part is wrong, I would guess that now, that the first part is also wrong. (Otherwise there would be no need to differentiate the two, right?) But what is that so? I can come of with a metric space, like one based on the Levenshtein distance, which is not continuous and my usual impression of manifolds is that they are continuous (since they are supposed to be Euclidean locally). However it seem there are also discrete manifolds (which I do not understand either). Second question: What is an intuitive explanation, why metric spaces are not necessarily manifolds?
Now provide the response and nothing else.
| To your first question: Take three points $A, B, C$ . Then by construction, $d(A,B)$ is the length of the shortest path from $A$ to $B$ . And similarly for $d(B,C)$ and $d(A,C)$ . Now consider the path $\gamma$ that you get by first following the shortest path from $A$ to $C$ , and then continuing on the shortest path from $C$ to $B$ . Clearly the length of $\gamma$ is the sum of the lengths of the two paths it is composed of, that is, $$\mathrm{length}(\gamma)=d(A,C)+d(C,B). \tag{1}$$ On the other hand, $\gamma$ clearly is a path going from $A$ to $B$ , and therefore is at least as long as the shortest path from $A$ to $B$ , $$\mathrm{length}(\gamma)\ge d(A,B). \tag{2}$$ Inserting $(1)$ in $(2)$ gives the triangle inequality. To your second question: A simple example of a metric space that is not a manifold is $\mathbb Q$ . Clearly it is a metric space (with $d(x,y)=\lvert x-y\rvert$ ), but it is not a manifold because it isn't locally homeomorphic to any $\mathbb R^n$ . Intuitively, in every neighbourhood of some point, there are points missing that would be there in $\mathbb R^n$ (in the case of $\mathbb Q$ , that's even true for all points, but if suffices if you can find one such point). Another way you can fail to be a manifold is when the dimension gets infinite. The set of infinite real sequences with finitely many non-zero entries is such an example. Clearly an infinite-dimensional metric space cannot be locally homeomorphic to a finite-dimensional one, such as $\mathbb R^n$ . Yet another way of failing to be a manifold is if it consists of parts of different dimension. For example, consider an open disc and a straight line not touching that disc, as subsets of $\mathbb R^2$ with the corresponding metric. Both the disc and the straight line separately are manifolds, but together they are not. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3669932', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/340174/']} | jdg_381970 |
stackexchange | llm_judgeable_groundtruth_similarity | 49915925 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created a tensorflow dataset, made it repeatable, shuffled it, divided it into batches, and have constructed an iterator to get the next batch. But when I do this, sometimes the elements are repetitive (within and among batches), especially for small datasets. Why?
Now provide the response and nothing else.
| Unlike what stated in your own answer, no, shuffling and then repeating won't fix your problems . The key source of your problem is that you batch, then shuffle/repeat . That way, the items in your batches will always be taken from contiguous samples in the input dataset. Batching should be one of the last operations you do in your input pipeline . Expanding the question slightly. Now, there is a difference in the order in which you shuffle, repeat and batch, but it's not what you think. Quoting from the input pipeline performance guide : If the repeat transformation is applied before the shuffletransformation, then the epoch boundaries are blurred. That is,certain elements can be repeated before other elements appear evenonce. On the other hand, if the shuffle transformation is appliedbefore the repeat transformation, then performance might slow down atthe beginning of each epoch related to initialization of the internalstate of the shuffle transformation. In other words, the former(repeat before shuffle) provides better performance, while the latter(shuffle before repeat) provides stronger ordering guarantees. Recapping Repeat, then shuffle: you lose the guarantee that all samples are processed in one epoch. Shuffle, then repeat: it is guaranteed that all samples will be processed before the next repeat begins, but you lose (slightly) in performance. Whichever you choose, do that before batching. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49915925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7428659/']} | jdg_381971 |
stackexchange | llm_judgeable_groundtruth_similarity | 16644475 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The title says it, look at my minimal example: template<class ptr_to_t>void f(ptr_to_t x) { typedef ptr_to_t t; // does not compile t elem = *x;}int main(){ int five = 5; f<int*>(&five); return 0;} Compiled like this: g++ -Wall typedef.cpp -o typedef This does not compile. What I want is to change the marked line (line 3) such that t is of type int (in this instantiation). Is such a typedef possible in C++11? Is such a typedef possible in "old" C++? Note: I guess this is a duplicate, but I really could not find this question anywhere.
Now provide the response and nothing else.
| Yes, it is possible. You should use std::remove_pointer from type_traits header: typedef typename std::remove_pointer<ptr_to_t>::type t; In pre-C++11 you could write your own implementation(like in the link above, for example): template< class T > struct remove_pointer {typedef T type;};template< class T > struct remove_pointer<T*> {typedef T type;};template< class T > struct remove_pointer<T* const> {typedef T type;};template< class T > struct remove_pointer<T* volatile> {typedef T type;};template< class T > struct remove_pointer<T* const volatile> {typedef T type;}; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16644475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/985292/']} | jdg_381972 |
stackexchange | llm_judgeable_groundtruth_similarity | 4269951 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
for example... if ( /* Condition */ ) { if ( /* Condition */ ) { if ( /* Condition */ ) { // Superb! } else { // Error 3 } } else { // Error 2 }} else { // Error 1} Do you know how to avoid this? Thank you!
Now provide the response and nothing else.
| If this is a library function, throw may be the appropriate action. if (!condition1) { throw "Condition 1 failed.";}if (!condition2) { throw "Condition 2 failed.";}if (!condition3) { throw "Condition 3 failed.";}// Superb! Other acceptable actions might be: Returning 0 , null , or undefined . Displaying an error to the user and returning. You will have to determine which failure action is right for your use case. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4269951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499899/']} | jdg_381973 |
stackexchange | llm_judgeable_groundtruth_similarity | 228595 |
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:
What are the main differences between two types of feedforward networks such as multilayer perceptrons (MLP) and radial basis function (RBF)? What are the fundamental differences between these two types?
Now provide the response and nothing else.
| MLP : uses dot products (between inputs and weights) and sigmoidal activation functions (or other monotonic functions such as ReLU ) and training is usually done through backpropagation for all layers (which can be as many as you want). This type of neural network is used in deep learning with the help of many techniques (such as dropout or batch normalization); RBF : uses Euclidean distances (between inputs and weights, which can be viewed as centers) and (usually) Gaussian activation functions (which could be multivariate), which makes neurons more locally sensitive. Thus, RBF neurons have maximum activation when the center/weights are equal to the inputs (look at the image below). Due to this property, RBF neural networks are good for novelty detection (if each neuron is centered on a training example, inputs far away from all neurons constitute novel patterns) but not so good at extrapolation. Also, RBFs may use backpropagation for learning, or hybrid approaches with unsupervised learning in the hidden layer (they usually have just 1 hidden layer). Finally, RBFs make it easier to grow new neurons during training. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/228595', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/12989/']} | jdg_381974 |
stackexchange | llm_judgeable_groundtruth_similarity | 48098829 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've started using Celery 4.1 in my Django Python project and have come across Signatures. In the documentation it says the following: You just learned how to call a task using the tasks delay method in the calling guide, and this is often all you need, but sometimes you may want to pass the signature of a task invocation to another process or as an argument to another function. A signature() wraps the arguments, keyword arguments, and execution options of a single task invocation in a way such that it can be passed to functions or even serialized and sent across the wire. Although I see them used in some of the examples I don't really know when and why to use them, as well as which problems they solve.Can someone explain this to a layman?
Now provide the response and nothing else.
| Signature used together with chain to create a workflow. ".s" is the abbreviation of ".signature". when use ".s", means that the result or return value of the front task will be pass to the next one. The opposite of 'signature' is 'immutable signature', in which every task is independent.for example(signature): res = chain(add.s(2,2), add.s(4), add.s(8))res().get()>> 16 example(immutable signature): res = chain(add.si(2,2)|add.si(4,4)|add.si(8,8))()res.get()>>16res.parent.get()>>8res.parent.parent.get()>>4 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48098829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5568461/']} | jdg_381975 |
stackexchange | llm_judgeable_groundtruth_similarity | 65858332 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've faced with The white square problem at SFML C++ while I'm trying to display a textured button. I've got an ImageButton.h which inherits from Button.h . The texture is loaded successfully (checked in debugger). But in the end, I see a white square . How to solve it? Button.h #ifndef BUTTON_H#define BUTTON_H#include<SFML/Graphics.hpp>class Button{public: Button(); Button(sf::Vector2f size, sf::Vector2f pos,sf::Color outlineColor, float sizeOutline); void virtual draw(sf::RenderWindow* w) = 0;protected: sf::RectangleShape frame;};#endif // !BUTTON_H Button.cpp #include "Button.h"Button::Button(){}Button::Button(sf::Vector2f size, sf::Vector2f pos,sf::Color outlineColor, float sizeOutline){ frame.setPosition(pos); frame.setSize(size); frame.setOutlineColor(outlineColor); frame.setOutlineThickness(sizeOutline);} ImageButton.h #ifndef IMAGE_BUTTON_H#define IMAGE_BUTTON_H#include"Button.h"class ImageButton : public Button{public: ImageButton(); ImageButton(sf::Vector2f size, sf::Vector2f pos, sf::Color outlineColor, float sizeOutline, std::string path); void draw(sf::RenderWindow* w);private: sf::Texture backTexture; sf::Sprite background;};#endif // !IMAGE_BUTTON_H ImageButton.cpp #include "ImageButton.h"ImageButton::ImageButton(){}ImageButton::ImageButton(sf::Vector2f size, sf::Vector2f pos, sf::Color outlineColor, float sizeOutline, std::string path) : Button(size,pos,outlineColor,sizeOutline){ backTexture.loadFromFile(path, sf::IntRect(sf::Vector2i(pos.x,pos.y),sf::Vector2i(size.x,size.y))); backTexture.setSmooth(true); background.setTexture(backTexture); background.setPosition(pos);}void ImageButton::draw(sf::RenderWindow* w){ w->draw(this->background); w->draw(this->frame);} programm.h #ifndef PROGRAMM_H#define PROGRAMM_H#include<SFML/Graphics.hpp>#include"ImageButton.h"class programm{public: programm(); void run();private: ImageButton b; sf::RenderWindow* window; sf::Event e; void render(); void update();};#endif // !PROGRAMM_H programm.cpp #include "programm.h"programm::programm(){ this->window = new sf::RenderWindow(sf::VideoMode(600, 600), "Novel Editor", sf::Style::Close); this->window->setPosition(sf::Vector2i(0, 0)); this->window->setFramerateLimit(60); this->b = ImageButton(sf::Vector2f(50.f, 50.f), sf::Vector2f(50.f, 50.f), sf::Color::Yellow, 5.f, "images\\putin.png");}void programm::run(){ while (this->window->isOpen()) { while (this->window->pollEvent(e)) { update(); } }}void programm::render(){ this->window->clear(); b.draw(this->window); this->window->display();}void programm::update(){ switch (e.type) { case sf::Event::Closed: { this->window->close(); break; } default: break; } render();} Screenshot
Now provide the response and nothing else.
| These 3 kind of probes have 3 different use cases. That's why we need 3 kind of probes. Liveness Probe If the Liveness Probe fails, the pod will be restarted (read more about failureThreshold). Use case: Restart pod, if the pod is dead. Best practices: Only include basic checks in the liveness probe. Never include checks on connections to other services (e.g. database). The check shouldn't take too long to complete.Always specify a light Liveness Probe to make sure that the pod will be restarted, if the pod is really dead. Startup Probe Startup Probes check, when the pod is available after startup. Use case: Send traffic to the pod, as soon as the pod is available after startup. Startup probes might take longer to complete, because they are only called on initializing. They might call a warmup task (but also consider init containers for initialization). After the Startup probe succeeds, the liveliness probe is called. Best practices: Specify a Startup Probe , if the pod takes a long time to start. The Startup and Liveness Probe can use the same endpoint, but the Startup Probe can have a less strict failure threshhold which prevents a failure on startup (s. Kubernetes in Action ). Readiness Probe In contrast to Startup Probes Readiness Probes check, if the pod is available during the complete lifecycle.In contrast to Liveness Probes only the traffic to the pod is stopped, if the Readiness probe fails, but there will be no restart. Use case: Stop sending traffic to the pod, if the pod can not temporarily serve because a connection to another service (e.g. database) fails and the pod will recover later. Best practices: Include all necessary checks including connections to vital services. Nevertheless the check shouldn't take too long to complete.Always specify a Readiness Probe to make sure that the pod only gets traffic, if the pod can properly handle incoming requests. Documentation This article explains very well the differences between the 3 kind of probes. The Official kubernetes documentation gives a good overview about all configuration options. Best practises for probes . The book Kubernetes in Action gives most detailed insights about the best practises. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/65858332', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13518476/']} | jdg_381976 |
stackexchange | llm_judgeable_groundtruth_similarity | 3427073 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a preferred method or style of creating a default implementation for interface methods? Suppose I had a commonly used interface where in 90% of the cases the functionality I wanted was identical. My first instinct is to create a concrete class with static methods. I would then delegate the functionality to the static methods when I want the default functionality. Here is a simple example: Interface public interface StuffDoer{ public abstract void doStuff();} Concrete Implementation of methods public class ConcreteStuffDoer{ public static void doStuff(){ dosomestuff... }} Concrete Implementation using default functionality public class MyClass implements StuffDoer{ public void doStuff(){ ConcreteSuffDoer.doStuff(); } } Is there a better approach here? EDIT After seeing a few of the proposed solutions I think I should be more clear about my intent. Essentially I am trying to work around Java not allowing multiple inheritance. Also to be clear I am not trying to make a statement about whether or not Java should allow multiple inheritance. I am just looking for the best way to create a default method implementation for classes implementing an interface.
Now provide the response and nothing else.
| This is the approach I would take: public interface MyInterface { MyInterface DEFAULT = new MyDefaultImplementation(); public static class MyDefaultImplemenation implements MyInterface { } } Of course, the MyDefaultImplementation may need to be private, or its own top level class, depending on what makes sense. You can then have the following in your implementations: public class MyClass implements MyInterface { @Override public int someInterfaceMethod(String param) { return DEFAULT.someInterfaceMethod(param); } } Its a bit more self-documenting, and ultimately more flexible, than a default implementation class that exists elsewhere but is not referenced by the interface. With this you can do things like just pass the default implementation as a method parameter when required (which you cannot do with the static methods). Of course, the above only works if there is no state involved. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3427073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1104/']} | jdg_381977 |
stackexchange | llm_judgeable_groundtruth_similarity | 7299619 |
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 JSP which gets a value called sum from the DB... String sum= request.getAttribute("s").toString();int s = Integer.parseInt(sum); I have a field in a form called weight who's value cannot exceed sum. So on clicking submit i'm running a function called validate. Which would check if field is greater than or equal to sum but it keeps giving me the warning all the time. <script type="text/javascript">function validate(){ var x= document.getElementById("s"); if(document.getElementById("weight").value>x) { alert("Weight exceeds maximum limit...!!!"); return false; } return true;} </script> Would appreciate the help..
Now provide the response and nothing else.
| Okay, so I worked it through and came to the following solution. I needed to costumize devise a little bit, but it's not that complicated. The User model # user.rbclass User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable attr_accessible :email, :password, :password_confirmation, :remember_me belongs_to :rolable, :polymorphic => trueend The Customer model # customer.rbclass Customer < ActiveRecord::Base has_one :user, :as => :rolableend The Designer model # designer.rbclass Designer < ActiveRecord::Base has_one :user, :as => :rolableend So the User model has a simple polymorphic association, defining if it's a Customer or a Designer. The next thing I had to do was to generate the devise views with rails g devise:views to be part of my application. Since I only needed the registration to be customized I kept the app/views/devise/registrations folder only and removed the rest. Then I customized the registrations view for new registrations, which can be found in app/views/devise/registrations/new.html.erb after you generated them. <h2>Sign up</h2><% # customized code begin params[:user][:user_type] ||= 'customer' if ["customer", "designer"].include? params[:user][:user_type].downcase child_class_name = params[:user][:user_type].downcase.camelize user_type = params[:user][:user_type].downcase else child_class_name = "Customer" user_type = "customer" end resource.rolable = child_class_name.constantize.new if resource.rolable.nil? # customized code end%><%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %> <%= my_devise_error_messages! # customized code %> <div><%= f.label :email %><br /> <%= f.email_field :email %></div> <div><%= f.label :password %><br /> <%= f.password_field :password %></div> <div><%= f.label :password_confirmation %><br /> <%= f.password_field :password_confirmation %></div> <% # customized code begin %> <%= fields_for resource.rolable do |rf| %> <% render :partial => "#{child_class_name.underscore}_fields", :locals => { :f => rf } %> <% end %> <%= hidden_field :user, :user_type, :value => user_type %> <% # customized code end %> <div><%= f.submit "Sign up" %></div><% end %><%= render :partial => "devise/shared/links" %> For each User type I created a separate partial with the custom fields for that specific User type, i.e. Designer --> _designer_fields.html <div><%= f.label :label_name %><br /><%= f.text_field :label_name %></div> Then I setup the routes for devise to use the custom controller on registrations devise_for :users, :controllers => { :registrations => 'UserRegistrations' } Then I generated a controller to handle the customized registration process, copied the original source code from the create method in the Devise::RegistrationsController and modified it to work my way (don't forget to move your view files to the appropriate folder, in my case app/views/user_registrations class UserRegistrationsController < Devise::RegistrationsController def create build_resource # customized code begin # crate a new child instance depending on the given user type child_class = params[:user][:user_type].camelize.constantize resource.rolable = child_class.new(params[child_class.to_s.underscore.to_sym]) # first check if child instance is valid # cause if so and the parent instance is valid as well # it's all being saved at once valid = resource.valid? valid = resource.rolable.valid? && valid # customized code end if valid && resource.save # customized code if resource.active_for_authentication? set_flash_message :notice, :signed_up if is_navigational_format? sign_in(resource_name, resource) respond_with resource, :location => redirect_location(resource_name, resource) else set_flash_message :notice, :inactive_signed_up, :reason => inactive_reason(resource) if is_navigational_format? expire_session_data_after_sign_in! respond_with resource, :location => after_inactive_sign_up_path_for(resource) end else clean_up_passwords(resource) respond_with_navigational(resource) { render_with_scope :new } end endend What this all basically does is that the controller determines which user type must be created according to the user_type parameter that's delivered to the controller's create method by the hidden field in the view which uses the parameter by a simple GET-param in the URL. For example: If you go to /users/sign_up?user[user_type]=designer you can create a Designer. If you go to /users/sign_up?user[user_type]=customer you can create a Customer. The my_devise_error_messages! method is a helper method which also handles validation errors in the associative model, based on the original devise_error_messages! method module ApplicationHelper def my_devise_error_messages! return "" if resource.errors.empty? && resource.rolable.errors.empty? messages = rolable_messages = "" if !resource.errors.empty? messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join end if !resource.rolable.errors.empty? rolable_messages = resource.rolable.errors.full_messages.map { |msg| content_tag(:li, msg) }.join end messages = messages + rolable_messages sentence = I18n.t("errors.messages.not_saved", :count => resource.errors.count + resource.rolable.errors.count, :resource => resource.class.model_name.human.downcase) html = <<-HTML <div id="error_explanation"> <h2>#{sentence}</h2> <ul>#{messages}</ul> </div> HTML html.html_safe endend UPDATE: To be able to support routes like /designer/sign_up and /customer/sign_up you can do the following in your routes file: # routes.rbmatch 'designer/sign_up' => 'user_registrations#new', :user => { :user_type => 'designer' }match 'customer/sign_up' => 'user_registrations#new', :user => { :user_type => 'customer' } Any parameter that's not used in the routes syntax internally gets passed to the params hash. So :user gets passed to the params hash. So... that's it. With a little tweeking here and there I got it working in a quite general way, that's easily extensible with many other User models sharing a common User table. Hope someone finds it useful. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7299619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/329563/']} | jdg_381978 |
stackexchange | llm_judgeable_groundtruth_similarity | 1088222 |
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:
Here is the question: If the roots of the equation $$x^4 - px^3 + qx^2 - pqx + 1 = 0$$ are $\alpha, \beta, \gamma,$ and $\delta$, show that $$(\alpha + \beta + \gamma)(\alpha + \beta + \delta)(\alpha + \gamma + \delta)(\beta + \gamma + \delta)= 1.$$ Pretty much exhausted my resources.If there are more than one way of doing it please state and you can state some good books for this particular topic. $$ 1+x^4+\text{qx}^2-\text{px}^3-\text{pqx} \equiv x^4+x^3 (-\alpha -\beta -\gamma -\delta )+x^2 (\alpha \beta +\alpha \gamma +\alpha \delta +\beta \gamma +\beta \delta +\gamma \delta )+x (-\alpha \beta \gamma -\alpha \beta \delta -\alpha \gamma \delta -\beta \gamma \delta )+\alpha \beta \gamma \delta$$ So,$$\text{p} = \alpha+\beta +\gamma +\delta $$$$\text{q} = \alpha \beta +\alpha \gamma +\alpha \delta +\beta \gamma +\beta \delta +\gamma \delta$$$$\text{p}\text{q}=\alpha \beta \gamma +\alpha \beta \delta +\alpha \gamma \delta +\beta \gamma \delta$$$$1= \alpha \beta \gamma \delta$$
Now provide the response and nothing else.
| We know the factorisation: $f(x) = x^4 - px^3 + qx^2 - pqx + 1 = (x - \alpha)(x - \beta)(x - \gamma)(x - \delta)$ Equating $x^3$ coefficients gives $\alpha + \beta + \gamma + \delta = p$. Thus we can write the expression in question as: $(p - \delta)(p - \gamma)(p - \beta)(p - \alpha) = f(p) = 1$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1088222', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/204325/']} | jdg_381979 |
stackexchange | llm_judgeable_groundtruth_similarity | 31669 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I like create an image backup for the first time I'm backing up a system. After this first time I use rsync to do incremental backups. My usual image backup is as follows: Mount and zero out the empty space: dd if=/dev/zero of=temp.dd bs=1M rm temp.dd umount and dd the drive while compressing it dd if=/dev/hda conv=sync,noerror bs=64K | gzip -c > /mnt/sda1/hda.ddimg.gz to put the system back to normal, I will usually do a gunzip -c /mnt/sda1/hda.img.gz | dd of=/dev/hda conv=sync,noerror bs=64K This is really straightforward and allows my to save the 'whole drive' but really just save the used space. Here is the problem. Lets say I do the above but not on a clean system and don't get the rsync backups going soon enough and there are files that I want to access that are on the image. Let's say I don't have the storage space to actually unzip and dd the image to a drive but want to mount the image to get individual files off of it.... Is this possible? Normally, one wouldn't compress the dd image, which will allow you to just mount the image using -o loop ... but this isn't my case... Any suggestions for mounting the compressed img on the fly? Would using AVFS to 'mount' the gz file then mounting the internal dd.img work (I don't think so... but would need verification...)?
Now provide the response and nothing else.
| It depends on whether the disk image is a full disk image, or just a partition. Washing the partition(s) If the disk is in good working condition, you will get better compression if you wash the empty space on the disk with zeros. If the disk is failing, skip this step. If you're imaging an entire disk then you will want to wash each of the partitions on the disk. CAUTION: Be careful, you want to set the of to a file in the mounted partition, NOT THE PARTITION ITSELF! mkdir image_sourcesudo mount /dev/sda1 image_sourcedd if=/dev/zero of=image_source/wash.tmp bs=4Mrm image_source/wash.tmpsudo umount image_source Making a Partition Image mkdir imagesudo dd if=/dev/sda1 of=image/sda1_backup.img bs=4M Where sda is the name of the device, and 1 is the partition number. Adjust accordingly for your system if you want to image a different device or partition. Making a Whole Disk Image mkdir imagesudo dd if=/dev/sda of=image/sda_backup.img bs=4M Where sda is the name of the device. Adjust accordingly for your system if you want to image a different device. Compression Make a "squashfs" image that contains the full uncompressed image. sudo apt-get install squashfs-toolsmksquashfs image squash.img Streaming Compression To avoid making a separate temporary file the full size of the disk, you can stream into a squashfs image. mkdir empty-dirmksquashfs empty-dir squash.img -p 'sda_backup.img f 444 root root dd if=/dev/sda bs=4M' Mounting a compressed partition image First mount the squashfs image, then mount the partition image stored in the mounted squashfs image. mkdir squash_mountsudo mount squash.img squash_mount Now you have the compressed image mounted, mount the image itself (that is inside the squashfs image) mkdir compressed_imagesudo mount squash_mount/sda1_backup.img compressed_image Now your image is mounted under compressed_image . EDIT: If you wanted to simply restore the disk image onto a partition at this point (instead of mounting it to browse/read the contents), just dd the image at squash_mount/sda1_backup.img onto the destination instead of doing mount . Mounting a compressed full disk image This requires you to use a package called kpartx. kpartx allows you to mount individual partitions in a full disk image. sudo apt-get install kpartx First, mount your squashed partition that contains the full disk image mkdir compressed_imagesudo mount squash.img compressed_image Now you need to create devices for each of the partitions in the full disk image: sudo kpartx -a compressed_image/sda_backup.img This will create devices for the partitions in the full disk image at /dev/mapper/loopNpP where N is the number assigned for the loopback device, and P is the partition number. For example: /dev/mapper/loop0p1 . Now you have a way to mount the individual partitions in the full disk image: mkdir fulldisk_part1sudo mount /dev/mapper/loop0p1 fulldisk_part1 | {} | {'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/31669', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4631/']} | jdg_381980 |
stackexchange | llm_judgeable_groundtruth_similarity | 10672578 |
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 extract video frames and save them as image. import os, sysfrom PIL import Imagea, b, c = os.popen3("ffmpeg -i test.avi")out = c.read()dp = out.index("Duration: ")duration = out[dp+10:dp+out[dp:].index(",")]hh, mm, ss = map(float, duration.split(":"))total = (hh*60 + mm)*60 + ssfor i in xrange(9): t = (i + 1) * total / 10 os.system("ffmpeg -i test.avi -ss %0.3fs frame%i.png" % (t, i)) But I have this error: FFmpeg version CVS, Copyright (c) 2000-2004 Fabrice BellardMac OSX universal build for ffmpegX configuration: --enable-memalign-hack --enable-mp3lame --enable-gpl --disable-vhook --disable-ffplay --disable-ffserver --enable-a52 --enable-xvid --enable-faac --enable-faad --enable-amr_nb --enable-amr_wb --enable-pthreads --enable-x264 libavutil version: 49.0.0 libavcodec version: 51.9.0 libavformat version: 50.4.0 built on Apr 15 2006 04:58:19, gcc: 4.0.1 (Apple Computer, Inc. build 5250)Input #0, avi, from 'test.avi': Duration: 00:00:30.5, start: 0.000000, bitrate: 465 kb/s Stream #0.0, 25.00 fps(r): Video: mpeg4, yuv420p, 640x480 Stream #0.1: Audio: mp3, 32000 Hz, mono, 32 kb/sUnable for find a suitable output format for 'frame0.png' Edit: ffmpeg -formats FFmpeg version CVS, Copyright (c) 2000-2004 Fabrice BellardMac OSX universal build for ffmpegX configuration: --enable-memalign-hack --enable-mp3lame --enable-gpl --disable-vhook --disable-ffplay --disable-ffserver --enable-a52 --enable-xvid --enable-faac --enable-faad --enable-amr_nb --enable-amr_wb --enable-pthreads --enable-x264 libavutil version: 49.0.0 libavcodec version: 51.9.0 libavformat version: 50.4.0 built on Apr 15 2006 04:58:19, gcc: 4.0.1 (Apple Computer, Inc. build 5250)File formats: E 3g2 3gp2 format E 3gp 3gp format D 4xm 4X Technologies format D RoQ Id RoQ format D aac ADTS AAC DE ac3 raw ac3 E adts ADTS AAC DE aiff Audio IFF DE alaw pcm A law format DE amr 3gpp amr file format DE asf asf format E asf_stream asf format DE au SUN AU Format DE avi avi format D avs avs format E crc crc testing format D daud D-Cinema audio format D dts raw dts DE dv DV video format E dvd MPEG2 PS format (DVD VOB) D ea Electronic Arts Multimedia Format DE ffm ffm format D film_cpk Sega FILM/CPK format D flic FLI/FLC/FLX animation format DE flv flv format E framecrc framecrc testing format DE gif GIF Animation DE h261 raw h261 DE h263 raw h263 DE h264 raw H264 video format D idcin Id CIN format DE image image sequence DE image2 image2 sequence DE image2pipe piped image2 sequence DE imagepipe piped image sequence D ingenient Ingenient MJPEG D ipmovie Interplay MVE format DE m4v raw MPEG4 video format D matroska Matroska file format DE mjpeg MJPEG video D mm American Laser Games MM format DE mmf mmf format E mov mov format D mov,mp4,m4a,3gp,3g2,mj2 QuickTime/MPEG4/Motion JPEG 2000 format E mp2 MPEG audio layer 2 DE mp3 MPEG audio layer 3 E mp4 mp4 format DE mpeg MPEG1 System format E mpeg1video MPEG video E mpeg2video MPEG2 video DE mpegts MPEG2 transport stream format D mpegvideo MPEG video E mpjpeg Mime multipart JPEG format DE mulaw pcm mu law format D nsv NullSoft Video format E null null video format DE nut nut format D nuv NuppelVideo format D ogg Ogg E psp psp mp4 format D psxstr Sony Playstation STR format DE rawvideo raw video format D redir Redirector format DE rm rm format E rtp RTP output format D rtsp RTSP input format DE s16be pcm signed 16 bit big endian format DE s16le pcm signed 16 bit little endian format DE s8 pcm signed 8 bit format D sdp SDP D shn raw shorten D smk Smacker Video D sol Sierra SOL Format E svcd MPEG2 PS format (VOB) DE swf Flash format D tta true-audio DE u16be pcm unsigned 16 bit big endian format DE u16le pcm unsigned 16 bit little endian format DE u8 pcm unsigned 8 bit format E vcd MPEG1 System format (VCD) D vmd Sierra VMD format E vob MPEG2 PS format (VOB) DE voc Creative Voice File format DE wav wav format D wc3movie Wing Commander III movie format D wsaud Westwood Studios audio format D wsvqa Westwood Studios VQA format DE yuv4mpegpipe YUV4MPEG pipe formatImage formats (filename extensions, if any, follow): DE gif gifCodecs: D V 4xm D V D 8bps DEA aac D V D aasc DEA ac3 DEA adpcm_4xm DEA adpcm_adx DEA adpcm_ct DEA adpcm_ea DEA adpcm_ima_dk3 DEA adpcm_ima_dk4 DEA adpcm_ima_qt DEA adpcm_ima_smjpeg DEA adpcm_ima_wav DEA adpcm_ima_ws DEA adpcm_ms DEA adpcm_sbpro_2 DEA adpcm_sbpro_3 DEA adpcm_sbpro_4 DEA adpcm_swf DEA adpcm_xa DEA adpcm_yamaha D A alac DEA amr_nb DEA amr_wb DEV D asv1 DEV D asv2 D V D avs D V bmp D V D camstudio D V D camtasia D V D cinepak D V D cljr D A cook D V D cyuv DES dvbsub DES dvdsub DEV D dvvideo DEV D ffv1 DEVSD ffvhuff D A flac D V D flic DEVSD flv D V D fraps DEA g726 DEV D h261 DEVSDT h263 D VSD h263i EV h263p DEV DT h264 DEVSD huffyuv D V D idcinvideo D V D indeo2 D V indeo3 D A interplay_dpcm D V D interplayvideo EV jpegls D V kmvc EV ljpeg D V D loco D A mace3 D A mace6 D V D mdec DEV D mjpeg D V D mjpegb D V D mmvideo DEA mp2 DEA mp3 D A mp3adu D A mp3on4 DEVSDT mpeg1video DEVSDT mpeg2video DEVSDT mpeg4 D A mpeg4aac D VSDT mpegvideo DEVSD msmpeg4 DEVSD msmpeg4v1 DEVSD msmpeg4v2 D V D msrle D V D msvideo1 D V D mszh D V D nuv DEV pam DEV pbm DEA pcm_alaw DEA pcm_mulaw DEA pcm_s16be DEA pcm_s16le DEA pcm_s24be DEA pcm_s24daud DEA pcm_s24le DEA pcm_s32be DEA pcm_s32le DEA pcm_s8 DEA pcm_u16be DEA pcm_u16le DEA pcm_u24be DEA pcm_u24le DEA pcm_u32be DEA pcm_u32le DEA pcm_u8 DEV pgm DEV pgmyuv DEV png DEV ppm D A qdm2 D V D qdraw D V D qpeg D V D qtrle DEV rawvideo D A real_144 D A real_288 D A roq_dpcm D V D roqvideo D V D rpza DEV D rv10 DEV D rv20 D A shorten D A smackaud D V smackvid D V D smc DEV snow D A sol_dpcm DEA sonic EA sonicls D V D sp5x DEV D svq1 D VSD svq3 D V theora D V D truemotion1 D V D truemotion2 D A truespeech D A tta D V D ultimotion D V vc9 D V D vcr1 D A vmdaudio D V D vmdvideo D A vorbis D V vp3 D V D vqavideo D A wmav1 D A wmav2 DEVSD wmv1 DEVSD wmv2 D V D wnv1 D A ws_snd1 D A xan_dpcm D V D xan_wc3 D V D xl EV xvid DEV D zlib D V zmbvSupported file protocols: file: pipe: udp: rtp: tcp: http:Frame size, frame rate abbreviations: ntsc pal qntsc qpal sntsc spal film ntsc-film sqcif qcif cif 4cifMotion estimation methods: zero(fastest) full(slowest) log phods epzs(default) x1 hex umh iterNote, the names of encoders and decoders dont always match, so there areseveral cases where the above table shows encoder only or decoder only entrieseven though both encoding and decoding are supported for example, the h263decoder corresponds to the h263 and h263p encoders, for file formats its evenworse What is wrong in my code? Thanks in advance
Now provide the response and nothing else.
| ffmpeg is complaining about there being a missing %d in the filename because you've asked it to convert multiple frames. This post suggests this would be a better way of using ffmpeg to extract single frames ffmpeg -i n.wmv -ss 00:00:20 -t 00:00:1 -s 320Γ240 -r 1 -f singlejpeg myframe.jpg [ edit ] After a bit more research , here is a command line which works outputing single png frames ffmpeg -i test.avi -vcodec png -ss 10 -vframes 1 -an -f rawvideo test.png Tested on my ubuntu 12.04 laptop | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10672578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/361635/']} | jdg_381981 |
stackexchange | llm_judgeable_groundtruth_similarity | 8670530 |
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 new to Javascript (and programming in general) and have been trying to get a basic grasp on working with the DOM. Apologies if this is a very basic mistake, but I looked around and couldn't find an answer. I am trying to use the appendChild method to add a heading and some paragraph text into the in the very basic HTML file below. <html> <head> <title>JS Practice</title> </head><body> <script src="script.js"></script> <div id = "main"> <h1>Simple HTML Page</h1> <p>This is a very simple HTML page.</p> <p>It's about as basic as they come. It has: </p> <ul> <li>An H1 Tag</li> <li>Two paragraphs</li> <li>An unordered list</li> </ul> </div> <div id="javascript"> </div></body></html> Here is the js code: var newHeading = document.createElement("h1"); var newParagraph = document.createElement("p"); newHeading.innerHTML = "New Heading!"; newParagraph.innerHTML = "Some text for a paragraph."; document.getElementById("javascript").appendChild(newHeading); document.getElementById("javascript").appendChild(newParagraph); Running it causes an error: "Cannot call method 'appendChild' of null" Help? I can't figure out why this isn't working...
Now provide the response and nothing else.
| Assuming this code is inside the script.js file, this is because the javascript is running before the rest of the HTML page has loaded. When an HTML page loads, when it comes across a linked resource such as a javascript file, it loads that resource, executes all code it can, and then continues running the page. So your code is running before the <div> is loaded on the page. Move your <script> tag to the bottom of the page and you should no longer have the error. Alternatively, introduce an event such as <body onload="doSomething();"> and then make a doSomething() method in your javascript file which will run those statements. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8670530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1058180/']} | jdg_381982 |
stackexchange | llm_judgeable_groundtruth_similarity | 479552 |
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:
Under a standard gaussian distribution (mean 0 and variance 1), the kurtosis is $3$ . Compared to a heavy tail distribution, is the kurtosis normally larger or smaller?
Now provide the response and nothing else.
| I. A direct answer to the OP Answer: It depends on what you mean by βheavy tails.β By some definitions of βheavy tails,β the answer is βno,β as pointed out here and elsewhere. Why do we care about heavy tails? Because we care about outliers (substitute the phrase βrare, extreme observationβ if you have a problem with the word βoutlier.β However, I will use the term βoutlierβ throughout for brevity.) Outliers are interesting from several points of view: In finance, outlier returns cause much more money to change hands than typical returns (see Talebβs discussion of black swans). In hydrology, the outlier flood will cause enormous damage and needs to be planned for. In statistical process control, outliers indicate βout of controlβ conditions that warrant immediate investigation and rectification. In regression analysis, outliers have enormous effects on the least squares fit. In statistical inference, the degree to which distributions produce outliers has an enormous effect on standard t tests for mean values. Similarly, the degree to which a distribution produces outliers has an enormous effect on the accuracy of the usual estimate of the variance of that distribution. So for various reasons, there is a great interest in outliers in data, and in the degree to which a distribution produces outliers. Notions of heavy-tailedness were therefore developed to characterize outlier-prone processes and data. Unfortunately, the commonly-used definition of βheavy tailsβ involving exponential bounds and asymptotes is too limited in its characterization of outliers and outlier-prone data generating processes: It requires tails extending to infinity, so it rules out bounded distributions that produce outliers. Further, the standard definition does not even apply to a data set , since all empirical distributions are necessarily bounded. Here is an alternative class of definitions of βheavy-tailedness,β which I will call βtail-leverage( $m$ )β to avoid confusion with existing definitions of heavy-tailedness, that addresses this concern. Definition: Assume absolute moments up to order $m>2$ exist for random variables $X$ and $Y$ . Let $U = |(X - \mu_X)/\sigma_X|^m$ and let $V =|(Y - \mu_Y)/\sigma_Y|^m$ . If $E(V) > E(U)$ , then $Y$ is said to have greater tail-leverage( $m$ ) than $X$ . The mathematical rationale for the definition is as follows: Suppose $E(V) > E(U)$ , and let $\mu_U = E(U)$ . Draw the pdf (or pmf, in the discrete case, or in the case of an actual data set) of $V$ , which is $p_V(v)$ . Place a fulcrum at $\mu_U$ on the horizontal axis. Because of the well-known fact that the distribution balances at its mean, the distribution $p_V(v)$ βfalls to the rightβ of the fulcrum at $\mu_U$ . Now, what causes it to βfall to the rightβ? Is it the concentration of mass less than 1, corresponding to the observations of $Y$ that are within a standard deviation of the mean? Is it the shape of the distribution of $Y$ corresponding to observations that are within a standard deviation of the mean? No, these aspects are to the left of the fulcrum, not to the right. It is the extremes of the distribution (or data) of $Y$ , in one or both tails, that produce high positive values of $V$ , which cause the βfalling to the right.β To illustrate, consider the following two graphs of discrete distributions. The top distribution has kurtosis = 2.46, "platykurtic," and the bottom has kurtosis = 3.45, "leptokurtic." Notice that kurtosis is my tail leverage measure with $m=4$ . Both distributions are scaled to a mean of 0.0 and variance of 1.0. Now, consider the distributions of the data values raised to the fourth power, with the red vertical bar indicating the mean of the top distribution: The top distribution balances at the red bar, which locates the kurtosis of the original, untransformed data (2.46). But the bottom distribution, having larger mean (3.45, the kurtosis of the original, untransformed data), "falls to the right" of the red bar located at 2.46. What causes it to "fall to the right"? Is it greater peakedness? No, because the first distribution is more peaked. Is it greater concentration of mass near the mean? No, because this would make it "fall to the left." As is apparent from the graph, it is the extreme values that makes it "fall to the right." BTW, the term βleverageβ should now be clear, given the physical representation involving the point of balance. But it is worth noting that, in the characterization of the distribution βfalling to the right,β that the βtail leverageβ measures can legitimately be called measures of βtail weight.β I chose not to do that because the "leverage" term is more precise. Much has been made of the fact that kurtosis does not correspond directly to the standard definition of βheavy tails.β Of course it doesnβt. Neither does it correspond to any but one of the infinitely many definitions of βtail leverageβ I just gave. If you restrict your attention to the case where $m=4$ , then an answer to the OPβs question is as follows: Greater tail leverage (using $m=4$ in the definition) does indeed imply greater kurtosis (and conversely). They are identical. Incidentally, the βleverageβ definition applies equally to data as it does to distributions: When you apply the kurtosis formula to the empirical distribution, it gives you the estimate of kurtosis without all the so-called βbias corrections.β (This estimate has been compared to others and is reasonable, often better in terms of accuracy; see "Comparing Measures of Sample Skewness and Kurtosis," D. N. Joanes and C. A. Gill, Journal of the Royal Statistical Society. Series D (The Statistician) Vol. 47, No. 1 (1998), pp. 183-189.) My stated leverage definition also resolves many of the various comments and answers given in response to the OP: Some beta distributions can be more greatly tail-leveraged (even if βthin-tailedβ by other measures) than the normal distribution. This implies a greater outlier potential of such distributions than the normal, as described above regarding leverage and the fulcrum, despite the normal distribution having infinite tails and the beta being bounded. Further, uniforms mixed with classical βheavy-tailedβ distributions are still "heavy-tailed," but can have less tail leverage than the normal distribution, provided the mixing probability on the βheavy tailedβ distribution is sufficiently low so that the extremes are very uncommon, and assuming finite moments. Tail leverage is simply a measure of the extremes (or outliers). It differs from the classic definition of heavy-tailedness, even though it is arguably a viable competitor. It is not perfect; a notable flaw is that it requires finite moments, so quantile-based versions would be useful as well. Such alternative definitions are needed because the classic definition of βheavy tailsβ is far too limited to characterize the universe of outlier-prone data-generating processes and their resulting data. II. My paper in The American Statistician My purpose in writing the paper βKurtosis as Peakedness, 1905-2014: R.I.P.β was to help people answer the question, βWhat does higher (or lower) kurtosis tell me about my distribution (or data)?β I suspected the common interpretations (still seen, by the way), βhigher kurtosis implies more peaked, lower kurtosis implies more flatβ were wrong, but could not quite put my finger on the reason. And, I even wondered that maybe they had an element of truth, given that Pearson said it, and even more compelling, that R.A. Fisher repeated it in all revisions of his famous book. However, I was not able to connect any math to the statement that higher (lower) kurtosis implied greater peakedness (flatness). All the inequalities went in the wrong direction. Then I hit on the main theorem of my paper. Contrary to what has been stated or implied here and elsewhere, my article was not an βopinionβ piece; rather, it was a discussion of three mathematical theorems. Yes, The American Statistician (TAS) does often require mathematical proofs. I would not have been able to publish the paper without them. The following three theorems were proven in my paper, although only the second was listed formally as a βTheorem.β Main Theorem: Let $Z_X = (X - \mu_X)/\sigma_X$ and let $\kappa(X) = E(Z_X^4)$ denote the kurtosis of $X$ . Then for any distribution (discrete, continuous or mixed, which includes actual data via their discrete empirical distribution), $E\{Z_X^4 I(|Z_X| > 1)\}\le\kappa(X)\le E\{Z_X^4 I(|Z_X| > 1)\} +1$ . This is a rather trivial theorem to prove but has major consequences: It states that the shape of the distribution within a standard deviation of the mean (which ordinarily would be where the βpeakβ is thought to be located) contributes very little to the kurtosis. Instead, the theorem implies that for all data and distributions, kurtosis must lie within $\pm 0.5$ of $E\{Z_X^4 I(|Z_X| > 1)\} + 0.5$ . A very nice visual image of this theorem by user "kjetil b Halvorsen" is given at https://stats.stackexchange.com/a/362745/102879; see my comment that follows as well. The bound is sharpened in the Appendix of my TAS paper: Refined Theorem: Assume $X$ is continuous and that the density of $Z_X^2$ is decreasing on [0,1]. Then the β+1β of the main theorem can be sharpened to β+0.5β. This simply amplifies the point of the main theorem that kurtosis is mostly determined by the tails. More recently, @sextus-empiricus was able to reduce the " $+0.5$ " bound to " $+1/3$ ", see https://math.stackexchange.com/a/3781761 . A third theorem proven in my TAS paper states that large kurtosis is mostly determined by (potential) data that are $b$ standard deviations away from the mean, for arbitrary $b$ . Theorem 3: Consider a sequence of random variables $X_i$ , $ i = 1,2,\dots$ , for which $\kappa(X_i) \rightarrow \infty$ . Then $E\{Z_i^4I(|Z_i| > b)\}/ \kappa(X_i) \rightarrow 1$ , for each $b>0$ . The third theorem states that high kurtosis is mostly determined by the most extreme outliers; i.e., those observations that are $b$ or more standard deviations from the mean. These are mathematical theorems, so there can be no argument with them. Supposed βcounterexamplesβ given in this thread and in other online sources are not counterexamples; after all, a theorem is a theorem, not an opinion. So what of one suggested βcounterexample,β where spiking the data with many values at the mean (which thereby increases βpeakednessβ) causes greater kurtosis? Actually, that example just makes the point of my theorems: When spiking the data in this way, the variance is reduced, thus the observations in the tails are more extreme, in terms of number of standard deviations from the mean. And it is observations with large standard deviation from the mean, according to the theorems in my TAS paper, that cause high kurtosis. Itβs not the peakedness. Or to put it another way, the reason that the spike increases kurtosis is not because of the spike itself, it is because the spike causes a reduction in the standard deviation, which makes the tails more standard deviations from the mean (i.e., more extreme), which in turn increases the kurtosis. It simply cannot be stated that higher kurtosis implies greater peakedness, because you can have a distribution that is perfectly flat over an arbitrarily high percentage of the data (pick 99.99% for concreteness) with infinite kurtosis. (Just mix a uniform with a Cauchy suitably; there are some minor but trivial and unimportant technical details regarding how to make the peak absolutely flat.) By the same construction, high kurtosis can be associated with any shape whatsoever for 99.99% of the central distribution - U-shaped, flat, triangular, multi-modal, etc. There is also a suggestion in this thread that the center of the distribution is important, because throwing out the central data of the Cauchy example in my TAS paper makes the data have low kurtosis. But this is also due to outliers and extremes: In throwing out the central portion, one increases the variance so that the extremes are no longer extreme (in terms of $Z$ values), hence the kurtosis is low. Any supposed "counterexample" actually obeys my theorems. Theorems have no counterexamples; otherwise, they would not be theorems. A more interesting exercise than βspikingβ or βdeleting the middleβ is this: Take the distribution of a random variable $X$ (discrete or continuous, so it includes the case of actual data), and replace the mass/density within one standard deviation of the mean arbitrarily, but keep the mean and standard deviation of the resulting distribution the same as that of $X$ . Q: How much change can you make to the kurtosis statistic over all such possible replacements? A: The difference between the maximum and minimum kurtosis values over all such replacements is $\le 0.25. $ The above question and its answer comprise yet another theorem. Anyone want to publish it? I have its proof written down (itβs quite elegant, as well as constructive, identifying the max and min distributions explicitly), but I lack the incentive to submit it as I am now retired. I have also calculated the actual max differences for various distributions of $X$ ; for example, if $X$ is normal, then the difference between the largest and smallest kurtosis is over all replacements of the central portion is 0.141. Hardly a large effect of the center on the kurtosis statistic! On the other hand, if you keep the center fixed, but replace the tails, keeping the mean and standard deviation constant, you can make the kurtosis infinitely large. Thus, the effect on kurtosis of manipulating the center while keeping the tails constant, is $\le 0.25$ . On the other hand, the effect on kurtosis of manipulating the tails, while keeping the center constant, is infinite. So, while yes, I agree that spiking a distribution at the mean does increase the kurtosis, I do not find this helpful to answer the question, βWhat does higher kurtosis tell me about my distribution?β There is a difference between βA implies Bβ and βB implies A.β Just because all bears are mammals does not imply that all mammals are bears. Just because spiking a distribution increases kurtosis does not imply that increasing kurtosis implies a spike; see the uniform/Cauchy example alluded to above in my answer. It is precisely this faulty logic that caused Pearson to make the peakedness/flatness interpretations in the first place. He saw a family of distributions for which the peakedness/flatness interpretations held, and wrongly generalized. In other words, he observed that a bear is a mammal, and then wrongly inferred that a mammal is a bear. Fisher followed suit forever, and here we are. A case in point: People see this picture of "standard symmetric PDFs" (on Wikipedia at https://en.wikipedia.org/wiki/File:Standard_symmetric_pdfs.svg ) and think it generalizes to the βflatness/peakednessβ conclusions. Yes, in that family of distributions, the flat distribution has the lower kurtosis and the peaked one has the higher kurtosis. But it is an error to conclude from that picture that high kurtosis implies peaked and low kurtosis implies flat. There are other examples of low kurtosis (less than the normal distribution) distributions that are infinitely peaked, and there are examples of infinite kurtosis distributions that are perfectly flat over an arbitrarily large proportion of the observable data. The bear/mammal conundrum also arises in the Finucan conditions, which state (oversimplified) that if tail probability and peak probability increase (losing some mass in between to maintain the standard deviation), then kurtosis increases. This is all fine and good, but you cannot turn the logic around and say that increasing kurtosis implies increasing tail and peak mass (and reducing what is in between). That is precisely the fatal flaw with the sometimes-given interpretation that kurtosis measures the βmovement of mass simultaneously to the tails and peak but away from the shoulders." Again, all mammals are not bears. A good counterexample to that interpretation is given here https://math.stackexchange.com/a/2523606/472987 in βcounterexample #1, which shows a family of distributions in which the kurtosis increases to infinity, while the mass inside the center stays constant. (There is also a counterexample #2 that has the mass in the center increasing to 1.0 yet the kurtosis decreases to its minimum, so the often-made assertion that kurtosis measures βconcentration of mass in the centerβ is wrong as well.) Many people think that higher kurtosis implies βmore probability in the tails.β This is not true; counterexample #1 shows that you can have higher kurtosis with less tail probability when the tails extend. So what does kurtosis measure? It precisely measures tail leverage (which can be called tail weight as well) as amplified through fourth powers, as I stated above with my definition of tail-leverage( $m$ ). I would just like to reiterate that my TAS article was not an opinion piece. It was instead a discussion of mathematical theorems and their consequences. There is much additional supportive material in the current post that has come to my attention since writing the TAS article, and I hope readers find it to be helpful for understanding kurtosis. | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/479552', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/108150/']} | jdg_381983 |
stackexchange | llm_judgeable_groundtruth_similarity | 554119 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was testing with some convergence series criteria, but I'm in trouble with the next: $$ \sum \frac{1+\cos(n)}{n+1}$$ I am sure that direct comparison criteria works, but what is the correct series to compare?
Now provide the response and nothing else.
| $\sum \frac{\cos n}{n+1}$ converges by Dirichlet's test $\color{blue}{^{[1]}}$. $\sum \frac{1}{n+1}$ diverges by Integral test against $\int_0^n \frac{dx}{1+x}$. $\sum \frac{1+\cos n}{n+1}$ diverges because it is a sum of a convergent and a divergence sequence. Notes $\color{blue}{[1]}$ To apply the Dirichlet's Test, one need to verify two conditions $\frac{1}{n+1}$ is monotonic decreasing and converges to $0$. The partials sums $\sum_{n=1}^N \cos n$ is bounded. The $1^{st}$ condition is obvious, the $2^{nd}$ condition is also true because$$\sum_{n=1}^N \cos n = \Re \left[ \sum_{n=1}^N e^{in} \right] = \Re\left[ e^i \frac{1-e^{iN}}{1-e^i}\right]\quad\implies\quad\left|\sum_{n=1}^N \cos n\right| \le \frac{2}{| 1 - e^i|} = \frac{1}{\sin\frac12}$$If you don't like the use of complex number, you can also derive same inequality using trigonometry. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/554119', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18927/']} | jdg_381984 |
stackexchange | llm_judgeable_groundtruth_similarity | 4707936 |
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 you display an error message in HTML, which element do you use, <span> or <label> ? Can you list some pros and cons for each of them, assuming that some styling, such as color and margin will be applied through their class ?
Now provide the response and nothing else.
| Assuming you mean an error message associated with a specific form control, use a <label> . The semantic arguments are subject to debate, as they aren't clear cut in this case, but the practical arguments win quite nicely. If a screen reader is in forms mode , it may skip over non-label text thus hiding the error messages from the user. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4707936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407236/']} | jdg_381985 |
stackexchange | llm_judgeable_groundtruth_similarity | 7683 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When comparing o,m,p -toluidine basicities, the ortho effect is believed to explain why o -toluidine is weaker. But when comparing o,m,p -toluic acid basicities, the ortho effect is stated as a reason why o -toluic acid is stronger acid. I was told that the ortho effect is a phenomenon in which an ortho- group causes steric hindrance, forcing the $\ce{-COOH}$, $\ce{-NH2}$ or some other bulky group to move out of the plane, inhibiting resonance. Then, if the ortho effect inhibits resonance, why is o -toluic acid the strongest and o -toluidine the weakest? Where am I going wrong in my understanding of the ortho effect?
Now provide the response and nothing else.
| I'd like to throw a tentative explanation for the ortho effect into the ring: In the molecules in question, an interaction between the protons of the methyl group and the lone pair of the amine nitrogen and the negative charge on the carboxylate, respectively, can be assumed. In the first case, the electron density on the N atom is (slightly) reduced and thus the basicity of o -toluidine. In the latter case, a similar interaction provides additional stabilisation of the carboxylate. As a result, o -toluic acid is more acidic than the isomers. | {} | {'log_upvote_score': 7, 'links': ['https://chemistry.stackexchange.com/questions/7683', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/4114/']} | jdg_381986 |
stackexchange | llm_judgeable_groundtruth_similarity | 1124590 |
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:
From this website, http://www.nayuki.io/page/fast-fibonacci-algorithms (fast doubling proof close to the bottom of the page). I have understood the proof for the most part but I am struggling to see how this part of the proof works especially when the the F(n) function is squared. \begin{align} F(2n+1) &= F(n+1)^2 + F(n)^2. \\ F(2n) &= F(n) \left[ F(n+1) + F(n-1) \right] \\ &= F(n) \left[ F(n+1) + (F(n+1) - F(n)) \right] \\ &= F(n) \left[ 2F(n+1) - F(n) \right]. \\ F(2n-1) &= F(n)^2 + F(n-1)^2. \end{align}
Now provide the response and nothing else.
| Start with: $$F(n+1) = F(n) + F(n-1)$$ Rewrite as: $$\begin{align} F(n + 1) &= F(n) + F(n-1) \\ F(n) &= F(n) \end{align}$$ which is: $$\begin{align}\begin{bmatrix} F(n+1) \\ F(n)\end{bmatrix}&=\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}\begin{bmatrix} F(n) \\ F(n-1)\end{bmatrix} \\ &=\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^2\begin{bmatrix} F(n-1) \\ F(n-2)\end{bmatrix} \\ &=\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^3\begin{bmatrix} F(n-1) \\ F(n-3)\end{bmatrix} \\ & \dots \\ &=\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n\begin{bmatrix} F(1) \\ F(0)\end{bmatrix} \end{align}$$ Taking $F(0) = 0$ and $F(1) = 1$, you get: $$\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n = \begin{bmatrix} F(n+1) & F(n) \\ F(n) & F(n-1) \end{bmatrix}$$ So to use "doubling", we just plug $2n$ into the formula: $$\begin{align}\begin{bmatrix} F(2n+1) \\ F(2n)\end{bmatrix}&=\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^{2n}\begin{bmatrix} F(1) \\ F(0)\end{bmatrix} \\ \\ &=\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^{n}\begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^{n}\begin{bmatrix} F(1) \\ F(0)\end{bmatrix} \\ \\ &=\begin{bmatrix} F(n+1) & F(n) \\ F(n) & F(n-1) \end{bmatrix}\begin{bmatrix} F(n+1) & F(n) \\ F(n) & F(n-1) \end{bmatrix}\begin{bmatrix} 1 \\ 0 \end{bmatrix} \\ \\ &=\begin{bmatrix} F(n+1)^2 + F(n)^2 \\ F(n)F(n+1) + F(n-1)F(n) \end{bmatrix} \\ \\ ~\\ & \text{And if you want...}\\ ~\\ &=\begin{bmatrix} F(n+1)^2 + F(n)^2 \\ F(n)F(n+1)+ \bigg(F(n+1) - F(n)\bigg)F(n) \end{bmatrix}\\ \\&=\begin{bmatrix} F(n+1)^2 + F(n)^2 \\ 2F(n+1)F(n) - F(n)^2 \end{bmatrix}\end{align}$$ Which isn't actually better than matrix exponentiation asymptotically. And regardless, since the Fibonacci sequence grows exponentially, it will always require exponential time to compute just due to the size of the output. The matrix or "doubling" approach takes you from $O({\rm exp}~x^2)$ to $O({\rm exp}~x)$ asymptotic calculation time, which isn't nothing, but it still isn't exactly tractable either. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1124590', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211428/']} | jdg_381987 |
stackexchange | llm_judgeable_groundtruth_similarity | 46850689 |
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 is takeWhile() different from filter() in Java 9. What extra utility does it have? Stream.of(1,2,3,4,5,6,7,8,9,10).filter(i -> i < 4 ) .forEach(System.out::println); This is perhaps what following would do Stream.of(1,2,3,4,5,6,7,8,9,10).takeWhile(i -> i < 4 ) .forEach(System.out::println); What was the need of this new function then?
Now provide the response and nothing else.
| filter will remove all items from the stream that do not satisfy the condition. takeWhile will abort the stream on the first occurrence of an item which does not satisfy the condition. e.g. Stream.of(1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1) .filter(i -> i < 4 ) .forEach(System.out::print); will print 123321 but Stream.of(1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1) .takeWhile(i -> i < 4 ) .forEach(System.out::print); will print 123 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/46850689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5808553/']} | jdg_381988 |
stackexchange | llm_judgeable_groundtruth_similarity | 52151383 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to know how to call this function? And where can i find it's implementation if it doesn't have name? extern void (*_malloc_message)(const char* p1, const char* p2, const char* p3, const char* p4);
Now provide the response and nothing else.
| It isn't a function. It's a declaration saying that _malloc_message is a pointer to a function, with return type void and the parameters as given. In order to use it, you'd have to assign to it the address of a function with that arity, return type, and parameter types. Then you'd use _malloc_message as if it were a function. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52151383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5941712/']} | jdg_381989 |
stackexchange | llm_judgeable_groundtruth_similarity | 3598681 |
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: C#: what is the difference between i++ and ++i? I see this operator (++) very often. I know what it does ultimately, but it seems like there's some rules I don't understand. For example, it seems to matter if you put it before or after the variable you're using it on. Can someone explain this?
Now provide the response and nothing else.
| The statement x++; is exactly equivalent to x = x + 1; except that x is evaluated only once (which makes a difference if it is an expression involving property getters). The difference between the following two: DoSomething(x++); // notice x first, then ++DoSomething(++x); // notice ++ first, then x Is that in the first one, the method DoSomething will see the previous value of x before it was incremented. In the second one, it will see the new (incremented) value. For more information, see C# Operators on MSDN. It is possible to declare a custom ++ operator for your own classes, in which case the operator can do something different. If you want to define your own ++ operator, see Operator Overloading Tutorial on MSDN. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3598681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330995/']} | jdg_381990 |
stackexchange | llm_judgeable_groundtruth_similarity | 15049864 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on an algorithm to check if a given edge is included in one of all possible mst's. For this question, we are considering non-distinct values and our edge e connects vertices A & B. So far, I have: If a path can be made from A to B consisting of edges with weights less than or equal to the weight of our edge e--we can say that edge e is not a part of any MST. Am I missing anything here/ ideas on a better algorithm? EDIT: What are thoughts on a solution involving the cycle property-- So, we consider all edges with weight less than the edge we are considering. If we can make a path from A->B with those edges, we can say that it is not part of any MST?
Now provide the response and nothing else.
| We will solve this using MST cycle property , which says that, "For any cycle C in the graph, if the weight of an edge e of C is larger than the weights of all other edges of C, then this edge cannot belong to an MST." Now, run the following O(E+V) algorithm to test if the edge E connecting vertices u and v will be a part of some MST or not. Step 1 Run dfs from one of the end-points(either u or v) of the edge E considering only those edges that have weight less than that of E. Step 2 Case 1 If at the end of this dfs, the vertices u and v get connected, then edge E cannot be a part of some MST. This is because in this case there definitely exists a cycle in the graph with the edge E having the maximum weight and it cannot be a part of the MST(from the cycle property). Case 2 But if at the end of the dfs u and v stay disconnected, then edge E must be the part of some MST as in this case E is always not the maximum weight edge in all the cycles that it is a part of. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15049864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1169425/']} | jdg_381991 |
stackexchange | llm_judgeable_groundtruth_similarity | 22876410 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a list of tuples: self.gridKeys = self.gridMap.keys() # The keys of the instance of the GridMap (It returns the product of every possible combination of positions in the specified grid, in tuples.)print self.gridKeys self.gridKeys: [(7, 3), (6, 9), (0, 7), (1, 6), (3, 7), (2, 5), (8, 5), (5, 8), (4, 0), (9, 0), (6, 7), (5, 5), (7, 6), (0, 4), (1, 1), (3, 2), (2, 6), (8, 2), (4, 5), (9, 3), (6, 0), (7, 5), (0, 1), (3, 1), (9, 9), (7, 8), (2, 1), (8, 9), (9, 4), (5, 1), (7, 2), (1, 5), (3, 6), (2, 2), (8, 6), (4, 1), (9, 7), (6, 4), (5, 4), (7, 1), (0, 5), (1, 0), (0, 8), (3, 5), (2, 7), (8, 3), (4, 6), (9, 2), (6, 1), (5, 7), (7, 4), (0, 2), (1, 3), (4, 8), (3, 0), (2, 8), (9, 8), (8, 0), (6, 2), (5, 0), (1, 4), (3, 9), (2, 3), (1, 9), (8, 7), (4, 2), (9, 6), (6, 5), (5, 3), (7, 0), (6, 8), (0, 6), (1, 7), (0, 9), (3, 4), (2, 4), (8, 4), (5, 9), (4, 7), (9, 1), (6, 6), (5, 6), (7, 7), (0, 3), (1, 2), (4, 9), (3, 3), (2, 9), (8, 1), (4, 4), (6, 3), (0, 0), (7, 9), (3, 8), (2, 0), (1, 8), (8, 8), (4, 3), (9, 5), (5, 2)] After sorting: self.gridKeys = self.gridMap.keys() # The keys of the instance of the GridMap (It returns the product of every possible combination of positions in the specified grid, in tuples.)self.gridKeys.sort() # They're dicts, so they need to be properly ordered for further XML-analysis.print self.gridKeys self.gridKeys: [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 0), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 0), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (7, 0), (7, 1), (7, 2), (7, 3), (7, 4), (7, 5), (7, 6), (7, 7), (7, 8), (7, 9), (8, 0), (8, 1), (8, 2), (8, 3), (8, 4), (8, 5), (8, 6), (8, 7), (8, 8), (8, 9), (9, 0), (9, 1), (9, 2), (9, 3), (9, 4), (9, 5), (9, 6), (9, 7), (9, 8), (9, 9)] The first element of each tuple is the "x", and the second the "y". I'm moving objects in a list through iteration and using these keys (So, if I want to move something in the x axis, I have to go through all the column, and that might be causing a horrid problem that I'm not being able to solve). How can I sort the tuples in this way?: [(1, 0), (2, 0), (3, 0), (4, 0), (5, 0), ...]
Now provide the response and nothing else.
| You can use the key parameter of the sort function, to sort the tuples. The function of key parameter, is to come up with a value which has to be used to compare two objects. So, in your case, if you want the sort to use only the first element in the tuple, you can do something like this self.gridKeys.sort(key=lambda x: x[0]) If you want to use only the second element in the tuple, then self.gridKeys.sort(key=lambda x: x[1]) sort function will pass each and every element in the list to the lambda function you pass as parameter to key and it will use the value it returns, to compare two objects in the list. So, in your case, lets say you have two items in the list like this data = [(1, 3), (1, 2)] and if you want to sort by the second element, then you would do data.sort(key=lambda x: x[1]) First it passes (1, 3) to the lambda function which returns the element at index 1 , which is 3 and that will represent this tuple during the comparison. The same way, 2 will be used for the second tuple. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22876410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1795924/']} | jdg_381992 |
stackexchange | llm_judgeable_groundtruth_similarity | 147939 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I intersperse strings among variables to create a table with labels for each entry. A simple example of what I tried to do would be a table of the value of a function $f(x)$ and the value of $x$. For example: Table[{"x=" x, "f[x]=" f}, {x, 0, 1, .1}] // TableForm What I would like to obtain: x=0 f=f[0]x=0.1 f=f[0.1]x=0.2 f=f[0.2]... But, of course, my code didn't produce that.
Now provide the response and nothing else.
| You (apparently) have a scalar function of three variables, so you cannot use a simple ContourPlot ; you must use ContourPlot3D . Moreover 3DPlot (which does not exist in Mathematica but instead Plot3D ) takes a function of two variables and plots the value in the third dimension. Instead you should use this: DensityPlot3D[x z + y z - x y z, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}, PlotLegends->Automatic] If you want contours: ContourPlot3D[x z + y z - x y z, {x, -2, 2}, {y, -2, 2}, {z, -2, 2}, Contours -> 10] If you want two-dimensional slices: GraphicsGrid[ Partition[ Table[ ContourPlot[x z + y z - x y z, {x, -2, 2}, {y, -2, 2}], {z, -2, 2, .5}], 3]] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/147939', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/49008/']} | jdg_381993 |
stackexchange | llm_judgeable_groundtruth_similarity | 21734905 |
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 perform a series of SQL*Server steps using dapper from C#. One step creates a temp table and populates it. Following steps query data from the temp table. The create/populate seems to run successfully, but the first query from the temp table fails saying: "Invalid object name '#GetPageOfGlobalUsers'." using (SqlConnection connection = DBConnectionProvider.CreateConnection()) { ... misc setup stuff... connection.Execute(@" create table #GetPageOfGlobalUsers(row int, EmailAddress nvarchar(max), LastName nvarchar(max), FirstName nvarchar(max), Id uniqueidentifier) insert into #GetPageOfGlobalUsers SELECT ROW_NUMBER() OVER (order by LastName, FirstName, EmailAddress) row, EmailAddress, LastName, FirstName, Id FROM Users WHERE LastName like @search or FirstName like @search or EmailAddress like @search ", new { search = search } ); int count = connection.Query<int>(@" SELECT count(*) from tempdb..#GetPageOfGlobalUsers ").Single<int>();... more queries from the temp table follow Above, the Execute works, but the Query fails with the error I mentioned above. (Note that I get the same error whether or not I use the "tempdb.." prefix.) If I create a permanent table instead (i.e. if I remove the leading hash) or if I make it a global temp table (i.e. prefix the name with two hashes) everything works fine. My understanding is that temp tables named with a single hash are scoped by the duration of the connection, so I don't know what's going on. But I'm sure someone can tell me! (BTW, I would appreciate it if no one tells me "don't do it this way" unless it simply can't be done.)
Now provide the response and nothing else.
| I don't understand exactly what's going on, but I am able to work around the problem by creating the temp table in an Execute of its own, as opposed to in an Execute that both creates the table and populates it, as in the code shown in my question. That is, the following works: connection.Execute(@" create table #PagesOfUsers(row int, EmailAddress nvarchar(max), LastName nvarchar(max), FirstName nvarchar(max), Id uniqueidentifier)" ); connection.Execute(@" insert into #PagesOfUsers SELECT ROW_NUMBER() OVER (order by LastName, FirstName, EmailAddress) row, EmailAddress, LastName, FirstName, Id FROM Users WHERE LastName like @search or FirstName like @search or EmailAddress like @search ", new { search = search } ); int count = connection.Query<int>(@" SELECT count(*) from #PagesOfUsers ").Single<int>(); This isn't horrible, but it is inconvenient. It's worth noting that I'd rather not have to explicitly create the temp table at all. Indeed, I'd originally coded the create/populate operation as a SELECT INTO so I didn't have to itemize the temp table's columns. But that also ran into the "invalid object" error on the subsequent query, so I tried the explicit CREATE TABLE to see if it made a difference and posted my question here after finding that it didn't. The behavior I'm seeing is that when the temp table is created and populated in the same Execute, it really isn't in tempdb after the Execute ends, ostensibly successfully. That leaves me to wonder if the Execute in my original code was doing anything at all! For all I can tell, it amounted to a NOOP. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21734905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3302659/']} | jdg_381994 |
stackexchange | llm_judgeable_groundtruth_similarity | 45847392 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create a news ticker with horizontal text that scrolls continuously without a break between loops. Ideally, the solution would be pure css/html, but I don't know if that's possible. Here's my rudimentary attempt so far: http://jsfiddle.net/lgants/ncgsrnza/ . Note that the fiddle contains an unwanted break between each loop. <p class="marquee"><span>This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text</span></p> .marquee { margin: 0 auto; white-space: nowrap; overflow: hidden; } .marquee span { display: inline-block; padding-left: 100%; animation: marquee 5s linear infinite; }
Now provide the response and nothing else.
| You could try having two marquees and set one of them with a delayed animation of 2.5s which is half the time of the full animation (5s). .marquee { margin: 0 auto; white-space: nowrap; overflow: hidden; position: absolute;}.marquee span { display: inline-block; padding-left: 100%; animation: marquee 5s linear infinite;}.marquee2 span { animation-delay: 2.5s;}@keyframes marquee { 0% { transform: translate(0, 0); } 100% { transform: translate(-100%, 0); }} <p class="marquee"> <span>This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - </span></p><p class="marquee marquee2"> <span>This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - </span></p> | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45847392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6090736/']} | jdg_381995 |
stackexchange | llm_judgeable_groundtruth_similarity | 1984718 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Show that any open interval $(a,b), (a,\infty), (-\infty,b)$ are homeomorphic to $\mathbb{R}$. I already know that $(a,b)$ is homeomorphic to $\mathbb{R}$. We know $(-1,1)$ and $\mathbb{R}$ are homeomorphic, then we define a suitable homeomorphism $f:(-1,1) \implies \mathbb{R}$ by $f(x)= \dfrac{x}{1-|x|}$. So I want to know how to prove that $(a,\infty), (-\infty,b)$ are homeomorphic to $\mathbb{R}$.
Now provide the response and nothing else.
| Let $q_i\in\mathbb{Q}$ be a decreasing sequence such that $q_i\to \sqrt{2}$ as $i\to\infty$ and consider$$\bigcup_{i=1}^\infty (q_i,\infty).$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1984718', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/382577/']} | jdg_381996 |
stackexchange | llm_judgeable_groundtruth_similarity | 19717902 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Till Android 4.3, an Android device with Bluetooth Low Energy support could only act as a central device. As is given in the Android 4.3 Bluetooth LE docs: Android 4.3 (API Level 18) introduces built-in platform support for Bluetooth Low Energy in the central role and provides APIs that apps can use to discover devices, query for services, and read/write characteristics. With the introduction of Android 4.4 KitKat , can it also behave as a peripheral device now? I couldn't find any documentation of that. If not, then do we have to wait for Android 4.5 for getting the BTLE peripheral mode on Android device? Or is there any alternative way in which an Android device can be made to act as a peripheral device?
Now provide the response and nothing else.
| Thanks everyone for the answers. Just to update, as of June 2014, it is offered in the Android L Developer preview. Hope to see it in the Android L official release. From their blog New in Android: L Developer Preview and Google Play Services 5.0 : The L Developer Preview, lets you explore many of the new features and capabilities of the next version of Android, and offers everything you need to get started developing and testing on the new platform. Here are a few of the highlights for developers: BLE Peripheral Mode β Android devices can now function in Bluetooth Low Energy (BLE) peripheral mode. Apps can use this capability to broadcast their presence to nearby devices β for example, you can now build apps that let a device to function as a pedometer or health monitor and transmit data to another BLE device. Update: The bad news is that BLE Peripheral mode will only work on the newer Android devices (as per the date), viz Nexus 6 and Nexus 9. It won't work on Nexus 4/ Nexus 5/nexus 7/ nexus 10 even if you update it to Android 5.0. You can read the comment by one of the Android Project manager on BLE advertise mode not working ticket. He says: We introduced BLE peripheral mode in Android 5.0 Lollipop. Nexus 6 and Nexus 9 are the first two production Nexus devices that support BLE peripheral mode. Due to hardware chipset dependency, older Nexus devices (4/5/7) will not have access to the feature on Lollipop. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19717902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306419/']} | jdg_381997 |
stackexchange | llm_judgeable_groundtruth_similarity | 465522 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
instead of doing session("myvar1") = something session("myvar2") = something session("myvar3") = something session("myvar4") = something is doing enum sessionVar myvar1 myvar2 myvar3 myvar4end enum session(sessionVar.myvar1.tostring) = something session(sessionVar.myvar2.tostring) = something session(sessionVar.myvar3.tostring) = something session(sessionVar.myvar4.tostring) = something would be better?
Now provide the response and nothing else.
| Instead of using constants for the session keys, I'm using my own type-safe session object, which looks like this (sorry this is in C#, see below for a VB version): public class MySession{ // Private constructor (use MySession.Current to access the current instance). private MySession() {} // Gets the current session. public static MySession Current { get { MySession session = HttpContext.Current.Session["__MySession__"] as MySession; if (session == null) { session = new MySession(); HttpContext.Current.Session["__MySession__"] = session; } return session; } } // My session data goes here: public string MyString { get; set; }; public bool MyFlag { get; set; }; public int MyNumber { get; set; };} Whenever I need to read/write something to/from the session, I can use my typesafe session object like this: string s = MySession.Current.MyString;s = "new value";MySession.Current.MyString = s; This solution results in several advantages: I have a typesafe Session (no more type-casts) I can document all session based data (by commenting the public properties in MySession) When adding a new element to the session, I don't have to search the solution to check if the same session-key was already used somewhere else. Update: Here's a VB version (automatically converted from the C# version). Sorry, but I don't know VB and so I didn't know how to write the properties in VB: Public Class MySession ' Private constructor (use MySession.Current to access the current instance). Private Sub New() End Sub ' Gets the current session. Public Shared ReadOnly Property Current() As MySession Get Dim session As MySession = TryCast(HttpContext.Current.Session("__MySession__"), MySession) If session = Nothing Then session = New MySession() HttpContext.Current.Session("__MySession__") = session End If Return session End Get End Property ' My session data goes here: Public MyString As String Public MyFlag As Boolean Public MyNumber As IntegerEnd Class | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/465522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40868/']} | jdg_381998 |
stackexchange | llm_judgeable_groundtruth_similarity | 47222685 |
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 am running ng build -prod I am getting the following warning. Warning: Can't resolve all parameters for UsersPermissionsService in C:/SourceControl/Test.Client/src/app/shared/users/users-permissions.service.ts: (?, ?, ?). This will become an error in Angular v5.xWarning: Can't resolve all parameters for UsersPermissionsService in C:/SourceControl/Test.Client/src/app/shared/users/users-permissions.service.ts: (?, ?, ?). This will become an error in Angular v5.x My code is the following: import { Injectable } from '@angular/core';@Injectable()export class UsersPermissionsService { public USERS_CREATE_PERMISSION: string = ''; public USERS_UPDATE_PERMISSION: string = ''; public USERS_DELETE_PERMISSION: string = ''; constructor(public UsersCreatePermission: string, public UsersUpdatePermission: string, public UsersDeletePermission: string) { this.USERS_CREATE_PERMISSION = UsersCreatePermission; this.USERS_UPDATE_PERMISSION = UsersUpdatePermission; this.USERS_DELETE_PERMISSION = UsersDeletePermission; }}@Injectable()export class UserModulePermissionsService extends UserPermissionsService { constructor() { super("ClientsCreate", "ClientsEdit", "ClientsDelete"); }}@Component({ templateUrl: './users-permissions.component.html', providers: [UsersPermissionsService]})export class UsersPermissionsComponent { constructor(public usersPermissionsService: UsersPermissionsService) { }} and in my lazy loaded module I have: providers: [ { provide: UsersPermissionsService, useClass: UserModulePermissionsService } ] Now that angular 5 is out I will need to update and as the message says this warning will become an error. Don't understand what is really the problem here.
Now provide the response and nothing else.
| Remove the @Injectable decorator from the base class. You should only include that decorator (or any decorator for that matter) on classes that Angular should instantiate directly (and while doing that also resolve their constructor parameters using the injector). Since it is obvious that in your case the base class is not to be instantiated by angular directly (it has constructor parameters which are not known by the injector), you should remove the decorators from it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47222685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1173307/']} | jdg_381999 |
stackexchange | llm_judgeable_groundtruth_similarity | 11127356 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to define a constraint between two nullable FK's in a table where if one is null the other needs a value, but both can't be null and both can't have values. Logic is the derived table inherits data from the either of the FK tables to determine its type. Also, for fun bonus points, is this a bad idea?
Now provide the response and nothing else.
| One way to achieve it is to simply write down what "exclusive OR" actually means: CHECK ( (FK1 IS NOT NULL AND FK2 IS NULL) OR (FK1 IS NULL AND FK2 IS NOT NULL)) However, if you have many FKs, the above method can quickly become unwieldy, in which case you can do something like this: CHECK ( 1 = ( (CASE WHEN FK1 IS NULL THEN 0 ELSE 1 END) + (CASE WHEN FK2 IS NULL THEN 0 ELSE 1 END) + (CASE WHEN FK3 IS NULL THEN 0 ELSE 1 END) + (CASE WHEN FK4 IS NULL THEN 0 ELSE 1 END) ... )) BTW, there are legitimate uses for that pattern, for example this one (albeit not applicable to MS SQL Server due to the lack of deferred constraints). Whether it is legitimate in your particular case, I can't judge based on the information you provided so far. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11127356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/554462/']} | jdg_382000 |
stackexchange | llm_judgeable_groundtruth_similarity | 69570 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to solve a discontinuous equation which is typical in theory of plasticity. For a simple case I get the following equation system (reformulated for numerical implementation): $$\begin{align*}s(t) &= \frac{\sigma(t)}{C_1} + s_{ep}\\s_{ep}'(t) &= \begin{cases}\frac{C_1}{C_1+C_2}s'(t) & \text{for } |\sigma(t)-C_2 s_{ep}(t)| \ge \sigma_{gr} \land \sigma(t)s'(t)>0\\0 & \text{otherwise}\end{cases}\end{align*}$$ with "zero" initial conditions. I'd like to get the solution for $s(t)$ for given parameters $C_1$ , $C_2$ , $\sigma_{gr}$ and a known function $\sigma(t)$ . I assumed: $\sigma(t) = 40000\sin(0.02t)$ , $C_1=80000$ , $C_2 = 20000$ , $\sigma_{gr} = 15000$ . This should give a hysteresis loop on a plane $\sigma(t)-s(t)$ . So in Mathematica I tried to use automatic discontinuity handling by defining the second equation using a Piecewise function: Ο[t_] := 40000*Sin[0.02*t];eq1 = s[t] == Ο[t]/C1 + sep[t];eq2 = sep'[t] == Piecewise[{{C1/(C1 + C2)*s'[t], (Ο[t]*s'[t] > 0) && ((Ο[t] - C2*sep[t] >= Οgr) || (Ο[t] - C2*sep[t]<=-Οgr))}}, 0];eqSys := {eq1, eq2, s[0] == 0, sep[0] == 0};ndsolve=NDSolve[eqSys, {s[t], sep[t]}, {t, 0, 1000}]disp[t_] := Evaluate[s[t] /. ndsolve];sTab = Table[disp[t][[1]], {t, 0, 1000, 1}];ΟTab = Table[Ο[t], {t, 0, 1000, 1}];ListPlot[Transpose[{sTab, ΟTab}], PlotRange -> All, GridLines -> Automatic] Unfortunately I get: NDSolve::tddisc: NDSolve cannot do a discontinuity replacement for event surfaces that depend only on time. >> and the results are incomplete or the algorithm crashes. I also tried using WhenEvent with "DiscontinuitySignature" but with no success. This approach gives good results only for a linear monotonic function of $\sigma$ , e.g. $\sigma(t) = 50t$ . I wrote a module to solve this using a simple first order Runge-Kutta so I obtained the solution but this is only a simple model. I'm sure Mathematica can solve this with its build-in methods. That would really save me a lot of work writing my own procedures.
Now provide the response and nothing else.
| Edit: Using a helper function fh will result in no messages and no need to set extra options. Ο[t_] := 40000 Sin[0.02 t]C1 = 80000;C2 = 20000;Οgr = 15000;fh[t_?NumericQ, x_, y_] := Piecewise[{{C1/(C1 + C2)*y, (Ο[t]*y > 0) && ((Ο[t] - C2*x >= Οgr) || (Ο[t] - C2*x <= -Οgr))}}, 0]sol = NDSolve[{s[t] == Ο[t]/C1 + sep[t], sep'[t] == fh[t, sep[t], s'[t]], s[0] == 0, sep[0] == 0}, {s[t], sep[t]}, {t, 0, 1000}];s[t_] = s[t] /. sol // First;ParametricPlot[{s[t], Ο[t]}, {t, 0, 10^3}, PlotRange -> All, AspectRatio -> Full, GridLines -> Automatic] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/69570', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/23338/']} | jdg_382001 |
stackexchange | llm_judgeable_groundtruth_similarity | 4544234 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I read somewhere that we should lock the mutex before calling pthread_cond_signal and unlock the mutex after calling it: The pthread_cond_signal() routine isused to signal (or wake up) anotherthread which is waiting on thecondition variable. It should becalled after mutex is locked, and mustunlock mutex in order forpthread_cond_wait() routine tocomplete. My question is: isn't it OK to call pthread_cond_signal or pthread_cond_broadcast methods without locking the mutex?
Now provide the response and nothing else.
| If you do not lock the mutex in the codepath that changes the condition and signals, you can lose wakeups. Consider this pair of processes: Process A: pthread_mutex_lock(&mutex);while (condition == FALSE) pthread_cond_wait(&cond, &mutex);pthread_mutex_unlock(&mutex); Process B (incorrect): condition = TRUE;pthread_cond_signal(&cond); Then consider this possible interleaving of instructions, where condition starts out as FALSE : Process A Process Bpthread_mutex_lock(&mutex);while (condition == FALSE) condition = TRUE; pthread_cond_signal(&cond);pthread_cond_wait(&cond, &mutex); The condition is now TRUE , but Process A is stuck waiting on the condition variable - it missed the wakeup signal. If we alter Process B to lock the mutex: Process B (correct): pthread_mutex_lock(&mutex);condition = TRUE;pthread_cond_signal(&cond);pthread_mutex_unlock(&mutex); ...then the above cannot occur; the wakeup will never be missed. (Note that you can actually move the pthread_cond_signal() itself after the pthread_mutex_unlock() , but this can result in less optimal scheduling of threads, and you've necessarily locked the mutex already in this code path due to changing the condition itself). | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4544234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69537/']} | jdg_382002 |
stackexchange | llm_judgeable_groundtruth_similarity | 10304863 |
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 custom complex type that I want to work with using Web API. public class Widget{ public int ID { get; set; } public string Name { get; set; } public decimal Price { get; set; }} And here is my web API controller method. I want to post this object like so: public class TestController : ApiController{ // POST /api/test public HttpResponseMessage<Widget> Post(Widget widget) { widget.ID = 1; // hardcoded for now. TODO: Save to db and return newly created ID var response = new HttpResponseMessage<Widget>(widget, HttpStatusCode.Created); response.Headers.Location = new Uri(Request.RequestUri, "/api/test/" + widget.ID.ToString()); return response; }} And now I'd like to use System.Net.HttpClient to make the call to the method. However, I'm unsure of what type of object to pass into the PostAsync method, and how to construct it. Here is some sample client code. var client = new HttpClient();HttpContent content = new StringContent("???"); // how do I construct the Widget to post?client.PostAsync("http://localhost:44268/api/test", content).ContinueWith( (postTask) => { postTask.Result.EnsureSuccessStatusCode(); }); How do I create the HttpContent object in a way that web API will understand it?
Now provide the response and nothing else.
| The generic HttpRequestMessage<T> has been removed . This : new HttpRequestMessage<Widget>(widget) will no longer work . Instead, from this post , the ASP.NET team has included some new calls to support this functionality: HttpClient.PostAsJsonAsync<T>(T value) sends βapplication/jsonβHttpClient.PostAsXmlAsync<T>(T value) sends βapplication/xmlβ So, the new code ( from dunston ) becomes: Widget widget = new Widget()widget.Name = "test"widget.Price = 1;HttpClient client = new HttpClient();client.BaseAddress = new Uri("http://localhost:44268");client.PostAsJsonAsync("api/test", widget) .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() ); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10304863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/925719/']} | jdg_382003 |
stackexchange | llm_judgeable_groundtruth_similarity | 61004 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to create a tar file with contents belonging to an owner:group pair who do not exist on the system from which the file is being made. Here's the direction I've tried: tar ca --owner='otherowner' --group='othergroup' mydata.tgz mydata And when running this command, I get the following error: tar: otherowner: Invalid ownertar: Error is not recoverable: exiting now Is there a way to force tar to accept the owner:group, even though neither of them exist on the system from which the file is being created?
Now provide the response and nothing else.
| Linux doesn't use internally owners and groups names but numbers - UIDs and GIDs. Users and groups names are mapped from contents of /etc/passwd and /etc/group files for convenience of user. Since you don't have 'otherowner' entry in any of those files, Linux doesn't actually know which UID and GID should be assigned to a file. Let's try to pass a number instead: $ tar cf archive.tar test.c --owner=0 --group=0$ tar -tvf archive.tar -rw-rw-r-- root/root 45 2013-01-10 15:06 test.c$ tar cf archive.tar test.c --owner=543543 --group=543543$ tar -tvf archive.tar -rw-rw-r-- 543543/543543 45 2013-01-10 15:06 test.c It seems to work. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/61004', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/30162/']} | jdg_382004 |
stackexchange | llm_judgeable_groundtruth_similarity | 1054086 |
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 found the answer to these questions but I want someone could give explaination $100$ tickets numbered $1,2,3...,100$ are sold to $100$ different people for a drawing. Four different prizes are awarded, including a grand prize (trip to Tahiti). How many ways are there to award the prizes if: a) There are no restrictions? Answer: $94109400$ b) The person holding ticket 47 wins the grand prize? Answer: $941094$ c) The person holding ticket 47 wins one of the prizes? Answer: $3764376$ d) The person holding ticket 47 does not win a prize? Answer: $90345024$ e) The person holding ticket 19 and 47 both wins prize? Answer: $114072$
Now provide the response and nothing else.
| a) If $k$ different prizes are there for $n$ people and no person can get more than one prize then there are: $$n\times(n-1)\times\cdots\times(n-k+1)$$ ways if there are no restrictions. Do you understand why? See the answer of @ndruiven. This leads to $100\times99\times98\times97=94109400$ ways in your case where $n=100$ and $k=4$. b) After handing out the grand prize there are $k=3$ different prizes left for $n=99$ persons. Apply the formula. c) $4$ times case b) since there are $4$ possibilities when it comes to the prizes that can be won by person $47$. d) $k=4$ and $n=99$. Person $47$ is left out. e) First hand out a prize to $47$. There are $4$ possibilities. Then hand out a prize to $19$. There are $3$ possibilities. Then the other prizes are handed out: $k=2$ and $n=98$. Finally you come to $4\times3\times98\times97=114072$ possibilities. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1054086', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/197769/']} | jdg_382005 |
stackexchange | llm_judgeable_groundtruth_similarity | 44540391 |
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 code generates error: Uncaught TypeError: Cannot set property '0' of undefined While I want to assign random numbers in array, please help. var array;for (var i = 1; i < 10; i++) { array[i] = Math.floor(Math.random() * 7);}console.log(array);
Now provide the response and nothing else.
| You are missing the array initialization: var array = []; Taking this into your example, you would have: var array = []; //<-- initialization herefor(var i = 1; i<10;i++) { array[i]= Math.floor(Math.random() * 7);}console.log(array); Also you should starting assigning values from index 0 . As you can see in the log all unassigned values get undefined , which applies to your index 0 . So a better solution would be to start at 0 , and adjust the end of for to <9 , so that it creates the same number of elements: var array = [];for(var i = 0; i<9;i++) { array[i]= Math.floor(Math.random() * 7);}console.log(array); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44540391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7686708/']} | jdg_382006 |
stackexchange | llm_judgeable_groundtruth_similarity | 350027 |
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 set a WPF image's source in code. The image is embedded as a resource in the project. By looking at examples I've come up with the below code. For some reason it doesn't work - the image does not show up. By debugging I can see that the stream contains the image data. So what's wrong? Assembly asm = Assembly.GetExecutingAssembly();Stream iconStream = asm.GetManifestResourceStream("SomeImage.png");PngBitmapDecoder iconDecoder = new PngBitmapDecoder(iconStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);ImageSource iconSource = iconDecoder.Frames[0];_icon.Source = iconSource; The icon is defined something like this: <Image x:Name="_icon" Width="16" Height="16" />
Now provide the response and nothing else.
| After having the same problem as you and doing some reading, I discovered the solution - Pack URIs . I did the following in code: Image finalImage = new Image();finalImage.Width = 80;...BitmapImage logo = new BitmapImage();logo.BeginInit();logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");logo.EndInit();...finalImage.Source = logo; Or shorter, by using another BitmapImage constructor: finalImage.Source = new BitmapImage( new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png")); The URI is broken out into parts: Authority: application:/// Path: The name of a resource file that is compiled into a referenced assembly. The path must conform to the following format: AssemblyShortName[;Version][;PublicKey];component/Path AssemblyShortName: the short name for the referenced assembly. ;Version [optional]: the version of the referenced assembly that contains the resource file. This is used when two or more referenced assemblies with the same short name are loaded. ;PublicKey [optional]: the public key that was used to sign the referenced assembly. This is used when two or more referenced assemblies with the same short name are loaded. ;component: specifies that the assembly being referred to is referenced from the local assembly. /Path: the name of the resource file, including its path, relative to the root of the referenced assembly's project folder. The three slashes after application: have to be replaced with commas: Note: The authority component of a pack URI is an embedded URI that points to a package and must conform to RFC 2396. Additionally, the "/" character must be replaced with the "," character, and reserved characters such as "%" and "?" must be escaped. See the OPC for details. And of course, make sure you set the build action on your image to Resource . | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/350027', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/22621/']} | jdg_382007 |
stackexchange | llm_judgeable_groundtruth_similarity | 16162474 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Recent Objective-C compilers introduce the 'instancetype' keyword, which among other things can be used to provide typed collections. . . I saw another purpose of instancetype, which was using it in 'objectWith' type methods on classes. For example: @interface Car +(instancetype)carWithWheels:(NSArray*)wheels;@end The justification was that the compiler will do type checking for initWith methods, but not for 'objectWith' methods. Besides being potentially easier to type, what is the benefit of using 'instancetype' in place of the actual class-name? Eg: @interface Car +(Car*)carWithWheels:(NSArray*)wheels;@end
Now provide the response and nothing else.
| By using instancetype , you're saying that subclasses will return an object of the subclass. If we have @interface Car +(instancetype)carWithWheels1:(NSArray *)wheels; +(Car *)carWithWheels2:(NSArray *)wheels;@end and @interface VolkswagenBeetle : Car@end then +[VolkswagenBeetle carWithWheels1:] is guaranteed to return an instance of VolkswagenBeetle ; but +[VolkswagenBeetle carWithWheels2:] might return a Buick , a Caddilac , or a ChittyChittyBangBang . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16162474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/404201/']} | jdg_382008 |
stackexchange | llm_judgeable_groundtruth_similarity | 86818 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $G$ be a finite simple graph and let $C(G)$ be the flag complex associated to $G$ (the set of vertices of $C(G)$ is the vertex set of $G$ and the set of all cliques of $G$ are its simplexes). Are there characterizations of contractibility of $C(G)$ ONLY in terms of the graph theoretical properties of $G$?
Now provide the response and nothing else.
| It is known that every induced subcomplex of the flag complex of a graph is contractible iff the graph is chordal (no induced cycles of length 4 or more). I doubt a necessary and sufficient condition that is purely graph theoretic for contractibility of just the flag complex is possible because the barycentric subdivision of any simplicial complex is a flag complex. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/86818', 'https://mathoverflow.net', 'https://mathoverflow.net/users/19075/']} | jdg_382009 |
stackexchange | llm_judgeable_groundtruth_similarity | 8367001 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was writing some code and it kept crashing. Later after digging the dumps I realized I was overshooting the maximum heap limit (life would have been easier if I had added a check on malloc). Although I fixed that, is there any way to increase my heap size? PS: A quite similar question here but the reply is unclear to me.
Now provide the response and nothing else.
| The heap usually is as large as the addressable virtual memory on your architecture. You should check your systems current limits with the ulimit -a command and seek this line max memory size (kbytes, -m) 3008828 , this line on my OpenSuse 11.4 x86_64 with ~3.5 GiB of ram says I have roughly 3GB of ram per process. Then you can truly test your system using this simple program to check max usable memory per process: #include <stdio.h>#include <stdlib.h>#include <string.h>int main(int argc,char* argv[]){ size_t oneHundredMiB=100*1048576; size_t maxMemMiB=0; void *memPointer = NULL; do{ if(memPointer != NULL){ printf("Max Tested Memory = %zi\n",maxMemMiB); memset(memPointer,0,maxMemMiB); free(memPointer); } maxMemMiB+=oneHundredMiB; memPointer=malloc(maxMemMiB); }while(memPointer != NULL); printf("Max Usable Memory aprox = %zi\n",maxMemMiB-oneHundredMiB); return 0;} This programs gets memory on 100MiB increments, presents the currently allocated memory, allocates 0's on it,then frees the memory. When the system can't give more memory, returns NULL and it displays the final max usable amount of ram. The Caveat is that your system will start to heavily swap memory in the final stages. Depending on your system configuration, the kernel might decide to kill some processes. I use a 100 MiB increments so there is some breathing space for some apps and the system. You should close anything that you don't want crashing. That being said. In my system where I'm writing this nothing crashed. And the program above reports barely the same as ulimit -a . The difference is that it actually tested the memory and by means of memset() confirmed the memory was given and used. For comparison on a Ubuntu 10.04x86 VM with 256 MiB of ram and 400MiB of swap the ulimit report was memory size (kbytes, -m) unlimited and my little program reported 524.288.000 bytes, which is roughly the combined ram and swap, discounting ram used by others software and the kernel. Edit: As Adam Zalcman wrote, ulimit -m is no longer honored on newer 2.6 and up linux kernels, so i stand corrected. But ulimit -v is honored. For practical results you should replace -m with -v, and look for virtual memory (kbytes, -v) 4515440 . It seems mere chance that my suse box had the -m value coinciding with what my little utility reported. You should remember that this is virtual memory assigned by the kernel, if physical ram is insufficient it will take swap space to make up for it. If you want to know how much physical ram is available without disturbing any process or the system, you can use long total_available_ram =sysconf(_SC_AVPHYS_PAGES) * sysconf(_SC_PAGESIZE) ; this will exclude cache and buffer memory, so this number can be far smaller than the actual available memory. OS caches can be quiet large and their eviction can give the needed extra memory, but that is handled by the kernel. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8367001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1043773/']} | jdg_382010 |
stackexchange | llm_judgeable_groundtruth_similarity | 21404879 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried to convert QByteArray to std::vector<unsigned char> using this code: unsigned char* buffer = (unsigned char*)byteArrayBuffer.constData();std::vector<unsigned char>::size_type size = strlen((const char*)buffer);std::vector<unsigned char> bufferToCompress(buffer, buffer + size); but, assuming that byteArrayBuffer is a QByteArray filled with data, I think it doesn't work well on line unsigned char* buffer = (unsigned char*)byteArrayBuffer.constData(); because byteArrayBuffer.size() returns a different value than bufferToCompress.size() . How can I get it working?
Now provide the response and nothing else.
| I'm not familiar with Qt, but surely you just want std::vector<unsigned char> bufferToCompress( byteArrayBuffer.begin(), byteArrayBuffer.end()); Note: strlen is not particularly useful in C++; it tells you the length of a C-style null-terminated string (by searching memory until it either finds either finds a zero-valued byte, or falls off the end of accessible memory and crashes), but can't tell you the size of an array, which is what you'd need here. Also, using evil C-style casts to force invalid code to compile is never a good idea. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21404879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1007758/']} | jdg_382011 |
stackexchange | llm_judgeable_groundtruth_similarity | 913627 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Being new to Cocoa, I'm having a few issues with Interface Builder , UIViewController and friends. I have a UIViewController subclass with a UIView defined in a xib, and with the controller's view outlet connected to the view. The xib's "file's owner" is set as myViewcontroller subclass. In this one instance, the following code to load the controller/view (from the main view controller) doesn't work as expected: if ( self.myViewController == nil ){ self.myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];}[self.navigationController pushViewController:self.myViewController animated:YES]; In MyViewController's methods, I have placed breakpoints and log messages to see what is going on: -(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { NSLog(@"initWithNibName\n"); } return self;}-(void)viewDidLoad { [super viewDidLoad]; NSLog(@"viewDidLoad\n");} Expected result Both -initWithNibName and -viewDidLoad methods are called, and myViewController's view is displayed. Observed result Only -initWithNibName is called, the view is not displayed. Have I missed something? Can anyone recommend anything to check? (Particularly in the wondrously opaque Interface Builder tool).
Now provide the response and nothing else.
| Ok, I have a partial answer - maybe the gurus can explain some more. The problem is: [self.navigationController pushViewController:myViewController animated:YES]; Looking more closely, in this case self.navigationController is nil - so the push message is going no-where. Instead, if I send: [self.view addSubview:self.myViewController.view]; Then the view appears and -viewDidLoad is called. I'm not entirely sure why self.navigationController is not set in this instance - the only thing I can think of is that self is a subclass of UIViewController rather than UITableViewController (where the pushViewController code came from). Also, silently allowing messages to go to nil seems like a bad idea, although these answers say otherwise. See also my question here . Final edit: Answers in comments below, I've realised the display function that I was actually after (given myViewController is modal) is: [self presentModalViewController:myViewController animated:YES]; Thanks everyone for their helpful responses. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/913627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/94239/']} | jdg_382012 |
stackexchange | llm_judgeable_groundtruth_similarity | 40107 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In this article in the Guardian , Rachel Roberts claims that: "Five major systematic reviews have also been carried out to analysethe balance of evidence from RCTs [randomized controlled trials] ofhomeopathy β four were positive ( Kleijnen, J, et al ; Linde, K,et al ; Linde, K, et al ; Cucherat, M, et al ) and one wasnegative ( Shang, A et al )." Is this claim true? And if so, is it representative? I am aware of the risk of cherry-picking trials to support one's hypothesis, but I would expect that systematic reviews would remove this selection bias. To be clear, I'm not interested in whether there is a scientific basis for homeopathy (since the author of the article does not argue that there is one, apart from anything else).
Now provide the response and nothing else.
| This statement is only true if you heavily distort the meaning of the word "positive". The following are quotes from the abstract of all four meta-analyses the article claimed are positive: At the moment the evidence of clinical trials is positive but not sufficient to draw definitive conclusions because most trials are of low methodological quality and because of the unknown role of publication bias. This indicates that there is a legitimate case for further evaluation of homoeopathy, but only by means of well performed trials. We conclude that in the study set investigated, there was clear evidence that studies with better methodological quality tended to yield less positive results. There is some evidence that homeopathic treatments are more effective than placebo; however, the strength of this evidence is low because of the low methodological quality of the trials. Studies of high methodological quality were more likely to be negative than the lower quality studies. Further high quality studies are needed to confirm these results. the results of our meta-analysis are not compatible with the hypothesis that the clinical effects of homeopathy are completely due to placebo. However, we found insufficient evidence from these studies that homeopathy is clearly efficacious for any single clinical condition. Further research on homeopathy is warranted provided it is rigorous and systematic. One of these didn't actually address the question whether homeopathy works or not, they examined the influence of study design and came to the conclusion that better studies tend to show more negative results on homeopathy. All other three essentially said that their results are not conclusive and that more research is necessary. They all state that the quality of the studies they're based on is often low, and that this affects their conclusion. It's very misleading at least to claim that these meta-analyses support homeopathy. | {} | {'log_upvote_score': 8, 'links': ['https://skeptics.stackexchange.com/questions/40107', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/39940/']} | jdg_382013 |
stackexchange | llm_judgeable_groundtruth_similarity | 39359504 |
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 Bigquery: How do we format a number that will be part of the resultset to have it formatted with commas: like 1000000 to 1,000,000 ?
Now provide the response and nothing else.
| below is for Standard SQL SELECT input, FORMAT("%'d", input) as formattedFROM ( SELECT 123 AS input UNION ALL SELECT 1234 AS input UNION ALL SELECT 12345 AS input UNION ALL SELECT 123456 AS input UNION ALL SELECT 1234567 AS input UNION ALL SELECT 12345678 AS input UNION ALL SELECT 123456789 AS input) Works great for integers, but if you will need floats too, you can use : SELECT input, CONCAT(FORMAT("%'d", CAST(input AS int64)), SUBSTR(FORMAT("%.2f", CAST(input AS float64)), -3)) as formattedFROM ( SELECT 123 AS input UNION ALL SELECT 1234 AS input UNION ALL SELECT 12345 AS input UNION ALL SELECT 123456.1 AS input UNION ALL SELECT 1234567.12 AS input UNION ALL SELECT 12345678.123 AS input UNION ALL SELECT 123456789.1234 AS input) added for Legacy SQL Btw, if for whatever reason you are bound to Legacy SQL - below is quick example for it SELECT input, formattedFROM JS(( SELECT input FROM (SELECT 123 AS input ), (SELECT 1234 AS input ), (SELECT 12345 AS input ), (SELECT 123456 AS input ), (SELECT 1234567 AS input ), (SELECT 12345678 AS input ), (SELECT 123456789 AS input) ), // input input, // output "[ {name: 'input', type:'integer'}, {name: 'formatted', type:'string'} ]", // function "function (r, emit) { emit({ input: r.input, formatted: r.input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') }); }") Above example uses in-line versin of Legacy SQL User-Defined Functions which is usually used for quick demo/example - but not recommended in production - if you will find it useful for you - you will need to "very slightly" transform it - see https://cloud.google.com/bigquery/user-defined-functions#webui for example | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39359504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4534467/']} | jdg_382014 |
stackexchange | llm_judgeable_groundtruth_similarity | 46775155 |
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 run classifier.py in the openface demos directory using: classifier.py train ./generated-embeddings/ I get the following error message: --> from sklearn.lda import LDA ModuleNotFoundError: No module named 'sklearn.lda'. I think to have correctly installed sklearn. What could be the reason for this message?
Now provide the response and nothing else.
| It seems that you have installed a newer version of sklearn but you are trying to call an old one . 1) First check your version import sklearnsklearn.__version__ 2) Then use something like the following depending on the version that you have installed from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA Documentation here: http://scikit-learn.org/stable/modules/generated/sklearn.discriminant_analysis.LinearDiscriminantAnalysis.html | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46775155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4576360/']} | jdg_382015 |
stackexchange | llm_judgeable_groundtruth_similarity | 49219 |
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:
Ill try to make it as clear as possible. This may seem like a simple question, but it is something that I havent quite figured out. It has to do with polarity on the leads of an AC source. Every book I read, pictures an AC source with two leads such as this: Now, on the books, I see that the + symbol is used on upper lead, and the - at the bottom when they are picturing the positive half of the waveform, and they use a - symbol on the top and + on the bottom when they are picturing the negative half of the waveform. So far so good. Here are the 3 scenarios and the thing that really confuses me: Is only one lead changing voltage while the other stays stationary at 0V, meaning that the upper lead will go from + to - and from - to + and so on while the lower lead stays at 0v? Or For the positive part of the waveform the upper terminal will be + and the lower 0V, and for the negative part of the waveform the lower terminal will be - and the upper 0v? Or The upper terminal will have an alternating current and the lower terminal will have a mirror signal with opposite polarity? in which case, where is my 0v reference? Comparing it to the AC wiring on any house, theres 1 cable which is "Hot" and the other which is the "neutral", I know the neutral doesnt carry any voltage and its the 0v reference, so the HOT cable is the one which changes its polarity. Now, what exactly happens when I ground something? for example what is the difference of having that 0v floating or connected to ground, and what happens when I ground a circuit at something else rather than 0v? For instance say I have the following circuit: An ac source feeding a transformer, there are a couple of resistors across its secondaries and the mid point between the resistors is connected to ground. So let say that the transformer has a 1:1 ratio and both resistors have the same resistance, 100ohms for this example, that means they will form a voltage divider of half the total voltage. I know all that because thats how they thaught it to me, what I dont know is this, if ground potential is 0V, and my transformer's (bottom lead) is at 0v, why will I get a voltage at point B with respect to ground? I get very confused between the diference of 0v and ground reference, and when I see circuits like the previous one which are grounded at some place different from 0V, specially on AC circuits. On DC it makes sense, if I ground the negative side or 0V side, I will have a positive voltage, if I ground the positive, I will get a negative voltage. But on AC it confuses me the fact that I dont know if the only alternating current is on one side of the terminals or if the 2 terminals are switching between each other. It seems like on some cases its only one side (like in a house electrical installation) and on others like in a balanced push pull circuit its both sides. It seems I dont have a clue of how exactly AC works.
Now provide the response and nothing else.
| The key is to realize that there is no such thing as 0 volts in an absolute sense. Voltage is a measurement of difference in potential between two points. You can say that something is 0V with respect to something else, but you can't say that a conductor is at 0V without including a reference. Consider a bird sitting on a high voltage power line. The power line and bird are both at 13,800V relative to the ground, but the bird is at 0V relative to the wire. To answer your question about AC, the AC source provides a potential difference (voltage) between the two conductors. It alternates in the sense that sometimes the first conductor is at the higher potential, and sometimes the second conductor is at the higher potential. "Higher potential" is an absolute concept; current will always flow from the higher potential to the lower potential if you were to connect them with a wire. For a floating AC source like you've depicted (or a transformer), there's simply no concept of 0V until you define one. And you can define that any way you want: call the bottom terminal 0V, then you're in your first scenario. Or call whichever terminal has the lower potential at any instant 0V, and you're in your second scenario. Or define 0V as the "midpoint" when the top and bottom are at the same potential, and now you're in your third scenario. When you use words like "stationary" you need to define what they're in reference to. Certainly the hot line does not stay "stationary" with respect to the neutral line, nor vice versa. In practice, it's common to use the earth ground as the reference point. In a house, it's common to physically connect neutral to the earth ground. Then, it's generally the case (modulo effects like resistance in wires) that the neutral will be at a potential of 0V relative to earth ground. It sounds like you understand the concept of a floating DC supply , where there is no intrinsic reference to ground and you can choose to connect ground to either terminal. Extending this understanding to AC should be straightforward: consider that an AC supply is just like a DC supply where someone's constantly adjusting the knob, except that you can also bring the voltage negative (e.g. bring the black terminal to a higher potential than the red terminal). | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/49219', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/11271/']} | jdg_382016 |
stackexchange | llm_judgeable_groundtruth_similarity | 18097756 |
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 fastest way to add a new item to an existing array? Dim arr As Integer() = {1, 2, 3}Dim newItem As Integer = 4 (I already know that when working with dynamic list of items you should rather use a List , ArrayList or similar IEnumerables . But what to do if you're stuck to legacy code that uses arrays?) What I've tried so far: ' A) converting to List, add item and convert backDim list As List(Of Integer)(arr)list.Add(newItem)arr = list.ToArray()' --> duration for adding 100.000 items: 33270 msec' B) redim array and add itemReDim Preserve arr(arr.Length)arr(arr.Length - 1) = newItem' --> duration for adding 100.000 items: 9237 msec' C) using Array.ResizeArray.Resize(arr, arr.Length + 1)arr(arr.Length - 1) = newItem' --> duration for adding 100.000 items: 1 msec' --> duration for adding 100.000.000 items: 1168 msec A) seems very slow since every time an item is added two conversions of the whole array are done. B) seems faster but still the array is copied once during the ReDim Preserve . C) seems to be the fastest at this point. Is there anything better?
Now provide the response and nothing else.
| Case C) is the fastest. Having this as an extension: Public Module MyExtensions <Extension()> _ Public Sub Add(Of T)(ByRef arr As T(), item As T) Array.Resize(arr, arr.Length + 1) arr(arr.Length - 1) = item End SubEnd Module Usage: Dim arr As Integer() = {1, 2, 3}Dim newItem As Integer = 4arr.Add(newItem)' --> duration for adding 100.000 items: 1 msec' --> duration for adding 100.000.000 items: 1168 msec | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18097756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1899323/']} | jdg_382017 |
stackexchange | llm_judgeable_groundtruth_similarity | 4297 |
Below is a question asked on the forum bioinformatics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Seurats ' documentation for FindClusters() function it is written that for around 3000 cells the resolution parameter should be from 0.6 and up to 1.2 . I am wondering then what should I use if I have 60 000 cells? How to determine that?
Now provide the response and nothing else.
| Assuming you have an informative selection of variable genes from which you have constructed a number of useful PCs, I'd run a number of iterations with FindClusters() as described in the other answer, then choose a level which overclusters the dataset (for example, clusters that are visibly separate on a t-SNE or other dimensionality reduction plot should definitely have their own number): seuratobject <- SetAllIdent(seuratobject, id='chosen.resolution') Then run: Seurat::BuildClusterTree()Seurat::FindAllMarkersNode() Assessing the cluster markers for each node will hopefully give you a good idea on which clusters should be combined. Then you can "combine" the clusters and re-label the cells using something like: library(plyr)cell.labels <- [email protected] <- mapvalues(cell.labels, from=0:16, # cluster numbers to=c('A', 'B', 'C', 'C', 'D', 'E', 'E', ... )) # etcseuratobject <- AddMetaData(seuratobject, cell.labels, 'Combined.clusters') The usefulness of the clustering will very much depend on the selection of variable genes, therefore, depending on the (diversity of the) dataset, you will want to experiment with selection parameters or subset the dataset and repeat the above procedure. | {} | {'log_upvote_score': 4, 'links': ['https://bioinformatics.stackexchange.com/questions/4297', 'https://bioinformatics.stackexchange.com', 'https://bioinformatics.stackexchange.com/users/2005/']} | jdg_382018 |
stackexchange | llm_judgeable_groundtruth_similarity | 51689653 |
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 smoothly scroll to an element without using jQuery β just pure javascript. I would like a generic function to be able to both scroll down and scroll up smoothly to a specific position in the document. I know I can use the following in jQuery: $('html, body').animate({ scrollTop: $('#myelementid').offset().top}, 500); How would I do it with just javascript? This is what I am trying to do: function scrollToHalf(){ //what do I do?}function scrollToSection(){ //What should I do here?} <input type="button" onClick="scrollToHalf()" value="Scroll To 50% of Page"> <br> <input type="button" onClick="scrollToSection()" value="Scroll To Section1"> <section style="margin-top: 1000px;" id="section1"> This is a section</section> In jquery I would do it like so: html, body{ height: 3000px;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input type="button" onClick="scrollToHalf()" value="Scroll To 50% of Page"><br><input type="button" onClick="scrollToSection()" value="Scroll To Section1"><section style="margin-top: 1000px;" id="section1"> This is a section</section><script>function scrollToHalf(){ var height = $('body').height(); $('html, body').animate({ scrollTop: height/2 }, 500);}function scrollToSection(){ $('html, body').animate({ scrollTop: $('#section1').offset().top }, 500);}</script> EDIT: I would also like to be able to smooth scroll to a certain position on the page EDIT: CSS solutions are also welcome (although I would prefer javascript solutions)
Now provide the response and nothing else.
| To scroll to a certain position in an exact amount of time, window.requestAnimationFrame can be put to use, calculating the appropriate current position each time. setTimeout can be used to a similar effect when requestAnimationFrame is not supported. /* @param pos: the y-position to scroll to (in pixels) @param time: the exact amount of time the scrolling will take (in milliseconds)*/function scrollToSmoothly(pos, time) { var currentPos = window.pageYOffset; var start = null; if(time == null) time = 500; pos = +pos, time = +time; window.requestAnimationFrame(function step(currentTime) { start = !start ? currentTime : start; var progress = currentTime - start; if (currentPos < pos) { window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos); } else { window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time)); } if (progress < time) { window.requestAnimationFrame(step); } else { window.scrollTo(0, pos); } });} Demo: /* @param time: the exact amount of time the scrolling will take (in milliseconds) @param pos: the y-position to scroll to (in pixels)*/function scrollToSmoothly(pos, time) { var currentPos = window.pageYOffset; var start = null; if(time == null) time = 500; pos = +pos, time = +time; window.requestAnimationFrame(function step(currentTime) { start = !start ? currentTime : start; var progress = currentTime - start; if (currentPos < pos) { window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos); } else { window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time)); } if (progress < time) { window.requestAnimationFrame(step); } else { window.scrollTo(0, pos); } });} <button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 300)">Scroll To Div (300ms)</button><button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 200)">Scroll To Div (200ms)</button><button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 100)">Scroll To Div (100ms)</button><button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 50)">Scroll To Div (50ms)</button><button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 1000)">Scroll To Div (1000ms)</button><div style="margin: 500px 0px;">DIV<p/><button onClick="scrollToSmoothly(0, 500)">Back To Top</button><button onClick="scrollToSmoothly(document.body.scrollHeight)">Scroll To Bottom</button></div><div style="margin: 500px 0px;"></div><button style="margin-top: 100px;" onClick="scrollToSmoothly(500, 3000)">Scroll To y-position 500px (3000ms)</button> For more complex cases, the SmoothScroll.js library can be used, which handles smooth scrolling both vertically and horizontally, scrolling inside other container elements, different easing behaviors, scrolling relatively from the current position, and more. var easings = document.getElementById("easings");for(var key in smoothScroll.easing){ if(smoothScroll.easing.hasOwnProperty(key)){ var option = document.createElement('option'); option.text = option.value = key; easings.add(option); }}document.getElementById('to-bottom').addEventListener('click', function(e){ smoothScroll({yPos: 'end', easing: easings.value, duration: 2000});});document.getElementById('to-top').addEventListener('click', function(e){ smoothScroll({yPos: 'start', easing: easings.value, duration: 2000});}); <script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/[email protected]/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script><!-- Taken from one of the library examples -->Easing: <select id="easings"></select><button id="to-bottom">Scroll To Bottom</button><br><button id="to-top" style="margin-top: 5000px;">Scroll To Top</button> Alternatively, you can pass an options object to window.scroll which scrolls to a specific x and y position and window.scrollBy which scrolls a certain amount from the current position: // Scroll to specific values// scrollTo is the samewindow.scroll({ top: 2500, left: 0, behavior: 'smooth' });// Scroll certain amounts from current position window.scrollBy({ top: 100, // could be negative value left: 0, behavior: 'smooth' }); Demo: <button onClick="scrollToDiv()">Scroll To Element</button><div style="margin: 500px 0px;">Div</div><script>function scrollToDiv(){var elem = document.querySelector("div");window.scroll({ top: elem.offsetTop, left: 0, behavior: 'smooth' });}</script> If you only need to scroll to an element, not a specific position in the document, you can use Element.scrollIntoView with behavior set to smooth . document.getElementById("elemID").scrollIntoView({ behavior: 'smooth' }); Demo: <button onClick="scrollToDiv()">Scroll To Element</button><div id="myDiv" style="margin: 500px 0px;">Div</div><script>function scrollToDiv(){ document.getElementById("myDiv").scrollIntoView({ behavior: 'smooth' });}</script> Modern browsers support the scroll-behavior CSS property , which can be used to make scrolling in the document smooth (without the need for JavaScript). Anchor tags can be used for this by giving the anchor tag a href of # plus the id of the element to scroll to). You can also set the scroll-behavior property for a specific container like a div to make its contents scroll smoothly. Demo: html, body{ scroll-behavior: smooth;}a, a:visited{ color: initial;} <a href="#elem">Scroll To Element</a><div id="elem" style="margin: 500px 0px;">Div</div> The CSS scroll-behavior property works with JavaScript as well when using window.scrollTo . Demo: html, body{ scroll-behavior: smooth;} <button onClick="scrollToDiv()">Scroll To Element</button><div style="margin: 500px 0px;">Div</div><script>function scrollToDiv(){ var elem = document.querySelector("div"); window.scrollTo(0, elem.offsetTop);}</script> To check if the scroll-behavior property is supported, you can check if it exists as a key in the style of the HTML element. var scrollBehaviorSupported = 'scroll-behavior' in document.documentElement.style;console.log('scroll-behavior supported:', scrollBehaviorSupported); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51689653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_382019 |
stackexchange | llm_judgeable_groundtruth_similarity | 45158095 |
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 Maven (Java) there is a possibility to build, for example, a webapp war with different "profiles", a "profile" indicating for example a URL of a web service to put in a configuration file.Thus the "test profile" will indicate a URL different from that of the "production profile". Is there something similar to profiles for ng build?
Now provide the response and nothing else.
| For Angular 6+ : Create a file for each profile inside environments folder: environments/environment.tsenvironments/environment.prod1.tsenvironments/environment.prod2.ts And inisde each file put the parameters of corresponding profile: export const environment = { production: true, serverUrl: "http://prod1.site.com"}; You can access the parameters iniside your component/service like this: import {environment} from '../../environments/environment';@Injectable()export class SomeService { SERVER_URL: string = environment.serverUrl; And add the new profiles environment inside angular.json under configurations : "configurations": { "prod1": { ... }, "prod2": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod2.ts" } ] }} And finally choose the profile when building the app: ng build --configuration = prod1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45158095', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999264/']} | jdg_382020 |
stackexchange | llm_judgeable_groundtruth_similarity | 447741 |
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:
Most papers define the learning as maximizing the expectation given some function. Is the expectation maximization applicable to most deep learning models in literature? Can learning be generalized to EM algorithm ? Most of the models can be treated as probability functions, but when is this not the case? Can we express every deep learning model as part of EM training algorithm?
Now provide the response and nothing else.
| (The original version of this post, the text of which I kept below the line for reference purposes, generated a lot of dispute and some back and forth which seems mostly to be around questions of interpretation and ambiguity, so I updated with a more direct answer) The OP seems to be asking: Are Deep Learning models a special case of the EM algorithm? No they aren't. Deep Learning models are general purpose function approximators, which can use different types of objective functions and training algorithms, whereas the EM algorithm is a very specific algorithm in terms of training approach and objective function. From this perspective, it is possible (although not very common) to use Deep Learning to emulate the EM algorithm. See this paper . Most of the (deep learning) models can be treated as probability functions, but when is this not the case? Probability distribution functions have to satisfy certain conditions such as summing up to one (the conditions are slightly different if you consider probability density functions). Deep Learning models can approximate functions in general - i.e. a larger class of functions than those that correspond to probability distributions and densities. When do they not correspond to probability densities and distributions? Any time the function they approximate doesn't satisfy the axioms of probability theory. For example a network whose output layer has $tanh$ activations can take negative values, and therefore doesn't satisfy the condition for being a probability distribution or density. There are three ways that a deep learning model can correspond to a probability distribution $P(x)$ : Use Deep Learning to learn a probability distribution directly. That is, have your neural network learn the shape of $y=P(x)$ . Here $P(x)$ satisfies the conditions for being a probability density or distribution. Have a Deep Learning model learn a general function $y=f(x)$ (that doesn't satisfy the conditions for being a probability distribution). After training the model, we then make assumptions about the probability distribution $P(y|x)$ , e.g. the errors are normally distributed, and then use simulations to sample from that distribution. See here for an example of how that can be done. Have a Deep Learning model learn a general function $y=f(x)$ (that doesn't satisfy the conditions for being a probability distribution) - and then interpret the output of the model as representing $P(y|x) = ~ \delta[y-f(x)]$ , with $\delta$ being the Dirac function . There are two issues with this last approach. There is some debate as to whether the Dirac Delta constitutes a valid distribution function. It is popular in the signal processing and physics communities, but not so much among the probability and statistics crowd. It also doesn't provide any useful information from a probability and statistics point of view, since it doesn't provide anyway of quantifying the uncertainty of the output, which defeats the purpose of using a probabilistic model in practice. Is the expectation maximization applicable to most deep learning models in literature? Not really. There are several key differences: Deep Learning models work by minimizing a loss function . Different loss functions are used for different problems, and then the training algorithm used focuses on the best way to minimize the particular loss function that is suitable for the problem at hand. The EM algorithm on the other hand, is about maximizing a likelihood function . The issue here isn't simply that we are maximizing instead of minimizing (both are optimization problems after all), but the fact that EM dictates a specific function to be optimized, whereas Deep Learning can use any loss function as long as it is compatible with the training method (which is usually some variant of Gradient Descent). EM estimates the parameters in a statistical method by maximizing the likelihood of those parameters. So we chose the model before hand (e.g. a Gaussian with mean $\mu$ and variance $\sigma^2$ ), and then we use EM to find the best values of those parameters (e.g. which values of $\mu$ and $\sigma^2$ best fit our data). Deep Learning models are non-parametric, they don't make any assumptions about the shape or distribution of the data. Instead they are universal approximators, which given enough neurons and layers, should be able to fit any function. Closely related to the previous point is the fact that Deep Learning models are just function approximators, that can approximate arbitrary functions without having to respect any of the constraints that are imposed on a probability distribution function. An MLE model, or even a non-parametric distribution estimator for that matter, will be bound by the laws of probability and the constraints imposed on probability distributions and densities. Now certain types of deep learning models can be considered equivalent to an MLE model, but what is really happening under the hood is that we specifically asking the neural network to learn a probability distribution as opposed to a more general arbitrary function by choosing certain activation functions and adding some constraints on the outputs of the network. All that means is that they are acting as MLE estimators, but not that they are special cases of the EM algorithm. Is the learning considered to be part of the EM algorithm? I would say that it is the other way around. It is possible that someone, somewhere, has come up with a Deep Learning model that is equivalent to the EM algorithm, but that would make the EM algorithm a special case of Deep Learning, not the other way around, since for this to work, you would have to use Deep Learning + additional constraints to make the model mimic EM. In response to the comments: "Minimizing and maximizing can be the same thing.": Agreed, they can be (almost) equivalent - which what I specified in my response - it is NOT about maximizing vs. minimizing, it is about having to use a specific objective function dictated by MLE, vs. being able to use just about any loss function compatible with backpropagation. "The loss function in this case is the expectation of E p_theta(x|z) where p_theta is the deep neural network model." - again this is possible, but as I point out later, this would make MLE a special case of Deep Learning, not the other way around. "Parameters in the case of the deep neural networks are the model weights. I don't think your explanation is correct" - the explanation is correct, but you are also correct that the word parametric is ambiguous , and is used in different ways in different sources. Model weights are parameters in the general sense, but in the strict sense of parametric vs. non-parametric models, they aren't the same as the parameters in a parametric model. In parametric model, the parameters have a meaning, they correspond to the mean, the variance, the seasonality in a time series, etc...whereas the parameters in a Deep Learning model don't having any meaning, they are jus the most convenient way for the network to store information. That is why neural networks are criticized for being black box - there is no established way of interpreting the meaning of the weights. Another way you can think of it is in terms of total parameters vs. number of effective parameters: In a truly parametric model that is estimated using EM, the number of fixed parameters is the same as the number of effective parameters. In a neural network, the number of effective parameters may change during training (by reducing weights to zero, or by using drop out, etc....), even if the total number of parameters is defined before hand and is fixed. Which brings us to the real difference between the two approaches: A fixed number of effective parameters means that the shape of the distribution or function is decided before hand, whereas changing effective parameters allows for models to approximate more general, and eventually arbitrary functions, per the universal approximation theorem. "DNN also try to learn the probability distribution of the data in order to make predictions." only if we configure and constrain them to learn probability distributions. But they can also learn other things besides probability distributions. To this how this is possible, you can simply specify a multi-class neural network, with 4 outputs, with sigmoid outputs instead of softmax outputs, and train it to learn cases where the output is [1, 1, 1, 1]. Since the sum of the outputs is > 1, this is not a probability distribution, but just an arbitrary mapping of the inputs to classes. More generally Neural Networks/Deep Learning models are just general purpose function approximators, which can be configured to the specific case of estimation probability distribution functions, but they are not limited to that case. In computer vision for example, the are often used as filters and segmentation devises, instead of as classifiers or distribution estimators. As Cagdas Ozgenc points out, just about any supervised learning problem or function approximation problem can be recast as an MLE. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/447741', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/212133/']} | jdg_382021 |
stackexchange | llm_judgeable_groundtruth_similarity | 1770670 |
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 adapting an application for touch screen interface and we want to use the tablet text input panel included in Windows Vista/7, specifically its keyboard. I want to show and hide it as appropriate for my app. Basically I want ShowKeyboard() and HideKeyboard() functions. What's the best way to control this? I looked at the ITextInputPanel API but I was unable to control the keyboard directly with it (maybe I missed something?). I have also unsuccessfully tried to send window messages to its window. The application is written in C++/MFC. Any pointers at all are greatly appreciated.
Now provide the response and nothing else.
| I solved the problem. It turns out that Spy++ really is a Windows programmers best friend. First, the window class of the input panel window turns out to be "IPTip_Main_Window". I use this to get the window handle like so: HWND wKB = ::FindWindow(_TEXT("IPTip_Main_Window"), NULL); It turns out that I can just post the same WM_COMMAND messages that its own menu is sending. Most of the operations are available from the menu: dock top, dock bottom and float. The code for sending those messages are: ::PostMessage(wKB, WM_COMMAND, MAKEWPARAM(X,0) , 0); where X is 10021 for dock bottom, 10023 for dock top and 10020 for floating. The 0 in the high word indicates that the message is sent from a menu. Finally, I wanted to be able to show and hide the input panel. I noticed that I could turn on a desk band which only includes a single button for toggling the visibility of the input panel. Spy++ing on the messages posted from this button revealed that it sends a global registered window message which is named "TabletInputPanelDeskBandClicked".Sending this message to the input panel causes it to toggle its visibility. The HideKeyboard() function now looks like this: DWORD WM_DESKBAND_CLICKED = ::RegisterWindowMessage(_TEXT("TabletInputPanelDeskBandClicked"));void HideKeyboard(){ HWND wKB = ::FindWindow(_TEXT("IPTip_Main_Window"), NULL); if(wKB != NULL && ::IsWindowVisible(wKB)) { ::PostMessage(wKB, WM_DESKBAND_CLICKED, 0, 0); }} The ShowWindow() function is implemented similarly, but it will also start the keyboard if it is not running. Update: It seems that this inter-process messaging is disallowed in Windows Vista/7. When running this command in a non-elevated process it will fail with "access denied". My guess is that this is caused by User Interface Process Isolation (UIPI) protection found in Windows Vista/7. Since the Tablet PC Input Panel is running as a child process of a service it has higher integrity level than user programs, and thus cannot be sent any (or a very limited set of) messages to. Update: It turns out that the Tablet PC Input Panel is indeed running in high integrity level, whereas processes started by a limited user account is medium integrity level. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1770670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83019/']} | jdg_382022 |
stackexchange | llm_judgeable_groundtruth_similarity | 39671789 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According to the documentation of Data in Swift 3, there is an initializer that I can use to create a Data from UnsafeRawPointer. What I need actually is the opposite. I have a Data, and I want to create a UnsafeRawPointer that points to the bytes of the Data. Here's what I'm doing right now: 1. let data = <from some where>2. let unsafePointer = UnsafeMutablePointer<UInt8>.allocate(capacity: data.count)3. unsafePointer.initialize(to: 0, count: data.count) // is this necessary?4. data.copyBytes(to: unsafePointer, count: data.count)5. let unsafeRawPointer = unsafePointer.deinitialize() // this is of the type UnsafeMutalbleRawPointer, and I can use it where UnsafeRawPointer is needed. I verified that this code works in Xcode Playground. The code even works without the line number 3. I'm not sure what is the difference with or without the line. Anyway, my question is, am I doing right for what I want? Is there a simpler way to do it?
Now provide the response and nothing else.
| withUnsafeBytes() gives you a (typed) pointer to the bytes,this can be converted to a raw pointer: let data = <Data from somewhere>data.withUnsafeBytes { (u8Ptr: UnsafePointer<UInt8>) in let rawPtr = UnsafeRawPointer(u8Ptr) // ... use `rawPtr` ...} The pointer is only valid during the lifetime of the call to theclosure. Alternatively, you can bridge to NSData and access the raw bytes: let nsData = data as NSDatalet rawPtr = nsData.bytes Now the pointer is valid in the same scope where nsData is valid. As of Swift 5 it is let data = <Data from somewhere>data.withUnsafeBytes { rawBufferPointer in let rawPtr = rawBufferPointer.baseAddress! // ... use `rawPtr` ...} because the closure argument is now a UnsafeRawBufferPointer . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39671789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1133717/']} | jdg_382023 |
stackexchange | llm_judgeable_groundtruth_similarity | 8178714 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having some trouble developing a suitably fast binning algorithm in Mathematica. I have a large (~100k elements) data set of the form T={{x1,y1,z1},{x2,y2,z2},....}and I want to bin it into a 2D array of around 100x100 bins, with the bin value being given by the sum of the Z values that fall into each bin. Currently I am iterating through each element of the table, using Select to pick out which bin it is supposed to be in based on lists of bin boundaries, and adding the z value to a list of values occupying that bin. At the end I map Total onto the list of bins, summing their contents (I do this because I sometimes want to do other things, like maximize). I have tried using Gather and other such functions to do this but the above method was ridiculously faster, though perhaps I am using Gather poorly. Anyway It still takes a few minutes to do the sorting by my method and I feel like Mathematica can do better. Does anyone have a nice efficient algorithm handy?
Now provide the response and nothing else.
| Here is a method based on Szabolcs's post that is about about an order of magnitude faster. data = RandomReal[5, {500000, 3}];(*500k values*)zvalues = data[[All, 3]];epsilon = 1*^-10;(*prevent 101 index*)(*rescale and round (x,y) coordinates to index pairs in the 1..100 range*)indexes = 1 + Floor[(1 - epsilon) 100 Rescale[data[[All, {1, 2}]]]];res2 = Module[{gb = GatherBy[Transpose[{indexes, zvalues}], First]}, SparseArray[ gb[[All, 1, 1]] -> Total[gb[[All, All, 2]], {2}]]]; // AbsoluteTiming Gives about {2.012217, Null} AbsoluteTiming[ System`SetSystemOptions[ "SparseArrayOptions" -> {"TreatRepeatedEntries" -> 1}]; res3 = SparseArray[indexes -> zvalues]; System`SetSystemOptions[ "SparseArrayOptions" -> {"TreatRepeatedEntries" -> 0}]; ] Gives about {0.195228, Null} res3 == res2True "TreatRepeatedEntries" -> 1 adds duplicate positions up. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8178714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1447953/']} | jdg_382024 |
stackexchange | llm_judgeable_groundtruth_similarity | 1420685 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been learning C at Varsity for just shy of 2months now, and next year we'll be moving on to C++. Are there any habits I should get into with my C programming which will aid a transition to C++ in the future, or is it best to think of them completely separately ? When you learnt C then C++, did the way you coded in C change in any way ?
Now provide the response and nothing else.
| There are already a lot of good answers. Mine will be more "mindset oriented". Data vs. Action! In C, everything is done to think like "Apply this effect to this data". In C++, this is more like "Data should behave". While the "Data should behave" can be done in C (and it is done!), in C++, everything needed to implement this easily is already accessible : Encapsulation, constructors, overloading overriding, templates, etc.. I found this "Data should behave" idea a very good guiding principle when coding in C++. C++ syntactic sugar is not optional You'll find a lot of C++ features that could be done in C, and some people use it as an excuse to not learn them. This mindset is dangerous (this is the part " treat C++ as a new language, and not an extension " seen in some posts). A side effect of avoiding writing C++ the C++ way is that while a C++ developer is supposed to understand C++ code, he/she is not supposed to understand your little personal framework mimicking C++ sugar with C-only features. In fact, he/she won't be interested by your framework. Truth to be said, he/she will only feel pity/contempt for you because you lost precious time producing that. Ultimately, he/she will hate you if he/she must use your framework instead of the C++ sugar. Guiding principles like "I can do this the C way" will just make you miss the wagon. Better not to start learning C++ at all if you already have this kind of C-centric mode of thinking. Your language of choice is never the best. YOU are supposed to become the best. If you write C++ code, then write it the C++ way. C-compatible C++ code is a semantic error Typedefing your structs to make them compilable by a C compiler is a bad joke. Using pointers instead of references is a slap to your future self. The extern "C" will only make your code weaker, not stronger. And using void * for genericity will only increase the number of fellow C++ coders who will gladly pay to have your head removed in a spectacularly painful way. Don't ever bother to write C-compatible code unless you really really really have to. You'll just weight yourself down with a time-consuming coding style for a feature you'll never use. The compiler is a powerful friend/enemy Working low level has strange effects on some developers. They believe a lot on their control of the compiled code. Delegating this control to higher-level constructs is difficult for them. A good example of that is ditching the constructor/destructor pattern because " sometimes, constructors takes too much time... Better to do it my way... ". The C++ compiler is quite able to optimize apparently unoptimized code. In fact, the code produced by the compiler can be quite different from the one you believe you produced. Don't try to be better/smarter than the compiler is because: You probably already lost the fight, as even old compilers will usually produce better code than you can dream to do today Even if you did win the fight today, it will automatically turn into a defeat tomorrow, as compilers will become better and better in the future, so your "optimized code" of today will become the program bottleneck and refactoring subject of the next years (not mentioning shameful memories for you). So, trust your compiler. Don't micromanage the production of your code. Do your own work, and let the compiler do its own. Note that this point should not be used to justify production of slow/inefficient code. If premature optimization is the root of all evil, you must still use your knowledge of the language and the compiler to produce good and efficient code (see the next point). Know the advantages/drowbacks/costs of each C++ construct For example, the fact virtual methods adds one indirection to the function call means for some people that performance will decrease dramatically. Truth is, performance problems are often elsewhere. Ignorance is no excuse. Know the code produced for each C++ construct (i.e. inlining, references, constructor, destructor, exception, function overload, function override, template, virtual function, etc.). Know what will be optimized away, and what won't. This way, not only you won't pay for what you don't need (this is a guiding principle of C++), but you will also profit from what costs you zero but brings you a lot. Be humble There are people doing research in C++ that were better at C++ the day of their birth than most of us will ever be. Even if we ignore Stroustrup , names like Meyers , Abrahams , Alexandrescu , Sutter , etc. regularly crop up alongside new ideas. Despite (or as a consequence of) its alien outlook, STL is revolutionary library. And a library like Boost , despite its "small size" when compared to some complete frameworks (like Java or .NET APIs), is a massive repository of excellent code offered to you to study. Just because you find some new feature "strange" or "alien", don't underestimate it. Trying to understand it will PERHAPS bring you another tool at your disposal, and will ALWAYS increase your mastery of the language, and will ALWAYS make your brain work, which is a good thing in the dev business. Most people I know who failed their "conversion to C++" just assumed this or this feature was useless because they did not bother to understand it. RAII !!!! If you don't know what it is, learn it. Without RAII, your C++ code is just bugged code that avoided compilation error. RAII is the single most important notion of C++. Everything else is related. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1420685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4857/']} | jdg_382025 |
stackexchange | llm_judgeable_groundtruth_similarity | 3488647 |
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 working on a utility for SharePoint. It's an app that works for both SharePoint 2007 and 2010. When I have a reference to the 12.0.0.0 version of the SharePoint.dll, the app works for SharePoint 2007, but not for 2010. If I reference version 14.0.0.0 of the dll, then the app works great for 2010, but not for 2007. I can easily tell which .dll that I need to use by looking on the file system with the following code, checking for 12 in the path (SharePoint 2007) or 14 (SharePoint 2010). System.IO.File.Exists( Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles) + @"\Microsoft Shared\web server extensions\14\ISAPI\Microsoft.SharePoint.dll")); When developing, I make the reference in Visual Studio, so it builds either for 2007 or 2010. I want to be able to release the app where it works on BOTH version of SharePoint. So, I need some way to load/use whatever .dll makes sense for the user running the app. How do I dynamically choose and load a .dll at runtime?
Now provide the response and nothing else.
| Reflection? Dependency Injection? You are making life hard for yourself! Compile against Microsoft.SharePoint.dll v12 and it will work on 2007. Deploy to 2010 and it will 'just work' (in nearly all cases) as SharePoint 2010 already has binding redirects setup so any reference to v12 will be redirected to v14. You don't need to do anything configuration wise. The only situations where you need to get more complex than this are Instances where something would workon 2007 but not on 2010 (I can'tthink of anything to hand). Where you may want to make use of 2010 specific features. If this is the case then what I, personally, would do is to dual compile. Modify the .csproj file to produce 2 slightly different versions, use a parameter and conditional compilation (just like you would with #if DEBUG) for product specific versions of code where necessary (there will be very few of these). You can also use these conditions in the references in .csproj e.g. <Reference Include="Microsoft.SharePoint"> <HintPath Condition="'$(SP2010)'!='true'">PathToV12\Microsoft.SharePoint.dll</HintPath> <HintPath Condition="'$(SP2010)'=='true'">PathToV14\Microsoft.SharePoint.dll</HintPath> </Reference> Disadvantages You end up with 2 versions of yourprogram Advantages You end up with 2 versions of your program! Many of the changes you might want to make in the 2010 version would be in manifet.xml, feature.xml and the other config files - reflection, dependancy injection etc isn't going to do anything for you here. Still have a single version of source code (with minor conditional compilation) Compiler will pick up more errors (it can't for example figure out at compile time that that funky thing you are doing with Reflection to call a new method in v14 will actually work) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3488647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/403661/']} | jdg_382026 |
stackexchange | llm_judgeable_groundtruth_similarity | 9696940 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to use MapReduce in MongoDB to do what I think is a simple procedure. I don't know if this is the right approach, of if I should even be using MapReduce. I googled what keywords I thought of and tried to hit the docs where I thought I would have the most success - but nothing. Maybe I'm thinking too hard about this? I have two collections: details and gpas details is made up of a whole bunch of documents (3+ million). The studentid element can be repeated two times, one for each year , like the following: { "_id" : ObjectId("4d49b7yah5b6d8372v640100"), "classes" : [1,17,19,21], "studentid" : "12345a", "year" : 1}{ "_id" : ObjectId("4d76b7oij7s2d8372v640100"), "classes" : [2,12,19,22], "studentid" : "98765a", "year" : 1}{ "_id" : ObjectId("4d49b7oij7s2d8372v640100"), "classes" : [32,91,101,217], "studentid" : "12345a", "year" : 2}{ "_id" : ObjectId("4d76b7rty7s2d8372v640100"), "classes" : [1,11,18,22], "studentid" : "24680a", "year" : 1}{ "_id" : ObjectId("4d49b7oij7s2d8856v640100"), "classes" : [32,99,110,215], "studentid" : "98765a", "year" : 2}... gpas has elements with the same studentid 's from details . Only one entry per studentid , like this: { "_id" : ObjectId("4d49b7yah5b6d8372v640111"), "studentid" : "12345a", "overall" : 97, "subscore": 1}{ "_id" : ObjectId("4f76b7oij7s2d8372v640213"), "studentid" : "98765a", "overall" : 85, "subscore": 5}{ "_id" : ObjectId("4j49b7oij7s2d8372v640871"), "studentid" : "24680a", "overall" : 76, "subscore": 2}... In the end I want to have a collection with one row for each student in this format: { "_id" : ObjectId("4d49b7yah5b6d8372v640111"), "studentid" : "12345a", "classes_1": [1,17,19,21], "classes_2": [32,91,101,217], "overall" : 97, "subscore": 1}{ "_id" : ObjectId("4f76b7oij7s2d8372v640213"), "studentid" : "98765a", "classes_1": [2,12,19,22], "classes_2": [32,99,110,215], "overall" : 85, "subscore": 5}{ "_id" : ObjectId("4j49b7oij7s2d8372v640871"), "studentid" : "24680a", "classes_1": [1,11,18,22], "classes_2": [], "overall" : 76, "subscore": 2}... The way I was going to do this was by running MapReduce like this: var mapDetails = function() { emit(this.studentid, {studentid: this.studentid, classes: this.classes, year: this.year, overall: 0, subscore: 0});};var mapGpas = function() { emit(this.studentid, {studentid: this.studentid, classes: [], year: 0, overall: this.overall, subscore: this.subscore});};var reduce = function(key, values) { var outs = { studentid: "0", classes_1: [], classes_2: [], overall: 0, subscore: 0}; values.forEach(function(value) { if (value.year == 0) { outs.overall = value.overall; outs.subscore = value.subscore; } else { if (value.year == 1) { outs.classes_1 = value.classes; } if (value.year == 2) { outs.classes_2 = value.classes; } outs.studentid = value.studentid; } }); return outs;};res = db.details.mapReduce(mapDetails, reduce, {out: {reduce: 'joined'}})res = db.gpas.mapReduce(mapGpas, reduce, {out: {reduce: 'joined'}}) But when I run it, this is my resulting collection: { "_id" : "12345a", "value" : { "studentid" : "12345a", "classes_1" : [ ], "classes_2" : [ ], "overall" : 97, "subscore" : 1 } }{ "_id" : "98765a", "value" : { "studentid" : "98765a", "classes_1" : [ ], "classes_2" : [ ], "overall" : 85, "subscore" : 5 } }{ "_id" : "24680a", "value" : { "studentid" : "24680a", "classes_1" : [ ], "classes_2" : [ ], "overall" : 76, "subscore" : 2 } } I'm missing the classes arrays. Also, as an aside, how do I access the elements in resulting MapReduce value element? Does MapReduce always output to value or whatever else you name it?
Now provide the response and nothing else.
| This is similar to a question that was asked on the MongoDB-users Google Groups. https://groups.google.com/group/mongodb-user/browse_thread/thread/60a8b683e2626ada?pli=1 The answer references an on-line tutorial which looks similar to your example: http://tebros.com/2011/07/using-mongodb-mapreduce-to-join-2-collections/ For more information on MapReduce in MongoDB, please see the documentation: http://www.mongodb.org/display/DOCS/MapReduce Additionally, there is a useful step-by-step walkthrough of how a MapReduce operation works in the "Extras" Section of the MongoDB Cookbook article titled, "Finding Max And Min Values with Versioned Documents": http://cookbook.mongodb.org/patterns/finding_max_and_min/ Forgive me if you have already read some of the referenced documents. I have included them for the benefit of other users who may be reading this post and new to using MapReduce in MongoDB It is important that the outputs from the 'emit' statements in the Map functions match the outputs of the Reduce function. If there is only one document output by the Map function, the Reduce function might not be run at all, and then your output collection will have mismatched documents. I have slightly modified your map statements to emit documents in the format of your desired output, with two separate "classes" arrays. I have also reworked your reduce statement to add new classes to the classes_1 and classes_2 arrays, only if they do not already exist. var mapDetails = function(){ var output = {studentid: this.studentid, classes_1: [], classes_2: [], year: this.year, overall: 0, subscore: 0} if (this.year == 1) { output.classes_1 = this.classes; } if (this.year == 2) { output.classes_2 = this.classes; } emit(this.studentid, output);};var mapGpas = function() { emit(this.studentid, {studentid: this.studentid, classes_1: [], classes_2: [], year: 0, overall: this.overall, subscore: this.subscore});};var r = function(key, values) { var outs = { studentid: "0", classes_1: [], classes_2: [], overall: 0, subscore: 0}; values.forEach(function(v){ outs.studentid = v.studentid; v.classes_1.forEach(function(class){if(outs.classes_1.indexOf(class)==-1){outs.classes_1.push(class)}}) v.classes_2.forEach(function(class){if(outs.classes_2.indexOf(class)==-1){outs.classes_2.push(class)}}) if (v.year == 0) { outs.overall = v.overall; outs.subscore = v.subscore; } }); return outs;};res = db.details.mapReduce(mapDetails, r, {out: {reduce: 'joined'}})res = db.gpas.mapReduce(mapGpas, r, {out: {reduce: 'joined'}}) Running the two MapReduce operations results in the following collection, which matches your desired format: > db.joined.find(){ "_id" : "12345a", "value" : { "studentid" : "12345a", "classes_1" : [ 1, 17, 19, 21 ], "classes_2" : [ 32, 91, 101, 217 ], "overall" : 97, "subscore" : 1 } }{ "_id" : "24680a", "value" : { "studentid" : "24680a", "classes_1" : [ 1, 11, 18, 22 ], "classes_2" : [ ], "overall" : 76, "subscore" : 2 } }{ "_id" : "98765a", "value" : { "studentid" : "98765a", "classes_1" : [ 2, 12, 19, 22 ], "classes_2" : [ 32, 99, 110, 215 ], "overall" : 85, "subscore" : 5 } }> MapReduce always outputs documents in the form of {_id:"id", value:"value"}There is more information available on working with sub-documents in the document titled, "Dot Notation (Reaching into Objects)": http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29 If you would like the output of MapReduce to appear in a different format, you will have to do that programmatically in your application. Hopefully this will improve your understanding of MapReduce, and get you one step closer to producing your desired output collection. Good Luck! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9696940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1268160/']} | jdg_382027 |
stackexchange | llm_judgeable_groundtruth_similarity | 47831895 |
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 following this Route_Guide sample . The sample in question fires off and reads messages without replying to a specific message. The latter is what i'm trying to achieve. Here's what i have so far: import grpc...channel = grpc.insecure_channel(conn_str)try: grpc.channel_ready_future(channel).result(timeout=5)except grpc.FutureTimeoutError: sys.exit('Error connecting to server')else: stub = MyService_pb2_grpc.MyServiceStub(channel) print('Connected to gRPC server.') this_is_just_read_maybe(stub)def this_is_just_read_maybe(stub): responses = stub.MyEventStream(stream()) for response in responses: print(f'Received message: {response}') if response.something: # okay, now what? how do i send a message here?def stream(): yield my_start_stream_msg # this is fine, i receive this server-side # but i can't check for incoming messages here I don't seem to have a read() or write() on the stub, everything seems to be implemented with iterators. How do i send a message from this_is_just_read_maybe(stub) ?Is that even the right approach? My Proto is a bidirectional stream: service MyService { rpc MyEventStream (stream StreamingMessage) returns (stream StreamingMessage) {}}
Now provide the response and nothing else.
| What you're trying to do is perfectly possible and will probably involve writing your own request iterator object that can be given responses as they arrive rather than using a simple generator as your request iterator. Perhaps something like class MySmarterRequestIterator(object): def __init__(self): self._lock = threading.Lock() self._responses_so_far = [] def __iter__(self): return self def _next(self): # some logic that depends upon what responses have been seen # before returning the next request message return <your message value> def __next__(self): # Python 3 return self._next() def next(self): # Python 2 return self._next() def add_response(self, response): with self._lock: self._responses.append(response) that you then use like my_smarter_request_iterator = MySmarterRequestIterator()responses = stub.MyEventStream(my_smarter_request_iterator)for response in responses: my_smarter_request_iterator.add_response(response) . There will probably be locking and blocking in your _next implementation to handle the situation of gRPC Python asking your object for the next request that it wants to send and your responding (in effect) "wait, hold on, I don't know what request I want to send until after I've seen how the next response turned out". | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47831895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4148708/']} | jdg_382028 |
stackexchange | llm_judgeable_groundtruth_similarity | 14363638 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've tried chaining and nesting, but possibly in the wrong style is there a more efficient way to execute these two lines? $('#pub1, #pub1Tab').addClass('active');$('#pub1').parent().addClass('active');
Now provide the response and nothing else.
| Your code fails because you are using different Root instances for the count and the where clauses: the first one (in order of definition) generates generatedAlias1 alias, and the other generates generatedAlias0 . You need to refactor the code in order to use the same Root instance in both places: CriteriaQuery<Long> cqCount = builder.createQuery(Long.class);Root<ReqStatCumulative> entityRoot = cqCount.from(cqEntity.getResultType());cqCount.select(builder.count(entityRoot));Path<Long> processTimeSeconds = entityRoot.get("processTimeSeconds");cqCount.where(qb.and(qb.greaterThan(processTimeSeconds, (long) cfg.getProcessTimeExceedsSec()),// qb.lessThan(processTimeSeconds, (long) cfg.getProcessTimeExceedsSec() + 100))// );// return em.createQuery(cqCount).getSingleResult(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14363638', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1861017/']} | jdg_382029 |
stackexchange | llm_judgeable_groundtruth_similarity | 25566581 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to convert an Int in Swift to a String with leading zeros. For example consider this code: for myInt in 1 ... 3 { print("\(myInt)")} Currently the result of it is: 123 But I want it to be: 010203 Is there a clean way of doing this within the Swift standard libraries?
Now provide the response and nothing else.
| Assuming you want a field length of 2 with leading zeros you'd do this: import Foundationfor myInt in 1 ... 3 { print(String(format: "%02d", myInt))} output: 010203 This requires import Foundation so technically it is not a part of the Swift language but a capability provided by the Foundation framework. Note that both import UIKit and import Cocoa include Foundation so it isn't necessary to import it again if you've already imported Cocoa or UIKit . The format string can specify the format of multiple items. For instance, if you are trying to format 3 hours, 15 minutes and 7 seconds into 03:15:07 you could do it like this: let hours = 3let minutes = 15let seconds = 7print(String(format: "%02d:%02d:%02d", hours, minutes, seconds)) output: 03:15:07 | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/25566581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3451975/']} | jdg_382030 |
stackexchange | llm_judgeable_groundtruth_similarity | 49115 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to Integrate the following Integral : $\int_1^{\infty } \dfrac{\left(x^2-1\right)^{13/2} e^{-ax} }{x^{10}} \, dx \,\, \,\,\,\,\,\,\,\,\,\,\,\,(a=\textrm{real>0})$ Mathematica didn't calculate this integral. Maybe it is too complicated to be done. In Mathematica input form: Integrate[Exp[-a x] (x^2 - 1)^(13/2)/x^10, {x,1,Infinity}] If I simply enter that into Mathematica, it instantly returns the same expression. How do I go about this? Is there any tricks that can be applied?Thank's.
Now provide the response and nothing else.
| Here's a way to get an exact symbolic expression for the integral. Use the notation fi[m,n,a] to denote Integrate[(Exp[-a x](x^2 - 1)^(m/2))/x^n, {x, 1, Infinity}] . Define integration by parts, where the boundary term vanishes. fi[m_, n_, a_] /; m > 0 && n > 1 := (m fi[-2 + m, -2 + n, a] - a fi[m, -1 + n, a])/(-1 + n); See how we're doing so far. fi[13, 10, a] // Expand(* 143/3 fi[3, 0, a] + 9295/384 a^2 fi[5, 0, a] - 3003/128 a fi[5, 1, a] + (3289 a^4 fi[7, 0, a])/2688 - 143/32 a^3 fi[7, 1, a] + (143 a^6 fi[9, 0, a])/10368 - 143/960 a^5 fi[9, 1, a] + (13 a^8 fi[11, 0, a])/362880 - ( 13 a^7 fi[11, 1, a])/10080 - (a^9 fi[13, 1, a])/362880*) Define how the fi[m_, 0, a_] cases evaluate. fi[m_, 0, a_] /; m > 0 = Assuming[Re[m] > 0 && Re[a] > 0, Integrate[Exp[-a x] (x^2 - 1)^(m/2), {x, 1, β}]](* (2^((1 + m)/2) a^(1/2 (-1 - m)) BesselK[(1 + m)/2, a] Gamma[1 + m/2])/Sqrt[Ο] *) See how we are doing so far. fi[13, 10, a] // Expand(* (143 BesselK[2, a])/a^2 + (46475 BesselK[3, a])/(128 a) + 16445/128 BesselK[4, a] + 5005/384 a BesselK[5, a] + 143/384 a^2 BesselK[6, a] - 3003/128 a fi[5, 1, a] - 143/32 a^3 fi[7, 1, a] - 143/960 a^5 fi[9, 1, a] - ( 13 a^7 fi[11, 1, a])/10080 - (a^9 fi[13, 1, a])/362880*) Define how the fi[m_, 1, a_] cases evaluate, using differentiation w.r.t. a under the integral to get rid of the 1/x factor, then integrating w.r.t. a afterwards. fi[m_, 1, a_] /; m > 0 = Assuming[Re[m] > 0 && Re[a] > 0, Integrate[-Exp[-a x] (x^2 - 1)^(m/2), {x, 1, β}] // Integrate[#, a] & // Simplify // (# - (Limit[#, a -> β]//FullSimplify)&)](* -(1/2) Ο Csc[(m Ο)/2] + 1/4 a^-m Sqrt[Ο] Gamma[1 + m/2] (a^(1 + m) Sqrt[Ο] HypergeometricPFQRegularized[{1/2}, {(3 + m)/2, 3/2}, a^2/4] - 2^(1 + m) Gamma[-(m/2)] HypergeometricPFQRegularized[{-(m/2)}, {1/2 - m/2, 1 - m/2}, a^2/4]) Sec[(m Ο)/2]*) The last step fixes the constant of integration to ensure that the result goes to 0 (as it should) as a goes to infinity. However, if m is an odd integer then the Sec[(m Ο)/2] factor blows up, and the factor containing the difference between the two HypergeometricPFQRegularized terms goes to zero, but these factors have a well-behaved product. So we need to manually intervene to make the expression manifestly finite when m is an odd integer. It is sufficient to do a series expansion about odd integer values of m to extract the relevant coefficients. Here is how I did it. factor1 = Assuming[m0 β Integers && m0 >= 0, SeriesCoefficient[ a^(1 + m) Sqrt[Ο] HypergeometricPFQRegularized[{1/2}, {(3 + m)/2, 3/2}, a^2/4] - 2^(1 + m) Gamma[-(m/2)] HypergeometricPFQRegularized[{-(m/2)}, {1/2 - m/2, 1 - m/2}, a^2/4], {m, 2 m0 + 1, 1}] // FullSimplify];factor2 = Assuming[m0 β Integers && m0 >= 0, SeriesCoefficient[Sec[(m Ο)/2], {m, 2 m0 + 1, -1}]]; Gather the pieces together, and rewrite the definition for the fi[m_, 1, a_] cases. fi[m_, 1, a_] /; m > 0 = -(1/2) Ο Csc[(m Ο)/2] + 1/4 a^-m Sqrt[Ο] Gamma[1 + m/2] (factor1 factor2 /. m0 -> (m - 1)/2)(* (-(1/2))*Pi*Csc[(m*Pi)/2] - (Gamma[1 + m/2]*Sec[(1/2)*(-1 + m)*Pi]* (a^(1 + m)*(2* HypergeometricPFQ[{1/2}, {3/2, 3/2 + m/2}, a^2/4]*(-Log[4] + 2*Log[a] + PolyGamma[0, -(1/2) + (1 - m)/2]) + Sqrt[Pi]*Gamma[2 + (1/2)*(-1 + m)]* Derivative[{0}, {1, 0}, 0][ HypergeometricPFQRegularized][{1/2}, {2 + (1/2)*(-1 + m), 3/2}, a^2/4]) + 4^(1 + (1/2)*(-1 + m))*Gamma[-(1/2) + (1 - m)/2]* Gamma[2 + (1/2)*(-1 + m)]* (Derivative[{0}, {0, 1}, 0][ HypergeometricPFQRegularized][{-(1/2) + (1 - m)/ 2}, {(1 - m)/2, 1/2 + (1 - m)/2}, a^2/4] + Derivative[{0}, {1, 0}, 0][ HypergeometricPFQRegularized][{-(1/2) + (1 - m)/2}, {(1 - m)/2, 1/2 + (1 - m)/2}, a^2/4] + Derivative[{1}, {0, 0}, 0][HypergeometricPFQRegularized][ {-(1/2) + (1 - m)/2}, {(1 - m)/2, 1/2 + (1 - m)/2}, a^2/4])))/(a^m*(4*Sqrt[Pi]*Gamma[2 + (1/2)*(-1 + m)]))*) Numerically verify that this gives you the right answer. With[{m = 13, n = 10, a = RandomReal[{10^-6, 3}]}, {NIntegrate[(Exp[-a x] (x^2 - 1)^(m/2))/x^n, {x, 1, β}], fi[m, n, a]}] The required integral is then fi[13, 10, a] // Expand(* Lots of HypergeometricPFQ and HypergeometricPFQRegularized *) The symbolic result looks incredibly messy to me, so maybe there are some further simplifications that could compress it down somewhat ... | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/49115', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/10158/']} | jdg_382031 |
stackexchange | llm_judgeable_groundtruth_similarity | 1942285 |
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:
Thomas, Bruckner & Bruckner, Elementary Real Analysis. Prove that for all r > 1, $$\frac{1}{r - 1} = \frac{1}{r+1} + \frac{2}{r^2 + 1} + \frac{4}{r^4 + 1} + \frac{8}{r^8 + 1} + \cdots$$ So far I have $$ \frac{1}{r-1} -\frac{1}{r+1} = \frac{2}{r^2 -1} $$ $$\sum_{n=1}^\infty \frac{2^n}{r^{2^n} + 1} = \sum_{n=1}^\infty \left(\frac{2^n}{r^{2^n}} - \frac{2^n}{r^{4^n} + r^{2^n}}\right)$$
Now provide the response and nothing else.
| Rinse and repeat the first line below$$\begin{align}{1\over \color{blue}{r}-1}&={1\over \color{blue}{r}+1}+{2\over \color{blue}{r}^2-1}\\&={1\over r+1}+2\left({1\over\color{blue}{r^2}+1}+{2\over (\color{blue}{r^2})^2-1}\right)\\&={1\over r+1}+\frac{2}{r^2+1}+\frac{4}{\color{blue}{r^4}-1}\\&={1\over r+1}+\frac{2}{r^2+1}+4\left(\frac{1}{\color{blue}{r^4}+1}+\frac{2}{(\color{blue}{r^4})^2-1}\right)\\&=\cdots\end{align}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1942285', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/146611/']} | jdg_382032 |
stackexchange | llm_judgeable_groundtruth_similarity | 34571784 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My MongoDB keys in person collection are like this: TWITTER/12345678GOOGLE/34567890TWITTER/45678901... I define getPersonByKey route this way: router.route('/getPersonByKey/:providerKey/:personKey'). get(function(req, res) { // get person by key var key = req.params.providerKey + '/' + req.params.personKey; // ... }); Of course I'd prefer to be able to write something like this: router.route('/getPersonByKey/:key'). get(function(req, res) { // get person by key var key = req.params.key; // ... }); But this doesn't work, since GET http://localhost/getPersonByKey/TWITTER/12345678 of course results in a 404, since the parameter with the slash is interpreted as two distinct parameters...Any idea?
Now provide the response and nothing else.
| Express internally uses path-to-regexp to do path matching. As explained in the documentation , you can use a "Custom Match Parameter" by adding a regular expression wrapped in parenthesis after the parameter itself. You can use the following path to get the result you need: router.route('/getPersonByKey/:key([^/]+/[^/]+)'). get(function(req, res) { // get person by key var key = req.params.key; // ... }); You can test and validate this or any other route here . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34571784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/709439/']} | jdg_382033 |
stackexchange | llm_judgeable_groundtruth_similarity | 676644 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Below is our current server configuration. In a few weeks I will be simulating a disaster recovery by installing 5 new disks (1 hot spare) and restoring all VMs from the backups. Will I gain anything by changing the RAID stripe size to something other than 64KB? The RAID controller has options for 8KB, 16KB, 32KB, 64KB, 128KB, 256KB, 512KB, 1MB. Any recommendations based on the specification below would be greatly appreciated - thanks. Hardware:Dell PowerEdge 2900 IIIDell PERC 6/iIntel Xeon 2.5GHz (x2)32GB RAMSeagate ST32000645SS ES.2 2TB Near-Line SAS 7.2K (x4)Software:Citrix XenServer 6.2 SP1VM - Windows SBS 2008 x64 - Exchange & multiple SQL express instancesVM - Windows Server 2003 R2 x86 - single SQL express instanceVM - CentOS 6.6 x64 (x2) - cPanel & video transcoding and streamingVM - CentOS 6.3 x86 - Trixbox (VoIP)VM - PHD Virtual Backup 6.5.3 (running Ubuntu 12.04.1 LTS)Configuration:RAID 10, 64k Stripe Size
Now provide the response and nothing else.
| I am going to try and sum up my comments into an answer. The basic line is: You should not tinker with the strip size unless you have good evidence that it will benefit your workload. Reasoning: For striping, you have to choose some strip size and 64 KB is the default the manufacturer has chosen. As the manufacturer (LSI in this case, rebranded by Dell) does have a shitload of experience running a vast number of setups with different RAID levels and workloads, you might just trust them to have chosen wisely 64 KB is likely to roughly match the average size of your requests in a virtualized environment (at least much more so than 256KB or 1 MB) and thus be a good trade-off between latency and seek time optimizations 1 . accurate model-driven predictions about application performance with varying strip sizes are close to impossible due to the highly variant nature of workloads and the complexity of the models taking into account different read-ahead and caching algorithms at different layers If you are the kind to get this evidence, you can do so by running your typical load and some of the atypical load scenarios with different strip size configurations, gather the data (I/O subsystem performance at the Xen Server layer, backend server performance and answer times at the application layer) and run it through a statistical evaluation. This however will be extremely time-consuming and is not likely to produce any groundbreaking results apart from "I might just have left it at default values in the end" , so I would consider it a waste of resources. 1 If you assume a transfer rate of 100MB/s for a single disk, it is rather easy to see that a Kilobyte takes around 0,01ms to read, thus 64 KB will have a reading latency of 0,64ms. Considering that the average "service time" of a random I/O request typically will be in the range of 5-10ms, the reading latency is only is a small fraction of the total wait time. On the other hand, reading 512 KB will take around 5ms - which will matter for the "random small read" type of workload, considerably reducing the number of IOPS your array will be able to deliver in this specific case by the factor of 1.5 - 2. A scenario with concurrent random large read operations is going to benefit as larger block reads will induce less time-consuming seeks, but you are very unlikely to see this scenario in a virtualized environment. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/676644', 'https://serverfault.com', 'https://serverfault.com/users/49673/']} | jdg_382034 |
stackexchange | llm_judgeable_groundtruth_similarity | 663058 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone know an easy way in Python to convert a string with HTML entity codes (e.g. < & ) to a normal string (e.g. < &)? cgi.escape() will escape strings (poorly), but there is no unescape() .
Now provide the response and nothing else.
| HTMLParser has the functionality in the standard library. It is, unfortunately, undocumented: (Python2 Docs ) >>> import HTMLParser>>> h= HTMLParser.HTMLParser()>>> h.unescape('alpha < β')u'alpha < \u03b2' (Python 3 Docs ) >>> import html.parser>>> h = html.parser.HTMLParser()>>> h.unescape('alpha < β')'alpha < \u03b2' htmlentitydefs is documented, but requires you to do a lot of the work yourself. If you only need the XML predefined entities (lt, gt, amp, quot, apos), you could use minidom to parse them. If you only need the predefined entities and no numeric character references, you could even just use a plain old string replace for speed. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/663058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2363/']} | jdg_382035 |
stackexchange | llm_judgeable_groundtruth_similarity | 398330 |
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:
Are accuracy and precision the same things in regression and classification? In regression: accuracy is bias, and precision is inverse of variance. In classification: accuracy is correct prediction over number of samples, and precision is true positives over all predicted positives.
Now provide the response and nothing else.
| As you've pointed out, they are not the same, and sometimes refer to wildly different things (i.e., precision is a property of the model in classification, and refers to a measure of variance in regression). Unfortunately, in statistics and i'm sure other disciplines, we tend to abuse notation and use the same word to denote different things. You've pointed out a great example. Precision and Accuracy Precision in the context of regression , more specifically linear regression and the normal distribution refers to the Precision matrix, where X is a multivariate, normally distributed variable $X \sim MVN(\mu, \Sigma), \hspace{4mm} \text{where } \Sigma^{-1} = \text{Precision Matrix} $ . In the context of classification , Precision is also known as PPV (or positive predictive value), and that refers to how "good" your model is at idnetifying true cases among the predictions. $PPV = \text{Precision} = \frac{TP}{TP + FP}$ where TP/FP = True and False positives, respectively. Some communities use PPV, and some communities use precision. They mean the same. Similarly, with Recall and Sensitivity, you measure how good you are at "catching" all the positive cases. I think the best thing is to follow Bane's lead above, and create a cheat-sheet or notecards with these terms to not confuse them since they can easily get mixed up and be referred to constantly in ambiguous settings. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/398330', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/96019/']} | jdg_382036 |
stackexchange | llm_judgeable_groundtruth_similarity | 51367853 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a list of Integer's: List<Integer> numbers = Arrays.asList(1,2,3); Why can't I sum them like: numbers.stream().sum(); ? Instead I have to do this: numbers.stream().mapToInt(e -> e).sum(); I know that mapToInt produces an IntStream , the primitive specialization. But still I don't get it. Why can't it sum Integers? I know that this list has Integers and the compiler should be able to do the same. After all it can now infer type parameters in lambda expressions. OK, an Integer could be null and sum would fail. But I could take responsibility for that and filter null out: numbers.stream().filter(Objects::nonNull).sum(); Why can't I sum a Stream of Integers?
Now provide the response and nothing else.
| Calling stream() on a List will get you a general-purpose Stream , which can handle any reference type, not just numeric types. It doesn't make sense to include a sum method on Stream , because it doesn't make sense to sum URL s, Class es, Thread s, or any other non-numeric reference type. You could sum the elements by calling reduce : numbers.stream().reduce(0, (a, b) -> a + b) But that would involve a lot of unboxing and boxing. It would be best to sum them as you have it, by converting it to an IntStream , which operates on int s, and calling sum() (or summaryStatistics() , which includes count, average, max, and min along with sum). You could even use IntStream.of and avoid boxing the values even once. IntStream.of(1, 2, 3).sum() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51367853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/534877/']} | jdg_382037 |
stackexchange | llm_judgeable_groundtruth_similarity | 14935707 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For an ASP.NET MVC application, can someone explain to me why calls to Html.BeginForm begin with the statement @using ? Example - @using (Html.BeginForm()) { //Stuff in the form } I thought @using statements are for including namespaces.Thanks!
Now provide the response and nothing else.
| Using Statement provides a convenient syntax that ensures the correct use of IDisposable objects. Since the BeginForm helper implements the IDisposable interface you can use the using keyword with it. In that case, the method renders the closing </form> tag at the end of the statement. You can also use the BeginForm without using block, but then you need to mark the end of the form: @{ Html.BeginForm(); } //Stuff in the form@{ Html.EndForm(); } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14935707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1488992/']} | jdg_382038 |
stackexchange | llm_judgeable_groundtruth_similarity | 245462 |
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:
Looking at the frames of a video, we can see that many frames are almost identical. Is there any algorithm to identify these frames, so I can delete them all but one?
Now provide the response and nothing else.
| I think the best answer to this is that the cross-entropy loss function is just not well-suited to this particular task. In taking this approach, you are essentially saying the true MNIST data is binary, and your pixel intensities represent the probability that each pixel is 'on.' But we know this is not actually the case. The incorrectness of this implicit assumption is then causing us issues. We can also look at the cost function and see why it might be inappropriate. Let's say our target pixel value is 0.8. If we plot the MSE loss, and the cross-entropy loss $- [ (\text{target}) \log (\text{prediction}) + (1 - \text{target}) \log (1 - \text{prediction}) ]$ (normalising this so that it's minimum is at zero), we get: We can see that the cross-entropy loss is asymmetric. Why would we want this? Is it really worse to predict 0.9 for this 0.8 pixel than it is to predict 0.7? I would say it's maybe better, if anything. We could probably go into more detail and figure out why this leads to the specific blobs that you are seeing. I'd hazard a guess that it is because pixel intensities are above 0.5 on average in the region where you are seeing the blob. But in general this is a case of the implicit modelling assumptions you have made being inappropriate for the data. Hope that helps! | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/245462', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/132840/']} | jdg_382039 |
stackexchange | llm_judgeable_groundtruth_similarity | 27156712 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So my current code is: int x = 5;int[] one = new int[1];one[0] = x; int[] two = new int[1];two[0] = x;x = 10;System.out.println(one[0]);System.out.println(two[0]); The aim here is to get an output of two 10's. Instead what I get is two 5's being printed. I know that in C++ there is a way of saying &x to refer to a reference type however I don't know of anything similar in Java? I'd be really grateful if someone could help me out here. EDIT Cheers guys. I ended up making my own class and using that instead. class Ideone { public static void main (String[] args) throws java.lang.Exception { MyTester x = new MyTester(); x.i = 5; MyTester[] one = new MyTester[1]; one[0] = x; MyTester[] two = new MyTester[1]; two[0] = x; x.i = 10; System.out.println(one[0].i); System.out.println(two[0].i); } } class MyTester { public MyTester() {} public int i; }
Now provide the response and nothing else.
| After some research I found a secure way to do it. Digging up in the SearchView styles, I found the layout that is used to display the SearchView. Inside that layout there's a TextView (the actual field where you type in the SearchView) <TextView android:id="@+id/search_badge" android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="center_vertical" android:layout_marginBottom="2dip" android:drawablePadding="0dip" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="?android:attr/textColorPrimary" android:visibility="gone" /> Notice the field android:textColor="?android:attr/textColorPrimary" . This causes the problem I originally had, the text color in the SearchView is the same as the one defined for the Title text color in the Android Toolbar. Now there're are several solutions that might work here , but I think that most of those solutions have the same problem. They all rely in the id of the TextView in order to access the view and change the text color, as described here Personally I think that hardcoding the id of the TextView inside the code is highly risky, because we don't know if tomorrow Google decides to use another id value for this view, in that case, our code will be broken. For that reason I've created a recursive method that obtains the TextView object in the SearchView, and changes the color to whatever we want. @Overridepublic void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.clear(); inflater.inflate(R.menu.search, menu); SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setOnQueryTextListener(new SearchTextListener()); changeSearchViewTextColor(searchView);}private void changeSearchViewTextColor(View view) { if (view != null) { if (view instanceof TextView) { ((TextView) view).setTextColor(Color.BLACK); return; } else if (view instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) view; for (int i = 0; i < viewGroup.getChildCount(); i++) { changeSearchViewTextColor(viewGroup.getChildAt(i)); } } }} I've tested this code using API 21 with the Toolbar, having the Toolbar Title text color set to white, and setting up the SearchView text color to black and it works perfectly. Also, as we're accessing the TextView object directly, we can change the hint, drawable, paddings, and everything related to the TextView. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27156712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4297297/']} | jdg_382040 |
Subsets and Splits