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
1450957
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 found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings. >>> import json>>> releases = {1: "foo-v0.1"}>>> json.dumps(releases)'{"1": "foo-v0.1"}' Is there any easy way to preserve the key as an int, without needing to parse the string on dump and load.I believe it would be possible using the hooks provided by the json module, but again this still requires parsing.Is there possibly an argument I have overlooked?cheers, chaz Sub-question:Thanks for the answers. Seeing as json works as I feared, is there an easy way to convey key type by maybe parsing the output of dumps?Also I should note the code doing the dumping and the code downloading the json object from a server and loading it, are both written by me. Now provide the response and nothing else.
This is one of those subtle differences among various mapping collections that can bite you. JSON treats keys as strings; Python supports distinct keys differing only in type. In Python (and apparently in Lua) the keys to a mapping (dictionary or table, respectively) are object references. In Python they must be immutable types, or they must be objects which implement a __hash__ method. (The Lua docs suggest that it automatically uses the object's ID as a hash/key even for mutable objects and relies on string interning to ensure that equivalent strings map to the same objects). In Perl, Javascript, awk and many other languages the keys for hashes, associative arrays or whatever they're called for the given language, are strings (or "scalars" in Perl). In perl $foo{1}, $foo{1.0}, and $foo{"1"} are all references to the same mapping in %foo --- the key is evaluated as a scalar! JSON started as a Javascript serialization technology. (JSON stands for J ava S cript O bject N otation.) Naturally it implements semantics for its mapping notation which are consistent with its mapping semantics. If both ends of your serialization are going to be Python then you'd be better off using pickles. If you really need to convert these back from JSON into native Python objects I guess you have a couple of choices. First you could try ( try: ... except: ... ) to convert any key to a number in the event of a dictionary look-up failure. Alternatively, if you add code to the other end (the serializer or generator of this JSON data) then you could have it perform a JSON serialization on each of the key values --- providing those as a list of keys. (Then your Python code would first iterate over the list of keys, instantiating/deserializing them into native Python objects ... and then use those for access the values out of the mapping).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1450957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/176166/']}
jdg_70341
stackexchange
llm_judgeable_groundtruth_similarity
462690
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: In his video Making logic gates from transistors Ben Eater draws a following scheme simulate this circuit – Schematic created using CircuitLab When the switch is on, the LED stops emitting light (to demonstrate that there is no current on the wire the LED is connected to). I wonder why there is no current on the LED wire. In theory, there should be at least SOME current flowing through LED. Is it assumed that the resistance of wire going through the transistor is negligible as compared to a huge resistance that is provided by LED and therefore the current going through LED is negligible too? Now provide the response and nothing else.
When the transistor is turned on in that manner it can be switched into saturation if the base current is sufficient. The collector-emitter emitter voltage will drop to about 0.2 V. This voltage will be applied to the LED. Figure 1. Current through various colours of LED as a function of forward voltage. Image source IV curves . Figure 1 shows that none of the LEDs from infrared to ultra-violet will pass any significant current at 0.2 V. There just isn't enough voltage to get the charge carriers to jump the P-N junction. Figure 2. A water check-valve analogy. Image source: What is an LED? . If you look at the check-valve in the figure above, it should be clear that the spring normally keeps the ball in position and prevents back-flow. When “forward-biased” the ball shut-off can be moved against the spring but it will take some initial pressure to move the ball. This results in a pressure drop across the valve: the pressure downstream will be less than the inlet pressure. In a similar manner the PN junction in an LED causes a voltage drop. For a red LED it is about 1.5 V to 2.0 V. You need to exceed the V f to get enough current to flow and light the LED. The links are to articles by me and may help you further.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/462690', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/233996/']}
jdg_70342
stackexchange
llm_judgeable_groundtruth_similarity
3414807
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to show that $$\left\lvert\int_\gamma \frac{\cos(z)}z \,dz\right\rvert \le 2\pi e$$ if $\gamma$ is a path that traces the unit circle once. The book recommends that I show that $\lvert \cos(z) \rvert \le e$ if $\lvert z \rvert = 1$ to help prove this. I know that if $\lvert f(z) \rvert \le M$ for all $z \in \gamma (I)$ then $$\left\lvert \int_\gamma f(z) \,dz \right\rvert \le M\ell (\gamma),$$ where $\ell (\gamma)$ is the length of the path, which in this case is $2\pi$ . So I can see why I would need to show $\lvert cos(z) \rvert \le e$ if $\lvert z \rvert = 1$ to prove the inequality, but I am not sure where to go from here to show that. Now provide the response and nothing else.
With the series expansion of $\cos$ we get for $|z|=1$ : $$| \cos z| \le \sum_{n=0}^{\infty}\frac{1}{(2n)!} \le \sum_{n=0}^{\infty}\frac{1}{n!}=e.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3414807', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/608771/']}
jdg_70343
stackexchange
llm_judgeable_groundtruth_similarity
3157095
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: Hi can you help me determine the $n^\text{th}$ term of the sequence $1, \frac{1}{2}, 3, \frac{1}{4}, 5, \frac{1}{6}, 7...$ ? Now provide the response and nothing else.
Your sequence can be given by the formula $$a_n = n^{(-1)^{n+1}}$$ Alternatively, it may also be defined by $$a_n = \begin{cases}n, & n \equiv 1 \pmod{2} \\ \frac{1}{n} & n \equiv 0 \pmod{2}\end{cases}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3157095', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/40318/']}
jdg_70344
stackexchange
llm_judgeable_groundtruth_similarity
7844359
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 a regular expression with condition: min 6 characters, max 50 characters must contain 1 letter must contain 1 number may contain special characters like !@#$%^&*()_+ Currently I have pattern: (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{6,50})$ However it doesn't allow special characters, does anybody have a good regex for that? Thanks Now provide the response and nothing else.
Perhaps a single regex could be used, but that makes it hard to give the user feedback for which rule they aren't following. A more traditional approach like this gives you feedback that you can use in the UI to tell the user what pwd rule is not being met: function checkPwd(str) { if (str.length < 6) { return("too_short"); } else if (str.length > 50) { return("too_long"); } else if (str.search(/\d/) == -1) { return("no_num"); } else if (str.search(/[a-zA-Z]/) == -1) { return("no_letter"); } else if (str.search(/[^a-zA-Z0-9\!\@\#\$\%\^\&\*\(\)\_\+]/) != -1) { return("bad_char"); } return("ok");}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7844359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1006338/']}
jdg_70345
stackexchange
llm_judgeable_groundtruth_similarity
34910306
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 function that updates a row: CREATE OR REPLACE FUNCTION MyTable_UPDATE ( _ID int, _Description text) RETURNS boolAS $$DECLARE _OK boolean;BEGIN _OK := false; UPDATE mytable SET Description = _Description WHERE ID = _ID; _OK := true; RETURN _OK; END;$$ LANGUAGE plpgsql STRICT; When I call it with a value in description it works: select MyTable_UPDATE(9, 'testing 123'); If I call it with a null value, it doesn't update, there is no error message and no value is returned: select MyTable_UPDATE(9, null); If I run an update query to set description = null, it works: UPDATE mytable SET Description = null WHERE ID = 9; Now provide the response and nothing else.
From postgresql documentation on CREATE FUNCTION STRICT RETURNS NULL ON NULL INPUT or STRICT indicates that the functionalways returns null whenever any of its arguments are null. If thisparameter is specified, the function is not executed when there arenull arguments; instead a null result is assumed automatically. In short, the function is not executed. You have to remove the STRICT parameter to be able to pass a NULL value.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34910306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/623583/']}
jdg_70346
stackexchange
llm_judgeable_groundtruth_similarity
1570288
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $(X, \mathcal O_X), (Y, \mathcal O_Y)$ be locally ringed spaces. A morphism of ringed spaces is defined to be a pair $(f,f^{\#}):(X, \mathcal O_X) \rightarrow (Y, \mathcal O_Y)$, where $f:X \rightarrow Y$ is continuous, and $f^{\#}: \mathcal O_Y \rightarrow f_{\ast} \mathcal O_X$ is a morphism of sheaves. We consider $(f,f^{\#})$ to also be a morphism of locally ringed spaces if for each $x \in X$, the homomorphism on the stalks $$f_x^{\#}: \mathcal O_{Y,f(x)} \rightarrow \mathcal O_{X,x}$$ is a local homomorphism (preimage of the unique maximal ideal remains maximal). My question is, what exactly is the map $f_{x}^{\#}$? I know since $f^{\#}$ is a morphism of sheaves, we have a homomorphism on the stalks $$f_{f(x)}^{\#}: \mathcal O_{Y,f(x)} \rightarrow (f_{\ast} \mathcal O_X)_{f(x)}$$ Are we getting $f_x^{\#}$ by composing $f_{f(x)}^{\#}$ with some homomorphism $(f_{\ast} \mathcal O_X)_{f(x)} \rightarrow \mathcal O_{X,x}$? Now provide the response and nothing else.
Given any sheaf $\mathcal{O}$ on a space $X$, a continuous map $f:X\to Y$, and a point $x\in X$, there is a canonical map $(f_*\mathcal{O})_{f(x)}\to\mathcal{O}_x$. Indeed, an element of $(f_*\mathcal{O})_{f(x)}$ is represented by a section of $f_*\mathcal{O}$ over some open set $V$ containing $f(x)$, which is just a section of $\mathcal{O}$ over $f^{-1}(V)$, which then determines an element of $\mathcal{O}_x$. It is easy to see that this correspondence is compatible with restriction and hence induces a well-defined map $(f_*\mathcal{O})_{f(x)}\to\mathcal{O}_x$. In your case, taking $\mathcal{O}=\mathcal{O}_X$, this is the map you are looking for.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1570288', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28556/']}
jdg_70347
stackexchange
llm_judgeable_groundtruth_similarity
134062
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to get a better grasp of representation theory. I was asking myself " what is the essential difference between representations of some group $G$ and a $KG$ module? How are they related, and what is the distinction? " What's confusing me is: I can understand matrix representations of a group in a simple way, since they are isomorphic to some permutation group, but what about a module? How do I get things cleared out? I need some insight. Now provide the response and nothing else.
There's essentially no real difference between modules and representations. Think of them as two sides of the same coin. Given a $\mathbb{K}G$ -module $V$ , you have a linear action of $G$ on a $\mathbb{K}$ -vector space $V$ . This in turn gives you a homomorphism from $G$ to $\mathrm{GL}(V)$ (invertible $\mathbb{K}$ -linear endomorphisms). Such a homomorphism is a representation . And then this can be turned around. Given a representation, you get an associated module. Specifically, let $V$ be a $\mathbb{K}G$ -module and let $g,h \in G$ , $v,w\in V$ , and $c\in\mathbb{K}$ . Give a name to the map: $v \mapsto g\cdot v$ say: $\varphi(g):V \to V$ (so $\varphi(g)(v)=g \cdot v$ ). Then $\varphi(g)(v+cw)$ $=g\cdot(v+cw)$ $=g\cdot v+cg\cdot w$ $=\varphi(g)(v)+c\varphi(g)(w)$ . Thus $\varphi(g)$ is $\mathbb{K}$ -linear. Then because $\varphi(1)$ is the identity map ( $1 \cdot v=v$ ) and $\varphi(g^{-1})(\varphi(g)(v))=g^{-1}\cdot g\cdot v=(g^{-1}g\cdot v=1\cdot v=v$ etc. we get $\varphi(g)$ is an invertible linear map. Therefore: $\varphi:G \to \mathrm{GL}(V)$ . Moreover, $\varphi(gh)=\varphi(g)\varphi(h)$ (easy to check) so $\varphi$ is a homomorphism (which we call a representation). Without going into the details, this all reverses. So $\mathbb{K}G$ -modules = representations of $G$ on $\mathbb{K}$ -vector spaces. If you've studied group actions, you've already seen this type of correspondence. Let $G$ act on $X$ . Then the map $x \mapsto g \cdot x$ turns out to be a bijection on $X$ . Thus if we define $\varphi(g)(x)=g\cdot x$ for all $x\in X$ , then $\varphi(g) \in S(X)$ (permutations on $X$ ). Moreover, $\varphi(gh)=\varphi(g)\varphi(h)$ so $\varphi : G\to S(X)$ is a group homomorphism. We call such things permutation representations . And again this can be reversed. Given a permutation representation: $\varphi:G \to S(X)$ , one can define a group action $g \cdot x \equiv \varphi(g)(x)$ . So $G$ -action on $X$ = permutation representation of $G$ on $X$ . If you look into other branches of algebra, you'll see this kind of thing over and over again: Lie algebra modules = Lie algebra representations etc. It's just different points of view. You can either think of "Algebra Thing" acting on "Thing" or a homomorphism from "Algebra Thing" to Maps from "Things to Things".
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/134062', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24598/']}
jdg_70348
stackexchange
llm_judgeable_groundtruth_similarity
57952
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why can the BGP protocol be implemented across routers? But the OSPF protocol can only be implemented on directly connected routers? Is the OSPF protocol based on IP? we know the BGP is based on TCP, so is this affect that? Now provide the response and nothing else.
OSPF was designed as an internal gateway protocol, to chose the best path in a network under your control. It would not make sense to connect non-adjacent routers, so that feature is not part of the protocol. BGP can be used at the edges of an autonomous system with intervening routers in the middle. So it can peer with non-adjacent routers.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/57952', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/51231/']}
jdg_70349
stackexchange
llm_judgeable_groundtruth_similarity
2104643
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have a 2D Numpy array: >>> a = np.random.random((4,6)) and I want to add a 1D array to each row: >>> c = np.random.random((6,))>>> a + c This works. Now if I try adding a 1D array to each column, I get an error: >>> b = np.random.random((4,))>>> a + bTraceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: shape mismatch: objects cannot be broadcast to a single shape I can fix this by using np.newaxis : >>> a + b[:,np.newaxis] which does work as expected. What are the shape-matching rules to avoid having to use np.newaxis? Is it that the last element of the numpy shape tuple has to match? Does this rule also apply to higher dimensions? For example, the following works: >>> a = np.random.random((2,3,4,5))>>> b = np.random.random((4,5))>>> a + b So my question is whether this is documented anywhere, and if it is a behavior that can be relied on, or whether it is best to always use np.newaxis? Now provide the response and nothing else.
This is a distinctive feature of numpy called 'broadcasting':if you can multiply a vector by a scalar why not allow multiplying a matrix by a vector ? Just like every element of a vector is multiplied by a scalar in the first case, every cell in the matrix row is multiplied by the corresponding vector element in the second case. Broadcasting is done using four rules which are a bit complicated in formulation but are rather intuitive once understood: All input arrays with ndim smaller than the input array of largest ndim ,have 1’s prepended to their shapes. The size in each dimension of the output shape is the maximum of all theinput sizes in that dimension. An input can be used in the calculation if its size in aparticular dimension either matchesthe output size in that dimension, orhas value exactly 1. If an input has a dimension size of 1 in its shape, the first data entryin that dimension will be used for allcalculations along that dimension. Inother words, the stepping machinery ofthe ufunc will simply not step alongthat dimension (the stride will be 0for that dimension). For example, The operation is possible (doesn't result in shape mismatch error you mentioned) in three cases: The arrays all have exactly the same shape. The arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1. The arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2. More examples can be found in my recent article on broadcasting [1] or in the official docs [2]. References Broadcasting in NumPy, 2021 https://towardsdatascience.com/58856f926d73 NumPy Reference. Broadcasting http://docs.scipy.org/doc/numpy/reference/ufuncs.html#broadcasting
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2104643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180783/']}
jdg_70350
stackexchange
llm_judgeable_groundtruth_similarity
738457
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I notice that every time I set up google apps, mailgun, mandrill or whatever I always have to set up domainkeys. That part makes sense - RSA, public/private, etc - I get that. Intuitively I would think there is a single standard for where to find SMTP domain keys, but instead it seems like one of these prefixes get picked at random: smtp k1 mx pic mailo . Example: smtp._domainkey.example.com (makes sense) mx._domainkey.example.net (yup) mailo._domainkey.example.org (why the o?) k1._domainkey.foo.com (k for key? 1 for primary?) pic._domainkey.bar.com (pic? what does that even mean?) So I'm looking at my list of domains and it appears that only those 5 variations occur, but I'm not seeing a pattern. Why isn't there just one standard prefix? How does that querying server know which to query? Isn't _ an illegal character? And if the domainkey prefixes are arbitrary, why only arbitrary-ish? I'd love to be pointed to some reading material as well as some short and sweet explanations if you have one on hand. P.S. I've tried googling a little, but I don't know enough to figure out what my query should be. All that I see are tech support how to articles for specific email or hosting providers. Now provide the response and nothing else.
Here are short sweet answers that you requested: How does that querying server know which to query? That prefix is called selector . The receiving server know which DNS record to query by looking into the DomainKey-Signature header containing the cryptographic signature. Among many useful information, there are the selector and domain values. For example: DomainKey-Signature: a=rsa-sha1; s=smtp; d=example.com ; c=simple; q=dns; b=JOc8ZszniSbVoGVyOfAKCdLXyuU4zGffruD4doXSlEG2q8Ldyd00laHRNiYzRv+Z; selector + "_domainkey" + domain = smtp._domainkey.example.com Why isn't there just one standard prefix? There isn't one standard prefix, because in some scenarios you want to have the option to configure multiple different DomainKeys records (e.g. you have two SMTP servers and you want each one to use it's own DomainKeys policy). Isn't _ an illegal character? As you can see, it's not :-) And here are some reading materials ;-)
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/738457', 'https://serverfault.com', 'https://serverfault.com/users/93930/']}
jdg_70351
stackexchange
llm_judgeable_groundtruth_similarity
24011003
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 couldn't understand exact meaning of this statement. let x where x.hasSuffix("pepper") What is meaning of that? Note: There is no need of let use? It makes me confusing.. Is this enough x where x.hasSuffix("pepper") ? because, let x should be already get assigned.? Update: From @Jacky comment here, it could be meaning same as below. let x = vegetable if (x.hasSuffix("pepper") ...... Now provide the response and nothing else.
The where in that context is used as pattern matching . From the example: case let x where x.hasSuffix("pepper"): When the suffix of x matches "pepper" it will set the constant vegetableComment : let vegetableComment = "Is it a spicy \(x)?" You can see as well that x can´t be "celery", "cucumber" or "watercress", otherwise it would give you a different outcome: case "celery": let vegetableComment = "Add some raisins and make ants on a log."case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." Because those cases are before case let x where x.hasSuffix("pepper"): . You can try changing the order of them and pass the value "celery" to see a different outcome. Edit: From my understanding it creates a constant x if x 's suffix is "pepper". The goal of creating this constant, is for you to use it after that: let vegetableComment = "Is it a spicy \(x)?" Edit 2: After a bit more research, that's called value binding and it's described as: switch case can bind the value or values it matches to temporary constants or variables, for use in the body of the case. This is known as value binding, because the values are “bound” to temporary constants or variables within the case’s body. Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24011003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2223390/']}
jdg_70352
stackexchange
llm_judgeable_groundtruth_similarity
351984
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $\{X_t, t \ge 0\}$ be a continuous stochastic process and adapted to the filtration $\{\mathcal{F}_t,t\ge 0 \}$ and consider $$\alpha = \inf\{t, |X_t|>1\},$$ the first time the the process $X_t$ leaves the interval $[-1,1]$. Then can you help me to show that $\alpha$ is in fact stopping time? Now provide the response and nothing else.
Then can you help me to show that $\alpha$ is in fact stopping time? Well, this would be difficult, since $\alpha$ is not always a stopping time for the natural filtration $(\mathcal F^X_t)_{t\geqslant0}$ of the process $(X_t)_{t\geqslant0}$ , defined by $\mathcal F^X_t=\sigma(X_s\,;\,0\leqslant s\leqslant t)$. For a counterexample, consider some event $A$ such that $0<P(A)<1$ and define the process $(X_t)_{t\geqslant0}$ as follows: On $A$, $X_t=t$ for every $t\geqslant0$. On $\Omega\setminus A$, $X_t=t$ for every $0\leqslant t\leqslant1$ and $X_t=2-t$ for every $t\geqslant1$. Then $\alpha=\inf\{t\,;\,|X_t|\gt1\}$ equals $\alpha=1$ on $A$ and $\alpha=3$ on $\Omega\setminus A$. Thus, $\{\alpha\leqslant1\}=A$. For every $t\leqslant1$, the random variable $X_t$ is deterministic, hence $\mathcal F^X_1=\{\varnothing,\Omega\}$ is the trivial sigma-algebra, but the event $A$ is not in $\mathcal F^X_1$ hence $\{\alpha\leqslant1\}\notin\mathcal F^X_1$, which proves that $\alpha$ is not a stopping time for the filtration $(\mathcal F^X_t)_{t\geqslant0}$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/351984', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24176/']}
jdg_70353
stackexchange
llm_judgeable_groundtruth_similarity
54802616
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 model class of which I want two fields to be a choice fields, so to populate those choices I am using an enum as listed below #models.pyclass Transaction(models.Model): trasaction_status = models.CharField(max_length=255, choices=TransactionStatus.choices()) transaction_type = models.CharField(max_length=255, choices=TransactionType.choices())#enums.pyclass TransactionType(Enum): IN = "IN", OUT = "OUT" @classmethod def choices(cls): print(tuple((i.name, i.value) for i in cls)) return tuple((i.name, i.value) for i in cls)class TransactionStatus(Enum): INITIATED = "INITIATED", PENDING = "PENDING", COMPLETED = "COMPLETED", FAILED = "FAILED" ERROR = "ERROR" @classmethod def choices(cls): print(tuple((i.name, i.value) for i in cls)) return tuple((i.name, i.value) for i in cls) However, when I am trying to access this model through admin I am getting the following error : Django Version: 1.11Exception Type: ValueErrorException Value: too many values to unpack (expected 2) I followed two articles that described how to use enums: https://hackernoon.com/using-enum-as-model-field-choice-in-django-92d8b97aaa63 https://blog.richard.do/2014/02/18/how-to-use-enums-for-django-field-choices/ Now provide the response and nothing else.
Django 3.0 has built-in support for Enums Example: from django.utils.translation import gettext_lazy as _class Student(models.Model): class YearInSchool(models.TextChoices): FRESHMAN = 'FR', _('Freshman') SOPHOMORE = 'SO', _('Sophomore') JUNIOR = 'JR', _('Junior') SENIOR = 'SR', _('Senior') GRADUATE = 'GR', _('Graduate') year_in_school = models.CharField( max_length=2, choices=YearInSchool.choices, default=YearInSchool.FRESHMAN, ) These work similar to enum from Python’s standard library, but with some modifications: Enum member values are a tuple of arguments to use when constructing the concrete data type. Django supports adding an extra string value to the end of this tuple to be used as the human-readable name, or label . The label can be a lazy translatable string. Thus, in most cases, the member value will be a (value, label) two-tuple. If a tuple is not provided, or the last item is not a (lazy) string, the label is automatically generated from the member name. A .label property is added on values, to return the human-readable name.A number of custom properties are added to the enumeration classes – .choices , .labels , .values , and .names – to make it easier to access lists of those separate parts of the enumeration. Use .choices as a suitable value to pass to choices in a field definition. The use of enum.unique() is enforced to ensure that values cannot be defined multiple times. This is unlikely to be expected in choices for a field. For more info, check the documentation Note: As @Danielle Madeley pointed out, if you try to access the year_in_school attribute directly Django still returns the raw string instead of the Enum object: >>> student.year_in_school'FR' What I usually do is to create a helper method that returns the Enum object: class Student(models.Model): ... def get_year_in_school(self) -> YearInSchool: # Get value from choices enum return self.YearInSchool[self.year_in_school]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/54802616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4755440/']}
jdg_70354
stackexchange
llm_judgeable_groundtruth_similarity
43407
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have always seen the hydrogen atom bonded to C5 drawn below the plane as in the following figure. Shouldn't it be drawn above the plane since it is drawn on left side in Fischer projection? Now provide the response and nothing else.
The Haworth projection depicts the pyranose (or furanose, as the case may be) as a planar ring. The Fischer projection depicts the open chain carbohydrate with the carbon backbone in a single plane. Importantly, the groups on the horizontal bonds are coming out of the plane and the vertical bonds are going into the plane. The result of this is that the carbon backbone is curving toward itself, and the compound is partially poised to close a ring. However, the ring of the pyranose is not all carbon. In glucose, it's the oxygen at C5 that adds to the aldehyde to close the ring. We can manipulate the Fischer projection so that this oxygen at C5 is coplanar with the rest of the atoms that will make up the ring. Rotating around the C4-C5 bond places this oxygen on the Fischer projection's vertical axis. The Haworth projection is essentially a closed version of the Fischer projection tipped on its side with C1 at the right. Forming the hemi-acetal gives the pyranose form of glucose. You imply in the question that groups that appear on the right side of the Fischer projection should appear on the bottom of the Haworth projection and groups that appear on the left side of the Fischer projection should appear on the top of the Haworth projection. That idea is true. However in the process above the -CH2OH is rotated to the the left side of the Fischer projection. Consequently, it appears on the top of the Haworth projection.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/43407', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/7697/']}
jdg_70355
stackexchange
llm_judgeable_groundtruth_similarity
44616530
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 display months (in abbreviated form) along the horizontal axis, with the corresponding year printed once. I know how to display month-year: The un-needed repetition of the year clutters the labels. Instead I would like something like this: except that the year would be printed below the months. I printed the year above the axis labels, because that's the best I could do. This follows a limitation of the annotate() function, which gets clipped if it lies outside of the plot area. I am aware of possible workarounds based on annotate_custom() , but I couldn't make them to work with date objects (I did not try to convert dates to numbers and back to dates again, as it seemed more complicated than hopefully necessary) I'm wondering if the new dup_axis() could be hijacked for this purpose. If instead of sending the duplicated axis to the opposite side of the panel, it could send it a few lines below the duplicated axis, then perhaps it would just be a matter of setting up one axis with panel.grid.major blanked out and the labels set to %b , while the other axis would have panel.grid.minor blanked out and the labels set to %Y . (an added challenge is that the year labels would be shifted to October instead of January) These questions are related. However, the annotate_custom() function and textGrob() functions do not play well with dates, as far as I can tell. how-can-i-add-annotations-below-the-x-axis-in-ggplot2 displaying-text-below-the-plot-generated-by-ggplot2 Data and basic code below: library("ggplot2") library("scales") ggplot(data = df, aes(x = Date, y = value)) + geom_line() + scale_x_date(date_breaks = "2 month", date_minor_breaks = "1 month", labels = date_format("%b %Y")) + xlab(NULL) ggplot(data = df, aes(x = Date, y = value)) + geom_line() + scale_x_date(date_minor_breaks = "2 month", labels = date_format("%b")) + annotate(geom = "text", x = as.Date("1719-10-01"), y = 0, label = "1719") + annotate(geom = "text", x = as.Date("1720-10-01"), y = 0, label = "1720") + xlab(NULL) # data df <- structure(list(Date = structure(c(-91455, -91454, -91453, -91452, -91451, -91450, -91448, -91447, -91446, -91445, -91444, -91443, -91441, -91440, -91439, -91438, -91437, -91436, -91434, -91433, -91431, -91430, -91429, -91427, -91426, -91425, -91424, -91423, -91422, -91420, -91419, -91418, -91417, -91416, -91415, -91413, -91412, -91411, -91410, -91409, -91408, -91406, -91405, -91404, -91403, -91402, -91401, -91399, -91398, -91397, -91396, -91395, -91394, -91392, -91391, -91390, -91389, -91388, -91387, -91385, -91384, -91382, -91381, -91380, -91379, -91377, -91376, -91375, -91374, -91373, -91372, -91371, -91370, -91369, -91368, -91367, -91366, -91364, -91363, -91362, -91361, -91360, -91359, -91357, -91356, -91355, -91354, -91353, -91352, -91350, -91349, -91348, -91347, -91346, -91345, -91343, -91342, -91341, -91340, -91339, -91338, -91336, -91335, -91334, -91333, -91332, -91331, -91329, -91328, -91327, -91326, -91325, -91324, -91322, -91321, -91320, -91319, -91315, -91314, -91313, -91312, -91311, -91310, -91308, -91307, -91306, -91305, -91304, -91303, -91301, -91300, -91299, -91298, -91297, -91296, -91294, -91293, -91292, -91291, -91290, -91289, -91287, -91286, -91285, -91284, -91283, -91282, -91280, -91279, -91278, -91277, -91276, -91275, -91273, -91272, -91271, -91270, -91269, -91268, -91266, -91265, -91264, -91263, -91262, -91261, -91259, -91258, -91257, -91256, -91255, -91254, -91252, -91251, -91250, -91249, -91248, -91247, -91245, -91244, -91243, -91242, -91241, -91240, -91238, -91237, -91236, -91235, -91234, -91233, -91231, -91230, -91229, -91228, -91227, -91226, -91224, -91223, -91222, -91221, -91220, -91219, -91217, -91216, -91215, -91214, -91213, -91212, -91210, -91209, -91208, -91207, -91205, -91201, -91200, -91199, -91198, -91196, -91195, -91194, -91193, -91192, -91191, -91189, -91188, -91187, -91186, -91185, -91184, -91182, -91181, -91180, -91179, -91178, -91177, -91175, -91174, -91173, -91172, -91171, -91170, -91168, -91167, -91166, -91165, -91164, -91163, -91161, -91160, -91159, -91158, -91157, -91156, -91154, -91153, -91152, -91151, -91150, -91149, -91147, -91146, -91145, -91144, -91143, -91142, -91140, -91139, -91138, -91131, -91130, -91129, -91128, -91126, -91125, -91124, -91123, -91122, -91121, -91119, -91118, -91117, -91116, -91115, -91114, -91112, -91111, -91110, -91109, -91108, -91107, -91104, -91103, -91102, -91101, -91100, -91099, -91097, -91096, -91095, -91094, -91093, -91091, -91090, -91089, -91088, -91087, -91086, -91084, -91083, -91082, -91081, -91080, -91079, -91077, -91076, -91075, -91074, -91073, -91072, -91070, -91069, -91068, -91065, -91063, -91062, -91061, -91060, -91059, -91058, -91056, -91055, -91054, -91053, -91052, -91051, -91049, -91048, -91047, -91046, -91045, -91044, -91042, -91041, -91040, -91039, -91038, -91037, -91035, -91034, -91033, -91032, -91031, -91030, -91028, -91027, -91026, -91025, -91024, -91023, -91021, -91020, -91019, -91018, -91017, -91016, -91014, -91013, -91012, -91011, -91010, -91009, -91007, -91006, -91005, -91004, -91003, -91002, -91000, -90999, -90998, -90997, -90996, -90995, -90993, -90992, -90991, -90990, -90989, -90988, -90986, -90985, -90984, -90983, -90982), class = "Date"), value = c(113, 113, 113, 113, 114, 114, 114, 115, 115, 115, 116, 116, 116, 116, 117, 117, 117, 117, 116, 117, 116, 116, 116, 117, 117, 117, 117, 117, 117, 117, 116, 117, 116, 116, 116, 117, 117, 117, 117, 117, 117, 117, 116, 116, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 117, 118, 118, 118, 118, 117, 118, 117, 117, 117, 117, 117, 117, 118, 116, 116, 116, 116, 116, 116, 116, 117, 117, 118, 118, 118, 118, 118, 119, 120, 120, 119, 119, 120, 120, 121, 121, 122, 124, 124, 122, 123, 124, 123, 123, 123, 123, 123, 124, 124, 126, 126, 126, 126, 126, 125, 125, 126, 127, 126, 126, 125, 126, 126, 126, 128, 128, 128, 130, 133, 131, 133, 134, 134, 134, 136, 136, 136, 135, 135, 135, 136, 136, 136, 136, 135, 135, 135, 135, 130, 129, 129, 130, 131, 136, 138, 155, 157, 161, 170, 174, 168, 165, 169, 171, 181, 184, 182, 179, 181, 179, 175, 177, 177, 174, 170, 174, 173, 178, 173, 178, 179, 182, 184, 184, 180, 181, 182, 182, 184, 184, 188, 195, 198, 220, 255, 275, 350, 310, 315, 320, 320, 316, 300, 310, 310, 320, 317, 313, 312, 310, 297, 285, 285, 286, 288, 315, 328, 338, 344, 345, 352, 352, 342, 335, 343, 340, 342, 339, 337, 336, 336, 342, 347, 352, 352, 351, 352, 352, 351, 352, 352, 355, 375, 400, 452, 487, 476, 475, 473, 485, 500, 530, 595, 720, 720, 770, 750, 770, 750, 735, 740, 745, 735, 700, 700, 750, 760, 755, 755, 760, 760, 765, 950, 950, 950, 875, 875, 875, 880, 880, 880, 900, 900, 900, 880, 880, 890, 895, 890, 880, 870, 870, 870, 870, 870, 860, 860, 860, 860, 850, 840, 810, 820, 810, 810, 805, 810, 805, 820, 815, 820, 805, 790, 800, 780, 760, 765, 750, 740, 820, 810, 800, 800, 775, 750, 810, 750, 740, 700, 705, 660, 630, 640, 595, 590, 570, 565, 535, 440, 400, 410, 400, 405, 390, 370, 300, 300, 180, 200, 310, 290, 260, 260, 275, 260, 270, 265, 255, 250, 210, 210, 200, 195, 210, 215, 240, 240, 220, 220, 220, 220, 210, 212, 208, 220, 210, 212, 208, 220, 215, 220, 214, 214, 213, 212, 210, 210, 195, 195, 160, 160, 175, 205, 210, 208, 197, 181, 185)), .Names = c("Date", "value"), row.names = c(NA, 393L ), class = "data.frame") Now provide the response and nothing else.
The code below provides two potential options for adding year labels. Option 1a: Faceting You could use faceting to mark the years. For example: library(ggplot2)library(lubridate)ggplot(df, aes(Date, value)) + geom_line() + scale_x_date(date_labels="%b", date_breaks="month", expand=c(0,0)) + facet_grid(~ year(Date), space="free_x", scales="free_x", switch="x") + theme_bw() + theme(strip.placement = "outside", strip.background = element_rect(fill=NA,colour="grey50"), panel.spacing=unit(0,"cm")) Note that with this approach, if there are missing dates at the beginning or end of a year (by "missing", I mean rows for those dates are not even present in the data) then the x-axis will start/end at the first/last date in the data for that year, rather than go from Jan-1 to Dec-31. In that case, you'd need to add in rows for the missing dates and either NA for value or interpolate value . In addition, with this method there is no space or line between December 31 of one year and January 1 of the next year, so there's a discontinuity across each year. Option 1b: Faceting + centered month labels To address @AF7's comment. You can center the month labels by adding some spaces before each label. But you have to choose the number of spaces manually, depending on the physical size of the plot when you print it to a device. (There's probably a way to center the labels programmatically based on the internal grob measurements, but I'm not sure how to do it.) I've also removed the minor vertical gridlines and lightened the line between years. ggplot(df, aes(Date, value)) + geom_line() + scale_x_date(date_labels=paste(c(rep(" ",11), "%b"), collapse=""), date_breaks="month", expand=c(0,0)) + facet_grid(~ year(Date), space="free_x", scales="free_x", switch="x") + theme_bw() + theme(strip.placement = "outside", strip.background = element_blank(), panel.grid.minor.x = element_blank(), panel.border = element_rect(colour="grey70"), panel.spacing=unit(0,"cm")) Option 2a: Edit the x-axis label grob Here's a more complex and finicky method (though it could likely be automated by someone who understands the structure and unit spacings of grid graphics better than I do) that avoids the pitfalls of the faceting method described above: library(grid)# Fake data with an extra year added for illustrationset.seed(2)df = data.frame(Date=seq(as.Date("1718-03-01"),as.Date("1721-09-20"), by="1 day"))df$value = cumsum(rnorm(nrow(df)))# The plot we'll start withp = ggplot(df, aes(Date, value)) + geom_vline(xintercept=as.numeric(df$Date[yday(df$Date)==1]), colour="grey60") + geom_line() + scale_x_date(date_labels="%b", date_breaks="month", expand=c(0,0)) + theme_bw() + theme(panel.grid.minor.x = element_blank()) + labs(x="") Now we want to add the year values below and in between June and July of each year. The code below does that by modifying the x-axis label grob and is adapted from this SO answer by @SandyMuspratt. # Get the grobg <- ggplotGrob(p)# Get the y axisindex <- which(g$layout$name == "axis-b") # Which grobxaxis <- g$grobs[[index]] # Get the ticks (labels and marks)ticks <- xaxis$children[[2]]# Get the labelsticksB <- ticks$grobs[[2]]# Edit x-axis label grob# Find every index of Jun in the x-axis labels and add a newline and# then a year labeljunes = which(ticksB$children[[1]]$label == "Jun")ticksB$children[[1]]$label[junes] = paste0(ticksB$children[[1]]$label[junes], "\n ", unique(year(df$Date))) # Put the edited labels back into the plotticks$grobs[[2]] <- ticksBxaxis$children[[2]] <- ticksg$grobs[[index]] <- xaxis# Draw the plotgrid.newpage()grid.draw(g) Option 2b: Edit the x-axis label grob and center the month labels Below is the only change that needs to be made to Option 2a to center the month labels, but, once again, the number of spaces needs to be tweaked manually. # Make the edit# Center the month labels between ticksticksB$children[[1]]$label = paste0(paste(rep(" ",7),collapse=""), ticksB$children[[1]]$label)# Find every index of Jun in the x-axis labels and a year labeljunes = grep("Jun", ticksB$children[[1]]$label)ticksB$children[[1]]$label[junes] = paste0(ticksB$children[[1]]$label[junes], "\n ", unique(year(df$Date)))
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44616530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1457380/']}
jdg_70356
stackexchange
llm_judgeable_groundtruth_similarity
279966
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 building a PHP application in CodeIgniter. CodeIgniter sends all requests to the main controller: index.php . However, I don't like to see index.php in the URI. For example, http://www.example.com/faq/whatever will route to http://www.example.com/index.php/faq/whatever . I need a reliable way for a script to know what it's address is, so it will know what to do with the navigation. I've used mod_rewrite , as per CodeIgniter documentation. The rule is as follows: RewriteEngine onRewriteCond $1 !^(images|inc|favicon\.ico|index\.php|robots\.txt)RewriteRule ^(.*)$ /index.php/$1 [L] Normally, I would just check php_self , but in this case it's always index.php . I can get it from REQUEST_URI , PATH_INFO , etc., but I'm trying to decide which will be most reliable. Does anyone know (or know where to find) the real difference between PHP_SELF , PATH_INFO , SCRIPT_NAME , and REQUEST_URI ? Thanks for your help! Note : I've had to add spaces, as SO sees the underscore, and makes it italic for some reason. Updated : Fixed the spaces. Now provide the response and nothing else.
Some practical examples of the differences between these variables: Example 1.PHP_SELF is different from SCRIPT_NAME only when requested url is in form: http://example.com/test.php/foo/bar [PHP_SELF] => /test.php/foo/bar[SCRIPT_NAME] => /test.php (this seems to be the only case when PATH_INFO contains sensible information [PATH_INFO] => /foo/bar)Note: this used to be different in some older PHP versions (<= 5.0 ?). Example 2.REQUEST_URI is different from SCRIPT_NAME when a non-empty query string is entered: http://example.com/test.php?foo=bar [SCRIPT_NAME] => /test.php[REQUEST_URI] => /test.php?foo=bar Example 3.REQUEST_URI is different from SCRIPT_NAME when server-side redirecton is in effect (for example mod_rewrite on apache): http://example.com/test.php [REQUEST_URI] => /test.php[SCRIPT_NAME] => /test2.php Example 4.REQUEST_URI is different from SCRIPT_NAME when handling HTTP errors with scripts. Using apache directive ErrorDocument 404 /404error.php http://example.com/test.php [REQUEST_URI] => /test.php[SCRIPT_NAME] => /404error.php On IIS server using custom error pages http://example.com/test.php [SCRIPT_NAME] => /404error.php[REQUEST_URI] => /404error.php?404;http://example.com/test.php
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/279966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27580/']}
jdg_70357
stackexchange
llm_judgeable_groundtruth_similarity
32954424
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 store an array of integers in my table and I can't find any type that supports array in Documentation , any suggestion. Migration: public function up(){ Schema::create('pickups', function (Blueprint $table) { $table->increment('id'); $table->boolean('default'); $table->integer('shifts'); <<--------- HERE I want to store an array of integers $table->integer('status_id'); $table->timestamps(); });} Now provide the response and nothing else.
The array datatype is not present in all database systems and because Laravel's Schema Builder is database agnostic, it doesn't offer methods to create non-common datatype columns. So you have two options: 1. Use a raw SQL statement to add the column, something like the statement below I think should work. Although I'm not sure if the Query Builder or Eloquent can handle these types of columns correctly: DB::statement('ALTER TABLE pickups ADD COLUMN shifts integer[]'); 2. Use Eloquent's available workaround by using attribute casting . In your migration create the column as json like so: public function up(){ Schema::create('pickups', function (Blueprint $table) { $table->increment('id'); $table->boolean('default'); $table->json('shifts'); $table->integer('status_id'); $table->timestamps(); });} Then you can setup your Pickup model (if you haven't done so already) and use the $casts property: class Pickup extends Model{ protected $casts = [ 'shifts' => 'array' ];} This will let Eloquent know that when it fetches data from the database it will have to convert the shifts column value to an array . This is only emulating an actual array, as at the database level the column is of type TEXT and the array is serialized. However when unserializing the column value, Eloquent returns an actual array of integers for you to use in your code. Below is an example use case: // Create a new Pickup entry$pickup = App\Pickup::create([ 'default' => true, 'shifts' => '[1, 5, 7]', // you can easily assign an actual integer array here 'status_id' => 1]); Assuming the above generated an entry with id equal to 1 when you later retrieve the entry: $pickup = App\Pickup::find(1);dump($pickup->shifts); The dump() from the code above will output an actual array of integers: array:3 [▼ 0 => 1 1 => 5 2 => 7]
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32954424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4281779/']}
jdg_70358
stackexchange
llm_judgeable_groundtruth_similarity
427533
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was asked to find a formula for all even moments of the form $E(X^{2n})$ and all odd moments of the form $E(X^{2n+1})$ using a mgf. Can you help me find the even moments? I will attempt to solve for the odd moments using similar techniques. Let $X$ be a continuous random variable having the density $f_X(x)=\frac{1}{2}e^{-|x|}$ , where $-\infty < x < \infty$ . My work: I was able to obtain the following moment-generating function: $M_X(t)=(1-t^2)^{-1}.$ However, I am unsure of where to go from here. Thank you for your help. Now provide the response and nothing else.
One way to make your mgf approach to the problem easier is to use the power series $$(1-t^2)^{-1}=\sum_{j=0}^{\infty} t^{2j}$$ Differentiating the rhs repeatedly is much easier than differentiating the lhs. (note this only applies for $|t|<1$ but as you are differentiating at $t=0$ it still works). You should see that it will just be a factorial. However is it probably even simpler to just evaluate the expectation directly $$E(X^{2n})=\int_{-\infty}^{\infty}\frac{x^{2n}}{2}\exp(-|x|)dx$$ The result should be a gamma function (ie factorial). This also becomes clear from the mgf power series. update regarding the mgf approach, to evaluate $E(X^{2n})$ we need to differentiate the rhs $2n$ times. The following result will be useful $$\frac{\partial^k x^{r}}{\partial x^k} =\left(\begin{matrix} \frac{r!}{(r-k)!}x^{r-k} & r=k,k+1,\dots \\0 & r=1,\dots,k-1\end{matrix}\right)$$ Now if you apply this to the term $t^{2j}$ and take the "2n-th" derivative, we have $r=2j$ and $k=2n$ and $x=t$ . Then we get $$\frac{\partial^{2n} t^{2j}}{\partial t^{2n}} =\left(\begin{matrix} \frac{(2j)!}{(2j-2n)!}t^{2j-2n} & 2j=2n,2n+2,2n+4,2n+6,\dots \\0 & 2j=0,2,\dots,2n-2\end{matrix}\right)$$ This means when we add up over all the terms we can write this as $$\sum_{j=0}^{\infty}\frac{\partial^{2n} t^{2j}}{\partial t^{2n}}=0+\dots+0+(2n)!+t^2\frac{(2n+2)!}{2!}+t^4\frac{(2n+4)!}{4!}+\dots$$ only the single tertm $(2n)!$ is not $0$ and also not a multiple of $t$ . So setting $t=0$ leaves only that term.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/427533', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/257939/']}
jdg_70359
stackexchange
llm_judgeable_groundtruth_similarity
1003613
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to use CSS to create a 'greyed out' effect on my page while a loading box is displayed in the foreground while the application is working. I've done this by creating a 100% height/width, translucent black div which has its visibility toggled on/off via javascript. I thought this would be simple enough; however, when the page content expands to the point that the screen scrolls, scrolling to the foot of the page reveals a portion which is not greyed out. In other words, the 100% in the div's height seems to be applying to the browser viewport size, not the actual page size. How can I make the div expand to cover the whole of the page's content? I've tried using JQuery .css('height', '100%') before toggling it's visibility on but this doesn't change anything. This is the CSS of the div in question: div.screenMask{ position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 1000; background-color: #000000; opacity: 0.7; filter: alpha(opacity=70); visibility: hidden;} Thanks. Now provide the response and nothing else.
If you change position: absolute to position: fixed it will work in all browsers except IE6. This fixes the div to the viewport, so it doesn't move out of view when scrolling. You can use $(document).height() in jQuery to make it work in IE6 too. E.g. $('.screenMask').height($(document).height()); That would obviously fix it for all the other browsers too, but I prefer not using JavaScript if I can avoid it. You'd need to do the same thing for the width too, actually, in case there's any horizontal scrolling. There are plenty of hacks around to make fixed positioning work in IE6 too, but they tend to either impose some other limitations on your CSS, or use JavaScript, so they're likely not worth the trouble. Also, I presume you have only one of these masks, so I'd suggest using an ID for it instead of a class.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1003613', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69285/']}
jdg_70360
stackexchange
llm_judgeable_groundtruth_similarity
17642433
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Whenever I create a pthread, valgrind outputs a memory leak, For example the below code: #include <stdio.h>#include <unistd.h>#include <pthread.h> void *timer1_function (void *eit){ (void) eit; printf("hello world\n"); pthread_exit(NULL);}int main(void){ pthread_t timer1; pthread_create( &timer1, NULL, timer1_function, NULL); ///////line13 int i=0; for(i=0;i<2;i++){usleep(1);} return 0;} valgrind outputs ==1395== HEAP SUMMARY:==1395== in use at exit: 136 bytes in 1 blocks==1395== total heap usage: 6 allocs, 5 frees, 1,134 bytes allocated==1395== ==1395== 136 bytes in 1 blocks are possibly lost in loss record 1 of 1==1395== at 0x402A629: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)==1395== by 0x4011304: allocate_dtv (dl-tls.c:297)==1395== by 0x4011AAB: _dl_allocate_tls (dl-tls.c:461)==1395== by 0x4052470: pthread_create@@GLIBC_2.1 (allocatestack.c:571)==1395== by 0x8048566: main (test.c:13)==1395== ==1395== LEAK SUMMARY:==1395== definitely lost: 0 bytes in 0 blocks==1395== indirectly lost: 0 bytes in 0 blocks==1395== possibly lost: 136 bytes in 1 blocks==1395== still reachable: 0 bytes in 0 blocks==1395== suppressed: 0 bytes in 0 blocks why pthread_create cause a problem although I was using the man page as reference, and how can I fix it? Now provide the response and nothing else.
A thread is an allocated resource and you did not free it before exiting. You should call pthread_join ; this would also eliminate the need for your hackish and incorrect sleep loop. It's possible that even once you fix this, valgrind will still see a "leak", since some implementations of POSIX threads (I'm guessing you're using glibc/NPTL) cache and reuse thread resources rather than freeing them fully. I'm not sure if valgrind works around this or not.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17642433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2178557/']}
jdg_70361
stackexchange
llm_judgeable_groundtruth_similarity
21492
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I have two naive questions about stacks. 1) Is it possible to define stacks in the Zariski topology? Presuming you can: 2) If a stack has a coarse moduli, and the coarse moduli space is a scheme, then does that mean that your stack is a stack in the Zariski topology? In general, I am trying to understand why a new notion of open cover is necessary if all I am interested in is remembering stabilizers. Certainly this is too simple a mind-set, so feel free to enlighten me. Now provide the response and nothing else.
1.) It's possible to define stacks on ANY category equipped with a Grothendieck topology (such a category with a topology is called a site). In particular, this holds true for the Zariski site. Moreover, there is always a way to define an "Artin stack"- these are those stacks which arise as torsors for a groupoid object in your site. Outside of algebraic geometry, these give rise to notions of topological and differentiable stacks, for instance. EDIT: As long as groupoid objects exist in your category. 2.) As in Harry's post, any stack which is a stack in a site which is finer than the Zariski topology is also a stack in the Zariski topology. To address your general question as to "why a new notion of open cover is necessary if all I am interested in is remembering stabilizers", you should learn a bit about Grothendieck topologies. I'll make a couple remarks: i) If all you cared about were stabilizers, then you wouldn't need to use any covers at all; ordinary fibered categories would do the trick! Indeed, take a group object in your site acting an object, and take the action groupoid- it is a groupoid object. Look at the pseudo-functor which assigns each object of your site the groupoid of maps into this groupoid object (considering the object as a groupoid with all identity arrows). This remembers the stabilizers for this action. ii) (subcanonical) Grothendieck topologies are a choice of a type of cover for your objects, in such a way that this object is the colimit of these covers, AND "this is important to remember". This is a little imprecise, so, allow me to elaborate via an example from topology: Let $U_i$, $i\in I$ be an open cover of a space X. Then, continuous maps from X to another space Y are in bijection with with continuous maps $f_i:U_i \to Y$ which agree on their intersection. This is just saying that X is the colimit of this open cover. Instead, we can view this a property of the presheaf $Hom(blank,Y)$ represented by $Y$ on the category of topological spaces (for you set theorists, choose a Grothendieck universe). For any $X$ and any open cover $U_i$, $i\in I$ of $X$, (let $Hom(blank,Y)=F$) the natural map $F(X) \to \varprojlim \left[{\prod{F(U_i)}} \rightrightarrows {\prod{F(U_{ij})}}\right]$ is a bijection. If $F$ is any presheaf, this is just saying $F$ is a sheaf. Since this is NOT true for an ARBITRARY presheaf $F$, X is no longer the colimit of its open covers in the full category of all presheaves. The same argument holds for all fibred categories- it's only true if we restrict to STACKS (and $X$ then becomes the weak colimit of this cover, but, never mind). The reason you add the condition for descent for covers, is so that "all maps into your stack from a space are continuous". More precisely, and more generally, it's so that maps from a space, scheme, whatever you site is, into a stack can be determined by mapping out of elements of some covering of your object in a way that glues (for stacks, rather than sheaves, they don't need to AGREE on the intersection, but, agree up to an invertible 2-cell, plus some coherency conditions). Combining these ideas, if you have a group acting on an object, the pseudo-functor produced by the action groupoid is rarely a stack with respect to your topology, but you can stackify it, and then it will become one and still remember all the stabilizers. I hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/21492', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1231/']}
jdg_70362
stackexchange
llm_judgeable_groundtruth_similarity
18178597
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 know this topic has been thoroughly covered on StackOverflow, but I can't for the life of me get my regular expression to work. So without further repetitive ado ... This is what I have. String: <p model='cat'></p> Regex: .match(/(?:model=')(.*)(?:')/g) This is what my expression returns: model='cat' This is what I want: cat Why isn't my non capture group ignored? Is it that I don't understand what a non-capturing group does? Why isn't my Regex working? Now provide the response and nothing else.
The entire match will always be group 0, you need to access that specific group (group 1 in this case since the first group is non-capture), you can do it like this: var str = "<p model='cat'></p>";var regex = /(?:model=')(.*)(?:')/gvar match = regex.exec(str);alert(match[1]); // cat Fiddle Also, I suppose you are probably wanting several matches within str, you could do that like this: var str = "<p model='cat'></p><p model='dog'></p><p model='horse'></p>";var regex = /(?:model=')([^']*)/gvar matches = [];var match;while (match = regex.exec(str)) { matches.push(match[1]);}alert(matches); // cat,dog,horse Fiddle
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18178597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1626976/']}
jdg_70363
stackexchange
llm_judgeable_groundtruth_similarity
5879128
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two MVars (well an MVar and a Chan). I need to pull things out of the Chan and process them until the other MVar is not empty any more. My ideal solution would be something like the UNIX select function where I pass in a list of (presumably empty) MVars and the thread blocks until one of them is full, then it returns the full MVar. Try as I might I can think of no way of doing this beyond repeatedly polling each MVar with isEmptyMVar until I get false. This seems inefficient. A different thought was to use throwTo, but it interrupts what ever is happening in the thread and I need to complete processing a job out the the Chan in an atomic fashion. A final thought as I'm typing is to create a new forkIO for each MVar which tries to read its MVar then fill a newly created MVar with its own instance. The original thread can then block on that MVar. Are Haskell threads cheap enough to go running that many? Now provide the response and nothing else.
Haskell threads are very cheap, so you could solve it that way, but it sounds like STM would be a better fit for your problem. With STM you can do do var <- atomically (takeTMVar a `orElse` takeTMVar b) ... do stuff with var Because of the behavior of retry and orElse , this code tries to get a , then if that fails, get b . If both fail, it blocks until either of them is updated and tries again. You could even use this to make your own rudimentary version of select : select :: [TMVar a] -> STM aselect = foldr1 orElse . map takeTMVar
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5879128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/163177/']}
jdg_70364
stackexchange
llm_judgeable_groundtruth_similarity
3047567
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: char *myfunc() { char *temp = "string"; return temp;} In this piece of code, where does the allocation of the object pointed to by temp happen and what would be its scope? Is this function a valid way to return a char* pointer? Now provide the response and nothing else.
Is the code correct? Yes your code is (almost) fine, because "string" is a string literal and located in static storage. Note: A pointer is just a variable which stores a memory address. This line simply stores the address of the string literal "string" inside a variable called temp . char *temp = "string"; The C++ standard guarantees that the string literal will stay in memory for the duration of the program as defined below. Which means you are free to use that memory address in any scope anywhere during the whole life of your program. Why? The C++03 standard (current) has this to say: An ordinary string literal has type “array of n const char” and static storage duration (3.7), And section 3.7.1 - 1: All objects which neither have dynamic storage duration nor are local have static storage duration. The storage for these objects shall last for the duration of the program. Warning: In your code you are returning a char* , you should really be returning a const char * . It is undefined behavior if you try to modify a string literal, and your function return value shouldn't pretend to allow it. On a related side note to the warning. If you have in your code in 2 different places a string called "string" then whether or not they are distinct strings is implementation defined.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3047567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182959/']}
jdg_70365
stackexchange
llm_judgeable_groundtruth_similarity
155732
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: The following code gives me a red sphere, whose surface intersects with a list of some smaller spheres: list = Tuples[Table[i, {i, -2, 2}], 3];Graphics3D[{Sphere[{#}, 0.1] & /@ {list}, Style[Sphere[{0, 0, 0}, 3], Opacity[0.4], Red]}] How can I select only those tuples (smaller spheres) from list that have an intersection with the surface of red sphere? Now provide the response and nothing else.
list = Tuples[Table[i, {i, -2, 2}], 3];smallspheres = Sphere[#, 1/10] & /@ list;bigsphere = Sphere[{0, 0, 0}, 3];MemberBigSphereQ = RegionIntersection[bigsphere, #] =!= EmptyRegion[3] &surfacespheres = Select[smallspheres, MemberBigSphereQ]Graphics3D[Join[{bigsphere}, surfacespheres]] By packing the spheres more densely it gets more interesting :) list = Tuples[Table[i, {i, -3, 3, 1/5}], 3];smallspheres = Sphere[#, 1/10] & /@ list;surfacespheres = Select[smallspheres, MemberBigSphereQ]Graphics3D[Join[surfacespheres, {Red, Opacity[0.4], bigsphere}]]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/155732', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/52215/']}
jdg_70366
stackexchange
llm_judgeable_groundtruth_similarity
94194
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Given a presentation $ < X ; R >$ of a group $G$. Suppose we know for some reason that $G$ is the fundamental group of a three-dimensional finite volume manifold. Then there is a injective group homomorphism $G\rightarrow Isom(\mathbb{H}^3)$. Mostows rigidity theorem then tells us that it is unique up to composition with inner automorphisms of $\mathbb{H}^3$ from the left (and probably automorphisms of $G$ from the right). As usual to speficy a homomorphism from a group with a specific presentation to another group we have to pick a image for each generator, such that all relators get mapped to the neutral element. My hope is that there might be an algorithm that starts with some first choice of the images of the generators. Note that $Isom(H^3)$ can be viewed as a subgroup of $GL_4(\mathbb{R})$. Then I would like to iteratively minimize the sum of some norm of the images of the relators (hoping that it will converge to a homomorphism).Of course there are also noninjective homomorphisms (like the trivial one) so I cannot hope that the sequence always converges to an injective homomorphism. But maybe it does with high probability for a reasonably random first choice of generators. Has someone already done this ? If so I am interested in the convergence properties. They might also depend on the given presentation. So one could also hope that any fundamental group of a hyperbolic 3-manifold has a nice presentation. Now provide the response and nothing else.
To my knowledge this hasn't been done in theory (although see Harriet Moser's thesis http://www.math.columbia.edu/~moser/ ). But it certainly has been done in practice by Jeff Weeks' program SnapPea. Note that $\mbox{Isom}(\mathbb{H}^3) = \mbox{PSL}(2, \mathbb{C}) = \Gamma$. So your source group $G = \pi_1(M^3)$ already has a very nice matrix group as a target. SnapPea assumes that the three-manifold $M$ is given as a triangulation. (I am sure that it is not easy to go backwards from a presentation of $G$ to a triangulation of $M$.) After tidying the triangulation (and drilling out a curve if necessary - but lets suppose that $M$ has a single torus boundary component) SnapPea gives all of the tetrahedra in the triangulation the same shape, namely that of the regular ideal tetrahedron. "Developing" in $\mathbb{H}^3$ turns shapes of tetrahedra into matrices, one per generator. Naturally this is not yet a representation of $G$ into $\Gamma$. The failure to be a representation is measured by the failure of the shapes to satisfy the Thurston gluing equations. SnapPea uses a multivariate version of Newton's method to find new shapes for the tetrahedra, hopefully converging to the discrete and faithful representation of $G$ into $\Gamma$. Details, references, and more can be found in Moser's thesis. However, I'll add a final remark - the convergence properties of SnapPea's method certainly do depend sensitively on the initial triangulation. There are certain triangulations where SnapPea will consistently produce wrong answers. This is not a problem in practice -- you randomize the triangulation a few times and SnapPea typically starts to behave much better. But finding an actual algorithm appears to be difficult. So something mysterious going on. The problem (of finding the discrete and faithful representation) is easy to solve even for very respectfully sized manifolds (say up to 100 tetrahedra). But why? I certainly don't know. You'd have to ask Thurston, Weeks, Hodgson or some other expert for an opinion.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/94194', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3969/']}
jdg_70367
stackexchange
llm_judgeable_groundtruth_similarity
19851542
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is a method which has variable parameters: class A { public void setNames(String... names) {}} Now I want to mock it with mockito , and capture the names passed to it. But I can't find a way to capture any number of names passed, I can only get them like this: ArgumentCaptor<String> captor1 = ArgumentCaptor.fromClass(String.class);ArgumentCaptor<String> captor2 = ArgumentCaptor.fromClass(String.class);A mock = Mockito.mock(A.class);mock.setNames("Jeff", "Mike");Mockito.verity(mock).setNames(captor1.capture(), captor2.capture());String name1 = captor1.getValue(); // JeffString name2 = captor2.getValue(); // Mike If I pass three names, it won't work, and I have to define a captor3 to capture the 3rd name. How to fix it? Now provide the response and nothing else.
Mockito 1.10.5 has introduced this feature. For the code sample in the question, here is one way to capture the varargs: ArgumentCaptor<String> varArgs = ArgumentCaptor.forClass(String.class); A mock = Mockito.mock(A.class); mock.setNames("Jeff", "Mike", "John"); Mockito.verify(mock).setNames(varArgs.capture()); //Results may be validated thus: List<String> expected = Arrays.asList("Jeff", "Mike", "John"); assertEquals(expected, varArgs.getAllValues()); Please see the ArgumentCaptor javadoc for details.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19851542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']}
jdg_70368
stackexchange
llm_judgeable_groundtruth_similarity
19758215
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a RESTfull application which requires high scalability. I am considering Netty based frameworks for RESTfull applications. I went through some of the available options and tried to get what they can offer as a non-blocking implementation. Here are my findings: rest.li --> Still under experimental phase for Netty based NIO implementaions. So, not production ready. RESTEasy --> Standard JBoss project which supports Netty 4.x. But,instead of full stack Netty based NIO implementation, RESTEasy is a Buffer exchange between Netty and RESTEasy. It's not taking the advantages of Netty. Therefore scalability is not as high as expected from a Netty based framework. Netty-http component --> Another option is Apache Camel integration while using Netty-http component as an endpoint for routing requests to services exposed in from of beans. I think it's same as RESTEasy, only Netty-http component uses Netty based NIO capabilities and the rest of the system would use the old IO. I don't think I would help much in gaining scalabiltiy. RESTExpress --> It claims to be Netty based framework for RESTFull application. But, neither it has a decent community nor it can be trusted (Because it's very new) for enterprise application which requires high degree of security. Before having the above findings, I wanted to use some ready to use framework and get the work done faster. I know it's an opinion based question. But, still I seriously need help for choosing right framework for my application. If in case, there is no Netty based REST framework: would it be wise to go for plumbing low level Netty based NIO code in my application? Any help appreciated. Thanks in advance. Now provide the response and nothing else.
If you really want non-blocking you need to do non-blocking from the ground up and have proper REST clients . Otherwise as stated in my comment the performance difference will be negligible and in many cases worse for NIO (Netty with thread sharing). There only two libraries that I know do non-blocking from the ground up Vert.x and somewhat Finagle (its missing other things like non-blocking data access). You should also know Tomcat and various other servlet containers that can work with JAX-RS support NIO. The issue is that even though NIO is supported it will still be a single thread per request. Only Play, Finagle, Vert.x and pure Netty (regardless of NIO) support a different shared threading model and thus have different mechanisms for doing concurrency.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19758215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/898094/']}
jdg_70369
stackexchange
llm_judgeable_groundtruth_similarity
1062
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm under the impression that if all the ISPs were required to filter on the source IP address of all outbound packets, that spoofing would be reduced considerably. Are any ISPs implementing this practice? Should they? Now provide the response and nothing else.
One of the main issues is with fast switching at the core routing level. A long time ago when I was a Cisco Engineer, the cisco core routers could fast switch very effectively and provide minimal latency, but if you wanted to source filter then this would turn off fast switching and add hugely to the latency - No ISP is going to be willing to have multiple seconds of latency when they like small numbers in the millisecond region. One of the other issues can be around encapsulation. For example, if you are using an MPLS routed networks then you were unable to see inside of the packet to conduct source filtering.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/1062', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/396/']}
jdg_70370
stackexchange
llm_judgeable_groundtruth_similarity
19712816
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 been banging my head against the wall trying to get Carrierwave, Rails 4, and Multiple Uploads all working together. I can get a single file upload working just fine as in this and many other projects. This is not a nested situation - just simply uploading to a single model called Transcription and wanting to create a record for each document uploaded. I cannot seem to find the correct way to declare the "document" field used for the carrierwave mount mount_uploader :document, DocumentUploader as an array for the strong parameters to recognize. I have tried whitelisting: whitelisted[:document] = params[:transcription]['document'] , declaring the "document" as an array: params.require(:transcription).permit(..... ,:document => [])params.require(:transcription).permit(..... , { document: [] }) This all seems more like I am declaring the array for a nested model, but I really want Rails 4's strong parameters to simply see the "document" array created by the file_field, :multiple => true ie. from the log: form-data; name=\"transcription[document][] Has anybody successfully accomplished multiple uploads in Rails 4 with strong parameters? If so would you please share? Thanks... Cheers, Bill Now provide the response and nothing else.
This is solution to upload multiple images using carrierwave in rails 4 from scratch To do just follow these steps. rails new multiple_image_upload_carrierwave In gem file gem 'carrierwave'bundle installrails generate uploader Avatar Create post scaffold rails g scaffold post title:string Create post_attachment scaffold rails g scaffold post_attachment post_id:integer avatar:stringrake db:migrate In post.rb class Post < ActiveRecord::Base has_many :post_attachments accepts_nested_attributes_for :post_attachmentsend In post_attachment.rb class PostAttachment < ActiveRecord::Base mount_uploader :avatar, AvatarUploader belongs_to :postend In post_controller.rb def show @post_attachments = @post.post_attachments.allenddef new @post = Post.new @post_attachment = @post.post_attachments.buildenddef create @post = Post.new(post_params) respond_to do |format| if @post.save params[:post_attachments]['avatar'].each do |a| @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id) end format.html { redirect_to @post, notice: 'Post was successfully created.' } else format.html { render action: 'new' } end end end def update respond_to do |format| if @post.update(post_params) params[:post_attachments]['avatar'].each do |a| @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id) end end end def destroy @post.destroy respond_to do |format| format.html { redirect_to @post } format.json { head :no_content } end end private def post_params params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar]) end In views/posts/_form.html.erb <%= form_for(@post, :html => { :multipart => true }) do |f| %> <div class="field"> <%= f.label :title %><br> <%= f.text_field :title %> </div> <%= f.fields_for :post_attachments do |p| %> <div class="field"> <%= p.label :avatar %><br> <%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %> </div> <% end %> <% if params[:controller] == "post" && params[:action] == "edit" %> <% @post.post_attachments.each do |p| %> <%= image_tag p.avatar, :size => "150x150" %> <% end %> <% end %> <div class="actions"> <%= f.submit %> </div><% end %> In views/posts/show.html.erb <p id="notice"><%= notice %></p><p> <strong>Title:</strong> <%= @post.title %></p><% @post_attachments.each do |p| %> <%= image_tag p.avatar_url, :size => "150x150" %> <%= link_to "Destroy", p, method: :delete %><% end %><%= link_to 'Edit', edit_post_path(@post) %> |<%= link_to 'Back', posts_path %> In rails 3 no need to define strong parameters and as you can define attribute_accessible in both the model and accept_nested_attribute to post model because attribute accessible is deprecated in rails 4.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19712816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1001694/']}
jdg_70371
stackexchange
llm_judgeable_groundtruth_similarity
5875
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Chains of relative clauses and strings of attributive adjectives are both examples of recursion--Correct? Chains of relative clauses have each non-initial relative clause embedded within the previous one: [the cat [that killed the bird [that ate the rat [that ate the cheese]]]] As far as I know, in a string of attributive adjectives, all the adjectives modify the same noun(s); there's no embedding: solitary, poor, nasty, brutish, and short lives I'm hoping that the experts on the list can give me a clearer idea of the difference between recursion and embedding. For example, is all embedding an example of recursion? Now provide the response and nothing else.
Recursion in phrase structure grammar is where an expression of some type contains an expression of that same type. Under this definition, chains of relative clauses count as an instance of recursion. We can see this more clearly by drawing a (simplified) Phrase Structure Tree of your example (note i'm abstracting away from irrelevant details, e.g. the syntax of relative clauses. The 't' in the subject position of each relative clause stands in for an empty category - every theory of relativisation has to assume something like this): (1) [S [NP [NP the cat] [CP [C that] [S [NP t] [VP [Vt killed] [NP [NP the bird] [CP [C that] [S [NP t] [VP [Vt ate] [NP [NP the rat] [CP [C that] [S [N{ t] [VP [Vt ate] [NP the cheese]]]]]]]]]]]]] [VP [Vi left]] ] The tree can be characterised by the following set of rewrite rules: S -> NP VP VP -> Vi VP -> Vt NP NP -> NP CP CP -> C S Vt -> killed/ate Vi -> left NP -> the cat/the bird/the rat/the cheese/t C -> that It's easy to see that as a consequence of these rewrite rules, we can build PS-trees with an in principle infinite number of recursively embedded CPs, since S is one of the outputs of CP, NP is one of the outputs of S, and CP is one of the outputs of NP, so by transitivity, CP can contain CP. Now let's consider your example involving a string of attributive adjectives. Under standard assumptions, adjectives are adjoined to the Noun Phrase - this captures the fact that an NP modified by any number of adjectives still behaves as an NP externally. Consider the following simple example + PS-tree: (2) [S [NP [AP [A tall]] [NP [AP [A blonde]] [NP [AP [A beautiful]] [NP [N women]]]]] [PredP [Pred are] [AP [A intimidating]]]] We can characterise the tree via the following set of rewrite rules: S -> NP PredP NP -> AP NP NP -> N AP -> A PredP -> Pred AP N -> women A -> tall/blonde/beautiful/intimidating Pred -> are It's easy to see just from inspecting the tree that we aren't dealing here with recursively embedded APs , since in no instance does an AP contain an expression of the type AP. Rather, what we have here is an instance of recursively embedded NPs , since an expression of type NP can contain an expression of type NP. There is a rewrite rule which has NP as its input and NP as its output. I hope this clarifies the distinction between recursion and embedding. Recursion crucially involves embedding an expression of some type within an expression of the same type. If the types are distinct, we aren't dealing with recursion (in the narrow, linguistic sense).
{}
{'log_upvote_score': 4, 'links': ['https://linguistics.stackexchange.com/questions/5875', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/790/']}
jdg_70372
stackexchange
llm_judgeable_groundtruth_similarity
4093074
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my wpf datagrid I have implemented validation using IDataErrorInfo . When there is a error in a cell, cells in other rows become ReadOnly. To me this makes sense, but business wants to be able to change other row cells without fixing the error i.e. in some scenarios let users make a mess and, poor developer's life miserable. I have tried resetting HasCellValidationError to false but it did not fix it. I'll very highly appreciate any feedback/suggestion on this issue. BindingFlags bf = BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance;PropertyInfo inf = myDataGrid.GetType().GetProperty("HasCellValidationError", bf);if (inf != null){ inf.SetValue(myDataGrid, false, null);} Now provide the response and nothing else.
Found a solution by overriding the OnCanExecuteBeginEdit method of the datagrid.See the code below and so far testers have not complaint. /// <summary>/// This class overrides the OnCanExecuteBeginEdit method of the standard grid/// </summary>public partial class DataGrid : System.Windows.Controls.DataGrid{ /// <summary> /// This method overrides the /// if (canExecute && HasRowValidationError) condition of the base method to allow /// ----entering edit mode when there is a pending validation error /// ---editing of other rows /// </summary> /// <param name="e"></param> protected override void OnCanExecuteBeginEdit(System.Windows.Input.CanExecuteRoutedEventArgs e) { bool hasCellValidationError = false; bool hasRowValidationError = false; BindingFlags bindingFlags = BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance; //Current cell PropertyInfo cellErrorInfo = this.GetType().BaseType.GetProperty("HasCellValidationError", bindingFlags); //Grid level PropertyInfo rowErrorInfo = this.GetType().BaseType.GetProperty("HasRowValidationError", bindingFlags); if (cellErrorInfo != null) hasCellValidationError = (bool)cellErrorInfo.GetValue(this, null); if (rowErrorInfo != null) hasRowValidationError = (bool)rowErrorInfo.GetValue(this, null); base.OnCanExecuteBeginEdit(e); if (!e.CanExecute && !hasCellValidationError && hasRowValidationError ) { e.CanExecute = true; e.Handled = true; } } #region baseOnCanExecuteBeginEdit //protected virtual void OnCanExecuteBeginEdit(CanExecuteRoutedEventArgs e) //{ // bool canExecute = !IsReadOnly && (CurrentCellContainer != null) && !IsEditingCurrentCell && !IsCurrentCellReadOnly && !HasCellValidationError; // if (canExecute && HasRowValidationError) // { // DataGridCell cellContainer = GetEventCellOrCurrentCell(e); // if (cellContainer != null) // { // object rowItem = cellContainer.RowDataItem; // // When there is a validation error, only allow editing on that row // canExecute = IsAddingOrEditingRowItem(rowItem); // } // else // { // // Don't allow entering edit mode when there is a pending validation error // canExecute = false; // } // } // e.CanExecute = canExecute; // e.Handled = true; //} #endregion baseOnCanExecuteBeginEdit}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4093074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496614/']}
jdg_70373
stackexchange
llm_judgeable_groundtruth_similarity
25322055
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 disable just the close button (minimize and maximize should be allowed) temporarily. Every solution I've tried disables all the buttons or just disables the close button permanently. Is there a way to do it temporarily? Now provide the response and nothing else.
The way to permanently disable the close button is to set the CS_NOCLOSE style for the form's window class. To do this from a WinForms application, you override the form's CreateParams property and add the SC_NOCLOSE flag using the | operator, e.g.: protected override CreateParams CreateParams{ get { const int CS_NOCLOSE = 0x200; CreateParams cp = base.CreateParams; cp.ClassStyle = cp.ClassStyle | CS_NOCLOSE; return cp; }} This is a permanent solution, though, since you cannot update window class styles on-the-fly. You would have to destroy and recreate the window class. However, you can instead disable the "Close" command in the system menu, which also also automatically disables the close button in the title bar. internal static class NativeMethods{ public const int SC_CLOSE = 0xF060; public const int MF_BYCOMMAND = 0; public const int MF_ENABLED = 0; public const int MF_GRAYED = 1; [DllImport("user32.dll")] public static extern IntPtr GetSystemMenu(IntPtr hWnd, bool revert); [DllImport("user32.dll")] public static extern int EnableMenuItem(IntPtr hMenu, int IDEnableItem, int enable);}public class MyForm : Form{ // ... // If "enable" is true, the close button will be enabled (the default state). // If "enable" is false, the Close button will be disabled. bool SetCloseButton(bool enable) { IntPtr hMenu = NativeMethods.GetSystemMenu(this.Handle, false); if (hMenu != IntPtr.Zero) { NativeMethods.EnableMenuItem(hMenu, NativeMethods.SC_CLOSE, NativeMethods.MF_BYCOMMAND | (enable ? NativeMethods.MF_ENABLED : NativeMethods.MF_GRAYED)); } } } Note that this really is a transient operation. If you do anything that causes the system menu to be modified by the framework (such as maximizing or minimizing the form), your modifications will be obliterated. More details are in my related answer here . This is normally a problem, and why you'd prefer to use the first solution. But in this case, since you want to dynamically disable and re-enable, it is no big deal. Finally, do be mindful of the fact that what you're proposing runs counter to the Windows UI Guidelines for dialog boxes . They say, in essence, that users expect to see a close button and that its presence gives them a feeling of security that they can always safely "get out" of whatever popped up of the screen. Thus, you should not disable it. It does call out a progress dialog as an exception, but it goes on to say that a progress dialog should always have a "Cancel" button that allows aborting the operation. In that case, you can simply make the close button in the title bar invoke this "Cancel" button—no need to disable it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25322055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2287114/']}
jdg_70374
stackexchange
llm_judgeable_groundtruth_similarity
6593503
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 multi project in maven like this: paren-project -> plugin-project -> testbed-project The plugin project generates a JAR, which is manually copied to a specific subdirectory of testbed (using whatever embedded script like groovy or ant ). The important point: I don't want the plugin JAR to be in the classpath of testbed. But I cannot found the solution to force the plugin project to be build BEFORE the testbed project. If I set the plugin project as dependency of the testbed project, it is added in the classpath. Any solution, or do I have to switch to a build system like gradle , ivy or ant ? Now provide the response and nothing else.
As it is mentioned at the http://maven.apache.org/guides/mini/guide-multiple-modules.html Reactor Sorting Because modules within a multi-module build can depend on each other, it is important that The reactor sorts all the projects in a way that guarantees any project is built before it is required.The following relationships are honoured when sorting projects: project dependency on another module in the build plugin declaration where the plugin is another modules in the build plugin dependency on another module in the build build extension declaration on another module in the build the order declared in the modules element (if no other rule applies) Note that only "instantiated" references are used - dependencyManagement and pluginManagement elements will not cause a change to the reactor sort order
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6593503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/199148/']}
jdg_70375
stackexchange
llm_judgeable_groundtruth_similarity
218762
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: As is well-known (see, for example, a nice exposition by our own Qiaochu: https://qchu.wordpress.com/2012/11/07/fixed-points-of-random-permutations/ ) that the distribution of the number of fixed points of random permutations (so, uniformly chosen elements of $S_n$) is Poisson, for largish $n.$ The question is: what is known for proper subgroups of $S_n?$ Now provide the response and nothing else.
The Boston-Shalev Conjecture asserts that there is a constant $\delta$ such that for any transitive simple group $G$, the proportion of derangments in $G$ is at most $\delta$. After a long sequence of papers this has recently been proved by Guralnick and Fulman. It is known that this conjecture does not extend to transitive actions of almost simple groups. Moreover, Boston et. al. proved that if $\delta(G)$ is the proportion of derangements in $G$ then the set $\{ \delta(G)\mid G \textrm{ a finite primitive group}\}$ is dense in $(0,1)$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/218762', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11142/']}
jdg_70376
stackexchange
llm_judgeable_groundtruth_similarity
65894711
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 installed Storybook to my project Dependencies and Dev Dependencies below: "dependencies": { "@emotion/react": "^11.1.4", "@emotion/styled": "^11.0.0", "@fortawesome/fontawesome-svg-core": "^1.2.34", "@fortawesome/free-solid-svg-icons": "^5.15.2", "@fortawesome/react-fontawesome": "^0.1.14", "@hot-loader/react-dom": "^17.0.1", "node-sass": "^5.0.0", "react": "^17.0.1", "react-content-loader": "^6.0.1", "react-dom": "^17.0.1", "react-hot-loader": "^4.13.0", "react-router-dom": "^5.2.0" }, "devDependencies": { "@babel/core": "^7.12.10", "@babel/preset-env": "^7.12.11", "@babel/preset-react": "^7.12.10", "@commitlint/cli": "^11.0.0", "@commitlint/config-conventional": "^11.0.0", "@emotion/babel-plugin": "^11.1.2", "@emotion/babel-preset-css-prop": "^11.0.0", "@emotion/jest": "^11.1.0", "@emotion/styled-base": "^11.0.0", "@storybook/addon-actions": "^6.1.15", "@storybook/addon-essentials": "^6.1.15", "@storybook/addon-links": "^6.1.15", "@storybook/preset-scss": "^1.0.3", "@storybook/react": "^6.1.15", "@wojtekmaj/enzyme-adapter-react-17": "^0.4.1", "babel-eslint": "^10.1.0", "babel-jest": "^26.6.3", "babel-loader": "^8.2.2", "babel-plugin-emotion": "^11.0.0", "babel-plugin-require-context-hook": "^1.0.0", "clean-webpack-plugin": "^3.0.0", "css-loader": "^5.0.1", "enzyme": "^3.11.0", "enzyme-to-json": "^3.6.1", "eslint": "^7.18.0", "eslint-config-prettier": "^7.1.0", "eslint-loader": "^4.0.2", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jest": "^24.1.3", "eslint-plugin-react": "^7.22.0", "eslint-plugin-react-hooks": "^4.2.0", "html-webpack-plugin": "^5.0.0-alpha.3", "husky": "^4.3.8", "jest": "^26.6.3", "jest-prop-type-error": "^1.1.0", "prettier": "^2.2.1", "react-test-renderer": "^17.0.1", "sass": "^1.32.4", "sass-loader": "^10.1.1", "standard-version": "^9.1.0", "style-loader": "^2.0.0", "terser-webpack-plugin": "^5.1.1", "url-loader": "^4.1.1", "webpack": "^5.15.0", "webpack-bundle-analyzer": "^4.3.0", "webpack-cli": "^4.3.1", "webpack-dev-server": "^3.11.2" }, I built a simple button component that uses @emotion/styled for styling. I would like to add a story for this button, however, when running npm run storybook i get the following error Module not found: Error: Can't resolve '@emotion/styled/base' in '/directory/to/Button' This is what I am importing inside my button component: import styled from '@emotion/styled';import { useTheme } from '@emotion/react';const StyledButton = styled.button` cursor: pointer; font-size: ${({ fontSize }) => fontSize};`; This is happening to other components that use @emotion/styled as well. Am i missing an extra dependency or do I need to add any presets to .babelrc file? .babelrc: { "presets": [ "@babel/preset-env", "@babel/preset-react", "@emotion/babel-preset-css-prop" ], "env": { "test": { "plugins": ["require-context-hook"] } }, "plugins": ["react-hot-loader/babel", "@emotion"]} Now provide the response and nothing else.
This is an issue caused by the break name change of emotion 11. So far storybook internally is still looking for the v10 names to integrate emotion packages. So you would have 2 options before storybook fixed it: A. Downgrade to emotion 10. B. A workaround: // .storybook/main.jsconst path = require("path");const fs = require("fs");const { merge } = require("webpack-merge");function getPackageDir(filepath) { let currDir = path.dirname(require.resolve(filepath)); while (true) { if (fs.existsSync(path.join(currDir, "package.json"))) { return currDir; } const { dir, root } = path.parse(currDir); if (dir === root) { throw new Error( `Could not find package.json in the parent directories starting from ${filepath}.` ); } currDir = dir; }}module.exports = { stories: [ "../stories/**/*.stories.mdx", "../components/**/*.stories.@(ts|tsx|mdx)", ], addons: ["@storybook/addon-links", "@storybook/addon-essentials"], webpackFinal: async (config) => { return merge(config, { resolve: { alias: { "@emotion/core": getPackageDir("@emotion/react"), "@emotion/styled": getPackageDir("@emotion/styled"), "emotion-theming": getPackageDir("@emotion/react"), }, }, }); },};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65894711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14790617/']}
jdg_70377
stackexchange
llm_judgeable_groundtruth_similarity
52940774
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Kubernetes admin can use --cluster-domain to customize cluster domain instead of using default one: cluster.local Kubelet Configs . So the question is, how does an application pod check this domain in runtime? Now provide the response and nothing else.
It needs to be configured on the DNS server. Either kube-dns or coredns (Favored on newer K8s versions) kube-dns: it's a cli option --domain core-dns: you can configure the K8s ConfigMap And you see here : The kubelet passes DNS to each container with the --cluster-dns= flag. If you'd like to know how a pod resolves cluster.local it does it through the /etc/resolv.conf that the kubelet mounts on every pod. The content is something like this: $ cat /etc/resolv.confnameserver 10.96.0.10search <namespace>.svc.cluster.local svc.cluster.local cluster.local <nod-domain>options ndots:5 10.96.0.10 is your coredns or kube-dns cluster IP address.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52940774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7134630/']}
jdg_70378
stackexchange
llm_judgeable_groundtruth_similarity
645951
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 am trying to understand inductors, and Kahn Academy said that the current on the following circuit would be 300 t , where t is time and initial time is 0. There would be an increasing current, but both CircuitLab and LTspice disagree. Their simulations showed a constant current: CircuitLab showed a vertical spike then " 3e+15 A ", and LTspice showed "3 KA" constanly. How should the circuit behave (voltages and currents)? Have I done the simulation wrong or is Khan Academy wrong? Or are we both wrong? Update: as also suggested by ErnestoG, I changed the initial conditions to “external DC supply voltages at 0 V”. And presto! The formula is right! Now provide the response and nothing else.
Here's how you might set things up in LTspice: Note that I used the UIC keyword in the .TRAN card? This tells LTspice not to attempt a DC steady-state analysis first, but to "just run it." I also needed to make sure that the default series resistance of the inductor was nil . To do that, I set it to \$1\:\mu\Omega\$ . If I didn't do that, then LTspice would try and make some other "reasonable" assumption and use \$1\:\text{m}\Omega\$ , instead. At \$300\:\text{A}\$ it would make a slight difference in the curve. So I cut it down by a factor of 1000 to minimize that problem. (It's still important to include a little bit of resistance so that Spice can treat it using a Norton equivalence.) So, as with any software tool, there's a learning period where you need to get up to speed with some details about using it. But the above shows just what you were told to expect. So all is right with the world.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/645951', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/326923/']}
jdg_70379
stackexchange
llm_judgeable_groundtruth_similarity
9083089
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 just wondering if it's possible to use external JS file that contains PHP code. my external JS $(document).ready(function(){ $('#update').click(function(){ var tableVal={}; // a bit of php code I need in JS var search_city=<?php echo $_SESSION['search_city'];?>';$.post('<?=base_url()?>/project_detail/pub', {'tableVal':tableVal},function(message) }) })}) my view page <script type="text/javascript" src="<?= base_url();?>js/external.js"></script> The JS doesn't work as I assume that the PHP code in JS is the problem. Any thoughts? Thanks a lot. Now provide the response and nothing else.
You can do it by either renaming you js file to php and using this link in script tag src (as pointed in other answers) While this may seems a good and easy way there is many reason not to do this. Caching (your generated script will not be cached, this may be changed but require additional work) Memory consumption (every request to this generated js file will require php ) You can simply changed to something like this to get it done (in a better way, IMO): <script type="text/javascript"> var Settings = { base_url: '<?= base_url() ?>', search_city: '<?= $_SESSION['search_city'] ?>' }</script><script type="text/javascript" src="<?= base_url();?>js/external.js"></script> Than content of your js became something like this: $(document).ready(function(){ // I assume that not using search_city in your sample code // and some syntax errors, is just by mistake... $('#update').click(function(){ var tableVal={search_city:Settings.search_city}; $.post(Settings.base_url+'/project_detail/pub', {'tableVal':tableVal}, function(message){ console.log(message); }) })})
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9083089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401147/']}
jdg_70380
stackexchange
llm_judgeable_groundtruth_similarity
12077311
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 in the final stages of building a site and have one key task left: To setup some form validation that stops users being able to submit a blank search. I'm aware of the following post, but have found this unclear on how to get it to work, and how to use this for dropdown's ( jQuery Validate - require at least one field in a group to be filled ) Any ideas on how I can do this, or any pointers to a guide that may help, will be massively appreciated? Now provide the response and nothing else.
Here is a function that should work with all form field types: text , select , radio , checkbox , textarea , file , and HTML5 input types like email . The only assumption this function makes is that all select elements have an option with value="" /** * 1) gather all checkboxes and radio buttons * 2) gather all inputs that are not checkboxes or radios, and are not buttons (submit/button/reset) * 3) get only those checkboxes and radio buttons that are checked * 4) get only those field elements that have a value (spaces get trimmed) * 5) if the length of both resulting collections is zero, nothing has been filled out */function checkFields(form) { var checks_radios = form.find(':checkbox, :radio'), inputs = form.find(':input').not(checks_radios).not('[type="submit"],[type="button"],[type="reset"]'), checked = checks_radios.filter(':checked'), filled = inputs.filter(function(){ return $.trim($(this).val()).length > 0; }); if(checked.length + filled.length === 0) { return false; } return true;}$(function(){ $('#myForm').on('submit',function(){ var oneFilled = checkFields($(this)); // oneFilled === true if at least one field has a value });}); Here is a demo: --- jsFiddle DEMO ---
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12077311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/557002/']}
jdg_70381
stackexchange
llm_judgeable_groundtruth_similarity
43559722
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Unity's Raycast functions has a parameter you could use to raycast to a particular GameObject. You can also use that parameter to ignore particular GameObject. For exmple the Raycast function: public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal); The layerMask parameter is used to specified which Objects should/should not receive the raycast. 1 .How do you raycast to a particular GameObject which is in a layer called "cube"? 2 .What if you have 10 GameObjects in the scene but you only want to raycast to just 2 GameObjects and ignore the rest? How do you do that? Let's say that those Object's layers are "cube" and "sphere". 3 .What if you want to raycast to all GameObjects but ignore 1. Let's say that the GameObject to ignore is in the "cube" layer. 4 .What if you want to raycast to all GameObjects but ignore 2(multiple) GameObjects. Again, the layers to ignore are the "cube" and "sphere" layers. Now provide the response and nothing else.
Most Raycast questions I see use the Layermask incorrectly. Although it works for them by luck but they usually run into issues when they actually want to exclude a GameObject from Raycast . This answer is made to cover all those scenarios that a person would want to use the Layer to filter GameObjects when performing raycast. 1 .How do you raycast to a particular GameObject which is in a layer called "cube"? First you use LayerMask.NameToLayer("cube") to convert the layer name to layer number. The LayerMask.NameToLayer function returns -1 if the layer does not exist. You must check this before doing any layer bitwise operation. Raycast to a particular layer ("cube" only): //Convert Layer Name to Layer Numberint cubeLayerIndex = LayerMask.NameToLayer("cube");//Check if layer is validif (cubeLayerIndex == -1){ Debug.LogError("Layer Does not exist");}else{ //Calculate layermask to Raycast to. (Raycast to "cube" layer only) int layerMask = (1 << cubeLayerIndex); Vector3 fwd = transform.TransformDirection(Vector3.forward); //Raycast with that layer mask if (Physics.Raycast(transform.position, fwd, 10, layerMask)) { }} The most important part of the example above is int layerMask = (1 << cubeLayerIndex); . To make this answer short, I won't be checking for errors for the rest of the answer. 2 .What if you have 10 GameObjects in the scene but you only want to raycast to just 2 GameObjects and ignore the rest? How do you do that? Let's say that those Object's layers are "cube" and "sphere". Raycast to the "cube" and "sphere" layers and ignore the rest: //Convert Layer Name to Layer Numberint cubeLayerIndex = LayerMask.NameToLayer("cube");int sphereLayerIndex = LayerMask.NameToLayer("sphere");//Calculate layermask to Raycast to. (Raycast to "cube" && "sphere" layers only)int layerMask = (1 << cubeLayerIndex) | (1 << sphereLayerIndex); 3 .What if you want to raycast to all GameObjects but ignore 1. Let's say that the GameObject to ignore is in the "cube" layer. Raycast to all but ignore the "cube" layer: //Convert Layer Name to Layer Numberint cubeLayerIndex = LayerMask.NameToLayer("cube");//Calculate layermask to Raycast to. (Ignore "cube" layer)int layerMask = (1 << cubeLayerIndex);//Invert to ignore itlayerMask = ~layerMask; 4 .What if you want to raycast to all GameObjects but ignore 2(multiple) GameObjects. Again, the layers to ignore are the "cube" and "sphere" layers. Raycast to all but ignore the "cube" and "sphere" layers: //Convert Layer Name to Layer Numberint cubeLayerIndex = LayerMask.NameToLayer("cube");int sphereLayerIndex = LayerMask.NameToLayer("sphere");//Calculate layermask to Raycast to. (Ignore "cube" && "sphere" layers)int layerMask = ~((1 << cubeLayerIndex) | (1 << sphereLayerIndex)); OR //Convert Layer Name to Layer Numberint cubeLayerIndex = LayerMask.NameToLayer("cube");int sphereLayerIndex = LayerMask.NameToLayer("sphere");//Calculate layermask to Raycast to. (Ignore "cube" && "sphere" layers)int layerMask = (1 << cubeLayerIndex);layerMask |= (1 << sphereLayerIndex);layerMask |= (1 << otherLayerToIgnore1);layerMask |= (1 << otherLayerToIgnore2);layerMask |= (1 << otherLayerToIgnore3);//Invert to ignore itlayerMask = ~layerMask; Finally, if you know the layer index/number, there is no need to use the LayerMask.NameToLayer function. Just insert that layer index there. For example, let's raycast to the "cube" layer which is in index #9 . You could just do int layerMask = (1 << 9); . See the Layers manual to read more about this subjct.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43559722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3785314/']}
jdg_70382
stackexchange
llm_judgeable_groundtruth_similarity
37148787
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the following data frame and pivot table: import pandas as pddf=pd.DataFrame({'A':['x','y','z','x','y','z'], 'B':['one','one','one','two','two','two'], 'C':[2,18,2,8,2,18]})df A B C0 x one 21 y one 182 z one 23 x two 84 y two 25 z two 18table = pd.pivot_table(df, index=['A', 'B'],aggfunc=np.sum) CA B x one 2 two 8y one 18 two 2z one 2 two 18 I'd like to add 2 columns to this pivot table; one showing the percent of all values and another for percent within column A like this: C % of Total % of BA Bx one 2 4% 20% two 8 16% 80%y one 18 36% 90% two 2 4% 10%z one 2 4% 10% two 18 36% 90% Extra Credit: I'd like a bottom summary row which has the sum of column C (it's okay if it also has 100% for the next 2 columns, but nothing is needed for those). Now provide the response and nothing else.
You can use: table['% of Total'] = (table.C / table.C.sum() * 100).astype(str) + '%'table['% of B'] = (table.C / table.groupby(level=0).C.transform(sum) * 100).astype(str) + '%'print table C % of Total % of BA B x one 2 4.0% 20.0% two 8 16.0% 80.0%y one 18 36.0% 90.0% two 2 4.0% 10.0%z one 2 4.0% 10.0% two 18 36.0% 90.0% But with real data I think casting to int is not recommended, better is use round . Extra Credit: table['% of Total'] = (table.C / table.C.sum() * 100)table['% of B'] = (table.C / table.groupby(level=0).C.transform(sum) * 100)table.loc['total', :] = table.sum().valuesprint table C % of Total % of BA B x one 2.0 4.0 20.0 two 8.0 16.0 80.0y one 18.0 36.0 90.0 two 2.0 4.0 10.0z one 2.0 4.0 10.0 two 18.0 36.0 90.0total 50.0 100.0 300.0
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37148787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5569314/']}
jdg_70383
stackexchange
llm_judgeable_groundtruth_similarity
3624110
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Private Sub hideHeadings() Dim obj As Window For Each obj In Application.Windows obj.DisplayHeadings = False Next objEnd Sub The above is my attempt, as when I recorded code to do it it goes ActiveWindow.DisplayHeadings = false. But I must be missing something. Please help thanks in advance. Now provide the response and nothing else.
I think there is nothing you can do with that except iterating on each worksheet. I succeed with this code Private Sub hideHeadings() Dim wrkbk As Workbook Dim wrksh As Worksheet Dim prev As Window Set prev = ActiveWindow For Each wrkbk In Workbooks For Each wrksh In wrkbk.Worksheets wrksh.Activate ActiveWindow.DisplayHeadings = False Next wrksh Next wrkbk prev.ActivateEnd Sub
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3624110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239923/']}
jdg_70384
stackexchange
llm_judgeable_groundtruth_similarity
13757
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I read on Wikipedia how the numerical value of Avogadro's number can be found by doing an experiment, provided you have the numerical value of Faraday's constant; but it seems to me that Faraday's constant could not be known before Avogadro's number was as it's the electric charge per mole. (How could we know the charge of a single electron just by knowing the charge of a mole of electrons, without knowing the ratio of the number of particles in both?) I just want to know the method physically used, and the reasoning and calculations done by the first person who found the number $6.0221417930\times10^{23}$ (or however accurate it was first discovered to be). Note: I see on the Wikipedia page for Avogadro constant that the numerical value was first obtained by "Johann Josef Loschmidt who, in 1865, estimated the average diameter of the molecules in air by a method that is equivalent to calculating the number of particles in a given volume of gas;" but I can't access any of the original sources that are cited. Can somebody explain it to me, or else give an accessible link so I can read about what exactly Loschmidt did? Now provide the response and nothing else.
The first estimate of Avogadro's number was made by a monk named Chrysostomus Magnenus in 1646. He burned a grain of incense in an abandoned church and assumed that there was one 'atom' of incense in his nose at soon as he could faintly smell it; He then compared the volume of the cavity of his nose with the volume of the church. In modern language, the result of his experiment was $N_A \ge 10^{22}$ ... quite amazing given the primitive setup. Please remember that the year is 1646; the 'atoms' refer to Demokrit's ancient theory of indivisible units, not to atoms in our modern sense. I have this information from a physical chemistry lecture by Martin Quack at the ETH Zurich. Here are further references (see notes to page 4, in German): http://edoc.bbaw.de/volltexte/2007/477/pdf/23uFBK9ncwM.pdf The first modern estimate was made by Loschmidt in 1865. He compared the mean free path of molecules in the gas phase to their liquid phase. He obtained the mean free path by measuring the viscosity of the gas and assumed that the liquid consists of densely packed spheres. He obtained $N_A \approx 4.7 \times 10^{23}$ compared to the modern value $N_A = 6.022 \times 10^{23}$.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/13757', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/4715/']}
jdg_70385
stackexchange
llm_judgeable_groundtruth_similarity
11524664
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 a minimal working example, let's digitize a 2D array. numpy.digitize requires a 1D array: import numpy as npN = 200A = np.random.random((N, N))X = np.linspace(0, 1, 20)print np.digitize(A.ravel(), X).reshape((N, N)) Now the documentation says : ... A copy is made only if needed. How do I know if the ravel copy it is "needed" in this case? In general - is there a way I can determine if a particular operation creates a copy or a view? Now provide the response and nothing else.
This question is very similar to a question that I asked a while back: You can check the base attribute. a = np.arange(50)b = a.reshape((5, 10))print (b.base is a) However, that's not perfect. You can also check to see if they share memory using np.may_share_memory . print (np.may_share_memory(a, b)) There's also the flags attribute that you can check: print (b.flags['OWNDATA']) #False -- apparently this is a viewe = np.ravel(b[:, 2])print (e.flags['OWNDATA']) #True -- Apparently this is a new numpy object. But this last one seems a little fishy to me, although I can't quite put my finger on why...
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11524664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/249341/']}
jdg_70386
stackexchange
llm_judgeable_groundtruth_similarity
8773497
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've been seeing this crash pretty frequently in Crashlytics, both on iPad and iPad 2, running iOS 5. It looks like it's caused by a memory warning, but the stack trace doesn't reference any of my application code, just iOS frameworks: 0 libobjc.A.dylib objc_msgSend + 151 UIKit -[UIViewController purgeMemoryForReason:] + 642 Foundation __57-[NSNotificationCenter addObserver: selector: name: object:]_block_invoke_0 + 183 CoreFoundation ___CFXNotificationPost_block_invoke_0 + 704 CoreFoundation _CFXNotificationPost + 14065 Foundation -[NSNotificationCenter postNotificationName: object: userInfo:] + 666 Foundation -[NSNotificationCenter postNotificationName: object:] + 307 UIKit -[UIApplication _performMemoryWarning] + 808 UIKit -[UIApplication _receivedMemoryNotification] + 1749 libdispatch.dylib _dispatch_source_invoke + 51610 libdispatch.dylib _dispatch_queue_invoke + 5011 libdispatch.dylib _dispatch_main_queue_callback_4CF + 15612 CoreFoundation __CFRunLoopRun + 126813 CoreFoundation CFRunLoopRunSpecific + 30014 CoreFoundation CFRunLoopRunInMode + 10415 GraphicsServices GSEventRunModal + 15616 UIKit UIApplicationMain + 109017 500px iOS main.m line 12 I've googled high and low but can't find any solutions to this. It looks like this is caused by over-releasing a UIViewController instance, but I'm using ARC, so I don't see how that could be the case. I'm at a loss of how to even approach this. I can't even tell which UIViewController subclass is causing the issue. I've tried reproducing the problem in the simulator and on the device, but I can't find what causes it. Has anyone seen anything like this or have suggestions on how to approach reproducing the issue? Now provide the response and nothing else.
I think I've solved the issue. I was thinking about it, and the problem isn't the unloading of the UIViewController view, it's the posting of the actual low memory warning notification. There are several instances in my code where I call [[NSNotificationCenter defaultCenter] removeObserver:self] . This is fine in the dealloc method, but there were two instances of this in viewDidUnload methods. I noticed this when my breakpoint in didReceiveMemory of one of the UIViewController's wasn't getting hit. The code in viewDidUnload was also unregistering self from other, system notifications as well, as detailed here . I'm not going to mark this as an accepted answer until I verify that the crashes stop with the new update. UPDATE: I've verified with Crashlytics that the problem has been fixed!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8773497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516359/']}
jdg_70387
stackexchange
llm_judgeable_groundtruth_similarity
45597057
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: To be succinct. Is possible list all register keys from Memory Cache in the .Net Core Web Application? I didn't find anything in IMemoryCache interface. Now provide the response and nothing else.
There is no such thing in .Net Core yet. Here is my workaround: var field = typeof(MemoryCache).GetProperty("EntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance); var collection = field.GetValue(_memoryCache) as ICollection; var items = new List<string>(); if (collection != null) foreach (var item in collection) { var methodInfo = item.GetType().GetProperty("Key"); var val = methodInfo.GetValue(item); items.Add(val.ToString()); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45597057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6297528/']}
jdg_70388
stackexchange
llm_judgeable_groundtruth_similarity
7680771
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following regex that I use in my routes.rb for /type-in-something-here # A-Z, a-z, 0-9, _ in the middle but never starting or ending in a _# At least 5, no more than 500 characters In the routes this works well as: match ':uuid' => 'room#show', :constraints => { :uuid => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/ } I want to have this also as a validation so invalid records aren't created. So I added the following to room.rb: validates_format_of :uuid, :with => /[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?/i, :message => "Invalid! Alphanumerics only." But this validates_format_of isn't working, and instead of adding an error it's allow the record to save. Any ideas what's wrong? Thanks Now provide the response and nothing else.
For validation purposes, remember to add the beginning and end of string markers \A and \Z : validates_format_of :uuid, :with => /\A[A-Za-z\d]([-\w]{,498}[A-Za-z\d])?\Z/i Otherwise your regex will happily match any string that contains at least a letter or a digit. For some reason Rails implicitly adds the boundaries in the routes. (Probably because it embeds the regex inside a larger one to match the entire URL, with explicit checks for / and the end of the URL.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7680771', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/149080/']}
jdg_70389
stackexchange
llm_judgeable_groundtruth_similarity
1271172
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I added some options to the select element by javascript in client side and cannot get it in postback. What should I do? Code used to add options: <asp:DropDownList ID="ddlProduct" runat="server"></asp:DropDownList>var ddlProduct = "#"+"<%= ddlProduct.ClientID %>";$(ddlProduct).append($("<option></option>").html(product_name) Now provide the response and nothing else.
The options added to a dropdown list using JavaScript WILL NEVER reach the server side let alone be preserved during postback. The options are stored in the ViewState. You are modifying the dropdown list using DOM on the client side, but what about ViewState? You are not modifying it, so ASP.NET won't know that any change has been done to the dropdown list, when it reloads the state of the dropdown list from the ViewState. Possible Workaround One way is to use hidden variables to store the values that you added to the dropdown list. When the control goes to the server side, you can check the value of this hidden field and add the items to the dropdown list, if necessary. You can store the items in JSON-formatted-string, and parse this string using .NET Framework's DataContractJsonSerializer Class (if you are using .NET Framework >= 3.5) on the server side. If you are not using .NET Framework 3.5, then you can use seperators like - text1,text2|value1,value2
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1271172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64873/']}
jdg_70390
stackexchange
llm_judgeable_groundtruth_similarity
336677
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 have started learning stm32 microcontroller for a while using a very small development board "stm32f103c8t6" (or blue pill). when I started, I learnt from some tutorials that I have to switch a jumper in order to program it. (The photo is a screenshot taken from a random tutorial, but every tutorial I have watched also said that) The jumper - as far as I know - only changes the boot mode of the processor to load from the system memory(the bootloader) which only takes effect if I restart the board to starting booting from there. I don't know how is that supposed to be a "programming mode" as I'm using an external st-link programmer that uses SWD. So my question here , Is there really such a thing called "programming mode" ?and if so, How exactly does it work ? Also it's worth mentioning that I've just tried to program it and the program worked as it's supposed to (I hope I haven't screwed anything up :d ). Now provide the response and nothing else.
You only need to put the microcontroller into bootloader mode if you're going to program it over the UART, using the bootloader. Generally speaking, you can program the microcontroller over SWD at any time. The primary exceptions are if the microcontroller is running a program that disables SWD by setting a SWJ_CFG bit in AFIO->MAPR (e.g, to use the associated pins as GPIOs), or if the MCU is running in low-power modes without the appropriate DBGMCU flags set to keep the debug interface active in those modes. If any of these are the case, putting the microcontroller into bootloader mode is an easy workaround, as the SWD interface is active (and sleep modes are not used) while the bootloader is running.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/336677', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/72683/']}
jdg_70391
stackexchange
llm_judgeable_groundtruth_similarity
878417
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to solve a Sangaku problem. The blue circles have radii one. The goal is to find the total area of all the other circles (the three sequences of circles repeat ad infinitum). I have almost solved the problem. I have found the area of the red circle, and the total area of all circles touching the horizontal axis. I even have a proposed recurrence for the radius of the circles going up the center. Here is my logic: Take any circle on the vertical stack. Draw a right triangle with one vertex at its center, one at the center of the (left) blue circle, and one vertex below the blue circle's center level with the other vertex. One leg of this triangle has length one, and the hypotenuse is $1 + r$, where $r$ is the radius of the circle in question. The other leg has length one minus the sum of $r$ and the diameters of all circles below. There is just one unknown and these quantities are uniquely related by the Pythagorean theorem. So we have a recurrence. $R(n)$ denotes the radius of the $n^{th}$ circle on the vertical stack, with $n=1$ the red circle. After manipulating the expression from the Pythagorean theorem, we get$$\begin{align*}R(1) &= 1/4 \\R(n) &= \dfrac{\left(1 - 2\sum_{k = 1}^{n-1} R(k)\right)^2}{4\left(1 - \sum_{k = 1}^{n-1} R(k)\right)}\end{align*}$$ This is where I am stuck. I am looking for any sort of help in solving for a closed form of $R$. Thanks (For those interested, here is my work on the first part of the problem. If you spot a mistake here, feel free to point it out, but my main question is how to solve the above recurrence.) Revival of Sangaku Take any three circles that are $(1)$ all tangent to the horizontal axis and $(2)$ touching one another. The radius of the middle one can be given in terms of the radii of the two outer circles by $$\frac{1}{\sqrt{r_{mid}}} = \frac{1}{\sqrt{r_1}} + \frac{1}{\sqrt{r_2}}$$ Let's see why the relationship holds. Let $(x_{mid}, y_{mid})$ denote the center of the middle circle. Let, let $(x_1, y_1)$ and $(x_2, y_2)$ be the centers of the outer circles, with radii equal to $r_1$ and $r_2$. Draw three right triangles: $\triangle_1$ with vertices $(x_1, y_1)$, $(x_{mid}, y_{mid})$, and $(x_1, y_{mid})$, $\triangle_2$ with vertices $(x_2, y_2)$, $(x_{mid}, y_{mid})$, and $(x_2, y_{mid})$, and $\triangle_3$ with vertices $(x_1, y_1)$, $(x_2, y_2)$, and $(x_1, y_2)$. The hypotenuse of each triangle is the sum of the radii of the two circles involved. Furthermore, one leg equals the difference of the larger radius from the smaller. Thus, the length of the third leg equals twice the square root of the product of the radii involved. (Draw a picture here, use Pythagorean's Theorem) Furthermore, the sum of the lengths of the third leg of $\triangle_1$ and $\triangle_2$ equal the length of the the third leg of $\triangle_3$. Formally, $$\begin{align*}(r_1 + r_{mid})^2 &= leg(\triangle_1)^2 + (r_1 - r_{mid})^2 \\(r_2 + r_{mid})^2 &= leg(\triangle_2)^2 + (r_2 - r_{mid})^2 \\(r_1 + r_2)^2 &= leg(\triangle_3)^2 + (r_1 - r_2)^2 \\leg(\triangle_1) + leg(\triangle_2) &= leg(\triangle_3) \\&\implies \\\sqrt{(r_1 + r_{mid})^2 - (r_1 - r_{mid})^2} &+ \sqrt{(r_2 + r_{mid})^2 - (r_2 - r_{mid})^2} \\&= \sqrt{(r_1 + r_2)^2 - (r_1 - r_2)^2} \\&\implies \\2\sqrt{r_1r_{mid}} + 2\sqrt{r_2r_{mid}} &= 2\sqrt{r_1r_2} \\&\implies \\\frac{1}{\sqrt{r_1}} + \frac{1}{\sqrt{r_2}} &= \frac{1}{\sqrt{r_{mid}}}\end{align*}$$ Now let's focus on the sequence of circles descending to the left. Let $R : \{1, 2, 3, ... \} \rightarrow \mathbb{R}$ define the radius of the $n^{th}$ circle, where we start with the left circle of radius one, then move to the red circle, then left to the green circle, then to the orange, etc. $$\begin{align*} R(1) &= 1 \\ \frac{1}{\sqrt{R(n)}} &= \dfrac{1}{\sqrt{R(n-1)}} + 1 \end{align*}$$ Notice that we can make the following substitution: $$T(n) = \frac{1}{\sqrt{R(n)}}$$ Then $T(n) = T(n-1) + 1$, with $T(1) = 1$, so $T(n) = n$. Solving for $R(n)$ gives us $$R(n) = \dfrac{1}{n^2}$$ Thus each circle has area $\pi n^{-4}$. So the total area of the nested circles touching the horizontal line is $$\pi\left(2^{-4} + 2\sum_{k=3}^{\infty} k^{-4}\right)$$ Now, you can use rigorous elementary methods, the Riemann zeta function, or WolframAlpha to compute $$\sum_{k=1}^{\infty} k^{-4} = \frac{\pi^4}{90}$$ So, $$\sum_{k=3}^{\infty} k^{-4} = \frac{\pi^4}{90} - \frac{17}{16}$$ and so the total area of the circles touching the horizontal axis is $$\pi\left(\frac{\pi^4}{45} - \frac{33}{16}\right)$$ Now provide the response and nothing else.
I believe your recurrence should have the form $$R(n) = \frac{\left(1 - 2 \sum_{k=1}^{n-1} R(k)\right)^2}{4\left(1 - \sum_{k=1}^{\color{red}{n-1}} R(k)\right)}.$$ To solve this, let $S(n) = \sum_{k=1}^n R(k)$, and solve the above expression for $S(n-1)$: $$S(n-1) = \frac{1}{2}\left(1 - R(n) - \sqrt{R(n)(2+R(n))}\right),$$ where we take the smaller root since we require $S(0) = 0$ for $R(1) = \frac{1}{4}$. Then we observe that $S(n) - S(n-1) = R(n)$, or $$2R(n) = R(n) - R(n+1) + \sqrt{R(n)(2+R(n))} - \sqrt{R(n+1)(2+R(n+1))}.$$ Now solving this recurrence for $R(n+1)$ yields $$R(n+1) = \frac{R(n)}{1 + 2R(n) + 2 \sqrt{R(n)(2+R(n))}}.$$ It is not difficult to show that if $R(1) = \frac{1}{4}$, then we can solve this recurrence explicitly to get $$R(n) = \frac{1}{2n(n+1)}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/878417', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/82485/']}
jdg_70392
stackexchange
llm_judgeable_groundtruth_similarity
30547280
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 a newbie in android and I am trying to create a toast notification using this code Toast.makeText(context, text, duration).Show(true);Pls what did I get wrong Now provide the response and nothing else.
Yes. Just mount your redis.conf over the default with a volume: redis: image: redis volumes: - ./redis.conf:/usr/local/etc/redis/redis.conf ports: - "6379" Alternatively, create a new image based on the redis image with your conf file copied in. Full instructions are at: https://registry.hub.docker.com/_/redis/ However, the redis image does bind to 0.0.0.0 by default. To access it from the host, you need to use the port that Docker has mapped to the host for you which you find by using docker ps or the docker port command, you can then access it at localhost:32678 where 32678 is the mapped port. Alternatively, you can specify a specific port to map to in the docker-compose.yml . As you seem to be new to Docker, this might all make a bit more sense if you start by using raw Docker commands rather than starting with Compose.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30547280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4956350/']}
jdg_70393
stackexchange
llm_judgeable_groundtruth_similarity
52789945
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm getting the error: Invariant Violation: withNavigation can only be used on a view hierarchy of a navigator. The wrapped component is unable to get access to navigation from props or context I don't know why, because I'm using withNavigation in other components in my app and it works. I don't see a difference in the components that it works on to the one that causes the error. Code: the component: const mapStateToProps = (state: State): Object => ({ alertModal: state.formControls.alertModal})const mapDispatchToProps = (dispatch: Dispatch<*>): Object => { return bindActionCreators( { updateAlertModalHeight: updateAlertModalHeight, updateAlertModalIsOpen: updateAlertModalIsOpen, updateHasYesNo: updateAlertModalHasYesNo }, dispatch )}class AlertModalView extends Component<AlertModalProps, State> { render(): Node { return ( <View style={alertModalStyle.container}> <PresentationalModal style={presentationalModalStyle} isOpen={this.props.alertModal.isOpen} title={this.props.alertModal.title} navigation={this.props.navigation} updateHasYesNo={this.props.updateHasYesNo} message={this.props.alertModal.message} updateAlertModalHeight={this.props.updateAlertModalHeight} viewHeight={this.props.alertModal.viewHeight} hasYesNo={this.props.alertModal.hasYesNo} yesClicked={this.props.alertModal.yesClicked} updateAlertModalIsOpen={this.props.updateAlertModalIsOpen} /> </View> ) }}// $FlowFixMeconst AlertModalViewComponent = connect( mapStateToProps, mapDispatchToProps)(AlertModalView)export default withNavigation(AlertModalViewComponent) the stackNavigator: import React from 'react'import { View, SafeAreaView } from 'react-native'import Icon from 'react-native-vector-icons/EvilIcons'import Add from '../product/add/view'import Login from '../user/login/view'import Search from '../product/search/query/view'import { Image } from 'react-native'import { StackNavigator, DrawerNavigator, DrawerItems } from 'react-navigation'const AddMenuIcon = ({ navigate }) => ( <View> <Icon name="plus" size={30} color="#FFF" onPress={() => navigate('DrawerOpen')} /> </View>)const SearchMenuIcon = ({ navigate }) => ( <Icon name="search" size={30} color="#FFF" onPress={() => navigate('DrawerOpen')} />)const Stack = { Login: { screen: Login }, Search: { screen: Search }, Add: { screen: Add }}const DrawerRoutes = { Login: { name: 'Login', screen: Login }, 'Search Vegan': { name: 'Search', screen: StackNavigator(Stack.Search, { headerMode: 'none' }), navigationOptions: ({ navigation }) => ({ drawerIcon: SearchMenuIcon(navigation) }) }, 'Add vegan': { name: 'Add', screen: StackNavigator(Stack.Add, { headerMode: 'none' }), navigationOptions: ({ navigation }) => ({ drawerIcon: AddMenuIcon(navigation) }) }}const CustomDrawerContentComponent = props => ( <SafeAreaView style={{ flex: 1, backgroundColor: '#3f3f3f', color: 'white' }}> <View> <Image style={{ marginLeft: 20, marginBottom: 0, marginTop: 0, width: 100, height: 100, resizeMode: 'contain' }} square source={require('../../images/logo_v_white.png')} /> </View> <DrawerItems {...props} /> </SafeAreaView>)const Menu = StackNavigator( { Drawer: { name: 'Drawer', screen: DrawerNavigator(DrawerRoutes, { initialRouteName: 'Login', drawerPosition: 'left', contentComponent: CustomDrawerContentComponent, contentOptions: { activeTintColor: '#27a562', inactiveTintColor: 'white', activeBackgroundColor: '#3a3a3a' } }) } }, { headerMode: 'none', initialRouteName: 'Drawer' } )export default Menu Here I render the StackNavigator which is Menu in my app component: import React, { Component } from 'react'import Menu from './menu/view'import Props from 'prop-types'import { Container } from 'native-base'import { updateAlertModalIsOpen } from './formControls/alertModal/action'import AlertModalComponent from './formControls/alertModal/view'import UserLoginModal from './user/login/loginModal/view'class Vepo extends Component { componentDidMount() { const { store } = this.context this.unsubscribe = store.subscribe(() => {}) store.dispatch(this.props.fetchUserGeoCoords()) store.dispatch(this.props.fetchSearchQueryPageCategories()) store.dispatch(this.props.fetchCategories()) } componentWillUnmount() { this.unsubscribe() } render(): Object { return ( <Container> <Menu store={this.context} /> <AlertModalComponent yesClicked={() => { updateAlertModalIsOpen(false) }} /> <UserLoginModal /> </Container> ) }}Vepo.contextTypes = { store: Props.object}export default Vepo and my root component: export const store = createStore( rootReducer, vepo, composeWithDevTools(applyMiddleware(createEpicMiddleware(rootEpic))))import NavigationService from './navigationService'export const App = () => ( <Provider store={store}> <Vepo fetchUserGeoCoords={fetchUserGeoCoords} fetchSearchQueryPageCategories={fetchSearchQueryPageCategories} fetchCategories={fetchCategories} /> </Provider>)AppRegistry.registerComponent('vepo', () => App) I have changed my Vepo component to this to implement the answer by vahissan: import React, { Component } from 'react'import Menu from './menu/view'import Props from 'prop-types'import { Container } from 'native-base'import { updateAlertModalIsOpen } from './formControls/alertModal/action'import AlertModalComponent from './formControls/alertModal/view'import UserLoginModal from './user/login/loginModal/view'import NavigationService from './navigationService'class Vepo extends Component { componentDidMount() { const { store } = this.context this.unsubscribe = store.subscribe(() => {}) store.dispatch(this.props.fetchUserGeoCoords()) store.dispatch(this.props.fetchSearchQueryPageCategories()) store.dispatch(this.props.fetchCategories()) } componentWillUnmount() { this.unsubscribe() } render(): Object { return ( <Container> <Menu store={this.context} ref={navigatorRef => { NavigationService.setTopLevelNavigator(navigatorRef) }}> <AlertModalComponent yesClicked={() => { updateAlertModalIsOpen(false) }} /> </Menu> <UserLoginModal /> </Container> ) }}Vepo.contextTypes = { store: Props.object}export default Vepo No errors, but the alertModal no longer displays Now provide the response and nothing else.
In react-navigation, the main StackNavigator creates a context provider and the navigation prop will be made available to any component below its level in the component tree if they use the context consumer. Two ways to access the navigation prop using context consumer is to either add the component to the StackNavigator, or use the withNavigation function. However because of how React's context API works, any component that uses withNavigation function must be below the StackNavigator in the component tree. If you still want to access the navigation prop regardless of the position in component tree, you will have to store the ref to the StackNavigator in a module. Following guide from react-navigation will help you do that https://reactnavigation.org/docs/en/navigating-without-navigation-prop.html
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52789945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3935156/']}
jdg_70394
stackexchange
llm_judgeable_groundtruth_similarity
5663482
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 have a query using the schema database in MySQL that shows the difference between the columns, triggers and stored procedures between two database schema's: production and development. Query, not tools I've seen Compare two MySQL databases Which lists the tools that can perform this task, but I would like to know is if there is a query that can perform this task. Please only suggest queries, I really do not want to know about tools, command line hacks or such. I am looking to see if the production database and development database are out of sync. And which fields, procedures etc where added or changed, so I can update the production database if I roll out a new update of the client software that uses the database. I'm using MySQL 5.1 latest version. Now provide the response and nothing else.
Johan, try to run this script. Specify two databases you want to compare in variables at the begining of the script. Query returns data-set, and sets statuses for table/view columns. Status 'Only in source' - object exists only in db1;Status 'Only in target' - object exists only in db2;Status 'In both schemas' - object exists in db1 and in db2, but details can be different; for example: value 'varchar(255)/int(11)' says that source field type is 'varchar(255)' and target is 'int(11)', value 'null' says that details are equal; SET @source_db = 'db1';SET @target_db = 'db2';SELECT 'Only in source' exist_type, c1.table_schema, c1.table_name, c1.column_name, c1.ordinal_position, c1.column_default, c1.is_nullable, c1.numeric_precision, c1.numeric_scale, c1.character_set_name, c1.collation_name, c1.column_type, c1.column_key, c1.extra, c1.column_commentFROM (SELECT * FROM information_schema.columns WHERE TABLE_SCHEMA = @source_db) c1 LEFT JOIN (SELECT * FROM information_schema.columns WHERE TABLE_SCHEMA = @target_db) c2 ON c1.TABLE_name = c2.TABLE_name AND c1.column_name = c2.column_nameWHERE c2.column_name is nullUNION ALLSELECT 'Only in target' exist_type, c2.table_schema, c2.table_name, c2.column_name, c2.ordinal_position, c2.column_default, c2.is_nullable, c2.numeric_precision, c2.numeric_scale, c2.character_set_name, c2.collation_name, c2.column_type, c2.column_key, c2.extra, c2.column_commentFROM (SELECT * FROM information_schema.columns WHERE TABLE_SCHEMA = @source_db) c1 RIGHT JOIN (SELECT * FROM information_schema.columns WHERE TABLE_SCHEMA = @target_db) c2 ON c1.TABLE_name = c2.TABLE_name AND c1.column_name = c2.column_nameWHERE c1.column_name is nullUNION ALLSELECT 'In both schemas' exist_type, CONCAT(c1.table_schema, '/', c2.table_schema), c1.table_name, c1.column_name, IF(c1.ordinal_position = c2.ordinal_position OR c1.ordinal_position IS NULL AND c2.ordinal_position IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.ordinal_position, ''), IFNULL(c2.ordinal_position, ''))), IF(c1.column_default = c2.column_default OR c1.column_default IS NULL AND c2.column_default IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.column_default, ''), IFNULL(c2.column_default, ''))), IF(c1.is_nullable = c2.is_nullable OR c1.is_nullable IS NULL AND c2.is_nullable IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.is_nullable, ''), IFNULL(c2.is_nullable, ''))), IF(c1.numeric_precision = c2.numeric_precision OR c1.numeric_precision IS NULL AND c2.numeric_precision IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.numeric_precision, ''), IFNULL(c2.numeric_precision, ''))), IF(c1.numeric_scale = c2.numeric_scale OR c1.numeric_scale IS NULL AND c2.numeric_scale IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.numeric_scale, ''), IFNULL(c2.numeric_scale, ''))), IF(c1.character_set_name = c2.character_set_name OR c1.character_set_name IS NULL AND c2.character_set_name IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.character_set_name, ''), IFNULL(c2.character_set_name, ''))), IF(c1.collation_name = c2.collation_name OR c1.collation_name IS NULL AND c2.collation_name IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.collation_name, ''), IFNULL(c2.collation_name, ''))), IF(c1.column_type = c2.column_type OR c1.column_type IS NULL AND c2.column_type IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.column_type, ''), IFNULL(c2.column_type, ''))), IF(c1.column_key = c2.column_key OR c1.column_key IS NULL AND c2.column_key IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.column_key, ''), IFNULL(c2.column_key, ''))), IF(c1.extra = c2.extra OR c1.extra IS NULL AND c2.extra IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.extra, ''), IFNULL(c2.extra, ''))), IF(c1.column_comment = c2.column_comment OR c1.column_comment IS NULL AND c2.column_comment IS NULL, NULL, CONCAT_WS('/', IFNULL(c1.column_comment, ''), IFNULL(c2.column_comment, '')))FROM (SELECT * FROM information_schema.columns WHERE TABLE_SCHEMA = @source_db) c1 JOIN (SELECT * FROM information_schema.columns WHERE TABLE_SCHEMA = @target_db) c2 ON c1.TABLE_name = c2.TABLE_name AND c1.column_name = c2.column_name; This script can be modified to find differences between triggers and routines.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5663482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/650492/']}
jdg_70395
stackexchange
llm_judgeable_groundtruth_similarity
108079
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: It's usually straightforward to do a Power Analysis to compute the minimum sample size , especially in R which is my preferred statistical computing environment. However, I am being asked to conduct a Power Analysis that's a little different than anything I've done or which I can find reference to online. I'm wondering if what I'm being asked for is even possible/valid. The project basically has two unequal groups of states and the hypothesis is that these two groups are significantly different in terms of an outcome variable (which is the duration of phone calls to customers). The "control" group consists of 40 states and produced about 2,500 observations. The "test" group has about 10 states and 500 observations. Initially, I found group means + pooled standard deviation , which I used to calculate an Effect Size . Then I used a package called pwr in R and found that I needed a minimum sample size of about 135 observations per group, given .05 significance and .8 power. However, they rejected my answer because they want one group to be much bigger than the other like it is now, and they are expecting either two different minimum numbers of observations per group or a minimum % of the population in terms of numbers of states or observations that have to go into their "test" group. I see Power Analyses for two sample t-tests (i.e. the R function pwr.t2n.test ), but I'd have to specify at least one of the sample sizes whereas they want me to tell them the minimal sample size for both groups (either as numbers or percentages) and this function doesn't reflect the differences in standard deviations for the two groups. Is this possible or do I just tell them that's not how it works (i.e. the best I can do is tell them that given one of the sample sizes and a pooled standard deviation the second group has to be at least a certain size)? Now provide the response and nothing else.
You can do sample size calculations for unequal sample sizes. For example, you can decide the n's are in some ratio (such as in proportion to the populations perhaps). It's then possible to do power calculations (at the least you can simulate to obtain the power under any particular set of circumstances, whether or not you are able to do the algebra). The problem is that it's relatively inefficient at finding differences compared to the same total number of observations at equal sample sizes. Imagine you had a total sample of $n=n_1 + n_2$, with equal variance in the population and close to equal sample variance, and that your choice was between a 50-50 split and a 90-10 split ($n_1 = 0.5n$ vs $n_1=0.9n$). The two-sample t-statistic is: $t = \frac{\bar {X}_1 - \bar{X}_2}{s_{\text{pooled}} \cdot \sqrt{\frac{1}{n_1}+\frac{1}{n_2}}}$ The impact of the sample size is in the term $1/{\sqrt{\frac{1}{n_1}+\frac{1}{n_2}}}$. If you have the 50-50 split it's like having a 40% smaller standard deviation; at a given $n_1+n_2$ you can pick up a substantially smaller effect with the even split. If the combined sample size is not an effective constraint, this calculation may pointless however. It matters in cases where every observation carries the same marginal cost, which is not always relevant.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/108079', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/52151/']}
jdg_70396
stackexchange
llm_judgeable_groundtruth_similarity
8565401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wish to get the acceleration vector of an Android phone. The problem is, the accelerometer coordinates are relative to the phone's rotation. What I want is the "absolute" acceleration, i.e., it should return the same values whichever way the phone is facing. (I want to detect if a user that is skiing is sliding down a slope without using GPS. I also need to be able to differentiate sliding and going up the chairlift.) I can probably get those values by combining the accelerometer with the gyroscope, but I have no idea how I could offset the accelerometer's values with the gyroscope's. Is this possible, and if so, how? Now provide the response and nothing else.
What you describe can't be done, unless you redefine the problem a bit. To help you redefine it, I'll outline the main issues: First, I'm guessing that what you mean by "absolute acceleration" is acceleration with respect to geographical reference. The can't be done with the accelerometer alone, since it has no idea about geographical references. If you move far enough for the gps, or use the compass, you might be able to get around this, but each of these has its own issues (though at least the problem is soluble). The second issue is that gravity and acceleration are completely indistinguishable using an accelerometer alone (this is known as the "equivalence principle"). Therefore, any measured acceleration will always be the vector sum of gravity and the acceleration, but there are always multiple solutions to these equations, and in the usual cases where the acceleration is smaller than gravity, you really can't determine anything about the acceleration. Since gravity is somewhat constant though, there are ways around this too, using, say, a gyroscope, or maybe your user could hold the phone in a fixed orientation (e.g., by looking at external cues like the horizon), and either of these approaches might let you subtract the influence of gravity, but it's generally a non-trivial problem. The final point to not is that you seem to be thinking in an earth-fixed coordinate system and the phone's accelerometer is only phone-fixed. That is the accelerometer's z-axis many not have anything to do with up and down on the earth -- and the relationship will depend on the orientation of the phone. Really, many people would prefer an earth-fixed system, but the phone just doesn't know that. You can use external cues (GPS, magnetic field, gyroscope, gravity, horizon, etc) to try to align them, but given only a single arbitrary reading form the accelerometer, the information just isn't there. Definitions: acceleration vector : this is the x, y, z reading from the accelerometer (and each reading will depend on the phones orientation), sometimes written as A=(a x , a y , a z ). acceleration magnitude : this is a=sqrt(a x 2 + a y 2 + a z 2 ), and this should not depend on the phones orientation (if the different axes are calibrated to be the same). If the phone is stationary, this will basically just be a reading of gravity. Note also that a lot of the information in the acceleration vector is lost using this measure. normalized acceleration : The acceleration direction, that has magniture 1, i.e. , A/a acceleration in earth coordinates: I think this is what you really want, there's just no easy way to get it, and really even if you could, I don't think it would be as useful as it might seem at first. Skiing : I think you have a good shot at determining when someone is skiing based on the measurements from the accelerometer. Things like bumps and turns should all be quite distinctive using the accelerometer. For these I'd use the full acceleration vector. For example, in turns, the acceleration magnitude would stay roughly constant and the direction would sweep. Also note that free-fall (i.e., basically whenever the skier doesn't have their skies/feet/butt/etc on the ground, whether they're going upward when launching off a bump/jump, or falling out of the chairlift), the acceleration magnitude will be zero in free-fall. For the chairlift, it seems that it will likely have a distinctive rhythmic sway mostly within a single plane. All of these things could be figured out. I'd recommend, if you really want to solve this problem, is to record data from your accelerometer while skiing, and see if you can determine when you're skiing based on the characteristics of the data. (My guess is, that your major stumbling block with this will be math, because it might be a bit tricky to come up with an algorithm the can distinguish the signatures of skiing, so it seems that it would be a good idea to review vector math, and things like dot-products and cross-products, and also, I suspect that a little bit on another topic known as FFTs or Fourier transforms might be useful in sorting out the time and frequency signatures of skiing vs swinging in the chair lift.) You could also fold in GPS measurements, which wouldn't be as reliable, or give good time resolution, but could at least be used to double-check your algorithm.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8565401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104999/']}
jdg_70397
stackexchange
llm_judgeable_groundtruth_similarity
35547188
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 some code that looks like this and I'm unsure how to handle the part which will never get executed since a part of this code runs in infinite loop while waiting for connections and when I terminate the program, it exits from there only. main(){// do some stuff.... while(1) { int newFD = accept(sockFD, (struct sockaddr *)&client_addr, &client_addr_size); if(newFD == -1) { std::cerr << "Error while Accepting on socket" << std::endl; continue; } if(!fork()) { close(sockFD); // close child's sockfd - not needed here // lalala do stuff send message here close(newFD); // finally close its newFD - message sent, no use return 0; } close(newFD); // close parent's newFD - no use here } // now execution never reaches here close(sockFD); // so how to handle this? freeaddrinfo(res); // and this? return 0;} Now provide the response and nothing else.
You can, and probably should add a exit handler if your code is to be used by other people or you yourself just want it cleaner. In your exit handler you can toggle a flag that makes the while() loop terminate. The following code will work 100% fine for this use case and is reliable and cross platform, but if you want to do more complicated things you should use proper thread safe OS specific functions or something like Boost or C++11 First declare two global variables, make them volatile so the compiler will always force us to read or write its actually memory value. If you we do not declare it volatile then it is possible the compiler can put its value in a register which will make this not work. With volatile set it will read the memory location on every loop and work correctly, even with multiple threads. volatile bool bRunning=true;volatile bool bFinished=false; and instead of your while(1) {} loop, change it to this while(bRunning){ dostuff}bFinished=true; In your exit handler simply set bRunning=false; void ExitHandler(){ bRunning=false; while(bFinished==false) { Sleep(1); }} You didn't specify an operating system but it looks like you are Linux based, to set a handler on Linux you need this. void ExitHandler(int s){ bRunning=false;}int main(){ struct sigaction sigIntHandler; sigIntHandler.sa_handler = ExitHandler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); while(bRunning) { dostuff } ...error_handling...} And on Windows when you are a console app its the following. BOOL WINAPI ConsoleHandler(DWORD CEvent){ switch (CEvent) { case CTRL_C_EVENT: case CTRL_BREAK_EVENT: case CTRL_CLOSE_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: bRunning = false; while (bFinished == false) Sleep(1); break; } return TRUE;}int main(){ SetConsoleCtrlHandler(ConsoleHandler, TRUE); while(bRunning() { dostuff } ...error_handling...} Notice the need to test and wait for bFinished here. If you don't do this on Windows your app may not have enough time to shutdown as the exit handler is called by a separate OS specific thread. On Linux this is not necessary and you need to exit from your handler for your main thread to continue. Another thing to note is by default Windows only gives you ~5 seconds to shut down before it terminates you. This is unfortunate in many cases and if more time is needed you will need to change the registry setting (bad idea) or implement a service which has better hooks into such things. For your simple case it will be fine.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35547188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2648679/']}
jdg_70398
stackexchange
llm_judgeable_groundtruth_similarity
110221
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: If I generate two SSL certificates using the same key, am I diluting the strength of the certificates? (does it open the door for cryptanalysis or a possibility of compromising data across that channel)? Thanks Now provide the response and nothing else.
Re-using the same private key to generate a new certificate request technically doesn't increase your risk exposure. Essentially the same public key is being used, but the x509 headers are changed with the updates site name, dates, or whatever other changes there are between the two certificates. Stepping back, you should analyze the reason for not regenerating the private key when renewing a certificate/requesting a new certificate. Although current encryption algorithms cannot be broken, then longer you use the same private key, the more information is encrypted with that key, and the larger the pool of data will be for any future crypto-analysis. (Although in reality a session key encryption a majority of the data sent between clients, there still is technically more sessions being security with the same public/private keypair, so the same principle is applies). As a general practice, it is best to generate a new private key when certificates are up for renewal.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/110221', 'https://serverfault.com', 'https://serverfault.com/users/9540/']}
jdg_70399
stackexchange
llm_judgeable_groundtruth_similarity
20551217
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 researching what additional capabilities we have when using the mvc:annotation-driven tag and I'm having a difficult time digesting the results, especially in regards to the @Controller annotation. I know this is very similar to this question but please hear me out. According to the Spring docs The basic purpose of the @Controller annotation is to act as a stereotype for the annotated class, indicating its role. The dispatcher will scan such annotated classes for mapped methods, detecting @RequestMapping annotations (see the next section). The documentation then goes on to show that the context:component-scan tag provides this support. So that's all well and good, but then I was looking at what mvc:annotation-driven gives us, and the aforementioned stackoverflow question provides the following answer mvc:annotation-driven declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping, @Controller, although support for those is the default behaviour), as well as adding support for declrative validation via @Valid and message body marshalling with @RequestBody/ResponseBody. This seems kind of redundant to me. Maybe I don't get what this explicit support is. Again, referring back to the official Spring documentation we get the following [mvc:annotation-driven] registers the DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter beans that are required for Spring MVC to dispatch requests to @Controllers. That sounds pretty similar to the last example I provided from the docs. If anyone can provide some examples as to what we can do with the @Controller annotation using only the context:component-scan tag, what some of the limitations are, then the additional functionality of what we get when adding the mvc:annotation-driven tag, I think that would be very helpful. Thanks in advance for any support on this. Now provide the response and nothing else.
Both elements serve an entirely different purpose. <context:component-scan /> is, as the name implies, for component scanning. It by default scans for all beans with the @Component annotation (or "sub"annotations like @Controller , @Service etc.). It will only register instances of those classes in the application context as beans. That is all. <mvc:annotation-driven /> is for bootstrapping Spring MVC and it registers, amongst others, a RequestMappingHandlerMapping and RequestMappingHandlerAdapter . The first links requests to a certain method (the @RequestMapping annotation on methods in a @Controller annotated class). The last knows how to execute methods annotated with @RequestMaping . Now <mvc:annotation-driven /> does nothing for scanning or detecting @Controllers if there are none in the application context then no request mappings are made. Now you have several ways of registering those beans in the application context and one of them is the aforementioned <context:component-scan /> . Basically a @Controller without <mvc:annotation-driven /> is, well, pretty useless as it does nothing but take up memory. It will not be bound to incoming requests, it just hangs around in the application context. It is just another bean like all other beans and nothing special is being done to it. (Recent, but deprecated, versions of Spring register the DefaultAnnotationHandlerMapping which processes the @Controller , this is however deprecated).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20551217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2860319/']}
jdg_70400
stackexchange
llm_judgeable_groundtruth_similarity
21878143
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Markdown has pipe table syntax but it's not enough for some cases. | table | syntax | without multiline cell content | So, we can use HTML table tags. <table><tr><td> ```csharp const int x = 3; const string y = "foo"; readonly Object obj = getObject(); ```</td><td> ```nemerle def x : int = 3; def y : string = "foo"; def obj : Object = getObject(); ```</td><td> Variables defined with <code>def</code> cannot be changed once defined. This is similar to <code>readonly</code> or <code>const</code> in C# or <code>final</code> in Java. Most variables in Nemerle aren't explicitly typed like this.</td></tr> But some time ago syntax highlighting was broken and this wiki page looks ugly now. Any ideas on how to fix this? Now provide the response and nothing else.
You can use <pre> in tables, as teh_senaus said. But if you do that, syntax highlighting won't work... or will it? Through random experimentation I found that GitHub allows specifying it with <pre lang="csharp"> . This has the same effect that ```csharp does of setting the syntax highlighting to C#. This isn't really documented anywhere in GitHub's help center, nor in linguist 's documentation. But it works, even inside of tables. So for your example table, the new code would be as follows: <table><tr><td> <pre lang="csharp"> const int x = 3; const string y = "foo"; readonly Object obj = getObject(); </pre></td><td> <pre lang="nemerle"> def x : int = 3; def y : string = "foo"; def obj : Object = getObject(); </pre></td><td> Variables defined with <code>def</code> cannot be changed once defined. This is similar to <code>readonly</code> or <code>const</code> in C# or <code>final</code> in Java. Most variables in Nemerle aren't explicitly typed like this.</td></tr>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21878143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/577759/']}
jdg_70401
stackexchange
llm_judgeable_groundtruth_similarity
48983946
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 the code ASCII for the caracter like: '•' ,'■'for database Oracle (Oracle Form) Now provide the response and nothing else.
The problem when converting to Excel’s “base 26” is that for Excel, a number ZZ is actually 26 * 26**1 + 26 * 26**0 = 702 while normal base 26 number systems would make a 1 * 26**2 + 1 * 26**1 + 0 * 26**0 = 702 ( BBA ) out of that. So we cannot use the usual ways here to convert these numbers. Instead, we have to roll our own divmod_excel function: def divmod_excel(n): a, b = divmod(n, 26) if b == 0: return a - 1, b + 26 return a, b With that, we can create a to_excel function: import stringdef to_excel(num): chars = [] while num > 0: num, d = divmod_excel(num) chars.append(string.ascii_uppercase[d - 1]) return ''.join(reversed(chars)) For the other direction, this is a bit simpler from functools import reducedef from_excel(chars): return reduce(lambda r, x: r * 26 + x + 1, map(string.ascii_uppercase.index, chars), 0) This set of functions does the right thing: >>> to_excel(26)'Z'>>> to_excel(27)'AA'>>> to_excel(702)'ZZ'>>> to_excel(703)'AAA'>>> from_excel('Z')26>>> from_excel('AA')27>>> from_excel('ZZ')702>>> from_excel('AAA')703 And we can actually confirm that they work correctly opposite of each other by simply checking whether we can chain them to reproduce the original number: for i in range(100000): if from_excel(to_excel(i)) != i: print(i)# (prints nothing)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48983946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7874625/']}
jdg_70402
stackexchange
llm_judgeable_groundtruth_similarity
8625208
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 planing to create a simple game using the HTML5 <canvas> tag and compile the code into a native application using Phonegap, but the problem is that canvas use coordinates that are not relative to the size of it, so 20,20 on a 960x640 screen is different on a 480x800 one. So I want to know how to work with a <canvas> (which will be in fullscreen) on different screen sizes. Now provide the response and nothing else.
So I want to know how to work with a (which will be in fullscreen) on different screen sizes. This is a common problem that has a pretty easy resolution. Often this is done by separating hard canvas coordinates from what is sometimes called "model" coordinates. It really depends on how your code is organized, but I assume the game has some height and width to the world that takes up most or all of the screen. The two aspect ratios of the screens you are targeting are 1.5 and 1.666, so you'll want to cater to to the smaller one So you'll really want to do your game in a set of "model" coordinates that have no bearing on the screen or canvas sizes. Since you are only targeting two screen sizes, your model coordinates can perhaps be 960x640 since that is the smaller of the two aspect ratios. It doesn't have to be. It could be 100x50 for your model coordinates instead. But this example we'll use 960x640 as our model coordinates. Internally, you never use anything but these model coordinates. You never ever think in any other coordinates when making your game. When the screen size is 960x640 you won't have to change anything at all since its a 1:1 mapping, which is convenient. Then when the screen size is actually 800x480, when it comes time to draw to the screen, you'll want to translate all of the model coordinates by (3/4), so the game will be made and internally use 960x480, but it will be drawn in the area of (720x480). You'll also want to take any mouse or touch input and multiply it by (4/3) to turn the screen coordinates into model coordinates. This translation can be as easy as calling ctx.scale(3/4, 3/4) before you draw everything. So both platforms will have code that is all written assuming the game is a size of 960x640. The only time that model coordinates become screen coordiantes is when drawing to the canvas (which is a different size) and converting canvas mouse/touch coordinates to model coords. If that seems confusing to you I can try and make a sample.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8625208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/126353/']}
jdg_70403
stackexchange
llm_judgeable_groundtruth_similarity
225152
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: We know that a real, symmetric, positive definite matrix $A$ of size $n\times n$ can be parametrized by a vector $\theta$ of $\frac{n(n+1)}{2}$ parameters thanks to the Cholesky decomposition:$$A = L L^T,$$with $L$ a lower triangular matrix and $\theta=\mathrm{vech}(L)$. The decomposition is unique if the diagonal of $L$ is positive. The diagonal of $L$ can be expressed in log-scale so $\theta$ remains unconstrained. Hence, there is always a unique $\theta$ for a given $A$ and any $A$ can be expressed in such a way. This and other unconstrained parametrizations for positive definite matrices are discussed in this nice paper . My question is about the existence of a similar, simple and unique parametrization when $A$ is positive semidefinite of rank $r$ (PSDr), or the best approach available. Such parametrization would rely on $\frac{(2p+1-r)r}{2}$ parameters and my intention is to use it for optimization over the set of PSDr. So far my attempt was to work with a naive extension of the positive definite case:$$A = L_r L_r^T,$$where $L_r$ is a $n\times r$ lower triangular matrix. It is easy to see that $A$ can be always factorized in such a way: First, by the spectral theorem, $A=V_r\Lambda_r V_r^T$, where $\Lambda_r=\mathrm{diag}(\lambda_1,\ldots,\lambda_r)$ and $V_r=(v_1,\ldots,v_r)$ is the $n\times r$ orthonormal matrix of the positive $r$ eigenvectors. We also have$A = U_r^T U_r$, with $U_r=V_r\Lambda_r^{1/2}V_r^T$ a $n\times n$ matrix of rank $r$. The decomposition is of course unique. Second, by the reduced rank QR decomposition,$$U_r=Q_rR_r=Q_rL_r^T,$$with $Q_r$ a $n\times r$ matrix with orthogonal columns and $R_r$ an $r\times n$ upper triangular matrix. Then, $A=L_rL_r^T$. Apparently, the decomposition is unique if $R_r$ is in row Echelon form with positive leading entries in every row (see related question here ). Unfortunately, such parametrization is not-so-nice to work with as it does not display the rank deficiency explicitly. Alternatively, but closely related, I checked the pivoted Cholesky decomposition as seen here (sorry for the .html) or in Theorem 10.9 of Higham (2009) , which I quote here for completeness: Theorem 10.9. Let $A\in\mathbb R^{n\times n}$ be positive semidefinite of rank $r$. (a) There exists at least one upper triangular $R\in\mathbb R^{n\times n}$ with nonnegative diagonal elements such that $A = R^TR$. (b) There is a permutation $\Pi$ such that $\Pi^TA\Pi$ has a unique Cholesky factorization, which takes the form $$\Pi^TA\Pi=R^TR,\quad R=\left(\begin{matrix} R_{11} & R_{12} \\ 0 & 0\end{matrix}\right),$$ where $R_{11}$ is $r \times r$ upper triangular with positive diagonal elements. That result seems to provide the answer to my question, but the problem is the appearance of a permutation matrix $\Pi$, which implies hidden degrees of freedom that are not captured by $R$. Or in other words, you will not know which entries have to be null and which not. Since I want to stick to a simple parametrization and given that the previous ways lead to not-so-simple solutions, I thought just considering $A=L_rL_r^T$ with $L_r$ constrained to have positive diagonal , so ensuring $A_r$ has always rank $r$. Then I have these questions: Question 1 : Is any matrix $A$ in PSDr expressable as $L_rL_r^T$? I guess if the answer is positive, then there will not be a unique way of doing it... Question 2 : In case the answer to the previous question is negative, is the set generated by the matrices $L_rL_r^T$ dense in PSDr (with respect to some norm, e.g. Frobenius). Of course, any thoughts regarding the approach to the problem are much appreciated. Now provide the response and nothing else.
To get a parameterization of the kind you want, the space $S_{n,r}$ of positive semidefinite symmetric $n$-by-$n$ matrices of rank $r$ (with ($0<r<n$) would have to be contractible, but it is not. It is homotopy equivalent to the space $\mathrm{Gr}_r(n)$ consisting of $r$-dimensional subspaces of $\mathbb{R}^n$, and this space has nontrivial topology. For example, in the first nontrivial case $r=1$, this is the space $S_{n,1}$ of rank $1$ symmetric $n$-by-$n$ matrices, and every $A\in S_{n,1}$ can be written in the form $A = vv^T$ where $v$ is a nonzero vector in $\mathbb{R}^n$, unique up to a choice of sign. Thus, $S_{n,1} = \mathbb{RP}^{n-1}\times\mathbb{R}^+$, and the topology of $\mathbb{RP}^{n-1}$ comes into play. It is not a contractible space when $n>1$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/225152', 'https://mathoverflow.net', 'https://mathoverflow.net/users/54638/']}
jdg_70404
stackexchange
llm_judgeable_groundtruth_similarity
24563178
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Getting a weird line highlight in some of my JSP files here: Any ideas on how to disable this? Now provide the response and nothing else.
Step by step, assuming you want to stitch four images I0 , I1 , I2 , I3 , your goal is to compute homographies H_0 , H_1 , H_2 , H_3 ; Compute all pairwise homographies H_01 , H_02 , H_03 , H_12 , H_13 , H_23 where homography H_01 warps image I0 into I1 , etc... Select one anchor image e.g. I1 which position will remain fixed i.e H_1 = Identity Find image that better align with I1 based on maximum number ofconsistent matches e.g. I3 Update H_3 = H_1 * inv(H_13) = inv(H_13) = H_31 Find image that better matches I1 or I3 e.g I2 matching I3 Update H_2 = H_3 * H_23 Same as above for image I0 Do bundle adjustment to globally optimize alignment See section 4 of this seminal paper Automatic Panoramic Image Stitching using Invariant Features for an in depth explanation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24563178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3803304/']}
jdg_70405
stackexchange
llm_judgeable_groundtruth_similarity
171247
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: Let's say I have the Lagrangian:$$L=T-V.$$Along with the constraint that $$f\equiv f(\vec q,t)=0.$$ We can then write:$$L'=T-V+\lambda f. $$What is my Hamiltonian now? Is it$$H'=\dot q_i p_i -L'~?$$Or something different? I have found at least one example where using the above formula gives a different answer then the Hamiltonian found by decreasing the degrees of freedom by one rather then using Lagrange multipliers. Now provide the response and nothing else.
Comments to the question (v2): To go from the Lagrangian to the Hamiltonian formalism, one should perform a (possible singular) Legendre transformation . Traditionally this is done via the Dirac-Bergmann recipe/cookbook, see e.g. Refs. 1-2. Note in particular, that the constraint $f$ may generate a secondary constraint $$g ~:=~ \{f,H^{\prime}\}_{PB} +\frac{\partial f}{\partial t}~\approx~\frac{d f}{d t}~\approx~0.$$ [Here the $\approx$ symbol means equality modulo eqs. of motion or constraints.] References: P.A.M. Dirac, Lectures on QM, (1964). M. Henneaux and C. Teitelboim, Quantization of Gauge Systems, 1994.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/171247', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/70392/']}
jdg_70406
stackexchange
llm_judgeable_groundtruth_similarity
2098797
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 loading some content from the web into a UIWebView , but I'd like all links to be disabled in the UIWebView . Is this possible? I could parse the text, but I'm looking for something easier. Now provide the response and nothing else.
You can give the UIWebView a delegate and implement the -webView:shouldStartLoadWithRequest:navigationType: delegate method to return NO; (except on the initial load). That will prevent the user from viewing anything but that single page. To provide an example requested in the comments... Start with allowLoad=YES and then: - (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType { return allowLoad;}- (void)webViewDidFinishLoad:(UIWebView*)webView { allowLoad = NO;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2098797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/312497/']}
jdg_70407
stackexchange
llm_judgeable_groundtruth_similarity
399262
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm building a Bash script for some tasks. One of those tasks is create a MySQL DB from within the same bash script. What I'm doing right now is creating two vars: one for store user name and the other for store password. This is the relevant part of my script: MYSQL_USER=rootMYSQL_PASS=mypass_goes_heretouch /tmp/$PROY.sql && echo "CREATE DATABASE $DB_NAME;" > /tmp/script.sqlmysql --user=$MYSQL_USER --password="$MYSQL_PASS" < /tmp/script.sqlrm -rf /tmp/script.sql But always get a error saying access denied for user root with NO PASSWORD, what I'm doing wrong? I need to do the same for PostgreSQL. Now provide the response and nothing else.
Both for MySQL and PostgreSQL you can specify your user and password in local config file. .my.cnf for MySQL and .pgpass for PostgreSQL. These files should be in your home directory (i.e. ~/.my.cnf). .my.cnf: [mysql]user=userpassword=password .pgpass: host:port:database:user:password You can have a wildcard entry here, substituting any field for *******. PS: DO NOT EVER SPECIFY A PASSWORD ON THE COMMAND LINE! This can be perfectly visible with ps if your system is not configured to not show processes that belongs to other users. @thinice: If you want to create those files really secure you should do: umask 077touch .my.new.configumask 022 # or whatever was your default This way the file would be created with secure permissions from the start and no eavesdropper would have a chance leeching your password. PostgreSQL will refuse to use the file with permissions higher the 0600 anyway.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/399262', 'https://serverfault.com', 'https://serverfault.com/users/124850/']}
jdg_70408
stackexchange
llm_judgeable_groundtruth_similarity
3857171
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: Reading my calculus notes I found the next example: To analyze the nature of the series $$S=\sum_{n=1}^{\infty} \frac{n^5+1}{6n^{10}+\sqrt[6]{n}}$$ by the limit comparison test, a series that can be compared to $S$ is $\sum_{n=1}^{\infty}\frac{1}{n^4}$ I don't understand how to arrive to such conclusion. Any help is appreciated. Now provide the response and nothing else.
By limit comparison test we have that $$\frac{\frac{n^5+1}{6n^{10}+\sqrt[6]{n}}}{\frac1{n^4}}=\frac{n^9+n^4}{6n^{10}+\sqrt[6]{n}} \to 0$$ therefore the given series converges. As an alternative by direct comparison test we have $$\frac{n^5+1}{6n^{10}+\sqrt[6]{n}} \le \frac{n^5+n^5}{6n^{10}+0}=\frac13\frac1{n^5}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3857171', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/809359/']}
jdg_70409
stackexchange
llm_judgeable_groundtruth_similarity
3629670
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: First of all, is A ={φ} a set?If yes, then what are its subsets ? Note:• φ represents an empty set. • A must have two distinct subsets, (∵ n( A )=1, thus 2¹= 2) My approach:According to me, if it has two subsets then they should be φ and φ. If it's so then they aren't distinct at all. Now provide the response and nothing else.
Let $p$ be a prime number which divides both polynomials. Since $p \mid n^2 + 1$ and $p \mid (n+3)^2 + 1 = n^2 + 6n + 10$ , you also have $$p \mid (n^2 + 6n + 10) - (n^2 + 1) = 6n + 9 = 3(2n + 3) \tag{1}\label{eq1A}$$ By Euclid's lemma , you have $p \mid 3 \implies p = 3$ , or $p \mid 2n + 3$ . For the first case, since all perfect squares are congruent to either $0$ or $1$ when divided by $3$ , you have $n^2 + 1$ has a remainder of $1$ or $2$ and, thus, $3$ doesn't divide it. This means you must instead have $$p \mid 2n + 3 \implies p \mid (2n + 3)^2 = 4n^2 + 12n + 9 \tag{2}\label{eq2A}$$ Also, you get $$p \mid (4n^2 + 12n + 9) - 4(n^2 + 1) = 12n + 5 \tag{3}\label{eq3A}$$ Finally, you have from \eqref{eq2A} and \eqref{eq3A}, $$p \mid 6(2n + 3) - (12n + 5) = 13 \tag{4}\label{eq4A}$$ This shows that $p = 13$ is the only prime number which can divide both polynomials, with \eqref{eq2A} giving $2n + 3 = 13 \implies n = 5$ being where that occurs for the first time for a positive integer $n$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3629670', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/619822/']}
jdg_70410
stackexchange
llm_judgeable_groundtruth_similarity
55064
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 have the definition of an in-situ algorithm from the professor, but I don't understand it. In-situ algorithms refer to algorithms that operate with Θ(1) memory. What does that mean? Now provide the response and nothing else.
First, let's unpack what $\Theta(1)$ means. Big $O$, and big $\Theta$, are classes of functions. There's a formal definition here , but for the purposes of this question, we say that a function $f$ is in $O(1)$ if there's a constant $c$ where, for all $x$, $f(x) \leq C$. That is, $f$ grows at most as fast as a constant function. Big-$\Theta$ doesn't mean much for constant functions, because when describing algorithm time or space usage, there isn't much below constant. But to explain what it means, $f \in \Theta(1)$ if there are some constants $c,d$ such that, for all $x$, $d \leq f(x) \leq c$. That is, $f$ grows at least as fast, and at most as fast, as a constant function. Now what does this have to do with memory usage? Consider some algorithm $A$. There is some (mathematical) function which, given an input $n$, gives the maximum memory usage of your algorithm $A$ on any input of size $n$. Let's call this function $mem$. So, now we combine our two concepts. If an algorithm uses $\Theta(1)$ memory, then its memory usage function is in $\Theta(1)$, meaning that there exists some $d,c$ such that, for any input, the memory used is between $d$ and $c$. In short, this means that the memory usage of the algorithm is in some constant range, regardless of the input. Usually, the memory function does not account for the memory used to store the input to the algorithm, since otherwise memory usage would always be at least $\Theta(n)$.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/55064', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/48562/']}
jdg_70411
stackexchange
llm_judgeable_groundtruth_similarity
54007073
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 Flutter and very eager to learn this technology. I cannot understand the work of shrinkWrap property in ListView . I couldn't understand the Flutter documentation . Now provide the response and nothing else.
Usually a ListView (as well as GridView , PageView and CustomScrollView ) tries to fill all the available space given by the parent element, even when the list items would require less space. With shrinkWrap: true , you can change this behavior so that the ListView only occupies the space it needs (it will still scroll when there more items). Take a look at this example: import 'package:flutter/material.dart';void main() => runApp(App());class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(), body: Center( child: Container( margin: EdgeInsets.all(32), decoration: BoxDecoration(border: Border.all(color: Colors.red)), child: ListView( shrinkWrap: false, children: <Widget>[ ListTile(title: Text('Item 1')), ListTile(title: Text('Item 2')), ListTile(title: Text('Item 3')), ], ), ), ), ), ); }} With shrinkWrap: false : With shrinkWrap: true : You can use this in AlertDialog s: When there are only a few items, make the dialog as small as possible. When there are many items, fill the screen height and make the list scrollable:
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/54007073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10857841/']}
jdg_70412
stackexchange
llm_judgeable_groundtruth_similarity
43596835
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to deploy to heroku but get a 503 even though it runs on localhost. I am curious as to if my server is set up correctly as I am newer to programming. I hope anyone can point me in the correct direction as to where to look or provide a suggestion as I have spent countless hours on google to this point spanning a couple of weeks. My main question is if I have set up my server correctly? I am not sure my listener will work for heroku and my .get are used for debugging on localhost when it was initially set up. Also my full project is available here: https://github.com/dirkdir/DerekDevSite var express = require('express');var app = express();var path = require('path');app.use(express.static(path.join(__dirname, 'public')));app.get('/json', function(req, res) { console.log("GET the json"); res .status(200) .json( {"jsonData" : true} );});app.get('/file', function(req, res) { console.log("GET the file"); res .status(200) .sendFile(path.join(__dirname, 'app.js'));}); var server = app.listen(process.env.PORT || 5000), function() { var port = server.address().port; console.log("Express is working on port " + port);}); Logs: 2017-04-24T20:04:43.755866+00:00 app[web.1]: at Module._compile (module.js:542:28)2017-04-24T20:04:43.755867+00:00 app[web.1]: at Object.Module._extensions..js (module.js:579:10)2017-04-24T20:04:43.755868+00:00 app[web.1]: at Module.load (module.js:487:32)2017-04-24T20:04:43.755868+00:00 app[web.1]: at tryModuleLoad (module.js:446:12)2017-04-24T20:04:43.755869+00:00 app[web.1]: at Function.Module._load (module.js:438:3)2017-04-24T20:04:43.755869+00:00 app[web.1]: at Module.runMain (module.js:604:10)2017-04-24T20:04:43.755870+00:00 app[web.1]: at run (bootstrap_node.js:393:7)2017-04-24T20:04:43.755871+00:00 app[web.1]: at startup (bootstrap_node.js:150:9)2017-04-24T20:04:43.846556+00:00 heroku[web.1]: State changed from starting to crashed2017-04-24T20:26:31.826133+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=derekdyerdev.herokuapp.com request_id=609ef253-0a56-41ac-b877-1fb242f6f4e1 fwd="69.36.89.218" dyno= connect= service= status=503 bytes= protocol=https2017-04-24T20:26:32.319732+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=derekdyerdev.herokuapp.com request_id=f2a34e62-9765- Now provide the response and nothing else.
You have the bracket on line 34 of your app.js file in the wrong place.Since the function is a callback, it needs to be within the params. Change that last block to this: const server = app.listen(process.env.PORT || 5000, () => { const port = server.address().port; console.log(`Express is working on port ${port}`);}); I also modified the Procfile to just this: web: node app.js After I modified that I was able to run locally, and I deployed it to my Heroku just to test, and it works fine :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43596835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7915819/']}
jdg_70413
stackexchange
llm_judgeable_groundtruth_similarity
2840835
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an unsigned char array that I need in a std::string, but my current way uses reinterpret_cast which I would like to avoid. Is there a cleaner way to do this? unsigned char my_txt[] = { 0x52, 0x5f, 0x73, 0x68, 0x7e, 0x29, 0x33, 0x74, 0x74, 0x73, 0x72, 0x55}unsigned int my_txt_len = 12;std::string my_std_string(reinterpret_cast<const char *>(my_txt), my_txt_len); Now provide the response and nothing else.
Use the iterator constructor: std::string my_std_string(my_txt, my_txt + my_txt_len); This is assuming that you want the unsigned chars to be converted to char. If you want them to be reinterpreted, then you should use reinterpret_cast . That would be perfectly clean, since what you say is exactly what is done. In your example, though, it doesn't make any difference, because all of the values in your array are within the range 0 to CHAR_MAX . So it's guaranteed that those values are represented the same way in char as they are in unsigned char , and hence that reinterpreting them is the same as converting them. If you had values greater then CHAR_MAX then implementations are allowed to treat them differently.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2840835', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115751/']}
jdg_70414
stackexchange
llm_judgeable_groundtruth_similarity
33745
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have used scipy.signal.remez to calculate the coefficients for a band-pass filter and when I use it to filter a sinusoidal signal that goes between 0 and some positive number (e.g. $2^{16}$) I get that the filtered signal is negative ( it is attenuated, as I expected ) but it has a negative offset, is this expected? I need my outputs to be between 0 and $2^{16}$ (since I am implementing this filter in an FPGA and send the filtered signal to a DAC which accepts positive numbers between 0 and $2^{16}$ Should I just deal with this by adding a positive offset to re-centre the attenuated signal? Code used to generate the FIR filter: fs = 2500000 # Sample rate, Hzband = [95000, 105000] # Desired pass band, Hztrans_width = 5000 # Width of transition from pass band to stop band, Hznumtaps = 200 # Size of the FIR filter.edges = [0, band[0] - trans_width, band[0], band[1], band[1] + trans_width, 0.5*fs]taps = scipy.signal.remez(numtaps, edges, [0, 1, 0], Hz=fs) The taps are real and look like this: Here is an example of the result of using this FIR filter to filter a 200KHz sine wave in python: Now provide the response and nothing else.
What you see is what one would expect. As pointed out in Marcus Müller's answer , your band pass filter has a relatively poor stop band attenuation, and since DC is in the filter's stop band, DC is not sufficiently attenuated. You can easily predict what is going to happen: compute the filter's DC gain, which is just the sum over all filter coefficients: $H(0)=\sum_nh[n]$ This will be a not so small negative number. Take the DC offset of your input signal ($2^{15}$), and multiply it with $H(0)$. This must be the DC offset of your output signal. So the DC offset of the output signal can be easily predicted, even without computing the output! What can you do to get rid the DC offset of the output signal? Since you can perfectly predict it, you can just subtract the DC offset $=2^{15}\cdot H(0)$ from your output signal. Another fun solution is to increase the filter length by $1$ sample, and set that new last sample to the value $-H(0)$ (as computed above). This will make sure that $H(0)$ of the new filter is exactly $0$, and it will only insignificantly change the overall frequency response of the filter. For the ones who wonder if it is normal that the first and last sample of the impulse response are much larger than all other samples: yes, this is normal, especially for narrow band pass filters, and it is a direct consequence of the equi-ripple optimality criterion implied by the Remez algorithm. These two impulses (first and last sample) are echos generating the sinusoidal (i.e., equi-ripple) stop band behavior in the frequency domain. The ripple in the impulse response generates the (impulse-like) narrow pass band in the frequency domain. So everything can be explained by the basic Fourier relationship "sinusoid $\Longleftrightarrow$ impulse".
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/33745', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/23345/']}
jdg_70415
stackexchange
llm_judgeable_groundtruth_similarity
18470136
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing a REST API and I have stumbled upon a problem. What is the best way to return the validation errors. Until now I have been returning the error messages dumped into a general error code (let's say bad request for example) { "status": 400, "error": { "code": 1, // General bad request code "message": [ "The Key \"a\" is missing", "The Key \"b\" is missing", "The Key \"c\" is missing", "Incorrect Format for field \"y\"" ] }) I have researched a little more about how should a good API response should look like and I thought of the following options: Stop at the first encountered error and return a response with the specific error code { "status": 400, //Same as the HTTP header returned "error" { "code": 1, // Specific field validation error code "message": "Field \"x\" is missing from the array structure", "developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}", "more_info" => "www.api.com/help/errors/1" }) Parse all the request data and return multiple field validation errors. { "status": 400, "error": { "code": 1 //General bad Request code "message": "Bad Request", "developer_message": "Field validation errors." "more_info": "www.api.com/help/errors/1", "error_details": { 0: { "code": 2 // Specific field validation error code "message": "Field \"x\" is missing from the array structure", "developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}", "more_info": "www.api.com/help/errors/2" }, 1: { "code": 3 // Specific field validation error code "message": "Incorrect Format for field \"y\"", "developer_message": "The field \"y\" must be in the form of \"Y-m-d\"", "more_info": "www.api.com/help/errors/3" } } } } In my opinion option 2 would be the right way (it gives more useful information to the developers/end users and the server load might be lower(less requests/no need to revalidate valid data/no need to compute the signature and authenticate the user)), but I am wandering what are the best practices, and if there is another way to treat this kind of problems. Also i think option 1 is still valid if i get a single fatal error in the flow of the script.(not validation errors) Please note that the code is just a simple array just so it is easier to follow. The response format will be JSON or XML. Now provide the response and nothing else.
Let's look to Facebook's Graph API . That is hit hard, and a great many errors are most likely generated. Here is what Facebook returns on an API error: { "error": { "message": "Message describing the error", "type": "OAuthException", "code": 190, "error_subcode": 460, "error_user_title": "A title", "error_user_msg": "A message" } } They try to make the Graph API as useful as possible, but they seem return a specific error with a code and a subcode ( Ref ). The fact that each error has its own code means it's easier to search for said code or message as a starting point for debugging. That's probably why they don't accumulate error messages in their official error response. If it's good enough and convenient for Facebook, it's probably good enough for us. Sample error responses: { "error": { "message": "(#200) Must have a valid access_token to access this endpoint", "type": "OAuthException", "code": 200 }} and "error": { "message": "(#604) Your statement is not indexable. The WHERE clause must contain an indexable column. Such columns are marked with * in the tables linked from http://developers.facebook.com/docs/reference/fql ", "type": "OAuthException", "code": 604} Then there is JSend which "is a specification that lays down some rules for how JSON responses from web servers should be formatted." Their goal is: There are lots of web services out there providing JSON data, and each has its own way of formatting responses. Also, developers writing for JavaScript front-ends continually re-invent the wheel on communicating data from their servers. While there are many common patterns for structuring this data, there is no consistency in things like naming or types of responses. Also, this helps promote happiness and unity between backend developers and frontend designers, as everyone can come to expect a common approach to interacting with one another. Here is a sample error message: { "status" : "fail", "data" : { "title" : "A title is required" }} It looks like Facebook and this group trying to set like an industry standard are opting for your choice #1. Bounty Question In response to the bounty request of "if anyone went #2 and maybe has any improvements on it?", there is a design pattern from Pragmatic RESTful API that states: Validation errors will need a field breakdown. This is best modeled by using a fixed top-level error code for validation failures and providing the detailed errors in an additional errors field, like so: { "code" : 1024, "message" : "Validation Failed", "errors" : [ { "code" : 5432, "field" : "first_name", "message" : "First name cannot have fancy characters" }, { "code" : 5622, "field" : "password", "message" : "Password cannot be blank" } ]}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18470136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/645136/']}
jdg_70416
stackexchange
llm_judgeable_groundtruth_similarity
1881922
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider this code: String first = "abc"; String second = new String("abc"); When using the new keyword, Java will create the abc String again right?Will this be stored on the regular heap or the String pool?How many String s will end in the String pool? Now provide the response and nothing else.
If you use the new keyword, a new String object will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap. The string pool is like a cache. If you do this: String s = "abc";String p = "abc"; then the Java compiler is smart enough to make just one String object, and s and p will both be referring to that same String object. If you do this: String s = new String("abc"); then there will be one String object in the pool, the one that represents the literal "abc" , and there will be a separate String object, not in the pool, that contains a copy of the content of the pooled object. Since String is immutable in Java, you're not gaining anything by doing this; calling new String("literal") never makes sense in Java and is unnecessarily inefficient. Note that you can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there). See the API documentation for that method for more info. See also String interning (Wikipedia).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1881922', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45963/']}
jdg_70417
stackexchange
llm_judgeable_groundtruth_similarity
28086459
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 Haskell's lens library, ix and element both take an Int an can be used e.g. to read or write a list element at some index, like this ghci> [1..10] ^? ix 4Just 5ghci> [1..10] & ix 4 .~ 1[1,2,3,4,1,6,7,8,9,10] and similarly: ghci> [1..10] ^? element 4Just 5ghci> [1..10] & element 4 .~ 1[1,2,3,4,1,6,7,8,9,10] What is the difference between element and ix ? Now provide the response and nothing else.
With ix you can index not only by number, but by e.g. key in the Maps. The element index in Traverse order. λ> let m = Map.fromList [("foo", 'f'), ("bar", 'b')]λ> m ^? ix "foo"Just 'f'λ> m ^? element 0 -- Map is ordered container!Just 'b' The difference is even more obvious with e.g. IntMap λ> let im = IntMap.fromList [(1, "one"), (2, "two")]λ> im ^? ix 1Just "one"λ> im ^? element 1Just "two"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28086459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1995474/']}
jdg_70418
stackexchange
llm_judgeable_groundtruth_similarity
47909
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 try to transfer files from remote computer using ssh to my computer : scp My_file.txt user_id@server:/Home This should put My_file.txt in the home folder on my own computer, right? I get scp/Home: permission denied Also when I try: ...@server:/Desktop , in order to copy the files from the remote computer to my desktop. What am I doing wrong? Now provide the response and nothing else.
Your commands are trying to put the new Document to the root ( / ) of your machine. What you want to do is to transfer them to your home directory (since you have no permissions to write to / ). If path to your home is something like /home/erez try the following: scp My_file.txt user_id@server:/home/erez/ You can substitute the path to your home directory with the shortcut ~/ , so the following will have the same effect: scp My_file.txt user_id@server:~/ You can even leave out the path altogether on the remote side; this means your home directory. scp My_file.txt user_id@server: That is, to copy the file to your desktop you might want to transfer it to /home/erez/Desktop/ : scp My_file.txt user_id@server:/home/erez/Desktop/ or using the shortcut: scp My_file.txt user_id@server:~/Desktop/ or using a relative path on the remote side, which is interpreted relative to your home directory: scp My_file.txt user_id@server:Desktop/ As @ckhan already mentioned, you also have to swap the arguments, it has to be scp FROM TO So if you want to copy the file My_file.txt from the server user_id@server to your desktop you should try the following: scp user_id@server:/path/to/My_file.txt ~/Desktop/ If the file My_file.txt is located in your home directory on the server you may again use the shortcut: scp user_id@server:~/My_file.txt ~/Desktop/
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/47909', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/23256/']}
jdg_70419
stackexchange
llm_judgeable_groundtruth_similarity
17129672
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 know that Node is non-blocking, but I just realized that the default behaviour of http.listen(8000) means that all HTTP requests are handled one-at-a-time. I know I shouldn't have been surprised at this (it's how ports work), but it does make me seriously wonder how to write my code so that I can handle multiple, parallel HTTP requests. So what's the best way to write a server so that it doesn't hog port 80 and long-running responses don't result in long request queues? To illustrate the problem, try running the code below and loading it up in two browser tabs at the same time. var http = require('http');http.createServer(function (req, res) { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.write("<p>" + new Date().toString() + ": starting response"); setTimeout(function () { res.write("<p>" + new Date().toString() + ": completing response and closing connection</p>"); res.end(); }, 4000);}).listen(8080); Now provide the response and nothing else.
You are misunderstanding how node works. The above code can accept TCP connections from hundreds or thousands of clients, read the HTTP requests, and then wait the 4000 ms timeout you have baked in there, and then send the responses. Each client will get a response in about 4000 + a small number of milliseconds. During that setTimeout (and during any I/O operation) node can continue processing. This includes accepting additional TCP connections. I tested your code and the browsers each get a response in 4s. The second one does NOT take 8s, if that is how you think it works. I ran curl -s localhost:8080 in 4 tabs as quickly as I can via the keyboard and the seconds in the timestamps are: 54 to 58 54 to 58 55 to 59 56 to 00 There's no issue here, although I can understand how you might think there is one. Node would be totally broken if it worked as your post suggested. Here's another way to verify: for i in 1 2 3 4 5 6 7 8 9 10; do curl -s localhost:8080 &;done
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17129672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279608/']}
jdg_70420
stackexchange
llm_judgeable_groundtruth_similarity
8135899
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to find out a way to detect if a process is running in Windows Task Manager for Windows OS and Macintosh Activity Monitor for MAC OS using Python Can someone please help me out with the code please? Now provide the response and nothing else.
psutil is a cross-platform library that retrieves information about running processes and system utilization. import psutilpythons_psutil = []for p in psutil.process_iter(): try: if p.name() == 'python.exe': pythons_psutil.append(p) except psutil.Error: pass >>> pythons_psutil[<psutil.Process(pid=16988, name='python.exe') at 25793424>]>>> print(*sorted(pythons_psutil[0].as_dict()), sep='\n')cmdlineconnectionscpu_affinitycpu_percentcpu_timescreate_timecwdexeio_countersionicememory_infomemory_info_exmemory_mapsmemory_percentnamenicenum_ctx_switchesnum_handlesnum_threadsopen_filespidppidstatusthreadsusername>>> pythons_psutil[0].memory_info()pmem(rss=12304384, vms=8912896) In a stock Windows Python you can use subprocess and csv to parse the output of tasklist.exe : import subprocessimport csvp_tasklist = subprocess.Popen('tasklist.exe /fo csv', stdout=subprocess.PIPE, universal_newlines=True)pythons_tasklist = []for p in csv.DictReader(p_tasklist.stdout): if p['Image Name'] == 'python.exe': pythons_tasklist.append(p) >>> print(*sorted(pythons_tasklist[0]), sep='\n')Image NameMem UsagePIDSession NameSession#>>> pythons_tasklist[0]['Mem Usage']'11,876 K'
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8135899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992808/']}
jdg_70421
stackexchange
llm_judgeable_groundtruth_similarity
18759383
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 someone please tell me what is the problem?the class Camera is extend Jpanel the code: public class Main extends JFrame { public static Image image; //sort the cameras by their heights. public static void main(String [] args){ image = new Image(400,400,"test"); Camera c=new Camera(100, 100, (Math.PI)/4, 0, 200,200,Math.PI,Color.MAGENTA); image.addCamera(c); JFrame f = new JFrame(); int width= image.getWidth(); int length = image.getLength(); f.setSize(width, length); f.add(new Main()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Sets the title of the frame f.setTitle(image.getName()); f.setVisible(true); } public void paint(Graphics g) { System.out.println("in the paint"); Vector<Camera> cameras = image.getCameras(); for(int i=0;i<cameras.size();i++){ cameras.get(i).paintComponent(g); } `enter code here`} in the class Camera there the function paintCompoment,but the result is: Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container at java.awt.Container.checkNotAWindow(Container.java:483) at java.awt.Container.addImpl(Container.java:1084) at java.awt.Container.add(Container.java:998) at javax.swing.JFrame.addImpl(JFrame.java:562) at java.awt.Container.add(Container.java:410) at CameraPack.Main.main(Main.java:22) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) Now provide the response and nothing else.
The problem is that my $exists query is (obviously, on second look) in the wrong place. Documents were being returned that, surely enough, didn't include my_date . Here's the patched up function, which works as expected. var incrementDates = function() { db.blah.find({ ... , my_date : { $exists : true } ).forEach(function(doc) { db.blah.update( { _id : doc._id } , { $set : { my_date : new Date(doc.my_date.getTime() + 86400000) }} ); });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18759383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2771777/']}
jdg_70422
stackexchange
llm_judgeable_groundtruth_similarity
163432
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: The more functional programming I do, the more I feel like it adds an extra layer of abstraction that seems like how an onion's layer is- all encompassing of the previous layers. I don't know if this is true so going off the OOP principles I've worked with for years, can anyone explain how functional does or doesn't accurately depict any of them: Encapsulation, Abstraction, Inheritance, Polymorphism I think we can all say, yes it has encapsulation via tuples, or do tuples count technically as fact of "functional programming" or are they just a utility of the language? I know Haskell can meet the "interfaces" requirement, but again not certain if it's method is a fact of functional? I'm guessing that the fact that functors have a mathematical basis you could say those are a definite built in expectation of functional, perhaps? Please, detail how you think functional does or does not fulfill the 4 principles of OOP. Edit:I understand the differences between the functional paradigm and object oriented paradigm just fine and realize there are plenty of multiparadigm languages these days which can do both. I am really just looking for definitions of how outright fp (think purist, like haskell) can do any of the 4 things listed, or why it cannot do any of them. i.e. "Encapsulation can be done with closures" (or if I am wrong in this belief, please state why). Now provide the response and nothing else.
Functional programming isn't a layer above OOP; it's a completely different paradigm. It's possible to do OOP in a functional style (F# was written for exactly this purpose), and on the other end of the spectrum you have stuff like Haskell, which explicitly rejects the principles of object orientation. You can do encapsulation and abstraction in any language advanced enough to support modules and functions. OO provides special mechanisms for encapsulation, but it's not something inherent to OO. The point of OO is the second pair you mentioned: inheritance and polymorphism. The concept is formally known as Liskov substitution, and you can't get it without language-level support for object-oriented programming. (Yes, it's possible to fake it in some cases, but you lose a lot of the advantages that OO brings to the table.) Functional programming doesn't focus on Liskov substitution. It focuses on increasing the level of abstraction, and on minimizing the use of mutable state and routines with "side effects", which is a term functional programmers like to use to make routines that actually do something (as opposed to simply calculating something) sound scary. But again, they're completely separate paradigms, that can be used together, or not, depending on the language and the skill of the programmer.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/163432', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/35276/']}
jdg_70423
stackexchange
llm_judgeable_groundtruth_similarity
29405858
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently I found that there is, possibly, a new way of commenting in HTML5. Instead of the typical <!-- --> multi-line commenting I've read about, I thought I noticed that my IDE made a regular <!div > commented out. So I tested it out, and to my surprise Chrome had commented out that tag. It only commented out the tag and not the contents of the div, so I had to comment out the closer <!/div> to avoid closing other divs. I tested another and it appears that generally putting an exclamation marker in front of the opening of any tag, this symbol < , makes that tag commented out. Is this actually new? Is it bad practice? It is actually very convenient, but is it practical yet (if not new)? Extra details: Although a syntax error or misinterpretations of this particular syntax is a good reason, how come Chrome actually renders them as full comments? The code is written as : <!div displayed> some text here that is still displayed <!/div> And then it is rendered as : <!--div displayed--> some text here that is still displayed <!--/div--> Now provide the response and nothing else.
There is no new standard for comments in HTML5. The only valid comment syntax is still <!-- --> . From section 8.1.6 of W3C HTML5 : Comments must start with the four character sequence U+003C LESS-THAN SIGN, U+0021 EXCLAMATION MARK, U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS ( <!-- ). The <! syntax originates in SGML DTD markup, which is not part of HTML5. In HTML5, it is reserved for comments, CDATA sections, and the DOCTYPE declaration. Therefore whether this alternative is bad practice depends on whether you consider the use of (or worse, the dependence on) obsolete markup to be bad practice. Validator.nu calls what you have a "Bogus comment." — which means that it's treated like a comment even though it's not a valid comment. This is presumably for backward compatibility with pre-HTML5, which was SGML-based, and had markup declarations that took the form <!FOO> , so I wouldn't call this new. The reason they're treated like comments is because SGML markup declarations were special declarations not meant to be rendered, but since they are meaningless in HTML5 (with the above exceptions), as far as the HTML5 DOM is concerned they are nothing more than comments. The following steps within section 8.2.4 lead to this conclusion, which Chrome appears to be following to the letter: 8.2.4.1 Data state : Consume the next input character: "<" (U+003C) Switch to the tag open state. 8.2.4.8 Tag open state : Consume the next input character: "!" (U+0021) Switch to the markup declaration open state. 8.2.4.45 Markup declaration open state : If the next two characters are both "-" (U+002D) characters, consume those two characters, create a comment token whose data is the empty string, and switch to the comment start state. Otherwise, if the next seven characters are an ASCII case-insensitive match for the word "DOCTYPE", then consume those characters and switch to the DOCTYPE state. Otherwise, if there is an adjusted current node and it is not an element in the HTML namespace and the next seven characters are a case-sensitive match for the string "[CDATA[" (the five uppercase letters "CDATA" with a U+005B LEFT SQUARE BRACKET character before and after), then consume those characters and switch to the CDATA section state. Otherwise, this is a parse error. Switch to the bogus comment state. The next character that is consumed, if any, is the first character that will be in the comment. Notice that it says to switch to the comment start state only if the sequence of characters encountered is <!-- , otherwise it's a bogus comment. This reflects what is stated in section 8.1.6 above. 8.2.4.44 Bogus comment state : Consume every character up to and including the first ">" (U+003E) character or the end of the file (EOF), whichever comes first. Emit a comment token whose data is the concatenation of all the characters starting from and including the character that caused the state machine to switch into the bogus comment state, up to and including the character immediately before the last consumed character (i.e. up to the character just before the U+003E or EOF character), but with any U+0000 NULL characters replaced by U+FFFD REPLACEMENT CHARACTER characters. (If the comment was started by the end of the file (EOF), the token is empty. Similarly, the token is empty if it was generated by the string " <!> ".) In plain English, this turns <!div displayed> into <!--div displayed--> and <!/div> into <!--/div--> , exactly as described in the question. On a final note, you can probably expect other HTML5-compliant parsers to behave the same as Chrome.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/29405858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2945133/']}
jdg_70424
stackexchange
llm_judgeable_groundtruth_similarity
2576902
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 know that there are a lot of similar questions like this on this forum but still I can't figure it out one thing of this definition. Definition: f is continuous at $x_o\in X\subset\mathbb{R}$ if $$\forall \epsilon>0 \exists \delta>0 |\forall x| |x-x_o|<\delta\Rightarrow|f(x)-f(x_o)|<\epsilon$$ My question is, why in this definition I can't take $\epsilon \to 0$? Now provide the response and nothing else.
Suppose $\newcommand{\ip}[2]{\langle #1\mid #2\rangle}\ip{Tu}{u}=0$ for every $u$. Then, given $u$ and $v$ and any scalar $a$ (assuming semilinearity in the first variable, with the opposite convention the proof is essentially the same):$$0=\ip{T(u+av)}{u+av}=a\ip{Tu}{v}+\bar{a}\ip{Tv}{u}$$In particular, for $a=i$, we get $\ip{Tu}{v}=\ip{Tv}{u}$ and, for $a=1$, $\ip{Tu}{v}=-\ip{Tv}{u}$. Therefore $\ip{Tu}{v}=0$, for every $u$ and $v$, in particular for $v=Tu$. Hence $Tu=0$. Note that this can fail on real Hilbert spaces; the easiest example is$$T\colon\mathbb{R}^2\to\mathbb{R}^2\qquadT\begin{bmatrix} x\\y\end{bmatrix}=\begin{bmatrix}-y\\x\end{bmatrix}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2576902', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/508560/']}
jdg_70425
stackexchange
llm_judgeable_groundtruth_similarity
9727962
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was curious if there was a good way to do this. My current code is something like: def factorialMod(n, modulus): ans=1 for i in range(1,n+1): ans = ans * i % modulus return ans % modulus But it seems quite slow! I also can't calculate n! and then apply the prime modulus because sometimes n is so large that n! is just not feasible to calculate explicitly. I also came across http://en.wikipedia.org/wiki/Stirling%27s_approximation and wonder if this can be used at all here in some way? Or, how might I create a recursive, memoized function in C++? Now provide the response and nothing else.
n can be arbitrarily large Well, n can't be arbitrarily large - if n >= m , then n! ≡ 0 (mod m) (because m is one of the factors, by the definition of factorial) . Assuming n << m and you need an exact value, your algorithm can't get any faster, to my knowledge. However, if n > m/2 , you can use the following identity ( Wilson's theorem - Thanks @Daniel Fischer!) to cap the number of multiplications at about m-n (m-1)! ≡ -1 (mod m)1 * 2 * 3 * ... * (n-1) * n * (n+1) * ... * (m-2) * (m-1) ≡ -1 (mod m)n! * (n+1) * ... * (m-2) * (m-1) ≡ -1 (mod m)n! ≡ -[(n+1) * ... * (m-2) * (m-1)] -1 (mod m) This gives us a simple way to calculate n! (mod m) in m-n-1 multiplications, plus a modular inverse : def factorialMod(n, modulus): ans=1 if n <= modulus//2: #calculate the factorial normally (right argument of range() is exclusive) for i in range(1,n+1): ans = (ans * i) % modulus else: #Fancypants method for large n for i in range(n+1,modulus): ans = (ans * i) % modulus ans = modinv(ans, modulus) ans = -1*ans + modulus return ans % modulus We can rephrase the above equation in another way, that may or may-not perform slightly faster. Using the following identity: we can rephrase the equation as n! ≡ -[(n+1) * ... * (m-2) * (m-1)] -1 (mod m)n! ≡ -[(n+1-m) * ... * (m-2-m) * (m-1-m)] -1 (mod m) (reverse order of terms)n! ≡ -[(-1) * (-2) * ... * -(m-n-2) * -(m-n-1)] -1 (mod m)n! ≡ -[(1) * (2) * ... * (m-n-2) * (m-n-1) * (-1) (m-n-1) ] -1 (mod m)n! ≡ [(m-n-1)!] -1 * (-1) (m-n) (mod m) This can be written in Python as follows: def factorialMod(n, modulus): ans=1 if n <= modulus//2: #calculate the factorial normally (right argument of range() is exclusive) for i in range(1,n+1): ans = (ans * i) % modulus else: #Fancypants method for large n for i in range(1,modulus-n): ans = (ans * i) % modulus ans = modinv(ans, modulus) #Since m is an odd-prime, (-1)^(m-n) = -1 if n is even, +1 if n is odd if n % 2 == 0: ans = -1*ans + modulus return ans % modulus If you don't need an exact value, life gets a bit easier - you can use Stirling's approximation to calculate an approximate value in O(log n) time (using exponentiation by squaring ) . Finally, I should mention that if this is time-critical and you're using Python, try switching to C++. From personal experience, you should expect about an order-of-magnitude increase in speed or more, simply because this is exactly the sort of CPU-bound tight-loop that natively-compiled code excels at (also, for whatever reason, GMP seems much more finely-tuned than Python's Bignum) .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9727962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1085885/']}
jdg_70426
stackexchange
llm_judgeable_groundtruth_similarity
44800472
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array where there is stored string that was splitted. I would like to now make a controller that would put each of this splitted strings into next li elements on the list. I know how to do ng-repeat with objects but i'm not sure how to do it with array cells? var app = angular.module("pageApp", []);app.controller('populateController', function($scope, $http) { $scope.dat=[]; $http.get('/api').success(function(data) { $scope.dat= data[0]; }); var str = $scope.dat.guide; var res= str.split("~");}) new Manual({ name: 'name1', category_name: 'sewing', difficulty_level: 'easy', guide: 'guide1' +'~2. guide2' +'~3. guide3' +'~4. guide4' +'~5. guide5' }), Now provide the response and nothing else.
You can sort timeSegments by start_time (using Array.prototype.sort ) and iterate through the sorted list and check if end_time of the current timeSegment is greater than start_time of the next one. If that happens, there is an overlap. You can see an example of implementation below: const checkOverlap = (timeSegments) => { if (timeSegments.length === 1) return false; timeSegments.sort((timeSegment1, timeSegment2) => timeSegment1[0].localeCompare(timeSegment2[0]) ); for (let i = 0; i < timeSegments.length - 1; i++) { const currentEndTime = timeSegments[i][1]; const nextStartTime = timeSegments[i + 1][0]; if (currentEndTime > nextStartTime) { return true; } } return false;};const timeSegments1 = [ ["03:00", "04:00"], ["02:00", "07:00"], ["12:00", "15:00"]];const timeSegments2 = [ ["05:00", "07:00"], ["03:00", "04:00"], ["12:00", "15:00"]];console.log(checkOverlap(timeSegments1)); // prints trueconsole.log(checkOverlap(timeSegments2)); // prints false Note that Array.prototype.sort mutates the array, performing the sort in-place. If you want to preserve the array passed to checkOverlap (which is, in general, a good practice), you can create a copy of timeSegments (using the spread syntax , for example): const sortedTimeSegments = [...timeSegments].sort(...);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44800472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_70427
stackexchange
llm_judgeable_groundtruth_similarity
92398
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f : X \to Y$ be a morphism of ringed spaces and $\mathcal{M}$, $\mathcal{N}$ sheaves of $\mathcal{O}_Y$-modules. Then one has a canonical isomorphism $f^*(\mathcal{M} \otimes_{\mathcal{O}_Y} \mathcal{N}) \cong f^*\mathcal{M} \otimes_{\mathcal{O}_X} f^*\mathcal{N}$, but I cannot find a proof in any of the standard references. The problem is that the definitions of the functors $f^*$ and $\otimes$ are so cumbersome that I cannot even write down a map between these two sheaves. Surely there is a nice way to do this: to give you an idea of what I mean by "nice," I am the type of person who likes to define such functors as adjoints to some less complicated functor, prove that they exist, and then forget the construction. Now provide the response and nothing else.
I figured it out: let $\mathcal{P}$ be a sheaf of $\mathcal{O}_X$ -modules. It is easy to check from the definition of $\mathscr{H}om$ and the adjointness of $f^*$ and $f_*$ that $f_*\mathscr{H}om_{\mathcal{O}_X}(f^*\mathcal{N},\mathcal{P}) \cong \mathscr{H}om_{\mathcal{O}_Y}(\mathcal{N},f_*\mathcal{P})$ as $\mathcal{O}_Y$ -modules, and then we see that \begin{align*}\text{Hom}_{\mathcal{O}_X}(f^*\mathcal{M} \otimes_{\mathcal{O}_X} f^*\mathcal{N},\mathcal{P}) &\cong \text{Hom}_{\mathcal{O}_Y}(\mathcal{M},f_*\mathscr{H}om_{\mathcal{O}_X}(f^*\mathcal{N},\mathcal{P}))\\&\cong \text{Hom}_{\mathcal{O}_Y}(\mathcal{M},\mathscr{H}om_{\mathcal{O}_Y}(\mathcal{N},f_*\mathcal{P}))\\&\cong \text{Hom}_{\mathcal{O}_X}(f^*(\mathcal{M} \otimes_{\mathcal{O}_Y} \mathcal{N}),\mathcal{P}).\end{align*} So $f^*\mathcal{M} \otimes_{\mathcal{O}_X} f^*\mathcal{N}$ and $f^*(\mathcal{M} \otimes_{\mathcal{O}_Y} \mathcal{N})$ represent the same functor, whence they are canonically isomorphic.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/92398', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4842/']}
jdg_70428
stackexchange
llm_judgeable_groundtruth_similarity
11965882
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I create a winForms "myForm" then the following boiler plate code is generated: public partial class myForm: Form{ public myForm() { //<<position 1 InitializeComponent(); //<<position 2 } } If I add extra code to the constructor method does it make any difference to the running of the app if I place my code in position 1 or 2 ? Now provide the response and nothing else.
Yes, it does. InitializeComponent is the method that VS generates that is responsible for creating and positioning the controls on a form. Code in "position 1" will execute before the controls exist. If you try to access a control in this position, you'll get a NullReferenceException (say, if you try to set the content of a TextBox ). Similar code in "position 2" will work as expected. There is use to "position 1" though: if you have custom controls or behaviour that rely on properties of your form, setting those properties in "position 1" might prevent that code from having to refresh if you allow controls to be created before those values are set.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11965882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1179880/']}
jdg_70429
stackexchange
llm_judgeable_groundtruth_similarity
36210537
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First of all, I read through all those topics how to use Zxing in Java but always got errors with missing com.google.zxing.client.j2se.* (I loaded the zxing core-3.2.1.jar in eclipse and all other zxing packages work unless j2se) or just found solutions for creating qr images... My aim is to write one single method which gets an image file finds the qr code in this image, decodes the qr code and returns the string, basically it should be something like the following: import com.google.zxing.*;public class QRCode { /* * ... */ public String getDecodedString(SomeStandardImageType photo){ // detect the qr code in a photo // create qr image from detected area in photo // decode the new created qr image and return the string return "This is the decoded dataString from the qr code in the photo"; }} To sum up the method should get an image file like the following and should return the url or if failed just "". The code should be compatible with Zxing 3.2.1. Edit: The question is solved. For others who are interested in this I want to say that it is important to add both external jars core-3.2.1.jar and javase-3.2.1.jar to external jars. The answer by me works without the latter but depends on android image libs. Now provide the response and nothing else.
here is the code to create the Qr-Code and read Message from Qr-code you need the build the zxing library main describe the qr-code creation and qr-code extraction package com.attendance.mark;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.HashMap;import java.util.Map;import javax.imageio.ImageIO;import com.google.zxing.BarcodeFormat;import com.google.zxing.BinaryBitmap;import com.google.zxing.EncodeHintType;import com.google.zxing.MultiFormatReader;import com.google.zxing.MultiFormatWriter;import com.google.zxing.NotFoundException;import com.google.zxing.Result;import com.google.zxing.WriterException;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.client.j2se.MatrixToImageWriter;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;public class QRCode { /** * * @param args * @throws WriterException * @throws IOException * @throws NotFoundException */ public static void main(String[] args) throws WriterException, IOException, NotFoundException { String qrCodeData = "student3232_2015_12_15_10_29_46_123"; String filePath = "F:\\Opulent_ProjectsDirectory_2015-2016\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\AttendanceUsingQRCode\\QRCodes\\student3232_2015_12_15_10_29_46_123"; String charset = "UTF-8"; // or "ISO-8859-1" Map<EncodeHintType, ErrorCorrectionLevel> hintMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); createQRCode(qrCodeData, filePath, charset, hintMap, 200, 200); System.out.println("QR Code image created successfully!"); System.out.println("Data read from QR Code: " + readQRCode(filePath, charset, hintMap)); } /*** * * @param qrCodeData * @param filePath * @param charset * @param hintMap * @param qrCodeheight * @param qrCodewidth * @throws WriterException * @throws IOException */ public static void createQRCode(String qrCodeData, String filePath, String charset, Map hintMap, int qrCodeheight, int qrCodewidth) throws WriterException, IOException { BitMatrix matrix = new MultiFormatWriter().encode( new String(qrCodeData.getBytes(charset), charset), BarcodeFormat.QR_CODE, qrCodewidth, qrCodeheight); MatrixToImageWriter.writeToFile(matrix, filePath.substring(filePath .lastIndexOf('.') + 1), new File(filePath)); } /** * * @param filePath * @param charset * @param hintMap * * @return Qr Code value * * @throws FileNotFoundException * @throws IOException * @throws NotFoundException */ public static String readQRCode(String filePath, String charset, Map hintMap) throws FileNotFoundException, IOException, NotFoundException { BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer( new BufferedImageLuminanceSource( ImageIO.read(new FileInputStream(filePath))))); Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, hintMap); return qrCodeResult.getText(); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36210537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_70430
stackexchange
llm_judgeable_groundtruth_similarity
15734677
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing functional tests with Symfony2. I have a controller that calls a getImage() function which streams an image file as follows: public function getImage($filePath) $response = new StreamedResponse(); $response->headers->set('Content-Type', 'image/png'); $response->setCallback(function () use ($filePath) { $bytes = @readfile(filePath); if ($bytes === false || $bytes <= 0) throw new NotFoundHttpException(); }); return $response;} In functional testing, I try to request the content with the Symfony test client as follows: $client = static::createClient();$client->request('GET', $url);$content = $client->getResponse()->getContent(); The problem is that $content is empty, I guess because the response is generated as soon as the HTTP headers are received by the client, without waiting for a data stream to be delivered. Is there a way to catch the content of the streamed response while still using $client->request() (or even some other function) to send the request to the server? Now provide the response and nothing else.
The return value of sendContent (rather than getContent ) is the callback that you've set. getContent actually just returns false in Symfony2 Using sendContent you can enable the output buffer and assign the content to that for your tests, like so: $client = static::createClient();$client->request('GET', $url);// Enable the output bufferob_start();// Send the response to the output buffer$client->getResponse()->sendContent();// Get the contents of the output buffer$content = ob_get_contents();// Clean the output buffer and end itob_end_clean(); You can read more on the output buffer here The API for StreamResponse is here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15734677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/885464/']}
jdg_70431
stackexchange
llm_judgeable_groundtruth_similarity
234699
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 $E$ be a set of measure zero and define $f = \infty$ on $E$. Show that $\int_E f = 0$. This is out of Royden 4E, p 84. I know how to prove this if $f=0$ on $E$. But I'm curious, as stated, won't this result in a situation in which $\infty \cdot 0$. Now provide the response and nothing else.
Royden's definition (at least in the Second Edition - I doubt that it has changed) of $\int_E f$, where $f$ is a nonnegative measurable function on measurable set $E$, is $$ \int_E f = \sup_{h \le f} \int_E h$$where $h$ is a bounded measurable function such that $m\{x: h(x) \ne 0\}$ is finite. So, if $h$ is such a function and $\mu(E) = 0$, what is $\int_E h$?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/234699', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8324/']}
jdg_70432
stackexchange
llm_judgeable_groundtruth_similarity
30065
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the formula for the forward price of a bond (assuming there are coupons in the interim period, and that the deal is collateralised) Please also prove it with an arbitrage cashflow scenario analysis! I suppose it is like fwd = spot - pv coupons) × (1+ repo × T ) , I am not certain at what rate to pv the coupons. Now provide the response and nothing else.
Amazingly, there are several different methods for computing bond forward price – the underlying ideas are the same (forward price = spot price - carry), but the computational details differ a bit based on market convention. Let's start with the basics. Assume between now ($t_0$) and the forward settlement date $t_2$, the bond makes a coupon payment at time $t_1$. Now consider the following series of trades: Today, a trader buys a bond at a price of $P + AI_0$ (spot clean price + spot accrued interest). To fund the purchase, the trader enters into a $t_1$-year term repo agreement at a repo rate of $r$. More specifically, he/she sells the repo by borrowing $P + AI_0$ and delivering the bond as collateral. At time $t_1$ (coupon payment date), the repo balance is $(P + AI_0)(1 + rt_1)$ and the trader receives a coupon payment of $c / 2$ for being the owner of the bond. The trader re-enters into another repo agreement that spans from $t_1$ to $t_2$ on a principal of $(P + AI_0)(1 + rt_1) - c/2$. This new loan, combined with the coupon payment of $c/2$, allows the trader to retire the old repo loan without putting up any additional capital. Finally, at time $t_2$, the trader gets back the bond and repays the repo loan along with interest from $t_1$ to $t_2$:$$ \left((P + AI_0)(1 + rt_1) - \frac{c}{2}\right) \bigl(1 + r(t_2-t_1)\bigr) . $$ These trades are economically no different from buying the bond forward at time $t_2$. Therefore, the forward clean price for settlement at $t_2$ must be$$ F(t_2) = (P + AI_0)(1 + rt_1)\bigl(1 + r(t_2-t_1)\bigr) - \frac{c}{2}\bigl(1 + r(t_2-t_1)\bigr) - AI_{t_2}. $$ The method above is known as the Compounded Method . In the US Treasury market (and most international bond markets), a small approximation is made. Recall for small $rt$, we have$$ (1 + rt_1)(1+r(t_2-t_1))\approx 1 + r(t_1+t_2-t_1) = 1 + rt_2, $$we therefore have the Proceeds Method :$$ F(t_2) = (P + AI_0)(1 + rt_2) - \frac{c}{2}\bigl(1 + r(t_2-t_1)\bigr) - AI_{t_2}. $$ The Proceeds Method is for all intents and purposes the standard/default way of pricing bond forwards. There's also the "Simple" and "Scientific" methods, but these are rarely used.
{}
{'log_upvote_score': 6, 'links': ['https://quant.stackexchange.com/questions/30065', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/17348/']}
jdg_70433
stackexchange
llm_judgeable_groundtruth_similarity
279959
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an entry in my .vimrc which makes it page down the viewport when I hit the spacebar. It looks like this: map <Space> <PageDown> I want to create another key mapping which pages the viewport up when holding shift and hitting the spacebar. I have tried the following entries: map <Shift><Space> <PageUp>map <S-Space> <PageUp> Neither work. Anybody know how to achieve this functionality? Now provide the response and nothing else.
You cannot. CMS's solution will work for gVim, but not in vim because terminals cannot distinguish between <Space> and <S-Space> because curses sees them the same. It might be possible in the future if vim gains libtermkey support and your terminal supports the proper <CSI> sequences (xterm does if properly configured; nothing else does yet).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/279959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2476/']}
jdg_70434
stackexchange
llm_judgeable_groundtruth_similarity
1078423
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to figure out the exact meaning of the words Covariance and Contravariance from several articles online and questions on StackOverflow, and from what I can understand, it's only another word for polymorphism . Am I correct with the above statement? Or have I got it wrong ? Now provide the response and nothing else.
It's certainly related to polymorphism. I wouldn't say they're just "another word" for polymorphism though - they're about very specific situations, where you can treat one type as if it were another type in a certain context . For instance, with normal polymorphism you can treat any reference to a Banana as a reference to a Fruit - but that doesn't mean you can substitute Fruit every time you see the type Banana . For example, a List<Banana> can't be treated as a List<Fruit> because list.Add(new Apple()) is valid for List<Fruit> but not for List<Banana> . Covariance allows a "bigger" (less specific) type to be substituted in an API where the original type is only used in an "output" position (e.g. as a return value). Contravariance allows a "smaller" (more specific) type to be substituted in an API where the original type is only used in an "input" position. It's hard to go into all the details in a single SO post (although hopefully someone else will do a better job than this!). Eric Lippert has an excellent series of blog posts about it.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1078423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']}
jdg_70435
stackexchange
llm_judgeable_groundtruth_similarity
62289899
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using CoinMarketCap API to fetch coin's data from server ,so i have a problem !Android studio give me this message: type 'int' is not a subtype of type 'double' My problem almost from my model ,so this my models:Coin class import 'Data.dart';import 'Status.dart';class Coin { Status status; List<Data> data; Coin(this.status, this.data); factory Coin.fromJson(Map<String, dynamic> json) { var data = new List<Data>(); if (json['data'] != null) { json['data'].forEach((v) { data.add(new Data.fromJson(v)); }); } return Coin( json['status'] != null ? new Status.fromJson(json['status']) : null, data ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); if (this.status != null) { data['status'] = this.status.toJson(); } if (this.data != null) { data['data'] = this.data.map((v) => v.toJson()).toList(); } return data; }} Data class import 'Platform.dart';import 'Quote.dart';class Data { int id; String name; String symbol; String slug; int numMarketPairs; String dateAdded; List<String> tags; double maxSupply; double circulatingSupply; double totalSupply; Platform platform; int cmcRank; String lastUpdated; Quote quote; Data( this.id, this.name, this.symbol, this.slug, this.numMarketPairs, this.dateAdded, this.tags, this.maxSupply, this.circulatingSupply, this.totalSupply, this.platform, this.cmcRank, this.lastUpdated, this.quote); factory Data.fromJson(Map<String, dynamic> json) { int id = json['id']; String name = json['name']; String symbol = json['symbol']; String slug = json['slug']; int numMarketPairs = json['num_market_pairs']; String dateAdded = json['date_added']; List<String> tags = json['tags'].cast<String>(); double maxSupply = json['max_supply']; double circulatingSupply = json['circulating_supply']; double totalSupply = json['total_supply']; Platform platform = json['platform'] != null ? new Platform.fromJson(json['platform']) : null; int cmcRank = json['cmc_rank']; String lastUpdated = json['last_updated']; Quote quote = json['quote'] != null ? new Quote.fromJson(json['quote']) : null; return Data( id, name, symbol, slug, numMarketPairs, dateAdded, tags, maxSupply, circulatingSupply, totalSupply, platform, cmcRank, lastUpdated, quote ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['name'] = this.name; data['symbol'] = this.symbol; data['slug'] = this.slug; data['num_market_pairs'] = this.numMarketPairs; data['date_added'] = this.dateAdded; data['tags'] = this.tags; data['max_supply'] = this.maxSupply; data['circulating_supply'] = this.circulatingSupply; data['total_supply'] = this.totalSupply; if (this.platform != null) { data['platform'] = this.platform.toJson(); } data['cmc_rank'] = this.cmcRank; data['last_updated'] = this.lastUpdated; if (this.quote != null) { data['quote'] = this.quote.toJson(); } return data; }} Platform class class Platform { int id; String name; String symbol; String slug; String tokenAddress; Platform(this.id, this.name, this.symbol, this.slug, this.tokenAddress); factory Platform.fromJson(Map<String, dynamic> json) { int id = json['id']; String name = json['name']; String symbol = json['symbol']; String slug = json['slug']; String tokenAddress = json['token_address']; return Platform( id, name, symbol, slug, tokenAddress ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['name'] = this.name; data['symbol'] = this.symbol; data['slug'] = this.slug; data['token_address'] = this.tokenAddress; return data; }} Quote class import 'USD.dart';class Quote { USD uSD; Quote(this.uSD); factory Quote.fromJson(Map<String, dynamic> json) { return Quote( json['USD'] != null ? new USD.fromJson(json['USD']) : null ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); if (this.uSD != null) { data['USD'] = this.uSD.toJson(); } return data; }} Status class class Status { String timestamp; int errorCode; Null errorMessage; int elapsed; int creditCount; Null notice; Status( this.timestamp, this.errorCode, this.errorMessage, this.elapsed, this.creditCount, this.notice); factory Status.fromJson(Map<String, dynamic> json) { String timestamp = json['timestamp']; int errorCode = json['error_code']; Null errorMessage = json['error_message']; int elapsed = json['elapsed']; int creditCount = json['credit_count']; Null notice = json['notice']; return Status( timestamp, errorCode, errorMessage, elapsed, creditCount, notice ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['timestamp'] = this.timestamp; data['error_code'] = this.errorCode; data['error_message'] = this.errorMessage; data['elapsed'] = this.elapsed; data['credit_count'] = this.creditCount; data['notice'] = this.notice; return data; }} USD class class USD { double price; double volume24h; double percentChange1h; double percentChange24h; double percentChange7d; double marketCap; String lastUpdated; USD( this.price, this.volume24h, this.percentChange1h, this.percentChange24h, this.percentChange7d, this.marketCap, this.lastUpdated); factory USD.fromJson(Map<String, dynamic> json) { double price = json['price']; double volume_24h = json['volume_24h']; double percent_change_1h = json['percent_change_1h']; double percent_change_24h = json['percent_change_24h']; double percent_change_7d = json['percent_change_7d']; double market_cap = json['market_cap']; String last_updated = json['last_updated'].toString(); return USD( price, volume_24h, percent_change_1h, percent_change_24h, percent_change_7d, market_cap, last_updated ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['price'] = this.price; data['volume_24h'] = this.volume24h; data['percent_change_1h'] = this.percentChange1h; data['percent_change_24h'] = this.percentChange24h; data['percent_change_7d'] = this.percentChange7d; data['market_cap'] = this.marketCap; data['last_updated'] = this.lastUpdated; return data; }} I think my problem from USD class ,so i changed USD class like this : ................double price = double.parse(json['price']);double volume_24h = double.parse(json['volume_24h']);double percent_change_1h = double.parse(json['percent_change_1h']);double percent_change_24h = double.parse(json['percent_change_24h']);double percent_change_7d = double.parse(json['percent_change_7d']);double market_cap = double.parse(json['market_cap']);String last_updated = json['last_updated'].toString();.............. Then android studio give me other problem type 'double' is not a subtype of type 'String' This is link to test : https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=..........&start="+index.toString()+"&limit=10" Give me help guys !!! Now provide the response and nothing else.
Try to print the JSON which is sent by the server and check if all the parameters are having the expected format. For e.g. if a particular parameter has int value and you are expecting it as double then change it to double. You can change the code of initialization of double parameter as following data['price'] = this.price; to json['price'] == null ? 0.0 : json['price'].toDouble() // forcefully convert int to double This will fix the error type 'int' is not a subtype of type 'double' To fix type 'double' is not a subtype of type 'String' , you need to find out the parameter which is returned as a double and you are trying to initialize it to a string variable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62289899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10669265/']}
jdg_70436
stackexchange
llm_judgeable_groundtruth_similarity
12782289
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to define preprocessor macros in build settings, like IPAD_BUILD, and IPHONE_BUILD (and how to use them in my factory methods)? I'm using these by heart now, would be cool to know what is going behind. Now provide the response and nothing else.
/#if works as usual if: #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200 if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { return YES; }#endif return NO;} /#ifdef means "if defined - some value or macros": #ifdef RKL_APPEND_TO_ICU_FUNCTIONS#define RKL_ICU_FUNCTION_APPEND(x) _RKL_CONCAT(x, RKL_APPEND_TO_ICU_FUNCTIONS)#else // RKL_APPEND_TO_ICU_FUNCTIONS#define RKL_ICU_FUNCTION_APPEND(x) x#endif // RKL_APPEND_TO_ICU_FUNCTIONS or: #ifdef __OBJC__ #import <Foundation/Foundation.h>#endif Use this link for more information http://www.techotopia.com/index.php/Using_Objective-C_Preprocessor_Directives To test whether you running iPad or not you should have smth like this: #define USING_IPAD UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPadif (USING_IPAD) { NSLog(@"running iPad");} Here's another useful preprocessor functions: #ifdef DEBUG //here we run application through xcode (either simulator or device). You usually place some test code here (e.g. hardcoded login-passwords)#else //this is a real application downloaded from appStore#endif
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12782289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215282/']}
jdg_70437
stackexchange
llm_judgeable_groundtruth_similarity
36622181
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 making a chrome extension however I seem to get the following error when I try to fire up an onclick() event. Refused to load the script 'https://apis.google.com/js/client.js?onload=handleClientLoad' because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:" and Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' blob: filesystem: chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. This is my manifest.json : { "manifest_version": 2, "name": "SECURE", "description": "this extension offers secure communication for GMAIL users", "version": "1.0", "browser_action": { "default_icon": "resources/icon16.png", "default_popup": "popup.html", "default_title": "Click here!" }, "background":{ "scripts":["background.js"]}, "content_scripts": [ { "matches": ["http://*/*", "https://*/*"], "js":["myscript.js"], "run_at": "document_end" } ],"permissions": ["identity", "https://accounts.google.com/*", "https://www.googleapis.com/*"],"oauth2": { "client_id": "975410329966.apps.googleusercontent.com", "scopes": [ "<all urls>", "https://www.googleapis.com/auth/drive", "https://mail.google.com/", "https://www.googleapis.com/auth/gmail.login", "https://www.googleapis.com/auth/gmail.compose", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.send" ], "content_security_policy":"script-src 'self' 'unsafe-inline' 'unsafe eval' https://apis.google.com/js/client.js?; object-src 'self'"}} Any help towards fixing this error would greatly be appreciated. Now provide the response and nothing else.
By default Content Security Policy , inline scripts won't be loaded and only local script can be loaded. You could relax the default policy by: Inline Script. Take a look at Official Guide , inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. See Hash usage for elements for an example. But I believe a better way would extract this logic to a separate script and not use inline script. Remote Script. You could whitelist script resources https://apis.google.com/js/client.js?onload=handleClientLoad by the following section in manifest.json "content_security_policy":"script-src 'self' https://apis.google.com; object-src 'self'" Also, I believe a better way could be downloading the remote client.js and include it as a local script. Please be aware as per the description of Inline Script , unsafe-inline no longer works. Up until Chrome 45, there was no mechanism for relaxing the restriction against executing inline JavaScript. In particular, s etting a script policy that includes 'unsafe-inline' will have no effect .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36622181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6203719/']}
jdg_70438
stackexchange
llm_judgeable_groundtruth_similarity
38836674
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 a newcomer to Angular2, I'm used to the Angular 1 digest cycle, meaning if I update the scope of a view I can manually trigger a digest by calling $scope.$digest() . However, I'm not sure how to do this in Angular2, esp given that the new framework doesn't have the implicit data binding that the old version had. Here's my problem. I have a route that loads a component when a url with a parameter is hit: // Routerexport const AppRoutes : RouterConfig = [ { path: 'my/:arg/view', component: MyComponent }] Then I have this component: // Componentexport class MyComponent { constructor(private route : ActivatedRoute, private r : Router) { let id = parseInt(this.route.params['value'].id); console.log(id); // do stuff with id } reloadWithNewId(id:number) { this.r.navigateByUrl('my/' + id + '/view'); }} Lets say I navigate to url /my/1/view . It will call the constructor and the number 1 is logged. However, if I call reloadWithNewId with a new id, reloadWithNewIf(2) , the constructor is not called again. How do I manually reload the component? Now provide the response and nothing else.
There shouldn't be a need to reload the component. Just update the model and the view updates itself: export class MyComponent { constructor(private route : ActivatedRoute, private r : Router) {} reloadWithNewId(id:number) { this.r.navigateByUrl('my/' + id + '/view'); } ngOnInit() { this.sub = this.route.params.subscribe(params => { this.paramsChanged(params['id']); }); } paramsChanged(id) { console.log(id); // do stuff with id }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38836674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/858962/']}
jdg_70439
stackexchange
llm_judgeable_groundtruth_similarity
43517660
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 directive that works as a ngIf to control if the user with the correct permission is allow to see specific content, something like this: <div [type-of-user]="load data from the user and check it (normal or premium)"> <h3>You are allow to see this.</h3></div> I was reading about how to do it and found on this doc about "Attribute Directives" but I still can't implement it (I am new with Angular 2) So far I have this: import {Directive, ElementRef, Input} from '@angular/core';@Directive({ selector: '[type-of-user]'})export class TypeOfUserDirective{ constructor(private el: ElementRef){} @Input('type-of-user') userControl: string; private haspermission(permission: string) { /*the style background color is just to test if works*/ this.el.nativeElement.style.backgroundColor = permission; }} I already added the directive in the app.module. Any advice how to proceed would be great. Now provide the response and nothing else.
After some more research I found a great doc about how to build custom directives, specifically the way I need, that acts as an ngIf directive. You can read about it here and see the plunkr here import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';@Directive({ selector: '[isAllow]'})export class isAllowDirective { constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {} @Input() set isAllow(allow: boolean){ if (allow) { // If condition is true add template to DOM this.viewContainer.createEmbeddedView(this.templateRef); } else { // Else remove template from DOM this.viewContainer.clear(); } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43517660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2309473/']}
jdg_70440