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 | 45191 |
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 we specify subsets of a reference set by pairs, where the first co-ordinate specifies a member of the universe of discourse, and the second co-ordinate specifies the value that the characteristic function yields for that member of the reference set. E. G., if we have $\{a, b\}$ as the universe of discourse, then we have subsets $\{(a, 0), (b, 0)\}, \{(a, 0), (b, 1)\}, \{(a, 1), (b, 0)\}, \{(a, 1), (b, 1)\}$, where $(x, 0)$ indicates that $x$ does not belong to the set, while $(x, 1)$ indicates that $x$ belongs to the set. Now, consider the empty set compared across different universes of discourses, for example $\{a, b\}$, and $\{a\}$. For $\{a, b\}$ we have $\{(a, 0), (b, 0)\}$ as the empty set under this specification, and for $\{a\}$ we have $\{(a, 0)\}$ as the empty set under this specification. So, it would seem that we have a relative notion of an empty set in this context, but oftentimes books talk of "the empty set" which suggests it as absolute. So, does the concept of the empty set come as absolute, or relative?
Now provide the response and nothing else.
| If you require extensionality from $\in$, i.e. two sets are equivalent if and only if they have the same memebers, and a model is transitive (a member of a set in the model is also in the model) - then the empty set is absolute. This is quite simple to prove, since all the elements of all the sets are also sets, and the empty set is such that no one is a member of it. On the other hand, if you consider $V$ a model of $ZF$, pick $x\in V$, and declare $\in^*$ to be the relation defined only on sets generated from iterations of $\mathcal P(x)$ (i.e. repeating the power set operation), no one will be in $x$, you will have a model of $ZF$ and the empty set of this model will be $x$. However, as the intuition guiding us with topological spaces is mostly $\mathbb R^n$ the same happens with set theory, and the intuition that guides us is that of well founded and transitive models of $ZF$, in which the empty set is somewhat absolute (with respect to inner models and forcing extensions). So essentially this all boils to your theory of sets, and how you define $\in$, and which models you are taking. Addendum: An important point is internal and external view of the empty set. If a model is extensional (i.e. $\in$ satisfies extensionality) then the empty set is unique for the model, and all the models perceive their empty sets the same way -- the only set that has no elements (and this is unique by extensionality). However, if we consider a model from an external point of view we have that it could have an empty set different than the model we work in, as the example I gave above. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/45191', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11300/']} | jdg_71241 |
stackexchange | llm_judgeable_groundtruth_similarity | 9609335 |
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 could possibly be causing this stack of error during compilation??I am using gwt 2+ with eclipse 3.7 [ERROR] Unexpected internal compiler error `java.lang.ArrayIndexOutOfBoundsException: 986507 at com.google.gwt.dev.asm.ClassReader.readUnsignedShort(ClassReader.java:1850) at com.google.gwt.dev.asm.ClassReader.accept(ClassReader.java:484) at com.google.gwt.dev.asm.ClassReader.accept(ClassReader.java:420) at com.google.gwt.dev.javac.TypeOracleMediator$TypeData.getCollectClassData(TypeOracleMediator.java:147) at com.google.gwt.dev.javac.TypeOracleMediator.addNewTypes(TypeOracleMediator.java:390) at com.google.gwt.dev.javac.TypeOracleMediatorFromSource.addNewUnits(TypeOracleMediatorFromSource.java:52) at com.google.gwt.dev.javac.CompilationState.assimilateUnits(CompilationState.java:164) at com.google.gwt.dev.javac.CompilationState.(CompilationState.java:82) at com.google.gwt.dev.javac.CompilationStateBuilder.doBuildFrom(CompilationStateBuilder.java:450) at com.google.gwt.dev.javac.CompilationStateBuilder.buildFrom(CompilationStateBuilder.java:370) at com.google.gwt.dev.cfg.ModuleDef.getCompilationState(ModuleDef.java:360) at com.google.gwt.dev.Precompile.precompile(Precompile.java:252) at com.google.gwt.dev.Precompile.precompile(Precompile.java:233) at com.google.gwt.dev.Precompile.precompile(Precompile.java:145) at com.google.gwt.dev.Compiler.run(Compiler.java:232) at com.google.gwt.dev.Compiler.run(Compiler.java:198) at com.google.gwt.dev.Compiler$1.run(Compiler.java:170) at com.google.gwt.dev.CompileTaskRunner.doRun(CompileTaskRunner.java:88) at com.google.gwt.dev.CompileTaskRunner.runWithAppropriateLogger(CompileTaskRunner.java:82) at com.google.gwt.dev.Compiler.main(Compiler.java:177) Shutting down PersistentUnitCache thread Exception in thread "UnitWriteThread" java.lang.NullPointerException at com.google.gwt.dev.util.DiskCache.transferToStream(DiskCache.java:183) at com.google.gwt.dev.javac.CompiledClass.writeObject(CompiledClass.java:163) at sun.reflect.GeneratedMethodAccessor22.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeArray(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) at java.io.ObjectOutputStream.writeSerialData(Unknown Source) at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source) at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at com.google.gwt.dev.javac.PersistentUnitCache$UnitWriter.run(PersistentUnitCache.java:226)
Now provide the response and nothing else.
| Having it per-route usually works for me. This is what I typically do: function requireRole (role) { return function (req, res, next) { if (req.session.user && req.session.user.role === role) { next(); } else { res.send(403); } }}app.get("/foo", foo.index);app.get("/foo/:id", requireRole("user"), foo.show);app.post("/foo", requireRole("admin"), foo.create);// All bars are protectedapp.all("/foo/bar", requireRole("admin"));// All paths starting with "/foo/bar/" are protectedapp.all("/foo/bar/*", requireRole("user")); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9609335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1252301/']} | jdg_71242 |
stackexchange | llm_judgeable_groundtruth_similarity | 48832731 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have the following system of equations: a * b = 5sqrt(a * b^2) = 10 How can I solve these equations for a and b in R ? I guess this problem can be stated as an optimisation problem, with the following function... ? fn <- function(a, b) { rate <- a * b shape <- sqrt(a * b^2) return(c(rate, shape) )}
Now provide the response and nothing else.
| In a comment the poster specifically asks about using solve and optim so we show how to solve this (1) by hand, (2) using solve , (3) using optim and (4) a fixed point iteration. 1) by hand First note that if we write a = 5/b based on the first equation and substitute that into the second equation we get sqrt(5/b * b^2) = sqrt(5 * b) = 10 so b = 20 and a = 0.25. 2) solve Regarding the use of solve these equations can be transformed into linear form by taking the log of both sides giving: log(a) + log(b) = log(5)0.5 * (loga + 2 * log(b)) = log(10) which can be expressed as: m <- matrix(c(1, .5, 1, 1), 2)exp(solve(m, log(c(5, 10))))## [1] 0.25 20.00 3) optim Using optim we can write this where fn is from the question. fn2 is formed by subtracting off the RHS of the equations and using crossprod to form the sum of squares. fn2 <- function(x) crossprod( fn(x[1], x[2]) - c(5, 10))optim(c(1, 1), fn2) giving: $par[1] 0.2500805 19.9958117$value[1] 5.51508e-07$countsfunction gradient 97 NA $convergence[1] 0$messageNULL 4) fixed point For this one rewrite the equations in a fixed point form, i.e. in the form c(a, b) = f(c(a, b)) and then iterate. In general, there will be several ways to do this and not all of them will converge but in this case this seems to work. We use starting values of 1 for both a and b and divide both side of the first equation by b to get the first equation in fixed point form and we divide both sides of the second equation by sqrt(a) to get the second equation in fixed point form: a <- b <- 1 # starting valuesfor(i in 1:100) { a = 5 / b b = 10 / sqrt(a)}data.frame(a, b)## a b## 1 0.25 20 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48832731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5861691/']} | jdg_71243 |
stackexchange | llm_judgeable_groundtruth_similarity | 15949734 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Spring Security 3.1.2This version allows multiple "http" tags. I have an application that has two separate login pages, one for user and another for admin. Both of them will use the same authentication manager. I have build my spring-security.xml in the following manner <sec:http pattern="/loginForm.jsp" security="none"/> <sec:http pattern="/loginForm2.jsp" security="none"/> <sec:http auto-config="true"> <sec:intercept-url pattern="/login1*" access="ROLE_USER" /> <sec:form-login login-page="/loginForm.jsp" default-target-url="/login1" authentication-failure-url="/loginForm.jsp?login_error=1" /> <sec:logout logout-success-url="/loginForm.jsp" /> </sec:http> <sec:http auto-config="true"> <sec:intercept-url pattern="/login2*" access="ROLE_ADMIN" /> <sec:form-login login-page="/loginForm2.jsp" default-target-url="/login2" authentication-failure-url="/loginForm2.jsp?login_error=1" /> <sec:logout logout-success-url="/loginForm2.jsp" /> </sec:http><sec:authentication-manager> <sec:authentication-provider> <sec:user-service> <sec:user name="qwertyui" password="123456" authorities="ROLE_USER" /> <sec:user name="asdfghjk" password="123456" authorities="ROLE_USER" /> </sec:user-service> </sec:authentication-provider> </sec:authentication-manager> But I am getting this error "A universal match pattern ('/**') is defined before other patterns in the filter chain, causing them to be ignored. Please check the ordering in your namespace or FilterChainProxy bean configuration" If I omit any one of the tag, it works fine.
Now provide the response and nothing else.
| Take a look at the following css: div{ border-radius: 10px / 100%;} This hardly known slash notation enables you to use elliptical border radii as you can see in the images of the MDN border-radius Doc . With the slash notation you can define the vertical and horizontal border-radius like this: border-radius: [up to 4 horizontal values] / [up to four vertical values]; This means you can define ellipses with different radii for each corner separately (following the normal rules of defining multiple values): /* horizontal values | vertical values */ /* ↓ top-left | ↓ top-left */ border-radius: 5px 6px 7px 8px / 10px 11px 12px 13px; /* bottom-right ↑ | bottom-right ↑ */ If you distort the ellipse strongly enough, you can achieve the effect needed for your case. div{ background:#bada55; color:white; font-size:30px; font-family:arial, sans-serif; padding:10px 20px; display:inline-block; margin:10px; border-radius: 10px / 90%; text-shadow:1px 1px 1px #792; box-shadow:inset 1px 1px 1px rgba(70,90,10,.3);} <div>sponsorship</div> JSFiddle | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15949734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1101278/']} | jdg_71244 |
stackexchange | llm_judgeable_groundtruth_similarity | 18830686 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to export an entire Neo4J database in Cypher, resulting in an ASCII file of the Cypher commands which could be used on an empty Neo4J database to re-create the original database? Since Neo4J is undergoing such rapid development, I worry about using the built-in backup functionality (of the enterprise version). For example, with Oracle, you can export the whole database in SQL*PLUS DML/DDL commands, which can be useful.
Now provide the response and nothing else.
| As of Neo4j 2.0 there is a dump command in neo4j-shell that does this. You can dump the results of a specific query or the entire database. By passing the dump command as an argument when starting neo4j-shell you can redirect the output to file to make a 'cypher create script' or to another neo4j-shell session recreating all or parts of the graph in a different database. Flatten and dump the results of a query neo4j-sh$ dump MATCH (n:StackOverflow:Question {questionId:18830686})<-[:ANSWERS]-(answer)<-[:WRITES]-(user) RETURN *; Dump entire database to a file usr@term: bin/neo4j-sh -c dump > ./backup/$(date +"%y%m%d_%H%M%S").cypher Pipe the dump to another shell session & database usr@term: db1/bin/neo4j-sh -path db1/data/graph.db/ -c dump | db2/bin/neo4j-shell -path db2/data/graph.db/ Caveat emptor There were some issues with doubles and floats being exported in scientific notation, which neo4j-shell couldn't interpret again on import ( SO , github ) and there were some problems with escaping "quoted strings" ( github ). I think these are both resolved, so if you have trouble you may want to check out a recent build. And finally there is one problem that I don't think is resolved yet. Recently schema was included in the dump so create index and create constraint statements are exported as well. However, all the exported statements are framed in one and the same transaction in the output and neo4j won't let you create schema and data in the same transaction. So if you pipe the dump directly into another shell session to recreate the graph, you're likely to run into > ;ConstraintViolationException: Cannot perform data updates in a transaction that has performed schema updates.neo4j-sh (?)$ commitFailed to commit, transaction rolled back It's easy to work around this by redirecting to a file and manually adding commit and begin after the last schema statement. Be sure to put them each on a new line, it should look something like ...create index on :`Person`(`name`)commitbegincreate (_0:`Person` {`name`:"Paul"})... Or you can edit the output from neo4j-shell on the fly and add it there, for instance if you dump programmatically and don't want to edit manually. On osx I have used sed like so db1/bin/neo4j-shell -path db1/data/graph.db/ -c dump | sed -E 's/create (index|constraint) on .*/&\'$'\ncommit''\'$'\nbegin/' | db2/bin/neo4j-shell -path db2/data/graph.db/ This adds a commit after each schema statement, which is more than what is necessary (could commit all schema statements together), but hey, it works. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18830686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2570334/']} | jdg_71245 |
stackexchange | llm_judgeable_groundtruth_similarity | 26941893 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
username html field Username: <input type="text" name="username" id="username" /> keyup() event $(document).ready(function(){ $('#username').on('keyup', function(){ var username = $("#username").val(); alert(username); });}); change() event $(document).ready(function(){ $("#username").change(function() { var username = $("#username").val(); alert(username); });}); My question is should I use keyup() event or change() event to do username verification?
Now provide the response and nothing else.
| They are almost the same thing. In jQuery or JavaScript, I would have to recommend the change() event. The reason you should not use keyup() is because if a user inputs a value using autofill, it will not fire the keyup() event. However, autofill does fire the change() event, and your verification script will run, and the input will be verified. NOTE: Normally, change() is fired when the element loses focus. If you want to check data after every key press, you could combine keyup() and change() , which would allow you to parse the data on both events. This is the best of both worlds in my opinion. Hope this helps! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26941893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4234468/']} | jdg_71246 |
stackexchange | llm_judgeable_groundtruth_similarity | 12592286 |
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 enum like the one below, but eclipse says that there are errors in the first definition of each opposite pair. public enum Baz{ yin(yang), //Cannot reference a field before it is defined yang(yin), good(evil), //Cannot reference a field before it is defined evil(good); public final Baz opposite; Baz(Baz opposite){ this.opposite = opposite; }} What I want to accomplish is being able to use Baz.something.opposite to get the opposite object of Baz.something . Is there a possible workaround for this? Maybe an empty placeholder for yang and bad before yin and good are defined in this example?
Now provide the response and nothing else.
| You could try something like: public enum Baz{ yin("yang"), yang("yin"), good("evil"), evil("good"); private String opposite; Baz(String opposite){ this.opposite = opposite; } public Baz getOpposite(){ return Baz.valueOf(opposite); }} and then reference it as Baz.something.getOpposite() That should accomplish what you are looking to do by looking up the enum value by it's string representation. I don't think you can get it to work with the recursive reference to Baz. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12592286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1494396/']} | jdg_71247 |
stackexchange | llm_judgeable_groundtruth_similarity | 49292475 |
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 Angular 4 Project where I am creating a sample Map as follows: let sampleMap = new Map<string, string>();sampleMap.set('key1','value1'); Now I am passing this Map as a parameter to a Angular 4 Post method which connects to a Spring Boot Rest backend as follows Angular 4 Code: this.http.post('http://localhost:8080/data/posturl', sampleMap).map((response: Response) => { return <string>response.text(); }) Spring Boot Rest Backend Code: @RequestMapping("/posturl")public String launch(@RequestBody Map<String, String> sampleMap) { System.out.println("Received=" + sampleMap); return "SUCCESS";} Although when I try to print the 'sampleMap' as shown above, it print a blank map like follows: Received={} I am using Typescript version '~2.3.3' and my 'tsconfig.json' mentions target as 'es5'. Can someone please explain this behavior?
Now provide the response and nothing else.
| You have to convert the Map to an array of key-value pairs, as Typescript maps cannot be used directly inside a http post body. You can convert the map as follows: const convMap = {};sampleMap.forEach((val: string, key: string) => { convMap[key] = val;});this.http.post('http://localhost:8080/data/posturl', convMap).map((response: Response) => { return <string>response.text();}) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49292475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5093990/']} | jdg_71248 |
stackexchange | llm_judgeable_groundtruth_similarity | 40271519 |
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 apply partial styling to contents of a cell? For example, if a cell contains the following text "Hello World". I want to make the word "Hello" bold while leaving the word "World" unchanged. I've applied styling to the entire cell just haven't been able to apply it to certain portions of a cell.
Now provide the response and nothing else.
| You should try to use ExcelRichText class. For example: var newFile = new FileInfo("example.xlsx");using (var package = new ExcelPackage(newFile)){ var worksheet = package.Workbook.Worksheets.Add("Example"); var boldRichText = worksheet.Cells[1, 1].RichText.Add("Hello"); boldRichText.Bold = true; var normalRichText = worksheet.Cells[1, 1].RichText.Add(" World"); normalRichText.Bold = false; package.Save();} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40271519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2602844/']} | jdg_71249 |
stackexchange | llm_judgeable_groundtruth_similarity | 24884151 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Java code: class P { public void hello() {}}class C extends P { public void hello(String s) {}} My question is: Is the hello in class C overloading the one with same name in super class P ? My friend says they are not because the are not in the same class.
Now provide the response and nothing else.
| Taking a more formal approach, the Java Language Specification for Java 7 states: If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded. http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.9 I would point your friend to this link. So, in short, in your example, the hello method is indeed overloaded. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24884151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']} | jdg_71250 |
stackexchange | llm_judgeable_groundtruth_similarity | 16830405 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to use the migrate function in Laravel 4 on OSX. However, I am getting the following error: Laravel requires the Mcrypt PHP extension. As far as I understand, it's already enabled (see the image below). What is wrong, and how can I fix it?
Now provide the response and nothing else.
| The web enabled extensions and command line enabled extensions can differ. Run php -m in your terminal and check to see if mcrypt is listed. If it's not then check where the command line is loading your php.ini file from by running php --ini from your terminal. In this php.ini file you can enable the extension. OSX I have heard of people on OSX running in to problems due to the terminal pointing to the native PHP shipped with OSX. You should instead update your bash profile to include the actual path to your PHP. Something like this (I don't actually use OSX so this might not be 100%): export PATH=/usr/local/php5/bin:$PATH Ubuntu On earlier versions of Ubuntu (prior to 14.04) when you run sudo apt-get install php5-mcrypt it doesn't actually install the extension into the mods-available . You'll need to symlink it. sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/mcrypt.ini On all Ubuntu versions you'll need to enable the mod once it's installed. You can do that with php5enmod . sudo php5enmod mcryptsudo service apache2 restart NOTES PHP 7.1 deprecated mcrypt and 7.2 has removed the mcrypt extension entirely Laravel 5.1 and later removed the need for mcrypt | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/16830405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1358522/']} | jdg_71251 |
stackexchange | llm_judgeable_groundtruth_similarity | 3043751 |
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:
Solve the equation $$f(x+y)=\max(f(x),y)+\min(x,f(y))$$ My work so far: 1) $y=0 $ $f(x)=\max(f(x),0)+\min (x,f(0))$ 2) $y=-x$ $f(0)=\max(f(x),-x)+\min(x,f(-x))$
Now provide the response and nothing else.
| If you put $y=x$ you get $$f(2x) = \max (f(x),x) + \min (f(x),x) = f(x)+x$$ because if one of them is the maximum the other one is the minimum. Let $g(x)=f(x)-x$ then $g(2x)+2x = g(x)+x+x$ hence $g(2x)=g(x)$ and so (assuming that $f$ is continuous) $g(x)$ is a constant, say $g(x)=c$ for some $c\in\mathbb{R}$ . It follows that $f(x)=x+c$ . Now we check for which $c$ we have a solution, we need that $f(x+y) = x+y+c = \max (x+c,y) + \min(x,y+c)$ clearly we can find $x,y$ such that $\max (x+c,y)=x+c$ and $\min(x,y+c)=y+c$ so we get that $$x+y+c = x+c+y+c$$ it follows that $c=0$ . We conclude that $f(x)=x$ is the only (continuous) solution. Edit: Without the continuity we can argue as follows: Observe that $$f(x+y) = \max (f(x),y) + \min (x,f(y))$$ $$f(y+x) = \max (f(y),x) + \min (y,f(x))$$ If we add these equations we get: $$2f(x+y) = f(x)+f(y)+x+y$$ Now let $g(x)=f(x)-x$ we have $$2g(x+y)+2x+2y = g(x)+x+g(y)+y+x+y$$ and so $$2g(x+y) = g(x)+g(y)$$ Let $y=0$ we have that $2g(x) = g(x)+g(0)$ therefore $g(x)=g(0)$ , we conclude that $g(x)$ is a constant. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3043751', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/309360/']} | jdg_71252 |
stackexchange | llm_judgeable_groundtruth_similarity | 28762715 |
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 do the following interface Updater { void update(String value);}void update(Collection<String> values, Updater updater) { update(values, updater::update, 0);}void update(Collection<String> values, Function<String, Void> fn, int ignored) { // some code} but I get this compiler error: "Cannot convert void to java.lang.Void" That means updater::update cannot be used as Function<String, Void> . Of course I can't write Function <String, void> and I don't want to change return type of update() to Void . How do I resolve this problem?
Now provide the response and nothing else.
| A Function returns a value, even if it is declared as being of type Void (you will have to return null then. In contrast, a void method really returns nothing, not even null . So you have to insert the return statement: void update(Collection<String> values, Updater updater) { update(values, s -> { updater.update(); return null; }, 0);} An alternative would be to change the Function<String,Void> to Consumer<String> , then you can use the method reference: void update(Collection<String> values, Updater updater) { update(values, updater::update, 0);}void update(Collection<String> values, Consumer<String> fn, int ignored) { // some code} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28762715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1526758/']} | jdg_71253 |
stackexchange | llm_judgeable_groundtruth_similarity | 90409 |
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 already asked the same question at stack exchange but got no response for quite a while, so I thought I'd ask here. I also know that this has a certain resemblance to this question , but I cannot really make much sense of the answer given there. Write $\mathbb{P}^n:=\mathbb{P}^n_\Bbbk$ for projective space over some (algebraically closed) field $\Bbbk$ and assume that $X\subseteq\mathbb{P}^n$ is a linear subvariety, $\mathbb{P}^m\cong X$, say. I now consider the blow-up of $Y:=\mathbb{P}^n$ in $X$, yielding a blow-up diagram$$\begin{matrix} \tilde{X} & \xrightarrow{\;j\;} & \tilde{Y} \\\hphantom{\scriptstyle g}\downarrow {\scriptstyle g} &&\hphantom{\scriptstyle f}\downarrow {\scriptstyle f} \\X &\xrightarrow{\;i\;} & Y \end{matrix}$$My question is, what is the second chern class $c_2(\tilde Y):=c_2(\mathcal{T}_{\tilde{Y}})$ of the tangent sheaf of $\tilde{Y}$? Remark : I am ultimately interested in the degree of $c_2(\tilde Y)c_1^{n-2}(\tilde Y)$. If I could understand the total chern class $c(\tilde Y)$, that would be even better. My thoughts so far: The chern classes of $Y$ (and $X$) have well-known representation, and there is a formula for computing the chern classes of blown-up varieties in Fulton's book Intersection Theory , namely Theorem 15.4 . For brevity, I will quote his Example 15.4.3 , which gives a formula for $c_2$: $$c_2(\tilde Y) = f^\ast(c_2(Y)) - j_\ast\left( (d-1) g^\ast(c_1(X)) + \tfrac{d(d-3)}{2} \zeta + (d-2) g^\ast(c_1(\mathcal{N})) \right)$$ Here, $\mathcal{N}=\mathcal{N}_{X/Y}$ is the normal bundle of $X$ in $Y$ and $\zeta$ denotes $c_1(\mathcal{O}_{\tilde{X}}(1))$. From Fulton's Example 3.2.12 , we know that $c_1(X)=(m+1-d)\cdot\xi$ and $c_1(\mathcal{N})=d\cdot\xi$ with $\xi = c_1(\mathcal{O}_X(1))$. Now, I am kinda stuck. I am not sure what the push-forwards and pullbacks really do - in particular, what is $g^\ast(\xi)$ in terms of $\zeta$? What is $f^\ast$, applied to the class of a hyperplane? What does $j_\ast$ do? More importantly, are these the right questions to ask? Ultimately, I thought (hoped) it would be possible to express $c_2(\tilde Y)$ or even $c(\tilde Y)$ as a sum of intersections of "obvious" cycles in $\tilde Y$, possibly involving only the class of the (strict) transform of a hyperplane and the exceptional divisor.
Now provide the response and nothing else.
| My understanding of this is very unsophisticated, but perhaps that means that what I can explain is precisely what you want. To understand $f^*[H] \in H^2(\tilde Y)$, where $H \subset Y = \mathbb{P}^n$ is a hyperplane, it may help to think of $H$ as the zero set of section $s$ of the anticanonical bundle $\mathcal{O}_Y(1)$. Then the zero set of $f^*s$ (essentially just the preimage of $H$) is a divisor representing $f^*[H]$. If $H$ contained the blow-up locus $X$, then the resulting divisor is the sum of the proper transform $P$ of $H$ (the blow-up of $H$ at $X$) and the exceptional set $\tilde X$. If $H$ was transverse to $X$, then the divisor is the proper transform of $H$ (which is exactly the pre-image of $H$ in this case), which is the blow-up $\tilde H$ of $H$ at $H \cap X$. I presume $d = n-m$, the codimension of $X$ in $Y$. If $D$ is a divisor in $\tilde X$ representing $[D] \in H^2(\tilde X)$, then $j_*[D]$ is the class $[D] \in H^4(\tilde Y)$ that you get by considering $D$ as a cycle in $\tilde Y$. $g^*\xi$ can be represented by a divisor that is the preimage in $\tilde X$ of a hyperplane in $X$. Writing that hyperplane as the intersection of $X$ with a transverse hyperplane $H \subset Y$, we find that $j_*g^*\xi = [\tilde H \cap \tilde X] \in H^4(\tilde Y)$. $\zeta \in H^2(\tilde X)$ corresponds to the conormal bundle of $\tilde X$ in $\tilde Y$, so it is the restriction of $-[\tilde X] \in H^2(\tilde Y)$ to $\tilde X$. Therefore $j_*\zeta = -[\tilde X]^2 \in H^4(\tilde Y)$. To describe $j_*\zeta$ another way, note that since $\mathcal{N} = \mathcal{O}_X(1)^d$, $\tilde X$ is a trivial bundle $X \times \mathbb{P}^{d-1}$. You can get an explicit trivialisation by picking copy of $\mathbb{P}^{d-1} \cong Z \subset Y$ disjoint from $X$: given points $x \in X$ and $z \in Z$, the line from $x$ to $z$ defines an element in the projectivisation of the fibre of $\mathcal{N}$ over $x$. Let $h$ be the projection $\tilde X \to Z$. Then $\mathcal{O}_{\tilde X}(-1) = g^*\mathcal{O}_X(1) + h^*\mathcal{O}_{Z}(-1)$.$h^*\mathcal{O}_{Z}(1)$ corresponds to a trivial $\mathbb{P}^{d-2}$ subbundle of $\tilde X$. Such a divisor is the intersection of $\tilde X$ with the proper transform $P$ of a hyperplane $H$ containing $X$ and some hyperplane in $Z$. In other words, $-\zeta = g^*\xi -[P \cap \tilde X] \in H^2(\tilde X)$, so $j_*(\zeta + g_*\xi) = [P \cap \tilde X] \in H^4(\tilde Y)$. Sanity check: $-[\tilde X] + [\tilde H] = [P]$ implies $-[\tilde X]^2 + [\tilde H \cap \tilde X] = [P \cap \tilde X]$, so it adds up. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/90409', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9947/']} | jdg_71254 |
stackexchange | llm_judgeable_groundtruth_similarity | 9741975 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is one file that I always made changes to, but that I never want to be checked in. I would like TFS to block me from ever checking it in or committing the changes. How can I configure TFS to do this? Details:There is another developer on the project that has checked in some bad code that I prefer to comment out on my local machine. Since they are a client, I prefer to keep this a technical exercise rather than make it a political one.
Now provide the response and nothing else.
| One of TFS undervalued features is cloaking . Like SVN's ignore , cloaking will let you ignore a certain folder or files. Cloaking a Folder Cloaking a folder is easy: just right click a folder on the source control explorer and select Cloak Cloaking a File The UI doesn't expose cloaking on a single file, but sometimes you may want to cloak a certain file like app.config . Go to File > Source Control > Workspaces Select your workspace and click Edit . Under the working folders, and a new entry with status Cloaked and enter the full server path of the file you want to cloak. (E.g.: $/MyTeamProject/Dev/Src/SomeProject/app.config ) Using Local Workspace .tfignore file (In TFS 2012, 2013, 2015 and up) In Local Workspace , use you can use .tfignore file (the equivalent of .gitignore for Git) .tfignore file example ####################################### Ignore .cpp files in the ProjA sub-folder and all its subfoldersProjA\*.cpp# # Ignore .txt files in this folder \*.txt## Ignore .xml files in this folder and all its sub-folders*.xml## Ignore all files in the Temp sub-folder\Temp## Do not ignore .dll files in this folder nor in any of its sub-folders!*.dll Blocking by Permissions Another approach is deny check-in on the file (requires administrative privileges): Right click the file > click Properties > Security Add your user and mark Deny on the Check In permission. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9741975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62539/']} | jdg_71255 |
stackexchange | llm_judgeable_groundtruth_similarity | 51706494 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
SITUATION: Here is what I want to do: 1) I load page 0. Page 0 contains clickable links to different pages. I want to load the content of all those pages. So: 2) Click on the first link. Load page 1. Get Data. Go back to the previous page (Page 0) 3) Click on the second link which loads page 2. Etc.. ad infinitum until all links have been clicked. With my current code, page 0 loads, then the first link is clicked and loads page 1, then there is a crash with the following error: (node:2629) UnhandledPromiseRejectionWarning: Error: Protocol error (Runtime.callFunctionOn): Execution context was destroyed. QUESTION: What am I doing wrong and how can I make my script behave the way I intended ? CODE: const puppeteer = require('puppeteer');const fs = require('fs');let getData = async () => { const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); await page.goto('url', { waitUntil: 'networkidle2' }); await page.setViewport({width: ..., height:...}); const result = await page.evaluate(async () => { let data = []; let elements = document.querySelector('.items').querySelectorAll('.item'); for (const element of elements) { element.click(); await new Promise((resolve) => setTimeout(resolve, 2000)); // GETTING THE DATA THEN PUSHING IT INTO THE DATA ARRAY await page.goBack(); } return data; // Return our data array }); browser.close(); return result; // Return the data};
Now provide the response and nothing else.
| OK here's my take on this. Firstly, you're using the evaluate method incorrectly. Mainly because you don't actually need it but also because you're asking it to do something it can't do. Just to explain: the evaluate method operates in the context of your web page only. It pretty much only allows you to execute Javascript instructions directly on the current page in the remote browser. It has no concept of variables that you've declared externally to that function - so in this case, when you do this: await page.goBack(); The evaluate method has no idea what page is nor how to use it. Now there are ways to inject page into the evaluate method but that won't resolve your problem either. Puppeteer API calls simply won't work inside an evaluate method (I've tried this myself and it always returns an exception). So now lets get back to the problem you do have - what you're doing in the evaluate function is retrieving one UI element with class .items and then searching for every UI element within that UI element with class .item . You're then looping through all of the found UI elements, clicking on each one, grabbing some kind of data and then going back to click on the next one. You can achieve all of this without ever using the evaluate method and, instead, using Puppeteer API calls as follows: const itemsList = await page.$('.items'); // Using '.$' is the puppeteer equivalent of 'querySelector'const elements = await itemsList.$$('.item'); // Using '.$$' is the puppeteer equivalent of 'querySelectorAll'const data = [];elements.forEach(async (element) => { await element.click(); // Get the data you want here and push it into the data array await page.goBack();}); Hope this helps you out! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51706494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8119401/']} | jdg_71256 |
stackexchange | llm_judgeable_groundtruth_similarity | 14326900 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I give to a variable such value: e = 17|-15; , I get -15 as an answer after compiling.I can't understand what arithmetic c++ uses. How does it perform a bit-wise OR operation on negative decimals?
Now provide the response and nothing else.
| It's just doing the operation on the binary representations of your numbers. In your case, that appears to be two's complement . 17 -> 00010001-15 -> 11110001 As you can see, the bitwise OR of those two numbers is still -15 . In your comments above, you indicated that you tried this with the two's complement representations, but you must have done something wrong. Here's the step by step: 15 -> 00001111 // 15 decimal is 00001111 binary-15 -> ~00001111 + 1 // negation in two's complement is equvalent to ~x + 1-15 -> 11110000 + 1 // do the complement-15 -> 11110001 // add the 1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14326900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978522/']} | jdg_71257 |
stackexchange | llm_judgeable_groundtruth_similarity | 9527999 |
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 master and new-project branches. And now I'd like to create a brand new repo with its master based on the new-project branch. Background: I have one repository which contains three independent applications. It didn't start out this way. There was originally just one app in the repo. Over time, however, business needs have changed. One app became two (a legacy version and a re-write.) A web service was added. Separate branches were used to contain the three projects. However, they don't share any code. And so it'd be simpler to have them split out into their own repos.
Now provide the response and nothing else.
| I started with @user292677's idea, and refined it to solve my problem: Create the new-repo in github. cd to your local copy of the old repo you want to extract from, which is set up to track the new-project branch that will become the new-repo 's master. $ git push https://github.com/accountname/new-repo.git +new-project:master The new Github repo is finished. The result is; a new Github repository named new-repo , whose master corresponds to the old repo's new-project , with all history preserved. In fact, I found that by using this method, I could create the new repo with a hand-picked selection of branches, renamed as I wanted: $ git push [email protected]:accountname/new_repo +new-project:master +site3a:rails3 The result is that the pre-existing site3a branch is now also moved to the new repo and will appear as rails3 . This works really well: the network diagram shows the new master and rails3 with full history and in their correct relationship to each other. Update 2013-12-07: Used this with another project, and verified that this recipe still works. Update 2018-01-11: Updated step 3. to use GitHub recommendation for https protocol. Recipe still works. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/9527999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106906/']} | jdg_71258 |
stackexchange | llm_judgeable_groundtruth_similarity | 51776791 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Looking at the Gatsby docs, they suggest that you can reference background images like you would anywhere else: .image { background-image: url(./image.png);} What they don't cover is where these images should live. I've tried placing the image directory in the src folder, in the layout folder, and in the root folder, but I keep getting the error: Loader /Users/username/Sites/my-app/node_modules/url/url.js?{"limit":10000,"name":"static/[name].[hash:8].[ext]"} didn't return a function @ ./~/css-loader!./~/postcss-loader!./src/layouts/index.css 6:400-435 What's the proper way to reference a background image using Gatsby? Current directory structure: my-app- src-- images --- image.png-- layouts--- index.css
Now provide the response and nothing else.
| Generally I keep component-specific images alongside their JSX and CSS files and general/global images in an images folder, so I might have a structure like this: .├── components│ ├── button.jsx│ ├── button.module.scss│ └── button_icon.png└── images └── logo.png To reference button_icon.png from button.module.css I would do this: background-image: url("./button_icon.png"); And to reference logo.png from button.module.css I would do this: background-image: url("../images/logo.png"); Update: Lately I've been using Emotion with my Gatsby projects, which requires a slightly different approach. This would work with StyledComponents or Glamor as well: import background from "images/background.png"import { css } from "@emotion/core"// Object styles:<div css={{ backgroundImage: `url(${background})` }} />// Tagged template literal styles:const backgroundStyles = css` background-image: url(${background});`<div css={backgroundStyles} /> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51776791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1363751/']} | jdg_71259 |
stackexchange | llm_judgeable_groundtruth_similarity | 39566964 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I use RxAndroid and I'd like to filter the result of an Observable<List<Item>> . Here is the code : Observable<List<Item>> observable = Observable.create((Observable.OnSubscribe<List<Item>>) subscriber -> { subscriber.onNext(ItemManager.getItems()); subscriber.onCompleted(); }); I would like to use .filter() to only get the valid items. Doing this would be perfect : observable.filter(new Func1<Item, Boolean>() { @Override public Boolean call(Item item) { return item.isValid(); }}); However, .filter() forces me to implement new Func1() : observable.filter(new Func1<List<Item>, Boolean>() { @Override public Boolean call(Item item) { } }); Does somebody know how to solve the problem? Thank you in advance :)
Now provide the response and nothing else.
| Observable.defer(() -> Observable.just(ItemManager.getItems()) .subscribeOn(Schedulers.io()) .flatMapIterable(items -> items) .filter(item -> item.isValid()) .toList(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39566964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146506/']} | jdg_71260 |
stackexchange | llm_judgeable_groundtruth_similarity | 2462560 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$$\lim_\limits{x\to 4}\;\frac{x^2 - 16}{3x - 12} $$ Factoring doesn't help so I'm not sure what to do Also, $$\lim_\limits{ x\to -\infty}\;\frac{x^3 - 5x^2}{3x}$$ If you put a really big negative number in $x^3$ it will still be negative, so I'm not sure why the answer is $\infty$ and not $-\infty $???
Now provide the response and nothing else.
| $$\lim_{x\rightarrow4}\frac{x^2-16}{3x-12}=\lim_{x\rightarrow4}\frac{(x-4)(x+4)}{3(x-4)}=\lim_{x\rightarrow4}\frac{x+4}{3}=\frac{8}{3}.$$Actually, if $x\rightarrow4$ then by the definition of the limit $x\neq4$. $$\lim_{x\rightarrow-\infty}\frac{x^3-5x^2}{3x}=\frac{1}{3}\lim_{x\rightarrow-\infty}x^2\left(1-\frac{5}{x}\right)=+\infty.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2462560', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/488924/']} | jdg_71261 |
stackexchange | llm_judgeable_groundtruth_similarity | 2336928 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know how to prove that if a (smooth, compact, connected) manifold of dimension $n$ is orientable then $H^n_{dR}(M) = \mathbb{R}.$ I was wondering why the converse is true, i.e., if the top comology isn't zero....how can I construct a never-vanishing n-form? I get that I can use an n-form $w$ that is closed but not exact...but does that imply that it is never-vanishing? Thanks!
Now provide the response and nothing else.
| Let $M$ be closed connected non-orientable and $\omega$ a top-dimensional form. Pull this back to the orientable double cover $\tilde M$; because the nontrivial deck transformation $\iota$ is orientation reversing, we have $$-\int \tilde \omega = \int \iota^*\tilde \omega,$$ and so $\int \tilde \omega = 0$. Therefore there is a form with $d\eta = \tilde \omega$. You can replace $\eta$ with $\frac 12(\eta + \iota^* \eta)$ to get an $\iota^*$-invariant form whose derivative is $\tilde \omega$; thus it descends to an antiderivative of $\omega$ on $M$, making every top form exact. This is not the constructive approach you're hoping for, I don't think. I think I have such an approach but it's tedious and not insightful. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2336928', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/202249/']} | jdg_71262 |
stackexchange | llm_judgeable_groundtruth_similarity | 20401703 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I use bootstrap multi-select and I want to update options on flow with ajax To populate on init my multiselect I do <select name="model" class="multiselect" multiple="multiple"> <? foreach ($sel_models as $mod) { ?> <option value="<?= $mod ?>" <?= ($mod == $params['model']) ? 'selected' : '' ?>><?= $mod ?></option> <? } ?> </select> then on event I would like to update my option list with the following ajax I was trying to use the rebuild method but won't fire the drop-down after creation $.ajax({ type: 'post', url: "helper/ajax_search.php", data: {models: decodeURIComponent(brands)}, dataType: 'json', success: function(data) { $('select.multiselect').empty(); $('select.multiselect').append( $('<option></option>') .text('alle') .val('alle') ); $.each(data, function(index, html) { $('select.multiselect').append( $('<option></option>') .text(html.name) .val(html.name) ); }); $('.multiselect').multiselect('rebuild') }, error: function(error) { console.log("Error:"); console.log(error); } }); With firebug I can see that the list is generated but on select won't show up
Now provide the response and nothing else.
| In the doc I can read : .multiselect('setOptions', options)Used to change configuration after initializing the multiselect. This may be useful in combination with .multiselect('rebuild'). Maybe you can't change your widget data by your initial way. In a correct way you should use setOptions method. Else : With your way, maybe should you think about destroy your widget .multiselect('destroy') and create it again after. Update after comment : In the doc : ( you've linked ) Provides data for building the select's options the following way: var data = [ {label: "ACNP", value: "ACNP"}, {label: "test", value: "test"}];$("#multiselect").multiselect('dataprovider', data); So : When you get data from your ajax call, you have to create an array of objects ( it's the options in the select you want to have ) with the format like var data = [ {label: 'option1Label', value: 'option1Value'}, {label: 'option2Label', value: 'option2Value'}, ...] When your objects array is created, then you just have to call the method $("#multiselect").multiselect('dataprovider', data); Where data is your array of objects. I hope I'm clear :/ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20401703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1831740/']} | jdg_71263 |
stackexchange | llm_judgeable_groundtruth_similarity | 2215066 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$$\lim_{n \to \infty} \sqrt[n]{3^n+4^n}$$ Is there there a way to solve this without using $e^{ln(3^n+4^n)}$? Maybe:$\displaystyle\lim_{n \to \infty} \sqrt[n]{4^n}=4\,\leq\,\lim_{n \to \infty} \sqrt[n]{3^n+4^n}\,\leq\,\lim_{n \to \infty} \sqrt[n]{2\cdot4^n}=4$?
Now provide the response and nothing else.
| $$\lim _{ n\rightarrow \infty }{ \sqrt [ n ]{ 3^{ n }+4^{ n } } } =4\cdot \lim _{ n\rightarrow \infty }{ \sqrt [ n ]{ \left( \frac { 3 }{ 4 } \right) ^{ n }+1 } } =4$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2215066', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103441/']} | jdg_71264 |
stackexchange | llm_judgeable_groundtruth_similarity | 4252 |
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In a three-qubit system, it's easy to derive the CNOT operator when the control & target qubits are adjacent in significance - you just tensor the 2-bit CNOT operator with the identity matrix in the untouched qubit's position of significance: $$C_{10}|\phi_2\phi_1\phi_0\rangle = (\mathbb{I}_2 \otimes C_{10})|\phi_2\phi_1\phi_0\rangle.$$ However, it isn't obvious how to derive the CNOT operator when the control & target qubits are not adjacent in significance: $C_{20}|\phi_2\phi_1\phi_0\rangle.$ How is this done?
Now provide the response and nothing else.
| For a presentation from first principles, I like Ryan O'Donnell's answer . But for a slightly higher-level algebraic treatment, here's how I would do it. The main feature of a controlled-$U$ operation, for any unitary $U$, is that it (coherently) performs an operation on some qubits depending on the value of some single qubit. The way that we can write this explicitly algebraically (with the control on the first qubit) is:$$ \mathit{CU} \;=\; \def\ket#1{\lvert #1 \rangle}\def\bra#1{\langle #1 \rvert}\ket{0}\!\bra{0} \!\otimes\! \mathbf 1 \,+\, \ket{1}\!\bra{1} \!\otimes\! U$$where $\mathbf 1$ is an identity matrix of the same dimension as $U$. Here, $\ket{0}\!\bra{0}$ and $\ket{1}\!\bra{1}$ are projectors onto the states $\ket{0}$ and $\ket{1}$ of the control qubit — but we are not using them here as elements of a measurement, but to describe the effect on the other qubits depending on one or the other subspace of the state-space of the first qubit. We can use this to derive the matrix for the gate $\mathit{CX}_{1,3}$ which performs an $X$ operation on qubit 3, coherently conditioned on the state of qubit 1, by thinking of this as a controlled-$(\mathbf 1_2 \!\otimes\! X)$ operation on qubits 2 and 3:$$\begin{aligned}\mathit{CX}_{1,3} \;&=\;\ket{0}\!\bra{0} \otimes \mathbf 1_4 \,+\, \ket{1}\!\bra{1} \otimes (\mathbf 1_2 \otimes X)\\[1ex]&=\;\begin{bmatrix} \mathbf 1_4 & \mathbf 0_4 \\ \mathbf 0_4 & (\mathbf 1_2 \!\otimes\! X) \end{bmatrix}\;=\;\begin{bmatrix} \mathbf 1_2 & \mathbf 0_2 & \mathbf 0_2 & \mathbf 0_2 \\ \mathbf 0_2 & \mathbf 1_2 & \mathbf 0_2 & \mathbf 0_2 \\ \mathbf 0_2 & \mathbf 0_2 & X & \mathbf 0_2 \\ \mathbf 0_2 & \mathbf 0_2 & \mathbf 0_2 & X\end{bmatrix},\end{aligned}$$where the latter two are block matrix representations to save on space (and sanity). Better still: we can recognise that — on some mathematical level where we allow ourselves to realise that the order of the tensor factors doesn't have to be in some fixed order — the control and the target of the operation can be on any two tensor factors, and that we can fill in the description of the operator on all of the other qubits with $\mathbf 1_2$. This would allow us to jump straight to the representation$$\begin{alignat}{2}\mathit{CX}_{1,3} \;&=&\;\underbrace{\ket{0}\!\bra{0}}_{\text{control}} \otimes \underbrace{\;\mathbf 1_2\;}_{\!\!\!\!\text{uninvolved}\!\!\!\!} \otimes \underbrace{\;\mathbf 1_2\;}_{\!\!\!\!\text{target}\!\!\!\!}&+\,\underbrace{\ket{1}\!\bra{1}}_{\text{control}} \otimes \underbrace{\;\mathbf 1_2\;}_{\!\!\!\!\text{uninvolved}\!\!\!\!} \otimes \underbrace{\; X\;}_{\!\!\!\!\text{target}\!\!\!\!}\\[1ex]&=&\;\begin{bmatrix} \mathbf 1_2 & \mathbf 0_2 & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} \\ \mathbf 0_2 & \mathbf 1_2 & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} \\ \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} \\ \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2}\end{bmatrix}\,&+\,\begin{bmatrix} \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} \\ \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} \\ \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & X & \mathbf 0_2 \\ \phantom{\mathbf 0_2} & \phantom{\mathbf 0_2} & {\mathbf 0_2} & X\end{bmatrix}\end{alignat}$$and also allows us to immediately see what to do if the roles of control and target are reversed:$$\begin{alignat}{2}\mathit{CX}_{3,1} \;&=&\;\underbrace{\;\mathbf 1_2\;}_{\!\!\!\!\text{target}\!\!\!\!} \otimes \underbrace{\;\mathbf 1_2\;}_{\!\!\!\!\text{uninvolved}\!\!\!\!} \otimes \underbrace{\ket{0}\!\bra{0}}_{\text{control}}\,&+\,\underbrace{\;X\;}_{\!\!\!\!\text{target}\!\!\!\!} \otimes \underbrace{\;\mathbf 1_2\;}_{\!\!\!\!\text{uninvolved}\!\!\!\!} \otimes \underbrace{\ket{1}\!\bra{1}}_{\text{control}}\\[1ex]&=&\;{\scriptstyle\begin{bmatrix} \!\ket{0}\!\bra{0}\!\! & & & \\ & \!\!\ket{0}\!\bra{0}\!\! & & \\& & \!\!\ket{0}\!\bra{0}\!\! & \\& & & \!\!\ket{0}\!\bra{0}\end{bmatrix}}\,&+\,{\scriptstyle\begin{bmatrix} & & \!\!\ket{1}\!\bra{1}\!\! & \\ & & & \!\!\ket{1}\!\bra{1} \\\!\ket{1}\!\bra{1}\!\! & & & \\& \!\!\ket{1}\!\bra{1} & &\end{bmatrix}}\\[1ex]&=&\;\left[{\scriptstyle\begin{matrix}1 & 0 & 0 & 0 \\0 & 0 & 0 & 0 \\0 & 0 & 1 & 0 \\0 & 0 & 0 & 0 \\0 & 0 & 0 & 0 \\0 & 1 & 0 & 0 \\0 & 0 & 0 & 0 \\0 & 0 & 0 & 1\end{matrix}}\right.\,\,&\,\,\left.{\scriptstyle\begin{matrix}0 & 0 & 0 & 0 \\0 & 1 & 0 & 0 \\0 & 0 & 0 & 0 \\0 & 0 & 0 & 1 \\1 & 0 & 0 & 0 \\0 & 0 & 0 & 0 \\0 & 0 & 1 & 0 \\0 & 0 & 0 & 0\end{matrix}}\right].\end{alignat}$$But best of all: if you can write down these operators algebraically, you can take the first steps towards dispensing with the giant matrices entirely, instead reasoning about these operators algebraically using expressions such as $\mathit{CX}_{1,3} =\ket{0}\!\bra{0} \! \otimes\!\mathbf 1_2\! \otimes\! \mathbf 1_2 + \ket{1}\!\bra{1} \! \otimes\! \mathbf 1_2 \! \otimes\! X$and$\mathit{CX}_{3,1} =\mathbf 1_2 \! \otimes\! \mathbf 1_2 \! \otimes \! \ket{0}\!\bra{0} +X \! \otimes\! \mathbf 1_2 \! \otimes \! \ket{1}\!\bra{1}$.There will be a limit to how much you can do with these, of course — a simple change in representation is unlikely to make a difficult quantum algorithm efficiently solvable, let alone tractable by manual calculation — but you can reason about simple circuits much more effectively using these expressions than with giant space-eating matrices. | {} | {'log_upvote_score': 6, 'links': ['https://quantumcomputing.stackexchange.com/questions/4252', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/4153/']} | jdg_71265 |
stackexchange | llm_judgeable_groundtruth_similarity | 203809 |
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 am building a GUI to interface an embedded device to a PC host. The GUI provides control over the device parameters and displays some feedback from it. The GUI also has to emulate some of the device functionality and present it to the user. I have been advised to use a Model-View-Controller pattern, so that if the device does not acknowledge some command, the the user knows about the ineffectiveness of his actions. Trouble is, I cannot decide which component(s) should cache data. Example: when a value is printed on the screen, the view clearly has to know it. However, the model also has to know it, as it uses it to calculate other values. Furthermore, the controller also has to know it as, for example, the value change could be proportional to a logarithm of the user action. How do I pull this off properly?
Now provide the response and nothing else.
| The view has to know it only in a way of how to show the information to the user. It doesn't really know whether it is a weather temperature, some random text, or anything else. It doesn't interpret data in any way. The model is the one that stores and process data. And it knows whether to enable or disable a control. In your case, you need to cache data in the model. The controller controls model and view layers. It is the one that can enable or disable a control in the view by using the value from the model. And it sets all the values in the view by just passing them from the model. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/203809', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/54268/']} | jdg_71266 |
stackexchange | llm_judgeable_groundtruth_similarity | 39392853 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Java, you can give a class to a method as a parameter using the type "Class". I didn't find anything similar in the typescript docs - is it possible to hand a class to a method? And if so, does the type "any" include such class-types? Background: I'm having an issue with Webstorm, telling me that I cannot hand over a class to @ViewChild(...) in Angular 2. However, the Typescript compiler does not complain. The signature of @ViewChild() seems to be "Type<any> | Function | string" , so I wonder if any includes Classes or not.
Now provide the response and nothing else.
| The equivalent for what you're asking in typescript is the type { new(): Class } , for example: class A {}function create(ctor: { new(): A }): A { return new ctor();}let a = create(A); // a is instanceof A ( code in playground ) The code above will allow only classes whose constructor has no argument. If you want any class, use new (...args: any[]) => Class | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39392853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2725515/']} | jdg_71267 |
stackexchange | llm_judgeable_groundtruth_similarity | 6627104 |
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 .NET 3.5 Windows Service. I'm testing with a small application that just sleeps threads after starting them, for random timespans of 300 to 6500ms. I have various questions about this issue. Is BackgroundWorker really intended for use just in WinForms applications or is this just nonsense, how exactly is it tuned to this effect? I've read about ThreadPool s in this question and this one . I'm not exactly sure how much it is a problem for me that the threads would last somewhere between half a second and a few seconds. Is this reason enough to look somewhere else? Am I best off just creating the background threads myself? The real-life service will poll the database for a list of pending requests, execute threads for each of those requests (limited to a certain amount of concurrent threads) and each thread will be checking if some data exists in a database, retrieve it if it does, or download it from a streaming API, store it, and return that data. The downloading would be the part that consumes the most time. I would really like this question to be answered for .NET 3.5 Framework, but if there are better or more efficient ways to accomplish this under .NET 4.0, I would like to read about them too. Links with more info are also very much welcome.
Now provide the response and nothing else.
| The value in BackgroundWorker is that it can raise its ProgressChanged and RunworkerCompleted event on the thread that created its instance. Which makes it very convenient in programs that cannot support free threading. For this to work properly, it is however required that the SynchronizationContext.Current property references a non-default synchronization provider. A provider which is responsible for marshaling calls from one thread to another. The .NET framework has two providers that are readily available: System.Windows.Forms.WindowsFormsSynchronizationContext and System.Windows.Threading.DispatcherSynchronizationContext. These providers handle synchronization for, respectively, Winforms and WPF. There's a connection, Winforms and WPF are both class libraries that have a threading problem. Both implement GUIs and Windows based graphical user interfaces are fundamentally thread-unsafe. Windows windows can only be updated from the thread that created them. In other words, these custom synchronization providers exist because there's a dire need for them. Also notable is that they work by taking advantage of the way UI threads work. A UI thread executes code in an event driven way, pumping a message loop to receive notifications. The synchronization provider can inject calls to event handlers using this mechanism. This is no accident. Back on topic, a Windows service has no such facility. It doesn't have a GUI and doesn't install a custom synchronization provider. As such, BackgroundWorker provides no feature that's useful in a service. Without the custom synchronization provider, the default provider simply runs events on a threadpool thread. Which is not useful, you might as well fire the event from your worker thread. Getting events to run on another specific thread is very difficult to achieve, unless you recreate the message loop mechanism or hook into the Winforms plumbing and create a simulated UI thread using an invisible window. Which is not entirely uncommon btw. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6627104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389745/']} | jdg_71268 |
stackexchange | llm_judgeable_groundtruth_similarity | 45368 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Case We have a working 802.1x configuration on all our access ports. I want to enable WakeOnLan, but have no idea, how to target computers with Magic Packet. Tests We tried to send Magic Packet over 802.1x' Guest VLAN, but it soon prooved to be working only in certain situations, eg. when client computer was connected through VoIP Phone: Interface State VLAN members Tag Tagging Blockingge-0/0/3.0 up GUEST 100 untagged unblocked default untagged unblocked VOIP 200 tagged unblocked But as soon as we reconnected computer directly, the port was still up, but JunOS downgraded the port to default VLAN (1): Interface State VLAN members Tag Tagging Blockingge-0/0/3.0 up default untagged unblocked VOIP 200 tagged unblocked Obvious solution is to send Magic Packet over default VLAN, but for several reasons this is not feasible for us (we do not want to propagate default VLAN between various segments of the network due to security and maintenance reasons). Question How to target Magic Packets to client computers while not utilising default VLAN?
Now provide the response and nothing else.
| There is a quite nice and simple solution: We have utilized the voice VLAN to send Magic Packets. Voice VLAN is configurable under: ethernet-switching-options { voip { interface access-dot1x { vlan VOIP; forwarding-class assured-forwarding; } }} We were already using it to connect VoIP phones. The feature exposed defined VLAN as tagged on all affected ports and also effect in this VLAN being advertised over LLDP to phones, which will automatically attempt to communicate over advertised VLAN. There was a doubt if a tagged Magic Packet would be recognized (and thus successfull), but tests with wide range of devices prooved positive. Also, there was no problem with forwarding a tagged Magic Packet through VoIP phone. The trick works both with directly connected and phone-bypassed computers. (it remains to be proven if this approach has any downsides, if you suspect any, please let me know) | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/45368', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/39944/']} | jdg_71269 |
stackexchange | llm_judgeable_groundtruth_similarity | 23878 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking at SMD leds, and it seems that same leds of same color in 0603 and 1206 cases, having same rated current and same angle of irradiation, show different light flux, 1206 being several times brighter. What is the explanation for this? My task is to get maximal brightness out of bunch of blue SMD leds. 0603 are smaller and cheaper, so for the same money I can place 3x times more of them, while 1206 have higher rated mcd flux.... Hi-power 1-3W leds which are rated in lumens does not work for me, as I would need them on flexible PCB. I am puzzled... Any info on that?
Now provide the response and nothing else.
| I think the problem is a lack of understanding of what one means by "brightness". Brightness is a very ambiguous term. First of all, I'll make the assumption that you are speaking in terms of a human's perception of brightness. This limits our discussion to photometry . You have to now differentiate between two measures of brightness, i.e. Luminous intensity and Luminous flux (or Luminous Power) . Luminous flux is the light power emitted in all directions and has SI units of "Lumens". Luminous Intensity is the light power emitted in one solid angle which has SI units of "candela". Think of a solid angle as a cone with it's vertex at the led emitter. You mentioned mcd as units, these are millicandela, so mcd is a measure of Luminous Intensity. You can't directly compare luminous Intensity (candela)) with Luminous Flux (lumens). I did find this tool to convert between the two units, but, it must have to make the assumption that the light is omnidirectional and is only accurate for such lights. You'll have to get your units straight before you can make sense out of this. In additon, you have to decide what your objective is. Are you trying to make a light with high luminous Flux or one with high Luminous Intensity? I would imagine that you are going for a light with high luminous Flux or you probably would be speaking of laser diodes instead of LEDs. So choose whatever package that maximizes your Luminous Flux, i.e. Lumens. You did not provide enough information to give a better recommendation than this. That is, you did not specify any additional design constraints. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/23878', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/2062/']} | jdg_71270 |
stackexchange | llm_judgeable_groundtruth_similarity | 8614858 |
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 it possible to create namespaces in Redis? From what I found, all the global commands (count, delete all) work on all the objects. Is there a way to create sub-spaces such that these commands will be limited in context? I don't want to set up different Redis servers for this purpose. I assume the answer is "No", and wonder why wasn't this implemented, as it seems to be a useful feature without too much overhead.
Now provide the response and nothing else.
| A Redis server can handle multiple databases... which are numbered. I think it provides 32 of them by default; you can access them using the -n option to the redis-cli shell scripting command and by similar options to the connection arguments or using the "select()" method on its connection objects. (In this case .select() is the method name for the Python Redis module ... I presume it's named similarly for other libraries and interfaces. There's an option to control how many separate databases you want in the configuration file for the Redis server daemon as well. I don't know what the upper limit would be and there doesn't seem to be a way to dynamically change that (in other words it seems that you'd have to shutdown and restart the server to add additional DBs). Also, there doesn't seem to be an away to associate these DB numbers with any sort of name nor to impose separate ACLS, nor even different passwords, to them. Redis, of course, is schema-less as well. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8614858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11236/']} | jdg_71271 |
stackexchange | llm_judgeable_groundtruth_similarity | 505573 |
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:
If $f\left(z \right)=\sum_{n=2}^{\infty}a_{n}z^n$ and $\sum_{n=2}^{\infty}|a_n|$ converges then,$$\sum_{n=1}^{\infty}f\left(\frac{1}{n}\right)=\sum_{n=2}^{\infty}a_n\zeta\left(n\right).$$Since if we set $C:=\sum_{m=2}^{\infty}|a_m|<\infty$, then$$\sum_{n=1}^{\infty}\sum_{m=2}^{\infty}|a_m\frac{1}{n^m}|\leq\sum_{n=1}^{\infty}\sum_{m=2}^{\infty}|a_m|\frac{1}{n^2}\leq C\sum_{n=1}^{\infty}\frac{1}{n^2}<\infty$$and by Cauchy's double series theorem, we can switch the order of summation:$$\sum_{n=1}^{\infty}f\left(\frac{1}{n}\right)=\sum_{n=1}^{\infty}\sum_{m=2}^{\infty}a_m\frac{1}{n^m}=\sum_{m=2}^{\infty}a_m\sum_{n=1}^{\infty}\frac{1}{n^m}=\sum_{n=2}^{\infty}a_n\zeta\left(n\right).$$This shows that $\sum_{n=2}^{\infty}\frac{\zeta(n)}{k^n}=\sum_{n=1}^{\infty}\frac{1}{kn(kn-1)}$. My Questions: 1) It's obvious that $\sum_{n=1}^{\infty}\frac{1}{2n(2n-1)}=\log(2)$, but how can I evaluate $\sum_{n=1}^{\infty}\frac{1}{3n(3n-1)}$? 2) Is there another method to evaluate $\sum_{n=2}^{\infty}\frac{\zeta(n)}{k^n}$?
Now provide the response and nothing else.
| Extended Harmonic Numbers Normally, we think of Harmonic Numbers as$$H_n=\sum_{k=1}^n\frac1k\tag{1}$$However, an alternate definition is often useful:$$H_n=\sum_{k=1}^\infty\left(\frac1k-\frac1{k+n}\right)\tag{2}$$For integer $n\ge1$, it is not too difficult to see that the two definitions agree. However, $(2)$ is easily extendible to all $n\in\mathbb{R}$ (actually, to all $n\in\mathbb{C}$). We can say some things about $H_n$ for some $n\in\mathbb{Q}\setminus\mathbb{Z}$. Note that for $m,n\in\mathbb{Z}$,$$\begin{align}H_{mn}-H_n&=\sum_{k=1}^\infty\left(\frac1k-\frac1{k+mn}\right)-H_n\\&=\sum_{k=1}^\infty\sum_{j=0}^{m-1}\left(\frac1{km-j}-\frac1{km-j+mn}\right)-H_n\\&=\frac1m\sum_{j=0}^{m-1}\sum_{k=1}^\infty\left(\left(\frac1k-\frac1{k-j/m+n}\right)-\left(\frac1k-\frac1{k-j/m}\right)\right)-H_n\\&=\frac1m\sum_{j=0}^{m-1}\left(\left(H_{n-j/m}-H_n\right)-H_{-j/m}\right)\tag{3}\end{align}$$Since $H_0=0$ and $H_n=\log(n)+\gamma+O\left(\frac1n\right)$, where $\gamma$ is the Euler-Mascheroni Constant , if we let $n\to\infty$ in $(3)$, we get$$\sum_{j=1}^{m-1}H_{-j/m}=-m\log(m)\tag{4}$$Using identity $(7)$ from this answer ,$$\begin{align}\pi\cot(\pi z)&=\sum_{k\in\mathbb{Z}}\frac1{k+z}\\&=\sum_{k=1}^\infty\left(\frac1{k-1+z}-\frac1{k-z}\right)\\&=\sum_{k=1}^\infty\left(\frac1k-\frac1{k-z}\right)-\sum_{k=1}^\infty\left(\frac1k-\frac1{k+z-1}\right)\\&=H_{-z}-H_{z-1}\tag{5}\end{align}$$which implies$$H_{-j/m}-H_{-(m-j)/m}=\pi\cot\left(\frac{\pi j}{m}\right)\tag{6}$$ Using $(4)$ and $(6)$ for $m=3$ yields$$H_{-1/3}+H_{-2/3}=-3\log(3)\tag{7}$$and$$H_{-1/3}-H_{-2/3}=\pi\cot\left(\frac\pi3\right)\tag{8}$$Averaging $(7)$ and $(8)$ yields$$H_{-1/3}=-\frac32\log(3)+\frac\pi{2\sqrt3}\tag{9}$$Finally,$$\begin{align}\sum_{n=1}^\infty\frac1{3n(3n-1)}&=-\frac13\sum_{n=1}^\infty\left(\frac1n-\frac1{n-1/3}\right)\\&=-\frac13H_{-1/3}\\[6pt]&=\frac12\log(3)-\frac\pi{6\sqrt3}\tag{10}\end{align}$$ Values for Future Reference Using $(4)$ and $(6)$, we can also compute$$\begin{align}H_{-1/4}&=\pi/2-3\log(2)\\H_{-1/2}&=-2\log(2)\\H_{-3/4}&=-\pi/2-3\log(2)\end{align}\tag{11}$$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/505573', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91500/']} | jdg_71272 |
stackexchange | llm_judgeable_groundtruth_similarity | 21392550 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the class Foo . public class Foo { private double size; public double getSize() { return this.size; // Always O(1) }} Foo has a property called size, which is frequently accessed, but never modified, by a given method. I've always cached a property in a variable whenever it is accessed more than once in any method, because "someone told me so" without giving it much thought. i.e. public void test(Foo foo) { double size = foo.getSize(); // Cache it or not? // size will be referenced in several places later on.} Is this worth it, or an overkill? If I don't cache it, are modern compilers smart enough to cache it themselves?
Now provide the response and nothing else.
| A couple of factors (in no particular order) that I consider when deciding whether or not to store the value returned by a call to a "get() method": Performance of the get() method - Unless the API specifies, or unless the calling code is tightly coupled with the called method, there are no guarantees of the performance of the get() method. The code may be fine in testing now, but may get worse if the get() methods performace changes in the future or if testing does not reflect real-world conditions. ( e.g. testing with only a thousand objects in a container when a real-world container might have ten million ) Used in a for-loop, the get() method will be called before every iteration Readability - A variable can be given a specific and descriptive name, providing clarification of its use and/or meaning in a way that may not be clear from inline calls to the get() method. Don't underestimate the value of this to those reviewing and maintaining the code. Thread safety - Can the value returned by the get() method potentially change if another thread modifies the object while the calling method is doing its thing? Should such a change be reflected in the calling method's behavior? Regarding the question of whether or not compilers will cache it themselves, I'm going to speculate and say that in most cases the answer has to be 'no'. The only way the compiler could safely do so would be if it could determine that the get() method would return the same value at every invocation. And this could only be guaranteed if the get() method itself was marked final and all it did was return a constant (i.e an object or primitive also marked 'final'). I'm not sure but I think this is probably not a scenario the compiler bothers with. The JIT compiler has more information and thus could have more flexibility but you have no guarantees that some method will get JIT'ed. In conclusion , don't worry about what the compiler might do. Caching the return value of a get() method is probably the right thing to do most of the time, and will rarely ( i.e almost never ) be the wrong thing to do. Favor writing code that is readable and correct over code that is fast(est) and flashy. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21392550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407236/']} | jdg_71273 |
stackexchange | llm_judgeable_groundtruth_similarity | 46575644 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here I am asking a question of google spreadsheet and google script.As when we copy the spreadsheet, the google script code will also be copied.While I have several templates for different cases and the structure of them is quite similar. What I want to ask is it possible to link all the script code for all the template together, like temp A's code is A1 and temp B's code is A2, A1 and A2 are same and if I make some change in A1, A2 will be updated automatically. Thank you.
Now provide the response and nothing else.
| If I understood your question right, you could use Libraries .The idea is that you create one script that you use as a library. Let us say it has a function like the following: function myAppend(){ SpreadsheetApp.getActive().getActiveSheet.appendRow(["Dummy Text"]);} Then you save a version of it going to File -> Manage Versions. Give it a name and save new version. Next you go to File -> Project Properties and copy the Script ID - value. I will refer it as the Library ID. Next, when you create a new Spreadsheet and a new script, you go to Resources -> Libraries. Enter the Library ID to the input labeled "Add a library" and Add. Now, for the next phase to work, everyone using your script need to have editing rights to the Library Script, otherwise the updating feature you need will not work. From the recently added Library you select "Development mode = on". Give a Identifier to the Library. I will use "TestLib" as my example. Now, in your TemplateSpreadsheet script you call the function from the library as follows: function append(){ TetsLib.myAppend();} Ok, now if your development mode in your sheet scripts is on and all the users have editing access to the library script, you should be set. Now when you copy the template sheet it will have the same script calling your library. Also, when you edit the function just in the library, all the scripts using it should update too. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46575644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7737245/']} | jdg_71274 |
stackexchange | llm_judgeable_groundtruth_similarity | 1228178 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to read lots of data(single column nvarchar(max)) from SQL Server 2005 and deserialize it to an object. We are currently using the following, but this is not fast enough is there a better/efficient way to do it? using(MemoryStream stream = Encoding.UTF8.GetBytes((string)cmd.ExecuteScalar())){ XmlTextReader xmlReader; DataContractSerializer deserializer; deserializer = new DataContractSerializer(typeToDeserialize); xmlReader = new XmlTextReader(stream); return deserializer.ReadObject(xmlReader);} I've als tried to do it with an SqlDataReader and GetBytes but then I get exceptions. Thanx in advance.
Now provide the response and nothing else.
| At a casual glance, it appears that this should (as in beer should be free) work. However, a quick sanity check shows us why it can't. Bear in mind that the following code will not compile . It's intended to show why it isn't allowed to, even though it looks alright up until a point. public interface IFoo { }public class Bar : IFoo { }public class Zed : IFoo { }//.....List<IFoo> myList = new List<Bar>(); // makes sense so farmyList.Add(new Bar()); // OK, since Bar implements IFoomyList.Add(new Zed()); // aaah! Now we see why.//..... myList is a List<IFoo> , meaning it can take any instance of IFoo . However, this conflicts with the fact that it was instantiated as List<Bar> . Since having a List<IFoo> means that I could add a new instance of Zed , we can't allow that since the underlying list is actually List<Bar> , which can't accommodate a Zed . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1228178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37311/']} | jdg_71275 |
stackexchange | llm_judgeable_groundtruth_similarity | 2509929 |
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 would a simple unit test look like to confirm that a certain controller exists if I am using Rhino Mocks, NUnit and ASP.NET MVC 2? I'm trying to wrap my head around the concept of TDD, but I can't see to figure out how a simple test like "Controller XYZ Exists" would look. In addition, what would the unit test look like to test an Action Result off a view ?
Now provide the response and nothing else.
| Confirm that a controller exists Having unit tests on its actions is a strong suggestion that the controller exists which brings us to: What would the unit test look like to test an Action Result off a view Here's an example: public class HomeController: Controller{ private readonly IRepository _repository; public HomeController(IRepository repository) { _repository = repository; } public ActionResult Index() { var customers = _repository.GetCustomers(); return View(customers); }} And the corresponding unit test: [Test]public void HomeController_Index_Action_Should_Fetch_Customers_From_Repo(){ // arrange var repositoryStub = MockRepository.GenerateStub<IRepository>(); var sut = new HomeController(repositoryStub); var expectedCustomers = new Customer[0]; repositoryStub .Stub(x => x.GetCustomers()) .Return(expectedCustomers); // act var actual = sut.Index(); // assert Assert. IsInstanceOfType(typeof(ViewResult), actual); var viewResult = (ViewResult)actual; Assert.AreEqual(expectedCustomers, viewResult.ViewData.Model);} MVCContrib has some great features allowing you to mock HttpContext and also test your routes . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2509929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135952/']} | jdg_71276 |
stackexchange | llm_judgeable_groundtruth_similarity | 24103981 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Learning node.js. Trumpet works by piping a stream back to itself, apparently, so the processed data can then be output. This makes no sense to me, since it seems to be like connecting both ends of a stream to itself. How does trumpet distinguish between the pre and post processed data? ie, why doesn't loud.pipe(...).pipe(loud) result in some form of infinite loop of processing? var trumpet = require('trumpet');var through = require('through');var tr = trumpet();var loud = tr.select('.loud').createStream();loud.pipe(through(function (buf) { this.queue(buf.toString().toUpperCase());})).pipe(loud);process.stdin.pipe(tr).pipe(process.stdout);
Now provide the response and nothing else.
| I had the exact same confusion: davecocoa had this to say to me at the nodeschool.io discussions thread on github.Below is an extract from https://github.com/nodeschool/discussions/issues/346 I think you might be confusing the two streams loud and tr . tr is the main trumpet stream It is a transform stream (has input and output like a pipe) It takes html as input It outputs html we connect stdin to its input, and we connect its output to stdout We created loud by asking tr to select html elements with class loud It is a duplex stream (has input and output like a telephone) it outputs or sends html elements it also receives html elements tr behaves such that, when html is streamed to it, if there are elements with class loud, they are output from loud , which sends them to the through stream you built for making the text uppercase, which sends them to back to loud 's input, where they are reinserted into the html tr originally received and output from tr . I guess an important thing to note is that, although loud has an important connection with tr , they are not actually piped together at all. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24103981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/766911/']} | jdg_71277 |
stackexchange | llm_judgeable_groundtruth_similarity | 54079531 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a simple REST API with NodeJS and Express without any database. I have stored all of my data in JSON files.The data is in the form of an array of objects. I have paths like fund-name/:portId so I am doing this: const fundName = require('./json/fund-name.json');app.get('/fund-details:portId', (req, res) => { const portId = req.params.portId; fundDetails.forEach(fund => { if (fund.portId === portId) { return res.json(fund); } return res.json([]); });}); when I hit the url http:localhost:3000/fund-details/1234 , I get the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:470:11) at ServerResponse.header (/home/username/Desktop/data-server/node_modules/express/l ib/response.js:767:10) It works fine when I don't pass any path param to get all the funds.Where am I going wrong??
Now provide the response and nothing else.
| This error is because you are using res.send() multiple time in single api call. Correct way if(a){ res.send()}else{ res.send()} Wrong way if(a){ res.send() res.send()}else{ res.send()} In your code. app.get('/fund-details:portId', (req, res) => {const portId = req.params.portId;fundDetails.forEach(fund => { if (fund.portId === portId) { return res.json(fund); // many or single times here } return res.json([]); // and here when fund !==portId here });}); You can try app.get('/fund-details:portId', (req, res) => {const portId = req.params.portId;var flag var data = []fundDetails.forEach(fund => { if (fund.portId === portId) { flag=true data.push(fund) }});if(flag){ res.send(data);}else{ res.send()}}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54079531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5924007/']} | jdg_71278 |
stackexchange | llm_judgeable_groundtruth_similarity | 335988 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to change the message-id in postfix? If I send Mails over an Java-Application I get the following message-id: message-id=<143303043.111334605578921.JavaMail.applicationanme@hostname> So I want that the message-id looks like this: message-id=<[email protected]> What I can understand, if I send mails with the Linux program mail it works: message-id=<[email protected]> I have already set my hostname in the postfix-conf, but when I send a mail with the java-application it doen't work. We use a relay host to send email and any messages which are sent without @domain.tld in the mail-id will detected as a spam mail. Do you have any idea how I can fix this?
Now provide the response and nothing else.
| Since no one gave you a solution on how to have postfix insert a message-id that reflects your domain and I had the same issue, I figured I would share how I was able to have postfix do so: Add to the end of /etc/postfix/main.cf header_checks = regexp:/etc/postfix/header_checks Insert a replace string in header_checks /Message-Id:\s+<(.*?)@hostname>/ REPLACE Message-Id: <[email protected]> Run postmap postmap /etc/postfix/header_checks Restart postfix service postfix restart | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/335988', 'https://serverfault.com', 'https://serverfault.com/users/102526/']} | jdg_71279 |
stackexchange | llm_judgeable_groundtruth_similarity | 17950598 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having a tough time figuring out how to access a page loaded in an iframe from the outer page. Both pages are local files, and I'm using Chrome. I have an outer page, and many inner pages. The outer page should always display the page title for the inner page (it makes sense in my application, perhaps less so in this stripped-down example). This works without any problem in AppJS, but I've been requested to make this app work directly in the browser. I'm getting the error " Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match. ". I think this is due to Chrome's same origin policy regarding local files, but that hasn't helped me fix the problem directly. I can work around the issue in this stripped-down example by using the window.postMessage method per Ways to circumvent the same-origin policy . However, going beyond this example, I also want to manipulate the DOM of the inner page from the outer page, since this will make my code much cleaner - so posting messages won't quite do the job. Outer Page <!DOCTYPE html><html> <head> <meta name="viewport"> </head> <body> This text is in the outer page <iframe src="html/Home.html" seamless id="PageContent_Iframe"></iframe> <script src="./js/LoadNewPage.js"></script> </body></html> Inner Page <!DOCTYPE html><html> <head> <title id="Page_Title">Home</title> <meta name="viewport"> </head> <body> This text is in the inner page </body></html> JavaScript var iFrameWindow = document.getElementById("PageContent_Iframe").contentWindow;var pageTitleElement = iFrameWindow.$("#Page_Title"); Per Is it likely that future releases of Chrome support contentWindow/contentDocument when iFrame loads a local html file from local html file? , I tried launching Chrome with the flag --allow-file-access-from-files But there was no change in the results. Per Disable same origin policy in Chrome , I tried launching Chrome with the flag --disable-web-security But again there was no change in the results. Per What does document.domain = document.domain do? , I had both pages run the command document.domain = document.domain; This resulted in the error " Blocked a frame with origin "null" from accessing a frame with origin "null". The frame requesting access set "document.domain" to "", but the frame being accessed did not. Both must set "document.domain" to the same value to allow access. " For fun, I had both pages run the command document.domain = "foo.com"; This resulted in the error " Uncaught Error: SecurityError: DOM Exception 18 ". I'm floundering. Any help from more knowledgeable people would be fantastic! Thanks!
Now provide the response and nothing else.
| Per our discussion in my cube just a minute ago :) I hit this same problem ( Ajax post response from express js keeps throwing error ) trying to get an AJAX post request to work correctly. What got me around it is not running the file directly off the file system but instead running it from a local server. I used node to run express.js. You can install express with the following command: npm install -g express Once that is accomplished, you can create an express project with the following command: express -s -e expressTestApp Now, in that folder, you should see a file named app.js and a folder named public. Put the html files you wish to work with in the public folder. I replaced the file app.js with the following code: var express = require('/usr/lib/node_modules/express');var app = express();app.use(function(err, req, res, next){ console.error(err.stack); res.send(500, 'Something broke!');});app.use(express.bodyParser());app.use(express.static('public'));app.listen(5555, function() { console.log("Server is up and running"); }); Note, the require line may be different. You have to find where your system actually put express. You can do that with the following command: sudo find / -name express Now, start the express web server with the following command: node app.js At this time, the webserver is up and running. Go ahead and open a browswer and navigate to your ip address (or if you're on the same machine as your server, 127.0.0.1). Use the ip address:portnumber\filename.html where port number is the 5555 in the app.js file we created. Now in that browser, you shouldn't (and didn't when we tested it) have any of these same problems anymore. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17950598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/634868/']} | jdg_71280 |
stackexchange | llm_judgeable_groundtruth_similarity | 240778 |
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 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it. If it really simplifies the problem, I can limit the polygon to a parallelogram, but a more general answer is preferred. Generating random points until one is inside the polygon wouldn't work because it's really unpredictable the time it takes.
Now provide the response and nothing else.
| A. If you can restrict your input to parallelogram, this is really simple: Take two random numbers between 0 and 1. We'll call then u and v . If your parallelogram is defined by the points ABCD such that AB, BC, CD and DA are the sides, then take your point as being: p = A + (u * AB) + (v * AD) Where AB is the vector from A to B and AD the vector from A to D. B. Now, if you cannot, you can still use the barycentric coordinates. The barycentric coordinates correspond, for a quad, to 4 coordinates (a,b,c,d) such that a+b+c+d=1 . Then, any point P within the quad can be described by a 4-uple such that: P = a A + b B + c C + d D In your case, you can draw 4 random numbers and normalize them so that they add up to 1. That will give you a point. Note that the distribution of points will NOT be uniform in that case. C. You can also, as proposed elsewhere, decompose the quad into two triangles and use the half-parallelogram method (i.e., as the parallelogram but you add the condition u+v=1 ) or the barycentric coordinates for triangles. However, if you want uniform distribution, the probability of having a point in one of the triangle must be equal to the area of the triangle divided by the area of the quad. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/240778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1815/']} | jdg_71281 |
stackexchange | llm_judgeable_groundtruth_similarity | 333796 |
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I ask a question, generally it is programming related. I simply go to whatever code I am working on, make an example mockup of the code, exclude specific variables and identifying information to the specific application I am working on, and then I post the mockup code. Generally my questions are answered right away, usually without hiccup. However when it comes to MySQL related issues, I find it much harder if not impossible to get answers. I do the same general idea of looking at the problem I am having, and creating mock data to post when asking my question. However I find when it comes to MySQL IT SEEMS so far based on my limited experiences on this site, that people are not so accepting to work with mock data. In one such recent question it has so far ended in a string of comments where I expressed confusion about what was being asked of me when it comes to "sample data", and it was told to me that "I need to run actual queries on the database I am working on and post the results of those queries". Obviously, I am not going to do that as I am dealing with a live database, and I am not about to just go sharing data from it on Stack Overflow. I suppose my question, without trying to start any kind of huge debate, is: How exactly do I generate a MySQL question without posting actual contents of my database that will be acceptable by others to actually answer? Here is an example of what I mean: https://stackoverflow.com/questions/39285286/complex-joins-and-unions-mysql?noredirect=1#comment65912520_39285286 As can be seen on that post, I shared mockup database data. I could literally write a CREATE database and a series of insert commands that would recreate the example mockup I gave, and reproduce my problem. So what is it about ACTUAL data that is so important? How do I fix the MySQL questions I ask so people actually answer instead of demand me expose the database I am working on?
Now provide the response and nothing else.
| Use a find, and replace any specific names with generic names in an IDE like Notepad++ . It can be painful, as I've asked many questions that don't make sense slipping up with that and then having to edit it. But it's the only way to anonymise any code. You should never have to share any real data. If people hassle you for that, bring it to meta with a question. | id | username | data | data2 | id | data3 | id | data4 |--------------------------------------------------------------------------------------------| 1 | someuser | some data | more data | 2 | more data | 3 | more data || 1 | someuser | some data | more data | 3 | more data | 2 | more data || 2 | someuser | some data | more data | 3 | more data | 1 | more data || 2 | someuser | some data | more data | 1 | more data | 3 | more data | Replace the repeated values with unique values e.g. user1, some data1, more data1.. and so on. Perhaps consider using name, address, city, instead of data2, data3.Having mock names Fred, Harry, Sally, and City, Sydney, NY, and so on. It's easier to read when there's a greater difference between these names. | id | username | name | city | id | street | id | Pets |--------------------------------------------------------------------------------------------| 1 | fred101 | Fred | NY | 2 | Apple Cove | 3 | Rover || 1 | hazza | Harry | Sydney | 3 | Sodds St | 2 | Rocky || 2 | sally7 | Sally | London | 3 | Rigor Road | 1 | Sid || 2 | bendo | Ben | Hobart | 1 | Moon Cres | 3 | Boots | Now this dummy data may not be consistent with what you're trying to ask and how the data matches, but this is where there is a lack of clarity in what you are asking. Also with the code: SELECT * from table1LEFT OUTER JOIN table2ON table1.username=table2.usernameUNIONSELECT * from table2LEFT OUTER JOIN table1ON table2.username=table1.usernameWHERE table1.username= :usernameAND table2.username = :username This is difficult to process also, as the repeated use of a username with the generic table appended with a number makes the mental gymnastics in the brain harder. If you look at something like this, it's easier to follow: SELECT * from UsersLEFT OUTER JOIN MembersON Users.username=Members.usernameUNIONSELECT * from MembersLEFT OUTER JOIN UsersON Members.username=Users.usernameWHERE Users.username= :usernameAND Members.username = :username Obviously match the data table with the query. | {} | {'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/333796', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/597390/']} | jdg_71282 |
stackexchange | llm_judgeable_groundtruth_similarity | 13591 |
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 can be shown by simple induction that $\dfrac{\mathrm d^n}{\mathrm dx^n}\left(\dfrac1{x}\right) = \dfrac{(-1)^n n!}{x^{n+1}}$. But what about the nth integral of $\dfrac1{x}$? Finding the first few primitives, I can't discern a pattern.
Now provide the response and nothing else.
| As Isaac noted, repeated integration seems to give the following pattern $$ \frac{x^{n-1} \log x}{(n-1)!} - C_n x^{n-1}$$ Note that the value of $\displaystyle C_n$ does not really matter, as differentiating $n$ times nukes it. Also, note that, we can add any arbitrary $\displaystyle (n-1)^{th}$ degree polynomial to this, without changing the $\displaystyle n^{th}$ derivative. In order to prove that the $\displaystyle n^{th}$ derivative of $\displaystyle \frac{x^{n-1} \log x}{(n-1)!}$ is $\displaystyle \frac{1}{x}$, we can use induction. $$ \frac{1}{(n-1)!} \frac{d (x^{n-1} \log x)}{dx} = \frac{x^{n-2}}{(n-1)!} + \frac{x^{n-2} \log x}{(n-2)!}$$ Since adding an arbitrary $\displaystyle (n-2)^{th}$ degree polynomial does not change the $\displaystyle (n-1)^{th}$ derivative of $\displaystyle \frac{x^{n-2} \log x}{(n-2)!}$ we are done using induction. Note that if $\displaystyle f(x)$ is another function such that $\displaystyle \frac{d^n f}{dx} = \frac{1}{x}$, then we have that $\displaystyle \phi(x) = f(x) - \frac{x^{n-1} \log x}{(n-1)!}$ has it's $\displaystyle n^{th}$ derivative to be zero, and hence it is a polynomial of degree $\displaystyle n-1$ or lower (can be proved using induction, again). Thus all the functions you are looking for are of the form $$\frac{x^{n-1} \log x}{(n-1)!} + \sum_{j=0}^{n-1} c_j x^j$$ where $\displaystyle c_j$ are arbitrary constants. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/13591', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4558/']} | jdg_71283 |
stackexchange | llm_judgeable_groundtruth_similarity | 7240519 |
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 around 500 text files inside a directory with each with the same prefix in their filename, for example: dailyReport_ . The latter part of the file is the date of the file. (For example dailyReport_08262011.txt , dailyReport_08232011.txt ) I want to delete these files using a Java procedure. (I could go for a shell script and add it a job in the crontab but the application is meant to used by laymen). I can delete a single file using something like this: try{ File f=new File("dailyReport_08232011.txt"); f.delete();}catch(Exception e){ System.out.println(e);} but can I delete the files having a certain prefix? (e.g. dailyReport08 for the 8th month) I could easily do that in shell script by using rm -rf dailyReport08*.txt . But File f=new File("dailyReport_08*.txt"); doesnt work in Java (as expected). Now is anything similar possible in Java without running a loop that searches the directory for files? Can I achieve this using some special characters similar to * used in shell script?
Now provide the response and nothing else.
| No, you can't. Java is rather low-level language -- comparing with shell-script -- so things like this must be done more explicetly. You should search for files with required mask with folder.listFiles(FilenameFilter), and iterate through returned array deleting each entry. Like this: final File folder = ...final File[] files = folder.listFiles( new FilenameFilter() { @Override public boolean accept( final File dir, final String name ) { return name.matches( "dailyReport_08.*\\.txt" ); }} );for ( final File file : files ) { if ( !file.delete() ) { System.err.println( "Can't remove " + file.getAbsolutePath() ); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7240519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/603633/']} | jdg_71284 |
stackexchange | llm_judgeable_groundtruth_similarity | 2804007 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $X$ be a complex Banach space and $A:X\to \mathbb{C}^{n}$ be a continuous linear map. If $B_{X} = \{x\in X\,:\, ||x||\leq 1\}$ is a closed unit ball in $X$, is it true that $A(B_{X})$ is compact in $\mathbb{C}^{n}$? Since every finite rank operator is compact operator, we know that the closure $\overline{A(B_{X})}$ is compact, but I can't verify that the image $A(B_{X})$ itself is compact, although it seems true.
Now provide the response and nothing else.
| If $X$ is not reflexive, then a counterexample can be formed using James' theorem. Since $X$ is not reflexive, there must exist a functional $f \in X^*$ such that $f$ fails to achieve its maximum on the closed unit ball. Take such a functional, and $f(B_X)$ becomes the open ball of $\mathbb{C}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2804007', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/350772/']} | jdg_71285 |
stackexchange | llm_judgeable_groundtruth_similarity | 679271 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
When sending mail, Outlook errors 4.7.1 Service unavailable - try again later . I have installed postfix, dovecot and openDKIM, but OpenDKIM is giving me errors: Mar 30 10:19:32 x opendkim[16762]: can't load key from /etc/ssl/private/mail.x.nl.key: Permission deniedMar 30 10:19:32 x opendkim[16762]: A058440C14: error loading key '_domainkey.x.nl'Mar 30 10:20:27 x opendkim[16762]: can't load key from /etc/ssl/private/mail.x.nl.key: Permission deniedMar 30 10:20:27 x opendkim[16762]: 6A4FF40C14: error loading key '_domainkey.x.nl'Mar 30 11:45:42 x opendkim[16762]: can't load key from /etc/ssl/private/mail.x.nl.key: Permission deniedMar 30 11:45:42 x opendkim[16762]: 0EDB640845: error loading key '_domainkey.x.nl'Mar 30 11:47:48 x postfix/postfix-script[1373]: error: unknown command: 'restart'Mar 30 11:47:48 x postfix/postfix-script[1374]: fatal: usage: postfix start (or stop, reload, abort, flush, check, status, set-permissions, upgrade-configuration)Mar 30 11:51:41 x opendkim[1888]: can't load key from /etc/ssl/private/mail.x.nl.key: Permission deniedMar 30 11:51:41 x opendkim[1888]: BF89E40845: error loading key '_domainkey.x.key** Output from namei -l ** f: /etc/ssl/private/mail.x.nl.keydrwxr-xr-x root root /drwxr-xr-x root root etcdrwxr-xr-x root root ssldrwx--x--- root ssl-cert private-rw-r--r-- opendkim opendkim mail.x.nl.key I have tried setting the .key files to 0755 with owner opendkim:opendkim . Can I solve this?
Now provide the response and nothing else.
| Your permissions are too restrictive. The opendkim user/group does not have access to the /etc/ssl/private folder. Depending on your setup it should be owned by the opendkim group, and the group should also have read/execute permissions on the folder. Also the permissions on your key file are too open. It should have 0600 permission, in no case should it be world readable. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/679271', 'https://serverfault.com', 'https://serverfault.com/users/140316/']} | jdg_71286 |
stackexchange | llm_judgeable_groundtruth_similarity | 3848597 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my bat script, I'm calling another script and passing it a string parameter cscript log.vbs "triggered from folder <foldername> by Eric" The string parameter as you can see contains the name of the folder from which the script is being called. What's the right way to pass this dynamically insert this folder name to the script?
Now provide the response and nothing else.
| If you want the directory where you're currently at, you can get that from %cd% . That's your current working directory. If you're going to be changing your current working directory during the script execution, just save it at the start: set startdir=%cd% then you can use %startdir% in your code regardless of any changes later on (which affect %cd% ). If you just want to get the last component of that path (as per your comment), you can use the following as a baseline: @setlocal enableextensions enabledelayedexpansion @echo off set startdir=%cd% set temp=%startdir% set folder=:loop if not "x%temp:~-1%"=="x\" ( set folder=!temp:~-1!!folder! set temp=!temp:~0,-1! goto :loop ) echo.startdir = %startdir% echo.folder = %folder% endlocal && set folder=%folder% This outputs: C:\Documents and Settings\Pax> testprog.cmd startdir = C:\Documents and Settings\Pax folder = Pax It works by copying the characters from the end of the full path, one at a time, until it finds the \ separator. It's neither pretty nor efficient, but Windows batch programming rarely is :-) EDIT Actually, there is a simple and very efficient method to get the last component name. for %%F in ("%cd%") do set "folder=%~nxF" Not an issue for this situation, but if you are dealing with a variable containing a path that may or may not end with \ , then you can guarantee the correct result by appending \. for %%F in ("%pathVar%\.") do set "folder=%~nxF" | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3848597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407723/']} | jdg_71287 |
stackexchange | llm_judgeable_groundtruth_similarity | 3308841 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that if $x$ is odd, then $x^2$ is odd Suppose $x$ is odd. Dividing $x^2$ by 2, we get: $$\frac{x^2}{2} = x \cdot \frac{x}{2}$$ $\frac{x}{2}$ can be rewritten as $\frac{x}{2} = a + 0.5$ where $a \in \mathbb Z$ . Now, $x\cdot\frac{x}{2}$ can be rewritten as: $$x\cdot\frac{x}{2} = x(a+0.5) = xa + \frac{x}{2}$$ $xa \in \mathbb Z$ and $\frac{x}{2} \notin \mathbb Z$ , hence $xa + \frac{x}{2}$ is not a integer. And since $xa + \frac{x}{2} = \frac{x^2}{2}$ , it follows that $x^2$ is not divisible by two, and thus $x^2$ is odd. Is it correct?
Now provide the response and nothing else.
| Your written proof is correct. FYI, here is another proof technique which, although it's far more than you need in your case as Bill's comment indicates, is somewhat shorter and, perhaps, of some use to you, such as for other more complicated related problems. Since $x$ is odd, this means it has no factors of $2$ . By the Fundamental theorem of arithmetic , $x^2$ has the same prime factors as $x$ , just twice as many of each of them and, thus, also no factor of $2$ . As such, it is also odd. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3308841', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/678074/']} | jdg_71288 |
stackexchange | llm_judgeable_groundtruth_similarity | 3752564 |
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 making a very simple database (mysql) with essentially two types of data, always with a 1 to 1 relationship: Events Sponsor Time (Optional) Location (City, State) Venue (Optional) Details URL Sponsors Name URL Cities will be duplicated often, but is there really much value in having a cities table for such a simple database schema? The database is populated by screen-scraping a website. On this site the city field is populated via selecting from a dropdown, so there will not be mistypes, etc and it would be easy to match the records up with a city table. I'm just not sure there would be much of a point even if the users of my database will be searching by city frequently.
Now provide the response and nothing else.
| Normalize the database now. It's a lot easier to optimize queries on normalized data than it is to normalize a pile of data. You say it's simple now - these things have a tendency to grow. Design it right and you'll get the experience of proper design and some future proofing. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3752564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415194/']} | jdg_71289 |
stackexchange | llm_judgeable_groundtruth_similarity | 23833255 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently when being interviewed, I got this question. Q: Have you written multithreaded applications? A: Yes Q: Care to explain more? A: I used Tasks (Task Parallel library) to carry out some tasks like waiting for some info from internet while loading UI . This improves my application usability. Q: But, just you have used TPL means that you have written an multithreaded application? Me: (Not sure what to say1) So, whats exactly a multi-threaded application? Is it different from using Tasks ?
Now provide the response and nothing else.
| Tasks can be used to represent operations taking place on multiple threads, but they don't have to. One can write complex TPL applications that only ever execute in a single thread. When you have a task that, for example, represents a network request for some data, that task is not going to create additional threads to accomplish that goal. Such a program is (hopefully) asynchronous, but not necessarily mutlithreaded. Parallelism is doing more than one thing at the same time. This may or may not be the result of multiple threads. Let's go with an analogy here. Here is how Bob cooks dinner: He fills a pot of water, and boils it. He then puts pasta in the water. He drains the pasta when its done. He prepares the ingredients for his sauce. He puts all of the ingredients for his sauce in a saucepan. He cooks his sauce. He puts his sauce on his pasta. He eats dinner. Bob has cooked entirely synchronously with no multithreading, asynchrony, or parallelism when cooking his dinner. Here is how Jane cooks dinner: She fills a pot of water and starts boiling it. She prepares the ingredients for her sauce. She puts the pasta in the boiling water. She puts the ingredients in the saucepan. She drains her pasta. She puts the sauce on her pasta. She eats her dinner. Jane leveraged asynchronous cooking (without any multithreading) to achieve parallelism when cooking her dinner. Here is how Servy cooks dinner: He tells Bob to boil a pot of water, put in the pasta when ready, and serve the pasta. He tells Jane to prepare the ingredients for the sauce, cook it, and then serve it over the pasta when done. He waits for Bob and Jane to finish. He eats his dinner. Servy leveraged multiple threads (workers) who each individually did their work synchronously, but who worked asynchronously with respect to each other to achieve parallelism. Of course, this becomes all the more interesting if we consider, for example, whether our stove has two burners or just one. If our stove has two burners then our two threads, Bob and Jane, are both able to do their work without getting in each others way, much. They might bump shoulders a bit, or each try to grab something from the same cabinet every now and then, so they'll each be slowed down a bit , but not much. If they each need to share a single stove burner though then they won't actually be able to get much done at all whenever the other person is doing work. In that case, the work won't actually get done any faster than just having one person doing the cooking entirely synchronously, like Bob does when he's on his own. In this case we are cooking with multiple threads, but our cooking isn't parallelized . Not all multithreaded work is actually parallel work . This is what happens when you are running multiple threads on a machine with one CPU. You don't actually get work done any faster than just using one thread, because each thread is just taking turns doing work. (That doesn't mean multithreaded programs are pointless on one cores CPUs, they're not, it's just that the reason for using them isn't to improve speed.) We can even consider how these cooks would do their work using the Task Parallel Library, to see what uses of the TPL correspond to each of these types of cooks: So first we have bob, just writing normal non-TPL code and doing everything synchronously: public class Bob : ICook{ public IMeal Cook() { Pasta pasta = PastaCookingOperations.MakePasta(); Sauce sauce = PastaCookingOperations.MakeSauce(); return PastaCookingOperations.Combine(pasta, sauce); }} Then we have Jane, who starts two different asynchronous operations, then waits for both of them after starting each of them to compute her result. public class Jane : ICook{ public IMeal Cook() { Task<Pasta> pastaTask = PastaCookingOperations.MakePastaAsync(); Task<Sauce> sauceTask = PastaCookingOperations.MakeSauceAsync(); return PastaCookingOperations.Combine(pastaTask.Result, sauceTask.Result); }} As a reminder here, Jane is using the TPL, and she's doing much of her work in parallel, but she's only using a single thread to do her work. Then we have Servy, who uses Task.Run to create a task that represents doing work in another thread . He starts two different workers, has them each both synchronously do some work, and then waits for both workers to finish. public class Servy : ICook{ public IMeal Cook() { var bobsWork = Task.Run(() => PastaCookingOperations.MakePasta()); var janesWork = Task.Run(() => PastaCookingOperations.MakeSauce()); return PastaCookingOperations.Combine(bobsWork.Result, janesWork.Result); }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/23833255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1360251/']} | jdg_71290 |
stackexchange | llm_judgeable_groundtruth_similarity | 27314663 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Introduction: I have a WebMethod on my ASP.NET page which returns a Person object.One of the fields is Birthday which is a DateTime property. WebMethod [WebMethod]public static Person GetPerson(){ Person p = new Person() { Id = 1, Name = "Test", Birthday = new DateTime(1988, 9, 13) }; return p;} If I make the call using $.ajax() I get the response of the server with the Person object. Ajax call // Class instancevar Ajaxcalls = function () {}_$.extend(Ajaxcalls, { GetPerson: function (label) { var self = label instanceof _$ ? label : $(label); _$.ajax({ url: 'Default.aspx/GetPerson', type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", success: function (data) { console.log(JSON.stringify(data.d)); self.html(new Date(Date.parse(data.d.Birthday))); } }); }}); Result: {"__type":"AjaxTest.Classes.Person","Id":1,"Name":"Test","Birthday":"/Date(590104800000)/"} Problem How do I parse the Birthday [/Date(590104800000)/] to a javascript/jQuery date?I tried new Date(Date.parse(data.d.Birthday)) but it gives me an Invalid date .
Now provide the response and nothing else.
| Use convertToJavaScriptDate() function that does this for you: function convertToJavaScriptDate(value) { var pattern = /Date\(([^)]+)\)/; var results = pattern.exec(value); var dt = new Date(parseFloat(results[1])); return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();} The convertToJavaScriptDate() function accepts a value in \/Date(ticks)\/ format and returns a date string in MM/dd/yyyy format. Inside, the convertToJavaScriptDate() function uses a regular expression that represents a pattern /Date\(([^)]+)\)/ . The exec() method accepts the source date value and tests for a match in the value. The return value of exec() is an array. In this case the second element of the results array ( results[1] ) holds the ticks part of the source date. For example, if the source value is \/Date(836418600000)\/ then results[1] will be 836418600000 . Based on this ticks value a JavaScript Date object is formed. The Date object has a constructor that accepts the number of milliseconds since 1 January 1970. Thus dt holds a valid JavaScript Date object. The convertToJavaScriptDate() function then formats the date as MM/dd/yyyy and returns to the caller. You can use the convertToJavaScriptDate() function as shown below: options.success = function (order) { alert("Required Date : " + convertToJavaScriptDate(order.RequiredDate) + ", Shipped Date : " + convertToJavaScriptDate(order.ShippedDate));}; Although the above example uses date in MM/dd/yyyy format, you can use other formats also once Date object is constructed. reference : Link | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27314663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3157202/']} | jdg_71291 |
stackexchange | llm_judgeable_groundtruth_similarity | 6110975 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using JDBC to connect to a DB. Since the network was slow, i could get the connection after some 2 or 3 retry manually. Is it possible to retry the connection automatically if connection fails? I am using SQLServer 2008 database.Thanks
Now provide the response and nothing else.
| A bit decent connection pool is already configureable to do so, for example BoneCP . Most do even do it by default. If you don't use a connection pool but just the basic DriverManager#getConnection() approach, then you have to re-execute it yourself in a while loop as long as the Connection is null . Here's a basic kickoff example: Connection connection = null;while (connection == null) { try { connection = DriverManager.getConnection(url, username, password); } catch (SQLException e) { logger.info("Connecting failed, retrying..."); }}return connection; This can of course be optimized more with bit longer pauses in between and by setting a maximum retry count, etcetera. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6110975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/236896/']} | jdg_71292 |
stackexchange | llm_judgeable_groundtruth_similarity | 3177364 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to destroy a session when user leave from a particular page. I use session_destroy() on the end of the page but its not feasible for me because my page has pagination. My page is: abc.php?page=1 or abc.php?page=2 or abc.php?page=3 . So, I need to destroy a session when a user leaves from abc.php page. How can I do it without using a cookie?
Now provide the response and nothing else.
| Doing something when the user navigates away from a page is the wrong approach because you don't know if the user will navigate to a whole different page (say contact.php for the sake of the argument) or he/she will just go to the next page of abc.php and, as Borealid pointed out, you can't do it without JS. Instead, you could simply add a check and see if the user comes from abc.php: First, in your abc.php file set a unique variable in the $_SESSION array which will act as a mark that the user has been on this page: $_SESSION['previous'] = basename($_SERVER['PHP_SELF']); Then, add this on all pages, before any output to check if the user is coming from abc.php: if (isset($_SESSION['previous'])) { if (basename($_SERVER['PHP_SELF']) != $_SESSION['previous']) { session_destroy(); ### or alternatively, you can use this for specific variables: ### unset($_SESSION['varname']); }} This way you will destroy the session (or specific variables) only if the user is coming from abc.php and the current page is a different one. I hope I was able to clearly explain this. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3177364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/87238/']} | jdg_71293 |
stackexchange | llm_judgeable_groundtruth_similarity | 36070031 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My Python project imports pytest 2.9.0 fine without any issues. I want to create a new empty directory that will last only the life of the test session. I see that pytest offers temporary directory support: https://pytest.org/latest/tmpdir.html You can use the tmpdir fixture which will provide a temporary directory unique to the test invocation, created in the base temporary directory. tmpdir is a py.path.local object which offers os.path methods and more. Here is an example test usage: The source-code for pytest shows that def tmpdir is a global/module function: https://pytest.org/latest/_modules/_pytest/tmpdir.html However my test file fails: import pytest# ...def test_foo(): p = pytest.tmpdir() With error: AttributeError: 'module' object has no attribute 'tmpdir' Doing from pytest import tmpdir fails with: ImportError: cannot import name tmpdir
Now provide the response and nothing else.
| UPDATE: Use tmp_path instead of tmpdir . tmp_path is a pathlib.Path / pathlib2.Path . tmpdir is a py.path (Actually LocalPath ), which has offered syntax very similar to pathlib.Path. See pytest issue . Usage of py.path is no longer recommended by the developers. Syntax is similar, eg: def test_something_else(tmp_path): #create a file "myfile" in "mydir" in temp directory f1 = tmp_path / "mydir/myfile" f1.parent.mkdir() #create a directory "mydir" in temp folder (which is the parent directory of "myfile" f1.touch() #create a file "myfile" in "mydir" #write to file as normal f1.write_text("text to myfile") assert f1.read_text() == "text to myfile" ORIGINAL: I looked into it an also found the behaviour peculiar, and I summarize what I learned below, for others who don't find it so intuitive. tmpdir is a predefined fixture in pytest similar to how setup is defined here: import pytestclass TestSetup: def __init__(self): self.x = [email protected]()def setup(): return TestSetup()def test_something(setup) assert setup.x == 4 Thus tmpdir is a fixed name defined in pytest which is passed on to your testfunction if you have it as an argument name. Example usage: def test_something_else(tmpdir): #create a file "myfile" in "mydir" in temp folder f1 = tmpdir.mkdir("mydir").join("myfile") #create a file "myfile" in temp folder f2 = tmpdir.join("myfile") #write to file as normal f1.write("text to myfile") assert f1.read() == "text to myfile" This works when you run it using pytest, eg running py.test test_foo.py in the terminal. The file generated in this way has read and write access, and can be viewed later in your systems temporary folder (for me this was /tmp/pytest-of-myfolder/pytest-1/test_create_file0 ) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36070031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159145/']} | jdg_71294 |
stackexchange | llm_judgeable_groundtruth_similarity | 420979 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I built a prototype keyboard/sound synthesizer using a chain of 13 astable multivibrator circuits whose outputs are connected to an audio amplifier chip (LM386) and speaker, all powered off a 9V DC battery. Each individual circuit gets tuned to one of the 13 frequencies in a musical octave (C5, C#, D, etc. up to C6) by varying a fine-tune trimpot that is in series with specific resistor values and which get the oscillation into the ballpark frequency. The oscillation is the classic BJT astable multivibrator you can see in Figure 1 here and which is explained in this article . The prototype stays correctly in tune for a short period (up to a day). You can hear what it sounds like here. (Safe to start at 0:49s -- Wadsworth's constant ;) ) What I can't figure out is why the circuit appears to get spontaneously detuned, i.e. one or more of the individual circuits end up with frequencies that are different from what they were tuned to (checked against an o'scope and a reference piano). The frequency deviation of the detuning is typically 2-5%, which is audibly noticeable (e.g. C5 at 523Hz might wander to 540Hz or 510Hz). Interestingly, the detuning never occurs while playing. But several hours afterwards, the keys no longer sound the same. I had originally thought maybe the trimmer pots were mechanically relaxing by themselves. To eliminate this I replaced the trimmer pots to try to "lock in" the specific frequencies based on resistor values alone so that no variability was left in the design. But the de-tuning problem persists even after replacing the trimpots with fixed resistor values. Before: 13-key analog synthesizer with fixed resistor values Resolution: Thanks all for the useful feedback, digital design ideas, and historical context to better understand the challenges of a pure analog design. All the answers were excellent. I've accepted ToddWilcox's answer as I get from it that (a) detuning is an expected part of pure analog designs, (b) the artistry lies in how to establish a slick way of tuning the instrument quickly. To solve the immediate problem, I've put trimmer pots (1-2K ohms) back in the design to give 2-5% tuneability to each key. It takes a couple of minutes at the start of playing to tune up the 13 oscillators, after which they stay in tune for several hours at a time. See new image below. Will post the results of the experiments using wall-wart, fresh batteries. The digital designs (using digital divider and/or 555 timer chips) are interesting, and would potentially compress the size significantly. Future updates can be found at the project page here . After: 13-key analog synthesizer with trimmer pots (1-2k ohm) for tune-ability
Now provide the response and nothing else.
| What I can't figure out is why the circuit appears to get spontaneously detuned, i.e. one or more of the individual circuits end up with frequencies that are different from what they were tuned to (used an oscope, and then a reference piano). Temperature changes, as mentioned in the other answer. I'm adding an answer here because, as a musician, I prefer the sound of oscillators that are 100% analog over a design based on: a circuit that uses as single higher frequency oscillator based upon a close tolerance crystal. Then the use of digital counters are used to divide this frequency down to the desired frequency for each note in the scale. EEs on this Stack might comment endlessly that I scientifically couldn't be able to hear the difference. Believe me when I say my wallet dearly wishes that I couldn't hear the difference, but I can, and it's not subtle. Anyway, major 100% analog synth manufacturers such as Moog Music and Sequential Circuits (formerly DSI) have solved this problem in different ways over the years. The old-school solution requires user intervention and frequent tuning. The original Moog Minimoog (AKA "Model D" after its most popular variant) had a crystal oscillator circuit built in that was not part of the signal path, but would create a stable 440 Hz tone. You turn on the 440Hz crystal tone, then play an A on the keyboard, and then turn the Master Tuning knob to re-tune the synth by ear. This was practical because the Minimoog was/is (it's been reissued with some technological improvements) a monosynth. Once you've tuned the bank of three oscillators all together, you're done. The Minimoog also has several adjustment trim pots to calibrate it to the various control voltages, which includes the ability to make sure the different oscillators are in tune and track with each other. The Sequential Circuits Prophet 5 is a different thing. All of the audio generation and signal path are analog and prone to drift, and in a way, a similar process is used as to the Minimoog for tuning, but instead of the user listening to a crystal oscillator tone and manually tuning the analog oscillators, the Prophet 5 featured microprocessor controlled automatic tuning calibration. According to one source, tuning took about 15 seconds after the Tune button was pressed. One reason why an automatic tuning system was necessary for the Prophet 5 was that instead of being a monophonic 3 oscillator synth, it was polyphonic with 5 voices of 2 oscillators each, for a total of ten oscillators. As drift could happen in the middle of a show, a fairly quick way to re-tune the synth was required to make it useful to musicians. So, what I'm suggesting is if you are building your own oscillators in order to get that 100% analog tone, you'll want to come up with some tuning mechanism. You also might have to play with oscillator designs to try to make them as thermally stable as possible. If I were heading down this road, I would start with the Moog method and make sure I know how to design a master tune knob that I can use to quickly re-tune the synth and work to get a design that is stable for at least an hour in a typical home room. Then I might look at "graduating" to tacking on a microprocessor that can electrically compare the oscillators to the reference crystal and automatically adjust the tuning knob. Today, both Sequential Circuits and Moog Music have real-time microprocessor-controlled tuning adjustment in the Prophet 6 and Model D Reissue products, and Sequential even offers an additional control which lets you control how well the microprocessor maintains the tuning, to get some vintage-style oscillator drift in the sound. More about the Prophet 5 design One way the oscillators for the Prophet 5 were made more stable was by using analog integrated circuits that had as much of a complete oscillator as possible on one chip. That meant that all the components on the chip changed temperature together (at least closer together than discrete components). There was also "on-chip temperature compensation circuitry". I'm not sure exactly what that involves, but my guess is that it's circuit design that uses on-chip components to make actual voltage drifts due to chip temperature "cancel out", as much as possible. Page 2-19 of the Prophet 5 Service Manual is very interesting on this topic: https://medias.audiofanzine.com/files/sequentialcircuitsprophet-5servicemanual-text-470674.pdf And I found an interesting paper on analog temperature compensation circuit designs for crystal oscillators: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.11.2410&rep=rep1&type=pdf | {} | {'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/420979', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/15238/']} | jdg_71295 |
stackexchange | llm_judgeable_groundtruth_similarity | 101174 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Python there is a really neat function called zip which can be used to iterate through two lists at the same time: list1 = [1, 2, 3]list2 = ["a", "b", "c"]for v1, v2 in zip(list1, list2): print v1 + " " + v2 The above code should produce the following: 1 a2 b3 c I wonder if there is a method like it available in .Net? I'm thinking about writing it myself, but there is no point if it's already available.
Now provide the response and nothing else.
| Update: It is built-in in C# 4 as System.Linq.Enumerable.Zip Method Here is a C# 3 version: IEnumerable<TResult> Zip<TResult,T1,T2> (IEnumerable<T1> a, IEnumerable<T2> b, Func<T1,T2,TResult> combine){ using (var f = a.GetEnumerator()) using (var s = b.GetEnumerator()) { while (f.MoveNext() && s.MoveNext()) yield return combine(f.Current, s.Current); }} Dropped the C# 2 version as it was showing its age. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/101174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16047/']} | jdg_71296 |
stackexchange | llm_judgeable_groundtruth_similarity | 17969515 |
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 figured out a a problem in my Code. First the code: public class Main { /** * @param args */ public static void main(String[] args) { String[] blablubb = { "a", "b", "c" }; for(String s : blablubb) { s = "over"; } printArray(blablubb); for (int i = 0; i < blablubb.length; i++) { blablubb[i] = "over"; } printArray(blablubb); } public static void printArray(String[] arr) { for( String s : arr ) { System.out.println(s); } }} The output is: abcoveroverover I assumed the first loop would also overwrite the String in the array. So the output would be over in any case. It seems it creates a copy of the value instead creating a reference.I never perceived this. Am I doing it wrong? Is there an option to create a reference instead? //Edit:Seems like everybody knows about that except me. I'm from C background and doesn't pay enough attention to the term reference which is very different to C. Fortunately it took me just 10 minutes to figure this out (this time).
Now provide the response and nothing else.
| This: for (String s : blablubb) { s = "over";} Is equal to this: for (int i = 0; i < blablubb.length; i++) { String s = blablubb[i]; s = "over";} This creates a temporary String with a copy of the value from array and you change only the copy. That's why blablubb[] content stays untouched. If you want to change values in the array, just use your second option: for (int i = 0; i < blablubb.length; i++) { blablubb[i] = "over";} And, by the way, you can print an array with just one line: System.out.println(Arrays.toString(blablubb)); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17969515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/772883/']} | jdg_71297 |
stackexchange | llm_judgeable_groundtruth_similarity | 28147076 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From Javadoc: Queue implementations generally do not allow insertion of null elements, although some implementations, such as LinkedList, do not prohibit insertion of null. Even in the implementations that permit it, null should not be inserted into a Queue , as null is also used as a special return value by the poll method to indicate that the queue contains no elements. How should it be interpreted? We can insert the null value into the LinkedList but couldn't insert it into the Queue , despite implementing Queue by LinkedList .
Now provide the response and nothing else.
| It means that if you insert a null to a LinkedList , if you call poll and get null , you can't tell is the Queue is empty or if a null element was at the head of the Queue . Therefore, you can insert null to a LinkedList , but you should avoid doing so if you intend to use that LinkedList as a Queue . If you look at the implementation of poll() : public E poll() { if (size==0) return null; return removeFirst(); // if the first element is null, `removeFirst()` // returns null, and you might mistakenly assume // the Queue is empty} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28147076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2786156/']} | jdg_71298 |
stackexchange | llm_judgeable_groundtruth_similarity | 40429917 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Python, how could you check if the type of a number is an integer without checking each integer type, i.e., 'int' , 'numpy.int32' , or 'numpy.int64' ? I thought to try if int(val) == val but this does not work when a float is set to an integer value (not type). In [1]: vals = [3, np.ones(1, dtype=np.int32)[0], np.zeros(1, dtype=np.int64)[0], np.ones(1)[0]]In [2]: for val in vals: ...: print(type(val)) ...: if int(val) == val: ...: print('{} is an int'.format(val))<class 'int'>3 is an int<class 'numpy.int32'>1 is an int<class 'numpy.int64'>0 is an int<class 'numpy.float64'>1.0 is an int I want to filter out the last value, which is a numpy.float64 .
Now provide the response and nothing else.
| You can use isinstance with a tuple argument containing the types of interest. To capture all python and numpy integer types use: isinstance(value, (int, np.integer)) Here is an example showing the results for several data types: vals = [3, np.int32(2), np.int64(1), np.float64(0)][(e, type(e), isinstance(e, (int, np.integer))) for e in vals] Result: [(3, <type 'int'>, True), (2, <type 'numpy.int32'>, True), (1, <type 'numpy.int64'>, True), (0.0, <type 'numpy.float64'>, False)] A second example which is true only for int and int64: [(e, type(e), isinstance(e, (int, np.int64))) for e in vals] Result: [(3, <type 'int'>, True), (1, <type 'numpy.int32'>, False), (0, <type 'numpy.int64'>, True), (0.0, <type 'numpy.float64'>, False)] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40429917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3585557/']} | jdg_71299 |
stackexchange | llm_judgeable_groundtruth_similarity | 9238552 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I read some stuff on Win32 and how the message loop works, and there's something that is still unclear to me: What exactly is stored in the message queue? The integer value that corresponds to a message ( WM_COMMAND , WM_CREATE , etc) or a pointer to a MSG structure containing the message integer value and other stuff like wParam , lParam , etc?
Now provide the response and nothing else.
| To answer your question narrowly, each message in the queue stores, at the least, a window handle to which the message is directed, the message code, wParam and lParam, as you already correctly noted, the time when the message was posted, that you retrieve with GetMessageTime() , for UI messages, the position of the cursor when the message was posted (see GetMessagePos() ). Note that not all messages are actually stored in the queue. Messages that are sent with SendMessage() to a window from the thread that owns the window are never stored; instead, a receiver window's message function is called directly. Messages sent from other threads are stored until processed, and the sending thread blocks until the message is replied to, either by exiting the window function or explicitly with a call to ReplyMessage() . The API function InSendMessage() helps figure out whether the windows function is processing a message sent from another thread. Messages that you or the system post are stored in the queue, with some exceptions. WM_TIMER messages are never actually stored ; instead, GetMessage() constructs a timer message if there are no other messages in the queue and a timer has matured. This means that, first, the timer messages have the lowest dequeuing priority, and, second, that multiple messages from a short period timer would never overflow queue, even if GetMessage() is not called for a while. As a result, a single WM_TIMER message is sent for the given timer, even if the timer has elapsed multiple times since the last WM_TIMER message from that timer has been processed. Similarly, WM_QUIT is also not stored, and rather only flagged. GetMessage() pretends to have retrieved the WM_QUIT after the queue has been exhausted, and this is the last message it retrieves. Another example is the WM_PAINT message (hat tip to @cody-gray for reminding about this). This message is also simulated when any part of the window¹ is marked as "dirty" and needs repainting. This is also a low-priority message, made so that multiple invalidated regions in a window are repainted all at once when the queue becomes empty, to reduce responsiveness of the GUI and reduce flicker. You can force an immediate repaint by calling UpdateWindow() . This function acts like SendMessage() , in the sense that it does not return until the exposed part of the window is redrawn. This function does not send a WM_PAINT to the window if the invalid region of that window is empty, as an obvious optimization. Probably, there are other exceptions and internal optimizations. Messages posted with PostMessage() end up in the queue of a thread that owns the window to which the message is posted. In what form the messages are stored internally, we do not know, and we do not care. Windows API abstracts that completely. The MSG structure is filled in memory you pass to GetMessage() or PeekMessage() . You do not need to know or to worry about the details of internal implementation beyond those documented in Windows SDK guides. ¹ I do not know how exactly WM_PAINT and WM_TIMER are prioritized relative to each other. I assume WM_PAINT has a lower priority, but I may be wrong. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9238552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1091856/']} | jdg_71300 |
stackexchange | llm_judgeable_groundtruth_similarity | 43874281 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
below code works fine but if I replace push @array,{%hash} with push @array,\%hash then it doesn't. Can someone please help me understand the difference. I believe {%hash} refers to an anonymous hash. Does it mean a anonymous hash lives longer than a reference to a named hash ( \%hash ). use strict;use warnings;use Data::Dumper;my @array;my %hash;%hash = ('a' => 1, 'b' => 2, 'c' => 3,);push @array,{%hash};%hash = ('e' => 1, 'f' => 2, 'd' => 3,);push @array,{%hash};print Dumper \@array; output $VAR1 = [ { 'c' => 3, 'a' => 1, 'b' => 2 }, { 'e' => 1, 'd' => 3, 'f' => 2 } ]; UPDATE Below is the actual code I am working on. I think in this case taking copy of the reference is the only possible solution I believe. Please correct me if I am wrong. use Data::Dumper;use strict;use warnings;my %csv_data;my %temp_hash;my @cols_of_interest = qw(dev_file test_file diff_file status);<DATA>; #Skipping the headerwhile (my $row = <DATA>) { chomp $row; my @array = split /,/,$row; @temp_hash{@cols_of_interest} = @array[3..$#array]; push @{$csv_data{$array[0]}{$array[1] . ':' . $array[2]}},{%temp_hash};}print Dumper \%csv_data;__DATA__dom,type,id,dev_file,test_file,diff_file,statusA,alpha,1234,dev_file_1234_1.txt,test_file_1234_1.txt,diff_file_1234_1.txt,passA,alpha,1234,dev_file_1234_2.txt,test_file_1234_2.txt,diff_file_1234_2.txt,failA,alpha,1234,dev_file_1234_3.txt,test_file_1234_3.txt,diff_file_1234_3.txt,passB,beta,4567,dev_file_4567_1.txt,test_file_4567_1.txt,diff_file_4567_1.txt,passB,beta,4567,dev_file_4567_2.txt,test_file_4567_2.txt,diff_file_4567_2.txt,failC,gamma,3435,dev_file_3435_1.txt,test_file_3435_1.txt,diff_file_3435_1.txt,passD,hexa,6768,dev_file_6768_1.txt,test_file_6768_1.txt,diff_file_6768_1.txt,fail
Now provide the response and nothing else.
| Both \%hash and {%hash} create references , but they reference two different things. \%hash is a ref to %hash . If dereferenced, its values will change with the values in %hash . {%hash} creates a new anonymous hash reference from the values in %hash . It creates a copy . It's the simplest way of creating a shallow copy of a data structure in Perl. If you alter %hash , this copy is not affected. How long a variable lives has nothing to do with what kind the variable is, or how it was created. Only the scope is relevant for that. References in Perl are a special case here, because there is an internal ref counter that keeps track of references to a value, so that it is kept alive if there are still references around somewhere even if it goes out of scope. That's why this works: sub frobnicate { my %hash = ( foo => 'bar' ); return \%hash;} If you want to disassociate the reference from the initial value, you need to turn it into a weak reference via weaken from Scalar::Util . That way, the ref count will not be influenced by it, but it will still be related to the value, while a copy would not be. See perlref and perlreftut for more information on references. This question deals with how to see the ref count. A description for that is also available in the chapter Reference Counts and Mortality in perlguts . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43874281', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1878947/']} | jdg_71301 |
stackexchange | llm_judgeable_groundtruth_similarity | 80157 |
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:
I am studying machine learning, and I have encountered the concept of bias and variance . I am a university student and in the slides of my professor, the bias is defined as: $bias = E[error_s(h)]-error_d(h)$ where $h$ is the hypotesis and $error_s(h)$ is the sample error and $error_d(h)$ is the true error . In particular, it says that we have bias when the training set and the test set are not independent. After reading this, I was trying to get a little deeper in the concept, so I searched on internet and found this video , where it defines the bias as the impossibility to capture the true relationship by a machine learning model . I don't understand, are the two definition equal or the two type of bias are different? Together with this, I am also studying the concept of variance , and in the slides of my professor it is said that if I consider two different samples from the sample, the error may vary even if the model is unbiased , but in the video I posted it says that the variance is the difference in fits between training set and test set . Also in this case the definitions are different, why?
Now provide the response and nothing else.
| What are Bias and Variance? Let's start with some basic definitions: Bias : it's the difference between average predictions and true values. Variance : it's the variability of our predictions, i.e. how spread out your model predictions are. They can be understood from this image: ( source ) What to do about bias and variance? If your model suffers from a bias problem you should increase its power. For example, if the prediction of your neural network is not good enough, add more parameters, add a new layer making it deeper, etc. If your model suffers from a variance problem instead, the best possible solution is coming from ensembling. Ensembles of Machine Learning models can significantly reduce the variance in your predictions. The Bias-Variance tradeoff If your model is underfitting, you have a bias problem, and you should make it more powerful. Once you made it more powerful though, it will likely start overfitting, a phenomenon associated with high variance. For that reason, you must always find the right tradeoff between fighting the bias and the variance of your Machine Learning models. ( source ) Learning how to do that is more an art than a science! | {} | {'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/80157', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/84229/']} | jdg_71302 |
stackexchange | llm_judgeable_groundtruth_similarity | 11822302 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two tables - one containing Address and another containing Photographs. The only common field between them is the PersonID. These were mapped to two POJO Classes Address and Photo. I was able to fetch details in these tables by creating criteria and adding restrictions on the fields . How should we write a join on the two tables. Is it possible to get the result as two objects -Address and Photo. I want to do a left join so that i can get records of persons without photos as well.I have read that this is possible only using hql but Can this be done using criterias as well?
Now provide the response and nothing else.
| You can easily write HQL query that will return result as two objects using Theta Join (as Adrian noted). Here is an example: String queryText = "select address, photo from Address address, Photo photo " + " where address.personID=photo.personId";List<Object[]> rows = session.createQuery(queryText).list();for (Object[] row: rows) { System.out.println(" ------- "); System.out.println("Address object: " + row[0]); System.out.println("Photo object: " + row[1]);} As you can see query returns list of Object[] arrays that represents each fetched row. First element of this array will contain one obejct and second element - another. EDIT: In case of left join I think you need to use native SQL query (not HQL query). Here how you can do this: String queryText = "select address.*, photo.* from ADDRESS address left join PHOTO photo on (address.person_id=photo.person_id)";List<Object[]> rows = sess.createSQLQuery(queryText) .addEntity("address", Address.class) .addEntity("photo", Photo.class) .list(); This should work for your case. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11822302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1381202/']} | jdg_71303 |
stackexchange | llm_judgeable_groundtruth_similarity | 195016 |
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 am looking for the derivation of Ohm's Law, i.e., $V$ is directly proportional to $I$ . Can someone help me with it?
Now provide the response and nothing else.
| Ohm's Law is not a construct which can be derived. It is essentially a generalized observation. It is only useful for a few materials (conductors and medium resistivity), and even then virtually all of those materials show deviations from the ideal, such as temperature coefficients and breakdown voltage limits. Rather, Ohm's Law is an idealization of the observed behavior of these materials. As the saying goes, "All models are wrong. Some models are useful." In this case, Ohm's Law is extraordinarily useful, but that doesn't make it universal. Semiconductors, for instance, do not follow Ohm's Law in any large sense, and look how widespread their use is. As originally discovered and formulated, there was a great deal of wishful thinking involved. There was no understanding of the forces involved, and there was no real definition, for instance, of voltage or current. Nonetheless, it was determined that a self-consistent set of values was possible (you can define different battery chemistries as producing specific voltages, and get consistent behavior of galvanometers - as long as you're willing to accept experimental error). Over time, standards were set and more objective measures discovered, such as the quantity of electrons in a coulomb, so that a current of 1 amp can be unambiguously measured) Eventually, a very good understanding of the behavior of electrons (and holes) in conductors was reached, and that understanding is generally, for a wide range of useful conditions, expressible as Ohm's Law. But it is not derived. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/195016', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/86265/']} | jdg_71304 |
stackexchange | llm_judgeable_groundtruth_similarity | 162836 |
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'm trying to understand why John Nash's 1950 2-page paper that was published in PNAS was such a big deal. Unless I'm mistaken, the 1928 paper by John von Neumann demonstrated that all n-player non-cooperative and zero-sum games possess an equilibrium solution in terms of pure or mixed strategies. From what I understand, Nash used fixed point iteration to prove that non-zero-sum games would also have the analogous result. Why was this such a big deal in light of the earlier work by von Neumann? There are two references I provide that are good: One is this discussion on simple proofs of Nash's theorem and this one is a very well done (readable and accurate) survey of the history in PNAS.
Now provide the response and nothing else.
| I think von Neumann dealt with the case $n=2$, and it was by no means obvious how to extend the concept of equilibrium for the general case and prove that it always exists. More precisely, $n$ players before Nash were reduced to the $n=2$ case by partioning the players into two groups in all possible ways. Once you regard several players as a single player, they are meant to cooperate as they must act like a single player. Nash is very clear about this in his 1951 Annals paper: Von Neumann and Morgenstern have developed a very fruitful theory of two-person zero-sum games in their book Theory of Games and Economic Behavior. This book also contains a theory of $n$-person games of a type which we would call cooperative. This theory is based on an analysis of the interrelationships of the various coalitions which can be formed by the players of the game. Our theory, in contradistinction, is based on the absence of coalitions in that it is assumed that each participant acts independently, without collaboration or communication with any of the others. The notion of an equilibrium point is the basic ingredient in our theory. This notion yields a generalization of the concept of the solution of a two-person zero-sum game. It turns out that the set of equilibrium points of a two-person zero-sum game is simply the set of all pairs of opposing "good strategies." In the immediately following sections we shall define equilibrium points and prove that a finite non-cooperative game always has at least one equilibrium point. We shall also introduce the notions of solvability and strong solvability of a non-cooperative game and prove a theorem on the geometrical structure of the set of equilibrium points of a solvable game. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/162836', 'https://mathoverflow.net', 'https://mathoverflow.net/users/31429/']} | jdg_71305 |
stackexchange | llm_judgeable_groundtruth_similarity | 38023025 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I try to insert block elements in a flex container, they all stay on the same line as if they were inline-blocks. I would like the two first div's to be on the same line, and the last one to be on a second line. Sadly, that doesn't seem to work. Anyone have any idea ? <div style="display: flex"> <div style="display: inline-block"> This is an inline block element </div> <div style="display: inline-block"> This is an inline block element </div> <div style="display: block"> This is a block element </div></div>
Now provide the response and nothing else.
| An initial setting of a flex container is flex-wrap: nowrap . This means flex items are forced to remain in a single line. You can override the default with flex-wrap: wrap . The display value of flex items is ignored in flex layout. A flex container, which is an element with display: flex or display: inline-flex , establishes a flex formatting context . Although similar to a block formatting context , there are differences. One difference is that children of a flex container ignore the display property. Another difference is that, in a flex container, margins don't collapse, and the float and clear properties have no effect. A flex container also comes with several default settings. Among them: justify-content: flex-start - flex items will stack at the start of the line flex-shrink: 1 - flex items are allowed to shrink and will not overflow the container align-items: stretch - flex items will expand to cover the cross-size of the container flex-direction: row - flex items will align horizontally flex-wrap: nowrap - flex items are forced to stay in a single line Note the last two items. Flex items will line up in a row and cannot wrap. If you want to have two flex items on the first line, and a third item on the second line, allow the container to be multi-line with flex-wrap: wrap . .container { display: flex; flex-wrap: wrap;}.box { flex: 0 0 45%; height: 50px; margin: 5px; background-color: lightgreen; border: 1px solid #ccc;} <div class="container"> <div class="box"></div> <div class="box"></div> <div class="box"></div></div> Also, if you want flex containers to display inline, use display: inline-flex not display: flex . These are comparable to display: inline-block and display: block . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38023025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6461432/']} | jdg_71306 |
stackexchange | llm_judgeable_groundtruth_similarity | 2586091 |
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 thinking was that if gangster A shoots gangster B, then gangster B will also shoot gangster A since they are the closest together, forming a pair. Since 55 is odd, then one must survive since 55 is 1 mod 2.
Now provide the response and nothing else.
| The pair of gangsters with lowest pairwise distance will shoot each other. If some other gangster shoots any of those two, then there will be at most $52$ bullets aimed at the remaining $53$ gangsters, and hence at least one will survive. If no other gangster shoots any of those two, the problem is reduced to the case of $53$ gangsters and we proceed by induction. At this point, it boils down to checking that the case for $3$ gangsters always ends up with one alive. | {} | {'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/2586091', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/376476/']} | jdg_71307 |
stackexchange | llm_judgeable_groundtruth_similarity | 55793 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've read the post Multiple Subnets in a VLAN and am wondering about the possible conflicts when using several subnets in a VLAN. The recommended design is of course put a IP subnet in a VLAN. If I configure several IP subnets in a VLAN, e.g. some hosts in 10.1.1.0/24, some hosts in 10.2.2.0/24 and both under a VLAN, will these two networks interrupt each other? If there's actually no impact then why is such a design not preferred?
Now provide the response and nothing else.
| This is possible however: you still need a router to have the hosts from one subnet to communicate with the hosts in the other subnet in a modern switched environment there's no collision, so this is not a issue, but you still have broadcast. All hosts will see the broadcasts from both domains which take some part of the bandwidth. Access Control Lists are bounded to interfaces. So to use ACL to limit traffic between the subnets you are limited to a single interface to place ingress / outgress rules; this is stil doable but more limited any host can potentially hear some traffic pertaining to the other subnet. That's a security issue. when troubleshooting a network issue, you may have to sniff traffic (with utility like tcpdump or wireshark), having several IP networks mixed render this or other troubleshooting more difficult overall, this is more complex to maintain and less scalable than having one subnet per vlan. Basically there's rarely a benefit in doing so, even if you can encounter some corner case where it is the simplest solution (or a temporary dirty fix, but in IT, a temporary setup often last years....). | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/55793', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/53815/']} | jdg_71308 |
stackexchange | llm_judgeable_groundtruth_similarity | 13128296 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
TABLEA JobCode Job1 Job2 Job3 zip------- ---- ---- ---- ----------F F S NULL 90030F F S NULL 90031F F S NULL 90031F F S NULL 90034F F NULL 90034F F S NULL 90034F F S NULL 90034F F NULL 90034F F S NULL 90035F F NULL 90035-4640 EXPECTED RESULTS: JobCode Job1 Job2 Job3 zip------- ---- ---- ---- ----------F F S NULL 90034F F NULL 90034F F S NULL 90034F F S NULL 90034F F NULL 90034F F S NULL 90031F F S NULL 90031F F S NULL 90030F F S NULL 90035F F NULL 90035-4640 Those with the SAME Zip should be ON top, then the rest follows. ORDER BY Zip does not work because it DOES sort by ZIP, and NOT by number of occurence Using SQL Server 08
Now provide the response and nothing else.
| SQL Server 2008 using COUNT() OVER select *, c = count(1) over (partition by zip)from tblorder by c desc; If you don't need to see the additional column, then you can move the COUNT() OVER clause into the ORDER BY clause. select JobCode, Job1, Job2, Job3, zipfrom tblorder by count(1) over (partition by zip) desc; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13128296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1778151/']} | jdg_71309 |
stackexchange | llm_judgeable_groundtruth_similarity | 20673625 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using Android Gradle plugin 0.7.0 with the following build.gradle : buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.7.0' }}apply plugin: 'android'repositories { maven { url "https://android-rome-feed-reader.googlecode.com/svn/maven2/releases" } maven { url "http://dl.bintray.com/populov/maven" } mavenCentral()}android { compileSdkVersion 19 buildToolsVersion '18.1.1' defaultConfig { minSdkVersion 9 targetSdkVersion 19 } buildTypes { release { runProguard true proguardFile getDefaultProguardFile('proguard-android-optimize.txt') } } productFlavors { defaultFlavor { proguardFile 'proguard-rules.txt' } } sourceSets { instrumentTest.setRoot('src/instrumentTest') }}configurations { apt}ext.androidAnnotationsVersion = '2.7.1';dependencies { compile 'com.android.support:support-v4:18.0.0' compile 'com.viewpagerindicator:library:2.4.1@aar' compile 'com.google.code.android-rome-feed-reader:android-rome-feed-reader:1.0.0-r2' compile 'org.jdom:jdom:1.1.1-android-fork' apt "com.googlecode.androidannotations:androidannotations:${androidAnnotationsVersion}" compile "com.googlecode.androidannotations:androidannotations-api:${androidAnnotationsVersion}" compile 'com.google.code.gson:gson:2.2.4' compile 'com.j256.ormlite:ormlite-android:4.47' compile 'com.j256.ormlite:ormlite-core:4.47' compile 'org.springframework.android:spring-android-core:1.0.1.RELEASE' compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE' compile 'com.prolificinteractive:actionbarsherlock:4.3.1@aar' compile 'com.google.code.geocoder-java:geocoder-java:0.15' compile files('libs/CWAC-Pager.jar')}android.applicationVariants.all { variant -> aptOutput = file("${project.buildDir}/source/apt_generated/${variant.dirName}") println "****************************" println "variant: ${variant.name}" println "manifest: ${variant.processResources.manifestFile}" println "aptOutput: ${aptOutput}" println "****************************" variant.javaCompile.doFirst { println "*** compile doFirst ${variant.name}" aptOutput.mkdirs() variant.javaCompile.options.compilerArgs += [ '-processorpath', configurations.apt.getAsPath(), '-AandroidManifestFile=' + variant.processResources.manifestFile, '-s', aptOutput ] }} gives the error Duplicate files copied in APK META-INF/LICENSE.txt : WARNING: Dependency commons-logging:commons-logging:1.0.4 is ignored for defaultFlavorDebug as it may be conflicting with the internal version provided by Android. In case of problem, please repackage it with jarjar to change the class packagesWARNING: Dependency commons-logging:commons-logging:1.0.4 is ignored for defaultFlavorRelease as it may be conflicting with the internal version provided by Android. In case of problem, please repackage it with jarjar to change the class packagesCreating properties on demand (a.k.a. dynamic properties) has been deprecated and is scheduled to be removed in Gradle 2.0. Please read http://gradle.org/docs/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html for information on the replacement for dynamic properties.Deprecated dynamic property: "aptOutput" on "com.android.build.gradle.internal.api.ApplicationVariantImpl_Decorated@5705013c", value: "/Users/david/Developer...".****************************variant: defaultFlavorDebugmanifest: /Users/david/Developer/.../build/manifests/defaultFlavor/debug/AndroidManifest.xmlaptOutput: /Users/david/Developer/.../build/source/apt_generated/defaultFlavor/debug****************************Deprecated dynamic property "aptOutput" created in multiple locations.****************************variant: defaultFlavorReleasemanifest: /Users/david/Developer/.../build/manifests/defaultFlavor/release/AndroidManifest.xmlaptOutput: /Users/david/Developer/.../build/source/apt_generated/defaultFlavor/release****************************:TravelGuard:compileDefaultFlavorDebugNdk UP-TO-DATE:TravelGuard:preBuild UP-TO-DATE:TravelGuard:preDefaultFlavorDebugBuild UP-TO-DATE:TravelGuard:preDefaultFlavorReleaseBuild UP-TO-DATE:TravelGuard:prepareComProlificinteractiveActionbarsherlock431Library UP-TO-DATE:TravelGuard:prepareComViewpagerindicatorLibrary241Library UP-TO-DATE:TravelGuard:prepareDefaultFlavorDebugDependencies:TravelGuard:compileDefaultFlavorDebugAidl UP-TO-DATE:TravelGuard:compileDefaultFlavorDebugRenderscript UP-TO-DATE:TravelGuard:generateDefaultFlavorDebugBuildConfig UP-TO-DATE:TravelGuard:mergeDefaultFlavorDebugAssets UP-TO-DATE:TravelGuard:mergeDefaultFlavorDebugResources UP-TO-DATE:TravelGuard:processDefaultFlavorDebugManifest UP-TO-DATE:TravelGuard:processDefaultFlavorDebugResources UP-TO-DATE:TravelGuard:generateDefaultFlavorDebugSources UP-TO-DATE:TravelGuard:compileDefaultFlavorDebugJava*** compile doFirst defaultFlavorDebug/Users/david/Developer/.../src/main/java/com/travelguard/service/TravelGuardService.java:53: cannot find symbolsymbol : class TravelGuardPrefs_location: class com.travelguard.service.TravelGuardService TravelGuardPrefs_ travelGuardPrefs; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/CategoriesActivity.java:14: cannot find symbolsymbol : class AssistanceFragment_location: package com.travelguard.ui.fragmentsimport com.travelguard.ui.fragments.AssistanceFragment_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/CategoriesActivity.java:16: cannot find symbolsymbol : class CategoryFragment_location: package com.travelguard.ui.fragmentsimport com.travelguard.ui.fragments.CategoryFragment_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/CategoriesActivity.java:17: cannot find symbolsymbol : class ContactFragment_location: package com.travelguard.ui.fragmentsimport com.travelguard.ui.fragments.ContactFragment_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/CountriesActivity.java:25: cannot find symbolsymbol : class TravelGuardPrefs_location: package com.travelguard.serviceimport com.travelguard.service.TravelGuardPrefs_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/CountriesActivity.java:44: cannot find symbolsymbol : class TravelGuardPrefs_location: class com.travelguard.ui.CountriesActivity TravelGuardPrefs_ travelGuardPrefs; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/InstructionsActivity.java:18: cannot find symbolsymbol : class AssistanceFragment_location: package com.travelguard.ui.fragmentsimport com.travelguard.ui.fragments.AssistanceFragment_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/InstructionsActivity.java:19: cannot find symbolsymbol : class ContactFragment_location: package com.travelguard.ui.fragmentsimport com.travelguard.ui.fragments.ContactFragment_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/InstructionsActivity.java:21: cannot find symbolsymbol : class InstructionsFragment_location: package com.travelguard.ui.fragmentsimport com.travelguard.ui.fragments.InstructionsFragment_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/MainActivity.java:36: cannot find symbolsymbol : class TravelGuardPrefs_location: package com.travelguard.serviceimport com.travelguard.service.TravelGuardPrefs_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/MainActivity.java:40: cannot find symbolsymbol : class AssistanceFragment_location: package com.travelguard.ui.fragmentsimport com.travelguard.ui.fragments.AssistanceFragment_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/MainActivity.java:41: cannot find symbolsymbol : class ContactFragment_location: package com.travelguard.ui.fragmentsimport com.travelguard.ui.fragments.ContactFragment_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/MainActivity.java:55: cannot find symbolsymbol : class TravelGuardPrefs_location: class com.travelguard.ui.MainActivity TravelGuardPrefs_ travelGuardPrefs; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/TermsActivity.java:17: cannot find symbolsymbol : class TravelGuardPrefs_location: package com.travelguard.serviceimport com.travelguard.service.TravelGuardPrefs_; ^/Users/david/Developer/.../src/main/java/com/travelguard/ui/TermsActivity.java:23: cannot find symbolsymbol : class TravelGuardPrefs_location: class com.travelguard.ui.TermsActivity TravelGuardPrefs_ travelGuardPrefs; ^Note: Starting AndroidAnnotations annotation processingNote: AndroidManifest.xml file found: /Users/david/Developer/.../build/manifests/defaultFlavor/debug/AndroidManifest.xmlNote: Number of files generated by AndroidAnnotations: 22Note: Generating source file: com.travelguard.service.SmartTravellerService_Note: Generating source file: com.travelguard.service.SmartTravellerWebservice_Note: Generating source file: com.travelguard.service.TravelGuardPrefs_Note: Generating source file: com.travelguard.service.TravelGuardService_Note: Generating source file: com.travelguard.service.TravelGuardWebservice_Note: Generating source file: com.travelguard.ui.AdviceActivity_Note: Generating source file: com.travelguard.ui.CategoriesActivity_Note: Generating source file: com.travelguard.ui.ContactDetailActivity_Note: Generating source file: com.travelguard.ui.ContactListActivity_Note: Generating source file: com.travelguard.ui.ContactTravelGuardActivity_Note: Generating source file: com.travelguard.ui.CountriesActivity_Note: Generating source file: com.travelguard.ui.InformationActivity_Note: Generating source file: com.travelguard.ui.InstructionsActivity_Note: Generating source file: com.travelguard.ui.MainActivity_Note: Generating source file: com.travelguard.ui.TermsActivity_Note: Generating source file: com.travelguard.ui.TravelGuardActivity_Note: Generating source file: com.travelguard.ui.fragments.AdviceDetailFragment_Note: Generating source file: com.travelguard.ui.fragments.AdviceFragment_Note: Generating source file: com.travelguard.ui.fragments.AssistanceFragment_Note: Generating source file: com.travelguard.ui.fragments.CategoryFragment_Note: Generating source file: com.travelguard.ui.fragments.ContactFragment_Note: Generating source file: com.travelguard.ui.fragments.InstructionsFragment_Note: Time measurements: [Whole Processing = 913 ms], [Generate Sources = 358 ms], [Extract Manifest = 163 ms], [Process Annotations = 158 ms], [Extract Annotations = 120 ms], [Validate Annotations = 82 ms], [Find R Classes = 28 ms],Note: Time measurements: [Whole Processing = 0 ms],Note: Time measurements: [Whole Processing = 0 ms],warning: The following options were not recognized by any processor: '[androidManifestFile]'Note: /Users/david/Developer/.../src/main/java/com/travelguard/ui/ContactDetailActivity.java uses or overrides a deprecated API.Note: Recompile with -Xlint:deprecation for details.Note: /Users/david/Developer/.../src/main/java/com/travelguard/service/SmartTravellerService.java uses unchecked or unsafe operations.Note: Recompile with -Xlint:unchecked for details.:TravelGuard:preDexDefaultFlavorDebug UP-TO-DATE:TravelGuard:dexDefaultFlavorDebug:TravelGuard:processDefaultFlavorDebugJavaRes UP-TO-DATE:TravelGuard:validateDebugSigning:TravelGuard:packageDefaultFlavorDebugError: duplicate files during packaging of APK /Users/david/Developer/.../build/apk/TravelGuard-defaultFlavor-debug-unaligned.apk Path in archive: META-INF/LICENSE.txt Origin 1: /Users/david/.gradle/caches/modules-2/files-2.1/commons-httpclient/commons-httpclient/3.1/964cd74171f427720480efdec40a7c7f6e58426a/commons-httpclient-3.1.jar Origin 2: /Users/david/.gradle/caches/modules-2/files-2.1/commons-codec/commons-codec/1.2/397f4731a9f9b6eb1907e224911c77ea3aa27a8b/commons-codec-1.2.jar:TravelGuard:packageDefaultFlavorDebug FAILEDFAILURE: Build failed with an exception.* What went wrong:Execution failed for task ':TravelGuard:packageDefaultFlavorDebug'.> Duplicate files copied in APK META-INF/LICENSE.txt File 1: /Users/david/.gradle/caches/modules-2/files-2.1/commons-httpclient/commons-httpclient/3.1/964cd74171f427720480efdec40a7c7f6e58426a/commons-httpclient-3.1.jar File 2: /Users/david/.gradle/caches/modules-2/files-2.1/commons-httpclient/commons-httpclient/3.1/964cd74171f427720480efdec40a7c7f6e58426a/commons-httpclient-3.1.jar* Try:Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.BUILD FAILEDTotal time: 21.957 secs Things were working fine this morning before I updated Android Studio. Any ideas? EDIT: I was able to temporarily fix it by running commands like zip -d spring-android-core-1.0.1.RELEASE.jar META-INF/notice.txt until all the duplicate errors went away.
Now provide the response and nothing else.
| As of Android Studio version 0.8.14 You should add: android { packagingOptions { exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude '...' } } to your build.gradle file. History: According to comment 14 in this bug: https://issuetracker.google.com/issues/36982149#comment14 this is a bug in v0.7.0 of the Android Gradle plugin, and is due to be fixed soon in 0.7.1. Here are the notes from that bug about the addition for 0.7.1: 0.7.1 is out with the fix for this. The DSL to exclude files is: android { packagingOptions { exclude 'META-INF/LICENSE.txt' }} You can add as many exclude statement as you want. The value is the archive path. No wildcard or glob support yet. Filenames "LICENSE.txt" and "NOTICE.txt" are case sensitive. Please try out with "license.txt" and "notice.txt" as well. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/20673625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335317/']} | jdg_71310 |
stackexchange | llm_judgeable_groundtruth_similarity | 17218139 |
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 struggling with a minor problem in Python (my program is in version 3.2.3 right now). I have a dictionary that looks like this (this is just an example, actually taken from another post here): [ {"abc": "movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr": "music"}, {"pqr": "movies"}, {"pqr": "sports"}, {"pqr": "news"}, {"pqr": "sports"},] I want to simply print() a list of unique values, eliminating duplicates. At the end of this list, I would like to print the number of unique values in the dictionary: moviessportsmusicnews4 Any help is appreciated. There are some other posts here I found that were somewhat related, but I don't know Python well enough to apply it to this specific problem.
Now provide the response and nothing else.
| Use set here as they only contain unique items. >>> lis = [{"abc":"movies"}, {"abc": "sports"}, {"abc": "music"}, {"xyz": "music"}, {"pqr":"music"}, {"pqr":"movies"},{"pqr":"sports"}, {"pqr":"news"}, {"pqr":"sports"}]>>> s = set( val for dic in lis for val in dic.values())>>> s set(['movies', 'news', 'music', 'sports']) Loop over this set to get the expected output: for x in s: print xprint len(s) #print the length of set after the for-loop... moviesnewsmusicsports4 This line s = set( val for dic in lis for val in dic.values()) is roughly equivalent to: s = set()for dic in lis: for val in dic.values(): s.add(val) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17218139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/348408/']} | jdg_71311 |
stackexchange | llm_judgeable_groundtruth_similarity | 62746 |
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 was reading through RFC 5280, PKIX Certificate and CRL Profile, Section 4.2.1.6, Subject Alternative Name : The subject alternative name extension allows identities to be boundto the subject of the certificate. These identities may be includedin addition to or in place of the identity in the subject field ofthe certificate. Defined options include an Internet electronic mailaddress, a DNS name, an IP address, and a Uniform Resource Identifier(URI). Other options exist, including completely local definitions. Question: how does one encode a username like "john" or "jdoe"? Here are the choices: GeneralName ::= CHOICE { otherName [0] OtherName, rfc822Name [1] IA5String, dNSName [2] IA5String, x400Address [3] ORAddress, directoryName [4] Name, ediPartyName [5] EDIPartyName, uniformResourceIdentifier [6] IA5String, iPAddress [7] OCTET STRING, registeredID [8] OBJECT IDENTIFIER } And I'm making a distinction between a PKCS #9 emailAddress ("[email protected]") and a username ("jdoe").
Now provide the response and nothing else.
| Faced with this question, Microsoft answered the way they are accustomed to: with a Microsoft-specific extension. They defined the User Principal Name , which is actually an OtherName element, the UPN being identified by a Microsoft OID (1.3.6.1.4.1.311.20.2.3) and encoded as an UTF8String (as succinctly specified there ). The format of the string mimics that of an email address, in that it consists in an account name and a domain name, joined together with an '@' character. It is noteworthy that though the UPN looks like an email address, it is not meant to be used for sending emails; and, correspondingly, Microsoft did not use a rfc822name element, because such a name conveys email-based semantics (in particular when the certificate is used with S/MIME ) that UPN are not supposed to embody. The "X.509 way" to encode a name in a certificate, whose format does not match the predefined categories, is to do it along the same lines Microsoft did: use otherName , with an OID of your own, and define your own syntax. Of course, such a name will be usable only by your own software... Although you may decide to reuse the Microsoft UPN format, and thus (possibly) gain some compatibility with Microsoft software (the UPN's goal is to map a certificate onto an Active Directory account). The really important thing is to determine which software systems will have to deal with your "username". It is useless to encode a username in a certificate if the systems which must decode that username don't know how to do it. For instance, suppose that the username must be used by an Apache-powered Web site, the client certificate being presented at the SSL level. The documentation , in particular the SSLUserName configuration directive, shows us that Apache may be set to use some specific certificate fields as "username", among the exhaustive list of environment variables maintained by the SSL module. If you are in that situation, then you will have to put your "username" in one of these fields, not in some otherName with a syntax of your own. From looking at these fields, I'd say that your best bet would be "UID". That's one of the components of a Distinguished Name, specified in RFC 4519 under OID 0.9.2342.19200300.100.1.1. It is basically a free-form string, and Apache's mod_ssl knows how to extract it and turn it into a username with: SSLUserName SSL_CLIENT_S_DN_UID As a part of a DN, this would go in the subjectDN field directly, not into a Subject Alt Name extension. (This raises the question of why Microsoft did not use that "UID" field for their UPN; my guess is that they wanted at some point to use the complete subjectDN as a path in some LDAP directory, and thus could not add extra fields at will in the DN.) | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/62746', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/-1/']} | jdg_71312 |
stackexchange | llm_judgeable_groundtruth_similarity | 18035388 |
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 Scrapy project with multiple spiders along with multiple pipelines. Is there a way I can tell Spider A to use pipeline A, etc??? My pipelines.py has multiple pipeline classes each doing something different and I want to be able to tell a spider to use a specific pipeline. I do not see any obvious ways looking at the available scrapy commands to do this...
Now provide the response and nothing else.
| ITEM_PIPELINES setting is defined globally for all spiders in the project during the engine start. It cannot be changed per spider on the fly. Here's what you can do. Define what spiders should be processed via the pipeline in the pipeline itself. Skip/continue processing items returned by spiders in the process_item method of your pipeline, e.g.: def process_item(self, item, spider): if spider.name not in ['spider1', 'spider2']: return item # process item Also see: Is there any method to using seperate scrapy pipeline for each spider? Hope that helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18035388', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/975478/']} | jdg_71313 |
stackexchange | llm_judgeable_groundtruth_similarity | 38198745 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My script makes a GameObject move on Input.GetMouseButtonUp(0) . Unfortunately, when I click on a UI Button , the move function is triggered causing the GameObject to move. I do not want my GameObject to move when I press a button on the screen (UI element). I want to prevent GameObject from moving when the click is on a UI component such as Button ? How can I remedy this? Also, I'd like to check if the mouse was clicked over specific UI elements (2 or 3 buttons)
Now provide the response and nothing else.
| After reading your comment. What you need is EventSystem.current.IsPointerOverGameObject() which checks if pointer is over UI. true when pointer is over UI, otherwise false . You can use it with ' ! ' and run your rotation code only if the mouse is not over the UI. For Desktop if(Input.GetMouseButtonUp(0) && !EventSystem.current.IsPointerOverGameObject()){ //Your code here} // For Mobile if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended && !EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)){ //Your code here} The solution above should work but there is a bug. When the mouse button is pressed over the UI Button then released outside of the UI Button , it will register as a click. So, basically, the solution works only when you click on UI Button and release on UI Button . If you release outside the U Button , the original problem will be back again. The best solution is to use a temporary boolean value and check if button was originally pressed on a UI with Input.GetMouseButtonDown . That saved boolean , you can then use when the Button is released with Input.GetMouseButtonUp(0) . The solution below is provided to work with both Mobile and Desktop. Mobile tested and it works. bool validInput = true;private void Update(){ validateInput(); #if UNITY_STANDALONE || UNITY_EDITOR //DESKTOP COMPUTERS if (Input.GetMouseButtonUp(0) && validInput) { //Put your code here Debug.Log("Valid Input"); } #else //MOBILE DEVICES if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Ended && validInput) { //Put your code here Debug.Log("Valid Input"); } #endif}void validateInput(){ #if UNITY_STANDALONE || UNITY_EDITOR //DESKTOP COMPUTERS if (Input.GetMouseButtonDown(0)) { if (EventSystem.current.IsPointerOverGameObject()) validInput = false; else validInput = true; } #else //MOBILE DEVICES if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) { if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) validInput = false; else validInput = true; } #endif} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38198745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6542063/']} | jdg_71314 |
stackexchange | llm_judgeable_groundtruth_similarity | 181627 |
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:
When requesting a website, let's say "crypto.stackexchange.com" often you get redirected to a secure connection, in this case" https://crypto.stackexchange.com ". Would I then request an insecure connection (http), get redirected to the secure https protocol by the http response, and thus making a less secure request?
Now provide the response and nothing else.
| Would I then request an insecure connection (http), get redirected to the secure https protocol by the http response, and thus making a less secure request? It depends. In all generality the answer is yes, you are making an insecure HTTP request first and then the server tells you (hopefully with a 301 response) that you should use the HTTPS site instead and the browser loads that one. Of course, on the first insecure request anything could happen, including you being served a fake website. However there are (at least) three exceptions to this rule, which will make the browser look up the HTTPS version directly. So let's go through them! 301 Redirect Caching. 301 is the HTTP status code for "permanently moved" and some browsers are caching this response and don't even try to request the old site anymore but send you straight to the new one, for performance reasons and in this case a HTTP to HTTPS redirect would also profit from this. Browser Add-Ons. There are browser add-ons which keep a database of domains supporting HTTPS (somewhat) and if you request data from any of these domains, the add-on will automatically re-write the request to ask for the HTTPS version of the site. HTTPS Everywhere famously does this and covers a wide range of websites which don't deem their HTTPS "production-ready" ( such as Stackexchange prior to March 2017 ). HTTP Strict Transport Security (HSTS). This is flag in the HTTP response header which states that the site (and optionally all its sub-domains) may only be accessed using HTTPS during the next specified days without exception. This way, when you request a known HSTS domain, the browser will directly convert the HTTP request to a HTTPS request automatically. As a bonus, you can register for HSTS pre-loading for your site with the browser vendors and then the browsers will come with your HSTS entry pre-equipped starting with the next update. Stackexchange has HSTS deployed without pre-loading (on most sites). | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/181627', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/96201/']} | jdg_71315 |
stackexchange | llm_judgeable_groundtruth_similarity | 42765113 |
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 developing two related project. One of which is "helper" one and another is "main" one. I am constantly updating "main", but from time to time I am also updating "helper" one. After then I am running install goal in gradle's maven plugin and get jars in local maven repo. After that I do gradle update in "main" project and have updated jars linked. There are two questions. 1) If staying with maven plugin, then how to publish source code into local maven repo too? 2) Can I do similar without maven plugin, staying only with Gradle?
Now provide the response and nothing else.
| It's easy to publish sources with the "maven-publish" plugin: apply plugin: "maven-publish"task sourceJar(type: Jar) { from sourceSets.main.allJava}publishing { publications { mavenJava(MavenPublication) { from components.java artifact sourceJar { classifier "sources" } } }} Then go publish to local maven run: gradle publishToMavenLocal More info in the docs: https://docs.gradle.org/current/userguide/publishing_maven.html#gsc.tab=0 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42765113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/258483/']} | jdg_71316 |
stackexchange | llm_judgeable_groundtruth_similarity | 2374218 |
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:
The description of the following illustration in Munkres reads: One can now see that the collection $\mathscr{B}$ of all circular regions in the plane generates the same topology as the collection $\mathscr{B}'$ of all rectangular regions. Can someone please elaborate on the meaning of this illustration? I may just be oblivious, but I'm not understanding the relation between the caption and the image. Also, how does this relate to bases?
Now provide the response and nothing else.
| The figure is referring to the preceding lemma, which states that the topology generated by basis $\mathcal{B}'$ is finer than (larger than) the topology generated by basis $\mathcal{B}$, if and only if for each $x \in X$ and $B \in \mathcal{B}$ containing $x$ there exists $B' \in \mathcal{B}'$ such that $x \in B' \subseteq B$. The image on the right shows that for any circle $B$ containing $x$, you can fit a rectangle $B'$ inside $B$ that contains $x$. The image on the left shows that the same holds with the roles of the bases reversed. Thus each topology is finer than the other, so they are the same. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2374218', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/447213/']} | jdg_71317 |
stackexchange | llm_judgeable_groundtruth_similarity | 251537 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to find a matrix $\mathbf{X}$ such that it belongs to $O(D,D)$ and satisfies the equation: $$\mathbf{X A X}^\top = \mathbf{B}$$ where both matrices are square, $\mathbf{A}$ is symmetric and $\mathbf{B}$ is diagonal. I have no idea how to easily do this in Mathematica. Any tips? Thanks!
Now provide the response and nothing else.
| For real, square and symmetric matrices A, B, X, the solution of $$ XAX^T=B,$$ is given by $$ X=B (B^{-1}A^{-1})^{1/2}. $$ For example, in Mathematica this can be written as A = {{1, 2}, {2, 3}};X = {{3, 4}, {4, -1}};B = X.A.Transpose[X]; and the solution can be verified to be In[4]:= X - B.MatrixPower[Inverse[B].Inverse[A], 1/2] // N // ChopOut[4]= {{0, 0}, {0, 0}} as expected. In the more general case, where the matrices are non-symmetric etc, the situation is more complicated, but still a numerical solution may be achieved using SchurDecomposition, see the classic paper" A Schur Method for Solving Algebraic Riccati Equations " by Laub, A.J., which can be found here . | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/251537', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/81187/']} | jdg_71318 |
stackexchange | llm_judgeable_groundtruth_similarity | 34971087 |
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 pretty new to angular (as you might guess). I'm trying to understand the best way to change content depending on what gets input in fields. For example, I have <div ng-app = ""> <p>Enter variable 1: <input type = "number" ng-model = "var1"></p> <p>Enter variable 2: <input type ="number" ng-model ="var2"></p> And I'm trying to display the product of the two variables, once both have been entered: <p>Your total value is {{ (var1 * var2).isFinite? (var1 * var2) : 'Please enter a number' }} </p> However, this doesn't work - it always displays 'Please enter a number'. What is the best way to do this?
Now provide the response and nothing else.
| In general, it is recommended to move away from the old defer model because you want the creator of a promise to be responsible for resolving or rejecting it - this just makes the control flow a ton easier to follow. You don't want to pass on the responsibility for resolving or rejecting to some other code. If outside code is involved in the decision to resolve or reject (such as your rollDice() function), then it can return info which is used to resolve or reject. For example, in your code example, it can be done like this. Note that the rollDice() function is now just a dice rolling function that tells you whether you rolled a specific number of not. It is then used by the other function to determine control flow rather than putting control flow in the dice rolling function itself. var rollDice = function() { console.log("rolling"); return Math.floor(Math.random() * 10) + 1;}var rollTillNum = function(num, ms) { return new Promise(function(resolve) { var interval = setInterval(function(){ if (rollDice() === num) { resolve(); clearInterval(interval); } }, ms); });}rollTillNum(7, 100).then(function(){ console.log("rolled a 7");}); Summary of Changes: Promise management is self-contained, not delegated to some other function (makes logic of the code easier to follow) which is one of the main reasons to use the new Promise constructor and not the deferred construct. The interval variable is now contained to a local scope. The rollDice() function is now generic so it can be used in other contexts. rollDice() now returns a 1-based value, not a 0-based value (since that's how dice work). Rather than hardwire rollTill7() , it's now rollTillNum() and you pass it the number you want it to achieve. While the above solution is more general (using an external function to provide feedback on whether you should resolve or not), in this specific case, if you don't even need the rollDice() function to be externally usable, then it can just be subsumed entirely inside of the rollTillNum() function: var rollTillNum = function(num, ms) { return new Promise(function(resolve) { var interval = setInterval(function(){ if ((Math.floor(Math.random() * 10) + 1) === num) { resolve(); clearInterval(interval); } }, ms); });}rollTillNum(7, 100).then(function(){ console.log("rolled a 7");}); Here's the above code made into a working demo: document.getElementById("roll").addEventListener("click", function() { var start = Date.now(); rollTillNum(7, 100).then(function(cnt) { var elapsed = ((Date.now() - start) / 1000).toFixed(1); log("It took " + elapsed + " seconds and " + cnt + " rolls to roll a 7"); });});var rollDice = function() { console.log("rolling"); return Math.floor(Math.random() * 10) + 1;}var rollTillNum = function(num, ms) { return new Promise(function(resolve) { var cntr = 0; var interval = setInterval(function(){ ++cntr; if (rollDice() === num) { resolve(cntr); clearInterval(interval); } }, ms); });}function log(x) { var div = document.createElement("div"); div.innerHTML = x; document.body.appendChild(div);} <button id="roll">Roll a 7</button><br><br> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34971087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2121911/']} | jdg_71319 |
stackexchange | llm_judgeable_groundtruth_similarity | 240543 |
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:
Consider a quantum system described by the Hilbert space $\mathcal{H}$ and consider $A,B\in \mathcal{L}(\mathcal{H},\mathcal{H})$ to be observables. If those observables do not commute there's no simultaneous basis of eigenvectors of each of them. In that case, in general if $|\varphi\rangle$ is eigenvector of $A$ it will not be of $B$. This leads to the problem of not having a definite value of some quantity in some states. Now, this is just a mathematical model. It works because it agrees with observations. But it makes me wonder about something. Concerning the Physical quantities associated to $A$ and $B$ (if an example helps consider $A$ to be the position and $B$ the momentum) what is really behind non-commutativity? Do we have any idea whatsoever about why two observables do not commute? Is there any idea about any underlying reason for that? Again I know one might say "we don't care about that because the theory agrees with the observation", but I can't really believe there's no underlying reason for some physical quantities be compatible while others are not. I believe this comes down to the fact that a measurement of a quantity affects the system in some way that interferes with the other quantity, but I don't know how to elaborate on this. EDIT: I think it's useful to emphasize that I'm not saying that "I can't accept that there exist observables which don't commute". This would enter the rather lengthy discussion about whether nature is deterministic or not, which is not what I'm trying to get here. My point is: suppose $A_1,A_2,B_1,B_2$ are observables and suppose that $A_1$ and $B_1$ commute while $A_2$ and $B_2$ do not commute. My whole question is: do we know today why the physical quantities $A_1$ and $B_1$ are compatible (can be simultaneously known) and why the quantities $A_2$ and $B_2$ are not? In other words: accepting that there are incompatible observables, and given a pair of incompatible observables do we know currently, or at least have a guess about why those physical quantities are incompatible?
Now provide the response and nothing else.
| Observables don't commute if they can't be simultaneously diagonalized, i.e. if they don't share an eigenvector basis. If you look at this condition the right way, the resulting uncertainty principle becomes very intuitive. As an example, consider the two-dimensional Hilbert space describing the polarization of a photon moving along the $z$ axis. Its polarization is a vector in the $xy$ plane. Let $A$ be the operator that determines whether a photon is polarized along the $x$ axis or the $y$ axis, assigning a value of 0 to the former option and 1 to the latter. You can measure $A$ using a simple polarizing filter, and its matrix elements are$$A = \begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}.$$ Now let $B$ be the operator that determines whether a photon is $+$ polarized (i.e. polarized southwest/northeast) or $-$ polarized (polarized southeast/northwest), assigning them values 0 and 1, respectively. Then$$B = \begin{pmatrix} 1/2 & -1/2 \\ -1/2 & 1/2 \end{pmatrix}.$$ The operators $A$ and $B$ don't commute, so they can't be simultaneously diagonalized and thus obey an uncertainty principle. And you can immediately see why from geometry: $A$ and $B$ are picking out different sets of directions. If you had a definite value of $A$, you have to be either $x$ or $y$ polarized. If you had a definite value of $B$, you'd have to be $+$ or $-$ polarized. It's impossible to be both at once. Or, if you rephrase things in terms of compass directions, the questions "are you going north or east" and "are you going northeast or southeast" do not have simultaneously well-defined answers. This doesn't mean compasses are incorrect, or incomplete, or that observing a compass 'interferes with orientation'. They're just different directions . Position and momentum are exactly the same way. A position eigenstate is sharply localized, while a momentum eigenstate has infinite spatial extent. Thinking of the Hilbert space as a vector space, they're simply picking out different directions; no vector is an eigenvector of both at once. | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/240543', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21146/']} | jdg_71320 |
stackexchange | llm_judgeable_groundtruth_similarity | 3278200 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the fridge there is a box containing 10 expensive high quality Belgian chocolates, which my mum keeps for visitors. Every day, when mum leaves home for work, I secretly pick 3 chocolates at random, I eat them and replace them with ordinary cheap ones, that have exactly the same wrapping. On the next day I do the same, obviously risking to eat also some of the cheap ones. How many days on average will it take for the full replacement of the expensive chocolates with cheap ones? I would say $10/3$ but this is very simplistic. Also, the total number of ways to pick 3 chocolates out of 10 is $\binom {10} 3=\frac {10!}{3!7!} = 120$ which means that after 120 days I will have replaced all chocolates but I don't think it is correct. Any help?
Now provide the response and nothing else.
| Sketch (not a complete solution, but a road map towards one): We proceed recursively. Let $E_i$ denote the expected number of day it takes given that you have exactly $i$ good ones left. The answer you want is $E_{10}$ . Let's compute $E_1$ , for example. Each day the good one gets selected with probability $\frac {3}{10}$ . Thus $$E_1=\frac {10}3$$ Now let's consider $E_2$ . The first draw you gets $0,1$ or $2$ of the good ones. We quickly deduce that $$\binom {10}3 \times E_2=\binom 83\times (E_2+1)+\binom 82\times \binom 21 \times (E_1+1)+ \binom 81\times \binom 22\times (1)$$ This resolves to $$E_2=\frac {115}{24}\approx 4.7917$$ Similarly, for $i>2$ $$\binom {10}3\times E_i=\binom {10-i}3\times (E_i+1)+\binom {10-i}2\times \binom i1\times (E_{i-1}+1)$$ $$+\binom {10-i}1\times \binom i2\times (E_{i-2}+1)+\binom {10-i}0\times \binom {i}3\times (E_{i-3}+1)$$ And we can solve the system step by step. The computation requires a bit of attention since in the recursion we must define $\binom nm=0$ when $n<m$ . In the end I get about $\boxed {9.046}$ but as the comments will clearly indicate, a great many careless errors were made en route so I advise checking carefully. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3278200', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/458464/']} | jdg_71321 |
stackexchange | llm_judgeable_groundtruth_similarity | 7277554 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a bitmask where the set bits describe where another number can be one or zero and the unset bits must be zero in that number. What's a good way to iterate through all its possible values? For example: 000 returns [000]001 returns [000, 001]010 returns [000, 010]011 returns [000, 001, 010, 011]100 returns [000, 100]101 returns [000, 001, 100, 101]110 returns [000, 010, 100, 110]111 returns [000, 001, 010, 011, 100, 101, 110, 111] The simplest way to do it would be to do it like this: void f (int m) { int i; for (i = 0; i <= m; i++) { if (i == i & m) printf("%d\n", i); }} But this iterates through too many numbers. It should be on the order of 32 not 2**32.
Now provide the response and nothing else.
| There's a bit-twiddling trick for this (it's described in detail in Knuth's "The Art of Computer Programming" volume 4A §7.1.3; see p.150): Given a mask mask and the current combination bits , you can generate the next combination with bits = (bits - mask) & mask ...start at 0 and keep going until you get back to 0. (Use an unsigned integer type for portability; this won't work properly with signed integers on non-two's-complement machines. An unsigned integer is a better choice for a value being treated as a set of bits anyway.) Example in C: #include <stdio.h>static void test(unsigned int mask){ unsigned int bits = 0; printf("Testing %u:", mask); do { printf(" %u", bits); bits = (bits - mask) & mask; } while (bits != 0); printf("\n");}int main(void){ unsigned int n; for (n = 0; n < 8; n++) test(n); return 0;} which gives: Testing 0: 0Testing 1: 0 1Testing 2: 0 2Testing 3: 0 1 2 3Testing 4: 0 4Testing 5: 0 1 4 5Testing 6: 0 2 4 6Testing 7: 0 1 2 3 4 5 6 7 (...and I agree that the answer for 000 should be [000] !) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7277554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/498804/']} | jdg_71322 |
stackexchange | llm_judgeable_groundtruth_similarity | 25725980 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm getting this error, in my ES log I'm using three nodes. Caused by: java.lang.ArrayIndexOutOfBoundsException[2014-09-08 13:53:56,167][WARN ][cluster.action.shard ] [Dancing Destroyer] [events][3] sending failed shard for [events][3], node[RDZy21y7SRep7n6oWT8ogg], [P], s[INITIALIZING], indexUUID [gzj1aHTnQX6XDc0SxkvxDQ], reason [Failed to start shard, message [IndexShardGatewayRecoveryException[[events][3] failed recovery]; nested: FlushFailedEngineException[[events][3] Flush failed]; nested: ArrayIndexOutOfBoundsException; ]][2014-09-08 13:53:56,357][WARN ][indices.cluster ] [Dancing Destroyer] [events][3] failed to start shardorg.elasticsearch.index.gateway.IndexShardGatewayRecoveryException: [events][3] failed recovery at org.elasticsearch.index.gateway.IndexShardGatewayService$1.run(IndexShardGatewayService.java:185) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744)Caused by: org.elasticsearch.index.engine.FlushFailedEngineException: [events][3] Flush failed at org.elasticsearch.index.engine.internal.InternalEngine.flush(InternalEngine.java:805) at org.elasticsearch.index.shard.service.InternalIndexShard.performRecoveryFinalization(InternalIndexShard.java:726) at org.elasticsearch.index.gateway.local.LocalIndexShardGateway.recover(LocalIndexShardGateway.java:249) at org.elasticsearch.index.gateway.IndexShardGatewayService$1.run(IndexShardGatewayService.java:132) ... 3 moreCaused by: java.lang.ArrayIndexOutOfBoundsException[2014-09-08 13:53:56,381][WARN ][cluster.action.shard ] [Dancing Destroyer] [events][3] sending failed shard for [events][3], node[RDZy21y7SRep7n6oWT8ogg], [P], s[INITIALIZING], indexUUID [gzj1aHTnQX6XDc0SxkvxDQ], reason [Failed to start shard, message [IndexShardGatewayRecoveryException[[events][3] failed recovery]; nested: FlushFailedEngineException[[events][3] Flush failed]; nested: ArrayIndexOutOfBoundsException; ]] This means that the status of ES is red and I'm missing nearly 10 million documents.What does this error mean, so that I'd might be able to recover?
Now provide the response and nothing else.
| It seems that I had a messed up shard, that needed fixing.It's a Lucene thing, where you tell Lucene to fix the shard. For Ubuntu, the solution was to go to the /usr/share/elasticsearch/lib directory and find out which Lucene core version is was running (running ls will show you a file named something like lucene-core-4.8.1.jar) and then type: java -cp lucene-core-x.x.x.jar -ea:org.apache.lucene... org.apache.lucene.index.CheckIndex /var/lib/elasticsearch/<clustername>/nodes/0/indices/<index>/<shard>/index/ -fix Replace the x.x.x with the Lucene core version, with your clustername, index with the name of the index and of course with the failing shard number. This can potentially give a loss of documents But it fixed our issue. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25725980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/486900/']} | jdg_71323 |
stackexchange | llm_judgeable_groundtruth_similarity | 15003974 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
All the typeclasses in Typeclassopedia have associated laws, such as associativity or commutativity for certain operators. The definition of a "law" seems to be a constraint that cannot be expressed in the type system. I certainly understand why you want to have, say, monad laws, but is there a fundamental reason why a typeclass that can be expressed fully within the type system is pointless?
Now provide the response and nothing else.
| You will notice that almost always the laws are algebraic laws. They could be expressed by the type system by using some extensions, but the proofs would be cumbersome to express. So you have unchecked laws and potentially implementations might break them. Why is this good? The reason is that the design patterns used in Haskell are motivated (and in most cases mirrored) by mathematical structures, usually from abstract algebra. While most other languages have an intuitive notion of certain features like safety, performance and semantics, we Haskell programmers prefer to establish a formal notion. The advantage of doing this is: Once your types and functions obey the safety laws, they are safe in the sense of the underlying algebraic structure. They are provably safe. Take functors as an example. A Haskell functor has the following two laws: fmap f . fmap g = fmap (f . g)fmap id = id Firstly this is very important: Functions in Haskell are opaque. You cannot examine, compare or whatever them. While this sounds like a bad thing in Haskell it is actually a very good thing. The fmap function cannot examine the function you've passed it. Particularly it can't check that you've passed the identity function or that you've passed a composition. In short: it can't cheat! The only way for it to obey these two laws is actually not to introduce any effects of its own. That means, in a proper functor fmap will never do anything unexpected. In fact it cannot do anything else than to map the given function. This is a very simple example and I haven't explained all the subtleties why fmap can't cheat, but it demonstrates the point. Now extend this all over the language, the base libraries and most sensible third party libraries. This gives you a language that is as predictable as a language can get. When you write code, you know what it's going to do. That's one of the main reasons why Haskell code often works out of the box. I often write pages of Haskell code before compiling. Once my type errors are fixed, my program usually works. The other reason why this is desirable is that it allows a more compositional style of programming. This is particularly useful when working as a team. First you map your application to algebraic structures and establish the necessary laws. For example: You express what it means for something to be a Valid Web Server. In particular you establish a formal notion of web server composition. If you compose two Valid Web Servers, the result is a Valid Web Server. Do you see where this is going? After establishing these laws the teammates go to work, and they work in isolation. Little to no communication is necessary to get their job done. When they meet again, everybody presents their Valid Web Servers and they just compose them to make the final product, a web site. Since the individual components were all Valid Web Servers, the final result must be a Valid Web Server. Provably. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15003974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/207096/']} | jdg_71324 |
stackexchange | llm_judgeable_groundtruth_similarity | 27537437 |
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 upgraded to sass-rails version 5.0.0 and are getting this deprecation warning: DEPRECATION WARNING: Extra .css in SCSS file is unnecessary. Rename /Users/foo/Projects/foo/app/assets/stylesheets/foo.css.scss to /Users/foo/Projects/foo/app/assets/stylesheets/foo.scss. (called from _app_views_layouts_application_html_erb__1560597815210891605_70190441246060 at /Users/foo/Projects/foo/app/views/layouts/application.html.erb:13) Anyone know whats going on with this? Does the gem really want me to rename all of my stylesheet assets from: app/assets/stylesheets/foo.css.scss to: app/assets/stylesheets/foo.scss ? Seems to run against years of Rails convention to me. Perhaps there is a way to suppress the deprecation warning?
Now provide the response and nothing else.
| Yes you need to rename your .css.scss to just .scss , as .css.scss will not be supported in sprockets 4. If you want to suppress the deprecation temporary you can the following to config/initializer/deprecations.rb Rails.application.config.after_initialize do old_behaviour = ActiveSupport::Deprecation.behavior ActiveSupport::Deprecation.behavior = ->(message, callstack) { unless message.starts_with?('DEPRECATION WARNING: Extra .css in SCSS file is unnecessary.', 'DEPRECATION WARNING: Extra .css in SASS file is unnecessary.') old_behaviour.each { |behavior| behavior[message,callstack] } end }end Or you can monkey patch to not to generate the message like this: module DisableCssDeprecation def deprecate_extra_css_extension(engine) if engine && filename = engine.options[:filename] if filename.end_with?('.css.scss','.css.sass') engine else super end end endendmodule Sass ; module Rails ; class SassImporter prepend DisableCssDeprecationend ; end ; end | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27537437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415409/']} | jdg_71325 |
stackexchange | llm_judgeable_groundtruth_similarity | 26187703 |
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 working on a windows form I have accidently clicked on buttons and now I have part of code related to this click event. I don't need them and I would like to remove these parts from the code but, if I do, Visual Studio complains when compiling cause it search for that missing code. How can I get rid of unused click events on my code?
Now provide the response and nothing else.
| When you double-click on a control, the default event gets wired up and a stubbed out handler gets created for you. The stubbed handler you know about as you saw it and deleted. private void button1_Click(object sender, EventArgs e){} The other piece is where the event actually gets wired. This is where the compile error comes from. You deleted the event handler, but did not remove the event subscription. This can be found in the Designer.cs file attached to the specific form. private void InitializeComponent(){ this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button1 // this.button1.Name = "button1"; //This is the line that has the compile error. this.button1.Click += new System.EventHandler(this.button1_Click);} As mentioned in the comments, you can go to the event properties for that control and reset the event, but you can also go into the designer and remove the invalid line. Using the Reset command will remove the stub and the event subscription. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26187703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3729944/']} | jdg_71326 |
stackexchange | llm_judgeable_groundtruth_similarity | 7983652 |
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 dereferencing a pointer notabley slower than just accessing that value directly? I suppose my question is - how fast is the deference operator?
Now provide the response and nothing else.
| Going through a pointer indirection can be much slower because of how a modern CPU works. But it has nothing much to do with runtime memory. Instead, speed is affected by prediction and cache. Prediction is easy when the pointer has not been changed or when it is changed in predictable ways (for example, increment or decrement by four in a loop). This allows the CPU to essentially run ahead of the actual code execution, figure out what the pointer value is going to be, and load that address into cache. Prediction becomes impossible when the pointer value is built by a complex expression like a hash function. Cache comes into play because the pointer might point into memory that isn't in cache and it will have to be fetched. This is minimized if prediction works but if prediction is impossible then in the worst case you can have a double impact: the pointer is not in cache and the pointer target is not in cache either. In that worst-case the CPU would stall twice. If the pointer is used for a function pointer, the CPU's branch predictor comes into play. In C++ virtual tables, the function values are all constant and the predictor has it easy. The CPU will have the code ready to run and in the pipeline when execution goes through the indirect jump. But, if it is an unpredictable function pointer the performance impact can be heavy because the pipeline will need to be flushed which wastes 20-40 CPU cycles with each jump. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7983652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/965369/']} | jdg_71327 |
stackexchange | llm_judgeable_groundtruth_similarity | 6202988 |
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 storing an action in a local variable, then I'm using after that local variable is out of scope. Is it in danger of being cleaned up before I use it? Here is an example: public List<object> GetMaps() { Action<Customer1, Customer2> baseMap = (Customer1 c1, Customer2 c2) => { c2.FirstName = c1.FirstName; }; var list = new List<object>() { new Action<SpecialCustomer1 c1, SpecialCustomer2 c2>() { baseMap(c1, c2); c2.SpecialProperty = c1.SpecialProperty; }, new Action<SpecialCustomer1 c1, SpecialCustomer2 c2>() { baseMap(c1, c2); c2.SpecialProperty2 = c1.SpecialProperty2; }, }; return list;} So, you can see in this example that the function is returning a list of actions that call baseMap . baseMap is just a local variable. Is the fact that it's called within the other actions enough for .NET to know not to clean it up?
Now provide the response and nothing else.
| I refer you to section 5.1.7 of the C# 4 spec, which says: If the local variable is captured by an anonymous function, its lifetime extends at least until the delegate or expression tree created from the anonymous function, along with any other objects that come to reference the captured variable, are eligible for garbage collection. Even if control passes the end of the scope of the local, the lifetime of the local is extended. In practice we do this by turning the local into a field of a closure class, and then keeping the class alive by referencing it in the delegate (or expression tree). Note though that you can run into the opposite problem; sometimes things live longer than you want them to: Expensive expensive = new Expensive();Cheap cheap = new Cheap();Action longlived = ()=>M(cheap);Action shortlived = ()=>M(expensive); The way this works in C# today is the closure generated for the two delegates keeps both "cheap" and "expensive" alive as long as the lifetime of the longer-lived delegate, even though the longer-lived delegate does not actually use "expensive"! (VB, JScript and many other languages that have closures also have this problem.) What we could do here is detect this situation in the compiler and create two closures. We're considering doing that for a future version of C#. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6202988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/543743/']} | jdg_71328 |
stackexchange | llm_judgeable_groundtruth_similarity | 2451436 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need the algorithm to animate the arrow based on 2 parameters, angle while shooting and power while drawing the bow.Ive tried to use y=asinx but it works only when shooting in up direction. Doesnt work well while shooting with straight or down direction. Thanks.
Now provide the response and nothing else.
| The flight of your projectile is described by x(t) = v * cos(theta) * ty(t) = v * sin(theta) * t - 1/2 * g * t^2 where t is time, v the initial velocity (power), theta the angle, g the acceleration due to gravity (e.g. 9.8 m/s^2), x the horizontal coordinate and y the height. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2451436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_71329 |
stackexchange | llm_judgeable_groundtruth_similarity | 13338837 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can someone help me why it doesn't work?I have a checkbox and if I click on it, this should uncheck all the checkbox inside the datagridview which were checked before including the user selected checkbox. Here is the code: private void chkItems_CheckedChanged(object sender, EventArgs e) { foreach (DataGridViewRow row in datagridview1.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1]; if (chk.Selected == true) { chk.Selected = false; } else { chk.Selected = true; } } } the checkbox should not be selected. it should be checked. here is the added column DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn(); CheckBox chk = new CheckBox(); CheckboxColumn.Width = 20; datagridview1.Columns.Add(CheckboxColumn);
Now provide the response and nothing else.
| Looking at this MSDN Forum Posting it suggests comparing the Cell's value with Cell.TrueValue . So going by its example your code should looks something like this:( this is completely untested ) Edit: it seems that the Default for Cell.TrueValue for an Unbound DataGridViewCheckBox is null you will need to set it in the Column definition. private void chkItems_CheckedChanged(object sender, EventArgs e){ foreach (DataGridViewRow row in dataGridView1.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1]; if (chk.Value == chk.TrueValue) { chk.Value = chk.FalseValue; } else { chk.Value = chk.TrueValue; } }} This code is working note setting the TrueValue and FalseValue in the Constructor plus also checking for null: public partial class Form1 : Form{ public Form1() { InitializeComponent(); DataGridViewCheckBoxColumn CheckboxColumn = new DataGridViewCheckBoxColumn(); CheckboxColumn.TrueValue = true; CheckboxColumn.FalseValue = false; CheckboxColumn.Width = 100; dataGridView1.Columns.Add(CheckboxColumn); dataGridView1.Rows.Add(4); } private void chkItems_CheckedChanged(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGridView1.Rows) { DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0]; if (chk.Value == chk.FalseValue || chk.Value == null) { chk.Value = chk.TrueValue; } else { chk.Value = chk.FalseValue; } } dataGridView1.EndEdit(); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13338837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647667/']} | jdg_71330 |
stackexchange | llm_judgeable_groundtruth_similarity | 268218 |
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:
Recently I was looking for a program that will run as a daemon and find files that have the same size/type, check if they're the same, then make both a hard link to a single copy if they are. And I started wondering why Operating Systems don't do this automatically. I thought maybe because it would be time consuming, but it wouldn't need to check if no new files were added outside of the cache directory, and checking the size would rapidly cut the search space. Then I thought maybe because it doesn't come up very often; but if that were the case then I would expect game consoles to do this, because most games will use the same stock sound effects package for instance, but they don't. Having two games from one series takes the same amount of space as just summing the two sizes, even though tons of assets would be reused. Or in a system like youtube, they check videos against other videos when checking for copyright violations, but they don't seem to cause two identical videos to be stored only once, considering how mirroring a video can prevent it being taken off the site, (e.g. when 'youtube vs the users' kept being mirrored they took it out of the search results rather than continuing to take them off the site). So, what's the reason the system doesn't compress things this way?
Now provide the response and nothing else.
| It's called deduplication. Some filesystems do it (like ZFS), some block-level storage systems do it (like NetApp), some backup systems do it (rsnapshot), source code managment systems do it (Git, bzr, fossil) It's not so rare, just that until recently it was an expensive option for generic filesystems. Note that it's not a good idea to do it as you suggest (hardlinks) for general-use volumes, since editing one 'copy' would edit the other one too. You should take care of breaking the link first. Some applications never "edit" files in place, instead on each "save" a new file is created and afterwards it is renamed to replace the original. In those cases yes, it would be reasonably safe to keep hardlinks; but do you want to audit every application you use on your files? Nuch easier is to keep separate copies separate | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/268218', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/129307/']} | jdg_71331 |
stackexchange | llm_judgeable_groundtruth_similarity | 2347562 |
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 quite massive program (>10k lines of C++ code). It works perfectly in debug mode or in release mode when launched from within Visual Studio, but the release mode binary usually crashes when launched manually from the command line (not always!!!). The line with delete causes the crash: bool Save(const short* data, unsigned int width, unsigned int height, const wstring* implicit_path, const wstring* name = NULL, bool enable_overlay = false){ char* buf = new char[17]; delete [] buf;} EDIT: Upon request expanded the example. The "len" has length 16 in my test case. It doesn't matter, if I do something with the buf or not, it crashes on the delete. EDIT: The application works fine without the delete [] line, but I suppose it leaks memory then (since the block is never unallocated). The buf in never used after the delete line. It also seems it does not crash with any other type than char. Now I am really confused. The crash message is very unspecific (typical Windows "xyz.exe has stopped working"). When I click the "Debug the program" option, it enters VS, where the error is specified to be "Access violation writing location xxxxxxxx". It is unable to locate the place of the error though "No symbols were loaded for any stack frame". I guess it is some pretty serious case of heap corruption, but how to debug this? What should I look for? Thanks for help.
Now provide the response and nothing else.
| have you checked memory leaks elsewhere? usually weird delete behavior is caused by the heap getting corrupted at one point, then much much later on, it becomes apparent because of another heap usage. The difference between debug and release can be caused by the way windows allocate the heap in each context. For example in debug, the heap can be very sparse and the corruption doesn't affect anything right away. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2347562', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/38256/']} | jdg_71332 |
stackexchange | llm_judgeable_groundtruth_similarity | 3196776 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a complex inner product space X. A linear operator A : X $\rightarrow$ X satisfies A $^2$ = A and A $^{*}$ A = AA $^{*}$ . Because X = R $_A$ $\oplus$ R $_A$$^{\perp}$ , then pick x = m $+$ n, in which m $\in$ R $_A$ , n $\in$ R $_A$$^{\perp}$ , x $\in$ X. I need to show Ax = m. I can show it until $\langle$ Ax, Ay $\rangle$ = $\langle$ m, A $^*$ Ay $\rangle$ . But feel difficult to show Ay = A $^{*}$ Ay. Is there any other wise way to do it?
Now provide the response and nothing else.
| Denoting your integral by $I$ , we have $$ I \ge \frac1{\sqrt\pi} \int_0^{\sqrt\pi} xe^{-x^2}\sin(x^2)\,dx = \frac1{2\sqrt\pi} \int_0^{\pi} e^{-y}\sin(y)\,dy $$ (where the equality comes from the substitution $y=x^2$ ).The integral in the RHS is easily computed using double integration by parts, and is equal to $(1+e^{-\pi})/2$ . Consequently, $$ I \ge \frac{1+e^{-\pi}}{4\sqrt\pi} > \frac{\sqrt\pi}2 e^{-\pi} $$ (in fact, $(1+e^{-\pi})/4\sqrt\pi\approx 0.1471$ , while $\frac{\sqrt\pi}2 e^{-\pi}\approx 0.0383$ ). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3196776', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/655156/']} | jdg_71333 |
stackexchange | llm_judgeable_groundtruth_similarity | 40382838 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
std::optional<int&> xx; just doesn't compile for the latest gcc-7.0.0 snapshot. Does the C++17 standard include std::optional for references? And why if it doesn't? (The implementation with pointers in a dedicated specialization whould cause no problems i guess.)
Now provide the response and nothing else.
| Because optional , as standardized in C++17, does not permit reference types. This was excluded by design. There are two reasons for this. The first is that, structurally speaking, an optional<T&> is equivalent to a T* . They may have different interfaces, but they do the same thing. The second thing is that there was effectively no consensus by the standards committee on questions of exactly how optional<T&> should behave. Consider the following: optional<T&> ot = ...;T t = ...;ot = t; What should that last line do? Is it taking the object being referenced by ot and copy-assign to it, such that *ot == t ? Or should it rebind the stored reference itself, such that ot.get() == &t ? Worse, will it do different things based on whether ot was engaged or not before the assignment? Some people will expect it to do one thing, and some people will expect it to do the other. So no matter which side you pick, somebody is going to be confused. If you had used a T* instead, it would be quite clear which happens: T* pt = ...;T t = ...;pt = t; //Compile error. Be more specific.*pt = t; //Assign to pointed-to object.pt = &t; //Change pointer. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40382838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/371239/']} | jdg_71334 |
stackexchange | llm_judgeable_groundtruth_similarity | 60615308 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While updating to dev06 and ran the app I got the following error: java.lang.NoSuchMethodError: No static method setContent(Landroid/app/Activity;Lkotlin/jvm/functions/Function0;)Landroidx/compose/Composition; in class Landroidx/ui/core/WrapperKt; or its super classes (declaration of 'androidx.ui.core.WrapperKt' appears in /data/app/tt.reducto.composesample-BYNjMDWbVhiprnPCNJw0LA==/base.apk)
Now provide the response and nothing else.
| If you're coming from dev05, dev04 (or less), there's a migration needed. UPDATE: This logic works up to Dev09. BETA Release is currently available. I manage to make it work. You need to do the following: Android Studio 4.1 Canary 2 or + gradle-wrapper.properties: distributionUrl=https\://services.gradle.org/distributions/gradle-6.2.1-all.zip build.gradle: (project level) buildscript { ext.kotlin_version = "1.3.70" repositories { google() jcenter() } dependencies { classpath "com.android.tools.build:gradle:4.1.0-alpha02" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" }}allprojects { repositories { google() jcenter() }}task clean(type: Delete) { delete rootProject.buildDir} build.gradle (app level): apply plugin: 'com.android.application'apply plugin: 'kotlin-android'apply plugin: 'kotlin-android-extensions'android { compileSdkVersion 29 defaultConfig { applicationId "com.package.name" minSdkVersion 21 targetSdkVersion 29 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } composeOptions { kotlinCompilerExtensionVersion = "0.1.0-dev06" // THIS ONE is important } buildFeatures { compose true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' }}dependencies { def compose_version = "0.1.0-dev06" implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation 'androidx.core:core-ktx:1.2.0' implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation "androidx.ui:ui-foundation:$compose_version" implementation "androidx.ui:ui-framework:$compose_version" implementation "androidx.ui:ui-tooling:$compose_version" implementation "androidx.ui:ui-layout:$compose_version" implementation "androidx.ui:ui-material:$compose_version" testImplementation 'junit:junit:4.12' androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'} Once you get all that done, run your code and you'd be good to go. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/60615308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6407556/']} | jdg_71335 |
stackexchange | llm_judgeable_groundtruth_similarity | 40126729 |
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 do you use the async function in the TestBed when testing in Angular 2? When do you use this? beforeEach(() => { TestBed.configureTestingModule({ declarations: [MyModule], schemas: [NO_ERRORS_SCHEMA], }); }); And when do you use this? beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [MyModule], schemas: [NO_ERRORS_SCHEMA], });})); Can anyone enlighten me on this ?
Now provide the response and nothing else.
| async will not allow the next test to start until the async finishes all its tasks. What async does is wrap the callback in a Zone, where all asynchronous tasks (e.g. setTimeout ) are tracked. Once all the asynchronous tasks are complete, then the async completes. If you have ever worked with Jasmine outside out Angular, you may have seen done being passed to the callback it('..', function(done) { someAsyncAction().then(() => { expect(something).toBe(something); done(); });}); Here, this is native Jasmine, where we tell Jasmine that this test should delay completion until we call done() . If we didn't call done() and instead did this: it('..', function() { someAsyncAction().then(() => { expect(something).toBe(something); });}); The test would complete even before the expectation, because the promise resolves after the test is finished executing the synchronous tasks. With Angular (in a Jasmine environment), Angular will actually call done behind the scenes when we use async . It will keep track of all the asynchronous tasks in the Zone, and when they are all finished, done will be called behind the scenes. In your particular case with the TestBed configuration, you would use this generally when you want to compileComponents . I rarely run into a situation in which I would have to call it otherwise beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [MyModule], schemas: [NO_ERRORS_SCHEMA], }) .compileComponent().then(() => { fixture = TestBed.createComponent(TestComponent); });})); When testing a component that uses templateUrl (if you are not using webpack), then Angular needs to make an XHR request to get the template, so the compilation of the component would be asynchronous. So we should wait until it resolves before continuing testing. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/40126729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5459440/']} | jdg_71336 |
stackexchange | llm_judgeable_groundtruth_similarity | 44432378 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working with firebase functions and arrived to hundreds of functions, and now it is very hard to manage it in single index.js file as shown in their lots of examples I tried to split that functions in multiple files like: --firebase.json--functions --node_modules --index.js --package.json --app --groupFunctions.js --authFunctions.js --storageFunctions.js In this structure i divide my functions in three categories and put in that three files groupFunctions.js , authFunctions.js , and storageFunctions.js . I then tried to import thise files in index.js , but I don't know why it is not working for me. Here is groupFunctions.js var functions = require('firebase-functions');module.exports = function(){ exports.onGroupCreate = functions.database.ref('/groups/{groupId}') .onWrite(event => { console.log(`A group is created in database named:${event.params.groupId}.`); // some logic... //... })} Here is index.js file: var functions = require('firebase-functions');module.exports = require("./app/groupFunctions")(); My editor not giving any warning in this code. But when I deploy this code with firebase deploy --only functions , it does not deploy function. If some functions already exist on firebase console, it remove all functions on deploy. here is deployment logs: question is also asked on github
Now provide the response and nothing else.
| Working code example: file structure: --firebase.json--functions --node_modules --index.js --package.json --src --groupFunctions.js --authFunctions.js --storageFunctions.js index.js file: require('./src/groupFunctions.js')(exports);require('./src/authFunctions.js')(exports);require('./src/storageFunctions.js')(exports); groupFunctions.js file: var functions = require('firebase-functions');module.exports = function (e) { e.onGroupCreate = functions.database.ref('/groups/{groupId}') .onWrite(event => { console.log(`A group is created in database named:${event.params.groupId}.`); // some logic... //... })} UPDATE: now I have better solution The full working code is located at https://github.com/malikasinger1/firebase-functions-with-typescript and it's written with cutting edge tech like typescript and webpack. You may use this as a boilerplate/starter. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44432378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4378475/']} | jdg_71337 |
stackexchange | llm_judgeable_groundtruth_similarity | 34498084 |
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 need to do some refactoring and I came across to this: if(LoanTerms.RateIncreasable.HasValue && LoanTerms.RateIncreasable.Value) { ... } and LoanTerms.RateIncreasable is of type System.Nullable<bool> So I'm wondering do I need .HasValue check on this? Will null be treated like false in if statement?
Now provide the response and nothing else.
| Since the default of bool is false you can use this code which does everything you need: if(LoanTerms.RateIncreasable.GetValueOrDefault()) { ... } For more information, look at the documentation at MSDN: Nullable(T).GetValueOrDefault() . But to answer your question: It is not legal to read the Value property of Nullable<T> if the Nullable<T> value is null (ie. HasValue == false ), you'll get an exception. So if you absolutely must read Value , ensure it has a value first. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34498084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1081079/']} | jdg_71338 |
stackexchange | llm_judgeable_groundtruth_similarity | 55369645 |
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 you customize the default login form in Django? # demo_project/urls.pyfrom django.contrib import adminfrom django.urls import include, pathurlpatterns = [ path('', include('pages.urls')), path('users/', include('users.urls')), # new path('users/', include('django.contrib.auth.urls')), # new path('admin/', admin.site.urls),]<!-- templates/registration/login.html --> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> Above code works but I need to customize that {{form.as_p}} Where is that form or can it be override? Thanks for the help.
Now provide the response and nothing else.
| you can overide default Authentication form like this from django.contrib.auth.forms import AuthenticationForm, UsernameFieldfrom django import formsclass UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) username = UsernameField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': '', 'id': 'hello'})) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': '', 'id': 'hi', })) in url.py you can pass this custom authentication form like this from django.contrib.auth import viewsfrom myapp.forms import UserLoginFormurlpatterns = [ path( 'login/', views.LoginView.as_view( template_name="login.html", authentication_form=UserLoginForm ), name='login')] also, you can override the login template and customize the template as per you requirement <form method="post"> {{ form.non_field_errors }} <div class="form-group"> <label for="{{ form.username.id_for_label }}">Username:</label> {{ form.username }} {{ form.username.errors }} </div> <div class="form-group"> <label for="{{ form.password.id_for_label }}">Password:</label> {{ form.password }} {{ form.password.errors }} </div> <button type="submit">Login</button></form> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55369645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11252268/']} | jdg_71339 |
stackexchange | llm_judgeable_groundtruth_similarity | 456250 |
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 standard on common website resolution? We are targeting newer monitors, perhaps at least 1280px wide, but the height may varies, and each browser may have different toolbar heights too. Is there any sort of standard to this?
Now provide the response and nothing else.
| The advice these days is: Optimize for 1024x768 . For most sites this will cover most visitors. Most logs show that 92-99% of your visits will be over 1024 wide. While 1280 is increasingly common, there are still lots at 1024 and some below that. Optimize for this but don't ignore the others. 1024 = ~960 . Accounting for scrollbars, window edges, etc means the real width of a 1024x768 screen is about 960 pixels . Some tools are based on a slightly smaller size, about 940 . This is the default container width in twitter bootstrap . Don't design for one size . Window sizes vary. Don't assume screen size equals windows size. Design for a reasonable minimum, but assume it will adjust. Use responsive design and liquid layouts . Use layouts that will adjust when the window is resized. People do this a lot, especially on big monitors. This is just good CSS practice. There are several front-end frameworks that support this. Treat mobile as a first-class citizen . You are getting more traffic from mobile devices all the time. These introduce even more screen sizes. You can still optimize for 960, but using responsive web design techniques means your page will adjust based on the screen size. Log browser display info . You can get actual numbers about this. I found some numbers here and here and here . You can also rig your site to collect the same data. User will scroll so don't worry much about height . The old argument was that users wouldn't scroll and anything important should be "above the fold." This was overturned years ago. Users scroll a lot . More about screen resolutions: Screen Resolution and Page Layout Best Screen Resolution to Design Websites Design for browser size - not screen size More about responsive design: Responsive Web Design (2010, May 25), Ethan Marcotte, A List Apart. Responsive Web Design at Wikipedia Multi-device layout patterns (2012, Mar 14) Luke Wroblewski. Catalogs the most popular patterns for adaptable multi-device screen layouts. Tools and front-end frameworks for responsive design and liquid layouts: Twitter Bootstrap Zurb Foundation 50 fantastic tools for responsive web design (2012, April 24) Denise Jacobs & Peter Gasston | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/456250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36036/']} | jdg_71340 |
Subsets and Splits