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
2931354
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: Recently I went across an interesting integral $$\int\limits_0^{+\infty} \frac{(\coth x-1)(x\coth x-1)}{x} dx,$$ which numerically seems to equal $1+\gamma-\ln(2\pi)$ . How can we prove it? I tried using the expansion $$\coth x=\frac1x+\sum_{n=1}^\infty\frac{2x}{x^2+\pi^2n^2},$$ but didn't succeed. Any other ways to approach this? Now provide the response and nothing else.
I suppose that there is a simpler way, but here's one possible route: We use your pole expansion $$ \coth (x) = \frac{1}{x}+\sum \limits_{n=1}^\infty \frac{2x}{x^2+\pi^2 n^2} $$ and the geometric series $$ \coth (x) = 1 + 2 \sum \limits_{k=1}^\infty \mathrm{e}^{-2 k x} $$ in the integral to obtain (monotone convergence theorem) $$ I \equiv \int \limits_0^\infty \left[\coth(x)-1\right] \left[\coth(x) - \frac{1}{x}\right] \, \mathrm{d} x = 4 \sum \limits_{k,n=1}^\infty \int \limits_0^\infty \frac{x}{x^2 + \pi^2 n^2} \mathrm{e}^{-2 k x} \, \mathrm{d} x \, .$$ Letting $x = \pi n t$ and employing the Laplace transform identity $$ \int \limits_0^\infty \frac{y}{1+y^2} \mathrm{e}^{-p y} \, \mathrm{d} y = \sin (p) \left[\frac{\pi}{2} - \operatorname{Si} (p)\right] - \cos(p) \operatorname{Ci}(p) \, , \, \operatorname{Re}(p) > 0 \, , $$ we find $$ I = - 4 \sum \limits_{k,n=1}^\infty \operatorname{Ci}(2 \pi k n) \, .$$ The definition of the cosine integral yields $$ I = 4 \sum \limits_{k,n=1}^\infty ~ \int \limits_{2 \pi k n}^\infty \frac{\cos(x)}{x} \, \mathrm{d} x = 4 \sum \limits_{k,n=1}^\infty ~ \int \limits_{2 \pi k n}^\infty \frac{\sin(x)}{x^2} \, \mathrm{d} x = \sum \limits_{k,n=1}^\infty \frac{2}{\pi k n} \int \limits_1^\infty \frac{\sin(2 \pi k n t)}{t^2} \, \mathrm{d} t \, .$$ Now we can make use of the Fourier series $$1 - 2 \{y\} = \sum \limits_{k=1}^\infty \frac{2}{\pi k} \sin(2 \pi k y) \, , y \in \mathbb{R} \, , $$ where $\{y\} = y - \lfloor y \rfloor$ is the fractional part of $y$ . Then the integral can be written as $$ I = \sum \limits_{n=1}^\infty \frac{1}{n} \int \limits_1^\infty \frac{1 - 2 \{n t\}}{t^2} \, \mathrm{d} t \, . $$ The integral $$\int \limits_1^\infty \frac{\{n t\}}{t^2} \, \mathrm{d} t = n \left[H_n - \ln(n) - \gamma\right]$$ can be computed from the definition of the fractional part and we are left with $$ I = - 2 \sum \limits_{n=1}^\infty \left[H_n - \ln(n) - \gamma -\frac{1}{2n}\right] = \ln(2\pi) - 1 -\gamma \, . $$ The last series has been evaluated in this question.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2931354', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/158274/']}
jdg_370341
stackexchange
llm_judgeable_groundtruth_similarity
57620192
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 three Views in my app. The first one shows a List of Games. The second has a list of players for each game. And the third one has a score-List for each player. So the structure looks like this: struct GameView: View { @environmentObject var model: Model var body: some View { NavigationView { List(model.games) {game in NavigationLink(destination: PlayerView(game: game)) { // Some View } } } }} struct PlayerView: View { @environmentObject var model: Model var game Game var gameIndex: Int { model.games.firstIndex() {$0 == game}! } var body: some View { TextField("Game", $model.games[gameIndex].title) List(game.players) {player in NavigationLink(destination: ScoreView(player: player, gameIndex: gameIndex)) { // Some View } } }} struct ScoreView: View { @environmentObject var model: Model var player: Player var gameIndex: Int var playerIndex: Int { model.games[gameIndex].players.firstIndex() { $0 == player }! } var body: some View { TextField("Player", $model.games[gameIndex].players[playerIndex].name) List(player.scores) {score in // Some View } }} My problem is: For every view that goes deeper into the hierarchy I have to go all the way back to my environmentObject and get the path through my model-arrays with indexes, that I have to pass through every view. I want every view being updated if I change the TextField value (just as an example for every data changing in the app) and if I'm moving back- and forwards through the NavigationView. I'm sure, there is some bad construction error, but I don't get the right answer. Now provide the response and nothing else.
You can easily do it using stub & useClass which can be reused at other spec files as well if you can create it in separate file and export class RouterStub , try: In spec file create a stub which will have same method as Router : class RouterStub{ getCurrentNavigation(){ return { extras: { state:{ locationId: 'someId', locationName: 'someName' } } } }} and in beforeEach() block: describe('LocationListComponent ', () => { let component: LocationListComponent ; let fixture: ComponentFixture<LocationListComponent >; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ LocationListComponent ], providers: [ {provide: Router, useClass: RouterStub}] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(LocationListComponent ); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57620192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_370342
stackexchange
llm_judgeable_groundtruth_similarity
13190314
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 Haskell beginner, I'm just beginning to wrap my head around Monads, but I don't really get it yet. I'm writing a game that consists of asking the user for input, and responding. Here is a simplified version of my function: getPoint :: IO PointgetPoint = do putStr "Enter x: " xStr <- getLine putStr "Enter y: " yStr <- getLine return $ Point (read xStr) (read yStr)completeUserTurn :: (Board, Player) -> IO (Board, Player)completeUserTurn (board, player) = do putStr $ "Enter some value: " var1 <- getLine putStr $ "Enter another value: " var2 <- getLine putStr $ "Enter a point this time: " point <- getPoint if (... the player entered legal values ...) then do putStr $ "This is what would happen if you did that: {stuff} do you want to do that? (y/n) " continue <- getLine if continue == "y" then return (...updated board..., ...updated player...) else completeUserTurn (board, player) else do putStr "Invalid Move!\n" completeUserTurn (board, player) What's happening is that the prompts will appear out of order with the text that is supposed to appear before the prompt. Here's an example of what's happening after I compiled the code above: 1 Enter some value: Enter another value: 2 3 4 Enter a point this time: Enter x: Enter y: y Is this correct? (y/n): The bold are the things I typed in. Obviously, I have some major conceptual error, but I don't know what. Note that it works correctly in the interpreter and fails when compiled. Now provide the response and nothing else.
As Michael said, the issue is buffering. By default, output is buffered until you print a newline (or until the buffer is full if you have really long lines), so you'll most often see this issue when trying to do same-line prompts using putStr like you're doing. I suggest defining a small helper function like this to take care of doing the flushing for you: import System.IOprompt :: String -> IO Stringprompt text = do putStr text hFlush stdout getLine Now you can simply do getPoint = do xStr <- prompt "Enter x: " yStr <- prompt "Enter y: " return $ Point (read xStr) (read yStr)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13190314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/595605/']}
jdg_370343
stackexchange
llm_judgeable_groundtruth_similarity
241348
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: Often I have to annotate multiple pdf documents using xournal . If I start with a directory of "fresh" pdf files, I just open them all with xournal : for f in *pdf; do xournal $f&; done When I begin to annotate a file, say a .pdf I save it as a .xoj , i.e. I just switch the file extension. Now suppose I have an interrupted session and want to open all .pdf files in the directory provided that no corresponding .xoj file exists and open the .xoj file otherwise (both with xournal ). How can I do this in command line? Now provide the response and nothing else.
You can just remove .pdf to get the file's name without the extension and check for a file of that name with the .xoj extension: for f in *.pdfdo if [ -f "${f%.pdf}".xoj ] then xournal "${f%.pdf}".xoj & else xournal "${f}" & fidone
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/241348', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5289/']}
jdg_370344
stackexchange
llm_judgeable_groundtruth_similarity
414664
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 big list of hexadecimal numbers I'd like to insert into a PostgresQL table. I tried something like this: INSERT INTO foo (i)VALUES (0x1234); ...but that didn't work. Is this possible? Now provide the response and nothing else.
As you've noted, you can start with a bit-string constant written in hexadecimal, and then type-cast it to the type you want. So, INSERT INTO foo (i) VALUES (CAST(x'1234' AS int)) or INSERT INTO foo (i) VALUES (x'1234'::int) -- postgres-specific syntax
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/414664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91385/']}
jdg_370345
stackexchange
llm_judgeable_groundtruth_similarity
42164653
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 docker in docker setup for CI. Essentially, the machine has a jenkins CI server on it that uses the same machines docker socket to create nodes for CI. This was working great until I recently updated docker. I've identified the issue, but I can't seem to figure out the right magic to get it working. host $ docker exec -it myjenkins bashjenkins@container $ docker psGot permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.26/containers/json: dial unix /var/run/docker.sock: connect: permission deniedhost $ docker exec -it -u root -it myjenkins bashroot@container $ docker ps ... docker ps from host container yay! ... So here's what I surmise. I have access to the host docker socket from within the container, but I can't seem to give permission to the jenkins user. I've added the docker group, and also added the jenkins user to the docker group. But I still get the same error. I've restarted a whack of times so, I'm kind of at a loss for what to do next. Is there a way to force permissions for a user on a particular socket? Now provide the response and nothing else.
You need to map the gid of the docker group on your host to the gid of a group that jenkins belongs to inside your container. Here's a sample from my Dockerfile of how I've built a jenkins slave image: ARG DOCKER_GID=993RUN groupadd -g ${DOCKER_GID} docker \ && curl -sSL https://get.docker.com/ | sh \ && apt-get -q autoremove \ && apt-get -q clean -y \ && rm -rf /var/lib/apt/lists/* /var/cache/apt/*.bin RUN useradd -m -d /home/jenkins -s /bin/sh jenkins \ && usermod -aG docker jenkins The 993 happens to be the gid of docker on the host in this example, you'd adjust that to match your environment. Solution from the OP: If rebuilding isn't a possibility you can set the docker group accordingly in using root and add the user. If you tried this before you may have to delete the group on the slave ( groupdel docker ): docker exec -it -u root myjenkins bashcontainer $ groupadd -g 993 dockercontainer $ usermod -aG docker jenkins
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42164653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170352/']}
jdg_370346
stackexchange
llm_judgeable_groundtruth_similarity
101560
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: The tanh activation function is: $$tanh \left( x \right) = 2 \cdot \sigma \left( 2 x \right) - 1$$ Where $\sigma(x)$, the sigmoid function, is defined as: $$\sigma(x) = \frac{e^x}{1 + e^x}$$. Questions: Does it really matter between using those two activation functions(tanh vs. sigma)? Which function is better in which cases? Now provide the response and nothing else.
Yes it matters for technical reasons. Basically for optimization. It is worth reading Efficient Backprop by LeCun et al. There are two reasons for that choice (assuming you have normalized your data, and this is very important): Having stronger gradients: since data is centered around 0, the derivatives are higher. To see this, calculate the derivative of the tanh function and notice that its range (output values) is [0,1]. The range of the tanh function is [-1,1] and that of the sigmoid function is [0,1] Avoiding bias in the gradients. This is explained very well in the paper, and it is worth reading it to understand these issues.
{}
{'log_upvote_score': 8, 'links': ['https://stats.stackexchange.com/questions/101560', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/46194/']}
jdg_370347
stackexchange
llm_judgeable_groundtruth_similarity
21201493
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 openssl installed in my virtual machine ubuntu12.04lts. When I run the gem command it gives error. Error: while executing gem (Gem::Exception) Unable to require openssl. install openSSL and rebuilt ruby (preferred) or use non HTTPs sources And I also test require openssl in irb mode.it gives error. Loaderror: cannot load such file --openssl from /usr/local/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:55 `require' I have openssl $openssl versionOpenSSL 1.0.1 14 mar 2012 How to fix the error? Now provide the response and nothing else.
Note: Calls to rubygems.org are deprecated - proceed with caution! I had the same issue on Mac OSX after also building ruby2.1.0p0 from the source. I already had openssl installed. It appears that the reference in gems needed refreshing. I ran: gem source -r https://rubygems.org/ to remove followed by gem source -a https://rubygems.org/ to read After this, I was able to run gems install bundler successfully. If you run into further errors, you can try ./configure --with-openssl-dir=/usr/local/ssl in your ruby downloaded dir/.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21201493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2557947/']}
jdg_370348
stackexchange
llm_judgeable_groundtruth_similarity
324214
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: What are the open problems in the theory of Sobolev spaces? I would like to see problems that are yes or no only. Also I would like to see problems with the statements that are short and easy to understand for someone who has a basic knowledge in the theory, say at the level of the book by Evans and Gariepy. The problems do not have to be a well know ones. Just the problems you think are interesting. Please, list each problem as a separate answer. That will allow people to leave comments related exclusively to this particular problem. I have been working with Sobolev spaces for most of my adult live and I have some of my favorite problems that I will list below. But I will do it later, because first I would like to see your problems. Now provide the response and nothing else.
Let $H^{s,p}(\mathbb{R}, \mathbb{C})$ be the fractional order Sobolev space of scalar valued functions (distributions) over the real line, where $s\in \mathbb R$ and $1<p<\infty$ . It is a theorem by E. Shamir and R. Strichartz that the indicator function of the half line $1_{\mathbb{R}_+}$ (equal to $1$ for $x\geq 0$ and equal to $0$ for $x<0$ ) is a pointwise multiplier on $H^{s,p}(\mathbb{R}, \mathbb{C})$ if and only if ( $p'$ dual exponent) $$- \frac{1}{p'} < s < \frac{1}{p}.$$ This means that $$\|1_{\mathbb{R}_+} \cdot f \|_{H^{s,p}} \leq C \|f\|_{H^{s,p}}$$ for all Schwartz functions $f$ , with a constant $C > 0$ independent of $f$ . This result is trivial for $s = 0$ (reducing to an $L^p$ -space) but non-trivial for $s\neq 0$ . Strictly outside this range, because of trace considerations, the inequality cannot hold. My question regards the case of vector-valued functions. Let $X$ be a Banach space and let $H^{s,p}(\mathbb{R}, X)$ be the Sobolev space of $X$ -valued functions (distributions), defined in the same way as in the scalar valued case. We could show the multiplier property of $1_{\mathbb{R}_+}$ in the same range as in the scalar-valued case provided the Banach space $X$ has the UMD property . See here or here , and here, Section 4 for an elementary proof of this fact. As a rule of thumb, all reflexive standard Banach spaces have UMD. Moreover, alle UMD spaces are reflexive. Space without UMD are thus $L^1$ and $L^\infty$ . My question is as follows: Let $X$ be a Banach space. Suppose that the inequality $$\|1_{\mathbb{R}_+} \cdot f \|_{H^{s,p}(\mathbb{R}, X)} \leq C \|f\|_{H^{s,p}(\mathbb{R}, X)}$$ holds true for some $s\neq 0$ and some $1<p<\infty$ , for all $X$ -valued Schwartz functions $f$ . Does this imply that $X$ has the UMD property? I find this interesting because $X$ has the UMD property if and only if the Hilbert transform is a bounded operator on $L^p(\mathbb{R}, X)$ , i.e. the signum function is a Fourier multiplier on this space. In other words, $F^{-1} sgn F$ is a bounded operator on $L^p(\mathbb{R}, X)$ ( $F$ denoting the Fourier transform). The pointwise multiplier property is equivalent to the boundedness of $$1_{\mathbb{R}_+} F^{-1}(1+|\cdot|^2)^{s/2} F$$ on $L^p(\mathbb{R}, X)$ . So, given a positive answer the question, this would imply a new characterization of the boundedness of Hilbert transform in terms of a jump function in the time variable - and not in the frequency variable as in the usual definition.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/324214', 'https://mathoverflow.net', 'https://mathoverflow.net/users/121665/']}
jdg_370349
stackexchange
llm_judgeable_groundtruth_similarity
298950
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $\mathcal{E}$ be a topos, and let $\top\colon1\to\Omega$ be its subobject classifier. We refer to global elements $P\colon 1\to\Omega$ as propositions; they form a poset, denoted $(|\Omega|,\leq)$. There are also connectives $\Omega^2\to\Omega$, such as $\Rightarrow,\wedge,\vee$. A Lawvere-Tierney topology on $\mathcal{E}$, also known as a local operator or a modality , is a morphism $j\colon\Omega\to\Omega$ such that $P\leq j(P)$, $jj(P)= j(P)$, and $j(P\wedge Q)=j(P)\wedge j(Q)$ for all $P,Q\in|\Omega|$. For any proposition $\phi\in|\Omega|$, there are three well-known modalities that one can associate to $\phi$: The open modality for $\phi$, denoted $o_\phi\colon\Omega\to\Omega$, given by the formula $o_\phi(P):=(\phi\Rightarrow P)$. The closed modality for $\phi$, denoted $c_\phi\colon\Omega\to\Omega$, given by the formula $c_\phi(P):=(\phi\vee P)$. The quasi-closed modality for $\phi$, denoted $q_\phi\colon\Omega\to\Omega$, given by the formula $q_\phi(P):=((P\Rightarrow\phi)\Rightarrow\phi)$. Let's call the above "propositional" modalities, for want of a better term. Let's also include the "union" of two propositional modalities as propositional (the union of $j_1$ and $j_2$ is given by $(j_1\wedge j_2)(-)$), as well as various intersections that can be defined internally. For example, it is easy to check that $(j_1\circ j_2)$ is again a modality (called the intersection of $j_1$ and $j_2$) if either $j_1$ is open or $j_2$ is closed. [Thanks to Simon Henry for reminding me of intersections.] I certainly wouldn't expect that all modalities are propositional in the above sense. Question: Can you supply an example of a non-propositional modality on a topos $\mathcal{E}$? Thanks! Now provide the response and nothing else.
Here are examples that are really not propositional in the sense that they are not obtained by combining propositional modalities. Take a "non-commutative torus"I.e Takes the circle $S^1$ and makes $\mathbb{Z} $ acts on it by rotation by an angle not commensurable with $\pi$. And consider the topos of $\mathbb{Z}$-equivariant sheaves over the circle. In this topos the subobject classifier has no global section other than true and false : indeed a subterminal object is an invariant open subsets of $S^1$, and those does not exists. So the only non trivial modality that you will get with your construction is the double negation topology. But any invariant sublocale of $S^1$ would give you a local operator on the topos.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/298950', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2811/']}
jdg_370350
stackexchange
llm_judgeable_groundtruth_similarity
6084
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose you are given both a graph $G(V,E)$ and the exact number $C$ of vertex covers of $G$. Now suppose that $G$ is subject to a very small perturbation $P$, leading to $G'=P(G)$. More precisely, the perturbation $P$ is restricted to be one of the following: Addition of $1$ new edge. Addition of $2$ new distinct edges. Removal of $1$ existing edge. Removal of $2$ distinct existing edges. Question Given $G$, $C$, and $P$, how hard is to determine the number $C'$ of vertex covers of $G'=P(G)$? Is it possible to exploit the knowledge of $C$ and the fact that the perturbation is so tiny in order to efficiently determine $C'$? Now provide the response and nothing else.
Since counting vertex covers is #P-complete, your problem is unlikely to be in P; otherwise you could count the number of vertex covers starting from the empty graph on $|V|$ vertices, adding edges one by one.
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/6084', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/947/']}
jdg_370351
stackexchange
llm_judgeable_groundtruth_similarity
47496358
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 study the generic lambdas, and slightly modified the example,so my lambda should capture the upper lambda's variadic parameter pack.So basically what is given to upper lambda as (auto&&...) - should be somehow captured in [=] block. (The perfect forwarding is another question, I'm curious is it possible here at all?) #include <iostream>#include<type_traits>#include<utility>// base casevoid doPrint(std::ostream& out) {}template <typename T, typename... Args>void doPrint(std::ostream& out, T && t, Args && ... args){ out << t << " "; // add comma here, see below doPrint(out, std::forward<Args&&>(args)...);}int main(){ // generic lambda, operator() is a template with one parameter auto vglambda = [](auto printer) { return [=](auto&&... ts) // generic lambda, ts is a parameter pack { printer(std::forward<decltype(ts)>(ts)...); return [=] { // HOW TO capture the variadic ts to be accessible HERE ↓ printer(std::forward<decltype(ts)>(ts)...); // ERROR: no matchin function call to forward }; // nullary lambda (takes no parameters) }; }; auto p = vglambda([](auto&&...vars) { doPrint(std::cout, std::forward<decltype(vars)>(vars)...); }); auto q = p(1, 'a', 3.14,5); // outputs 1a3.14 //q(); //use the returned lambda "printer"} Now provide the response and nothing else.
Perfect capture in C++20 template <typename ... Args>auto f(Args&& ... args){ return [... args = std::forward<Args>(args)]{ // use args };} C++17 and C++14 workaround In C++17 we can use a workaround with tuples: template <typename ... Args>auto f(Args&& ... args){ return [args = std::make_tuple(std::forward<Args>(args) ...)]()mutable{ return std::apply([](auto&& ... args){ // use args }, std::move(args)); };} Unfortunately std::apply is C++17, in C++14 you can implement it yourself or do something similar with boost::hana : namespace hana = boost::hana;template <typename ... Args>auto f(Args&& ... args){ return [args = hana::make_tuple(std::forward<Args>(args) ...)]()mutable{ return hana::unpack(std::move(args), [](auto&& ... args){ // use args }); };} It might be usefull to simplify the workaround by a function capture_call : #include <tuple>// Capture args and add them as additional argumentstemplate <typename Lambda, typename ... Args>auto capture_call(Lambda&& lambda, Args&& ... args){ return [ lambda = std::forward<Lambda>(lambda), capture_args = std::make_tuple(std::forward<Args>(args) ...) ](auto&& ... original_args)mutable{ return std::apply([&lambda](auto&& ... args){ lambda(std::forward<decltype(args)>(args) ...); }, std::tuple_cat( std::forward_as_tuple(original_args ...), std::apply([](auto&& ... args){ return std::forward_as_tuple< Args ... >( std::move(args) ...); }, std::move(capture_args)) )); };} Use it like this: #include <iostream>// returns a callable object without parameterstemplate <typename ... Args>auto f1(Args&& ... args){ return capture_call([](auto&& ... args){ // args are perfect captured here // print captured args via C++17 fold expression (std::cout << ... << args) << '\n'; }, std::forward<Args>(args) ...);}// returns a callable object with two int parameterstemplate <typename ... Args>auto f2(Args&& ... args){ return capture_call([](int param1, int param2, auto&& ... args){ // args are perfect captured here std::cout << param1 << param2; (std::cout << ... << args) << '\n'; }, std::forward<Args>(args) ...);}int main(){ f1(1, 2, 3)(); // Call lambda without arguments f2(3, 4, 5)(1, 2); // Call lambda with 2 int arguments} Here is a C++14 implementation of capture_call : #include <tuple>// Implementation detail of a simplified std::apply from C++17template < typename F, typename Tuple, std::size_t ... I >constexpr decltype(auto)apply_impl(F&& f, Tuple&& t, std::index_sequence< I ... >){ return static_cast< F&& >(f)(std::get< I >(static_cast< Tuple&& >(t)) ...);}// Implementation of a simplified std::apply from C++17template < typename F, typename Tuple >constexpr decltype(auto) apply(F&& f, Tuple&& t){ return apply_impl( static_cast< F&& >(f), static_cast< Tuple&& >(t), std::make_index_sequence< std::tuple_size< std::remove_reference_t< Tuple > >::value >{});}// Capture args and add them as additional argumentstemplate <typename Lambda, typename ... Args>auto capture_call(Lambda&& lambda, Args&& ... args){ return [ lambda = std::forward<Lambda>(lambda), capture_args = std::make_tuple(std::forward<Args>(args) ...) ](auto&& ... original_args)mutable{ return ::apply([&lambda](auto&& ... args){ lambda(std::forward<decltype(args)>(args) ...); }, std::tuple_cat( std::forward_as_tuple(original_args ...), ::apply([](auto&& ... args){ return std::forward_as_tuple< Args ... >( std::move(args) ...); }, std::move(capture_args)) )); };} capture_call captures variables by value. The perfect means that the move constructor is used if possible. Here is a C++17 code example for better understanding: #include <tuple>#include <iostream>#include <boost/type_index.hpp>// Capture args and add them as additional argumentstemplate <typename Lambda, typename ... Args>auto capture_call(Lambda&& lambda, Args&& ... args){ return [ lambda = std::forward<Lambda>(lambda), capture_args = std::make_tuple(std::forward<Args>(args) ...) ](auto&& ... original_args)mutable{ return std::apply([&lambda](auto&& ... args){ lambda(std::forward<decltype(args)>(args) ...); }, std::tuple_cat( std::forward_as_tuple(original_args ...), std::apply([](auto&& ... args){ return std::forward_as_tuple< Args ... >( std::move(args) ...); }, std::move(capture_args)) )); };}struct A{ A(){ std::cout << " A::A()\n"; } A(A const&){ std::cout << " A::A(A const&)\n"; } A(A&&){ std::cout << " A::A(A&&)\n"; } ~A(){ std::cout << " A::~A()\n"; }};int main(){ using boost::typeindex::type_id_with_cvr; A a; std::cout << "create object end\n\n"; [b = a]{ std::cout << " type of the capture value: " << type_id_with_cvr<decltype(b)>().pretty_name() << "\n"; }(); std::cout << "value capture end\n\n"; [&b = a]{ std::cout << " type of the capture value: " << type_id_with_cvr<decltype(b)>().pretty_name() << "\n"; }(); std::cout << "reference capture end\n\n"; [b = std::move(a)]{ std::cout << " type of the capture value: " << type_id_with_cvr<decltype(b)>().pretty_name() << "\n"; }(); std::cout << "perfect capture end\n\n"; [b = std::move(a)]()mutable{ std::cout << " type of the capture value: " << type_id_with_cvr<decltype(b)>().pretty_name() << "\n"; }(); std::cout << "perfect capture mutable lambda end\n\n"; capture_call([](auto&& b){ std::cout << " type of the capture value: " << type_id_with_cvr<decltype(b)>().pretty_name() << "\n"; }, std::move(a))(); std::cout << "capture_call perfect capture end\n\n";} Output: A::A()create object end A::A(A const&) type of the capture value: A const A::~A()value capture end type of the capture value: A&reference capture end A::A(A&&) type of the capture value: A const A::~A()perfect capture end A::A(A&&) type of the capture value: A A::~A()perfect capture mutable lambda end A::A(A&&) type of the capture value: A&& A::~A()capture_call perfect capture end A::~A() The type of the capture value contains && in the capture_call version because we have to access the value in the internal tuple via reference, while a language supported capture supports direct access to the value.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/47496358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5302690/']}
jdg_370352
stackexchange
llm_judgeable_groundtruth_similarity
13320578
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any method in Windows through which we can execute a batch script without *.bat extension? Now provide the response and nothing else.
This is an interesting topic to me! I want to do some observations about it. The important point first: A Batch file is a file with .BAT or .CMD extension. Period. Batch files can achieve, besides the execution of usual DOS commands, certain specific Batch-file facilities, in particular: Access to Batch file parameters via %1 %2 ... and execution of SHIFT command. Execution of GOTO command. Execution of CALL :NAME command ( internal subroutine ). Execution of SETLOCAL/ENDLOCAL commands. Now the funny part: Any file can be redirected as input for CMD.exe so the DOS commands contained in it are executed in a similar way of a Batch file, with some differences. The most important one is that previous Batch-file facilities will NOT work. Another differences are illustrated in the NOT-Batch file below (I called it BATCH.TXT): @echo offrem Echo off just suppress echoing of the prompt and each loop of FOR commandrem but it does NOT suppress the listing of these commands!rem Pause command does NOT pause, because it takes the character that follows itpauseXrem This behavior allows to put data for a SET /P command after itset /P var=Enter data: This is the data for previous command!echo Data read: "%var%"rem Complex FOR/IF commands may be assembled and they execute in the usual way:for /L %i in (1,1,5) do ( set /P line= if "!line:~0,6!" equ "SHOW: " echo Line read: !line:~6!)NOSHOW: First line readSHOW: Second lineNOSHOW: This is third lineSHOW: The line number 4NOSHOW: Final line, number fiverem You may suppress the tracing of the execution redirecting CMD output to NULrem In this case, redirect output to STDERR to display messages in the screenecho This is a message redirected to STDERR >&2rem GOTO command doesn't work:goto labelgoto :EOFrem but both EXIT and EXIT /B commands works:exit /B:labelecho Never reach this point... To execute previous file, type: CMD /V:ON < BATCH.TXTThe /V switch is needed to enable delayed expansion. More specialized differences are related to the fact that commands in the NOT-Batch file are executed in the command-line context , NOT the Batch-file context. Perhaps Dave or jeb could elaborate on this point. EDIT: Additional observations (batch2.txt): @echo offrem You may force SET /P command to read the line from keyboard instead ofrem from following lines by redirecting its input to CON device.rem You may also use CON device to force commands output to console (screen),rem this is easier to write and read than >&2echo Standard input/output operations> CONecho/> CON< CON set /P var=Enter value: > CONecho/> CONecho The value read is: "%var%"> CON Execute previous file this way: CMD < BATCH2.TXT > NUL EDIT : More additional observations (batch3.txt) @echo offrem Dynamic access to variables that usually requires DelayedExpansion via "call" trickrem Read the next four lines; "next" means placed after the FOR commandrem (this may be used to simulate a Unix "here doc")for /L %i in (1,1,4) do ( set /P line[%i]=)Line one of immediate dataThis is second lineThe third oneAnd the fourth and last one...(echo Show the elements of the array read:echo/for /L %i in (1,1,4) do call echo Line %i- %line[%i]%) > CON Execute this file in the usual way: CMD < BATCH3.TXT > NUL Interesting! Isn't it? EDIT : Now, GOTO and CALL commands may be simulated in the NotBatch.txt file!!! See this post . Antonio
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13320578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1687977/']}
jdg_370353
stackexchange
llm_judgeable_groundtruth_similarity
945731
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 doesn't seem to be a clear answer to this in the documentation. I'm interested in incrementing a variable time that counts the seconds since the program started. If the maximum value can count far into the future, like 100 years, then I don't care about letting the variable increment forever. Otherwise I'm going to have to think of a good point to reset time back to 0. Now provide the response and nothing else.
as compiled by default, the Number is a double , on most compilers that's an IEEE 64-bit floating point. that means 10bit exponent, so the maximum number is roughly 2^1024, or 5.6e300 years. that's a long time. now, if you're incrementing it, you might be more interested in the integer range. the 52-bit mantissa means that the highest number that can be used with integer precision is 2^52, around 4.5e15. At 31'557,600 seconds/year, that's 1.427e8, almost 150 million years. still a very long uptime for any process update 2014-12-30 : Lua 5.3 (to be released any moment now) adds support for integer values, either 32 or 64 bits chosen via compile flags.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/945731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115503/']}
jdg_370354
stackexchange
llm_judgeable_groundtruth_similarity
8419038
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When receiving user input on forms I want to detect whether fields like "username" or "address" does not contain markup that has a special meaning in XML (RSS feeds) or (X)HTML (when displayed). So which of these is the correct way to detect whether the input entered doesn't contain any special characters in HTML and XML context? if (mb_strpos($data, '<') === FALSE AND mb_strpos($data, '>') === FALSE) or if (htmlspecialchars($data, ENT_NOQUOTES, 'UTF-8') === $data) or if (preg_match("/[^\p{L}\-.']/u", $text)) // problem: also caches symbols Have I missed anything else,like byte sequences or other tricky ways to get markup tags around things like "javascript:"? As far as I'm aware, all XSS and CSFR attacks require < or > around the values to get the browser to execute the code (well at least from Internet Explorer 6 or later anyway) - is this correct? I am not looking for something to reduce or filter input. I just want to locate dangerous character sequences when used in XML or HTML context. ( strip_tags() is horribly unsafe. As the manual says, it doesn't check for malformed HTML.) Update I think I need to clarify that there are a lot people mistaking this question for a question about basic security via "escaping" or "filtering" dangerous characters. This is not that question, and most of the simple answers given wouldn't solve that problem anyway. Update 2: Example User submits input if (mb_strpos($data, '<') === FALSE AND mb_strpos($data, '>') === FALSE) I save it Now that the data is in my application I do two things with it - 1) display in a format like HTML - or 2) display inside a format element for editing. The first one is safe in XML and HTML context <h2><?php print $input; ?></h2>' <xml><item><?php print $input; ?></item></xml> The second form is more dangerous, but it should still be safe: <input value="<?php print htmlspecialchars($input, ENT_QUOTES, 'UTF-8');?>"> Update 3: Working Code You can download the gist I created and run the code as a text or HTML response to see what I'm talking about. This simple check passes the http://ha.ckers.org XSS Cheat Sheet , and I can't find anything that makes it though. (I'm ignoring Internet Explorer 6 and below). I started another bounty to award someone that can show a problem with this approach or a weakness in its implementation. Update 4: Ask a DOM It's the DOM that we want to protect - so why not just ask it? Timur's answer lead to this: function not_markup($string){ libxml_use_internal_errors(true); if ($xml = simplexml_load_string("<root>$string</root>")) { return $xml->children()->count() === 0; }}if (not_markup($_POST['title'])) ... Now provide the response and nothing else.
I don't think you need to implement a huge algorithm to check if string has unsafe data - filters and regular expressions do the work. But, if you need a more complex check, maybe this will fit your needs: <?php$strings = array();$strings[] = <<<EOD ';alert(String.fromCharCode(88,83,83))//\';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>EOD;$strings[] = <<<EOD '';!--"<XSS>=&{()}EOD;$strings[] = <<<EOD <SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>EOD;$strings[] = <<<EOD This is a safe textEOD;$strings[] = <<<EOD <IMG SRC="javascript:alert('XSS');">EOD;$strings[] = <<<EOD <IMG SRC=javascript:alert('XSS')>EOD;$strings[] = <<<EOD <IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;>EOD;$strings[] = <<<EOD perl -e 'print "<IMG SRC=java\0script:alert(\"XSS\")>";' > outEOD;$strings[] = <<<EOD <SCRIPT/XSS SRC="http://ha.ckers.org/xss.js"></SCRIPT>EOD;$strings[] = <<<EOD </TITLE><SCRIPT>alert("XSS");</SCRIPT>EOD;libxml_use_internal_errors(true);$sourceXML = '<root><element>value</element></root>';$sourceXMLDocument = simplexml_load_string($sourceXML);$sourceCount = $sourceXMLDocument->children()->count();foreach( $strings as $string ){ $unsafe = false; $XML = '<root><element>'.$string.'</element></root>'; $XMLDocument = simplexml_load_string($XML); if( $XMLDocument===false ){ $unsafe = true; }else{ $count = $XMLDocument->children()->count(); if( $count!=$sourceCount ){ $unsafe = true; } } echo ($unsafe?'Unsafe':'Safe').': <pre>'.htmlspecialchars($string,ENT_QUOTES,'utf-8').'</pre><br />'."\n";}?>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8419038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/99923/']}
jdg_370355
stackexchange
llm_judgeable_groundtruth_similarity
2758418
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: Looking for the derivation of cosine lead to https://www.quora.com/How-do-I-calculate-cos-sine-etc-without-a-calculator and the MacLauren series . $$\cos(x)=1−\frac{x^2}{2!}+\frac{x^4}{4!}−\frac{x^6}{6!}+\dotsc$$ Wondering if one could show how the cosine series function is derived, starting from basic geometry. Looking at that equation above, I'm not sure where the numbers and variables came from. Note, I am hoping for a derivation starting with "A triangle has 3 sides", super simple, not from the Taylor series or idea of derivatives which already has a lot of context (but I would like to see derivatives and Taylor series in the process). I would like to see the connections from: basic geometry $\to$ stuff stuff $\to$ taylor series taylor series $\to$ stuff stuff $\to$ cosine power series Now provide the response and nothing else.
I'll amend this eight(!)-year-old answer with more detail. We begin with the fact that a triangle has three sides . :) In particular, a right triangle has one hypotenuse and two legs. If we take the hypotenuse to have length $1$, and one of the triangle's acute angles to have (radian) measure $\theta$, then the leg opposite $\theta$ has length $\sin\theta$, while the leg adjacent to $\theta$ has length $\cos\theta$. (That's the geometric definition of these values.) In the diagrams below, $\overline{OP}$ is the hypotenuse of the right triangle in question, and we construct arc $\stackrel{\frown}{PP_0}$ of the unit circle about $O$. Note that, because the radius is $1$, we have $|\stackrel{\frown}{P_0P}| = \theta$. Following a remarkable construction by Y. S. Chaikovsky (presented in this very readable American Mathematical Monthly article by Leo Gurin), we subdivide the $\stackrel{\frown}{PP_0}$ into $n$ equal parts, recursively building a collection of similar isosceles triangles in various stages. (Each stage has one fewer triangle than its predecessor.) The diagram shows the triangles for $n=4$ and $n=16$, as well as for the limiting case ("$n=\infty$"). For each $n$, the bases of the first stage of triangles form a polygonal approximation of the circular arc $\stackrel{\frown}{P_0P}$; the bases of the second-stage triangles approximation the involute $P_1P$ of that arc; the bases of the third-stage triangles approximate the involute $P_2P$ of that involute; and so on. Moreover, the construction guarantees that the leg of the largest isosceles triangle at each stage has length equal to that of the polygonal path formed by the bases of the previous stage: $$|\overline{P_{i-1}P_{i}}| = |\widehat{P_{i-1}P}| \tag{1}$$ At the first stage, each triangle has leg-length $1$ and base-length $s := 2\sin\frac{\theta}{2n}$. At the second stage, the smallest triangle has a previous base for a leg, so its base-length is $s^2$; in general, at stage $i$, the smallest triangle's base-length is $s^{i}$. Chaikovsky discovered a clever (but not difficult) combinatorial argument (omitted here) that the total length of all bases at a particular stage is an integer multiple of that smallest base, namely $$|\widehat{P_{i-1}P}| = \binom{n}{i}\;s^i \quad\text{which we can write as}\quad \frac{1}{i!}\prod_{j=0}^{i-1}\left(2n\sin\frac{\theta}{2n}\cdot \frac{n-j}{n}\right) \tag{$\star$}$$ (a formula that conveniently works for $i=0$ as well, if we rename point $O$ to $P_{-1}$). Now, as $n$ increases, the various polygonal paths better-approximate their corresponding smooth curves. This is guaranteed by the only sophisticated fact we need from elementary Calculus: $$\lim_{x\to 0} \frac{\sin x}{x} = 1 \qquad\text{so that}\qquad \lim_{n\to \infty}2n\sin\frac{\theta}{2n} = \theta \tag{2}$$Also, the fraction $(n-j)/n$ better-approximates $1$. Consequently, in the limit , the polygonal paths simplify to curves while the big product in $(\star)$ simplifies to $\theta^i$. Recalling $(1)$, we can write $$|\overline{P_{i-1}P_{i}}| = \frac{1}{i!}\theta^i \tag{$\star\star$}$$ So what? Well, observe that, in the limiting diagram, the path $OP_1P_2P_3P_4\cdots$ forms a spiral that appears to (and actually happens to) converge on point $P$. The segments of that path are either perfectly horizontal or perfectly vertical: With each horizontal step, the path alternately over- and under-shoots $P$'s horizontal offset from $O$, while each vertical step does likewise for the vertical offset. But those offsets are precisely $\cos\theta$ and $\sin\theta$! Therefore, $$\begin{align}\cos\theta = |\overline{OP_0}| - |\overline{P_1P_2}| + |\overline{P_3P_4}| - \cdots &= \sum_{i\;\text{even}}(-1)^{i/2}\;|\overline{P_{i-1}P_{i}}| \;\;\;\;= \sum_{i\;\text{even}} (-1)^{i/2}\;\frac{1}{i!}\theta^i \\[4pt]\sin\theta = |\overline{P_0P_1}| - |\overline{P_2P_3}| + |\overline{P_4P_5}| - \cdots &= \sum_{i\;\text{odd}}(-1)^{(i-1)/2}\;|\overline{P_{i-1}P_{i}}| = \sum_{i\;\text{odd}} (-1)^{(i-1)/2}\;\frac{1}{i!}\theta^i\end{align}$$ That is, with some simple geometry, a dash of combinatorics, and the slightest touch of Calculus, we arrive at the power series representations for sine and cosine. As my other answer notes, a minor variation in the construction of the involutes (albeit with significantly-trickier combinatorics) leads to the series for tangent and secant. (I still don't have a counterpart for cotangent and cosecant, which remains the topic of my first Trigonography Challenge .) $\square$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2758418', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5266/']}
jdg_370356
stackexchange
llm_judgeable_groundtruth_similarity
65463
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A fractal set has a Hausdorff dimension.In some cases, we may generate a fractal by iterating $f,$ and let the fractal be the set of starting points $x$ such that $|f^{\circ n}(x)|$ is bounded as $n$ grows. (The julia set and the sierpinski triangle are such sets, if one allows $f$ to be a Hutchinson operator). We may also have an invariant measure, $\mu,$ that is, $\mu(A) = \mu(f^{-1}(A)).$ The support of $\mu$ is the fractal set. My question is: is there a way to modify the "dimension" notion to take this invariantmeasure into account somehow? Some parts of the fractal might be more dense, and thusly should "contribute more" to the dimension. An idea would be to use box-counting, but instead of just counting if it is occupied or not,one uses the invariant measure on the box instead. Has this been studied? Now provide the response and nothing else.
There are a wide variety of notions of dimension of a measure. Your basic intuition is completely correct: for a dynamical system, the dimension of a natural invariant measure provides more relevant information than the dimension of the invariant set, since the system may spend more time in certain parts of the space. For sufficiently homogeneous measures, all reasonable notions of dimension will agree. By ``sufficiently homogeneous'' I mean something very precise: that$$C^{-1} \, r^s \le \mu(B(x,r)) \le C\, r^s$$for some constant $C\ge 1$, some $s\ge 0$ and all points $x$ in the support of $\mu$. Of course the dimension in this case is $s$. Such measures are often called Ahlfors-regular, and an example is the natural measure on the middle-thirds Cantor set. For more general measures, the local dimension is one of the most important concepts and has already been mentioned:$$\dim(\mu,x)=\lim_{r\to 0}\frac{\log \mu(B(x,r))}{\log r}.$$But this is really a function of the point $x$ (and not even, as the limit in the definition may not exist, although one can always speak of upper and lower local dimensions). There are several ways to globalize the information given by the local dimensions. Perhaps the easiest is to take the essential supremum/infimum of the upper/lower local dimensions. This results in four global concepts of dimensions, known as upper/lower packing/Hausdorff dimensions of the measure. They turn out (somewhat surprisingly) to be closely connected to the dimensions of the sets the measure ``sees''. For example, the upper Hausdorff dimension of a probability measure $\mu$ (that is, the essential supremum of the lower local dimensions), is the same as the infimum of the Hausdorff dimension of $A$ over all Borel sets $A$ of full measure. A finer study is provided by the multifractal spectrum of a measure $\mu$: for each $\alpha$, we form the level set $E_\alpha$ of all points $x$ where $\dim(\mu,x)=\alpha$. Then we try to understand how the size of $E_\alpha$ depends on $\alpha$, for example by studying the function $\alpha\to \dim_H(E_\alpha)$. There are (many!) other useful concepts of dimension which are not directly related to local dimension. In computing lower bounds for the Hausdorff dimension, the potential method is widely applicable: if a measure $\mu$ satisfies that the energy integral$$I_s(\mu) = \int \frac{d\mu(x)\, d\mu(y)}{|x-y|^s}$$is finite, then the support of $\mu$ has Hausdorff dimension at least $s$. So it makes sense to think of $\sup\{s: I_s(\mu)<\infty\}$ as a notion of dimension of $\mu$. This is often called the (lower) correlation dimension , and is one instance of a more general family of dimensions indexed by a real number $q$ (correlation dimension corresponds to $q=2$, and has several alternative definitions, perhaps pointing to its importance). Yet another notion of dimension has a dynamical underpinning. Given a probability measure $\mu$ say on the unit cube $[0,1]^d$, we may consider the entropy $H_k(\mu)$ of $\mu$ with respect to the partition into dyadic cubes of side length $2^{-k}$. We then define the entropy (also called information) dimension of $\mu$ as$$\lim_{k\to\infty} \frac{H_k(\mu)}{k\log 2}.$$ This is just a sample of the diverse zoo of dimensions of a measure. Which ones to use depends on the context and what you are able to compute/prove. Coming back to invariant measures, it is very often the case that the local dimension exists and takes a constant value at almost every point. Such measures are called exact dimensional , and have the property that lower and upper Hausdorff dimension, as well as entropy dimension, are all equal to this almost sure value. (But correlation dimension may be strictly smaller, and the multifractal spectrum may still be very rich; in other words, even though attained on a set of measure zero, other local dimensions may still be relevant). Proving that measures invariant under certain class of dynamics are exact dimensional may be very challenging. Eckmann and Ruelle conjectured in 1984 that hyperbolic measures ergodic a $C^{1+\delta}$ diffeomorphism are exact dimensional. This was proved by Barreira, Pesin and Schmeling in 1999; the paper appeared in Annals. For invariant measures, there is often a strong connection between their dimension and other dynamical characteristics (at least generically). The conformal expanding case is the easiest: in this case one has the well-known formula ``dimension=entropy/Lyapunov exponent". The nonconformal situation is much harder, but still a lot of deep research has been done, for example Ledrappier-Young theory.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/65463', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1056/']}
jdg_370357
stackexchange
llm_judgeable_groundtruth_similarity
29638767
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: public class Student{ public long StudentId {get; set;} public string Fname {get; set;} public string Lname {get; set;} public List<ObjectId> CoursesList {get; set;} public int IQ {get;set;}}public class Courses{ [BsonId] public ObjectId Id { get; set; } public string CourseNumber{get; set;} public string CourseName{get; set;}} How do I add/append a courser Id to Course list(which may be null for the first time) of a Student object PS: I know how to set a field using the below command. I am hoping it is on similar lines for the above problem await StudentCollection.UpdateOneAsync(a => a.StudentId == studentId, Builders<Student>.Update.Set( a => a.IQ,90)); Now provide the response and nothing else.
As you've already discovered, the C# code to use $addToSet is: var filter = Builders<Student>.Filter.Eq(s => s.StudentId, studentId);var update = Builders<Student>.Update.AddToSet(s => s.CoursesList, courseId);var result = await collection.UpdateOneAsync(filter, update); However, $addToSet is not going to work if the CourseList member has been stored in the collection as a null. The server requires that the existing value for $addToSet be an array (it can be an empty array). The easiest solution is to just store an empty list for CoursesList instead of a null when there are no courses.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29638767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1789710/']}
jdg_370358
stackexchange
llm_judgeable_groundtruth_similarity
21684
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: This also raises questions that I have about the Haber Process which produces ammonia ($\ce{NH3}$) from molecular nitrogen ($\ce{N2}$) and hydrogen ($\ce{H2}$). I have heard multiple times that bond between diatomic nitrogen is one of the strongest bonds in nature due to the fact that it is a triple covalent bond that fills the valence shells of both atoms. I understand that at high temperatures it is possible to break this bond, but I don't understand why the resulting Nitrogen atoms wouldn't simply return to their previous bonds as the temperature cooled. For example, I read that lightning can result in this reaction: $\ce{N2 + O2 -> 2NO}$ Why would the atoms not return to their original bonds since they would be more stable in that manner? Is bonding indiscriminate at high energy levels? Completely random and dependent on luck? Now provide the response and nothing else.
$\Delta G = \Delta H - T \Delta S$ In the case of the $\ce{N2 + O2 -> 2NO}$ , $\Delta H$ and $\Delta S$ are both positive, so the reaction is thermodynamically favorable at high temperature (such as in lightning) but not at low temperature. If the temperature drops to room temperature after NO is formed, it is thermodynamically favorable for NO to decompose to nitrogen and oxygen. However, that NO is unstable at room temperature tells us nothing about the rate of the decomposition reaction. In fact there was an interesting 40 year study showing very little decomposition of NO sealed in glass tubes over that time period. The authors' calculations show that without a catalyst the timescale of decompsition could be $10^{29}$ years!
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/21684', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/2234/']}
jdg_370359
stackexchange
llm_judgeable_groundtruth_similarity
623529
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'm aware that, like all quantum objects (I think), an electron can act as both a wave and a particle. Electron diffraction is a good example of how an electron can act as a wave, but I'm struggling to come up with an example of how it acts as a particle. Any help would be much appreciated! Now provide the response and nothing else.
In an old-school TV picture tube, electrons were shot into one end of it, accelerated, steered into specific directions, and then collided with a thin phosphor coating on the inside of the picture end of the tube. Each collision created a burst of light, building up a visible picture for the TV watchers. This process is well-modeled by envisioning the electrons as particles. The original SLAC particle accelerator can be thought of as a machine for adding huge amounts of energy to electrons by shooting them down an evacuated tube two miles long, in which the electrons were separated into individual bunches and then made to surf on the crests of an intense microwave beam traveling down the same tube. This process is also well-modeled by envisioning the electrons as particles.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/623529', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/251162/']}
jdg_370360
stackexchange
llm_judgeable_groundtruth_similarity
43088339
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 Angular4 Application hosted in an Azure Web App and a .NET core Web API hosted in an Azure API App. The API is secured with Azure Active Directory. Currently I use ng2-adal to aquire an access token which I inject to the headers to perform my API calls. Now I try to remove the ng2-adal module and secure my Web App with the Authentication / Authorization feature using the same ClientId (like the API). When I browse to my website I get redirected to the AAD login and after I successfully login, I get redirected to my site. Now I wan't to call the API (that is secured with the same ClientId) within my Web App but can't find a way to retrieve the token. Is there a way to retrieve the access token within my Angular App in this scenario?It looks like the token is stored encrypted within the AppServiceAuthSession Cookie: Now provide the response and nothing else.
The AppServiceAuthSession is cookie which is different than a token . In this scenario, you need to modify the config of Azure app to make it acquire the access_token for the web API. We can use the Resource Explore to modify the settings like below: 1 . locate the angular web app 2 . locate the config->authsettings(resource is the clientId of Azure app which used to protect your apps) "additionalLoginParams": [ "response_type=code id_token", "resource=3fa9607b-63cc-4050-82b7-91e44ff1df38"], 3. config the redirect_uri for Azure app like below: https://appfei.azurewebsites.net/.auth/login/aad/callback Then after you login in the angular app, you can get the access_token via the endpoint: https://appfei.azurewebsites.net/.auth/me Then we need to protect the web API using the Advanced Azure Active Settings like figure below to enable the access_token could call the web API:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43088339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1163423/']}
jdg_370361
stackexchange
llm_judgeable_groundtruth_similarity
1186073
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: Task is: $f(x)$ is positive, continious function in the field of real numbers, and $\int_{-\infty}^{\infty}f(x)dx=1$. Let $\alpha\in(0,1)$, and length of $[a,b]$ is minimal from all $\int_{a}^{b}f(x)dx=\alpha$. Prove that $f(a)=f(b)$ I've tried to use mean value theorem . And I've tried to use some knowledge from probability theory, because $f(x)$ is seems like probability density function. But for now, I haven't came any closer to proof. Now provide the response and nothing else.
The trick is reframing it in language that is familiar to optimization. Let $g(a,b) = b - a$. We want to minimize $g$ subject to the constraint $h(a,b) = \int_a^b f(t) \ dt = \alpha$ for some $\alpha \in (0,1)$. Note that the constraint isn't vacuous because $\int_{\mathbb R}f = 1 $ implies there must be at least one pair $(a,b)$ which satisfies $h(a,b) = \alpha$. Using now Lagrange multipliers, $\nabla g - \lambda \nabla h = 0$ iff $$-1 + \lambda \frac{\partial h}{\partial a} = 0 \ \ \ \text{ and } \ \ \ 1 + \lambda \frac{\partial h}{\partial b} = 0$$ Apply the Fundamental Theorem of Calculus and you're done. This is a nice result. I tried at first to construct a counterexample. Intuitively, I think I've convinced myself it makes sense: on the optimizing interval $[a,b]$, there is some value of $x \in (a,b)$ for which $f(x) > \max\left( f(a), f(b) \right)$. Now look at alternative scenario intervals $J= [a\pm\delta_1, b\pm\delta_2]$, which maintain $\int_J f = \alpha$. If $f(a) \neq f(b)$ it looks like we can make $J$ shorter than $b - a$. If anyone can turn that into a formal argument it would be interesting to see.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1186073', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/222739/']}
jdg_370362
stackexchange
llm_judgeable_groundtruth_similarity
613733
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: As I mentioned in the title "physically", when the computer is off and there is no power, how are the bits stored? For example, how can an image be stored? Now provide the response and nothing else.
Zeros and ones may be stored as different orientation of a magnetic field stored in a ferromagnetic media such as disks or tapes. They may be stored as an electric field in semiconductors in the gate oxide of field effect transistors. Another method are holes in an opaque layer of a disc read out by a laser beam used for DVD. A very old method but still used in the seventies are punched holes in paper tapes or cards. Between about 1955 and 1975 core memories were used. The cores were small toroidal rings of magnetic material. They were read and written by electric currents flowing through wires threaded through the cores. The data was stored in a powered down computer too.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/613733', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/252582/']}
jdg_370363
stackexchange
llm_judgeable_groundtruth_similarity
58828878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a custom component with an event Action called TabChanged. In my Razor page I set the reference to it up like so: <TabSet @ref="tabSet"> ...</TabSet>@code { private TabSet tabSet; ...} In the OnAfterRenderAsync method I assign a handler to the event: protected override async Task OnAfterRenderAsync(bool firstRender){ if(firstRender) { tabSet.TabChanged += TabChanged; } } The first time the page renders I get a System.NullReferenceException: Object reference not set to an instance of an object error. If I switch to use subsequent renders it works fine: protected override async Task OnAfterRenderAsync(bool firstRender){ if(!firstRender) { tabSet.TabChanged += TabChanged; } } But of course this is sloppy and I will be firing multiple event handlers as they stack up during renders. How can I assign the reference one time and on first render? I am following the docs as outlined here EDIT Here is the TabSet.razor file: @using Components.Tabs<!-- Display the tab headers --><CascadingValue Value="this"> <ul class="nav nav-tabs"> @ChildContent </ul></CascadingValue><!-- Display body for only the active tab --><div class="nav-tabs-body" style="padding:15px; padding-top:30px;"> @ActiveTab?.ChildContent</div>@code { [Parameter] public RenderFragment ChildContent { get; set; } public ITab ActiveTab { get; private set; } public event Action TabChanged; public void AddTab(ITab tab) { if (ActiveTab == null) { SetActiveTab(tab); } } public void RemoveTab(ITab tab) { if (ActiveTab == tab) { SetActiveTab(null); } } public void SetActiveTab(ITab tab) { if (ActiveTab != tab) { ActiveTab = tab; NotifyStateChanged(); StateHasChanged(); } } private void NotifyStateChanged() => TabChanged?.Invoke();} TabSet also uses Tab.razor: @using Components.Tabs@implements ITab<li> <a @onclick="Activate" class="nav-link @TitleCssClass" role="button"> @Title </a></li>@code { [CascadingParameter] public TabSet ContainerTabSet { get; set; } [Parameter] public string Title { get; set; } [Parameter] public RenderFragment ChildContent { get; set; } private string TitleCssClass => ContainerTabSet.ActiveTab == this ? "active" : null; protected override void OnInitialized() { ContainerTabSet.AddTab(this); } private void Activate() { ContainerTabSet.SetActiveTab(this); }} And ITab.cs Interface using Microsoft.AspNetCore.Components;namespace PlatformAdmin.Components.Tabs{ public interface ITab { RenderFragment ChildContent { get; } public string Title { get; } }} It's taken from a Steve Sanderson example found here EDIT 2 Here is the debugger showing tabSet is null on first render: And not null on additional renders: Now provide the response and nothing else.
As Dani Herrera pointed out in the comments this may be due to the component being withing an if/else statement and indeed it was. Previously I had the component hidden if an object was null: @if(Account != null){ <TabSet @ref="tabSet"> ... </TabSet>} I left this out for brevity and made the incorrect assumption that the issue was not the conditional. I was very wrong as on first render the object is null and therefore the component does not exist! So be careful out there. I resolved it by moving my conditionals to the sections within the component: <TabSet @ref="tabSet"> @if(Account != null) { <Tab> ... </Tab> <Tab> ... </Tab> }</TabSet>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58828878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/638311/']}
jdg_370364
stackexchange
llm_judgeable_groundtruth_similarity
529535
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 PHP script which executes a shell command: $handle = popen('python last', 'r');$read = fread($handle, 4096);print_r($read);pclose($handle); I echo the output of the shell output. When I run this in the command I get something like this: [root@localhost tester]# python last[last] ZVZX-W3vo9I: Downloading video webpage[last] ZVZX-W3vo9I: Extracting video information[last] ZVZX-W3vo9I: URL: x[download] Destination: here.flv[download] 0.0% of 10.09M at ---b/s ETA --:--[download] 0.0% of 10.09M at 22.24k/s ETA 07:44[download] 0.0% of 10.09M at 66.52k/s ETA 02:35[download] 0.1% of 10.09M at 154.49k/s ETA 01:06[download] 0.1% of 10.09M at 162.45k/s ETA 01:03 However, when I run that same command from PHP I get this output: [last] ZVZX-W3vo9I: Downloading video webpage[last] ZVZX-W3vo9I: Extracting video information[last] ZVZX-W3vo9I: URL: x[download] Destination: here.flv As you can see the bottom bit is missing which is the bit I need!! The problem before was that the percentages were being updated on the same line but now I have changed my Python script so that it creates a new line. But this made difference! :( This question is related to this one . Thank you for any help. Update Needed to redirect output "2>&1". Arul got lucky :P since I missed the deadline to pick the one true answer which belonged to Pax! Now provide the response and nothing else.
You read only the first 4,096 bytes from the pipe, you'll need to place the fread / print _r in a loop and check for the end-of-file using the feof function. $handle = popen('python last', 'r');while(!feof($handle)){ print_r(fread($handle, 4096));} pclose($handle);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/529535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51649/']}
jdg_370365
stackexchange
llm_judgeable_groundtruth_similarity
2479638
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: This is a question in the contest. Prove that there exists two consecutive natural numbers such that sum of all digits of each number is multiple of $2017$. My Solution: I take $a = \underbrace{9\dots 9}_{224}0\underbrace{9\dots 9}_{k}$ such that $2017$ divided $9\times 224 + 9k$ (at least, one can take $k=2017-224=1793$) and of course $a+1 = \underbrace{9\dots 9}_{224}1\underbrace{0\dots 0}_{k}$ which has sum of digits is $2017$. My question: I don't think they are the smallest pair but I cannot find another smaller solution. Can someone give me a hint? Now provide the response and nothing else.
Let $\Sigma_n$ be the sum of the decimal digits of $n$. Then $$\Sigma_{n+1}=\Sigma_{n}+1-9T_n$$ where $T_n$ is the number of trailing nines (because cascaded carries replace all trailing nines by zeroes). The smallest solution of $9T_n-1=2017k$ is indeed $T_n=1793$ and you can't avoid all these nines. As the sum of these digits is $1\mod 2017$, a total of $2016=9\cdot224$ is missing. You can't just preprend these $224$ nines, because more carries would result. It suffices to split the last nine to avoid that, and the best way is by moving one unit ahead. The smalles pair is thus $$1\underbrace{9\dots 9}_{223}8\underbrace{9\dots 9}_{1793}\to9\cdot2017$$ $$1\underbrace{9\dots 9}_{223}9\underbrace{0\dots 0}_{1793}\to1\cdot2017$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2479638', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/255061/']}
jdg_370366
stackexchange
llm_judgeable_groundtruth_similarity
52605997
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 proxy in my react client, my package.json contains: ..."scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "proxy": { "/auth/google": { "target": "http://localhost:5000" } },... But when I ran it, I got error When specified, "proxy" in package.json must be a string.[1] Instead, the type of "proxy" was "object".[1] Either remove "proxy" from package.json, or make it a string. I tried to convert to string, no errors but proxy is not working "proxy": "http://localhost:5000" My App.js <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p>hey there</p> <a href="/auth/google">Sign In With Google</a> </header> </div> Now provide the response and nothing else.
The issue that you are facing is because of CRA v2 . Firstly, you will not require any additional configuration if you are just using a plain string in your proxy. But the moment you use an object, you are using advanced configuration. So, you would have to follow the steps listed below: Install http-proxy-middleware by typing npm i --save http-proxy-middleware Remove the entries from package.json: "proxy": { "/auth/google": { "target": "http://localhost:5000" }} Now create a setup file for your proxy. You should name it setupProxy.js in your src folder on the client side and type the following code: const proxy = require('http-proxy-middleware');module.exports = function(app) { app.use(proxy('/auth/google', { target: 'http://localhost:5000/' } ));} for more info check this
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52605997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3448799/']}
jdg_370367
stackexchange
llm_judgeable_groundtruth_similarity
4350215
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the fastest way to find closest point to the given point in data array? For example, suppose I have an array A of 3D points (with coordinates x, y and z, as usual) and point (x_p, y_p, z_p). How do I find the closest point in A to (x_p, y_p, z_p)? As far as I know, slowest way to do it is to use linear search. Are there any better solutions? Addition of any an auxiliary data structure is possible. Now provide the response and nothing else.
You may organize your points in an Octree . Then you only need to search a small subset. A Octree is a fairly simple data structure you can implement yourself (which would be a valuable learning experience), or you may find some helpful libraries to get you going.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4350215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/483965/']}
jdg_370368
stackexchange
llm_judgeable_groundtruth_similarity
10819715
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there an idiomatic way to compare two NumPy arrays that would treat NaNs as being equal to each other (but not equal to anything other than a NaN). For example, I want the following two arrays to compare equal: np.array([1.0, np.NAN, 2.0])np.array([1.0, np.NAN, 2.0]) and the following two arrays to compare unequal: np.array([1.0, np.NAN, 2.0])np.array([1.0, 0.0, 2.0]) I am looking for a method that would produce a scalar Boolean outcome. The following would do it: np.all((a == b) | (np.isnan(a) & np.isnan(b))) but it's clunky and creates all those intermediate arrays. Is there a way that's easier on the eye and makes better use of memory? P.S. If it helps, the arrays are known to have the same shape and dtype. Now provide the response and nothing else.
If you really care about memory use (e.g. have very large arrays), then you should use numexpr and the following expression will work for you: np.all(numexpr.evaluate('(a==b)|((a!=a)&(b!=b))')) I've tested it on very big arrays with length of 3e8, and the code has the same performance on my machine as np.all(a==b) and uses the same amount of memory
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10819715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/367273/']}
jdg_370369
stackexchange
llm_judgeable_groundtruth_similarity
135703
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: Let $X_1, X_2,...,X_n$ be iid random variables. Let $Z_1, Z_2, Z_3$ be defined as $X_1, X_1+X_2, X_1+X_2+X_3$ respectively. Are $Z_1, Z_2$ and $Z_3$ also iid's? The question is based on renewal processes. If the inter arrival durations are iid, are the arrival times also iid? Now provide the response and nothing else.
Assume that $E[X_i]=0$. If this is not true, then simply subtract the mean, it's a constant, so it will not change anything. For independent random variables $Cov[Z_nZ_{n-1}]=E[Z_nZ_{n-1}]=0$. Evaluate the left hand side$$E[Z_nZ_{n-1}]=E[(Z_{n-1}+X_n)Z_{n-1}]=E[X_nZ_{n-1}]+E[Z^2_{n-1}]=E[Z^2_{n-1}]>0$$So, $Z_n$ is not independent of $Z_{n-1}$. Here, we used $E[X_nZ_{n-1}]=0$, because $X_n$ is independent of all $X_i$.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/135703', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/55780/']}
jdg_370370
stackexchange
llm_judgeable_groundtruth_similarity
1000767
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: My use case: I have Ubuntu Server 18.04 installed on an M.2 SSD. I have a 4TB HDD I want to add as storage. Since it's mostly for large media files and backups, it won't be written to very often. Which filesystem do you think is best suited for this use case? My leading candidates are Ext3/4, XFS, Btrfs, and ZFS (feel free to argue for another). I'm not asking "What is the best filesystem?"—There is no such thing as 'the best.' I'm just asking people which filesystem might be most suited for this use case. Please try to include: Are there any drawbacks or risks? I heard XFS can corrupt data if there's a power loss. Same with ZFS without ECC RAM. Is it possible to add RAID-1 later on without losing data? I don't have enough money for another hard drive right now (I used that for an external drive; RAID doesn't replace backups), but I may add one later. This isn't a requirement, just something that might be nice. What is the read/write performance? Btrfs would probably fit most of my needs, but it's very slow in Phoronix benchmarks. XFS has impressive performance, but I've heard it can cause data loss. Thanks for your advice. Now provide the response and nothing else.
I generally use one of the following two filesystems: XFS for anything which does not play well with CoW (or for virtual machines whose datastore already is on a CoW filesystem) or when extremely fast direct I/O is required; ZFS for anything else. For your use case I would use ZFS, especially considering that Ubuntu 18.04 already ships it. As you can easily attach another mirror leg to an already existing device, ZFS fits the bill very well. For example, let name your disk nvme0p1 : zpool create tank /dev/nvme0p1 create your single vdev pool called “tank”; zpool attach tank <newdev> /dev/nvme0p1 enables mirroring. If, for some reasons, you don't/can't use ZFS, then MDRAID and XFS are your friends: mdadm --create /dev/md200 -l raid1 -n 2 /dev/nvme0p1 missing will create a RAID1 array with a missing leg (see #1); mdadm --manage /dev/md200 --add <newdev> attaches a new mirror leg (forming a complete RAID1, see #2) After creating the array, you can format it with XFS via mkfs.xfs I do not suggest using BTRFS, as both performance and resilience are subpar. For example, from the Debian wiki : There is currently (2019-07-07, linux ≤ 5.1.16) a bug that causes atwo-disk raid1 profile to forever become read-only the second time itis mounted in a degraded state—for example due to amissing/broken/SATA link reset disk Please also note that commercial NAS vendor using BTRFS (read: Synology) do not use its own, integrated RAID feature; rather, they use the proven Linux MDRAID layer. EDIT: while some maintain that XFS is prone to data loss, this is simply not correct. Well, compared to ext3, XFS (and other filesystems supporting delayed allocation) can lose more un-synched data in case of uncontrolled poweroff. But synced data (ie: important writes) are 100% safe. Moreover, a specific bug exacerbating XFS data loss was corrected over 10 years ago . That bug apart, any delayed allocation filesystem (ext4 and btrfs included) will lose a significant number or un-synched data in case of uncontrolled poweroff. Compared to ext4, XFS has unlimited inode allocation, advanced allocation hinting (if you need it) and, in recent version, reflink support (but they need to be explicitly enabled in Ubuntu 18.04, see mkfs.xfs man page for additional information) 1: Example /proc/mdstat file with missing device: Personalities : [raid1]md200 : active raid1 loop0[0] 65408 blocks super 1.2 [2/1] [U_]unused devices: <none> 2: /proc/mdstat file after adding a second device Personalities : [raid1]md200 : active raid1 loop1[2] loop0[0] 65408 blocks super 1.2 [2/2] [UU]unused devices: <none>
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/1000767', 'https://serverfault.com', 'https://serverfault.com/users/557562/']}
jdg_370371
stackexchange
llm_judgeable_groundtruth_similarity
2765473
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 seem to remember Scala treating methods ending in _= specially, so something like this: object X { var x: Int = 0; def y_=(n : Int) { x = n }}X.y = 1 should call X.y_=(1) . However, in 2.8.0 RC1, I get an error message: <console>:6: error: value y is not a member of object X X.y = 1 ^ Interestingly, just trying to call the method without parentheses fails as well: scala> X.y_= 1<console>:1: error: ';' expected but integer literal found. X.y_= 1 ^ Am I misremembering something which does actually exist or did I just invent it out of whole cloth? Now provide the response and nothing else.
This is one of those corner cases in Scala. You cannot have a setter without a getter and vice versa . The following works fine: scala> object X { | var x: Int = 0 | def y = x | def y_=(n: Int) { x = n } | }defined module Xscala> X.y = 45scala> X.yres0: Int = 45
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2765473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9204/']}
jdg_370372
stackexchange
llm_judgeable_groundtruth_similarity
2778932
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My exercise is the folowing : let $G$ be a groupe such that for all $x \in G, x^2=e $. Show that $G$ is abelian. If $G$ is finite, show that there exists $n$ such that $g$ is isomorphic to $(\Bbb Z/2)^n$. I already have prove that $G$ is abelian, but I'm blocking on the second question. I think I am supposed to find an application $\phi$ such that $\phi : (\Bbb Z/2)^n \rightarrow G $ and prove that this application is bijectiv but I can't find such an application. Can you help me find such an application ? Now provide the response and nothing else.
USING LINEAR ALGEBRA: I will show that it satisfies the axioms of $\Bbb Z/2$-vector space. Addition: $$x+y=xy$$ Scalar multiplication: $$\lambda \cdot x= \begin{cases} x & \lambda=1 \\ e & \lambda=0\end{cases}$$Check that all axioms are satisfied, so that $G$ is a (finite dimensional) vector space over $\Bbb Z/2$. This is equivalent on showing that it is isomorphic to some $(\Bbb Z/2)^n$. Where is $x^2=e$ involved? In proving distributivity:$$e= 0\cdot x = (1+1) \cdot x = 1 \cdot x + 1 \cdot x = x + x = x^2$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2778932', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/559968/']}
jdg_370373
stackexchange
llm_judgeable_groundtruth_similarity
9955713
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 ran git fsck --lost-found on my repository. I expected to see a couple dangling commits, where I had reset HEAD . However, I was surprised to see likely over several thousand dangling blob messages. I don't believe anything is wrong with my repository, but I'm curious as to what causes these dangling blobs? There's only two people working on the repository, and we haven't done anything out of the ordinary. I wouldn't think they were created by an older version of a file being replaced by a new one, since git would need to hold onto both blobs so it can display history. Come to think of it, at one point we did add a VERY large directory (thousands of files) to the project by mistake and then remove it. Might this be the source of all the dangling blobs? Just looking for insight into this mystery. Now provide the response and nothing else.
Last time I looked at this I stumbled across this thread , specifically this part: You can also end up with dangling objects in packs. When that pack is repacked, those objects will be loosened, and then eventually expired under the rule mentioned above. However, I believe gc will not always repack old packs; it will make new packs until you have a lot of packs, and then combine them all (at least that is what "gc --auto" will do; I don't recall whether just "git gc" follows the same rule). So it's normal behavior, and does get collected eventually, I believe. edit: Per Daniel, you can immediately collect it by running git gc --prune="0 days"
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9955713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136451/']}
jdg_370374
stackexchange
llm_judgeable_groundtruth_similarity
649873
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 consider the element neon. Its ground-state electron configuration is: $1s^2 2s^2 2p^6$ . What would happen if enough energy was given for one electron in the $1s$ orbital to jump to the $2s$ orbital (i.e. exactly the $\Delta E$ between $1s$ and $2s$ was supplied)? Would the electron from the $1s$ orbital absorb the energy? There can't be more than 2 electrons in an orbital, so what would happen to the electrons in the $2s$ orbital if the $1s$ electron absorbed the energy? Now provide the response and nothing else.
Overview Transitions to other unoccupied states are possible but extremely unlikely, more likely that the photon will not be absorbed. Introduction The Pauli exclusion principle prevents a third electron occupying the $2s$ state. Even if there was space in the $2s$ state a $1s\to 2s$ transition is unlikely due to selection rules and a $1s\to2p$ transition is significantly more likely if there is space in the $2p$ orbital. Other answers here have stated that the transition to other energy levels is forbidden. Now while the probability of a transition is extremely small, it is non-zero. A quick note on notation: I will be using a bold typeface for vectors as opposed to an over arrow so that vector operators are clearer. Quantisation of the Electromagnetic Field Minimal coupling of the electron to the electromagnetic field using the Coulomb potential adds a perturbation of: $$\hat H_1=\frac{e}{m_e}\hat{\boldsymbol p}\cdot\hat{\boldsymbol A}\left(\boldsymbol r,t\right)$$ to the Hamiltonian. Where $e$ and $m_e$ are the charge and mass of the electron, $\hat{\boldsymbol p}$ is the momentum operator acting on the electron and the vector potential operator has the form: $$\hat{\boldsymbol A}\left(\boldsymbol r,t\right)=\sum_{\lambda,\boldsymbol k}\sqrt{\frac{\hbar}{2v\epsilon_0\omega\left(\boldsymbol k\right)}}\left(\hat a_\lambda\left(\boldsymbol k\right)\boldsymbol s_\lambda\left(\boldsymbol k\right)e^{i\left(\boldsymbol {k}\cdot\boldsymbol r-\omega t\right)}+\text{h.c.}\right)$$ where $\text{h.c.}$ is the Hermitian conjugate of the preceding terms, $v$ is the volume of the cavity in which the experiment is taking place; $\omega\left(\boldsymbol k\right)$ is the angular frequency of the photon mode as a function of the wavevector $\boldsymbol k$ ; $\lambda$ labels the two polarisations; $\boldsymbol s_\lambda\left(\boldsymbol k\right)$ is the polarisation vector of the mode; $\hat a_\lambda\left(\boldsymbol k\right)$ is the annihilation operator for the mode; and $\boldsymbol r$ is the position of the atom (assuming the wavelength is larger than the atom the uncertainty in the electron's position can be ignored). If we have a single wavelength and polarisation then: $$\hat H_1=\frac{e}{m_e}\sqrt{\frac{\hbar}{2v\epsilon_0\omega}}\hat{\boldsymbol {p}}\cdot\boldsymbol s\hat a e^{i\left(\boldsymbol k\cdot\boldsymbol r-\omega t\right)}+\text{h.c.}$$ Thus, let: $$\begin{align}\hat V&=\frac{e}{m_e}\sqrt{\frac{\hbar}{2v\epsilon_0\omega}}\hat{\boldsymbol {p}}\cdot\boldsymbol s\hat a e^{i\boldsymbol k\cdot\boldsymbol r}\\\implies\hat H_1&=Ve^{-i\omega t}+\hat V^\dagger e^{i\omega t}\end{align}$$ Then using first-order time-dependent perturbation theory which holds in the limit $\frac{t}{\hbar}\left|\langle f|\hat V|i\rangle\right|\ll1$ for all $n\ge2$ . We find the probability of a transition having occured if the atom is measured after a time $t$ since the electromagentic field was applied is: $$\begin{align}P\left(t\right)=\frac{t^2}{\hbar^2}\Bigg|&\overbrace{e^{i\left(\Delta\omega-\omega\right)t/2}\operatorname{sinc}\left(\frac{1}{2}t\left(\Delta\omega-\omega\right)\right)\langle f|\hat V|i\rangle}^\text{absorption}\\+&\underbrace{e^{i\left(\Delta\omega+\omega\right)t/2}\operatorname{sinc}\left(\frac{1}{2}t\left(\Delta\omega+\omega\right)\right)\langle f|\hat V^\dagger|i\rangle}_\text{emission}\Bigg|^2\end{align}\tag{1}$$ where $\Delta E=\hbar \Delta \omega$ be the difference in the energy levels of the initial $|i\rangle$ and final $|f\rangle$ states. This is in general non-zero even when $\Delta \omega\ne\omega$ . However, we can make one more approximation to aid in understanding: if the final state $|f\rangle$ has absorbed a photon then in the limit $t\Delta\omega\gg2\pi$ the $\operatorname{sinc}$ functions do not overlap and so we need only retain the absorption term: $$P\left(t\right)=\left(\frac{\left|\langle f|\hat V|i\rangle\right|}{\hbar}\right)^2t^2\operatorname{sinc}^2\left(\frac{1}{2}t\left(\Delta\omega-\omega\right)\right)\tag{2}$$ Further approximations from here will give you Fermi's Golden rule, one of these approximations is taking the limit such that $t\operatorname{sinc}^2$ tends to a delta function and so removes the possibility for a transition when the energy of the photon is not exactly equal to the energy gap: and so this is an inappropriate approximation to make in this case. Energy Conservation in Quantum Mechanics While the expectation value of the energy is conserved in the evolution of a system as described by Schrödinger equation, there may be a discontinuous jump in the energy of the system when a measurement is performed. Consider a system in a superposition of energy eigenstates, when you measure the energy the state will collapse into an energy eigenstate which in general will not have the same energy as the expectation value for the energy - the energy of the system has increased or decreased! The energy may be transferred to or from the measurement device or surroundings to compensate. In previous edits this section also contained a discussion of the many-words type interpretation which in my naivety I included. I apologise for anyone I have mislead and for more details you can see this question: "Conservation of energy, or lack thereof," in quantum mechanics @Jagerber48's answer is the most relevant to this question giving additional details that will likely be of interest to any reader of this question. @benrg's answer gives a good explanation of why energy is conserved. @NiharKarve's comment includes a blog post which explains why the paper may be misleading. Putting this all Together Equation (1) shows, in general, the when an atom is illuminated by light of a single specific wavelength and polarisation, a transition is possible even if the energy of the photons is not equal to the energy gap, which would violate energy conservation (but this is allowed); however, the probability is extremely small. Equation (2) makes a further approximation which we can now use to find an expression for the probability: $$P\left(t\right)=\frac{e^2}{2v\epsilon_0m_e^2\hbar\omega}\left|\langle f|\hat{\boldsymbol {p}}\cdot\boldsymbol s\hat a |i\rangle\right|^2t^2\operatorname{sinc}^2\left(\frac{1}{2}t\left(\Delta\omega-\omega\right)\right)$$ As $|i\rangle\equiv|i\rangle_e|f\rangle_{EM}$ and $|f\rangle_e|f\rangle_{EM}$ where subscript $e$ is the electrons states and subscript $EM$ are the states of the electromagnetic field. Without detail $_e\langle f|\hat{\boldsymbol {p}}\cdot\boldsymbol s|i\rangle_e\equiv\boldsymbol d_{fi}\cdot\boldsymbol s$ where $\left\{\boldsymbol d_{fi}\right\}$ are the dipole matrix elements and are zero for transitions between certain orbitals independent of the energy supplied (for more details see selection rules ). Finally, $_{EM}\langle f|\hat a|i\rangle_{EM}=\sqrt{N}$ if the state $|i\rangle_{EM}$ is the state for $N$ photons of the given wavelength and polarisation - but other states such as coherent states are also posible. $$\implies P\left(t\right)=\frac{e^2N}{2v\epsilon_0m_e^2\hbar\omega}\left|\boldsymbol d_{fi}\cdot\boldsymbol s\right|^2t^2\operatorname{sinc}^2\left(\frac{1}{2}t\left(\Delta\omega-\omega\right)\right)\tag{3}$$ which holds in the limit: $$t\ll\frac{\hbar}{\left|\,_e\langle f|\left(\hat{\boldsymbol {p}}\cdot\boldsymbol s\right)|i\rangle_e\right|}\sim 10^{-25}\text{s}$$ As the limit $t\Delta\omega\gg2\pi$ is not needed when the state $|i\rangle_{EM}$ is the state for $N$ photons of the given wavelength and polarisation because the creation operator causes the emission term to vanish anyway. However, the time is of the order of $10^{-25}\text{s}$ give or take a few orders of magnitude for Neon (obtained using the only data I could find for reduced matrix elements for dipole transitions), which is not a practical time scale to measure on. Finally, considering your given case, given selection rules, the most likely case if the $1s$ electron did absorb a photon is a transition to the $3p$ state (as $2p$ is occupied and $3s$ is forbidden to first order by selection rules). Substituting values into equation (3) gives an order of magnitude estimate for the probability of transitioning from $1s$ to $3p$ in Neon of $10^{-12}\%\text{ per }\left(\text{photon }m^{-3}\right)$ for $t=10^{-25}\text{s}$ which is the point the approximation of first order perturbation breaks down.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/649873', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/306354/']}
jdg_370375
stackexchange
llm_judgeable_groundtruth_similarity
23272181
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: C++11 Standard §12.3.2/1 (emphasis mine): A member function of a class X having no parameters with a name of the form conversion-function-id : operator conversion-type-id conversion-type-id : type-specifier-seq conversion-declarator conversion-declarator : ptr-operator conversion-declarator specifies a conversion from X to the type specified by the conversion-type-id . Such functions are called conversion functions. No return type can be specified. If a conversion function is a member function , the type of the conversion function (8.3.5) is “function taking no parameter returning conversion-type-id ”. Is a conversion function always a member function, or there are cases where this is not true? Now provide the response and nothing else.
The clause "If a conversion function is a member function," was added to the working draft in N2798 as part of the Concepts wording per N2773 Proposed Wording for Concepts . N2798 12.3.2/1 reads (I'll use bold to show additions, and strikeout to show removals): 1 A member function of a class X having no parameters, or an associated function of a concept whose sole parameter is of type X , with a name of the form conversion-function-id: operator conversion-type-id conversion-type-id: type-specifier-seq attribute-specifier opt conversion-declarator opt conversion-declarator: ptr-operator conversion-declarator opt specifies a conversion from X to the type specified by the conversion-type-id . Such member functions are called conversion functions. Classes, enumerations, and typedef-names shall not be declared in the type-specifier-seq . Neither parameter types nor No return type can be specified. If a conversion function is a member function, t T he type of a the conversion function (8.3.5) is “function taking no parameter returning conversion-type-id ” ; if a conversion function is an associated function, the type of the conversion function is “function taking a parameter of type X returning conversion-type-id ” . A conversion function is never used to convert ... The Concepts wording was removed in draft N2960 . The "If a conversion function is a member function," should have also been removed at that time since it is now vestigal. Pertinent portion of N2960 §12.3.2/1: 1 A member function of a class X having no parameters, or an associated function of a concept whose sole parameter is of type X, with a name of the form conversion-function-id: operator conversion-type-id conversion-type-id: type-specifier-seq attribute-specifier opt conversion-declarator opt conversion-declarator: ptr-operator conversion-declarator opt specifies a conversion from X to the type specified by the conversion-type-id . Such functions are called conversion functions. No return type can be specified. If a conversion function is a member function, the type of the conversion function (8.3.5) is “function taking no parameter returning conversion-type-id ” ; if a conversion function is an associated function, the type of the conversion function is “function taking a parameter of type X returning conversion-type-id ” . ... 2018-02-03 Update: This has been fixed in C++17 CWG corrected this wording as a drive-by while fixing CWG issue 1990 .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23272181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1162978/']}
jdg_370376
stackexchange
llm_judgeable_groundtruth_similarity
920201
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the specific technical causes of Ruby being so much slower on Windows? People report about a 3X speed drop from Linux/OSX and there are some vague discussions about Ruby using a compiler for Windows versions that produces slow code but I can't find any specific details. Anybody know the specifics? I'm not interested in hurf durf Windoze sucks yuk yuks. Now provide the response and nothing else.
I would guess there are a few possible options, and they probably all add up: Ruby being mainly developed on Linux, it ends up mechanically optimised for it. The code is regularly tested for Windows and everything works, but the result is still that developer will spend more time optimising for Linux than Windows. To my experience, recent versions of gcc (4.3 and greater) produce code more efficient than recent versions of Visual Studio (at least 2005). My tests included in both case spending about a day finding the best options for code optimisation. Related to point 1, if you compile the same project using gcc for Windows or Linux, I usually observe a drop of performances of about 20% on Windows compared to Linux. Here again, I suppose this is because Linux (or Unices in general) is a primary target for gcc, windows is a port. Less time is spent optimising for Windows than Linux. In the end, if one would want to optimise Ruby for Windows, a significant amount of time (and money, as far as I know, profilers on Windows don't come for free) will have to be spent using a profiler and optimising bottlenecks. And everything will have to be tested on Linux to make sure there is no loss of performance. Of course, all than should be tested again with their new interpreter YARV .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/920201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6805/']}
jdg_370377
stackexchange
llm_judgeable_groundtruth_similarity
33557043
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 webapp with which I'm using flexbox for layout. I'm trying to both fill the screen (it's an app, not a document), and as far as possible to not specify any fixed widths or heights as the content could be all sorts of things (Full fluid layout! The dream!) So I need fluid height, full width headers and footers, and then a main panel in the middle filling the remaining vertical space, divided into columns, each of which scrolls when too high, and where the width of each non-primary column should shrink to fit its content, and a primary column which uses up the remaining space. I am so close, but have had to resort to explicitly sizing the non-main columns - I believe that flex-basis: content; is supposed to do this but isn't supported by browsers yet. Here's a minimal demo showing fixed size columns: var list = document.querySelector('ul')for (var i = 0; i < 100; i++) { var li = document.createElement('li') li.textContent = i list.appendChild(li)} html,body { height: 100%; width: 100%; margin: 0;}body { display: flex; flex-direction: column;}main { display: flex; flex-direction: row; overflow: hidden;}main > section { overflow-y: auto; flex-basis: 10em; /* Would be better if it were fluid width/shrink to fit, unsupported: */ /* flex-basis: content; */}main > section:last-child { display: flex; flex: auto; flex-direction: column;}main > section:last-child > textarea { flex: auto;} <header> <h1>Heading</h1></header><main> <section> <h1>One</h1> <ul> </ul> </section> <section> <h1>Two</h1> </section> <section> <header> <h1>Three</h1> </header> <textarea></textarea> <footer> <p>Footer</p> </footer> </section></main><footer> <p>Footer</p></footer> Which looks like this - I want columns One and Two to shrink/grow to fit rather than being fixed: My question is, is there a CSS-only workaround for flex-basis: content , or an alternative way to realise this goal? I can possibly live with fixing the column sizes as above, or using javascript, but I HAVE A DREAM DAMN IT. Now provide the response and nothing else.
I want columns One and Two to shrink/grow to fit rather than being fixed. Have you tried: flex-basis: auto or this: flex: 1 1 auto , which is short for: flex-grow: 1 (grow proportionally) flex-shrink: 1 (shrink proportionally) flex-basis: auto (initial size based on content size) or this: main > section:first-child { flex: 1 1 auto; overflow-y: auto;}main > section:nth-child(2) { flex: 1 1 auto; overflow-y: auto;}main > section:last-child { flex: 20 1 auto; display: flex; flex-direction: column; } revised demo Related: Make flex items take content width, not width of parent container Make flex container take width of content, not width 100%
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33557043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/447907/']}
jdg_370378
stackexchange
llm_judgeable_groundtruth_similarity
2707469
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 new to Ruby, and have been working my way through Mr Neighborly's Humble Little Ruby Guide. There have been a few typos in the code examples along the way, but I've always managed to work out what's wrong and subsequently fix it - until now! This is really basic, but I can't get the following example to work on Mac OS X (Snow Leopard): gone = "Got gone fool!"puts "Original: " + gonegone.delete!("o", "r-v")puts "deleted: " + gone Output I'm expecting is: Original: Got gone fool!deleted: G gne fl! Output I actually get is: Original: Got gone fool!deleted: Got gone fool! The delete! method doesn't seem to have had any effect. Can anyone shed any light on what's going wrong here? :-\ Now provide the response and nothing else.
The String.delete method ( Documented here ) treats its arguments as arrays and then deletes characters based upon the intersection of its arrays. The intersection of 2 arrays is all characters that are common to both arrays. So your original delete of gone.delete!("o", "r-v") would become gone.delete ['o'] & ['r','s','t','u','v'] There are no characters present in both arrays so the deletion would get an empty array, hence no characters are deleted.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2707469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297966/']}
jdg_370379
stackexchange
llm_judgeable_groundtruth_similarity
40945
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This question is inspired by an answer of Tim Porter . Ronnie Brown pioneered a framework for homotopy theory in which one may consider multiple basepoints. These ideas are accessibly presented in his book Topology and Groupoids. The idea of the fundamental groupoid, put forward as a multi-basepoint alternative to the fundamental group, is the highlight of the theory. The headline result seems to be that the van-Kampen Theorem looks more natural in the groupoid context. I don't know whether I find this headline result compelling- the extra baggage of groupoids and pushouts makes me question whether the payoff is worth the effort, all the more so because I am a geometric topology person, rather than a homotopy theorist. Do you have examples in geometric topology (3-manifolds, 4-manifolds, tangles, braids, knots and links...) where the concept of the fundamental groupoid has been useful, in the sense that it has led to new theorems or to substantially simplified treatment of known topics? One place that I can imagine (but, for lack of evidence, only imagine) that fundamental groupoids might be useful (at least to simplify exposition) is in knot theory, where we're constantly switching between (at least) three different "natural" choices of basepoint- on the knot itself, on the boundary of a tubular neighbourhood, and in the knot complement. This change-of-basepoint adds a nasty bit of technical complexity which I have struggled with when writing papers. A recent proof (Proposition 8 of my paper with Kricker ) which would have been a few lines if we hadn't had to worry about basepoints, became 3 pages. In another direction, what about fundamental groupoids of braids? Have the ideas of fundamental groupoids been explored in geometric topological contexts? Conversely, if not, then why not? Now provide the response and nothing else.
Here is an interesting example where groupoids are useful. The mapping class group $\Gamma_{g,n}$ is the group of isotopy classes of orientation preserving diffeomorphisms of a surface of genus $g$ with $n$ distinct marked points (labelled 1 through n). The classifying space $B\Gamma_{g,n}$ is rational homology equivalent to the (coarse) moduli space $\mathcal{M}_{g,n}$ of complex curves of genus $g$ with $n$ marked points (and if you are willing to talk about the moduli orbifold or stack, then it is actually a homotopy equivalence) The symmetric group $\Sigma_n$ acts on $\mathcal{M}_{g,n}$ by permuting the labels of the marked points. Question: How do we describe the corresponding action of the symmetric group on the classifying space $B\Gamma_{g,n}$? It is possible to see $\Sigma_n$ as acting by outer automorphisms on the mapping class group. I suppose that one could probably build an action on the classifying space directly from this, but here is a much nicer way to handle the problem. The group $\Gamma_{g,n}$ can be identified with the orbifold fundamental group of the moduli space. Let's replace it with a fundamental groupoid. Fix a surface $S$ with $n$ distinguished points, and take the groupoid where objects are labellings of the distinguished points by 1 through n, and morphisms are isotopy classes of diffeomorphisms that respect the labellings (i.e., sending the point labelled $i$ in the first labelling to the point labelled $i$ in the second labelling). Clearly this groupoid is equivalent to the original mapping class group, so its classifying space is homotopy equivalent. But now we have an honest action of the symmetric group by permuting the labels on the distinguished points of $S$.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/40945', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2051/']}
jdg_370380
stackexchange
llm_judgeable_groundtruth_similarity
63809553
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 fastapi project built by poetry. I want to run the application with a scripts section in pyproject.tom like below: poetry run start What is inside double quotes in the section? [tool.poetry.scripts]start = "" I tried to run the following script. import uvicornfrom fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}def main(): print("Hello World") uvicorn.run(app, host="0.0.0.0", port=8000, reload=True, workers=2)if __name__ == "__main__": main() It stops the application and just shows warning like this. WARNING: You must pass the application as an import string to enable 'reload' or 'workers'. Now provide the response and nothing else.
I found the solution to this problem. See below: In pyproject.toml [tool.poetry.scripts]start = "my_package.main:start" In your main.py inside my_package folder. import uvicornfrom fastapi import FastAPIapp = FastAPI()@app.get("/")async def root(): return {"message": "Hello World"}def start(): """Launched with `poetry run start` at root level""" uvicorn.run("my_package.main:app", host="0.0.0.0", port=8000, reload=True)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63809553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12036118/']}
jdg_370381
stackexchange
llm_judgeable_groundtruth_similarity
275781
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone explain the difference between Server.MapPath(".") , Server.MapPath("~") , Server.MapPath(@"\") and Server.MapPath("/") ? Now provide the response and nothing else.
Server.MapPath specifies the relative or virtual path to map to a physical directory . Server.MapPath(".") 1 returns the current physical directory of the file (e.g. aspx) being executed Server.MapPath("..") returns the parent directory Server.MapPath("~") returns the physical path to the root of the application Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application) An example: Let's say you pointed a web site application ( http://www.example.com/ ) to C:\Inetpub\wwwroot and installed your shop application (sub web as virtual directory in IIS, marked as application) in D:\WebApps\shop For example, if you call Server.MapPath() in following request: http://www.example.com/shop/products/GetProduct.aspx?id=2342 then: Server.MapPath(".") 1 returns D:\WebApps\shop\products Server.MapPath("..") returns D:\WebApps\shop Server.MapPath("~") returns D:\WebApps\shop Server.MapPath("/") returns C:\Inetpub\wwwroot Server.MapPath("/shop") returns D:\WebApps\shop If Path starts with either a forward slash ( / ) or backward slash ( \ ), the MapPath() returns a path as if Path was a full, virtual path. If Path doesn't start with a slash, the MapPath() returns a path relative to the directory of the request being processed. Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences. Footnotes Server.MapPath(null) and Server.MapPath("") will produce this effect too .
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/275781', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2133/']}
jdg_370382
stackexchange
llm_judgeable_groundtruth_similarity
40126565
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can anyone explain to me the differences between @SuppressWarnings and @SuppressLint ? When we should use one over another? I've read the documentation, but still don't get the differences. Explain using an example/sample code will be much appreciated. Thanks. Now provide the response and nothing else.
There are actually two lints: one belongs to the compiler, so is Java-specific, and one belongs to Google and is Android-specific. If your warning is about something in Java that isn't specific to Android, it's suppressed with @SuppressWarnings , and if it's Android-specific, it's suppressed with @SuppressLint . Android Lint Warnings Lint warnings are listed here: http://tools.android.com/tips/lint-checks So let's say you have a warning about missing permissions, and the warning description starts off "This check scans through your code and libraries and looks at the APIs being used, and checks this against the set of permissions required to access those APIs." In the lint warnings page linked above, we find this: MissingPermission Summary: Missing Permissions Priority: 9 / 10 Severity: Error Category: Correctness This check scans through your code and libraries and looks at the APIs being used, and checks this against the set of permissions required to access those APIs. If the code using those APIs is called at runtime, then the program will crash. Furthermore, for permissions that are revocable (with targetSdkVersion 23), client code must also be prepared to handle the calls throwing an exception if the user rejects the request for permission at runtime. So to suppress this, we put this annotation on the code: @SuppressLint("MissingPermission") Compiler Warnings Let's say we find this warning: "Unchecked cast: 'java.lang.Object' to 'java.lang.Integer' ..." If you are reading this in hover popup in Android Studio, there is a More... link at the end. When you click the More... link, the text expands and you find this at the bottom: "Hint: Pass -Xlint:unchecked to javac to get more details." This tells you that you would use "unchecked" in the annotation like this: @SuppressWarnings("unchecked") For a list of compiler warnings, run javac -X : C:\>javac -X -Xlint Enable recommended warnings -Xlint:{all,auxiliaryclass,cast,classfile,deprecation,dep-ann,divzero,empty,fallthrough,finally,options,overloads,overrides,path,processing,rawtypes,serial,static,try,unchecked,varargs,-auxiliaryclass,-cast,-classfile,-deprecation,-dep-ann,-divzero,-empty,-fallthrough,-finally,-options,-overloads,-overrides,-path,-processing,-rawtypes,-serial,-static,-try,-unchecked,-varargs,none} Enable or disable specific warnings . . . Those are the values that you can use in @SuppressWarnings .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40126565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7041125/']}
jdg_370383
stackexchange
llm_judgeable_groundtruth_similarity
3258243
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I check whether the remote repository has changed and I need to pull? Now I use this simple script: git pull --dry-run | grep -q -v 'Already up-to-date.' && changed=1 But it is rather heavy. Is there a better way? The ideal solution would check all the remote branches, and return names of the changed branches and the number of new commits in each one. Now provide the response and nothing else.
First use git remote update , to bring your remote refs up to date. Then you can do one of several things, such as: git status -uno will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same. git show-branch *master will show you the commits in all of the branches whose names end in 'master' (eg master and origin/master ). If you use -v with git remote update ( git remote -v update ) you can see which branches got updated, so you don't really need any further commands. However, it looks like you want to do this in a script or program and end up with a true/false value. If so, there are ways to check the relationship between your current HEAD commit and the head of the branch you're tracking, although since there are four possible outcomes you can't reduce it to a yes/no answer. However, if you're prepared to do a pull --rebase then you can treat "local is behind" and "local has diverged" as "need to pull", and the other two ("local is ahead" and "same") as "don't need to pull". You can get the commit id of any ref using git rev-parse <ref> , so you can do this for master and origin/master and compare them. If they're equal, the branches are the same. If they're unequal, you want to know which is ahead of the other. Using git merge-base master origin/master will tell you the common ancestor of both branches, and if they haven't diverged this will be the same as one or the other. If you get three different ids, the branches have diverged. To do this properly, eg in a script, you need to be able to refer to the current branch, and the remote branch it's tracking. The bash prompt-setting function in /etc/bash_completion.d has some useful code for getting branch names. However, you probably don't actually need to get the names. Git has some neat shorthands for referring to branches and commits (as documented in git rev-parse --help ). In particular, you can use @ for the current branch (assuming you're not in a detached-head state) and @{u} for its upstream branch (eg origin/master ). So git merge-base @ @{u} will return the (hash of the) commit at which the current branch and its upstream diverge and git rev-parse @ and git rev-parse @{u} will give you the hashes of the two tips. This can be summarized in the following script: #!/bin/shUPSTREAM=${1:-'@{u}'}LOCAL=$(git rev-parse @)REMOTE=$(git rev-parse "$UPSTREAM")BASE=$(git merge-base @ "$UPSTREAM")if [ $LOCAL = $REMOTE ]; then echo "Up-to-date"elif [ $LOCAL = $BASE ]; then echo "Need to pull"elif [ $REMOTE = $BASE ]; then echo "Need to push"else echo "Diverged"fi Note: older versions of git didn't allow @ on its own, so you may have to use @{0} instead. The line UPSTREAM=${1:-'@{u}'} allows you optionally to pass an upstream branch explicitly, in case you want to check against a different remote branch than the one configured for the current branch. This would typically be of the form remotename/branchname . If no parameter is given, the value defaults to @{u} . The script assumes that you've done a git fetch or git remote update first, to bring the tracking branches up to date. I didn't build this into the script because it's more flexible to be able to do the fetching and the comparing as separate operations, for example if you want to compare without fetching because you already fetched recently.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/3258243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234780/']}
jdg_370384
stackexchange
llm_judgeable_groundtruth_similarity
29643714
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 large database of 22GB . I used to take backup with mysqldump command in a gzip format. When i extract the gz file it produces the .sql file of 16.2GB When I try to import the database in my local server, it takes approximately 48hrs to import.Is there a way to increase the speed of the import process? Also i would like to know if any hardware changes need to be done to improve the performance. Current System Config Processor: 4th Gen i5 RAM: 8GB #update my.cnf is as follows ## The MySQL database server configuration file.## You can copy this to one of:# - "/etc/mysql/my.cnf" to set global options,# - "~/.my.cnf" to set user-specific options.# # One can use all long options that the program supports.# Run program with --help to get a list of available options and with# --print-defaults to see which it would actually understand and use.## For explanations see# http://dev.mysql.com/doc/mysql/en/server-system-variables.html# This will be passed to all mysql clients# It has been reported that passwords should be enclosed with ticks/quotes# escpecially if they contain "#" chars...# Remember to edit /etc/mysql/debian.cnf when changing the socket location.[client]port = 3306socket = /var/run/mysqld/mysqld.sock# Here is entries for some specific programs# The following values assume you have at least 32M ram# This was formally known as [safe_mysqld]. Both versions are currently parsed.[mysqld_safe]socket = /var/run/mysqld/mysqld.socknice = 0[mysqld]## * Basic Settings#user = mysqlpid-file = /var/run/mysqld/mysqld.pidsocket = /var/run/mysqld/mysqld.sockport = 3306basedir = /usrdatadir = /var/lib/mysqltmpdir = /tmplc-messages-dir = /usr/share/mysqlskip-external-locking## Instead of skip-networking the default is now to listen only on# localhost which is more compatible and is not less secure.bind-address = 127.0.0.1## * Fine Tuning#key_buffer = 16Mmax_allowed_packet = 512Mthread_stack = 192Kthread_cache_size = 8# This replaces the startup script and checks MyISAM tables if needed# the first time they are touchedmyisam-recover = BACKUP#max_connections = 100#table_cache = 64#thread_concurrency = 10## * Query Cache Configuration#query_cache_limit = 4Mquery_cache_size = 512M## * Logging and Replication## Both location gets rotated by the cronjob.# Be aware that this log type is a performance killer.# As of 5.1 you can enable the log at runtime!#general_log_file = /var/log/mysql/mysql.log#general_log = 1## Error log - should be very few entries.#log_error = /var/log/mysql/error.log## Here you can see queries with especially long duration#log_slow_queries = /var/log/mysql/mysql-slow.log#long_query_time = 2#log-queries-not-using-indexes## The following can be used as easy to replay backup logs or for replication.# note: if you are setting up a replication slave, see README.Debian about# other settings you may need to change.#server-id = 1#log_bin = /var/log/mysql/mysql-bin.logexpire_logs_days = 10max_binlog_size = 100M#binlog_do_db = include_database_name#binlog_ignore_db = include_database_name## * InnoDB## InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.# Read the manual for more InnoDB related options. There are many!## * Security Features## Read the manual, too, if you want chroot!# chroot = /var/lib/mysql/## For generating SSL certificates I recommend the OpenSSL GUI "tinyca".## ssl-ca=/etc/mysql/cacert.pem# ssl-cert=/etc/mysql/server-cert.pem# ssl-key=/etc/mysql/server-key.pem[mysqldump]quickquote-namesmax_allowed_packet = 512M[mysql]#no-auto-rehash # faster start of mysql but no tab completition[isamchk]key_buffer = 512M## * IMPORTANT: Additional settings that can override those from this file!# The files must end with '.cnf', otherwise they'll be ignored.#!includedir /etc/mysql/conf.d/ It is being uploading for 3 days and right now 9.9 GB has been imported. The Database has both MyISAM and InnoDB tables. What can i do to improve the import performance? I have tried exporting each table separately in gz format with mysqldump and importing each table through PHP script executing the following code $dir="./";$files = scandir($dir, 1);array_pop($files);array_pop($files);$tablecount=0;foreach($files as $file){ $tablecount++; echo $tablecount." "; echo $file."\n"; $command="gunzip < ".$file." | mysql -u root -pubuntu cms"; echo exec($command);} Now provide the response and nothing else.
There are a lot of parameters that are missing, to fully understand the reason for the problem. such as: MySQL version Disk type and speed Free memory on the server before you start MySQL server iostat output before and at the time of the mysqldump. What are the parameters that you use to create the dump file in the first place. and many more. So I'll try to guess that your problem is in the disks because I have 150 instances of MySQL that I manage with 3TB of data on one of them, and usually the disk is the problem Now to the solution: First of all - your MySQL is not configured for best performance. You can read about the most important settings to configure at Percona blog post: http://www.percona.com/blog/2014/01/28/10-mysql-settings-to-tune-after-installation/ Especially check the parameters: innodb_buffer_pool_size innodb_flush_log_at_trx_commitinnodb_flush_method If your problem is the disk - reading the file from the same drive - is making the problem worse. And if your MySQL server starting to swap because it does not have enough RAM available - your problem becomes even bigger. You need to run diagnostics on your machine before and at the time of the restore procedure to figure that out. Furthermore, I can suggest you to use another technic to perform the rebuild task, which works faster than mysqldump. It is Percona Xtrabackup - http://www.percona.com/doc/percona-xtrabackup/2.2/ You will need to create the backup with it, and restore from it, or rebuild from running server directly with streaming option. Also, MySQL version starting from 5.5 - InnoDB performs faster than MyISAM. Consider changing all your tables to it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29643714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3398816/']}
jdg_370385
stackexchange
llm_judgeable_groundtruth_similarity
301844
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Suppose $\mathbf{v},\mathbf{w} \in \mathbb{R}^n$ (and if it helps, you can assume they each have non-negative entries), and let $\mathbf{v}^2,\mathbf{w}^2$ denote the vectors whose entries are the squares of the entries of $\mathbf{v}$ and $\mathbf{w}$. My question is how to prove that\begin{align*}\|\mathbf{v}^2\|\|\mathbf{w}^2\| - \langle \mathbf{v}^2,\mathbf{w}^2\rangle \leq \|\mathbf{v}\|^2\|\mathbf{w}\|^2 - \langle \mathbf{v},\mathbf{w}\rangle^2.\end{align*} Some notes are in order: The Cauchy-Schwarz inequality tells us that both sides of this inequality are non-negative. Thus the proposed inequality is a strengthening of Cauchy-Schwarz that gives a non-zero bound on the RHS. I know that this inequality is true, but my method of proving it is extremely long and roundabout. It seems like it should have a straightforward-ish proof, or should follow from another well-known inequality, and that's what I'm looking for. Now provide the response and nothing else.
Here is a proof for every $n$. Using the notation $\mathbf{v}=(v_1,\dots,v_n)$ and $\mathbf{w}=(w_1,\dots,w_n)$, the inequality reads$$\left(\sum_i v_i^4\right)^{1/2}\left(\sum_i w_i^4\right)^{1/2}-\sum_i v_i^2 w_i^2\leq \left(\sum_i v_i^2\right)\left(\sum_i w_i^2\right)-\left(\sum_i v_i w_i\right)^2.$$Rewriting the right hand side in a familiar way, and then rearranging and squaring, we obtain the equivalent form$$\left(\sum_i v_i^4\right)\left(\sum_i w_i^4\right)\leq\left(\sum_i v_i^2 w_i^2+\sum_{i<j}(v_iw_j-v_j w_i)^2\right)^2.$$Rewriting the left hand side in a familiar way, we obtain the equivalent form$$\left(\sum_i v_i^2w_i^2\right)^2+\sum_{i<j}(v_i^2w_j^2-v_j^2w_i^2)^2\leq\left(\sum_i v_i^2 w_i^2+\sum_{i<j}(v_iw_j-v_j w_i)^2\right)^2.$$Equivalently,$$\sum_{i<j}(v_i^2w_j^2-v_j^2w_i^2)^2\leq 2\left(\sum_k v_k^2w_k^2\right)\sum_{i<j}(v_iw_j-v_j w_i)^2+\left(\sum_{i<j}(v_iw_j-v_j w_i)^2\right)^2.$$It will be clear in a moment why we renamed the variable $i$ to $k$ in the first sum on the right hand side. Namely, we claim that the following stronger inequality holds:$$\sum_{i<j}(v_i^2w_j^2-v_j^2w_i^2)^2\leq 2\sum_{i<j}(v_i^2w_i^2+v_j^2w_j^2)(v_iw_j-v_j w_i)^2+\sum_{i<j}(v_iw_j-v_j w_i)^4.$$Indeed, this inequality can be rearranged to$$0\leq 2\sum_{i<j}(v_iw_i-v_jw_j)^2(v_iw_j-v_jw_i)^2,$$and we are done.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/301844', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11236/']}
jdg_370386
stackexchange
llm_judgeable_groundtruth_similarity
2431836
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the pros and cons of using either of the following approaches to pulling out a double from an object? Beyond just personal preferences, issues I'm looking for feedback on include ease of debugging, performance, maintainability etc. public static double GetDouble(object input, double defaultVal){ try { return Convert.ToDouble(input); } catch { return defaultVal; }}public static double GetDouble(object input, double defaultVal){ double returnVal; if (double.TryParse(input.ToString(), out returnVal)) { return returnVal; }else { return defaultVal; }} Now provide the response and nothing else.
TryParse will be faster than catching an exception TryParse indicates something expected - nothing exceptional is happening here, it's just that you suspect your data may not be valid. TryParse isn't using exception handling for normal control flow Basically, go with TryParse :) By the way, your code can be rewritten as: public static double GetDouble(object input, double defaultVal){ double parsed; return double.TryParse(input.ToString(), out parsed)) ? parsed : defaultVal;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2431836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292251/']}
jdg_370387
stackexchange
llm_judgeable_groundtruth_similarity
106737
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 just received a .jpg file that I'm almost positive contains a virus, so I have two questions about what I am able to do with the image. My first question originates from the fact that I opened the file once and the program I used to open it gave the error "invalid or corrupt image". So I want to know whether or not its possible a virus contained inside the image could still have been executed if the software did not 'fully' open the image? My second question is if there is any way to decode/decompile the image data in order to better view its contents. Currently I'm using Notepad++, I just opened the file and am looking at its raw contents, which is one of the reasons why I'm so confident its a virus: So is there a better way to find out what the virus does and how it works? I need to know whether or not my security has been compromised. EDIT: Reasons why I think it contains a virus: It's way bigger than the image I was expecting Scan Looking at contents in Notepad ( file ) The way the person who gave me the file acted Now provide the response and nothing else.
Based on the description at Virustotal you've linked to this is in reality not an image, but a real PE32 executable (normal windows executable). So only the file name extension was changed to hide the real purpose of the file. PE32 will not be automatically executed when they have the .jpg extension like in this case. Also the image viewer which will be invoked with the file by default will not execute the code but instead exit or complain that this is not a valid image. Thus this file would not work alone. But such files are typically used together with another file which will rename it to name.exe and execute it. This can be done by some batch file, with the help of the Windows Scripting Host ActiveX inside a website or mail or similar. This strategy is used to bypass antivirus and firewalls which might skip analyzing the "jpg" file because of the extension and will not find anything suspicious in the accompanying script (which only renames the file and executes it). ...if there is any way to decode/decompile the image data Again, this is not an image but an executable so the tool of choice could be some disassembler, debugger, sandboxed execution etc. See also the analysis from Virustotal .
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/106737', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/93150/']}
jdg_370388
stackexchange
llm_judgeable_groundtruth_similarity
68336407
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 retrieved a list from my firebase Database containing all the users. How do I check if the given user name and password exist in this list? const Login = () => { const [userName, setUserName] = useState(); const [password, setPassword] = useState(); const [users, setUsers] = useState({}); useEffect(() => { firebaseDb.child('users').on('value', snapshot => { if (snapshot.val() !== null) setUsers({ ...snapshot.val() }) else setUsers({}) }) }, []); const Login = e => { e.preventDefault(); let item = { userName, password }; //How to check if item is in users } } return ( <> <form autoComplete="off" onSubmit={Login}> ...); The SignUp function is down below, please note that each user has a username a name and a password const signUp = e => { e.preventDefault(); firebaseDb.child('users').push( values, err => { if (err) console.log(err) else { history.push("/allUsers") localStorage.setItem("user-info", JSON.stringify(values.name)) } }) Now provide the response and nothing else.
It is definitely best to just call useQuery again, because it's the only thing that creates a subscription, so your component will re-render correctly if new data comes in. You can do it imperatively with queryClient.getQueryData('todos') , but it doesn't create a subscription. Note that useQuery will not always trigger a fetch of the data. You can customize staleTime to tell react-query how long a resource is considered fresh, and as long as it's fresh, data will come from the internal cache only. If you set staleTime: Infinity , there will only be one fetch, and all other invocations will only read from the cache (apart from manual invalidations and garbage collection). It's also best to extract useQuery calls to a custom hook: const useTodos = () => useQuery('todos', fetchFunction) HomeComponent:const { data } = useTodos() TodosComponent:const { data } = useTodos()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/68336407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16143808/']}
jdg_370389
stackexchange
llm_judgeable_groundtruth_similarity
8082425
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: _radixSort_0 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];/*RADIX SORTUse 256 binsUse shadow array- Get counts- Transform counts to pointers- Sort from LSB - MSB*/function radixSort(intArr) { var cpy = new Int32Array(intArr.length); var c4 = [].concat(_radixSort_0); var c3 = [].concat(_radixSort_0); var c2 = [].concat(_radixSort_0); var c1 = [].concat(_radixSort_0); var o4 = 0; var t4; var o3 = 0; var t3; var o2 = 0; var t2; var o1 = 0; var t1; var x; for(x=0; x<intArr.length; x++) { t4 = intArr[x] & 0xFF; t3 = (intArr[x] >> 8) & 0xFF; t2 = (intArr[x] >> 16) & 0xFF; t1 = (intArr[x] >> 24) & 0xFF ^ 0x80; c4[t4]++; c3[t3]++; c2[t2]++; c1[t1]++; } for (x=0; x<256; x++) { t4 = o4 + c4[x]; t3 = o3 + c3[x]; t2 = o2 + c2[x]; t1 = o1 + c1[x]; c4[x] = o4; c3[x] = o3; c2[x] = o2; c1[x] = o1; o4 = t4; o3 = t3; o2 = t2; o1 = t1; } for(x=0; x<intArr.length; x++) { t4 = intArr[x] & 0xFF; cpy[c4[t4]] = intArr[x]; c4[t4]++; } for(x=0; x<intArr.length; x++) { t3 = (cpy[x] >> 8) & 0xFF; intArr[c3[t3]] = cpy[x]; c3[t3]++; } for(x=0; x<intArr.length; x++) { t2 = (intArr[x] >> 16) & 0xFF; cpy[c2[t2]] = intArr[x]; c2[t2]++; } for(x=0; x<intArr.length; x++) { t1 = (cpy[x] >> 24) & 0xFF ^ 0x80; intArr[c1[t1]] = cpy[x]; c1[t1]++; } return intArr;} EDIT: So far, the best/only major optimization brought to light is JS typed arrays. Using a typed array for the normal radix sort's shadow array has yielded the best results. I was also able to squeeze a little extra out of the in place quick sort using JS built in stack push/pop. latest jsfiddle benchmark Intel i7 870, 4GB, FireFox 8.02milradixSort(intArr): 172 msradixSortIP(intArr): 1738 msquickSortIP(arr): 661 ms200kradixSort(intArr): 18 msradixSortIP(intArr): 26 msquickSortIP(arr): 58 ms It appears standard radix sort is indeed king for this work-flow. If someone has time to experiment with loop-unrolling or other modifications for it I would appreciate it. I have a specific use case where I'd like the fastest possible sorting implementation in JavaScript. There will be large (50,000 - 2mil), unsorted (essentially random), integer (32bit signed) arrays that the client script will access, it then needs to sort and present this data. I've implemented a fairly fast in place radix sort and in place quick sort jsfiddle benchmark but for my upper bound array length they are still fairly slow. The quick sort performs better on my upper bound array size while the radix sort performs better on my lower bound. defaultSort is the built-in JavaScript array.sort with an integer compare functionIntel C2Q 9650, 4GB, FireFox 3.62milradixSortIP(intArr): 5554 msquickSortIP(arr): 1796 ms200kradixSortIP(intArr): 139 msquickSortIP(arr): 190 msdefaultSort(intArr): 354 msIntel i7 870, 4GB, FireFox 8.02milradixSortIP(intArr): 990 msquickSortIP(arr): 882 msdefaultSort(intArr): 3632 ms200kradixSortIP(intArr): 28 msquickSortIP(arr): 68 msdefaultSort(intArr): 306 ms Questions Is there a better implementation of any sorting algorithm that would meet my use case/needs? Are there any optimizations that can be made to my in place radix/quick sort implementations to improve performance? Is there an efficient way to convert my in place radix sort from a recursive to iterative function? Memory and execution speed. Goal I am hoping these answers will help me get ~20-30% performance improvement in my benchmark test. Clarifications/Notes "DEFINE FAST" I would prefer a general case where it runs well on all modern browsers, but if there is a browser specific optimization that makes a significant improvement that may be acceptable. The sorting COULD be done server side, but I'd prefer to avoid this because the JS app may become a standalone (paired with some off the shelf proprietary app that will stream sensor data to a file). JavaScript may not be the best language for this but it's a requirement. I've already asked this question https://stackoverflow.com/questions/7111525/fastest-way-to-sort-integer-arrays-in-javascript an incorrect answer was up-voted and the question was closed. I've attempted using multiple browser window instances as a makeshift multi-threading; it didn't pan out. I'd be interested in useful info regarding spawning multiple windows for concurrency. Now provide the response and nothing else.
I've tested typed arrays , the QSIP version seems to be good in modern browsers: 2 000 000 elements QSIP_TYPED | RDXIP_TYPED | QSIP_STD | RDXIP_STD----------------------------------------------------------Chrome | 300 1000 600 1300Firefox | 550 1500 800 1600 http://jsfiddle.net/u8t2a/35/ Support ( source: http://caniuse.com/typedarrays ): IE 10+ | FF 4+ | Chrome 7+ | Safari 5.1+ | Opera 11.6+
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8082425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/884862/']}
jdg_370390
stackexchange
llm_judgeable_groundtruth_similarity
69300
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: How does a dual gate MOSFET reduce Miller effect ? I am trying to gain a global understaning of the physics behind them, not necessarily exact formula's that come with it other than maybe some for practical use. The Wikipedia article refers to a tetrode article based on tubes, where I get slightly lost. I guess the questions in order are: What is a tetrode ( in discrete transistor/MOSFET speak ); How is a dual gate MOSFET similar to a tetrode, what are the 'mechanics' behind it in global terms? (Trying to get a feeling for the physics behind it). How does it reduce Miller effect and is a dual gate MOSFET different from a discrete tetrode in this. Is a dual gate MOSFET any good for other properties? Now provide the response and nothing else.
I'm going to ignore the reference to tetrode, I have never understood why an exact analogy reveals a fundamental truth. The miller effect arises in situations from a connecting capacitance across two nodes that that have an inverting voltage gain/relationship between them. it doesn't have to be in transistors either, but in MOSFET's you have \$C_{GD}\$. How this is traditionally solved is to cascode the amplifier by isolating the offending capacitance so it doesn't appear across the gain stage. The dual gate Mosfet is basically a cascode stage with the cascode transistor built in (this has a secondary effect, see below), you just have to bias the the transistors so that they are in the active regime. M1 = amplifier, M2 = cascode simulate this circuit – Schematic created using CircuitLab The amplifer transistor converts the input voltage in the output current and the cascode transistor simply transfers this current to the output load. the output is on the drain of the cascode and the input is on the gate of the amplifier transistor. There is no capacitance across the two nodes, the miller effect is greatly reduced. Cascoding greatly helps in gain too. An interesting effect from manufacturing comes into play. The upper device is a longer gate device and the lower is a dual gate device. The S/D implant to channel capacitance tends to be lower than the S/D to isolation edge capacitance (the S/D's on the outer edge) so the S/D in between the gates will tend to have a lower capacitance that if you were to have designed the circuit using two separate transistors in a cascode configuration (and obviously they take up less area). This means that the \$C_{SB}\$ capacitance is less as well making for a higher speed circuit, here SB = Source to Bulk (AKA well).
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/69300', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/8627/']}
jdg_370391
stackexchange
llm_judgeable_groundtruth_similarity
2729815
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Other than the type it returns and the fact that you call it differently of course <% Html.RenderPartial(...); %><%= Html.Partial(...) %> If they are different, why would you call one rather than the other one? The definitions: // Type: System.Web.Mvc.Html.RenderPartialExtensions// Assembly: System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35// Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dllusing System.Web.Mvc;namespace System.Web.Mvc.Html{ public static class RenderPartialExtensions { public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model); public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData); }}// Type: System.Web.Mvc.Html.PartialExtensions// Assembly: System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35// Assembly location: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 2\Assemblies\System.Web.Mvc.dllusing System.Web.Mvc;namespace System.Web.Mvc.Html{ public static class PartialExtensions { public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model); public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData); }} Now provide the response and nothing else.
The only difference is that Partial returns an MvcHtmlString , and must be called inside <%= %> , whereas RenderPartial returns void and renders directly to the view. If you look at the source code , you'll see that they both call the same internal method, passing a StringWriter for it to render to. You would call Partial if you want to view, save, or manipulate the generated HTML instead of writing it to the page.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2729815', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156415/']}
jdg_370392
stackexchange
llm_judgeable_groundtruth_similarity
10412651
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I remove script elements before they are being executed ? I thought about using the DOMNodeInserted event, but apparently it doesn't catch script elements. I've also tried using the jQuery livequery plugin like that: $("script").livequery(function () { $(this).remove();}); It did remove the script element, but after it was executed. I'm looking for a cross-browser solution, but I'm not even sure if that's possible. I read about Mutation Observers which seems close enough but I'm not sure if it can solve my problem. It would be even better if there was a way to modify the script content before it is being executed without removing and recreating it. Now provide the response and nothing else.
Removing a script element does not do anything. If you can somehow access a script element, it was executed a long time ago and removing it will have no effect. So we need to work around it. If your script element is at the top of the page like this: <head> <script src="yourscript.js"></script> You could make a synchronous ajax request to the same page, so you can parse its content into a new document, modify all script tags and then replacethe current document with the modified document. var xhr = new XMLHttpRequest, content, doc, scripts;xhr.open( "GET", document.URL, false );xhr.send(null);content = xhr.responseText;doc = document.implementation.createHTMLDocument(""+(document.title || ""));doc.open();doc.write(content);doc.close();scripts = doc.getElementsByTagName("script");//Modify scripts as you please[].forEach.call( scripts, function( script ) { script.removeAttribute("src"); script.innerHTML = 'alert("hello world");';});//Doing this will activate all the modified scripts and the "old page" will be gone as the document is replaceddocument.replaceChild( document.importNode(doc.documentElement, true), document.documentElement); Unfortunately this cannot be set up in jsfiddle or jsbin. But you should be able to copy paste this code exactly as it is into this page's console in google chrome. You should see the alerts and when you inspect the live dom, each script was modified. The difference is that we are running this after scripts have been executed on the page, so the old scripts should still have a working effect on the page. That's why, for this to work, you need to be the very first script on the page to do it. Tested to work in google chrome. Firefox is completely ignoring the doc.write call for some reason.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10412651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140937/']}
jdg_370393
stackexchange
llm_judgeable_groundtruth_similarity
27764979
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Absolute newbie to C#. Was trying to run this program and the output simply would not show any computations.Why? I did not want to go through p,q,r,s for add, sub, multiply, divide etc., Also, how can i put space between "Please enter a number" and userName? string userName;double x, y;Console.WriteLine(" Enter Your Name ");userName = Console.ReadLine();Console.WriteLine(" Please Enter A Number "+ userName);First = Convert.ToDouble(Console.ReadLine());Console.WriteLine("Please Enter Another Number"+ userName);Second = Convert.ToDouble(Console.ReadLine());Console.WriteLine("The addition of Two Numbers is",x,y, x*y);Console.WriteLine("The substraction of Two Numbers is",x,y,x/y);Console.WriteLine("The multiplication of Two Numbers is",x,y,x * y);Console.WriteLine("The division of Two Numbers given is", x,y,x / y);Console.ReadKey(); Now provide the response and nothing else.
When you pass additional parameters to show output, you must tell WriteLine where to put it by adding placeholders to the format line, like this: Console.WriteLine("The product of Two Numbers {0} and {1} is {2}", x, y, x*y); Positions are zero-based. The printed value of the first additional parameter (i.e. x ) will replace {0} ; the value of y will replace {1} , and the value of x*y will replace {2} in the final output. The reason you did not have to do it with userName is that you passed a single parameter: Console.WriteLine("Please Enter Another Number " + userName); The result of appending userName to "Please Enter Another Number" string is passed as a single parameter to WriteLine . You could rewrite it with a format specifier, like this: Console.WriteLine("Please Enter Another Number {0}", userName);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27764979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4417019/']}
jdg_370394
stackexchange
llm_judgeable_groundtruth_similarity
1801440
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: You are playing a game in which you have $100$ jellybeans, $10$ of them are poisonous (You eat one, you die). Now you have to pick $10$ at random to eat. Question : What is the probability of dying? How I tried to solve it: Each jellybean has a $\frac{1}{10}$ chance of being poisonous. Since you need to take $10$ of them, I multiply it by $10$ which gave $1$ (Guaranteed death). How other people tried to solve it : Each jellybean is picked out separately. The first jellybean has a $\frac{10}{100}$ chance of being poisonous, the second -- $\frac{10}{99}$, the third -- $\frac{10}{98}$ and so on.. which gives a sum of roughly $\sim 1.04$ (More than guaranteed death!) Both these results make no sense since there are obviously multiple possibilities were you survive since there are $90$ jellybeans to pick out of. Can someone explain this to me? Now provide the response and nothing else.
So you live if you do not choose a deadly jellybean :) And we die if we select at least one deadly bean, so I think it goes as follows$$P(\text{Die}) = 1-P(\text{Live}) = 1-\frac{\binom{10}{0}\binom{90}{10}}{\binom{100}{10}}=0.6695237889.$$ In this case, we literally have good beans and bad beans, and we select without replacement. Then the number of bad beans selected follows a hypergeometric distribution. So for completeness, there are $\binom{10}{0}$ ways to choose a zero bad beans, $\binom{90}{10}$ ways to choose 10 good beans, and finally $\binom{100}{10}$ ways to choose 10 beans from the total. Note: $\binom nk = \frac{n!}{k!(n-k)!}$, the binomial coefficient .
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1801440', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/342630/']}
jdg_370395
stackexchange
llm_judgeable_groundtruth_similarity
18414585
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 doing a webpage with the Bootstrap framework. I want to have a single page, with a form that pops up and has two or three tabs on it. I want this, The tabs for "The Markup", "The CSS", "The JavaScript". I have them showing up on the top left of the page like it's on the main navbar, but I can't get them anywhere else. Ideally, I'd like them to be on top of a form and switch between the forms. Another question that's probably elementary, but to get the buttons like I have them I used this code, <div class="note-tabs"> <ul class="nav nav-tabs"> <li class="active"><a href="#navbar-fixed-html" data-toggle="tab"><strong>The Markup</strong></a></li> <li><a href="#navbar-fixed-css" data-toggle="tab"><strong>The CSS</strong></a></li> <li><a href="#navbar-fixed-js" data-toggle="tab"><strong>The JavaScript</strong></a></li> </ul></div> What does it mean when the href field has a # at the front? This is from an example page at tutsplus and this is what came with the download. There isn't a separate html file for those, so what exactly is that linking to? Thanks UPDATE Here is the form I have, I want to add tabs to the top of this form. One tab that selects this form and another tab that will select another form. The form is place in the middle of the page http://jsfiddle.net/BS4Te/3/ Now provide the response and nothing else.
Step debug into g++ 6.4 stdlibc++ source Did you know that on Ubuntu's 16.04 default g++-6 package or a GCC 6.4 build from source you can step into the C++ library without any further setup? By doing that we easily conclude that a Red-black tree used in this implementation. This makes sense, since std::map , unlike std::unordered_map , can be traversed in key order, which would not be efficient in if a hash map were used. main.cpp #include <cassert>#include <map>int main() { std::map<int, int> m; m.emplace(1, -1); m.emplace(2, -2); assert(m[1] == -1); assert(m[2] == -2);} Compile and debug: g++ -g -std=c++11 -O0 -o main.out main.cppgdb -ex 'start' -q --args main.out Now, if you step into s.emplace(1, -1) you immediately reach /usr/include/c++/6/bits/stl_map.h : 556 template<typename... _Args>557 std::pair<iterator, bool>558 emplace(_Args&&... __args)559 { return _M_t._M_emplace_unique(std::forward<_Args>(__args)...); } which clearly just forwards to _M_t._M_emplace_unique . So we open the source file in vim and find the definition of _M_t : typedef _Rb_tree<key_type, value_type, _Select1st<value_type>, key_compare, _Pair_alloc_type> _Rep_type; /// The actual tree structure. _Rep_type _M_t; So _M_t is of type _Rep_type and _Rep_type is a _Rb_tree . OK, now that is enough evidence for me. If you don't believe that _Rb_tree is a Black-red tree, step a bit further and read the algorithm unordered_map uses hash table Same procedure, but replace map with unordered_map on the code. This makes sense, since std::unordered_map cannot be traversed in order, so the standard library chose hash map instead of Red-black tree, since hash map has a better amortized insert time complexity. Stepping into emplace leads to /usr/include/c++/6/bits/unordered_map.h : 377 template<typename... _Args>378 std::pair<iterator, bool>379 emplace(_Args&&... __args)380 { return _M_h.emplace(std::forward<_Args>(__args)...); } So we open the source file in vim and search for the definition of _M_h : typedef __umap_hashtable<_Key, _Tp, _Hash, _Pred, _Alloc> _Hashtable; _Hashtable _M_h; So hash table it is. std::set and std::unordered_set Analogous to std::map vs std::unordered_map : What is the underlying data structure of a STL set in C++? Performance characteristics You could also infer the data structure used by timing them: Graph generation procedure and Heap vs BST analysis and at: Heap vs Binary Search Tree (BST) Since std::map is analogous to std::set we clearly see for: std::map , a logarithmic insertion time std::unordered_map , a more complex hashmap pattern: on the non-zoomed plot, we clearly see the backing dynamic array doubling on huge one off linearly increasing spikes on the zoomed plot, we see that the times are basically constant and going towards 250ns, therefore much faster than the std::map , except for very small map sizes Several strips are clearly visible, and their inclination becomes smaller whenever the array doubles. I believe this is due to average linearly increasing linked list walks withing each bin. Then when the array doubles, we have more bins, so shorter walks.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18414585', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1357707/']}
jdg_370396
stackexchange
llm_judgeable_groundtruth_similarity
2875394
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why is there no holomorphic function $f:D \rightarrow D$ such that $f(1)=1, f(2)=4$? Here, $D = \{ z\in \mathbb{C}:Re(z) > 0\}$. Would you give me any hint? Thanks in advance. Now provide the response and nothing else.
Consider the diagram, which transforms the given function $f:D\to D$ into a function $g:U\to U$, where $U$ is the unit disk centered in the origin:$\require{AMScd}$\begin{CD} D @>f>> D\\ @V \mu V V @VV \mu V\\ U @>>g> U\end{CD} with $$\mu(z)=\frac{z-1}{z+1}\ .$$The Möbius transformation $\mu$ above is associated to the matrix $\begin{bmatrix}1 & -1\\1&1\end{bmatrix}$, it has as inverse the Möbius transformation associated to the matrix $\begin{bmatrix}1 & 1\\-1 & 1\end{bmatrix}$. It is relatively simple to show that $\mu$ is biholomorphic. We have $\mu(1)=0$, $\mu(2)=1/3$, $\mu(4)=3/5$. This means that the holomorphic function $g$ satisfies $g(0)=0$, and $g(1/3)=3/5$.This contradicts $|g(z)|\le |z|$, Schwarz Lemma on $U$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2875394', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/577525/']}
jdg_370397
stackexchange
llm_judgeable_groundtruth_similarity
43425
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As @ProfRob stated in his excellent answer regarding the ejection of the Solar System's fifth gas giant , It is for similar reasons that, even though the Sun was probably born in a cluster of $\sim 10^4$ stars, none of those siblings have been firmly identified. So why is it so difficult to find such stellar siblings? NB: Maybe it's because open clusters tend to disassociate quickly and the stars would be scattered everywhere. But wouldn't stars with similar spectra, age, metallicity, etc. be found easily? Now provide the response and nothing else.
Here are the problems/issues: Most stars are born in clusters/associations but a cursory investigation of cluster demographics with age reveals that the vast majority of clusters do not survive to old age. The majority either are never gravitationally bound to begin with or become unbound in the first 10 Myr. The Sun was likely born in a cluster of $10^3-10^4$ stars ( Adams 2010 ). If it dispersed more than 4 billion years ago, then its members would have had time to spread all around the galaxy by now. That is because although the members would be kinematically coherent to begin with, the velocity distribution of stars in the Galactic disc becomes "heated" as stars scatter in the potential of giant molecular clouds and pass through spiral arms ( Wielen 1977 ). They attain a significant velocity dispersion which means they could now occupy positions over a broad swathe of the Galactic disc and be displaced above/below the disc by $\sim 200$ pc. If we argue that the Sun's siblings could be in an annulus, with width $\pm 1$ kpc and thickness 400 pc, then if the solar cluster was $10^4$ stars, then the nearest sibling is expected to be at a distance of 160 pc. Another way of looking at this: The density of stars in the Galactic disc is around 0.1 per cubic parsec compared to the expected density of solar siblings of $2.4\times 10^{-7}$ per cubic parsec.Thus only about 1 in 400,000 of the local stars might be a solar sibling. How could they be found?Cluster members would have a similar age and a similar chemical composition. We know the age of the Sun precisely and accurately. We don't have that information for any other star. Age estimates of field stars are imprecise, model-dependent and are of indeterminate accuracy. In the best cases - solar type stars and a little more massive - asteroseismology and the HR diagram position might give an age to about $\pm 0.5$ Gyr. But you need good data to do that and we don't have asteroseismology for the nearest 400,000 solar-type stars (in order to find ONE solar sibling). Even if we did, it would only narrow the candidates down by a factor of 10. What about chemical abundances? There are now big spectroscopic surveys that have observed large-ish numbers of stars. Again, the most robust data comes for stars like the Sun, so that a differential abundance analysis can be done. The more numerous cooler stars have spectra which are more difficult to deal with and there may be systematic abundance errors when comparing with the Sun. Giant stars are bright, with narrow spectral lines, which is good, but their abundances may have been modified during their evolution. Thus we are limited to looking at solar-type field stars. No spectroscopic surveys (yet) have detailed spectra of 400,000 potential solar siblings. Chemical abundance may also not be that discriminatory. In the solar neighbourhood, stars have an abundance dispersion of about a factor of two , centered quite close (a bit below) the solar metallicity. Good quality spectroscopic analysis can give the metallicity to 10%, so enough to resolve the distribution, but it would only whittle down the candidates by factors of a few. Very high quality spectra could look at the detailed abundance mixture, but is only available perhaps for a few thousand stars. The majority also have an abundance mixture that is not very different to the Sun. Thus whilst the evidence is that the detailed abundance dispersion in a cluster is much smaller than the dispersion in field stars ( Paulson et al. 2003 ), it does not look like the Sun is that unusual or has any unique chemical "markers" ( Bensby et al. 2014 ). Some hope may be offered by the detailed mix of s- and r- process elements; the former may be age sensitive (e.g. Jofre et al. 2020 ), while the latter might reveal some peculiarity associated with contamination by nearby supernovae in the Sun's natal environment. At the moment, although candidate solar twins can be found, it is unclear by how much that narrows down the one in 400,000 figure, especially when you consider that abundance peculiarities may also be imprinted by later accretion events or some process associated with planet formation (e.g. Melendez et al. 2012 ) or that the abundance dispersion in a cluster may not be exactly zero (e.g. Liu et al. 2016 ). In summary, the space density of solar siblings is likely to be very low compared with unassociated field stars. The properties of those siblings are not that unusual compared with typical field stars and we lack precise enough measurements of age and chemical composition to have anything more than a list of candidate solar twins at the moment. It's like looking for a needle in a huge pile of other needles.
{}
{'log_upvote_score': 6, 'links': ['https://astronomy.stackexchange.com/questions/43425', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/31410/']}
jdg_370398
stackexchange
llm_judgeable_groundtruth_similarity
7480
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 use ssh a lot to connect to a variety of servers at my university. The machines are administrated by students, so assume they can't really be trusted;-) What are the risks in making a ssh connection to a host I have no control over?What information can be gained about an ssh client from the server side?Is there a chance they can open a shell from the server on my client machine? Now provide the response and nothing else.
SSH does not allow to open a shell on the client from the remote server. It does support reversed port forwarding, but that is initiated on the client side via -R or a ~-command. The main risk is X11 forwarding. If your SSH client is configured to allow programs on the server to render gui windows on your screen, there is an issue. Even untrusted X11 programs can cause a lot of damage. So it is best to use -x (important: small x) on the command line or ForwardX11 no in the ssh_config file. -X Enables X11 forwarding. This can also be specified on a per-host basis in a configuration file. X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring. For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. -x Disables X11 forwarding. -Y Enables trusted X11 forwarding. Trusted X11 forwardings are not subjected to the X11 SECURITY extension controls. Source: man ssh
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/7480', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/5117/']}
jdg_370399
stackexchange
llm_judgeable_groundtruth_similarity
13670274
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 form in C# that I want to enter as red, green and blue in 3 TextBox controls and make a new color. For example: red=3, green=2, blue=5when I click on "MAKE COLOR" button, a label shows me the new color. Now provide the response and nothing else.
Let us assume that you have some code that looks similar to this: int red = Convert.ToInt32(RedColorComponentValueTextBox.Text);int green = Convert.ToInt32(GreenColorComponentValueTextBox.Text);int blue = Convert.ToInt32(BlueColorComponentValueTextBox.Text);//Don't forget to try/catch this Then to create the color from these values, try Color c = Color.FromArgb(red, green, blue); Then set the ForeColor property (or the BackColor property -- not sure which one you meant to change) of the label to c . You will need to have using System.Drawing; in your code file (or class) preamble. Note: If you wanted to also have an alpha component, you could try this: Color c = Color.FromArgb(alpha, red, green, blue); General hint: If you want to use an HTML/CSS color specification of the form #RRGGBB e.g. #335577 , try this pattern int red = 0x33, green = 0x55, blue = 0x77;
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13670274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1688056/']}
jdg_370400
stackexchange
llm_judgeable_groundtruth_similarity
3609101
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: It’s well known that the geometric mean of a set of positive numbers is less sensitive to outliers than the arithmetic mean. It’s easy to see this by example, but is there a deeper theoretical reason for this? How would I go about “proving” that this is true? Would it make sense to compare the variances of the GM and AM of a sequence of random variables? Now provide the response and nothing else.
The geometric mean is the exponential of the arithmetic mean of a log-transformed sample. In particular, $$\log\left( \biggl(\prod_{i=1}^n x_i\biggr)^{\!1/n}\right) = \frac{1}{n} \sum_{i=1}^n \log x_i,$$ for $x_1, \ldots, x_n > 0$ . So this should provide some intuition as to why the geometric mean is insensitive to right outliers, because the logarithm is a very slowly increasing function for $x > 1$ . But what about when $0 < x < 1$ ? Doesn't the steepness of the logarithm in this interval suggest that the geometric mean is sensitive to very small positive values--i.e., left outliers? Indeed this is true. If your sample is $(0.001, 5, 10, 15),$ then your geometric mean is $0.930605$ and your arithmetic mean is $7.50025$ . But if you replace $0.001$ with $0.000001$ , this barely changes the arithmetic mean, but your geometric mean becomes $0.165488$ . So the notion that the geometric mean is insensitive to outliers is not entirely precise.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/3609101', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/208270/']}
jdg_370401
stackexchange
llm_judgeable_groundtruth_similarity
23605
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: In the movie The Matrix, during "bullet time" sequences, bullets are shown trailing evenly-spaced refracting blobs: which presumably represent shockwaves or vapour trails. In reality, if it were possible to (almost) freeze time and move around the scene, what would a real bullet trail look like, if at all visible? Is it significantly different for different types of bullets (ignoring tracer bullets) or atmospheric conditions? These video clips claim to show trails, but they are not at all obvious: http://youtu.be/uO0MeyKlmPM?t=255 http://youtu.be/Kgh1bFeu3FI?t=18 Now provide the response and nothing else.
In reality, it is possible to "(almost) freeze time" and examine such phenomena, through the use of high speed photography. The fact that no clear photographs of "bullet trails" are readily found is a good indicator that such phenomena are not readily produced or observed. That said, there are two effects I can think of that could in principle lead to visible phenomena in your case of interest. They are both mentioned below, but the short answer is that neither will typically be "visible" in any reasonable sense of the word for a projectile the size of a bullet. In the right regime ($M \approx 1$), the Prandtl-Glauert singularity can lead to condensation, producing a visible cone of condensed water vapor [gallery] , [discussion] . The characteristic scale of this cloud is the same as that of the object. In this case, that means we are talking about a "cloud" of water vapor on the scale of a few $cm^3$. It is highly doubtful this effect would be readily visible for a projectile the size of a typical bullet, but nevertheless it could be present, given the appropriate conditions. photo credit: Ensign John Gay, USS Constellation, US Navy The second phenomena that could potentially be visually observed is distortion/refraction due to the changing density of air. I believe this is the effect present in the video clips you linked. This will visually act like a mirage (arising from the same physical cause, spatial variation of fluid density and therefore index of refraction), and it's visibility will depend significantly on illumination conditions and observational geometry. It doesn't "look like" anything, but rather distorts the path of light rays passing through it. It can be made much more readily apparent in controlled conditions as in this shadowgraph : photo credit: Andrew Davidhazy
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/23605', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7927/']}
jdg_370402
stackexchange
llm_judgeable_groundtruth_similarity
49101152
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This answer worked like a charm previously: https://stackoverflow.com/a/41041580/3894981 However, since Webpack v4 it doesn't work anymore. Since then it throws: Error: webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead. What is necessary here in order to make it work in Webpack v4? I've tried using the following without luck: const uglifyJsPlugin = require('uglifyjs-webpack-plugin');if (process.argv.indexOf('-p') !== -1) { // compress and remove console statements. Only add this plugin in production // as even if drop_console is set to false, other options may be set to true config.plugins.push(new uglifyJsPlugin({ compress: { 'drop_console': true } }));} Now provide the response and nothing else.
You're still putting it in config.plugins, have you tried putting it in config.optimization.minimizer? const UglifyJSPlugin = require('uglifyjs-webpack-plugin')...optimization: { minimizer: [ new UglifyJSPlugin({ uglifyOptions: { compress: { drop_console: true, } } }) ]}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49101152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3894981/']}
jdg_370403
stackexchange
llm_judgeable_groundtruth_similarity
161924
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 stumbled something interesting today when I was adding an account to my gmail one. Why is SSL boldly stated as recommended when TLS supersedes SSL? The links for SSL and TLS is the same: https://support.google.com/mail/answer/22370?hl=en Now provide the response and nothing else.
From that link: Select a secured connection Check with your other mail service for their recommended port number and authentication type. Here are some common combinations: SSL with port 465 TLS with port 25 or 587 The difference, then, is that "SSL" means SMTP over SSL-or-TLS on port 465, and "TLS" means SMTP with STARTTLS on port 25 or 587. So what's the difference between them? STARTTLS is opportunistic encryption. The connection starts as plaintext SMTP, and the client tries to initiate encryption if the server says that it can. The problem with this is that the plaintext negotiation can be relayed and modified by a Man-in-the-Middle attacker, exactly the way that sslstrip works for HTTP redirects and links to HTTPS. SMTP-over-SSL, on the other hand, starts with a SSL (or TLS--the exact protocol is negotiated) connection, then SMTP is conducted over that tunnel. With this configuration, the client always expects to use SSL, and can't be tricked into going plaintext. So the SSL-or-TLS naming is not the real issue. Google is using "SSL" to mean the older "smtps" standard, which is actually more secure in this case. In reality, the service is probably using TLS, and Google's mail servers will negotiate the most secure connection possible, depending on the other service. EDIT: As @Mehrdad points out in the comments, Google will change which option is "recommended" based on the port number that is selected in the dropdown. This shows that their recommendation is not based on higher assurance of encryption, but on what is most likely to work: port 465 is registered with IANA as 'smtps', and is expected to be SMTP-over-SSL. Ports 25 and 587 are 'smtp' and 'submission' respectively, and are expected to be plaintext. Since I doubt that Google will refuse to send mail over these ports if STARTTLS cannot be negotiated, "TLS" remains the weaker, opportunistic option. It is, however, more likely to be supported than port 465. EDIT 2: @grawity did the legwork and determined that Google does not, in fact, fall back to plaintext SMTP if STARTTLS is not supported. You have to explicitly select the "Unsecured" option when configuring the server. This is really good work by Google to ensure transport security for emails. Of course, all that has been said already about STARTTLS remains true: it requires this extra step of making TLS a strong requirement to avoid downgrade attacks.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/161924', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/122806/']}
jdg_370404
stackexchange
llm_judgeable_groundtruth_similarity
2099192
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So I have been learning about projective spaces for the last few hours, and I think I understand the basics pretty well, but there is an exercise, which I do not know how to solve at all. It comes down to being able to imagine and understand vector spaces and projective spaces over a finite field. Let's say, my projective space is a set of all the one dimensional subspaces of my vector space. Then, each line in my projective space has at least one, most of the time multiple representants (in other words: direction vectors) that span the line. The picture below shows the projective plane over a finite field with 3 elements (the Galois-Field $GF(3)$). I would now like to find a description for the points in this pictures, whereas each point should have some corresponding representants. How do I determine which vector belongs to which point? In $\mathbb{R}^3$ I can very well see that a vector $(1,0,0)$ spans my first axis, but what about a finite field? Any help is greatly appreciated! Now provide the response and nothing else.
Since your question specifically mentions projective planes, let's suppose that we have the three-dimensional vector space $V = \Bbb F_q^3$ over $\Bbb F_q$, the finite field with $q$ elements (that is, $GF(q)$ in your notation). One-dimensional subspaces Let's start with the fact that a one-dimensional subspace $L$ has the form $L = \{c \mathbf{v} : c \in \Bbb F_q\}$; it consists of all scalar multiples of some vector $\mathbf{v} \in V$. In particular, there are as many points in $L$ as there are scalars in $\Bbb F_q$: there are $q$ of them, and $q - 1$ are nonzero. But as you've pointed out, there aren't as many one-dimensional subspaces of $V$ as there are nonzero vectors in $V$ (when $V$ is finite, at least); two vectors $\mathbf{v}_1$ and $\mathbf{v}_2 $ determine the same subspace when they are scalar multiples of each other. Put another way, any of the $q - 1$ nonzero vectors in a one-dimensional subspace $L$ generate (in the sense of the "span of a set of vectors") $L$. Thus, by counting nonzero vectors in $V$, we've overcounted one-dimensional subspaces by a factor of $q - 1$, so there are $$\frac{q^3 - 1}{q - 1} = 1 + q + q^2$$ one dimensional subspaces of the three-dimensional vector space over $\Bbb F_q$. In your projective plane example, we have $q = 3$ for a total of $1 + 3 + 9 = 13\ \checkmark$ one-dimensional subspaces of $V$, or points in the projective plane. Two-dimensional Subspaces To think about lines in the picture, we need to understand two-dimensional subspaces of $\Bbb F_3^3$. Every pair of nonzero vectors $\mathbf{v}, \mathbf{w}$ where $\mathbf{v} \neq c \mathbf{w}$ determines a two-dimensional subspace of the form $P = \{c_1 \mathbf{v} + c_2 \mathbf{w} : c_1, c_2 \in \Bbb F_q\}$. This subspace contains $q^2$ vectors, and $q^2 - 1$ of them are nonzero. As we noted above, not all pairs of vectors in $P$ generate $P$: we must be careful that they do not lie on the same one-dimensional subspace. We can pick any nonzero vector in $P$ to start, and then any vector not in the span of the first; there are $(q^2 - 1)(q - 1)$ pairs $(\mathbf{v}, \mathbf{w})$ that span $P$. To count two-dimensional subspaces, we pick two nonzero vectors in $V$ not lying in the same one-dimensional subspace, and then take care of overcounting that arises due to multiple ways to generate the same plane: there are $$\frac{(q^3 - 1)(q^3 - q)}{(q^2 - 1)(q^2 - q)} = 1 + q + q^2$$ two-dimensional subspaces of three-dimensional $V$, the same number of one-dimensional subspaces! Food for thought: wouldn't it be nice if there was a "natural" bijection between the one- and two-dimensional subspaces, in our three-dimensional space? Specific one-dimensional subspaces To list the points of this projective plane, we can list $13$ vectors in $\Bbb F_3^3$ that don't lie (pairwise) in the same one-dimensional subspace: \begin{array}{lll} (c, 0, 0), & (0, c, 0), & (0, 0, c) \\ (0, c, c), & (c, 0, c), & (c, c, 0) \\(0, 2c, c), & (2c, 0, c), & (2c, c, 0) \\(c, c, 2c), & (c, 2c, c), & (c, c, 2c) \\ & (c, c, c), & \\\end{array} where here $(2c, c, c)$ means $\{c(2, 1, 1) : c \in \Bbb F_3\}$. To get some experience with vector spaces over finite fields, you should actually write out elements in some of these subspaces, and convince yourself that all $26$ nonzero vectors of $\Bbb F_3^3$ live in exactly one of these one-dimensional subspaces. Specific two-dimensional subspaces These are messier. It's easy to pick two linearly independent vectors $\mathbf{v}, \mathbf{w}$ and write some subspaces $\operatorname{Span}(\{\mathbf{v}, \mathbf{w}\})$, but listing them all, and without repeats, is a bit tedious (and not exactly easy!). Instead, recall that two-dimensional subspaces can always be described as the solution set to a linear equation $\{(x, y, z) : ax + by + cz = 0\}$ (just like you're used to with vector spaces over $\Bbb R$), and each such equation is "uniquely" determined by a vector $(a, b, c)$ normal to the subspace. This is great, because we just computed all the one-dimensional subspaces! With a bit of work, we can write down what generic elements in our two-dimensional subspaces look like: \begin{array}{lll}(0, a, b), & (a, 0, b), & (a, b, 0) \\(b, a, 2a), & (a, b, 2a), & (a, 2a, b) \\(b, a, a), & (a, b, a), & (a, a, b) \\(a, b, a + b), & (a, a+b, b), & (a+b, a, b) \\ & (a, b, 2a + 2b), & \\\end{array} where, for instance, $(a, b, a)$ represents the subspace $\{a(1, 0, 1) + b(0, 1, 0) : a, b \in \Bbb F_3\}$. Additionally, it's in the same place as $(2c, 0, c)$ in the previous table. This signifies that the subspaces are orthogonal: $(2c, 0, c) \cdot (a, b, a) = 2ac + ac = 3ac \equiv 0 \pmod 3$. Again to build familiarity, it would be good to pick a subspace or two and write out all vectors in these subspaces, as well as the one-dimensional subspaces it contains. The good news here is that projective planes have lots of symmetry (in fact, yours has 5616 automorphisms!); you can start building a correspondence between vectors and points in the image freely, although before long, you will have to be careful about how you're constructing things (to make sure points on the same line correspond to one-dimensional subspaces in a common two-dimensional subspace). It's probably better to create the image from scratch, using the picture as a guide for what should happen. A note of caution I didn't write out things for a general $n$-dimensional vector space, because things get more complicated. Another source of difficulty is the structure of $GF(p^n)$ for prime $p$ and $n > 1$. When you're working over $GF(p)$ for prime $p$, things are nice: You're just working in the ring $\Bbb Z /p\Bbb Z$, doing arithmetic modulo $p$. But this stops being the case in $GF(p^n)$, and I personally don't know how to work "quickly" in such a field, which is often constructed as a quotient of the polynomial ring $GF(p)[X]$ by an irreducible polynomial of degree $n$. Hopefully you've played around with the Fano plane too, things are very nice there!
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2099192', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/393220/']}
jdg_370405
stackexchange
llm_judgeable_groundtruth_similarity
3660567
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just like the title says, is there a way to check if an object is serializable, and if not, make it so at run time? Now provide the response and nothing else.
Short answer - no. Longer answer - yes, using byte-code manipulation, for example with asm. But you should really consider whether this is needed. Serialization is a serious matter (Effective Java has a whole chapter on serialization) Btw, there are alternatives to binary serialization, that do not require the object implementing Serializble (as pointed by Jacob in the comments): XML - java.beans.XMLEncoder.encode(..) is the xml version of ObjectOutputStream JSON - frameworks like Jacskon, Gson let you serialize an object with one line.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3660567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332347/']}
jdg_370406
stackexchange
llm_judgeable_groundtruth_similarity
191851
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 am building a VAR model to forecast the price of an asset and would like to know whether my method is statistically sound, whether the tests I have included are relevant and if more are needed to ensure a reliable forecast based on my input variables. Below is my current process to check for Granger causality and forecast the selected VAR model. require("forecast")require("vars")#Read Datada=read.table("VARdata.txt", header=T)dac <- c(2,3) # Select variablesx=da[,dac]plot.ts(x)summary(x)#Run Augmented Dickey-Fuller tests to determine stationarity and differences to achieve stationarity.ndiffs(x[, "VAR1"], alpha = 0.05, test = c("adf"))ndiffs(x[, "VAR2"], alpha = 0.05, test = c("adf"))#Difference to achieve stationarityd.x1 = diff(x[, "VAR1"], differences = 2)d.x2 = diff(x[, "VAR2"], differences = 2)dx = cbind(d.x1, d.x2)plot.ts(dx)#Lag optimisationVARselect(dx, lag.max = 10, type = "both")#Vector autoregression with lags set according to results of lag optimisation. var = VAR(dx, p=2)#Test for serial autocorrelation using the Portmanteau test#Rerun var model with other suggested lags if H0 can be rejected at 0.05serial.test(var, lags.pt = 10, type = "PT.asymptotic")#ARCH test (Autoregressive conditional heteroscedasdicity)arch.test(var, lags.multi = 10)summary(var)#Granger Causality test#Does x1 granger cause x2?grangertest(d.x2 ~ d.x1, order = 2)#Does x2 granger cause x1?grangertest(d.x1 ~ d.x2, order = 2)#Forecastingprd <- predict(var, n.ahead = 10, ci = 0.95, dumvar = NULL)print(prd)plot(prd, "single") Is this method sound? Now provide the response and nothing else.
I think you got it pretty right, but when building a VAR model, I usually make sure I follow these steps: 1. Select the variables This is the most important part of building your model. If you want to forecast the price of an asset, you need to include variables that are related with the mechanism of price formation. The best way to do this is through a theoretical model. Since you did not mention what is the asset and what are the other variables you included in your model I really cannot say much about this item, but you can find a summary of asset pricing models in here . 2. Check the data and make the proper adjustments Once you select the variables, you can make some adjustments to the data that will improve the estimation and interpretation of the model. It is useful to use summary statistics and see a plot of the series to detect outliers, missing data and other strange behaviors. When working with price data, people usually take natural logs, which is a variance-stabilizing transformation and also has a good interpretation (price difference in logs become continuously compound returns). I'm not sure if you have taken logs before estimating the model, but it is a good idea to do so if you are working with asset prices. 3. Check if data contains non-stationary components Now you can use unit root tests to check if your series are stationary. If you are only interested in forecasting, as noted by @JacobH, you can run VAR in levels even when your series are non-stationary, but then your standard errors cannot be trusted, meaning that you can't make inference about the value of the coefficients. You've tested stationary using the ADF test, which is very commonly used in these applications, but note that you should specify if you want to run the test with i) no constant and no trend; ii) a constant and no trend; and iii) a constant and a trend. Usually price series have stochastic trends, so a linear trend will not be accurate. In this case you may choose the specification ii. In your code you used the ndiffs function of the forecast package. I am not sure which of those three alternatives this function implements in order to calculate the number of differences (I couldn't find it in the documentation). To check your result you may want to use the ur.df function in the "urca" package: adf <- ur.df(x[, "VAR1"], type = "drift", lags = 10, selectlags = "AIC") Note that this command will run the ADF test with a constant and the lags selected by the AIC command, with maximum lag of 10. If you have problems interpreting the results just look at this question . If the series are I(1) just use the difference, which will be equal to the continuously compounded returns. If the test indicates that the series are I(2) and you are in doubt about that you can use other tests, e.g. Phillips-Perron test ( PP.test function in R). If all tests confirm that your series are I(2) (remember to use the log of the series before running the tests) then take the second difference, but note that your interpretation of the results will change, since now you are working with the difference of the continuously compounded returns. Prices of assets are usually I(1) since they are close to a random walk, which is a white noise when applying the first difference. 4. Select the order of the model This can be done with commonly used criteria such as Akaike, Schwarz (BIC) and Hannan-Quinn. You've done that with the VARselect function and that is right, but remember what is the criterion that you used to make your decision. Usually different criteria indicate different orders for the VAR. 5. Check if there are cointegrating relationships If all your series are I(1) or I(2), before running a VAR model, it is usually a good idea to check if there is no cointegration relationships between the series, specially if you want to make impulse response analysis with the residuals. You can do that using the Johansenn test or the Engle-Granger (only for bivariate models). In R you can run the Johansen test with the ca.jo function of the "urca" package. Note that this test also has different specifications. For price series I usually use the following code (where p is the lag length of item 4, performed with the series in levels): jo_eigen <- ca.jo(x, type = "eigen", ecdet = "const", K = p)jo_trace <- ca.jo(x, type = "trace", ecdet = "const", K = p) 6. Estimate the model If your series are not cointegrated, you can easily estimate the model with the VAR command, as done in your code. In case the series are cointegrated you need to consider the long run relationship by estimating a Vector Error Correction model with the following code (where k is the order of cointegration): vecm <- cajorls(joeigen, r = k) 7. Run diagnostics tests To test if your model is well specified you can run a test of serial correlation on the residuals. In your code you used a Portmanteau test with the serial.test function. I've never used this function but I think it is OK. There is also a multivariate version of the Ljung-Box test implemented in the package MTS which you can run with the function mq . 8. Make predictions After you are sure your model is well specified you can use the predict function as you did in your code. You can even plot impulse response functions to check how the variables respond to a particular shock using the irf function. 9. Evaluate predictions Once you made your predictions you must evaluate them and compare against other models. Some methods to evaluate accuracy of forecasts can be found here , but to do that it is crucial that you divide your series in a training and a test set, as explained in the link.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/191851', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/91349/']}
jdg_370407
stackexchange
llm_judgeable_groundtruth_similarity
41206
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: We're running on a virtual "dedicated" server, which should, in theory, mean that we're the only guys on the server. In practice.... I'm thinking we might not be. Notice that although it looks like we're killing our machine, "Steal time" is at 71% I'm taking statistics on load and I was disappointed that this stat didn't show up in my graphs. Are there any tools which monitor this which might be able to help? Additional information: We're running 4 cores, model: # grep "model name" /proc/cpuinfo | sort -umodel name : Intel(R) Core(TM)2 Duo CPU E7500 @ 2.93GHz Now provide the response and nothing else.
You're question is well defined, but you're not giving a lot of information about your environment, how you're currently monitoring or what graphing tools you're using. However, given that SNMP is used pretty much universally for that I'll assume that you're using it and have at least some familiarity with it. Although (as near as I can tell) the CPU Steal time isn't currently available from snmpd, you can extend it yourself with the UCD-SNMP-MIB::extOutput object and exec commands. The easiest way (that I've found) to get the steal time is from iostat . Using the following construct we can get just the steal time: $ iostat -c | awk 'NR==4 {print $5}'0.00 Therefore, append the following to your snmpd.conf: exec cpu_steal_time /usr/bin/iostat -c | /usr/bin/awk 'NR==4 {print $5}' (Alternatively you can put the command in a wrapper script and call the wrapper from inside snmpd.conf .) Each exec call in snmpd.conf is indexed starting from 1. So if you only have a single exec statement then you'll want to poll UCD-SNMP-MIB::extOutput.1 . If this is the 5th exec statement then poll UCD-SNMP-MIB::extOutput.5 , etc. The numeric OID for UCD-SNMP-MIB::extOutput is .1.3.6.1.4.1.2021.8.1.101 so if you're at index 1 it would be .1.3.6.1.4.1.2021.8.1.101.1 , and index 5 would be .1.3.6.1.4.1.2021.8.1.101.5 , etc. You then create a graph polling that SNMPD OID of type gauge, ranging from 0–100. This should give you some pretty graphs.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/41206', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/14792/']}
jdg_370408
stackexchange
llm_judgeable_groundtruth_similarity
4122268
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 scenario: setTimeout("alert('this alert is timedout and should be the first');", 5000);alert("this should be the second one"); I need the code after the setTimeout to be executed after the code in the setTimeout is executed. Since the code that comes after the setTimeout is not code of my own I can't put it in the function called in the setTimeout... Is there any way around this? Now provide the response and nothing else.
Is the code contained in a function? function test() { setTimeout(...); // code that you cannot modify?} In that case, you could prevent the function from further execution, and then run it again: function test(flag) { if(!flag) { setTimeout(function() { alert(); test(true); }, 5000); return; } // code that you cannot modify}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4122268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/309054/']}
jdg_370409
stackexchange
llm_judgeable_groundtruth_similarity
249927
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I restart(recycle) IIS Application Pool from C# (.net 2)? Appreciate if you post sample code? Now provide the response and nothing else.
If you're on IIS7 then this will do it if it is stopped. I assume you can adjust for restarting without having to be shown. // Gets the application pool collection from the server.[ModuleServiceMethod(PassThrough = true)]public ArrayList GetApplicationPoolCollection(){ // Use an ArrayList to transfer objects to the client. ArrayList arrayOfApplicationBags = new ArrayList(); ServerManager serverManager = new ServerManager(); ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools; foreach (ApplicationPool applicationPool in applicationPoolCollection) { PropertyBag applicationPoolBag = new PropertyBag(); applicationPoolBag[ServerManagerDemoGlobals.ApplicationPoolArray] = applicationPool; arrayOfApplicationBags.Add(applicationPoolBag); // If the applicationPool is stopped, restart it. if (applicationPool.State == ObjectState.Stopped) { applicationPool.Start(); } } // CommitChanges to persist the changes to the ApplicationHost.config. serverManager.CommitChanges(); return arrayOfApplicationBags;} If you're on IIS6 I'm not so sure, but you could try getting the web.config and editing the modified date or something. Once an edit is made to the web.config then the application will restart.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/249927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_370410
stackexchange
llm_judgeable_groundtruth_similarity
64087
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Here is my confusion: we can see colored light of different wavelengths: form red to violet. To my understanding, these stimuli cause a confirmational change in the photoreceptors in our eyes and results in a STP that eventually leads to an "all or nothing" action potential that sends another signal, again an all or nothing action potential through the optic chiasm to the occipital lobe and we perceive the colors as we see them. My question is *how does this signaling work? * ; How can a minor stimulus, resulting in an "all or nothing" chain of action potentials be converted into something as specific as the vision of color? Asked another way, how does variation in a confirmational change at a receptor that results in "all or nothing" signaling lead to specific signals being sent such as colored vision ? PS: I dont know jack about sensory physiology Now provide the response and nothing else.
Short answer Action potentials generated to different colors are indeed similar throughout the nervous system and do not encode color as such. Instead, the different color- sensitive cells in the retina are connected to different neurons and these color-specific signals are kept segregated up until the higher visual cortical areas. Background Action potentials are indeed pretty similar throughout the nervous system. However, the color-sensitive sensory cells in the retina , called the cones , come in three flavors: red, green and blue. These colors form the RGB system just like in your LED TV and can together make all the available millions of colors. These three cones synapse ultimately onto color-specific secondary sensory neurons (Fig. 1). Hence, R, G and B cones indeed generate identical action potentials in downstream neurons, the trick is they do so in different retinal ganglion cells , and at different firing rates depending on the intensity of light that particular cone is sensitive to. These different classes of retinal ganglion cells project onto different classes of neurons in the brainstem ( lateral geniculate nucleus , or LGN) and ultimately onto different neurons in the higher cortical visual areas in the brain. Fig. 1. Different classes of cones synapse onto different classes of secondary sensory neurons in the retina. source: Discovery Eye Foundation The reason why we can differentiate millions of colors can be explained by the Hering model of color vision (Fig. 2). Basically, the different cones converge pairwise onto opponent color-sensitive cells. The red-green opponent system, for example, operates by weighing the amount of red and green in the incoming signal. This weighting results in an analogue system that can code millions of colors along the red-green axis (Fig. 3). Fig. 2. Hering model of color vision. source: Webvision Fig. 3. Red-green color axis. source: SO
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/64087', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/32886/']}
jdg_370411
stackexchange
llm_judgeable_groundtruth_similarity
4387154
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I declare a non-member function (global function, may be) as const in C++? I understand that the const keyword actually is applied to the implicit "this" argument passed in member functions. Also since only member functions follow the "thiscall" calling convention, can const be applied for non-member functions? Leaving aside what I am trying to do by declaring non-member function const, would compiler report error for doing so? Now provide the response and nothing else.
No, only a non-static member function may be const qualified. What semantic would you expect from a const non-member function ? If you want to enforce that no parameters are modified by the function, just take them by const reference.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4387154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248643/']}
jdg_370412
stackexchange
llm_judgeable_groundtruth_similarity
421498
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 am not very conversant with the growth of a group, so this may be a very silly question. It is known that $F_2$ , the free group of rank $2$ , has exponential growth. I was wondering whether the following is true: If a group has exponential growth does it contain a free subgroup? Now provide the response and nothing else.
A famous theorem of Wolf shows that the growth of a solvable group is either polynomial or exponential. So no intermediate growth among solvable groups. And a famous theorem of Gromov shows that having polynomial growth implies being virtually nilpotent. Consequently, any solvable group that is not virtually nilpotent provides an example of a group with exponential growth but no non-abelian free subgroups. Of course, using big theorems is not necessary to find explicit examples, but it gives some general perspectives, and it justifies that many examples exist. One simple example is the Baumslag-Solitar group $BS(1,2)$ . It has a Cayley graph that is sufficiently simple to be drawn. The pictures are taken from Wikipedia , where there is also a nice animation.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/421498', 'https://mathoverflow.net', 'https://mathoverflow.net/users/333818/']}
jdg_370413
stackexchange
llm_judgeable_groundtruth_similarity
2831434
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 to design a server that needs to serve millions of clients that are simultaneously connected with the server via TCP. The data traffic between the server and the clients will be sparse, so bandwidth issues can be ignored. One important requirement is that whenever the server needs to send data to any client it should use the existing TCP connection instead of opening a new connection toward the client (because the client may be behind a firewall). Does anybody know how to do this, and what hardware/software is needed (at the least cost)? Now provide the response and nothing else.
What operating systems are you considering for this? If using a Windows OS and using something later than Vista then you shouldn't have a problem with many thousands of connections on a single machine. I've run tests (here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html ) with a low spec Windows Server 2003 machine and easily achieved more than 70,000 active TCP connections. Some of the resource limits that affect the number of connections possible have been lifted considerably on Vista (see here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html ) and so you could probably achieve your goal with a small cluster of machines. I don't know what you'd need in front of those to route the connections. Windows provides a facility called I/O Completion Ports (see: http://msdn.microsoft.com/en-us/magazine/cc302334.aspx ) which allow you to service many thousands of concurrent connections with very few threads (I was running tests yesterday with 5000 connections saturating a link to a server with 2 threads to process the I/O...). Thus the basic architecture is very scalable. If you want to run some tests then I have some freely available tools on my blog that allow you to thrash a simple echo server using many thousands of connections ( 1 ) and ( 2 ) and some free code which you could use to get you started ( 3 ) The second part of your question, from your comments, is more tricky. If the client's IP address keeps changing and there's nothing between you and them that is providing NAT to give you a consistent IP address then their connections will, no doubt, be terminated and need to be re-established. If the clients detect this connection tear down when their IP address changes then they can reconnect to the server, if they can't then I would suggest that the clients need to poll the server every so often so that they can detect the connection loss and reconnect. There's nothing the server can do here as it can't predict the new IP address and it will discover that the old connection has failed when it tries to send data. And remember, your problems are only just beginning once you get your system to scale to this level...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2831434', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340851/']}
jdg_370414
stackexchange
llm_judgeable_groundtruth_similarity
44585909
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 currently digging into Hyperledger Fabric and I can't get stuff started with the Java SDK (talking about 1.0.0-beta here). Is there a working example starting from connecting to the Fabric node, doing queries, etc? All I found so far through extensive googling are "let's-write-some-chaincode" examples. Now provide the response and nothing else.
You can take a look at the following - Java SDK for Hyperledger Fabric 2.2 . In this, there are two files given in the folder "fabric-sdk-java/src/test/java/org/hyperledger/fabric/sdkintegration/" ==> End2endAndBackAgainIT.java, End2endIT.java. This can help. For a demonstration, refer to Youtube channel video: End to end Demo For a fabric network which has everything (network & crypto) setup for the E2E demo: E2E Cli Setup Update on 2020-June-07 The link above Java SDK for Hyperledger Fabric 2.2 , is a low level SDK for interacting with Hyperledger Fabric. If your purpose is building Hyperledger Fabric blockchain client applications, then its recommended to use the Hyperledger Fabric Gateway SDK for Java , a high level API. Its very simple to use, just refer to the code snippet from [2.2]. please refer to the link how to use // code snippet from [2.2]class Sample { public static void main(String[] args) throws IOException { // Load an existing wallet holding identities used to access the network. Path walletDirectory = Paths.get("wallet"); Wallet wallet = Wallets.newFileSystemWallet(walletDirectory); // Path to a common connection profile describing the network. Path networkConfigFile = Paths.get("connection.json"); // Configure the gateway connection used to access the network. Gateway.Builder builder = Gateway.createBuilder() .identity(wallet, "user1").networkConfig(networkConfigFile); // Create a gateway connection try (Gateway gateway = builder.connect()){ // Obtain a smart contract deployed on the network. Network network = gateway.getNetwork("mychannel"); Contract contract = network.getContract("fabcar"); // Submit transactions that store state to the ledger. byte[] createCarResult = contract.createTransaction("createCar").submit("CAR10", "VW", "Polo", "Grey","Mary"); System.out.println(new String(createCarResult, StandardCharsets.UTF_8)); // Evaluate transactions that query state from the ledger. byte[] queryAllCarsResult = contract.evaluateTransaction("queryAllCars"); System.out.println(new String(queryAllCarsResult, StandardCharsets.UTF_8)); } catch (ContractException | TimeoutException | InterruptedException e) { e.printStackTrace(); } } } API documentation for both 1.4 and 2.2 are available.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44585909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3996393/']}
jdg_370415
stackexchange
llm_judgeable_groundtruth_similarity
1670092
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 $(G,\circ)$ be a group and let $Z(G):=\{x \in G : ax=xa \ \forall \ a \in G\}$ be the center of $G$ . How can I show that $Z(G)$ is an abelian subgroup of $G$ ? What I did so far: $Z(G)$ is a subgroup if $$a,b \ \in Z(G) \implies a\circ b^{-1} \in Z(G)$$ But I don't know/understand how I can show this. And still there is missing the commutativity.Maybe someone can help me out with this! Now provide the response and nothing else.
Let $a,b \in Z(G)$, to prove $ab^{-1}\in Z(G)$, we have to prove that $$ (ab^{-1})c = c(ab^{-1}), \qquad \text{all }c \in G$$So let $c \in G$, we have\begin{align*} ab^{-1}c &= a(c^{-1}b)^{-1}\\ &= a(bc^{-1})^{-1} & \text{as $b \in Z(G)$}\\ &= acb^{-1}\\ &= cab^{-1} & \text{as $a \in Z(G)$} \end{align*}For the "abelian" part, see @lhf's answer.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1670092', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/295829/']}
jdg_370416
stackexchange
llm_judgeable_groundtruth_similarity
24335
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Can some one please explain me what is the difference between one class SVM and SVDD(support vector data description) Now provide the response and nothing else.
Support vector data description (SVDD) finds the smallest hypersphere that contains all samples, except for some outliers. One-class SVM (OC-SVM) separates the inliers from the outliers by finding a hyperplane of maximal distance from the origin. If the kernel function has the property that $k(\mathbf{x}, \mathbf{x}) = 1 \quad \forall \mathbf{x} \in \mathbb{R}^d$ , SVDD and OC-SVM learn identical decision functions. Many common kernels have this property, such as RBF, Laplacian and $\chi^2$ . SVDD and OC-SVM are also equivalent in the case that all samples lie on a hypersphere centered at the origin, and are are linearly separable from it. See Lampert, C. H. (2009). Kernel methods in computer vision (Chapter 5) for more detailed descriptions of these models.
{}
{'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/24335', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/41297/']}
jdg_370417
stackexchange
llm_judgeable_groundtruth_similarity
10177870
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have a large Silverlight, WCF RIA based solution that builds just fine with VS2010 on my desktop. However, on the TFS server we are seeing the following: ViewModels\MyVM.cs (47): The type 'TestService.Web.SystemAccount' exists in both'd:\Builds\1\MyProduct\Binaries\Silverlight\TestService.dll' and 'd:\Builds\1\MyProduct\Binaries\Silverlight\CommonService.dll' .. and ... Generated_Code\TestService.Web.g.cs (37476): The type 'TestService.Web.GroupToRule' in'd:\Builds\1\MyProduct\Sources\Source\UI\TestService\Generated_Code\TestService.Web.g.cs' conflicts with the imported type 'CommonService.GroupToRule' in 'd:\Builds\1\MyProduct\Binaries\silverlight\CommonService.dll'. Using the type defined in 'd:\Builds\1\MyProduct\Sources\Source\UI\CommonService\Generated_Code\CommonService.Web.g.cs'. All was happy until a developer checked over the weekend (a very large check in unfortunately). We have looked at what changed in the changeset but haven't spotted anything. We are using an approach similar to the one mentioned in this question and here , whereby we have a prebuild solution to avoid the circular references RIA code generation process can introduce. Our suspicion is that the build order has been altered and are checking into this, but can anyone suggest some diagnostic steps or a solution for this? Now provide the response and nothing else.
Element.children() returns an Elements object - a list of Element objects. Looking at the parent class, Node , you'll see methods to give you access to arbitrary nodes, not just Elements, such as Node.childNodes() . public static void main(String[] args) throws IOException { String str = "<div>" + " Some text <b>with tags</b> might go here." + " <p>Also there are paragraphs</p>" + " More text can go without paragraphs<br/>" + "</div>"; Document doc = Jsoup.parse(str); Element div = doc.select("div").first(); int i = 0; for (Node node : div.childNodes()) { i++; System.out.println(String.format("%d %s %s", i, node.getClass().getSimpleName(), node.toString())); }} Result: 1 TextNode Some text 2 Element <b>with tags</b>3 TextNode might go here. 4 Element <p>Also there are paragraphs</p>5 TextNode More text can go without paragraphs6 Element <br/>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10177870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134294/']}
jdg_370418
stackexchange
llm_judgeable_groundtruth_similarity
1801106
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I show this? $$ \int_{-\infty}^{\infty} x^2 \frac{e^x}{(e^x+1)^2} dx = \pi^2/3$$ I tried applying residuals, but the pole is of infinite(?) order. Now provide the response and nothing else.
Here, we present an approach that uses " Feynmann's Trick " for differentiating under the integral along with Contour Integration . Let $I$ be the integral given by $$I=\int_{-\infty}^\infty \frac{x^2e^x}{(e^x+1)^2}\,dx$$ "FEYNMANN'S TRICK" Enforcing the substitution $x\to \log(x)$ reveals $$\begin{align}I&=\int_0^\infty \frac{\log^2(x)}{(x+1)^2}\,dx\\\\&=\bbox[5px,border:2px solid #C0A000]{\left.\left(\frac{d^2}{da^2}\int_0^\infty \frac{x^a}{(x+1)^2}\,dx\right)\right|_{a=0}} \tag 1\end{align}$$ CONTOUR INTEGRATION To evaluate the integral in $(1)$, we move to the complex plane and analyze the closed-contour integral $J(a)$ given by $$\bbox[5px,border:2px solid #C0A000]{J(a)=\oint_C \frac{z^a}{(1+z)^2}\,dz} \tag 2$$ where $C$ is the classical "key-hole" contour along the branch cut extending from the origin along the non-negative real axis. Evaluation Using the Residue Theorem From the Residue Theorem , $J(a)$ is given by $$\begin{align}J(a)&=2\pi i \text{Res}\left(\frac{z^a}{(1+z)^2}, z=-1\right)\\\\&=2\pi i \left.\frac{d}{dz}\left((1+z)^2\frac{z^a}{(1+z)^2}\right)\right|{z=-1}\\\\&=\bbox[5px,border:2px solid #C0A000]{-2\pi i a e^{i\pi a}} \tag 2\end{align}$$ Decomposing $J(a)$ Next, we write $J(a)$ as $$\begin{align}J(a)&=\int_0^\infty \frac{x^a}{(1+x)^2}\,dx-\int_0^\infty \frac{x^ae^{i2\pi a}}{(1+x)^2}\,dx\\\\&=\bbox[5px,border:2px solid #C0A000]{(1-e^{i2\pi a})\int_0^\infty \frac{x^a}{(1+x)^2}\,dx} \tag 3\end{align}$$ PUTTING THINGS TOGETHER From $(2)$ and $(3)$ we see that $$\bbox[5px,border:2px solid #C0A000]{\int_0^\infty \frac{x^a}{(1+x)^2}\,dx=\frac{\pi a}{\sin(\pi a)}} \tag 4$$ FINISHING IT OFF Finally, using $(4)$ in $(1)$ reveals $$\begin{align}I&=\left.\left(\frac{d^2}{da^2}\frac{\pi a}{\sin(\pi a)}\right)\right|_{a=0}\\\\&=\lim_{a\to 0}\left(\frac{\pi^3 a(1+\cos^2(\pi a))-2\pi^2 \cos(\pi a)\sin(\pi a)}{\sin^3(\pi a)}\right)\\\\\&=\frac{\pi^2}{3}\end{align}$$ as was to be shown!
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1801106', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/190848/']}
jdg_370419
stackexchange
llm_judgeable_groundtruth_similarity
422193
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that some languages like APL have a dedicated NAND operator, but I'm thinking about languages like C, C++ , Java , Rust , Go , Swift , Kotlin , even instruction sets , etc. since these are the languages which actually implement golfing languages. As far as I know, modern processors are made up of NAND gates, since any logic gate can be implemented as a combination of NAND gates . For example, processors compose NAND gates like this to create these operators: A AND B == ( A NAND B ) NAND ( A NAND B )A OR B == ( A NAND A ) NAND ( B NAND B ) NOT A == ( A NAND A ) So, it just makes sense to me that it would be really efficient for a program to say "Hey, I have a NAND operation for you; please pass it through only one gate and store the result in a register." However, as far as I'm aware, no such operator exists in actual compiled languages. I've seen arguments saying that these languages don't contain a dedicated NAND operator since C = A NAND B can be expressed as these: C = NOT ( A AND B ) C = ( NOT A ) OR ( NOT B ) The problem I see is that, since each of these operators is implemented in the processor as a combination of NAND s, then expressing NAND as these compositions might have them be executed as this: ; C = NOT ( A AND B )X = A NAND BX = X NAND XC = X NAND X; alternatively:C = ( ( A NAND B ) NAND ( A NAND B ) ) NAND ( ( A NAND B ) NAND ( A NAND B ) ) ; C = ( NOT A ) OR ( NOT B )X = A NAND AY = B NAND BC = ( X NAND X ) NAND ( Y NAND Y ); alternatively:C = ( ( A NAND A ) NAND ( A NAND A ) ) NAND ( ( B NAND B ) NAND ( B NAND B ) ) This seems silly and inefficient to me! Just look at the first line of the implementation of C = NOT ( A AND B ) : it gives us the result right away! But we toss it back and forth a few times after that anyway to return to the result we started with. I know each of these gates is a single processor instruction, but wouldn't that instruction be so much more efficient if it only passed through one gate rather than several? I assume and pray that some compiler or something is smart enough to optimize this (after all, I see NAND in some IBM instruction sets ), but I haven't heard of higher-level languages having an operator that explicitly invokes it. My question is why not just let the dev specify "Here is a NAND operation; just do that"? -- Related: Why is there no nand instruction in modern CPUs? (about the circuits within a CPU, not languages) Why do higher level languages have neither xor nor nand short-circuit operators? (about missing operators in general, not this specific one. Also about short-circuiting) Now provide the response and nothing else.
There are so many levels in between the source code of some program and the circuits on a chip. While some microarchitecture details definitely have a high-level performance impact, the ability to specify a NAND operation wouldn't be one of them. High-level programs have little connection to circuits on a chip First, our program must be converted to machine code. This might happen through an ahead of time compiler, or a JIT compiler immediately before execution, or the program might be interpreted without compilation. All of these approaches already introduce substantial overhead that goes beyond what would be saved by a simpler circuit. When the CPU executes machine code, the machine code is handled in a pipeline. Instructions in this pipeline are decoded and partially executed ahead of time. Actually, the machine code instructions are usually decoded into microcode, a CPU-internal instruction set. And then finally the microcode is dispatched on specialized hardware circuits. This decoding is controlled largely by firmware, i.e. the CPU performs a hardware-assisted just-in-time re-compilation.The point is that every instruction is touched by millions of transistors before it is actually executed. Per the instruction set specification, the CPU has a certain number of cycles to execute a machine code operation. This number depends on the complexity of the operation. On this scale, an AND and NAND operation would likely take the same number of cycles. However, adding a NAND instruction could still be worth it e.g. if this would save power or lead to more compact programs. But those are fairly big assumptions that have to be balanced with the complexity of the instruction set. Every instruction complicates the decoding pipeline. Adding very small instructions is not generally worth it. Of course, the decoding pipeline might recognize a pattern like and a, b; not a and issue a NAND microcode instruction in its place. But again: this wouldn't likely save any cycles, makes the CPU more complicated, and in any case would be unobservable from the outside. I don't know if modern CPUs have such microcode, but I'd bet they have better uses for that die space than a somewhat rare operation that can be easily emulated through other logical operations.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/422193', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/104052/']}
jdg_370420
stackexchange
llm_judgeable_groundtruth_similarity
3640061
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 find all the parent elements that have the CSS style display:none . I can't seem to get it to work though. Here's what I've got: var $parents = $(...).parents("[css=display:none]"); Now provide the response and nothing else.
If you want the ones that are actually display: none; (not just possibly contained in another display: none; ), you can use .filter() and .css() to get those parents, like this: var $parents = $(...).parents().filter(function() { return $(this).css('display') == 'none'; }); This gets the parents, then filters them to get only the ones that are display: none; on that specific parent.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3640061', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438422/']}
jdg_370421
stackexchange
llm_judgeable_groundtruth_similarity
4796482
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Invalid iPhone Application Binary Im ripping my hair out over this!!! I have tried like everything and evertime i submit my app to itunes connect it allways says: Upload Received (2 minutes Later) Invalid Binary Its Driving me mad and i have already: Cleaned all builds Made a new Entitlement.plist Checked that it built with TheDistribution Profile. Now provide the response and nothing else.
check up your mailbox associated with your apple developer account, apple will send email to your mailbox with some diagnose information and how to solve your problem. for me, apple send following diagnose information. I actually have never touched iCound, which is really confusing. after all, I created a new app id without Wild-card character, then a new distribution profile, and sign my app, finally summit to apple, which turn out to be successful. Invalid Code Signing Entitlements - The signature for your app bundle contains entitlement values that are not supported. For the com.apple.developer.ubiquity-container-identifiers entitlement, the first value in the array must consist of the prefix provided by Apple in the provisioning profile followed by a bundle identifier suffix. The bundle identifier must match the bundle identifier for one of your apps or another app that you are permitted to use as the iCloud container identifier. Specifically, value "K8FN29QYP2.*" for key "com.apple.developer.ubiquity-container-identifiers" in ProductName is not supported. Invalid Code Signing Entitlements - The signature for your app bundle contains entitlement values that are not supported. Specifically, value "K8FN29QYP2.*" for key "com.apple.developer.ubiquity-kvstore-identifier" in ProductName is not supported.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4796482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587864/']}
jdg_370422
stackexchange
llm_judgeable_groundtruth_similarity
27534284
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 180,000 x 400 dataframe where the rows correspond to users but every user has exactly two rows. id date ...1 2012 ...3 2010 ...2 2013 ...2 2014 ...1 2011 ...3 2014 ... I want to subset the data so that only the most recent row for each user is retained (i.e. the row with the highest value for date for each id). I first tried using which() looping ids with an ifelse() statement in sapply() which was painfully slow ( O(n^2) I believe). Then I tried sorting the df by id and then looping through in increments of two and comparing adjacent dates but this was also slow (I guess because loops in R are hopeless). The comparison of the two dates is the bottleneck as the sort was pretty much instant. Is there a way to vectorize the comparison? SOLUTION from Remove duplicates keeping entry with largest absolute value aa <- df[order(df$id, -df$date), ] #sort by id and reverse of dateaa[!duplicated(aa$id),] Runs very quickly!! Now provide the response and nothing else.
Here's a simple and fast approach using data.table package library(data.table)setDT(df)[, .SD[which.max(date)], id]# id date# 1: 1 2012# 2: 3 2014# 3: 2 2014 Or (could be a bit faster because of keyed by setkey(setDT(df), id)[, .SD[which.max(date)], id] Or using OPs idea via the data.table package unique(setorder(setDT(df), id, -date), by = "id") Or setorder(setDT(df), id, -date)[!duplicated(id)] Or base R solution with(df, tapply(date, id, function(x) x[which.max(x)]))## 1 2 3 ## 2012 2014 2014 Another way library(dplyr)df %>% group_by(id) %>% filter(date == max(date)) # Will keep all existing columns but allow multiple rows in case of ties# Source: local data table [3 x 2]# Groups: id# # id date# 1 1 2012# 2 2 2014# 3 3 2014 Or df %>% group_by(id) %>% slice(which.max(date)) # Will keep all columns but won't return multiple rows in case of ties Or df %>% group_by(id) %>% summarise(max(date)) # Will remove all other columns and wont return multiple rows in case of ties
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27534284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4346952/']}
jdg_370423
stackexchange
llm_judgeable_groundtruth_similarity
11727
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: DuckDuckGo is a search engine that has a Tor Exit Enclave and hidden service . This site is focused on the safe, secure searching of its users. Since DNS is not used in Tor, it appears that HTTPS is less secure due to its reliance on DNS Considering that the Tor Hidden Service protocol encrypts traffic end-to-end, does that remove any threats that exist when compared to a HTTPS session? Is MITM risk reduced? Is name resolution more secure than DNS? (protection from spoofers) Are there additional risks? Please provide additional details and information. For example, how does Tor HSP compare to HTTPS + IPSEC + DNSSec (or the lack of the latter two)? Now provide the response and nothing else.
makerofthings7 wrote: it seems TOR is better/more secure since it doesn't use DNS, and it doesn't rely on CAs Just as it's ultimately the user's responsibility to verify a TLS certificate before accepting it, it's the user's responsibility to verify that an onion address is the intended address. By starting with (a) I know an onion address (b) I know a regular domain name (f.ex. "google.com") you are stating, by hypothesis: (a) I have solved a tricky problem (b) I have yet to solve a tricky problem and (a) directly implies more security than (b) because of the stronger hypothesis. But stating (a) actually means " I know how to solve tricky problems " so you should be able to also solve (b). IOW, if you can reliably obtain an onion address (f.ex. over the phone from someone whose voice you know), you should be able to reliably obtain a TLS certificate fingerprint of the website by the same provider. But you are probably relying on some Internet resource (website, Usenet message, email...) to learn the onion address: (1) do you trust the claimed author of the message? (2) do you trust that the message was really written by this author? Maybe the message was found on an HTTPS website, and you are back with: (a) verifying that the owner of the website is the person you trust (b) the website you see is the real website, IOW that the TLS certificate is valid. Maybe the message was found in an email, and you have to check the PGP/GPG (or S/MIME) signature. Then you are back with: who owns this PGP/GPG/S/MIME signature? In any case, you need a trust anchor . No cryptographic protocol or tool alone solves this problem, because it isn't an algorithmic matter, it's a matter of fact checking , facts like " this key really belongs to this person ", and in most cases trusting others to do the fact checking , unless you can meet the guy in person and ask him his key fingerprint, which honestly is rarely the case (I tried with my bank and they had no idea what the fingerprint of the key was).
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/11727', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/396/']}
jdg_370424
stackexchange
llm_judgeable_groundtruth_similarity
29790070
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 just upgraded my app to use the newly released v22.1.0 AppCompat and I'm now getting the following exception when I open my app. Caused by: java.lang.IllegalArgumentException: AppCompat does not support the current theme features at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:360) at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:246) at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:106) How do I fix it? Now provide the response and nothing else.
AppCompat is now more strict on what it expect in theme window flags, more closely matching what you would get from the framework. The main reason behind this is to support AppCompatDialogs which we were also adding in this release. They make heavy use of the windowNoTitle flag, which AppCompat previously didn't pay much attention to. So to fix your issue you have two options: The easy way is to just use Theme.AppCompat.NoActionBar as your parent theme. This will always do the right thing. If you can't do that though (maybe you need to support action bar and no action bar), you should do the following: <style name="MyTheme" parent="Theme.AppCompat"> ...</style><style name="MyTheme.NoActionBar"> <!-- Both of these are needed --> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item></style> You should be back on track now.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/29790070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474997/']}
jdg_370425
stackexchange
llm_judgeable_groundtruth_similarity
155795
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm reading through Abstract Algebra by Hungerford and he makes the remark that the intersection of all subfields of the real numbers is the rational numbers. Despite considerable deliberation, I'm unsure of the steps to take to show that the subfield is $\mathbb Q$. Any insight? Now provide the response and nothing else.
First note that $\mathbb Q$ is itself a subfield of $\mathbb R$, so the intersection of all subfields must be a subset of the rationals. Second note that $\mathbb Q$ is a prime field, that is, it has no proper subfields. This is true because if $F\subseteq\mathbb Q$ is a field then $1\in F$, deduce that $\mathbb N\subseteq F$, from this deduce that $\mathbb Z\subseteq F$ and then the conclusion. Third, conclude the equality.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/155795', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33288/']}
jdg_370426
stackexchange
llm_judgeable_groundtruth_similarity
41204576
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 in shell the exclamation mark can invert the outcome of condition. Here I wanna use it to test variable is true or false . #! /bin/bashbat=falseif [ ! $bar ]; then echo 'bar is false'else echo 'bar is true'fi I was expecting 'bar is false'. However it turned out the other way. Then I use "$bar" == "false". It is right. So what is the tips for using exclamation mark. Would it only invert outcome when we test about file ? Now provide the response and nothing else.
tl;dr [ ! $bar ] treats $bar as a string , and any nonempty string is considered "true" - including literal false ; in other words: [ ! 'true' ] && [ ! 'false' ] both evaluate to "false", because the operands are nonempty strings in both cases and ! negates the outcome. Therefore, you must use string comparison: bar=falseif [ ! "$bar" = 'true' ]; then # same as: [ "$bar" != 'true' ] echo 'bar is false'else echo 'bar is true'fi In Bash, you can also use [[ ! $bar == 'true' ]] or [[ $bar != 'true' ]] ; unless you need to remain POSIX-compliant, I suggest using [[ ... ]] . In the context of [ ... ] and [[ ... ]] (Bash-specific), variable values are strings by default , and, generally, POSIX-like shells have no explicit Boolean data type . Unary operator ! interprets its operand implicitly as a Boolean, and a string in a Boolean context is interpreted as follows: only an empty string is considered "false" (exit code 1 (!)) any nonempty string - including literal false - is considered "true" (exit code 0 (!)) Thus, ! $bar evaluates to "false", because $bar - containing nonempty string 'false' - evaluates to "true", and ! inverts that. ! can also be used outside of conditionals to directly negate the success status of commands (including [ ). Since false and true also exist as command names (typically, as shell builtins), you could do the following, but do note that it only works as intended with variable values that are either the literals false or true : bar=falseif ! "$bar"; then echo 'bar is false'else echo 'bar is true'fi Background information POSIX-like shells only have 2 basic (scalar) data types: strings (by default): In [ ... ] and [[ ... ]] conditionals, operators = ( == in Bash) , < , <= , > , >=` perform string comparison. integers: In [ ... ] and [[ ... ]] conditionals, distinct arithmetic operators ( -eq , lt , le , gt , ge ) must be used to perform numerical comparison Alternatively, in an arithmetic expansion ( $(( ... )) ), == , < , <= , > , >= have their usual, numeric meaning. In Bash, you can also use (( ... )) as an arithmetic conditional . Note: Per POSIX, you cannot type a variable as an integer (because there is no way to declare a shell variable), so it is only implicitly treated as one in comparisons using arithmetic operators / in arithmetic contexts. In Bash, however, you can declare integer variables with declare -i / local -i , but in conditionals / arithmetic contexts it is still the choice of operator / arithmetic context that determines whether the value is treated as a string or as an integer. Booleans in shells are expressed implicitly as exit codes , in a reversal of the usual Boolean-to-integer mapping: "true" maps to exit code 0 (!) "false" is expressed as exit code 1 (!) or any other nonzero exit code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41204576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3529352/']}
jdg_370427
stackexchange
llm_judgeable_groundtruth_similarity
1713988
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose that $a,b\in\mathbb R$ with $a<b$ and that $f:(a,b)\to\mathbb R$ is continuous and bijective. I would like to prove that $f$ is a homeomorphism using elementary methods (no resort to invariance of domain, for instance). To my surprise, I have not found a straightforward, standard (textbook) reference for this result. If you know any or you have a clever hint in mind, I would be grateful if you could share it. Now provide the response and nothing else.
It is easy to prove by the intermediate value theorem that any continuous injection from an interval to $\mathbb{R}$ must be monotone (for instance, if $c<d<e$ and $f(c)<f(e)<f(d)$ then $f(e')=f(e)$ for some $e'\in (c,d)$; other failures of monotonicity can be handled similarly). Thus $f$ is either an order-preserving bijection or an order-reversing bijection $(a,b)\to\mathbb{R}$, which maps open intervals to open intervals and is hence a homeomorphism.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1713988', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87778/']}
jdg_370428
stackexchange
llm_judgeable_groundtruth_similarity
344830
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: For every $k\ge1$ integer number if we define the sequence : $a_1,a_2,a_3,...,$ in the form of :$$a_1=2$$ $$a_{n+1}=ka_n+\sqrt{(k^2-1)(a^2_n-4)}$$ For every $n=1,2,3,....$ how to prove that $a_n$ is an integer for every $n$ Now provide the response and nothing else.
$a_{n+1}=ka_n+\sqrt{(k^2-1)(a^2_n-4)}\Rightarrow a_{n+1}-ka_n=\sqrt{(k^2-1)(a^2_n-4)}$ Squaring both sides we have, $a_{n+1}^2+k^2a_n^2-2ka_{n+1}a_n=k^2a_n^2-4k^2-a_n^2+4$ $\Rightarrow a_{n+1}^2+k^2a_n^2-2ka_{n+1}a_n-k^2a_n^2+4k^2+a_n^2-4=0 $ $\Rightarrow a_{n+1}^2-2ka_{n+1}a_n+4k^2+a_n^2-4=0 \dots (1)$ Replacing $n+1$ by n we have similarly, $\Rightarrow a_{n}^2-2ka_{n}a_{n-1}+4k^2+a_{n-1}^2-4=0 \dots (2)$ By $(1)-(2)$ we have, $a_{n+1}^2-a_{n-1}^2-2ka_{n}(a_{n+1}-a_{n-1})=0$ $(a_{n+1}-a_{n-1})(a_{n+1}+a_{n-1}-2ka_n)=0$ $\Rightarrow$ either $a_{n+1}=a_{n-1}$ or $a_{n+1}=2ka_n-a_{n-1}$ Now we use induction, Hypothesis: $\{a_{k}\}_{k=1}^{n}$ are all integers. As $a_{n+1}=a_{n-1}$ or $a_{n+1}=2ka_n-a_{n-1}$ so $a_{n+1} $ is also integer.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/344830', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/69901/']}
jdg_370429
stackexchange
llm_judgeable_groundtruth_similarity
3727202
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: Consider a sequence of terms of powers of $m\in\mathbb{R}$ as $$M_n = m^0, m^1, m^2, m^3, \ldots, m^n$$ and create a set that contains all the values of the various signed combinations of these terms. For example, for $M_2 = m^0,m^1,m^2$ we would have our set $S$ containing the values $$|m^0 + m + m^2|$$ $$|m^0 - m + m^2|$$ $$|m^0 + m - m^2|$$ $$|m^0 - m - m^2|$$ Notice that we always keep $m^0$ positive. Now, in the special case of $m=2$ it turns out that our set $S$ will always comprise of the first $2^n$ odd numbers. This means that our example with $M_2$ $$S = \{1,3,5,7\}$$ This is very nice because we can create a nice, indexed closed form of our set using the formula $$S = \{2k-1 | 1\leq k \leq n\}$$ which then makes summations incredibly easy. My question is, does there exist such a closed form expression that iterates over all values of a set $S$ , given any $m$ and any $n$ ? Now provide the response and nothing else.
Many years ago, I found a rather simple method of convergence acceleration of alternating series. I wondered: what if a series $a_k$ is not alternating, can I transform it, i.e. find a series $b_k$ so that $$\sum^\infty_{k=1}a_k=\sum^\infty_{k=1}(-1)^{k-1}b_k\tag{1}?$$ If the RHS is absolutely convergent, we can write $$\sum^\infty_{k=1}(-1)^{k-1}b_k=\sum^\infty_{k=1}b_k-2\sum^\infty_{k=1}b_{2k}=\sum^\infty_{k=1}(b_k-2\,b_{2k}).$$ So (1) is satisfied if we choose $b_k$ so that $$a_k=b_k-2\,b_{2k}\tag{2}.$$ Replacing in (2) $k$ by $k\,2^n,$ multiplying by $2^n$ and summing from $n=0$ to $\infty,$ we find $$b_k=\sum^\infty_{n=0}2^n\,a_{k\,2^n}\tag{3},$$ provided $\displaystyle\lim_{n\to\infty}2^n\,b_{k\,2^n}=0.$ Now let $$a_k=\frac1{k(k+1)},$$ i.e. $$b_k=\sum^\infty_{n=0}2^n\frac1{k\,2^n(k\,2^n+1)}=\frac1k\sum^\infty_{n=0}\frac1{k\,2^n+1}.$$ Then, (1) becomes $$\sum^\infty_{k=1}\frac1{k(k+1)}=\sum^\infty_{k=1}(-1)^{k-1}\frac1k\sum^\infty_{n=0}\frac1{k\,2^n+1},$$ and the LHS is $$\sum^\infty_{k=1}\left(\frac1k-\frac1{k+1}\right)=1.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3727202', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/426335/']}
jdg_370430
stackexchange
llm_judgeable_groundtruth_similarity
1000025
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: Well the question is the title. I tried to grab at some straws and computed the Minkowski bound. I found 19,01... It gives me 8 primes to look at. I get $2R = (2, 1 + \sqrt{223})^2 = P_{2}^{2}$ $3R = (3, 1 + \sqrt{223})(3, 1 - \sqrt{223}) = P_{3}Q_{3}$ $11R = (11, 5 + \sqrt{223})(11, 5 - \sqrt{223}) = P_{11}Q_{11}$ $17R = (17, 6 + \sqrt{223})(17, 6 - \sqrt{223}) = P_{17}Q_{17}$ where I denote $R$ the ring of integers $\mathbb{Z}[\sqrt{223}]$. Others are prime. EDIT : Ok, so I tried to find some answers on various pdf. Unfortunately, it's always at best half cryptic. That is what I understood I can do. I computed the norm for a general element of $\mathbb{Z}[\sqrt{223}]$ : $N(a + b\sqrt{223}) = a^{2} - 223b^{2}$. I checked which norms were available among $\pm 2, \pm 3, \pm 11, \pm 17$. Only 2 is (with $a = 15$ and $b = 1$). This tells me that $P_{2}$ is principal and the other six are not. And I'm stuck here. And please, don't tell me to think about some hint. I already have, I can't think of anything. I just need one example to understand the method and so helping me understand the theory behind. $\text{EDIT}^2$ : I think I made a mistake with the Minkowski's bound. For remainder, it is $M_{K} = \frac{n!}{n^{n}}\left(\frac{4}{\pi}\right)^{r_{2}}\sqrt{|\text{disc}(K)|}$. I took $r_{2} = 1$, which is wrong, it should be $r_{2} = 0$ (I think), thus giving $M_{K} = 14, \dots$. We don't need to consider $(17)$ and $(19)$. Now provide the response and nothing else.
Cam would know this better, but let me give a few pointers for pencil & paper calculations. IIRC calculations like this use heavily the following rules. In what follows $(a_1,a_2,\ldots,a_n)$ is the ideal generated by the listed elements. We have the rules $(a_1,a_2,\ldots,a_n)=(a_1,a_2,\ldots,a_{n-1},a_n-ra_1)$ for all $r\in R$. In other words we can subtract from one generator a multiple of another. The validity of this rule is hopefully clear (the process is reversible). This allows to replace an uncomfortably large generator with a smaller one. Also, if $a_n$ happens to be a multiple of $a_1$, the remainder is zero, and we can drop that altogether, as zero won't generate much. The product of the ideals follows the rule:$$(a_1,a_2,\ldots,a_n)\cdot(b_1,b_2,\ldots, b_m)=(a_ib_j|1\le i\le n, 1\le j\le m).$$ Because the operation in the ideal class group is the product of representatives you will be doing this a lot. You calculated that the ideal classes are among the listed six (and the class of principal ideals). The goal of proving that the class group is of order three is a powerful hint. Among other things it implies that the ideals $P_3^3$ and $Q_3^3$ should both be principal. These are both of index $3^3=27$ in $R$, so a search for principal ideals of norm $27$ is natural. We don't need to look further than$$223-27=196=14^2 \implies (27)=(14-\sqrt{223})(14+\sqrt{223}).$$Because $(27)=P_3^3Q_3^3$ this actually already implies the claim that $P_3^3$ and $Q_3^3$ are the principal ideals $J_1=(14+\sqrt{223})$ and $J_2=(14-\sqrt{223})$. This is because we easily see that $J_1+J_2$ contains both $27$ and $28$, hence also $1$, so the ideals $J_1$ and $J_2$ are coprime. As $P_3$ and $Q_3$ are the only primes lying above $3$, we must have $P_3^3=J_1$ and $Q_3^3=J_2$ or the other way round. To gain a bit more experience and to decide which is which let us calculate using theabove rules. I will abbreviate $u=\sqrt{223}$ to spare some keystrokes :-)$$\begin{aligned}P_3^2&=(3,1+u)(3,1+u)=(9,3+3u,3+3u,(1+u)^2)=(9,3+3u,224+2u)\\&=(9,3+3u,224+2u-9\cdot25)=(9,3+3u,-1+2u)\\&=(9,(3+3u)+3(-1+2u),-1+2u)=(9,9u,-1+2u)\\&=(9,-1+2u).\end{aligned}$$Therefore$$\begin{aligned}P_3^3&=(9,-1+2u)(3,1+u)=(27,-3+6u,9+9u,(-1+2u)(1+u)=445+u)\\&=(27,-3+6u,9+9u,445+u-16\cdot27=13+u)\\&=(27,-3+6u,9+9u+3(-3+6u),13+u)=(27,-3+6u,27u,13+u)\\&=(27,-3+6u,13+u)\\&=(27-2(13+u),-3+6u,13+u)=(1-2u,-3(1-2u),13+u)\\&=(1-2u,13+u)=(1-2u,14-u).\end{aligned}$$Here $1-2u$ has norm $-891=-33\cdot27$. The expectation is now that $P_3^3=(14-u)=J_2$, so we know what to try!$$\begin{aligned}\frac{1-2u}{14-u}&=\frac{(1-2u)(14+u)}{14^2-u^2}=-\frac{14-2u^2+27u}{27}\\&=-\frac{14-2\cdot223+27u}{27}=-\frac{-16\cdot27+27u}{27}=16-u.\end{aligned}$$Therefore $P_3^3=(1-2u,14-u)=(14-u)$. As $P_3$ itself is not principal we have now shown that it is of order three in the class group. Also, $Q_3$ has to be a representative of the inverse class, as $P_3Q_3$ is principal. What about the remaining four ideals? The goal is surely to prove that the ideals $P_{11},Q_{11},P_{17},Q_{17}$ are all in the same class as either $P_3$ or $Q_3$ for otherwise the class group would be larger. Can we find principal ideals of norm $3\cdot11=33$? Sure!$$33=256-223=16^2-223=(16-u)(16+u).$$Thus we have high hopes that either $P_3P_{11}$ or $Q_3P_{11}$ would be one of $(16-u)$ or $(16+u)$ (the other being the product of $Q_{11}$ and one of the norm three prime ideals). Let's try!$$\begin{aligned}P_3P_{11}&=(3,1+u)(11,5+u)=(33,11+11u,15+3u,228+6u)\\&=(33,11+11u,15+3u,-3+6u)\\&=(33,11+11u,15+3u+5(-3+6u),-3+6u)=(33,11+11u,33u,-3+6u)\\&=(33,11+11u,-3+6u)=(33,17-u,-3+6u)\\&=(-1+2u,17-u,3(-1+2u))=(-1+2u,17-u)\\&=(-1+2u,16+u).\end{aligned}$$A calculation similar to the preceding one shows that $-1+2u$ is a multiple of $16+u$,so $P_3P_{11}=(16+u)$. I got lucky! It might have just as well happened that $P_3Q_{11}$ is the principal one! Anyway, this shows that the classes of $P_3$ and $P_{11}$ are inverses to each other in the class group. Leaving the norm 17 ideals for you with the hint (sorry!) that$$29^2=2^2\cdot223-51.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1000025', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/179929/']}
jdg_370431
stackexchange
llm_judgeable_groundtruth_similarity
4148352
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: "Rings are groups" I've read in many places that "rings are groups", for example: on this site, on the accepted answer for this querstion and on Wikipedia (second paragraph): Formally, a ring is an abelian group whose operation is called addition, with a second binary operation called multiplication that is… I've also read that a group is a set of elements and a ( one ) binary operator over that set, for example on Wikipedia (first paragraph): "Groups are one binary operator over a set" In mathematics, a group is a set equipped with an operation that… And again in the same article, in the more detailed section #Definition : A group is a set $G$ together with a binary operation on $G$ , here denoted " $\cdot$ ", that… Inconsistency Obviously these are inconsistent because a group is supposed to have one operator based on these definitions above. I need more consistent definitions for "ring" and "group". Thank you in advance. The following un-official definitions provide a more consistent alternative, but the problem with them is that I made them up. I need generally-accepted consistent definitions. group : a set of elements and at least one binary operator(s) over that set ring : a group with exactly two operators: addition and multiplication Please tell me if I'm missing something. I feel like I am. Now provide the response and nothing else.
If you want to do things very formally, then a group $G$ is a pair $G=(G_\text{set},\star)$ , where $G_\text{set}$ is a set and $\star\colon G_\text{set}\times G_\text{set}\to G_\text{set}$ is an operation such that certain axioms are satisfied. Similarly, a ring $R$ is a triple $R=(R_\text{set},+,\times)$ where $R_\text{set}$ is a set, both $+$ and $\times$ are operations on $R_\text{set}$ and certain axioms are satisfied. One of these axioms is that the pair $(R_\text{set},+)$ is an abelian group. However, mathematicians are lazy and language needs to be efficient, so usually we will see a group $G=(G_\text{set},\star)$ being treated as a set itself and we write statements like $g\in G$ when formally it should be $g\in G_\text{set}$ . But everybody knows which set is meant, so we drop the distinction between $G_\text{set}$ and $G$ . In this way, a group $G$ is a set with some additional structure (the operation $\star$ ). Similarly, when $R=(R_\text{set},+,\times)$ is a ring, you always have the group $(R_\text{set},+)$ and we may say that a ring is a group with some additional structure (the operation $\times$ ). Now the symbol $R$ is used to denote all three: the underlying set, the abelian group and the ring.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4148352', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/930825/']}
jdg_370432
stackexchange
llm_judgeable_groundtruth_similarity
2496956
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 large application that currently exists as a hybrid of WebForms and MVC 2.0. Startup of my application is dreadful, and the culprit is primarily because of the AreaRegistration.RegisterAllAreas call. More specifically, that it is using the System.Web. Compilation.BuildManager.GetReferencedAssemblies to enumerate all types in assemblies directly referenced by the application and test them to see if they derive from AreaRegistration . Unfortunately, I have a number of third-party assemblies that happen to be quite extensive, so this initial load can be pretty bad. I'd have much better results if I could tell it which assemblies to look for AreaRegistrations , or even register areas manually for the time being. I can gather up all the internals of AreaRegistration to create and invoke the registration, but I'm just curious if others have had and worked around this issue. Now provide the response and nothing else.
I put together the following utility to isolate Assemblies for registering Areas. I had to hack out the internals of area registration, but they don't seem terribly complicated and this has been running reasonably well for me: using System;using System.Linq;using System.Reflection;using System.Web.Mvc;using System.Web.Routing;namespace MyCompany.Web.Mvc{ /// <summary> /// Provides helpful utilities for performing area registration, where <see cref="AreaRegistration.RegisterAllAreas()"/> may not suffice. /// </summary> public static class AreaRegistrationUtil { /// <summary> /// Registers all areas found in the assembly containing the given type. /// </summary> /// <typeparam name="T">A type that derives from <see cref="AreaRegistration"/> and has a default constructor.</typeparam> public static void RegisterAreasForAssemblyOf<T>() where T : AreaRegistration, new() { RegisterAreasForAssemblyOf<T>(null); } /// <summary> /// Registers all areas found in the assembly containing the given type. /// </summary> /// <typeparam name="T">A type that derives from <see cref="AreaRegistration"/> and has a default constructor.</typeparam> /// <param name="state">An object containing state that will be passed to the area registration.</param> public static void RegisterAreasForAssemblyOf<T>(object state) where T : AreaRegistration, new() { RegisterAreasForAssemblies(state, typeof (T).Assembly); } /// <summary> /// Registers all areas found in the given assemblies. /// </summary> /// <param name="assemblies"><see cref="Assembly"/> objects containing the prospective area registrations.</param> public static void RegisterAreasForAssemblies(params Assembly[] assemblies) { RegisterAreasForAssemblies(null, assemblies); } /// <summary> /// Registers all areas found in the given assemblies. /// </summary> /// <param name="state">An object containing state that will be passed to the area registration.</param> /// <param name="assemblies"><see cref="Assembly"/> objects containing the prospective area registrations.</param> public static void RegisterAreasForAssemblies(object state, params Assembly[] assemblies) { foreach (Type type in from assembly in assemblies from type in assembly.GetTypes() where IsAreaRegistrationType(type) select type) { RegisterArea((AreaRegistration) Activator.CreateInstance(type), state); } } /// <summary> /// Performs area registration using the specified type. /// </summary> /// <typeparam name="T">A type that derives from <see cref="AreaRegistration"/> and has a default constructor.</typeparam> public static void RegisterArea<T>() where T : AreaRegistration, new() { RegisterArea<T>(null); } /// <summary> /// Performs area registration using the specified type. /// </summary> /// <typeparam name="T">A type that derives from <see cref="AreaRegistration"/> and has a default constructor.</typeparam> /// <param name="state">An object containing state that will be passed to the area registration.</param> public static void RegisterArea<T>(object state) where T : AreaRegistration, new() { var registration = Activator.CreateInstance<T>(); RegisterArea(registration, state); } private static void RegisterArea(AreaRegistration registration, object state) { var context = new AreaRegistrationContext(registration.AreaName, RouteTable.Routes, state); string ns = registration.GetType().Namespace; if (ns != null) context.Namespaces.Add(string.Format("{0}.*", ns)); registration.RegisterArea(context); } /// <summary> /// Returns whether or not the specified type is assignable to <see cref="AreaRegistration"/>. /// </summary> /// <param name="type">A <see cref="Type"/>.</param> /// <returns>True if the specified type is assignable to <see cref="AreaRegistration"/>; otherwise, false.</returns> private static bool IsAreaRegistrationType(Type type) { return (typeof (AreaRegistration).IsAssignableFrom(type) && (type.GetConstructor(Type.EmptyTypes) != null)); } }} Easiest way to use this, for me, is AreaRegistrationUtil.RegisterAreasForAssemblyOf<SomeTypeInTargetAssembly>(); This has made noticeable improvements in start up time, at the expense of not being able to drop in an area and have the application automatically register it. However, that isn't a concern of mine in this case.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2496956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64750/']}
jdg_370433
stackexchange
llm_judgeable_groundtruth_similarity
377892
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: With zfs, if you have copies=2 and then you lose a drive containing some of those copies, how do you tell the system that it should make a new copy of the data blocks for the affected files? Or does zfs just start adding data blocks for the extra copies as soon as it finds out about bad data blocks? Will scrub do this? (v0.6.0.56-rc8, ZFS pool version 28, ZFS filesystem version 5, Ubuntu 11.10) Now provide the response and nothing else.
"copies=2" (or 3) is more designed to be used with pools with no redundancy (single disk or stripes). The goal is to be able to recover minor disk corruption, not a whole device failure. In the latter case, the pool is unmountable so no ditto blocks restoration can occur. If you have redundancy (mirroring/raidz/raidz2/raidz3), the ditto blocks are not different than other ones and scrubbing/resilvering will recreate them.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/377892', 'https://serverfault.com', 'https://serverfault.com/users/44984/']}
jdg_370434
stackexchange
llm_judgeable_groundtruth_similarity
3289191
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: Last year, the largest Mersenne prime $2^{82,589,933}$ that we now know of was discovered. It contains almost $25,000,000$ digits if expanded out. I do not understand much how GIMPS operates, other than it makes use of the Lucas-Lehmer test algorithm. My question might be naive, but I ask it anyway: On a PC with 8GB of RAM, am I capable of running the Lucas-Lehmer test on a Mersenne number $M_{p}$ with a prime $p$ of my choice? In theory, I certainly could recursively compute the $(n-1)st$ term of the underlying extended Lucas sequence sequence that GIMPS uses and attempt to divide my chosen $M_{p}$ into it. But can little computers like mine handle such large numbers? Now provide the response and nothing else.
LLT implementation in Pari/gp p = 19937; Mp = 2^p-1; x = 4; moduloM(p,n) = { a= shift(n,-p); b = n-shift(a,p); r = b+a; }; for(n=1, p-2, x = moduloM(p,moduloM(p,x^2-2))); /* slow version : x = Mod(4,Mp); for(n=1, p-2, x = x^2-2); */ if(x == Mp, print("2^",p,"-1 is prime"), print("2^",p,"-1 is NOT PRIME"));
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3289191', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/684402/']}
jdg_370435
stackexchange
llm_judgeable_groundtruth_similarity
27827
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 often deal with messy survey data which requires a lot of cleaning up before any statistics can be done. I used to do this "manually" in Excel, sometimes using Excel formulas, and sometimes checking entries one-by-one. I started doing more and more of these tasks by writing scripts to do them in R, which has been very beneficial (benefits include having a record of what was done, less chance of mistakes, and being able to reuse code if the data set is updated). But there are still some types of data that I have trouble handling efficiently. For example: > d <- data.frame(subject = c(1,2,3,4,5,6,7,8,9,10,11),+ hours.per.day = c("1", "2 hours", "2 hr", "2hr", "3 hrs", "1-2", "15 min", "30 mins", "a few hours", "1 hr 30 min", "1 hr/week"))> d subject hours.per.day1 1 12 2 2 hours3 3 2 hr4 4 2hr5 5 3 hrs6 6 1-27 7 15 min8 8 30 mins9 9 a few hours10 10 1 hr 30 min11 11 1 hr/week hours.per.day is meant to be the average number of hours per day spent on a certain activity, but what we have is exactly what the subject wrote. Suppose I make some decisions on what to do with ambiguous responses, and I want the tidied variable hours.per.day2 as follows. subject hours.per.day hours.per.day21 1 1 1.00000002 2 2 hours 2.00000003 3 2 hr 2.00000004 4 2hr 2.00000005 5 3 hrs 3.00000006 6 1-2 1.50000007 7 15 min 0.25000008 8 30 mins 0.50000009 9 a few hours 3.000000010 10 1 hr 30 min 1.500000011 11 1 hr/week 0.1428571 Assuming that the number of cases is quite large (say 1000) and knowing that the subjects were free to write anything they liked, what is the best way to approach this? Now provide the response and nothing else.
I would use gsub() to identify the strings that I know and then perhaps do the rest by hand. test <- c("15min", "15 min", "Maybe a few hours", "4hr", "4hour", "3.5hr", "3-10", "3-10")new_var <- rep(NA, length(test))my_sub <- function(regex, new_var, test){ t2 <- gsub(regex, "\\1", test) identified_vars <- which(test != t2) new_var[identified_vars] <- as.double(t2[identified_vars]) return(new_var) }new_var <- my_sub("([0-9]+)[ ]*min", new_var, test)new_var <- my_sub("([0-9]+)[ ]*(hour|hr)[s]{0,1}", new_var, test) To get work with the ones that you need to change by hand I suggest something like this: # Which have we not foundby.hand <- which(is.na(new_var))# View the unique ones not foundunique(test[by.hand])# Create a list with the onesmy_interpretation <- list("3-10"= 5, "Maybe a few hours"=3)for(key_string in names(my_interpretation)){ new_var[test == key_string] <- unlist(my_interpretation[key_string])} This gives: > new_var[1] 15.0 15.0 3.0 4.0 4.0 3.5 5.0 5.0 Regex can be a little tricky, every time I'm doing anything with regex I run a few simple tests. Se ?regex for the manual. Here's some basic behavior: > # Test some regex> grep("[0-9]", "12")[1] 1> grep("[0-9]", "12a")[1] 1> grep("[0-9]$", "12a")integer(0)> grep("^[0-9]$", "12a")integer(0)> grep("^[0-9][0-9]", "12a")[1] 1> grep("^[0-9]{1,2}", "12a")[1] 1> grep("^[0-9]*", "a")[1] 1> grep("^[0-9]+", "a")integer(0)> grep("^[0-9]+", "12222a")[1] 1> grep("^(yes|no)$", "yes")[1] 1> grep("^(yes|no)$", "no")[1] 1> grep("^(yes|no)$", "(yes|no)")integer(0)> # Test some gsub, the \\1 matches default or the found text within the ()> gsub("^(yes|maybe) and no$", "\\1", "yes and no")[1] "yes"
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/27827', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/3835/']}
jdg_370436
stackexchange
llm_judgeable_groundtruth_similarity
291387
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 new to .net and c#, so I want to make sure i'm using the right tool for the job. The XML i'm receiving is a description of a directory tree on another machine, so it go many levels deep. What I need to do now is to take the XML and create a structure of objects (custom classes) and populate them with info from the XML input, like File, Folder, Tags, Property... The Tree stucture of this XML input makes it, in my mind, a prime candidate for using recursion to walk the tree. Is there a different way of doing this in .net 3.5? I've looked at XmlReaders, but they seem to be walking the tree in a linear fashion, not really what i'm looking for... The XML i'm receiving is part of a 3rd party api, so is outside my control, and may change in the futures. I've looked into Deserialization, but it's shortcomings (black box implementation, need to declare members a public, slow, only works for simple objects...) takes it out of the list as well. Thanks for your input on this. Now provide the response and nothing else.
I would use the XLINQ classes in System.Xml.Linq (this is the namespace and the assembly you will need to reference). Load the XML into and XDocument: XDocument doc = XDocument.Parse(someString); Next you can either use recursion or a pseudo-recursion loop to iterate over the child nodes. You can choose you child nodes like: //if Directory is tag name of Directory XML//Note: Root is just the root XElement of the documentvar directoryElements = doc.Root.Elements("Directory"); //you get the ideavar fileElements = doc.Root.Elements("File"); The variables directoryElements and fileElements will be IEnumerable types, which means you can use something like a foreach to loop through all of the elements. One way to build up you elements would be something like this: List<MyFileType> files = new List<MyFileType>();foreach(XElelement fileElement in fileElements){ files.Add(new MyFileType() { Prop1 = fileElement.Element("Prop1"), //assumes properties are elements Prop2 = fileElement.Element("Prop2"), });} In the example, MyFileType is a type you created to represent files. This is a bit of a brute-force attack, but it will get the job done. If you want to use XPath you will need to using System.Xml.XPath. A Note on System.Xml vs System.Xml.Linq There are a number of XML classes that have been in .Net since the 1.0 days. These live (mostly) in System.Xml. In .Net 3.5, a wonderful, new set of XML classes were released under System.Xml.Linq. I cannot over-emphasize how much nicer they are to work with than the old classes in System.Xml. I would highly recommend them to any .Net programmer and especially someone just getting into .Net/C#.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/291387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37794/']}
jdg_370437
stackexchange
llm_judgeable_groundtruth_similarity
2775067
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: $$x^2 - 4xy + y^2 = 4$$ $$2x - 4xy' -4y + 2yy' = 0$$$$-4xy' + 2yy' = -2x + 4y$$$$y'(-4 + 2y) = -2x + 4y$$$$y' = \frac{-2x + 4y}{-4x+2y}$$ But the answer on wolfram is: $\frac{x - 2y}{2x - y}$ Sorry for the newb question. Is this right? And also, can you always multiply the top and bottom of a fraction by $-1$? I guess it makes sense since it's equivalent to $1$? Now provide the response and nothing else.
The two expressions are the same: $$\frac{-2x+4y}{-4x+2y} = \frac{-2(x-2y)}{-2(2x-y)} = \frac{-2}{-2}\cdot\frac{x-2y}{2x-y} = 1\cdot \frac{x-2y}{2x-y}=\frac{x-2y}{2x-y}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2775067', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/77211/']}
jdg_370438
stackexchange
llm_judgeable_groundtruth_similarity
19624105
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 vim to wrap long lines, but not split words in the middle. I found this post: Word wrap in Gvim but that does not work for me. I already have l in formatoptions and linebreak enabled. :set formatoptions?formatoptions=lnq As you can see, it is still splitting words: http://i.imgur.com/ekJIHww.png After consulting the relevant help pages, I also tried setting breakat to \s , but that didn't work either. Now provide the response and nothing else.
As you found out this is done using the 'linebreak' option (with 'wrap' on). If on Vim will wrap long lines at a character in 'breakat' rather than at the last character that fits on the screen. And since 'breakat' by default contains Space and Tab and some punctuation characters, this should break lines as expected (not in the middle of a word). I suggest resetting 'breakat' to the Vim default in case it has been changed by a plugin or a mapping. Oh, and don't set 'list' , these features don't mix. All together now: :set nolist wrap linebreak breakat&vim
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19624105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1436470/']}
jdg_370439
stackexchange
llm_judgeable_groundtruth_similarity
10676173
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 some reason Git is telling me I have a file which is both "to be committed" and also "not staged for commit"? This doesn't make sense: % git status # On branch master# Changes to be committed:# (use "git reset HEAD <file>..." to unstage)## modified: Dir1/Dir2/filename.cpp## Changes not staged for commit:# (use "git add <file>..." to update what will be committed)# (use "git checkout -- <file>..." to discard changes in working directory)## modified: Dir1/Dir2/filename.cpp Dir1 , Dir2 and filename.cpp are definitely all the same file. I had to add filename.cpp back again to get it to appear as a change to be committed (after it was originally in the repository). About the only thing that may have caused the problem was that I stashed, pull --rebase , then popped the stash ? .gitignore does not list Dir1 , Dir2 or filename.cpp anywhere and the patterns don't suggest they would catch this file? Now provide the response and nothing else.
It means that you made a change to filename.cpp , added that change (with git add ), then made another change that has not yet been added. The "changes to be committed" part means that Git has updated its index with a change. When you run git commit , the changes to the index will be used to create the new commit object. The "changes not staged" part shows the difference between the index and your working copy. You can reproduce what you're seeing like so: Edit filename.cpp Run git status . You'll see "changes not staged". Run git add filename.cpp Run git status . You'll see "changes to be committed". Edit filename.cpp again Run git status . You'll see both "changes not staged" and "changes to be committed". Does that make sense? It's always a little tricky explaining how Git works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10676173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1406626/']}
jdg_370440