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
|
25686969
|
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 implement a factory design pattern in Scala using the apply methods available on the companion object. I have the following approach. sealed trait MyType { def param: String}case class TypeA(param: String) extends MyTypecase class TypeB(param: String, anotherParam: String) extends MyType object MyType { def apply(param: String): TypeA = ??? def apply(param, anotherParam: String): TypeB = ???} How do I now force the callers of the above trait to go via the companion object when creating instances of TypeA or TypeB ?
Now provide the response and nothing else.
|
You can move the case classes inside the companion object, and set the constructors to be private and accessed only within the companion object. sealed trait MyType { def param: String}object MyType { case class TypeA private[MyType] (param: String) extends MyType case class TypeB private[MyType] (param: String, anotherParam: String) extends MyType def apply(param: String): TypeA = TypeA(param) def apply(param: String, anotherParam: String): TypeB = TypeB(param, anotherParam)} No one would be able to instantiate the case classes directly, unless though reflection. scala> MyType("Test")res0: MyType.TypeA = TypeA(Test)scala> MyType("Test", "another test")res1: MyType.TypeB = TypeB(Test,another test)scala> MyType.TypeA("test??")<console>:12: error: constructor TypeA in class TypeA cannot be accessed in object $iw MyType.TypeA("test??") ^
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25686969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3102968/']}
|
jdg_372941
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2608355
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am creating a MyOperation object (inherited from NSOperation) and add to a NSOperationQueue. Then I am doing KVO on MyOperation.I am using this method - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context; to get a value from MyOperation if it is finished. In this method I am using a convenience method from an other class to get some other data. Maybe here synchronization problems in the observeValue... method?
Now provide the response and nothing else.
|
NSOperation uses KVO intrinsically in it's operation; having to implement isFinished and isExecuted as part of the processing, for example are 100% KVO and are part of an operation's required contract with a client/queue. So advising that these should be avoided is inaccurate; NSOperation uses KVO itself so adopting dannywartnaby's premise would indicate that the implementation of NSOperation is in itself flawed, which is definitely not the case. Admittedly the developer must take care to use KVO properly, although i would argue that subclassing NSOperation is a non-trivial task probably left for the more experienced Objective-C programmer. Notifications, one could argue, are too coarse grained for the kind of work undertaken by an operation, although not always, i think we must be careful when advising on practices to ensure that the wrong message isnt passed as best practice. Danny, would you care to elaborate on why using KVO is not advised when using NSOperation or threads? many examples of NSOperation implementation use KVO...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2608355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227026/']}
|
jdg_372942
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2693558
|
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 write a C++ application with Qt, but build a prototype first using Python and then gradually replace the Python code with C++. Is this the right approach, and what tools (bindings, binding generators, IDE) should I use? Ideally, everything should be available in the Ubuntu repositories so I wouldn't have to worry about incompatible or old versions and have everything set up with a simple aptitude install . Is there any comprehensive documentation about this process or do I have to learn every single component, and if yes, which ones? Right now I have multiple choices to make:Qt Creator, because of the nice auto completion and Qt integration. Eclipse, as it offers support for both C++ and Python.Eric (haven't used it yet)Vim PySide as it's working with CMake and Boost.Python, so theoretically it will make replacing python code easier.PyQt as it's more widely used (more support) and is available as a Debian package. Edit : As I will have to deploy the program to various computers, the C++-solution would require 1-5 files (the program and some library files if I'm linking it statically), using Python I'd have to build PyQt/PySide/SIP/whatever on every platform and explain how to install Python and everything else.
Now provide the response and nothing else.
|
I want to write a C++ application with Qt, but build a prototype first using Python and then gradually replace the Python code with C++. Is this the right approach? That depends on your goals. Having done both, I'd recommend you stay with Python wherever possible and reasonable. Although it takes a bit of discipline, it's very possible to write extremely large applications in Python. But, as you find hotspots and things that can be better handled in C++, you can certainly port relevant parts to C++. Is there any comprehensive documentation about this process or do I have to learn every single component, and if yes, which ones? Here's what I'd recommend for the various pieces: EDITOR/IDE : Use any editor/IDE you're comfortable with, but I'd highly recommend one that supports refactoring. If you're comfortable with Eclipse, use it. If you want to mainly go the C++ route and you're not too familiar with any editors, you might be better off with QtCreator. Eric is an extremely good Python IDE with support for refactoring, unless you're going to be doing lots of C++, take a look at it. Even better, its source code is an example of good PyQt usage and practices. PROCESS : The quick summary: Write your application in Python using PyQt When identified as hotspots, convert decoupled Python classes to C++ Create bindings for those classes using SIP Import the newly defined libraries in Python in place of their Python counterparts Enjoy the speed boost General details: Write the application in Python using PyQt. Be careful to keep a good separation of concerns so that when you need to port pieces to C++ they will be separate from their dependencies. When you finally need to port something to C++, write it in C++/Qt and then create bindings for it using SIP . SIP has a good reference manual on the process, and you have all of PyQt as an example. DEPLOYMENT : C++ - For many applications the dependencies are sufficiently simple that it's not too difficult to create an installer using a tool like NullSoft's Installer or InnoSetup . Python/PyQt - PyQt applications are a bit more difficult to install because of the dependency on Python and its dependence on the presence of the Qt libraries. One person documented his efforts on this post at ARSTechnica . py2exe works pretty well on Windows and should work fine. IME, freeze.py , which comes with the Python source, sometimes has problems determining which shared libraries are truly necessary and will sometimes end up creating a binary whose dependencies aren't present. Py2app can be made to work on Mac OS X . But worse , however, is the PyQt/Qt licensing. If you are developing a commercial application, you need to have a commercial PyQt (and Qt) license and make sure to prevent the users from easily modifying the source or otherwise writing code against the PyQt/Qt API because of licensing restrictions . Because of that, the PyQt author created a tool called VendorId (although it has a Python license). Within VendorId is a tool called SIB that can be used to create an executable which depends only on the Python interpreter. But, if you're going to go this far, you might want to install a custom Python along with your application. DISCLAIMER : I haven't used PySide at all, so I'm not sure how it compares to PyQt. Also, note the following warning on their website: PySide is a work in progress and is not yet suited for application development requiring production-level stability. But, on a good note, they intend, at least for the initial release to "maintain API compatibility with PyQt." So, aside from the C++ bindings, you could easily switch between the two later.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2693558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73299/']}
|
jdg_372943
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33947
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
(This question actually arose in some research on number theory.) I once learned that any countable dense subspace of any Euclidean space $\mathbb R^n$ is homeomorphic to the rationals $\mathbb Q$ . Now I wonder if something similar is true for the irrationals $J \mathrel{:=} \mathbb R \setminus \mathbb Q$ (with the subspace topology from $\mathbb R$ ). Let $\mathfrak c$ denote the cardinality of the continuum. I . Is each cartesian power $J^n$ homeomorphic to $J$ ? Also, how far can this be pushed? II . Let $X$ be a dense totally disconnected subspace of $\mathfrak R$ such that every neighborhood of each point of $X$ contains $\mathfrak c$ points. Is $X$ homeomorphic to $J$ ? What about for such subspaces of fairly nice subspaces of $\mathbb R^n$ ? IIa . Let $X$ be any subspace of $\mathbb R^n$ as described in II ., and let $B$ denote any subspace of $\mathbb R^n$ homeomorphic to [the open unit ball in $\mathbb R^n$ $\cup$ any subset of its boundary]. Then is $X \cap B$ homeomorphic to $J$ ? And what about greater generality? III . Is there a simple set of conditions that describe exactly all spaces (or subspaces of $\mathbb R^n$ ) that are homeomorphic to $J$ ? What about $J^n$ ? (Perhaps the word homogeneous or metric needs to be included.) (I found nothing relevant via Google, in MathSciNet, or here on MathOverflow.)
Now provide the response and nothing else.
|
The space of irrationals is homeomorphic to the Baire space $\mathbb N^{\mathbb N}$of functions from $\mathbb N$ to $\mathbb N$.Here $\mathbb N$ gets the discrete topology and the power gets the product topology.In particular, every finite or countably infinite power of the space of irrationals is homeomorphic to the irrationals. The Baire space is very well studied in descriptive set theory. See the book by Kechris, Classical Descriptive Set Theory.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/33947', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5484/']}
|
jdg_372944
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21828834
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading about skip lists and MemSQL and was wondering why skip lists are not more widely used in databases? Are there any major disadvatages to using skiplists?
Now provide the response and nothing else.
|
Databases are typically so huge that they have to be stored in external memory, such as a giant disk drive. As a result, the bottleneck in most database applications is the number of times that we have to do a memory transfer from the disk drive into main memory. B-trees and their variants are specifically designed to minimize the number of block reads and writes necessary to perform each of their operations. Mathematically, the number of memory transfers required for each B-tree operation is O(log n / log B), where B is the block size. Compare this to a skiplist, which requires O(log n) memory transfers on expectation. Since B is usually measured in megabytes, log B can be in the neighborhood of 15 - 25, so the B-tree can be significantly faster. Even when the database is in main memory, the effect of the memory hierarchy (L1 and L2 caches, etc.) can be so pronounced that B-tree variants are still faster in practice than many other data structures. This Google blog post gives some background on this. Although each operation on a B-tree typically requires more CPU work than corresponding operations in other data structures, the fact that they require so few memory transfers tends to make them significantly faster in practice than other data structures. Therefore, it would not be advisable to use a skip list in a database. There's another reason B-trees are nice: they're worst-case efficient. Although deterministic skip lists do exist, most skiplist implementations are randomized and give expected guarantees on their behavior. In a database, this might be unacceptable because many use cases on databases require worst-case efficient behavior. Hope this helps!
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21828834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2843996/']}
|
jdg_372945
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34613761
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I detect non-ascii characters in a vector of strings in a grep like fashion. For example below I'd like to return c(1, 3) or c(TRUE, FALSE, TRUE, FALSE) : x <- c("façile test of showNonASCII(): details{", "This is a good line", "This has an ümlaut in it.", "OK again. }") Attempt: y <- tools::showNonASCII(x)str(y)p <- capture.output(tools::showNonASCII(x))
Now provide the response and nothing else.
|
another possible way is to try to convert your string to ASCII and the try to detect all the generated non printable control characters which couldn't be converted grepl("[[:cntrl:]]", stringi::stri_enc_toascii(x))## [1] TRUE FALSE TRUE FALSE Though it seems stringi has a built in function for this type of things too stringi::stri_enc_mark(x)# [1] "latin1" "ASCII" "latin1" "ASCII"
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34613761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000343/']}
|
jdg_372946
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3058679
|
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 have stumbled upon the following integral: $$I=\int_0^\infty \frac{\ln x}{(\pi^2+\ln^2 x)(1+x)^2} \frac{dx}{\sqrt x}=-\frac{\pi}{24}$$ Although I could solve it, I am not quite comfortable with the way I did it. But first I will show the way. We can substitute $\ln x \rightarrow t\ $ which gives: $$I=\int_{-\infty}^\infty \frac{t}{\pi^2+t^2}\frac{e^{\frac{t}{2}}}{(1+e^t)^2}dt\overset{t=-x}=\int_{-\infty}^\infty \frac{-x}{\pi^2+x^2}\frac{e^{-\frac{x}{2}}}{(1+e^{-x})^2}dx$$ Also adding the two integral from above and simplify some of it yields: $$2I= \int_{-\infty}^\infty \frac{x}{\pi^2+x^2}\left(\frac{e^{\frac{x}{2}}}{(1+e^x)^2}-\frac{e^{-\frac{x}{2}}}{(1+e^{-x})^2}\right)dx$$ $$\Rightarrow I=-\frac{1}{4} \int_{-\infty}^\infty \frac{x}{\pi^2+x^2}\frac{\sinh \left(\frac{x}{2}\right)}{\cosh ^2\left(\frac{x}{2}\right)}dx$$ And now a round of IBP gives: $$I=\frac12 \int_{-\infty}^\infty \left(\frac{x^2-\pi^2}{(x^2+\pi^2)^2}\right)\left(\frac{1}{\cosh \left(\frac{x}{2}\right)}\right)dx$$ Using the Plancherel theorem the integral simplifies to: $$I=\int_0^\infty \left(\sqrt{\frac{\pi}{2}}x\left(-e^{-\pi x}\right)\right)\left(\sqrt{2\pi}\frac{1}{\cosh(\pi x)}\right)dx\overset{\pi x\rightarrow x}=-\frac{1}{\pi}\int_0^\infty \frac{x}{\cosh( x)}e^{- x}dx$$ We also have the following Laplace tranform for: $$f(t)=\frac{t}{\cosh( t)}\rightarrow F(s)=\frac18\left(\psi_1\left(\frac{s+1}{4}\right)-\psi_1\left(\frac{s+3}{4}\right)\right)$$ Where $\displaystyle{\psi_1(z)=\sum_{n=0}^\infty \frac{1}{(z+n)^2}}\,$ is the trigamma function . $$\Rightarrow I=-\frac{1}{\pi}F(s=1)=-\frac{1}{\pi}\cdot \frac18\left(\psi_1\left(\frac{1}{2}\right)-\psi_1 (1)\right)=-\frac{1}{\pi}\cdot \frac18\left(\frac{\pi^2}{2}-\frac{\pi^2}{6}\right)=-\frac{\pi}{24}$$ Have I done anything wrong, or can it be improved?I have to admit that I mostly used wolfram when applying Plancherel theorem and Laplace transform which I'm not comfortable with, but I didn't find an alternative method myself. For this question I would like to see a different proof that doesn't rely on that theorem. Probably not needed, but I should mention that my contour integration knowledge is pretty low. Also maybe there is a conexion with this integral , but I didn't find any.
Now provide the response and nothing else.
|
From the identity $$\Im\int_0^\infty e^{-(\pi-it)x}\,dx=\frac t{\pi^2+t^2}$$ we see that it suffices to compute the imaginary part of the integral $$\int_0^\infty dx\int_{-\infty}^\infty dt\;\frac{e^{\alpha t}}{(1+e^t)^2}e^{-\pi x}$$ where $\alpha=1/2+ix$ . Now, the integral with respect to $t$ is easy by means of the substitution $u=e^t$ and using the beta function . We thus get $$\int_0^\infty \pi\left(\frac12-ix\right)\frac{e^{-\pi x}}{\cosh(\pi x)}\,dx.$$ Taking the imaginary part we see that the problem boils down to compute the integral $$\int_0^\infty \frac{x e^{-\pi x}}{\cosh(\pi x)}\,dx=2\int_0^\infty \frac{x}{1+e^{2\pi x}}\,dx$$ which, after the substitution $v=2\pi x$ , reduces to the integral representation of the eta function $\eta(2)$ . Also notice that taking the real part we obtain the evaluation $$\int_0^\infty\frac1{(\pi^2+\log^2 x)(1+x)^2} \frac{dx}{\sqrt x}=\frac{\log2}{2\pi}.$$ This method generalises to other integrals such as \begin{align*}\int_0^\infty \frac{1}{(\pi^2+\ln^2 x)(1+x)^3} \frac{dx}{\sqrt x}&=\frac{3\log (2)}{8 \pi }-\frac{3 \zeta (3)}{16 \pi ^3}\\\int_0^\infty \frac{\ln x}{(\pi^2+\ln^2 x)(1+x)^3} \frac{dx}{\sqrt x}&=-\frac{\pi }{24}\\\int_0^\infty \frac{1}{(\pi^2+\ln^2 x)(1+x)^4} \frac{dx}{\sqrt x}&=\frac{5 \log (2)}{16 \pi }-\frac{9 \zeta (3)}{32 \pi ^3}\\\int_0^\infty \frac{\ln x}{(\pi^2+\ln^2 x)(1+x)^4} \frac{dx}{\sqrt x}&=-\frac{223 \pi }{5760}\\\int_0^\infty \frac{1}{(\pi^2+\ln^2 x)(1+x)^5} \frac{dx}{\sqrt x}&=-\frac{43 \zeta (3)}{128 \pi ^3}+\frac{15 \zeta (5)}{256 \pi ^5}+\frac{35 \log (2)}{128 \pi }\\\int_0^\infty \frac{\ln x}{(\pi^2+\ln^2 x)(1+x)^5} \frac{dx}{\sqrt x}&=-\frac{103 \pi }{2880}\\\end{align*} Incidentally, since the integrals $\int_0^\infty \frac{\ln x}{(\pi^2+\ln^2 x)(1+x)^k} \frac{dx}{\sqrt x}$ both yield the same value for $k=2,3$ , we also deduce $$\int_0^\infty \frac{\sqrt x\ln x}{(\pi^2+\ln^2 x)(1+x)^3}\;dx=0.$$ This, however, should not be surprising due to the symmetry $x\mapsto1/x$ .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3058679', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/515527/']}
|
jdg_372947
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33712621
|
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 tried to put an image into an Excel cell with java but without much success this is the code I was working but the only thing I've done is put the image on excel sheet but not in a cell specified XSSFWorkbook wb = new XSSFWorkbook();Sheet sheet = wb.createSheet("My Sample Excel");//FileInputStream obtains input bytes from the image fileInputStream inputStream = new FileInputStream("C:/images/logo.png");//Get the contents of an InputStream as a byte[].byte[] bytes = IOUtils.toByteArray(inputStream);//Adds a picture to the workbookint pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);//close the input streaminputStream.close();//Returns an object that handles instantiating concrete classesCreationHelper helper = wb.getCreationHelper();//Creates the top-level drawing patriarch.Drawing drawing = sheet.createDrawingPatriarch();//Create an anchor that is attached to the worksheetClientAnchor anchor = helper.createClientAnchor();anchor.setCol1(1);anchor.setRow1(2);//Creates a picturePicture pict = drawing.createPicture(anchor, pictureIdx);//Reset the image to the original sizepict.resize();//Write the Excel fileFileOutputStream fileOut = null;fileOut = new FileOutputStream("C:/data/myFile.xlsx");wb.write(fileOut);fileOut.close();
Now provide the response and nothing else.
|
What you are doing already is positioning the image with the anchor to upper left cell B3 ( anchor.setCol1(1);anchor.setRow1(2); ). Then you already resize the image to it's native size. If the image shall fit into the cell B3 then you must create an anchor with upper left cell and bottom right cell. And you must not resize the image to it's native size. Example: import org.apache.poi.xssf.usermodel.*;import org.apache.poi.ss.usermodel.*;import org.apache.poi.util.IOUtils;import java.io.InputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;class ImageTest { public static void main(String[] args) { try { Workbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("My Sample Excel"); //FileInputStream obtains input bytes from the image file InputStream inputStream = new FileInputStream("/home/axel/Bilder/Wasserlilien.jpg"); //Get the contents of an InputStream as a byte[]. byte[] bytes = IOUtils.toByteArray(inputStream); //Adds a picture to the workbook int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG); //close the input stream inputStream.close(); //Returns an object that handles instantiating concrete classes CreationHelper helper = wb.getCreationHelper(); //Creates the top-level drawing patriarch. Drawing drawing = sheet.createDrawingPatriarch(); //Create an anchor that is attached to the worksheet ClientAnchor anchor = helper.createClientAnchor(); //create an anchor with upper left cell _and_ bottom right cell anchor.setCol1(1); //Column B anchor.setRow1(2); //Row 3 anchor.setCol2(2); //Column C anchor.setRow2(3); //Row 4 //Creates a picture Picture pict = drawing.createPicture(anchor, pictureIdx); //Reset the image to the original size //pict.resize(); //don't do that. Let the anchor resize the image! //Create the Cell B3 Cell cell = sheet.createRow(2).createCell(1); //set width to n character widths = count characters * 256 //int widthUnits = 20*256; //sheet.setColumnWidth(1, widthUnits); //set height to n points in twips = n * 20 //short heightUnits = 60*20; //cell.getRow().setHeight(heightUnits); //Write the Excel file FileOutputStream fileOut = null; fileOut = new FileOutputStream("myFile.xlsx"); wb.write(fileOut); fileOut.close(); } catch (IOException ioex) { } }} If you remove the comment signs form the program rows ... //set width to n character widths = count characters * 256 int widthUnits = 20*256; sheet.setColumnWidth(1, widthUnits); //set height to n points in twips = n * 20 short heightUnits = 60*20; cell.getRow().setHeight(heightUnits);... you can resize the cell B3 and so the image resizes.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33712621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5158306/']}
|
jdg_372948
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
548938
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two hostnames sharing the same domain name which I want to serve over HTTPs. I've got a wildcard-SSL certificate and created two vhost configs: Host A listen 127.0.0.1:443 ssl;server_name a.example.com;root /data/httpd/a.example.com;ssl_certificate /etc/ssl/wildcard.cer;ssl_certificate_key /etc/ssl/wildcard.key; Host B listen 127.0.0.1:443 ssl;server_name b.example.com;root /data/httpd/b.example.com;ssl_certificate /etc/ssl/wildcard.cer;ssl_certificate_key /etc/ssl/wildcard.key; However, I get the same vhost served for either hostname.
Now provide the response and nothing else.
|
You need to split vhosts from ssl listening/configuration part: Listening part: server { listen 127.0.0.1:443 default_server ssl; server_name _; ssl_certificate /etc/ssl/wildcard.cer; ssl_certificate_key /etc/ssl/wildcard.key;} And now vhosts: server { listen 127.0.0.1:443; server_name a.example.com; root /data/httpd/a.example.com;}server { listen 127.0.0.1:443; server_name b.example.com; root /data/httpd/b.example.com;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/548938', 'https://serverfault.com', 'https://serverfault.com/users/99559/']}
|
jdg_372949
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51615421
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create a switch statement using the char index of a string and an Enum using this wrapper to get the value of the selected enum from a Description. It pretty much allows you to store a string to an enum value. Here is my if statement: if (msgComingFromFoo[1] == Convert.ToChar(Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString())){ //foo} and here is my switch statement: switch (msgComingFromFoo[1]){ case Convert.ToChar(Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString()): break;} Why is it accepting the if statement and not the switch ? I tried converting it to a char since I'm selecting an index from a string, but unfortunately it didn't work. Update: Here is the Message.Code Enum public class Message{ public enum Code { [Description("A")] FOO_TRIGGER_SIGNAL }} As you can see, I need the Description assigned to the enum not the enum value that is 0. Using Message.Code.FOO_TRIGGER_SIGNAL.EnumDescriptionToString() from the mentioned wrapper returns A not 0 Error: A Constant Value Is Expected
Now provide the response and nothing else.
|
You cannot have expressions in the case (prior to C# 7), but you can in the switch, so this will work: switch (ConvertToMessageCode(msgComingFromFoo[1])){ case Message.Code.FOO_TRIGGER_SIGNAL: break;} Where you will need to write ConvertToMessageCode to do the necessary conversion to the Message.Code enum. ConvertToMessageCode just abstracts the conversion details, you may find you do not need a separate method, but can make do with inline code in the switch statement, e.g., a cast.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51615421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9908376/']}
|
jdg_372950
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21183482
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a class like the one below: class Program { static void Main(string[] args) { var outputWindow = new OutputWindow(); var threads = new List<Thread>(); Action action = () => outputWindow.Display(20); for (int i = 0; i < 10; i++) { var thread = new Thread(() => action()) {Name = "Thread " + i}; threads.Add(thread); } foreach (var thread in threads) { thread.Start(); } } } public class OutputWindow { public void Display(int x) { for (int i = 0; i < x; i++) { Console.WriteLine(Thread.CurrentThread.Name + " Outputcounter: " + i); } } } Question is- is this thread safe and will this lead to any race condition on the local variable i inside the display method? Will all the threads increment the value of the variable "i" as expected(which is it increments the value and does not encroch into other threads value of i) If this is threadsafe, will it be safe to assume that any local variables declared within a method is always thread safe and shared variables are the ones which needs synchronization? Thanks,-Mike
Now provide the response and nothing else.
|
Each method invocation will have a separate set of local variables. However, those variables could refer to objects which other methods also use. For example: public void AppendSomething(StringBuilder builder){ builder.Append("Something");} Here builder is still a local variable (parameters are local variables) and each invocation of AppendSomething will have an independent variable - but you could call the method from multiple threads using the same StringBuilder reference, so that method is not thread-safe. (As StringBuilder isn't thread-safe.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21183482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336749/']}
|
jdg_372951
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27977479
|
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 CXF JAX-RS app being built with Maven. I'm working on converting it to Gradle, but using the Ant XJC task. The current build uses a couple of extensions, one of which is a copy of the "element wrapper" plugin, and the other is the "jaxb-fluent-api". I tried putting the jars for those two plugins into the xjc classpath, but when I run the XJC task, I get the following: java.util.ServiceConfigurationError: com.sun.tools.xjc.Plugin: Provider dk.conspicio.jaxb.plugins.XmlElementWrapperPlugin not a subtype The XmlElementWrapperPlugin class extends "com.sun.tools.xjc.Plugin". Any idea what's going on here? If it matters, my Maven configuration for the xjc plugin looks something like this: <plugin> <groupId>org.apache.cxf</groupId> <artifactId>cxf-xjc-plugin</artifactId> <executions> <execution> <id>generate-sources</id> <phase>generate-sources</phase> <goals> <goal>xsdtojava</goal> </goals> <configuration> <extensions> <extension>JAXBXMLElementWrapperPlugin:JAXBXMLElementWrapperPlugin:1.0.0</extension> <extension>net.java.dev.jaxb2-commons:jaxb-fluent-api:2.1.8</extension> </extensions> <xsdOptions> <xsdOption> <xsd>${basedir}/src/main/resources/schema/serviceCallResults.xsd</xsd> <packagename>com.att.sunlight.service.domain.serviceCallResults</packagename> <extension>true</extension> <extensionArgs> <extensionArg>-Xxew</extensionArg> <extensionArg>-summary ${basedir}/target/xew-summary.txt</extensionArg> <extensionArg>-instantiate lazy</extensionArg> <extensionArg>-Xfluent-api</extensionArg> </extensionArgs> </xsdOption> </xsdOptions> </configuration> </execution> </executions></plugin> Here's my "build.gradle", with only the repositories elided: apply plugin: 'java'apply plugin: 'maven'apply plugin: 'war'group = 'SunlightDataService'version = '1.2.4-SNAPSHOT'sourceCompatibility = 1.6targetCompatibility = 1.6repositories { ...}configurations { jaxb}dependencies { jaxb 'com.sun.xml.bind:jaxb-xjc:2.2.7-b41' jaxb 'com.sun.xml.bind:jaxb-impl:2.2.7-b41' jaxb 'javax.xml.bind:jaxb-api:2.2.7' jaxb "JAXBXMLElementWrapperPlugin:JAXBXMLElementWrapperPlugin:1.0.0" jaxb "net.java.dev.jaxb2-commons:jaxb-fluent-api:2.1.8" compile group: 'org.springframework', name: 'spring-beans', version:'3.2.8.RELEASE' compile group: 'org.springframework', name: 'spring-webmvc-portlet', version:'3.2.8.RELEASE' compile group: 'org.apache.cxf', name: 'cxf-rt-transports-http', version:'2.7.7' compile group: 'log4j', name: 'log4j', version:'1.2.16' compile group: 'org.springframework', name: 'spring-jdbc', version:'3.2.8.RELEASE' compile group: 'org.springframework', name: 'spring-context', version:'3.2.8.RELEASE' compile group: 'org.apache.cxf', name: 'cxf-rt-frontend-jaxrs', version:'2.7.7' compile group: 'org.apache.cxf', name: 'cxf-rt-bindings-xml', version:'2.7.7' compile group: 'org.apache.cxf', name: 'cxf-rt-databinding-jaxb', version:'2.7.7' compile group: 'org.apache.cxf', name: 'cxf-rt-core', version:'2.7.7' compile group: 'org.apache.cxf', name: 'cxf-api', version:'2.7.7' compile group: 'org.apache.cxf', name: 'cxf-rt-rs-extension-providers', version:'2.7.7' compile group: 'org.codehaus.jettison', name: 'jettison', version:'1.3.4' compile group: 'org.perf4j', name: 'perf4j', version:'0.9.14' compile group: 'cglib', name: 'cglib', version:'2.2.2' compile group: 'org.aspectj', name: 'aspectjweaver', version:'1.6.12' compile group: 'commons-collections', name: 'commons-collections', version:'3.2.1' compile group: 'esGateKeeper', name: 'GLCookieDecryption', version:'1.0.0' compile group: 'joda-time', name: 'joda-time', version:'2.3' compile group: 'org.apache.jackrabbit', name: 'jackrabbit-core', version:'2.4.0' compile group: 'org.apache.commons', name: 'commons-lang3', version:'3.1' testCompile group: 'org.springframework', name: 'spring-test', version:'3.2.8.RELEASE' testCompile group: 'oracle.jdbc', name: 'oracle.jdbc.OracleDriver', version:'1.0.0' testCompile group: 'com.atomikos', name: 'transactions-jta', version:'3.7.0' testCompile group: 'org.apache.cxf', name: 'cxf-rt-transports-http-jetty', version:'2.7.7' testCompile group: 'com.atomikos', name: 'transactions-jdbc', version:'3.7.0' testCompile group: 'org.mockito', name: 'mockito-all', version:'1.9.5' testCompile group: 'junit', name: 'junit', version:'4.10' testCompile group: 'org.assertj', name: 'assertj-core', version:'1.6.1' providedCompile group: 'javax.transaction', name: 'jta', version:'1.1' providedCompile group: 'javax.servlet.jsp', name: 'jsp-api', version:'2.1' providedCompile group: 'javax.servlet', name: 'servlet-api', version:'2.5'}task processXSDs() << { ant.taskdef(name: 'xjc', classname: 'com.sun.tools.xjc.XJCTask', classpath: configurations.jaxb.asPath) ant.xjc(destdir: 'tmp', package: "com.att.sunlight.service.domain.serviceCallResults", extension: true) { schema(dir: "src/main/resources/schema", includes: "serviceCallResults.xsd") arg(line: "-Xxew") arg(line: "-summary target/xew-summary.txt") arg(line: "-instantiate lazy") arg(line: "-Xfluent-api") }}compileJava.dependsOn processXSDs Update: I've determined that this is not an issue with the "Element Wrapper" extension. If I remove that jar from the classpath and rebuild, it reports the same error for the "Fluent API" plugin. I've also determined this isn't strictly a Gradle issue. I get the same symptom with an Ant "build.xml", and even a plain shell script directly calling the "XJCFacade" Java class. In fact, I can simplify this script a bit by not even specifying any schema files, which makes it clear this error happens even before trying to process any schemas. The following is my current script: #! /bin/bashjava -classpath "lib/commons-beanutils-1.7.0.jar;lib/commons-lang-2.2.jar;lib/commons-logging-1.1.1.jar;lib/istack-commons-runtime-2.16.jar;lib/jaxb2-basics-runtime-0.6.5.jar;lib/jaxb2-basics-tools-0.6.5.jar;lib/jaxb-api-2.2.7.jar;lib/jaxb-core-2.2.7.jar;lib/jaxb-fluent-api-2.1.8.jar;lib/jaxb-xew-plugin-1.4.jar;lib/jaxb-xjc-2.2.7.jar" com.sun.tools.xjc.XJCFacade -extension You could construct the same test by downloading all of those artifacts to your Gradle or Maven cache and copying them into a simple folder structure. Also note that I'm running this test mainly on Windows 7, but I zipped up this project and moved it to my CentOS VM and it gives me the exact same error.
Now provide the response and nothing else.
|
I have tried java -cp jaxb-api-2.2.7.jar;jaxb-core-2.2.7.jar;jaxb-xjc-2.2.7.jar;commons-logging-1.1.1.jar;commons-lang-2.2.jar;jaxb2-basics-tools-0.6.5.jar;jaxb-xew-plugin-1.3.jar com.sun.tools.xjc.XJCFacade -verbose -extension -d src xsd and indeed that fails with Exception in thread "main" java.util.ServiceConfigurationError: com.sun.tools.xjc.Plugin: Provider com.sun.tools.xjc.addon.xew.XmlElementWrapperPlugin not a subtype , so the problem is clearly reproducible. I have debugged java.util.ServiceLoader and it turned out that plugins should be passed as argument to XJC (not to classpath of Java). Actually, all maven plugins (like jaxb2-maven-plugin or maven-jaxb2-plugin …) know about this feature and form XJC argments correctly. So the correct command line is: java -cp jaxb-api-2.2.7.jar;jaxb-core-2.2.7.jar;jaxb-xjc-2.2.7.jar;commons-lang-2.2.jar;commons-logging-1.1.1.jar com.sun.tools.xjc.XJCFacade -classpath jaxb-xew-plugin-1.3.jar;jaxb2-basics-tools-0.6.5.jar -verbose -extension -Xxew -d src xsd Note that -classpath is argument for XJC. commons-xxx libs can go to system classpath as the packages they export are not screened, but jaxb2-basics-tools should be in XJC classpath. If you are interested in details: This happens because XJC does classpath loader screening to be able to load higher versions of JAXB API in JRE that has lower build-in version of API. See XJCFacade.java line 69 . That means that com.sun.tools.xjc.Plugin is loaded once by custom XJCFacade classloader while the same class is loaded by another (actually, parent) classloader again when Class.forName("com.sun.tools.xjc.addon.xew.XmlElementWrapperPlugin") is called, but now classes are not equal. Actually you can workaround like this (solution found after source code inspection): java -Dcom.sun.tools.xjc.XJCFacade.nohack=true -cp jaxb-core-2.2.7.jar;jaxb-xjc-2.2.7.jar;commons-lang-2.2.jar;commons-logging-1.1.1.jar;jaxb2-basics-tools-0.6.5.jar;jaxb-xew-plugin-1.3.jar com.sun.tools.xjc.XJCFacade -verbose -extension -Xxew -d src xsd Note that I have removed jaxb-api-2.2.7.jar from Java classpath but you'd better put JAXB API into lib/endorsed as it may not work on different Java versions: works fine for Java 7, because it's JAXB API is close to 2.2.7 , but may not work on Java 6 + JAXB API 2.2.11.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27977479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10508/']}
|
jdg_372952
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
262119
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have just got back a manuscript with a comment from a reviewer that has been puzzling...I am getting data for two neuroimaging modalities (A, B). For each modality I have information for 8 regions of the brain. Moreover I have baseline and follow-up data for 16 patients. Therefore 256 observations. The reviewer is asking me explicitly 'if the two modalities (A, B) are correlating if someone plots baseline/follow-up data for all patients and regions'. The way that I thought would be to employ linear mixed models as follows: >mod <- lmer(A ~ B * Time.Point +(1 |ID/region), data=df) A, B are continuous variable and Time Point is a factor (Baseline, Follow up)In this way I would nest the regions to every patient as a random variable. >summary(mod) ... Fixed effects: Estimate Std.Err df t value Pr(>|t|) (Intercept) 1.68758 0.18635 193.11000 9.056 <2e-16 *** B -0.20152 0.15555 196.17000 -1.296 0.1966 Time.PointFollow up 0.16453 0.08861 123.36000 1.857 0.0657 . B:Time.PointFollow up -0.17367 0.07494 123.36000 -2.317 0.0221 * ... > anova(mod) Analysis of Variance Table of type III with Satterthwaite approximation for degrees of freedom Sum Sq Mean Sq NumDF DenDF F.value Pr(>F) B 0.0066976 0.0066976 1 199.89 3.6523 0.05742 . Time.Point 0.0063231 0.0063231 1 123.36 3.4480 0.06571 . B:Time.Point 0.0098489 0.0098489 1 123.36 5.3707 0.02213 * --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1. The interaction is significant but not the fixed factors.From what I understand that means that there is a significantly different slope at the two time points in the relationship between A and B. I can visualise the different slopes with: plot(allEffects(model)) But the question remains: Is the relationship between A, B significant?
Now provide the response and nothing else.
|
That's a nicely asked and interesting question. I have some questions : Do you already have insights about the feasibility of your goal ? (anticipate some failures) Did you identify variable that augur a failure ? What is the typical time before failure ? I think the natural way to study such a problem would be to use survival analysis. And being familiar with it will be plus ! What I would do (despite I'm not aware all specificity of your problem) : Compute your time of interest variable ($y$) and occurrence of event variable ($delta$) : in this step you may : consider the failure time as event consider the preventive maintenance time as censoring variable skip the shift time for the computation of failure time and censoring Fit a Cox model on this data : Remark : you have time changing covariates (there is at this address a vignette about how to handle time dependent covariates in the Cox model : https://cran.r-project.org/web/packages/survival/vignettes/timedep.pdf ) This step may not be easy (I don't know I'm not a specialist of time dependent covariates). For instance I'm thinking you may be in trouble because you may have too much change points in your data (time when one of the covariate changes) Then, to use you model (and see if you can predict that a failure will occur in the future (enough time before)), you should use your Cox model : The Cox model will give you an estimation of the hazard rate. So the simplest thing you may do to use your model is to compute an online prediction as your machine is running, and decide to stop the machine when the hazard rate exceed a threshold) Though the natural way to study your problem would be to use survival analysis, you may use classification methods especially if the time before failure is short (this way you are analyzing past data and you will not be disturbed by censoring). In this case, I think the overall approach would be quite similar. Give us some feedback about your problem !
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/262119', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/93473/']}
|
jdg_372953
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5372091
|
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 helper class in my program which has many static functions used in different classes of my program. E.g. helper.h : Class helper { public: static void fn1 () { /* defined in header itself */ } /* fn2 defined in src file helper.cpp */ static void fn2(); } Helper has only static member functions. So, no objects of helper are created by other modules. Helper functions are used in other modules like: A.cpp #include "helper.h"A::foo() { helper::fn1(); helper::fn2();} B.cpp #include "helper.h"B::foo() { helper::fn1(); helper::fn2(); } Does the compiler create separate copies of helper functions in A.cpp and B.cpp ? I read some earlier posts and I gathered from the replies that compiler will create so. But when I print the address of fn1 and fn2 as printf("Address of fn1 is %p\n", &helper::fn1); and printf("Address of fn1 is %p\n", &helper::fn1); from both A.cpp and B.cpp , I get the same address. I'm confused now. Can someone clarify, If I'm missing something. The reason I'm worried about multiple copies of helper functions (if it happens) is we are trying to reduce our executable size and wanted to optimize it.
Now provide the response and nothing else.
|
Functions defined inside the class body are implicitly marked inline . If you take the address of the function, the compiler will also create a regular copy of the function (per compilation unit), but the linker will pick just one of these copies to include in the executable, so there's only one address. However, the inlining process could make many copies of the function, even more than the number of compilation units. Often the increased size of duplicating the code is offset by the increased optimization possible by eliminating argument passing and function call overhead, as well as opportunities for common subexpression elimination, etc. Although inlining is often considered a tradeoff between size and speed, the size increase is often negligible or even negative. The function that's just declared in the class and then implemented in a single compilation unit, definitely has just one copy in the executable.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5372091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/668636/']}
|
jdg_372954
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4624811
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is a related question to this: What's the best method to pass parameters to SQLCommand? But I am wanting to know what the differences are and if there are any problems with the different ways. I usually use a structure something like this: using (SqlConnection conn = new SqlConnection(connectionString))using (SqlCommand cmd = new SqlCommand(SQL, conn)){ cmd.CommandType = CommandType.Text; cmd.CommandTimeout = Settings.Default.reportTimeout; cmd.Parameters.Add("type", SqlDbType.VarChar, 4).Value = type; cmd.Connection.Open(); using (SqlDataAdapter adapter = new SqlDataAdapter(cmd)) { adapter.Fill(ds); } //use data } Now there are several ways to add the cmd parameters and I am wondering which is best: cmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = "Bob";cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = "Bob";cmd.Parameters.Add("@Name").Value = "Bob";cmd.Parameters.AddWithValue("@Name", "Bob"); Having the length of the field in the passing of the varchars I assume is not preferable as it's a magic value which may be changed later at the database. Is this correct? Does it cause any issue passing a varchar in this way (performance or other), I assume it defaults to varchar(max) or the database equivalent. I am reasonably happy this will work. The part that concerns me more is the loss of the SqlDbType enum if I am using the third or fourth options I listed above I am not supplying a type at all. Are there cases where this won't work I can imagine problems with varchar being incorrectly cast to char or vice versa or perhaps issues with decimal to money.... In terms of the database the field type I would say is much less likely to change than the length so is it worth retaining?
Now provide the response and nothing else.
|
In my experience, I would make sure I do these things: make sure it's you that defines the data type for the parameter. ADO.NET does a decent job at guessing, but in some cases, it can be terribly off - so I would avoid this method: cmd.Parameters.Add("@Name").Value = "Bob";cmd.Parameters.AddWithValue("@Name", "Bob"); Letting ADO.NET guess the type of the parameter by the value passed is tricky, and if it's off for any reason, those are really tricky bugs to track and find! Imagine what happens when you pass in a DBNull.Value - what datatype should ADO.NET pick for that? Just be explicit - say what type it is you want! if you're using string parameters, make sure to explicitly define the length - so I would avoid this method, too: cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = "Bob"; If you don't provide a length, ADO.NET might default to some arbitrary value, or the length of the string passed in as a value, or something else - you're never quite sure. And if your length doesn't match what the stored proc really expects, you might see conversion and other unpleasant surprises. So if you define a string, define its length, too! So in your case, the only approach that really works for me is this one here: cmd.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = "Bob"; because it a) defines the data type to use explicitly, and b) defines the length of the string explicitly.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4624811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16989/']}
|
jdg_372955
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8330188
|
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 come from a MySQL background and am trying to wrap my head around MongoDB . In particular, I'm struggling to conceptualize how I should model n:n relationships the "Mongo way." For this example, let's say we have two collections : users and interests . We need to be able to represent or query for several things in our data: User's interests User's rating of interest, e.g. "like" or "dislike" Users with a given interest Counter (which can be incremented/decremented) of each rating of the interest Interest name In MySQL , I would have created a users_interests table indexed on both user IDs and interest IDs. For the counter, I would have had separate columns for each rating type, and each time a user rated/un-rated an interest, done a transaction to ensure that the counts were never false. I've tried reading about some schema designs , but to no avail. Can you help a lost soul find the way?
Now provide the response and nothing else.
|
Great question. Let me first outline a bit of how the N:N relationship works then I'll go into detail on each of your bullet points. N:N in MySQL normally you have your pivot table associating between your user and interests (user_interests table). In mongo you do this a bit differently. You still have a users and interest collection, however instead now, you store a list of keys under interests for a user. SO something like this: User Collection { "name":"Josh", "user":"jsmith", "interests":[ { "_id":12345, "rating":"like" }, {..}.. ]} By storing your interests in a list which is keyed off on your interest table, you can perform each of the actions you require. If you wanted to do a query you'd od it based on the ID which is in the interest table then do a query using the $in modifier . Now for your interests collection I'd do the following: User Interest { "_id":objectId "label":"Swimming", "count":intValue} When adding an interest to a users document, the count variable would then depend on the definition of your ratings. If you're storing your ratings in a separate area (or in logic), then the value you assigned to them would be what you relate then to the int value in interest. IE: User rates it meh (which has a value of 1) then you would add 1 to the count value. Hopefully this is helpful and has at the very least brought about some other ideas on how to structure it! Best of luck, remember MONGO IS AWESOME.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8330188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/373496/']}
|
jdg_372956
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2128459
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I read somewhere that Java is case-sensitive. I have been unable to confirm this. Is it? If so, why?
Now provide the response and nothing else.
|
I read somewhere that Java is case-sensitive. I have been unable to confirm this. Java source code is case sensitive, if you mean that. i.e. Double is not the same type as double , and you can have two different and separate variables myData and mydata . Is it? If so, why? Case sensitivity is the norm in most programming languages and environments, because lower and upper case letters are represented differently at the lowest levels. To a computer, "a" and "A" are two completely different things, and it takes extra work to make it act as if they were the same. Furthermore, some languages have very tricky special rules for casing, e.g. the German letter ß has no uppercase version and is typically uppercased to "SS" - so should "weiß" and "WEISS" be considered syntactially identical? Even worse is Turkish: they have two separate letters i with and without a dot, and each has its own uppercase version. So in Turkey, "IMAGE" is not the uppercase version of "image"! And this is not irrelevant at all, especially for Java, since you can actually use all these letters as identifiers in your Java programs if you want. In the light of all this, it's very understandable that programming language designers would choose the simple solution of having the syntax be case sensitive.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2128459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240698/']}
|
jdg_372957
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
68727567
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Coil accepts a drawable resource as an error placeholder. Is there a way to use an image URL here instead? Here is the code I am working on: // Global variablesvar currentlySelectedImageUri = mutableStateOf<Uri?>(null)var previousImageUri: Uri? = null// @Composable fun() {...Image( painter = rememberImagePainter( if (currentlySelectedImageUri.value != null) { // use the currently selected image currentlySelectedImageUri.value } else { if (previousImageUri != null) { // use the previously selected image previousImageUri } else { R.drawable.blank_profile_picture // use the placeholder image } }, builder = { placeholder(R.drawable.blank_profile_picture) error(R.drawable.blank_profile_picture) // FIXME: Set the previously selected image }), contentDescription = "profile image", contentScale = ContentScale.Crop, modifier = Modifier.fillMaxWidth())
Now provide the response and nothing else.
|
In Coil 2.0.0 both AsyncImage and rememberAsyncImagePainter have error parameter that takes any other painter: AsyncImage( model = imageURL, contentDescription = null, error = painterResource(R.drawable.error)) Coil 1.4.0 version: You can check painter.state value. Initially it's ImagePainter.State.Empty , while image is loading it's ImagePainter.State.Loading , and if it failed - it becomes ImagePainter.State.Error . At this point you can change coil url, as an example, using local remember variable: val localImagePainterUrl = remember { mutableStateOf<Uri?>(null) }val painter = rememberImagePainter( data = localImagePainterUrl.value ?: currentlySelectedImageUri.value ?: previousImageUri ?: R.drawable.blank_profile_picture, builder = { placeholder(R.drawable.blank_profile_picture) })val isError = painter.state is ImagePainter.State.ErrorLaunchedEffect(isError) { if (isError) { localImagePainterUrl.value = previousImageUri }}Image( painter = painter, ...)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/68727567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16611863/']}
|
jdg_372958
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2799212
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm studying for an exam and I ran into these problems. I'm having a feeling that this is not true. Hence, I don't need to prove. I need to just provide a counterexample. However, the appropriate example is not just coming. Any help? Prove or give a counterexample: If $\sum_{n=1}^{\infty}a_n=1$ and each $a_n\geq 0,$ then $\lim\limits_{n\to\infty}na_n=0$ If $a_n\geq 0$ and $\sum_{n=1}^{\infty}a_n$ converges, then $\lim\limits_{n\to\infty}na_n=0$
Now provide the response and nothing else.
|
Let $a_{n^2}=\dfrac{1}{n^2}$ and $a_n=0$ otherwise. Then $na_n$ does not tend to $0$, and the series is convergent. The sum is $\dfrac{\pi^2}{6}$, but note you can multiply each term by the same constant to make the limit any nonzero number you wish. Note, however, that if $a_n$ is also nonincreasing, the situation is different: Series converges implies $\lim{n a_n} = 0$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2799212', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/544685/']}
|
jdg_372959
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
377707
|
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 Michael Artin's Algebra textbook page 484 Chapter 12 Exercise 1.6: A module is called simple if it is not the zero module and if it has no proper submodule. (a) Prove that any simple module is isomorphic to R/M, where M is a maximal ideal. My questions are: Is $R/M$ a left module over $R$? or over itself $R/M$? When we defined a module $N$ we defined a map $R\times N\to N$ where $R$ is a ring and $N$ is an Abelian group. Now let the ring $R$ be $M$ as given in question, where $M$ is a maximal ideal of $R$. So the map becomes $M\times N\to N$. As far as I know, there no equivalent notion of ideal in module. The reason I said that is because from the definition of quotient module $V/W$, $W$ is just a submodule of $V$, not an "ideal" submodule of $V$. Is my reasoning correct? If my reasoning in 2. above is wrong, then how can we interpret a maximal ideal in a language of module? Is there a definition of maximal ideal in module distinct to definition of a maximal ideal in ring? To prove the question, I consulted other sources in the internet. There is a proof that says "Any submodule of $R/M$ is an ideal, since it would be an additive group that is closed under multiplication by elements of $R$ and therefore $R/M$." Since I am still not clear of the definition of ideal in module, I am confused by the meaning of the above statement, especially what does it mean by "closed under multiplication by elements of R and therefore $R/M$"? Thank you very much for any helps. I really appreciate it.
Now provide the response and nothing else.
|
An right $R$ module is, as you said, an abelian group $N$ and the map from $N\times R\to N$ satisfying special properties like distributivity etc. In other words, $nr$ is another element of $N$ for every $n\in N$, and $r\in R$. If $N'$ is an additive subgroup of $N$, we say that it's a submodule if $n'r\in N'$ for every $n'\in N'$ and $r\in R$. In other words, it looks like $N'R\subseteq N'$ (which didn't necessarily have to happen!). Now $R$ can be considered as a right module over itself, since the ring multiplication $R\times R\to R$ satisfies all the axioms that are necessary to make $R$ into a right module. Since we have already defined what a submodule is, we can ask what the submodules of the right module $R$ are. They an additive subgroup $I$ of $R$ is a submodule if $IR\subseteq I$. You'll notice that looks like the definition of a right ideal: and that's exactly what it is! The term "right ideal" is just another term for a submodule of the right module $R$. Similarly, $R$ can be considered as a left module over itself, and you can ask about its left submodules (=left ideals). Nobody says "ideals in a module" because ideals are reserved as a term for submodules of $R$. If you already know that for any submodule $N'$ of $N$ you can form the quotient module $N/N'$, then it will be no surprise that if $M$ is a right ideal (=right submodule!) of $R$, then you can form the quotient module $R/M$. The proof of the title fact is very easy if you know the isomorphism theorems for modules. If $S$ is a right $R$ module (nonzero, of course), pick a nonzero $s\in S$ and make a map from $R\to S$ by $r\mapsto sr$. Call this map $\phi$. This is clearly a nonzero map to $S$. Since the image is a submodule of $S$ and $S$ is simple, it must be all of $S$. By the isomorphism theorem, $R/\ker(\phi)\cong Im(\phi)=S$. By the correspondence of submodules, the absence of submodules of $S$ corresponds to an absence of submodules between $R$ and $\ker(\phi)$, and so $\ker(\phi)$ is a maximal right ideal of $R$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/377707', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71346/']}
|
jdg_372960
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8085
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
It is well known that the Fourier transform $\mathcal{F}$ maps $L^1(\mathbb{R}^d)$ into, but not onto, $\overline{C_0^0}(\mathbb{R}^d)$, where the closure is taken in the $L^\infty$ norm. This is a consequence of the open mapping theorem, for instance. My question is: what's an explicit example of a function in $\overline{C_0^0}(\mathbb{R}^d)$ which is not in the image of $L^1(\mathbb{R}^d)$ under the Fourier transform? I would also like to know whether there is a useful characterization of $\mathcal{F}(L^1(\mathbb{R}^d))$. Remark: it is easy to see that the Banach space $\overline{C_0^0}(\mathbb{R}^d)$ consists of all continuous functions $f$ on $\mathbb{R}^d$ such that $f(\xi)\rightarrow 0$ as $|\xi|\rightarrow\infty$.
Now provide the response and nothing else.
|
For the first question I commented above that the function $\sqrt(1-|x|^2)$ extended to $0$ outside the unit ball is not the fourier transform of any integrable function in dimension 2 or higher. In dimension $1$ there's "Further results" of Chapter I in Introduction to Fourier Analysis of Stein. In case you don't have access to the book, this is the construction:Observe that $|\int_a^b \sin(x)/x\ dx| \leq C<\infty$ for any strictly positive $a$ and $b$. Now, if $f\in L^1$ and $F(f)$ is odd you have $F(f)(x) = \int f(t) \sin(xt)\ dt$ up to a multiplicative constant. Than it's easy to see from the previous estimate that $|\int_1^b F(f)(x)/xdx|\leq C'<\infty$ uniformly in $b$. So a function which is continuous, odd and which decays too slowly ($1/\log(x)$ will do) is not the Fourier transform of an integrable function.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/8085', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2274/']}
|
jdg_372961
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2648107
|
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:
$U$ - unitary operator on complex Hilbert space. Show that$\sigma(U) \subset \{z \in\mathbb C : |z| = 1\}.$ So $U$ is unitary operator if is is surjective and it preserves a scalar product and a unitary operator is a bounded linear operator $U : H → H$ on a Hilbert space H that satisfies $U^*U = UU^* = I$, where $U^*$ is the adjoint of $U$, and $I : H \to H$ is the identity operator. But how do I show that $\sigma(U) \subseteq \{z \in C : |z| = 1\}.$ ? Thanks in advance for any help
Now provide the response and nothing else.
|
A unitary operator $U$ is invertible with inverse $U^{-1}=U^*$. So$\|U\|=\|U^{-1}\|=1$. Any operator $B$ with $\|B\| < 1$ is such that $I-B$ is invertible with $(I-B)^{-1}=\sum_{n=0}^{\infty}B^{n}$. Therefore, if $|\lambda| < 1$, the following is invertible:$$ U-\lambda I = U(I-\lambda U^{-1})$$And, for $|\lambda| > 1$, the following is also invertible:$$ U-\lambda I=-\lambda\left(I-\frac{1}{\lambda}U\right)$$So the spectrum of a unitary $U$ is a subset of the unit circle in the complex plane.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2648107', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/523505/']}
|
jdg_372962
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27477730
|
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 many gzipped files stored on S3 which are organized by project and hour per day, the pattern of the paths of the files is as: s3://<bucket>/project1/20141201/logtype1/logtype1.0000.gzs3://<bucket>/project1/20141201/logtype1/logtype1.0100.gz....s3://<bucket>/project1/20141201/logtype1/logtype1.2300.gz Since the data should be analyzed on a daily basis, I have to download and decompress the files belongs to a specific day, then assemble the content as a single RDD. There should be several ways can do this, but I would like to know the best practice for Spark. Thanks in advance.
Now provide the response and nothing else.
|
The underlying Hadoop API that Spark uses to access S3 allows you specify input files using a glob expression . From the Spark docs : All of Spark’s file-based input methods, including textFile, support running on directories, compressed files, and wildcards as well. For example, you can use textFile("/my/directory") , textFile("/my/directory/*.txt") , and textFile("/my/directory/*.gz") . So in your case you should be able to open all those files as a single RDD using something like this: rdd = sc.textFile("s3://bucket/project1/20141201/logtype1/logtype1.*.gz") Just for the record, you can also specify files using a comma-delimited list, and you can even mix that with the * and ? wildcards. For example: rdd = sc.textFile("s3://bucket/201412??/*/*.gz,s3://bucket/random-file.txt") Briefly, what this does is: The * matches all strings, so in this case all gz files in all folders under 201412?? will be loaded. The ? matches a single character, so 201412?? will cover all days in December 2014 like 20141201 , 20141202 , and so forth. The , lets you just load separate files at once into the same RDD, like the random-file.txt in this case. Some notes about the appropriate URL scheme for S3 paths: If you're running Spark on EMR, the correct URL scheme is s3:// . If you're running open-source Spark (i.e. no proprietary Amazon libraries) built on Hadoop 2.7 or newer, s3a:// is the way to go. s3n:// has been deprecated on the open source side in favor of s3a:// . You should only use s3n:// if you're running Spark on Hadoop 2.6 or older.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27477730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/698067/']}
|
jdg_372963
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
721907
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to print out the first line of each .txt file that is more than a 100 bytes. So far, I've managed to gather the files that match the criteria but I don't know how to print out the files' first line of text. find -size +100c -name "*.txt" Or am I on the wrong track completely?
Now provide the response and nothing else.
|
You need to run head -n 1 on each file: find . -size +100c -name '*.txt' -execdir head -n 1 {} \; or, if your find doesn’t support -execdir , find . -size +100c -name '*.txt' -exec head -n 1 {} \; If your head version supports -q , or you don’t care about the headers shown for each file when multiple files are processed in one invocation, you can make both variants slightly more efficient using … -exec head -q -n 1 {} + (See Race Conditions with -exec to understand the benefits of -execdir .)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/721907', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/546118/']}
|
jdg_372964
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
482068
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
(a) $5$ $|$ $3^{3n+1}+2^{n+1}$ (b) $21$ $|$ $4^{n+1} + 5^{2n-1}$ (c) $24$ $|$ $2 \cdot7^n + 3 \cdot5^n - 5$ These are trivial by using induction. But I have tried to prove it by binomial theorem and remainder theorem, but couldn't succeed. Please help to prove it.
Now provide the response and nothing else.
|
Hints with modular arithmetic: $$(a)\;\;3^3=2\pmod 5\implies \left(3^{3}\right)^n\cdot 3=2^n\cdot 3\implies 3^{3n+1}+2^{n+1}=2^n(3+2)\pmod 5$$ $$(b)\;\;5^2=4\pmod {21}\implies 4^{n+1}+5^{2n-1}=4^n(4+5^{-1})\pmod{21}\;,\;$$ $$\text{but}\;5^{-1}=-4\pmod{21}\ldots$$ Now you try something similar as the above for the third one
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/482068', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91374/']}
|
jdg_372965
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3632385
|
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 really need to get started with source control because I'm going absolutely crazy keeping track of my code and modifications as it is. I'm a single developer on Windows. I use Eclipse for most of my development. Some of my projects are saved in wamp/www folder. Other non-PHP projects are in one or more Eclipse workspaces. I don't work in a team with other developers, so my needs are different this way: I need something that lets me create a local repository. Don't want to depend on an outside site. What I need is the version control, not the external backup. Easy backup is really really important to me. I need to easily backup and restore the repository if I format my computer. I found this question that suggests a version control called Fossil which sounds really attractive in my case, because the whole system is a sqlite file. This would be super easy to backup and restore, but I'd prefer to something a little more well-known if there's any other well-known version systems that let me do the same thing. fossil-scm.org/index.html/doc/tip/www/index.wiki I need something that would preferably play nice with wamp. I'm leaning on the side of git because a lot of people talk about it, but I wonder if it's really the right thing for me. I have a feeling it's best for teams.
Now provide the response and nothing else.
|
One of fossil's strong advantages is that it was designed for "low ceremony". You don't have to do much configuration of anything, the database file itself can be kept locally, and it mostly just stays out of the way. I've been using it on a handful of projects that are mostly single-principle-developer and am becoming quite attached to it. It has a small user community partially because it hasn't had much overt marketing or evangelism. But that community makes up for its lack of marketing by being very responsive on its mailing list. But it is also the version control standing behind SQLite, so it is both a user of SQLite for its database file, as well as an important supporting tool for SQLite's implementation. Even for a single user, taking advantage of the ease of replication of a repository is a good way to provide a backup. Hide your repositories on a second machine with a minimal amount of CGI configuration and you can autosynch your work and have a live backup. Put that machine in a friend's house or at an inexpensive webhost and you have an offsite backup. Edit: See the fossil homepage for a good starting point. Any repository can be viewed via the built-in web interface which allows access to the timeline, ticket system, wiki, and project settings. It also can be used to view documents that are checked into the repository. In fact, all links to pages at the fossil web site are being served by a copy of fossil. There is a decent book in draft form that walks through the process of using fossil for common tasks in a reasonably sized project. The source repository for SQLite is also maintained by fossil, and its web interface is served by a copy of fossil as well. All the SQLite repositories and the fossil repository are kept synchronized among several geographically separated servers by cron jobs that do periodic fossil sync commands. One easy way to get a hold of a repository with a rich history to play around with is to clone the source to fossil itself. To do this, put a copy of the fossil executable in your PATH, then in an empty folder somewhere say C:...>fossil clone http://www.fossil-scm.org/ fossil.fossilC:...>mkdir srcC:...>cd srcC:...>fossil open ../fossil.fossil You are now standing in an open fossil repository containing the complete source code and revision history of fossil. With GCC, awk, and zlib available, you should be able to build it from source. (On Windows, it is easiest to build with MinGW from an MSYS bash prompt in my experience.) You can periodically do fossil update to keep your clone current, and I recommend you try fossil ui to see the full power of the web interface with administrative access to your clone.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3632385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/438520/']}
|
jdg_372966
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43820
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In this video (at 5:09 mark) Zoe Harcombe says the following: The body needs those basal metabolic calories in the form of fat, protein, vitamins, and minerals. And that's all it needs for those. Carbohydrates are of no use to the body whatsoever for the basal metabolic need. Carbohydrates provide energy. Can anyone verify this claim?
Now provide the response and nothing else.
|
No. She talks about basal metabolic rate. And the body uses every source of fuel to fulfil this necessity. This includes carbohydrates. They are used for this and they are even the preferred source of energy for that. Ketosis states are only achieved if supply of carbohydrates are too low to meet these requirements. This looks quite like a simple reversal of language that just needs interpretation: For a large part this seems almost adequate, albeit in oversimplified form of imprecise terms. If you watch the video, it becomes clear that she talks about: Basal metabolic rate Metabolism comprises the processes that the body needs to function. 2 Basal metabolic rate is the amount of energy per unit time that a person needs to keep the body functioning at rest. Some of those processes are breathing, blood circulation, controlling body temperature, cell growth, brain and nerve function, and contraction of muscles. Basal metabolic rate (BMR) affects the rate that a person burns calories and ultimately whether that individual maintains, gains, or loses weight. The basal metabolic rate accounts for about 60 to 75% of the daily calorie expenditure by individuals. Nothing in the body needs sugar — from the diet and strictly speaking — or any other carbohydrate; Although one current recommended dietary carbohydrate intake for adults is 150 g/d, it is interesting to examine how this recommendation was determined at a recent international conference (5) : “The theoretical minimal level of carbohydrate (CHO) intake is zero, but CHO is a universal fuel for all cells, the cheapest source of dietary energy, and also the source of plant fiber. In addition, the complete absence of dietary CHO entails the breakdown of fat to supply energy [glycerol as a gluconeogenic substrate, and ketone bodies as an alternative fuel for the central nervous system (CNS)], resulting in symptomatic ketosis. Data in childhood are unavailable, but ketosis in adults can be prevented by a daily CHO intake of about 50 g. Eric C Westman: "Is dietary carbohydrate essential for human nutrition?" The American Journal of Clinical Nutrition, Volume 75, Issue 5, May 2002, Pages 951–953, DOI except the brain: The mammalian brain depends upon glucose as its main source of energy, and tight regulation of glucose metabolism is critical for brain physiology. Consistent with its critical role for physiological brain function, disruption of normal glucose metabolism as well as its interdependence with cell death pathways forms the pathophysiological basis for many brain disorders. Sugar for the brain: the role of glucose in physiological and pathological brain function All other organs, liver, muscles etc., might get their energy needs from fat or even protein. How good of an idea that is would be another question. But as the brain needs carbs and accounts for quite a bit of metabolic rate , this specific organ should not be discounted… We find that the brain’s metabolic requirements peak in childhood, when it uses glucose at a rate equivalent to 66% of the body’s resting metabolism and 43% of the body’s daily energy requirement, and that brain glucose demand relates inversely to body growth from infancy to puberty. Our findings support the hypothesis that the unusually high costs of human brain development require a compensatory slowing of childhood body growth. Christopher W. Kuzawa et al.: "Metabolic costs and evolutionary implications of human brain development", Proc Natl Acad Sci U S A. 2014 Sep 9; 111(36): 13010–13015, 2014 Aug 25 . DOI If there is no carbohydrate coming from food, the liver will and has to produce ketones which can sustain brain function or engage in gluconeogenesis . But immediately before the questioned claim we see: The body needs those basal metabolic calories in the form of fat, protein, vitamins, and minerals. And that's all it needs for those. Vitamins and Minerals provide zero calories. What the author seems to mean is that "food contains calories" and that from that food she regards only the fat, protein, vitamins and minerals as essential nutrients; or 'needed for basic metabolism'? Within the framework of a special weight reduction diet, that would then make some sense, albeit the terminology and its usage remain confusing. With this level of linguistic imprecision in scientific terminology, it seems hard to answer "is this correct" with anything else but: "No". Thus, cells that use glucose as their primary energy source are less susceptible to stress and harmful conditions than cells that use other energy sources or that exhibit higher rates of glycolysis. Although our knowledge about the critical role of glucose metabolism in the maintenance of high level brain function has grown considerably in recent years, the various factors that regulate glucose uptake and utilization in the CNS are not well understood. Moreover, the brain must regulate the relative use of glucose, glutamine, and ketone bodies for energy under normal circumstances and especially during development and aging. The brain is the metabolically most active organ and is therefore highly dependent on a continuous supply of its fuel. To meet its very high energy demands, the brain (around 1/40 of the body weight) possesses a relatively high blood flow and glucose consumption equal in amount to about one-fifth of the entire resting requirements of the body. In mammals, the regulation of fuel metabolism is regulated principally to serve the needs of brain and muscle, the major consumers of fuel. The adult mammalian brain relies almost completely on glucose as energy source while ketone bodies (KB) are preferentially directed toward lipid synthesis (Roeder et al., 1982; Yeh, 1984). The KB consist of acetoacetate, 3-hydroxybutyrate, and acetone. In nonruminant mammals, the liver is the only significant site of KB formation through fatty acid β-oxidation. Cultured astrocytes, however, may produce KB at rates similar to those of hepatocytes and like hepatocytes appear to be ketogenic cells (Blazquez et al., 1998; Guzman and Blazquez, 2001). After entering the blood, KB are oxidized in extrahepatic tissues, under particular circumstances also the brain, by mitochondrial enzymes to form acetyl-CoA, the substrate of the tricarboxylic acid (TCA) cycle. Glycolysis not only meets the brain’s constant need for fuel but also provides the substrate for anabolic processes, namely pyruvate which via the TCA cycle and anaplerotic pathways is the source for a variety of amino acids and neurotransmitters such as GABA and glutamate, and for acetyl-CoA which is used for lipid and acetylcholine (ACh) synthesis. Donard Dwyer (Ed): "Glucose Metabolism in the Brain", International Review Of Neurobiology Volume 51, Academic Press: Amsterdam, Boston, 2002 . Simple glucose is often described as the preferred fuel for all cells. That most of them can also use an alternative energy source doesn't make the carbohydrates "useless for basal metabolic rate". The claim seems more like a simplified demonisation of a nutrient a human body usually puts to good use to stay alive; and sometimes even to use a brain for thinking. The video with the claim seems to advertise a low-carb diet and sells it by using a description for a weight-reduction and -control diet that seems to be confusing metabolic pathways of 'calories' from minimal amounts of dual-use essential macronutrients (proteins) with calories from 'pure fuel' macronutrients (carbs). What the claimant apparently wants to express with 'basal metabolic rate' is that the first fraction of ingested proteins are usually used for tissue maintenance and build-up, like muscles; and can be used as energy as well. Whereas carbohydrates are mainly used for immediate energy or storage in glycogen and fat. As the author of the claim is now a somewhat controversial figure, some circumstantial evidence might help to evaluate her statements: Correction to Harcombe Z, Baker JS, Cooper SM, et al. Evidence from randomised controlled trials did not support the introduction of dietary fat guidelines in 1977 and 1983: a systematic review and meta-analysis. Open Heart 2015;2:e000196. doi:10.1136/openhrt-2014-000196 DOI (Included here, as the authors undeclared conflict of interest seems to play no role in two Wikipedia pages: Saturated fat , Fat ) ASA Adjudication on Zoë Harcombe Upheld in part Internet (on own site) 03 December 2014 And a nice collection of other popular claims by the very same author: Healthy eating according to Zoe Harcombe ,
|
{}
|
{'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/43820', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/48737/']}
|
jdg_372967
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
431167
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I got a string like the following: test.de. 1547 IN SOA ns1.test.de. dnsmaster.test.de. 2012090701 900 1000 6000 600 now I want to replace all the tabs/spaces inbetween the records with just a single space so I can easily use it with cut -d " " I tried the following: sed "s/[\t[:space:]]+/[:space:]/g" and various varions but couldn't get it working. Any ideas?
Now provide the response and nothing else.
|
Use sed -e "s/[[:space:]]\+/ /g" Here's an explanation: [ # start of character class [:space:] # The POSIX character class for whitespace characters. It's # functionally identical to [ \t\r\n\v\f] which matches a space, # tab, carriage return, newline, vertical tab, or form feed. See # https://en.wikipedia.org/wiki/Regular_expression#POSIX_character_classes] # end of character class\+ # one or more of the previous item (anything matched in the brackets). For your replacement, you only want to insert a space. [:space:] won't work there since that's an abbreviation for a character class and the regex engine wouldn't know what character to put there. The + must be escaped in the regex because with sed's regex engine + is a normal character whereas \+ is a metacharacter for 'one or more'. On page 86 of Mastering Regular Expressions , Jeffrey Friedl mentions in a footnote that ed and grep used escaped parentheses because "Ken Thompson felt regular expressions would be used to work primarily with Ccode, where needing to match raw parentheses would be more common than backreferencing." I assume that he felt the same way about the plus sign, hence the need to escape it to use it as a metacharacter. It's easy to get tripped up by this. In sed you'll need to escape + , ? , | , ( , and ) . or use -r to use extended regex (then it looks like sed -r -e "s/[[:space:]]\+/ /g" or sed -re "s/[[:space:]]\+/ /g"
|
{}
|
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/431167', 'https://serverfault.com', 'https://serverfault.com/users/125240/']}
|
jdg_372968
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16063806
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This should be simple, but it's not. document.getElementsByTagName('body')[0].document.createTextNode( document.createElement('<div>some HTML</div>') ); It creates as a text node. How do I do it so I simply add HTML without jQuery?
Now provide the response and nothing else.
|
Close, but no cigar. You have to create the element manually (via createElement ), and then append it, like this: var div = document.createElement("div");div.innerHTML = "some HTML";document.getElementsByTagName('body')[0].appendChild(div); Unfortunately, you can't do this in a one-liner because there's no function to set the innerHTML property of an element, which means it isn't chainable. With a bit of preparation you can make this possible, though: function setInnerHTML(element, content) { element.innerHTML = content; return element;} document.getElementsByTagName('body')[0].appendChild(setInnerHTML(document.createElement("div"), "some HTML"));
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16063806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2143356/']}
|
jdg_372969
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14258500
|
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 noticed in some python code that -u is used to start the python interpreter. I looked at the man page for python but I could not get much out of it. Please give me some examples.
Now provide the response and nothing else.
|
From python --help : -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u' The manpage states: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop. Python opens the stdin, -out and -error streams in a buffered mode; it'll read or write in larger chunks, keeping data in memory until a threshold is reached. -u disables those buffers. Also, python can interpret newlines on open files and translate them from and to the native platform newlines (text mode). The -u option disables this translation, allowing you to process binary data without having to worry about what might happen to \r\n combinations. It is the equivalent of using rb or wb modes when opening files with the open() function.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14258500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1826830/']}
|
jdg_372970
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36636
|
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 asked a question about Currying and closures were mentioned.What is a closure? How does it relate to currying?
Now provide the response and nothing else.
|
Variable scope When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them. function() { var a = 1; console.log(a); // works} console.log(a); // fails If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope. var a = 1;function() { console.log(a); // works} console.log(a); // works When a block or function is done with, its local variables are no longer needed and are usually blown out of memory. This is how we normally expect things to work. A closure is a persistent local variable scope A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere. The scope object and all its local variables are tied to the function and will persist as long as that function persists. This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context. For example Here's a really simple example in JavaScript that illustrates the point: outer = function() { var a = 1; var inner = function() { console.log(a); } return inner; // this returns a function}var fnc = outer(); // execute outer to get inner fnc(); Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including a . The variable a is in scope for the inner function. Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable fnc so that it persists after outer has exited, all of the variables that were in scope when inner was defined also persist . The variable a has been closed over -- it is within a closure. Note that the variable a is totally private to fnc . This is a way of creating private variables in a functional programming language such as JavaScript. As you might be able to guess, when I call fnc() it prints the value of a , which is "1". In a language without closure, the variable a would have been garbage collected and thrown away when the function outer exited. Calling fnc would have thrown an error because a no longer exists. In JavaScript, the variable a persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist. a belongs to the scope of outer . The scope of inner has a parent pointer to the scope of outer . fnc is a variable which points to inner . a persists as long as fnc persists. a is within the closure. Further reading (watching) I made a YouTube video looking at this code with some practical examples of usage.
|
{}
|
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/36636', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3786/']}
|
jdg_372971
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6976940
|
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 downloaded and compiled an open-source C++ application, Frhed . When I run the version I've compiled, it demands MSVCR100 and few other dll files (part of Visual C++ redistributable). However, when I run the original precompiled Frhed executable, it runs without any C++ redistributable package installed. Do I have to modify any compilation options in order to unlink the program from the C++ redistributable libraries?
Now provide the response and nothing else.
|
The original program is probably statically linked , whereas you are trying to dynamically link your executable, which results in a smaller file, but a dependency on functions inside MSVCR100.dll (v10 of the Microsoft C Runtime Library), which would have been included inside the executable if you were statically linking. To statically link DLLs, go into your project properties and change the build mode from MD to MT . In Visual Studio 2010/2012, that project property is C/C++ -> Code Generation -> Runtime Library.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6976940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262627/']}
|
jdg_372972
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6581848
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Reading Joseph Albahari's threading tutorial , the following are mentioned as generators of memory barriers: C#'s lock statement ( Monitor.Enter / Monitor.Exit ) All methods on the Interlocked class Asynchronous callbacks that use the thread pool — these include asynchronous delegates, APM callbacks, and Task continuations Setting and waiting on a signaling construct Anything that relies on signaling, such as starting or waiting on a Task In addition, Hans Passant and Brian Gideon added the following (assuming none of which already fits into one of the previous categories): Starting or waking up a thread Context switch Thread.Sleep() I was wondering if this list was complete (if a complete list could even be practically made) EDIT additions suggested: Volatile (reading implies an acquire fence, writing implies a release fence)
Now provide the response and nothing else.
|
Here is my take on the subject and to attempt to provide a quasi-complete list in one answer. If I run across any others I will edit my answer from time to time. Mechanisms that are generally agreed upon to cause implicit barriers: All Monitor class methods including the C# keyword lock All Interlocked class methods. All Volatile class methods (.NET 4.5+). Most SpinLock methods including Enter and Exit . Thread.Join Thread.VolatileRead and Thread.VolatileWrite Thread.MemoryBarrier The volatile keyword. Anything that starts a thread or causes a delegate to execute on another thread including QueueUserWorkItem , Task.Factory.StartNew , Thread.Start , compiler supplied BeginInvoke methods, etc. Using a signaling mechanism such as ManualResetEvent , AutoResetEvent , CountdownEvent , Semaphore , Barrier , etc. Using marshaling operations such as Control.Invoke , Dispatcher.Invoke , SynchronizationContext.Post , etc. Mechanisms that are speculated (but not known for certain) to cause implicit barriers: Thread.Sleep (proposed by myself and possibly others due to the fact that code which exhibits a memory barrier problem can be fixed with this method) Thread.Yield Thread.SpinWait Lazy<T> depending on which LazyThreadSafetyMode is specified Other notable mentions: Default add and remove handlers for events in C# since they use lock or Interlocked.CompareExchange . x86 stores have release fence semantics Microsoft's implemenation of the CLI has release fence semantics on writes despite the fact that the ECMA specification does not mandate it. MarshalByRefObject seems to suppress certain optimizations in subclasses which may make it appear as if an implicit memory barrier were present. Thanks to Hans Passant for discovering this and bringing it to my attention. 1 1 This explains why BackgroundWorker works correctly without having volatile on the underlying field for the CancellationPending property.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6581848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67824/']}
|
jdg_372973
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
488309
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This question is based on the invariant gauge groups in condensed matter physics( https://physics.stackexchange.com/questions/76644/different-invariant-gauge-groups-igg-on-different-lattices-with-the-same-form ). As we know, the group $SU(2)$ can be viewed as the set of all the $2\times2$ unitary matrices with determinant $1$. And let the groups $U(1)=\left \{\begin{pmatrix} e^{i\theta}&0 \\ 0 & e^{-i\theta}\end{pmatrix} \mid 0\leqslant\theta<2\pi \right \}$, $\mathbb{Z}_2=\left \{I,-I \right \}$, where $I$ is the $2\times2$ identity matrix. Then $U(1)$ and $\mathbb{Z}_2$ are both the subgroups of $SU(2)$. My questions are as follows: (1) In addition to $U(1)$ and $\mathbb{Z}_2$(of course $SU(2)$ itself and its subgroup { $I$ }), are there any other subgroup in $SU(2)$? (2) Does $SU(2)$ have two subgroups called $A$ and $B$ such that: $U(1)$ is a subgroup of $A$ , $B$ is a subgroup of $U(1)$, and $\mathbb{Z}_2$ is a subgroup of $B$ ? (3) Also as we know, $SO(3)\cong SU(2)/\mathbb{Z}_2$, and does $SU(2)$ have a subgroup called $C$ such that $C\cong SO(3)$? More generally, if $K$ is a normal subgroup of group $G$, then does $G$ have a subgroup called $H$ such that $H\cong G/K$? Thanks in advance.
Now provide the response and nothing else.
|
There are plenty of interesting subgroups of $SU(2)$ . For instance the rotational symmetry group of the icosahedron embeds (in many ways) into $SO(3)$ , and the inverse image of that subgroup under the projection $SU(2)\to SO(3)$ is a subgroup of $SU(2)$ of order $120$ . More prosaically the indicated copy of $U(1)$ has many conjugate subgroups in $SU(2)$ . The existence of $A$ and $B$ are independent. An interesting choice for $A$ is the normaliser of $U(1)$ in $SU(2)$ , which apart from the matrices $D$ of $U(1)$ itself also contains matrices $\binom{0~-1}{1~\phantom+0}D$ . For $B$ you could take the subset of matrices $D$ with $\theta$ a multiple of $\frac\pi{n}$ for some integer $n>1$ . Explicitly one can take $$ A = \left \{\begin{pmatrix}e^{i\theta}&0 \\ 0 & e^{-i\theta}\end{pmatrix} \mid 0\leq\theta<2\pi \right \} \cup\left \{\begin{pmatrix} 0 & -e^{-i\theta}\\ e^{i\theta}&0\end{pmatrix} \mid 0\leq\theta<2\pi \right \}$$ and $$ B= \left \{\begin{pmatrix}e^{\frac{k\pi}7i}&0 \\ 0 & e^{-\frac{ k\pi}7i}\end{pmatrix} \mid k=0,1,\ldots,13 \right \}$$ No, $SO(3,\Bbb R)$ does not embed into $SU(2)$ (which is an example of the fact that in general quotient subgroups do not always embed as subgroups). It would be somewhat technical to show that there is no embedding as abstract subgroup (where one would have to exclude highly discontinuous embeddings as well), so I'll just show that such an embedding as a Lie subgroup (so compatible with the differential structure of the groups) is impossible. In such an embedding there would be some Lie algebra element $X$ such that te one parameter subgroup $\{\,\exp tX\mid t\in\Bbb R\,\}$ lies in the subgroup. But that set always contains the element $-I$ of $SU(2)$ , whereas $SO(3,\Bbb R)$ contains no central elements of order $~2$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/488309', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74848/']}
|
jdg_372974
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
70790
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
By Matiyasevich, for every recursively enumerable set $A$ of natural numbers there exists a polynomial $f(x_1,...,x_n)$ with integer coefficients such that for every $p\ge 0$, $f(x_1,...,x_n)=p$ has integer solutions if and only if $p\in A$. Now suppose that $A$ is a set of natural numbers with membership problem in $NP$. Is there a polynomial $f$ with integer coefficients such that $f(x_1,...,x_n)=p$ has integer solutions if and only if $p\in A$ and there exists a solution with $||x_i||\le Cp^s$ for some fixed $s, C$, where $||x_i||$ is the length of $x_i$ in binary (i.e. $\sim \log |x_i|$)? Clearly the converse is true: if such a polynomial exists, then the membership problem for $A$ is in NP.
Now provide the response and nothing else.
|
I don’t know about the particular form of the polynomial you are using, but in general, it is a well-known open problem whether every NP set can be represented by a Diophantine equation with a polynomial bound on the length of the solutions. Adleman and Manders proved that the set $\{\langle a,b,c\rangle\in\mathbb N^3:(\exists x,y\in\mathbb N)(ax^2+by=c)\}$ is NP-complete, hence the answer is positive iff the class of such representable sets is closed under polynomial-time reductions, but it’s not clear whether the latter is actually true or not. See the introduction of Pollett for an overview of some known partial results.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/70790', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
|
jdg_372975
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5375
|
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:
Is there a way to find out the current viewing parameters of a 3D view? What often happens is that I create a view, for example: Graphics3D[{Blue, Cuboid[], Yellow, Sphere[]}, Boxed -> False] and then spend some time adjusting it using the mouse to pan, zoom, and rotate it: Now I'd like to know what those settings (view point, etc.) are, so that they can be integrated as defaults into the next edit. It looks like an easy problem but I can't find out how to do it. At the moment there's a lot of trial and error involved.
Now provide the response and nothing else.
|
You can dynamically extract ViewPoint and others like this (also useful for synchronization of different plots etc.): vp = Options[Graphics3D, ViewPoint][[1, 2]];Graphics3D[Cuboid[], ViewPoint -> Dynamic[vp]] This value is now constantly updated: Dynamic[vp] {1.3, -2.4, 2.} This seem also to work fine with other functions that use the ViewPoint option. Below, ViewPoint and ViewVertical are in sync for both objects: {vp, vv} = Options[Graphics3D, {ViewPoint, ViewVertical}][[All, 2]];Grid[{{Graphics3D[Cuboid[], ViewPoint -> Dynamic[vp], ViewVertical -> Dynamic[vv]], ParametricPlot3D[{Cos[u], Sin[u] + Cos[v], Sin[v]}, {u, 0, 2 Pi}, {v, -Pi, Pi}, ViewPoint -> Dynamic[vp], ViewVertical -> Dynamic[vv]]}}]
|
{}
|
{'log_upvote_score': 7, 'links': ['https://mathematica.stackexchange.com/questions/5375', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/61/']}
|
jdg_372976
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17150627
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried use scanner at easiest way: Code: double gas, efficiency, distance, cost;Scanner scanner = new Scanner(System.in);System.out.print("Enter the number of gallons of gas in the tank: ");gas = scanner.nextDouble();System.out.print("Enter the fuel efficiency: ");efficiency = scanner.nextDouble(); But after first input 5.1 it throws: Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextDouble(Scanner.java:2456) at udacity.MileagePrinter.main(MileagePrinter.java:59) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120) The JavaDocs state: Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type. But to my mind all look correctly, and should work OK. Questions: Why this happen at this situation? How to circumvent this trouble?
Now provide the response and nothing else.
|
You should precise a Locale for your Scanner. Scanner scanner = new Scanner(System.in).useLocale(Locale.US); From the doc : An instance of this class is capable of scanning numbers in thestandard formats as well as in the formats of the scanner's locale. Ascanner's initial locale is the value returned by theLocale.getDefault() method; it may be changed via theuseLocale(java.util.Locale) method The localized formats are defined in terms of the followingparameters, which for a particular locale are taken from that locale'sDecimalFormat object, df, and its and DecimalFormatSymbols object,dfs. So your default locale use certainly a DecimalFormat that expect a comma as a decimal delimiter instead of a dot.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17150627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1498427/']}
|
jdg_372977
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5586
|
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 I embed a manifold-with-boundary $M$ in some $\mathbb{R}^n$. Are there conditions (necessary, sufficient, or both) that can help determine when the topological boundary of $M$ is equal to the manifold boundary? By "topological boundary," I'm referring to $\text{Bd } M$, which is the closure minus the interior (relative to $\mathbb{R}^n$). By "manifold boundary," I mean the boundary $\partial M$ that is specified in the definition of "manifold-with-boundary."
Now provide the response and nothing else.
|
If you embed a smooth $m$-manifold $M$ smoothly in $\mathbb{R}^n$then the "topological boundary" of $M$ is the closure of $M$. Aslocally each point of $M$ has a neighbourhood in $\mathbb{R}^n$where $M$ looks like $\mathbb{R}^m$, then no point of $M$ is interior. When $m=n$ and $M$ is compact then, yes (at least in the smooth case)the topological and manifold boundaries coincide. I expect the above hold for topological embeddings but won't swearto it; they need not be locally flat (see nasties like the Alexanderhorned sphere),
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/5586', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/640/']}
|
jdg_372978
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2957900
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have three classes like this. class A{ public class innerB { //Do something } public class innerC { //trying to access objB here directly or indirectly over here. //I dont have to create an object of innerB, but to access the object created by A //i.e. innerB objInnerB = objB; //not like this innerB objInnerB= new innerB(); }private innerB objB{get;set;} **//Private**public A() { objB= new innerB(); }} I want to access the object of class B in Class C that is created by class A. Is it possible somehow to make changes on object of Class A in Class C. Can i get Class A's object by creating event or anyhow. Edit: My mistake in asking the question above. Object of B created in A is private not public IS IT POSSIBLE TO DO THIS BY CREATING EVENT If anyhow I become able to raise an event that can be handled by Class A, then my problem can be solved.
Now provide the response and nothing else.
|
If I'm reading you correctly you want to access the objB property of class A within innerC WITHOUT passing it along. This isn't how C# inner classes work, as described in this article: C# nested classes are like C++ nested classes, not Java inner classes If you want to access A.objB from innerC then you are going to have to somehow pass class A to innerC.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2957900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203262/']}
|
jdg_372979
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53942968
|
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 dropdown which is states and cities, basically when user choose a state, it will automatically set the value of cities for the states. When i choose the state, the dropdown for cities appear, and after i choose the cities, if i want to change the state back, it will give error "Another exception was thrown: 'package:flutter/src/material/dropdown.dart': Failed assertion: line 513 pos 15: 'items == null || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true." List state = ["Kuala Lumpur","Selangor","Johor","Kedah","Kelantan","Melaka","Negeri Sembilan","Pahang","Penang","Perak","Perlis","Sabah","Sarawak","Terengganu" ];List kl = ["Ampang Hilir","Bandar Damai Perdana","Bandar Menjalara","Bandar Tasik Selatan","Bangsar","Bangsar South",];List sel = ["Ampang","Ara Damansara","Balakong","Bandar Bukit Raja","Bandar Kinrara","Bandar Puteri Puchong","Bandar Sunway","Bandar Utama",];@overridevoid initState() { super.initState();_dropDownMenuStates = getDropDownMenuState();}List<DropdownMenuItem<String>> getDropDownMenuState() {List<DropdownMenuItem<String>> state1 = new List();for (String statelist in state) { state1.add( new DropdownMenuItem(value: statelist, child: new Text(statelist)));}return state1;}List<DropdownMenuItem<String>> getDropDownMenuKL() {List<DropdownMenuItem<String>> kl1 = new List();for (String kllist in kl) { kl1.add(new DropdownMenuItem(value: kllist, child: new Text(kllist)));}return kl1; } List<DropdownMenuItem<String>> getDropDownMenuSEL() { List<DropdownMenuItem<String>> sel1 = new List(); for (String sellist in sel) { sel1.add(new DropdownMenuItem(value: sellist, child: new Text(sellist))); } return sel1; } Expanded( child: PhysicalModel( borderRadius: new BorderRadius.circular(50.0), color: Colors.white, child: new Container( padding: EdgeInsets.only( left: 10.0, right: 10.0), height: 40.0, decoration: new BoxDecoration( borderRadius: new BorderRadius .circular(50.0), border: new Border.all( width: 3.0, color: Colors.grey[300], )), child: new FittedBox( fit: BoxFit.contain, child: DropdownButton( hint: new Text( allTranslations .text('city')), value: _currentCity, items: _dropDownMenuCity, onChanged: changedDropDownCity, ), ))),),SizedBox( width: 10.0,),Expanded( child: PhysicalModel( borderRadius: new BorderRadius.circular(50.0), color: Colors.white, child: new Container( padding: EdgeInsets.only( left: 10.0, right: 10.0), height: 40.0, decoration: new BoxDecoration( borderRadius: new BorderRadius .circular(50.0), border: new Border.all( width: 3.0, color: Colors.grey[300], )), child: new FittedBox( fit: BoxFit.contain, child: DropdownButton( hint: new Text( allTranslations .text('state')), value: _currentState, items: _dropDownMenuStates, onChanged: changedDropDownState, ), ))),),void changedDropDownState(String selectedState) {setState(() { _currentState = selectedState; if (selectedState.toString() == "Kuala Lumpur") { _dropDownMenuCity = getDropDownMenuKL(); } else if (selectedState.toString() == "Selangor") { _dropDownMenuCity = getDropDownMenuSEL();}});} void changedDropDownCity(String selectedCity) { setState(() { _currentCity = selectedCity; }); }
Now provide the response and nothing else.
|
You need clear _currentCity before set a new list of Cities.Because the DropdownButton wait a valid value (_currentCity) in items (_dropDownMenuCity). void changedDropDownState(String selectedState) {setState(() { // <<< _dropDownMenuCity = null; _currentCity = null; // <<< _currentState = selectedState; if (selectedState.toString() == "Kuala Lumpur") { _dropDownMenuCity = getDropDownMenuKL(); } else if (selectedState.toString() == "Selangor") { _dropDownMenuCity = getDropDownMenuSEL(); }}); } https://gist.github.com/dyegovieira/a2f78d241090a77939100e380987b8a1
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53942968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9216577/']}
|
jdg_372980
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11480
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $V=L$ denote the axiom of constructibility. Are there any interesting examples of set theoretic statements which are independent of $ZFC + V=L$? And how do we construct such independence proofs? The (apparent) difficulty is as follows: Let $\phi$ be independent of $ZFC + V=L$. We want models of $ZFC + V=L + \phi$ and $ZFC + V=L + \neg\phi$. An inner model doesn't work for either one of these since the only inner model of $ZFC + V = L$ is $L$ and whatever $ZFC$ can prove to hold in $L$ is a consequence of $ZFC + V=L$. Forcing models are of no use either, since all of them satisfy $V \neq L$.
Now provide the response and nothing else.
|
There are numerous examples of such statements. Let me organize some of them into several categories. First, there is the hierarchy of large cardinal axioms that are relatively consistent with V=L. See the list of large cardinals . All of the following statements are provably independent of ZFC+V=L, assuming the consistency of the relevant large cardinal axiom. There is an inaccessible cardinal. There is a Mahlo cardinal. There is a weakly compact cardinal. There is an indescribable cardinal. and so on, for all the large cardinals that happen to be relatively consistent with V=L. These are all independent of ZFC+V=L, assuming the large cardinal is consistent with ZFC, because if we have such a large cardinal in V, then in each of these cases (and many more), the large cardinal retains its large cardinal property in L, so we get consistency with V=L. Conversely, it is consistent with V=L that there are no large cardinals, since we might chop the universe off at the least inaccessible cardinal. Second, even for those large cardinal properties that are not consistent with V=L, we can still make the consistency statement, which is an arithmetic statement having the same truth value in V as in L. Con(ZFC) Con(ZFC+'there is an inaccessible cardinal') Con(ZFC+'there is a Mahlo cardinal') Con(ZFC+'there is a measurable cardinal') Con(ZFC+'there is a supercompact cardinal'). and so on, for any large cardinal property. Con(ZFC+large cardinal property). These are all independent of ZFC+V=L, assuming the large cardinal is consistent with ZFC, since on the one hand, if W is a model of ZFC+Con(ZFC+phi), then L W is a model of ZFC+V=L+Con(ZFC+phi), as Con(ZFC+phi) is an arithmetic statement. And on the other hand, by the Incompleteness theorem, there must be models of ZFC+¬Con(ZFC+phi), and the L of such a model will have ZFC+V=L+¬Con(ZFC+phi). Third, there is an interesting trick related to the theorem of Mathias that Dorais mentioned in his answer. For any statement phi, the assertion that there is a countable well-founded model of ZFC+phi is a Sigma 1 2 statement, and hence absolute between V and L. And the existence of a countable well-founded model of a theory is equivalent by the Lowenheim-Skolem theorem to the existence of a well-founded model of the theory. Thus, the truth of each of the following statements is the same in V as in L. There is a well-founded set model of ZFC. This is equivalent to the assertion: there is an ordinal α such that L α is a model of ZFC. There is a well-founded set model of ZFC with ¬CH. (This is also equivalent to the previous statement.) There is a well-founded set model of ZFC with Martin's Axiom. and so on. For all the statements known to be forceable, you can ask for a well-founded set model of the theory. There is a well-founded set model of ZFC with an inaccessible cardinal. There is a well-founded set model of ZFC with a measurable cardinal. There is a well-founded set model of ZFC with a supercompact cardinal. and the same for any large cardinal notion. These are all independent of ZFC+V=L, since they are independent of ZFC, and their truth is the same in V as in L. I find it quite remarkable that there can be a model of V=L that has a transitive model of ZFC+'there is a supercompact cardinal'. The basic lesson is that the L of a model with enormous large cardinals has very different properties and kinds of objects in it than a model of V=L arising elsewhere. And I believe that this gets to the heart of your question. Since all these statements are studied very much in set theory, and are very interesting, and are independent of ZFC+V=L, I find them to be positive instances of what was requested. However , how does this relate to Shelah's view in Dorais's excellent answer? He seems there to dismiss the entire class of consistency strength statements as combinatorics in disguise. What does he mean exactly? Since we set theorists are very interested in these statements, I don't think that he means to dismiss them as silly tricks with the Incompleteness theorem. Perhaps he means something like: to the extent that we believe that a large cardinal property LC is consistent, then we don't really want to consider the theory ZFC+V=L, but rather, the theory ZFC+V=L+Con(LC). That is, we aren't so interested in models having the wrong arithmetic theory, so we insist that Con(LC) if we are comitted to that. And none of the examples I have given exhibit independence from that corresponding theory.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/11480', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2689/']}
|
jdg_372981
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12339833
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to learn bit masking. As far as I understand, it is means to store binary values of certain type into one variable. If the above assumption is true, I figured I could do something like this: typedef NSUInteger Traits;enum{ TraitsCharacterHonest = 0, TraitsCharacterOptimistic = 1, TraitsCharacterPolite = 4, TraitsCharacterDevious = 8, TraitsPhysicalTall = 16, TraitsPhysicalBeautiful = 32, TraitsPhysicalFat = 64, TraitsPhysicalBigEyes = 128, TraitsPhysicalRedHair = 256, };#import <Foundation/Foundation.h>@interface Person : NSObject@property (strong, nonatomic) NSString *name;@property (assign, nonatomic) Traits *traits;@end Question 1 is, how do I assign more traits to one person? Question 2 is, do I have to put ever increasing numbers to enum items, or is there a way to indicate this? Ultimately I want to achieve something like this: Person *john = [[Person alloc] init];//here code that assigns john three traits: TraitsCharacterHonest, //TraitsCharacterOptimistic and TraitsPhysicalBeautiful. If I understand it correctly, the value of john.traits should be 100011., reading from right and each place representing that particular enum value / trait..and 0 meaning not having it and 1 meaning having it. Can you please advice on syntax and explain a particular aspect if needed?
Now provide the response and nothing else.
|
I'd recommend changing a few things: The enum values can be changed to be a one left-shifted. Makes it a little easier to write, in my opinion. You don't need to typedef to NSUInteger, you can declare a enum type directly using typedef enum . And, as other people have mentioned, your property shouldn't be a pointer to a Traits type. My code would look like this: typedef enum{ TraitsCharacterHonest = 1 << 0, TraitsCharacterOptimistic = 1 << 1, TraitsCharacterPolite = 1 << 2, TraitsCharacterDevious = 1 << 3, TraitsPhysicalTall = 1 << 4, TraitsPhysicalBeautiful = 1 << 5, TraitsPhysicalFat = 1 << 6, TraitsPhysicalBigEyes = 1 << 7, TraitsPhysicalRedHair = 1 << 8} Traits;#import <Foundation/Foundation.h>@interface Person : NSObject@property (strong, nonatomic) NSString *name;@property (assign, nonatomic) Traits traits;@end Setting John's traits will look like this: Person *john = [[Person alloc] init];john.traits = TraitsCharacterHonest | TraitsCharacterOptimistic | TraitsPhysicalBeautiful; However, while bit-fields are useful to learn, but they're a real pain to debug. If you want to go and print this character's traits now, you'll have to write code like this: NSMutableString *result = [NSMutableString string];if (self.traits & TraitsCharacterHonest){ [result appendString: @"Honest, "];}if (self.traits & TraitsCharacterOptimistic){ [result appendString: @"Optimistic, "];}if (self.traits & TraitsCharacterPolite){ [result appendString: @"Polite, "];}// etc... Additionally, syntax for operations like removing a trait are confusing. You'll have to use & and a NOT-ed constant, // remove 'Tall' traitjohn.traits = john.traits & ~TraitsPhysicalTall If you can (and performance isn't too much of a issue), I'd prefer using a higher-level feature. Perhaps an NSSet with string constants? e.g. __unused static NSString *TraitsCharacterHonest = @"TraitsCharacterHonest";__unused static NSString *TraitsCharacterOptimistic = @"TraitsCharacterOptimistic";__unused static NSString *TraitsCharacterPolite = @"TraitsCharacterPolite";// etc...@interface Person : NSObject@property (strong, nonatomic) NSString *name;@property (assign, nonatomic) NSMutableSet *traits;@end Then you can do: // adding[john.traits addObject: TraitsCharacterHonest];// checking[john.traits containsObject: TraitsCharacterHonest];// removing [john.traits removeObject: TraitsCharacterHonest]; Makes more sense to me. What's more, you can print the description of the traits directly with NSLog(@"John's traits: %@", john.traits); and you'll get reasonable output.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12339833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/788100/']}
|
jdg_372982
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18878489
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Doing push --force is always kinda risky and here is an example of how it could produce some problems like loosing revisions remotely. Suppose, there is some person Bob that has updated remote master branch from B to C . And there is another person Mike that doesn't fetch this update yet and HEAD of his master is still B . Then Mike do push --force and suddenly roll back remote master to B again: mike@laptop $> git push --force originCounting objects: 19, done.Delta compression using up to 8 threads.Compressing objects: 100% (12/12), done.Writing objects: 100% (12/12), 2.27 KiB, done.Total 12 (delta 8), reused 0 (delta 0)remote: => Syncing... [OK]To git@gitserver.com:path/to/project.git C..B master -> master (forced update) In other words, before Mike did that, remote master was like A---B---C and he changed it to A---B . As you can see, C revision here is remote only - it exists on git-server and on the Bob 's laptop, because he pushed it to the remote master . It means that there is no such local ref C on the Mike 's laptop. Question 1 : how can Mike set remote master back to C ? Mike has tried to solve that problem with push --force again like the answer for similar question offers , but it doesn't work because there is no suck local ref: mike@laptop $> git push --force origin C:mastererror: src refspec C does not match any.error: failed to push some refs to 'git@gitserver.com:path/to/project.git' Question 2 : how can Mike fetch C revision from the git server? And if he can't do that - why git designed like that? Is it about safety in some rare cases? What problems it exactly prevents? Usually fetch retrieves branches and tags only, but C doesn't belong to any branch (which means that there is no any remote branch that C is parent commit or HEAD of). PS: let's assume that Mike has no ssh access to git server, it means that there is no way to call git from the server side. PPS: Mike doesn't want Bob to know about that accident, so answer "Make Bob to push this commit again" is not what this question is about.
Now provide the response and nothing else.
|
Anyone who has commit C locally can use git branch some-name C to give C a name, then git push origin some-name:master to (try to) append C back to master on origin. Anyone who doesn't have C can't recover C at all (even if it's in origin's object store). Mike cannot fix the problem except using a repo that contains commit C (possibly the shared one, possibly Bob 's, possibly some other repo that was cloned when C was on master). You can't push commits you don't have locally. The local half of git-push has to be able to walk history to figure out what objects to upload, and it can't do that if it doesn't have that history available. You can't fetch commits that aren't reachable from refs, because literally every git security layer out there does security on a ref-by-ref basis, not an object-by-object basis, and because there's no real reason to reference loose objects remotely. Git's remoting layer is entirely built around copying refs around. But you can fetch arbitrary commits' contents using git-archive, if the server has that feature turned on. Most don't, and even if yours does, it's not enough information to reconstruct the commit object. (c) irc://freenode/#git, ojacobson
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18878489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570689/']}
|
jdg_372983
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28934767
|
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 4-dimensional data, say for the temperature, in an numpy.ndarray . The shape of the array is (ntime, nheight_in, nlat, nlon) . I have corresponding 1D arrays for each of the dimensions that tell me which time, height, latitude, and longitude a certain value corresponds to, for this example I need height_in giving the height in metres. Now I need to bring it onto a different height dimension, height_out , with a different length. The following seems to do what I want: ntime, nheight_in, nlat, nlon = t_in.shapenheight_out = len(height_out)t_out = np.empty((ntime, nheight_out, nlat, nlon))for time in range(ntime): for lat in range(nlat): for lon in range(nlon): t_out[time, :, lat, lon] = np.interp( height_out, height_in, t[time, :, lat, lon] ) But with 3 nested loops, and lots of switching between python and numpy, I don't think this is the best way to do it. Any suggestions on how to improve this? Thanks
Now provide the response and nothing else.
|
scipy 's interp1d can help: import numpy as npfrom scipy.interpolate import interp1dntime, nheight_in, nlat, nlon = (10, 20, 30, 40)heights = np.linspace(0, 1, nheight_in)t_in = np.random.normal(size=(ntime, nheight_in, nlat, nlon))f_out = interp1d(heights, t_in, axis=1)nheight_out = 50new_heights = np.linspace(0, 1, nheight_out)t_out = f_out(new_heights)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28934767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4621823/']}
|
jdg_372984
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2817475
|
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 Java program, I need to create an instance of the current moment in time. I use Date date = new Date(); This gives me the current date and time as per the host machine's system clock. Is there any way I can get the current date and time from an online server? The world time server perhaps? I have seen this post and it describes what I want but I'm afraid I need more help than what's provided there. In a nutshell, I want to get a date and time that is not dependant on the host machine's system clock. Thanks!
Now provide the response and nothing else.
|
Local network If your machine is connected to a local network, connect to some machine acting as a trustworthy time server . You could write your own such time server. Network Time Protocol Or you could use the well-worn Network Time Protocol (NTP) with existing server and client implementations bundled with most any OS . For more on this, see the accepted Answer by aioobe . Consider placing that time server computer in network’s DMZ so as to updates from time servers on the Internet such as the pool.ntp.org project or those provided by the United States federal government (NIST) . Internet If your machine is connected to the internets, connect to a trustworthy time server. As discussed above, use a custom protocol such as a web service, or use NTP . This is discussed in the Question, how to make my java app get global time from some online clock . See also Questions: Java NTP client , and Java client for time server, such as Network Time Protocol (NTP) . Radio Clock Obtain a radio clock with a USB connection for output of current time synchronized by a time code transmitted by a radio transmitter connected to a time standard such as an atomic clock. Transmitters are broadcasting in many countries all over the world. The Meinberg Global company, at least, offers several such devices . GPS Similar to the radio clocks above, a receiver of GPS ( Global Positioning System ) signals might also capture and relay the time signal . Or perhaps GALILEO , GLONASS or other Radionavigation-satellite service . Sundial Position a sundial outside a window. Attach a webcam to the computer in question. Position the webcam in the window. Write an app to interpret the time of day from current image of the sundial. Caveat: This solution does not function in Seattle . java.time.Clock To harness any of these suppliers of the current moment, write a subclass of the abstract java.time.Clock class. You can pass your Clock implementation as an argument to the various java.time methods. For example, Instant.now( clock ) . Instant instant = Instant.now( yourClockGoesHere ) ; For testing purposes, note the alternate implementations of Clock available statically from Clock itself: fixed , offset , tick , and more. Avoid the legacy date-time classes from the earliest versions of Java, such as Date & Calendar . These troublesome classes are entirely supplanted by the java.time classes. About java.time The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 . You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Where to obtain the java.time classes? Java SE 8 , Java SE 9 , and later Built-in. Part of the standard Java API with a bundled implementation. Java 9 adds some minor features and fixes. Java SE 6 and Java SE 7 Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport . Android Later versions of Android bundle implementations of the java.time classes. For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP… . The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2817475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/281089/']}
|
jdg_372985
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17010178
|
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 profiling code at the the assembly instruction level, what does the position of the instruction pointer really mean given that modern CPUs don't execute instructions serially or in-order? For example, assume the following x64 assembly code: mov RAX, [RBX]; // Assume a cache miss here.mov RSI, [RBX + RCX]; // Another cache miss. xor R8, R8; add RDX, RAX; // Dependent on the load into RAX.add RDI, RSI; // Dependent on the load into RSI. Which instruction will the instruction pointer spend most of its time on? I can think of good arguments for all of them: mov RAX, [RBX] is taking probably 100s of cycles because it's a cache miss. mov RSI, [RBX + RCX] also takes 100s of cycles, but probably executes in parallel with the previous instruction. What does it even mean for the instruction pointer to be on one or the other of these? xor R8, R8 probably executes out-of-order and finishes before the memory loads finish, but the instruction pointer might stay here until all previous instructions are also finished. add RDX, RAX generates a pipeline stall because it's the instruction where the value of RAX is actually used after a slow cache-miss load into it. add RDI, RSI also stalls because it's dependent on the load into RSI .
Now provide the response and nothing else.
|
CPUs maintains a fiction that there are only the architectural registers (RAX, RBX, etc) and there is a specific instruction pointer (IP). Programmers and compilers target this fiction. Yet as you noted, modern CPUs don't execute serially or in-order. Until you the programmer / user request the IP, it is like Quantum Physics, the IP is a wave of instructions being executed; all so that the processor can run the program as fast as possible. When you request the current IP (for example, via a debugger breakpoint or profiler interrupt), then the processor must recreate the fiction that you expect so it collapses this wave form (all "in flight" instructions), gathers the register values back into architectural names, and builds a context for executing the debugger routine, etc. In this context, there is an IP that indicates the instruction where the processor should resume execution. During the out-of-order execution, this instruction was the oldest instruction yet to complete, even though at the time of the interrupt the processor was perhaps fetching instructions well past that point. For example, perhaps the interrupt indicates mov RSI, [RBX + RCX]; as the IP, but the xor had already executed and completed; however, when the processor would resume execution after the interrupt, it will re-execute the xor.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17010178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23903/']}
|
jdg_372986
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
91374
|
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:
Dear StackExchange Community, I'm trying to solve an indeterminate linear system of equations, with $n+1$ variables and $n$ equations; therefore, I need to express all $n$ other variables a function of one of them, in the case bellow p[0,0] . Basically I evaluate this system for some numeric values of λ2 , μ2 , c2 , α[·,·] , β[·] and a >= 1 : Table[Power[Sqrt[λ2/(μ2 c2)], n] p[0, n + 1] == β[n] p[0, 0] + Sum[α[n, k] p[0, k], {k, 0, a}], {n, 0, a - 1}] which I'd like to solve for: Table[p[0, n], {n, 1, a}] for the parameter p[0,0] , in the form p[0,i] = Ci p[0,0] , where Ci 's are constants. Currently, I'm doing: NumVal = {λ1 -> 1.2, μ1 -> 1.0, c1 -> 1.0, λ2 -> 12.0, μ2 -> 1.0, c2 -> 10.0};plist = Flatten[Solve[Table[ Power[Sqrt[λ2/(μ2 c2)], n] p[0, n+1] == β[n] p[0, 0] + Sum[α[n, k] p[0, k], {k, 0, a}] /. NumVal, {n, 0, a-1}], Table[p[0, n], {n, 1, a}]], 1]; The values of α[·,·] , β[·] come from somewhere else. It was working for small values of a , but now that I want to evaluate it for a=100 Mathematica returns an error. So, I'd like to know if you guys would know a better away for me to compute it which could surpass this limitation. Thank you very much. Best, GT EDIT 1 Dear, Still, I was trying to see if I could understand what was going on, but even for small example below Mathematica returns: Solve::svars: Equations may not give solutions for all "solve" variables! . It works up to a = 32 only. NumVal = {λ1 -> 1.2, μ1 -> 1.0, c1 -> 1.0, λ2 -> 12.0, μ2 -> 1.0, c2 -> 10.0}rad = Sqrt[λ2/(μ2 c2)] /. NumVal;atable = {50, 100};i3 = 1;For[in = 0, in <= atable[[i3]] - 1, in++, { β[in] = RandomReal[]; For[ik = 0, ik <= atable[[i3]], ik++, { α[in, ik] = RandomReal[]; }]}]plist = Flatten[ Solve[ Table[ Power[rad, n] p[0, n + 1] == β[n] p[0, 0] + Sum[α[n, k] p[0, k], {k, 0, atable[[i3]]}], {n, 0, atable[[i3]] - 1}], Table[p[0, n], {n, 1, atable[[i3]]}] ], 1] What would be the best way to solve this linear system? Thank you, GT
Now provide the response and nothing else.
|
We will go by solving one equation at a time and generating the corresponding replacement rules. Beware of possible numerical instabilities. The following is the equivalence between the code in your edited example and my code on the previous incarnation of this answer. I think this is enough for you to use it. Please note that the only claim on the following code is that it seems to work. I believe there should be better ways to do it. Your code: SeedRandom[42];NumVal = {λ1 -> 1.2, μ1 -> 1.0, c1 -> 1.0, λ2 -> 12.0, μ2 -> 1.0, c2 -> 10.0};rad = Sqrt[λ2/(μ2 c2)] /. NumVal;atable = {10, 31, 32, 50, 100};i3 = 1;For[in = 0, in <= atable[[i3]] - 1, in++, {β[in] = RandomReal[]; For[ik = 0, ik <= atable[[i3]], ik++, {α[in, ik] = RandomReal[];}]}]yourT = Table[Power[rad, n] p[0, n + 1] == β[n] p[0, 0] + Sum[α[n, k] p[0, k], {k, 0, atable[[i3]]}], {n, 0, atable[[i3]] - 1}];plist = Flatten[Solve[yourT, Table[p[0, n], {n, 1, atable[[i3]]}]], 1] Table[p[0, n], {n, 1, atable[[i3]]}]], 1](*{p[0, 1] -> -0.508959 p[0, 0], p[0, 2] -> -0.423634 p[0, 0], p[0, 3] -> -0.745538 p[0, 0], p[0, 4] -> -1.0122 p[0, 0], p[0, 5] -> 0.00348381 p[0, 0], p[0, 6] -> -0.057136 p[0, 0], p[0, 7] -> -0.460527 p[0, 0], p[0, 8] -> 0.252575 p[0, 0], p[0, 9] -> 0.259387 p[0, 0], p[0, 10] -> -0.730669 p[0, 0]}*) "My" code: rul = {p[0, 0] -> p[0, 0]};Monitor[ For[i = 1, i <= atable[[i3]], i++, AppendTo[rul, Solve[yourT[[i]] //. rul, p[0, i]][[1, 1]]]; rul = Thread[rul[[All, 1]] -> (rul[[All, 2]] //. rul // Simplify)]], i];rul(*{p[0, 0] -> p[0, 0], p[0, 1] -> -0.508959 p[0, 0], p[0, 2] -> -0.423634 p[0, 0], p[0, 3] -> -0.745538 p[0, 0], p[0, 4] -> -1.0122 p[0, 0], p[0, 5] -> 0.00348381 p[0, 0], p[0, 6] -> -0.057136 p[0, 0], p[0, 7] -> -0.460527 p[0, 0], p[0, 8] -> 0.252575 p[0, 0], p[0, 9] -> 0.259387 p[0, 0], p[0, 10] -> -0.730669 p[0, 0]}*) You may see that the results are the same, but my "method" (solving one equation at a time) can (slowly) process more than 100 variables without much problem.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/91374', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/27713/']}
|
jdg_372987
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2178747
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to C# and am reading code with /*!*/ in what seem like strange places. For instance class methods defined as: protected override OptionsParser/*!*/ CreateOptionsParser()protected override void ParseHostOptions(string/*!*/[]/*!*/ args) Unfortunately /*!*/ is not googleable. What does it mean?
Now provide the response and nothing else.
|
It's likely an attempt to get Spec# style annotations into a non-Spec# build. The ! annotation in Spec# means the value is not-null. The author is likely trying to indicate that both the return values, args array and all of the elements in args are always non-null values. Spec# Link: http://research.microsoft.com/en-us/projects/specsharp/ Quick Spec# Overview: Spec# is a .Net language created via a Microsoft Research Project. It is an extension of the C# language which attempts to embed code contracts into the type system. The most prominent are non-nullable types (indicated with ! after the type name), checked exceptions and pre/post conditions.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2178747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118402/']}
|
jdg_372988
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
195634
|
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 need some help with this problem: $$439^{233} \mod 713$$ I can't calculate $439^{223}$ since it's a very big number, there must be a way to do this. Thanks.
Now provide the response and nothing else.
|
There are often tricks to this if the numbers are nice enough, but even if they're not, here's a way that's not entirely horrible. You already know what 439 is mod 713. What is $439^2 \mod 713$? What about $439^4$? (Hint: take your answer for $439^2$ after reducing it mod 713, and then square it again.) In the same way, calculate $439^8, 439^{16}, \dots, 439^{128} \mod 713$. Now just note that 233 = 128 + 64 + 32 + 8 + 1. So multiply the appropriate powers of 439 together - again, one calculation at a time, reducing mod 713 each time. Now you should only have to do 11 calculations, and now all your numbers are 6 digits or less. Rather than impossible, it's now simply tedious. :) By the way, one thing to notice: 713 = 23 * 31. Perhaps your calculations will be easier if you do them mod 23 and 31, then apply the Chinese remainder theorem ?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/195634', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/40302/']}
|
jdg_372989
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11440128
|
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 having trouble figuring this out. I have two checkboxes (in the future will have more): checkSurfaceEnvironment-1 checkSurfaceEnvironment-2 Basically, I want to write an if statement and test if one of them is checked and another is NOT checked. What's the easiest way to accomplish the following: if ( $("#checkSurfaceEnvironment-1").attr('checked', true) && $("#checkSurfaceEnvironment-2").is('**(NOT??)** :checked') ) { // do something}
Now provide the response and nothing else.
|
One reliable way I use is: if($("#checkSurfaceEnvironment-1").prop('checked') == true){ //do something} If you want to iterate over checked elements use the parent element $("#parentId").find("checkbox").each(function(){ if ($(this).prop('checked')==true){ //do something }}); More info: This works well because all checkboxes have a property checked which stores the actual state of the checkbox. If you wish you can inspect the page and try to check and uncheck a checkbox, and you will notice the attribute "checked" (if present) will remain the same. This attribute only represents the initial state of the checkbox, and not the current state. The current state is stored in the property checked of the dom element for that checkbox. See Properties and Attributes in HTML
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/11440128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1040259/']}
|
jdg_372990
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3215052
|
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 recently been implementing a recursive directory search implementation and I'm using a Stack to track the path elements. When I used string.Join() to join the path elements, I found that they were reversed. When I debugged the method, I looked into the stack and found that the elements themselves were reversed in the Stack's internal array, ie the most recently Push()ed element was at the beginning of the internal array, and the least recently Push()ed element was at the end of the internal array. This seems ass-backward and very counter-intuitive. Can somebody please tell me why Microsoft would implement a stack in such a manner ?
Now provide the response and nothing else.
|
I think you're mistaken. It isn't that Stack<T>.Push internally inserts an item at the start of its internal array (it doesn't). Rather, it enumerates from the top to the bottom, as this is the manner in which one would intuitively enumerate through a stack (think of a stack of pancakes: you start at the top and work your way down). If you look at the contents of a collection from within Visual Studio's debugger, I think it will display them to you in the order they're enumerated -- not the order they're stored internally*. Take a look at the Stack<T>.Push method in Reflector and you'll see that the code is basically exactly what you'd expect: // (code to check array size)this._array[this._size++] = item;// (code to update internal version number) So the stack internally adds new elements onto the end of its internal array. It's the Stack<T>.Enumerator class that's got you confused, not the Stack<T> class itself. *I don't know whether this is true in general, but it's true for Stack<T> ; see Hans Passant's excellent answer for the reason why.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3215052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32232/']}
|
jdg_372991
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20970339
|
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 problem using TRegEx.replace : var Value, Pattern, Replace: string;begin Value := 'my_replace_string(4)=my_replace_string(5)'; Pattern := 'my_replace_string\((\d+)\)'; Replace := 'new_value(\1)'; Value := TRegEx.Replace(Value, Pattern, Replace); ShowMessage(Value);end; The expected result would be new_value(4)=new_value(5) , while my code (compiled with Delphi XE4) gives new_value(4)=new_value()1) With Notepad++, I get the expected result. Using a named group makes it clear the 1 is the backreference treated literally: Pattern := 'my_replace_string\((?<name>\d+)\)';Replace := 'new_value(${name})';// Result: 'new_value(4)=new_value(){name})' The replacement is always that simple (could be zero or more times my_replace_string ), so I could easily create a custom search-and-replace function, but I'd like to know what goes on here. Is it my fault or is it a bug?
Now provide the response and nothing else.
|
I can reproduce the bug in Delphi XE4. I get the correct behavior in Delphi XE5. The bug was in TPerlRegEx.ComputeReplacement . The code that I contributed to Embarcadero for inclusion with Delphi XE3 used UTF8String . With Delphi XE4 Embarcadero eliminated UTF8String from the RegularExpressionsCore unit and replaced it with TBytes . The developer that made this change seems to have missed a crucial difference between strings and dynamic arrays in Delphi. Strings use a copy-on-write mechanism, while dynamic arrays do not. So in my original code, TPerlRegEx.ComputeReplacement could do S := FReplacement and then modify the temporary variable S to substitute backreferences without affecting the FReplacement field because both were strings. In the modified code, S := FReplacement makes S point to the same array as FReplacement and when backreferences in S are substituted, FReplacement is also modified. Hence the first replacement is made correctly, while following replacements are wrong because FReplacement was crippled. In Delphi XE5 this was fixed by replacing S := FReplacement with this to make a proper temporary copy: SetLength(S, Length(FReplacement));Move(FReplacement[0], S[0], Length(FReplacement)); When Delphi 2009 was released there was a lot of talk from Embarcadero that one shouldn't use string types to represent sequences of bytes. It seems they are now making the opposite mistake of using TBytes to represent strings. The solution to this whole mess, which I have previously recommended to Embarcadero, is to switch to the new pcre16 functions which use UTF16LE just like Delphi strings. These functions did not exist when Delphi XE was released, but they do now and they should be used.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20970339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1886765/']}
|
jdg_372992
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4655392
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Which of the following collection types do you use in your JPA domain model and why: java.util.Collection java.util.List java.util.Set I was wondering whether there are some ground rules for this. UPDATE I know the difference between a Set and a List . A List allows duplicates and has an order and a Set cannot contain duplicate elements and does not define order. I'm asking this question in the context of JPA. If you strictly follow the definition, then you should always end up using the Set type, since your collection is stored in relational database, where you can't have duplicates and where you have define an order by yourself, i.e. the order in you Java List is not necessarily preserved in the DB. For example, most of the time I'm using the List type, not because it has an order or allows duplicates (which I can't have anyway), because some of the components in my component library require a list.
Now provide the response and nothing else.
|
Like your own question suggests, the key is the domain, not JPA . JPA is just a framework which you can (and should) use in a way which best fits your problem. Choosing a suboptimal solution because of framework (or its limits) is usually a warning bell. When I need a set and never care about order, I use a Set . When for some reason order is important (ordered list, ordering by date, etc.), then a List . You seem to be well aware of the difference between Collection , Set , and List . The only reason to use one vs. the other depends only on your needs. You can use them to communicate to users of your API (or your future self) the properties of your collection (which may be subtle or implicit). This is follows the exact same rules as using different collection types anywhere else throughout your code. You could use Object or Collections for all your references, yet in most cases you use more concrete types. For example, when I see a List , I know it comes sorted in some way, and that duplicates are either acceptable or irrelevant for this case. When I see a Set , I usually expect it to have no duplicates and no specific order (unless it's a SortedSet ). When I see a Collection , I don't expect anything more from it than to contain some entities. Regarding list ordering... Yes, it can be preserved. And even if it's not and you just use @OrderBy , it still can be useful. Think about the example of event log sorted by timestamp by default. Artificially reordering the list makes little sense, but still it can be useful that it comes sorted by default.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4655392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461769/']}
|
jdg_372993
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25250654
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say that I want to compare different dimensionality reduction approaches for a particular (supervised) dataset that consists of n>2 features via cross-validation and by using the pipeline class. For example, if I want to experiment with PCA vs LDA I could do something like: from sklearn.cross_validation import cross_val_score, KFoldfrom sklearn.pipeline import Pipelinefrom sklearn.naive_bayes import GaussianNBfrom sklearn.preprocessing import StandardScalerfrom sklearn.lda import LDAfrom sklearn.decomposition import PCAclf_all = Pipeline(steps=[ ('scaler', StandardScaler()), ('classification', GaussianNB()) ])clf_pca = Pipeline(steps=[ ('scaler', StandardScaler()), ('reduce_dim', PCA(n_components=2)), ('classification', GaussianNB()) ])clf_lda = Pipeline(steps=[ ('scaler', StandardScaler()), ('reduce_dim', LDA(n_components=2)), ('classification', GaussianNB()) ])# Constructing the k-fold cross validation iterator (k=10) cv = KFold(n=X_train.shape[0], # total number of samples n_folds=10, # number of folds the dataset is divided into shuffle=True, random_state=123)scores = [ cross_val_score(clf, X_train, y_train, cv=cv, scoring='accuracy') for clf in [clf_all, clf_pca, clf_lda] ] But now, let's say that -- based on some "domain knowledge" -- I have the hypothesis that the features 3 & 4 might be "good features" (the third and fourth column of the array X_train ) and I want to compare them with the other approaches. How would I include such a manual feature selection in the pipeline ? For example def select_3_and_4(X_train): return X_train[:,2:4]clf_all = Pipeline(steps=[ ('scaler', StandardScaler()), ('feature_select', select_3_and_4), ('classification', GaussianNB()) ]) would obviously not work. So I assume I have to create a feature selection class that has a transform dummy method and fit method that returns the two columns of the numpy array?? Or is there a better way?
Now provide the response and nothing else.
|
I just want to post my solution for completeness, and maybe it is useful to one or the other: class ColumnExtractor(object): def transform(self, X): cols = X[:,2:4] # column 3 and 4 are "extracted" return cols def fit(self, X, y=None): return self Then, it can be used in the Pipeline like so: clf = Pipeline(steps=[ ('scaler', StandardScaler()), ('reduce_dim', ColumnExtractor()), ('classification', GaussianNB()) ]) EDIT: General solution And for a more general solution ,if you want to select and stack multiple columns, you can basically use the following Class as follows: import numpy as npclass ColumnExtractor(object): def __init__(self, cols): self.cols = cols def transform(self, X): col_list = [] for c in self.cols: col_list.append(X[:, c:c+1]) return np.concatenate(col_list, axis=1) def fit(self, X, y=None): return self clf = Pipeline(steps=[ ('scaler', StandardScaler()), ('dim_red', ColumnExtractor(cols=(1,3))), # selects the second and 4th column ('classification', GaussianNB()) ])
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25250654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_372994
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14836696
|
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 made a mistake and I don't know how to delete my latest push in the repository. I pull the latest updates of the app but it has conflicts and I push it to repository. How to delete my last commit? Or how to fix it?
Now provide the response and nothing else.
|
In the first place, if you are working with other people on the same code repository, you should not delete a commit since when you force the update on the repository it will leave the local repositories of your coworkers in an illegal state (e.g. if they made commits after the one you deleted, those commits will be invalid since they were based on a now non-existent commit). Said that, what you can do is revert the commit. This procedure is done differently (different commands) depending on the CVS you're using: On git : git revert <commit> On mercurial : hg backout <REV> EDIT: The revert operation creates a new commit that does the opposite than the reverted commit (e.g. if the original commit added a line, the revert commit deletes that line), effectively removing the changes of the undesired commit without rewriting the repository history.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14836696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2008506/']}
|
jdg_372995
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3471899
|
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 property on a class that is an ISet. I'm trying to get the results of a linq query into that property, but can't figure out how to do so. Basically, looking for the last part of this: ISet<T> foo = new HashedSet<T>();foo = (from x in bar.Items select x).SOMETHING; Could also do this: HashSet<T> foo = new HashSet<T>();foo = (from x in bar.Items select x).SOMETHING;
Now provide the response and nothing else.
|
I don't think there's anything built in which does this... but it's really easy to write an extension method: public static class Extensions{ public static HashSet<T> ToHashSet<T>( this IEnumerable<T> source, IEqualityComparer<T> comparer = null) { return new HashSet<T>(source, comparer); }} Note that you really do want an extension method (or at least a generic method of some form) here, because you may not be able to express the type of T explicitly: var query = from i in Enumerable.Range(0, 10) select new { i, j = i + 1 };var resultSet = query.ToHashSet(); You can't do that with an explicit call to the HashSet<T> constructor. We're relying on type inference for generic methods to do it for us. Now you could choose to name it ToSet and return ISet<T> - but I'd stick with ToHashSet and the concrete type. This is consistent with the standard LINQ operators ( ToDictionary , ToList ) and allows for future expansion (e.g. ToSortedSet ). You may also want to provide an overload specifying the comparison to use.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3471899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246914/']}
|
jdg_372996
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37760355
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Been trying with no luck to upload an image to S3 from React Native using pre-signed url. Here is my code: generate pre-signed url in node: const s3 = new aws.S3();const s3Params = { Bucket: bucket, Key: fileName, Expires: 60, ContentType: 'image/jpeg', ACL: 'public-read'};return s3.getSignedUrl('putObject', s3Params); here is RN request to S3: var file = { uri: game.pictureToSubmitUri, type: 'image/jpeg', name: 'image.jpg',};const xhr = new XMLHttpRequest();var body = new FormData();body.append('file', file);xhr.open('PUT', signedRequest);xhr.onreadystatechange = () => { if(xhr.readyState === 4){ if(xhr.status === 200){ alert('Posted!'); } else{ alert('Could not upload file.'); } }};xhr.send(body); game.pictureToSubmitUri = assets-library://asset/asset.JPG?id=A282A2C5-31C8-489F-9652-7D3BD5A1FAA4&ext=JPG signedRequest = https://my-bucket.s3-us-west-1.amazonaws.com/8bd2d4b9-3206-4bff-944d-e06f872d8be3?AWSAccessKeyId=AKIAIOLHQY4GAXN26FOQ&Content-Type=image%2Fjpeg&Expires=1465671117&Signature=bkQIp5lgzuYrt2vyl7rqpCXPcps%3D&x-amz-acl=public-read Error message: <Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> I can successfully curl and image to S3 using the generated url, and I seem to be able to successfully post to requestb.in from RN (however I can only see the raw data on requestb.in so not 100% sure the image is properly there). Based on all this, I've narrowed my issue down to 1) my image is not correctly uploading period, or 2) somehow the way S3 wants my request is different then how it is coming in. Any help would be muuuuuucchhhh appreciated! UPDATE Can successfully post from RN to S3 if body is just text ({'data': 'foo'}). Perhaps AWS does not like mutliform data? How can I send as just a file in RN???
Now provide the response and nothing else.
|
FormData will create a multipart/form-data request. S3 PUT object needs its request body to be a file. You just need to send your file in the request body without wrapping it into FormData : function uploadFile(file, signedRequest, url) { const xhr = new XMLHttpRequest(); xhr.open('PUT', signedRequest); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if(xhr.status === 200) { alert(url); } else { alert('Could not upload file.'); } } }; xhr.send(file);}; See https://devcenter.heroku.com/articles/s3-upload-node for example in a browser. Please also ensure your Content-Type header is matched with the signed URL request.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37760355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3735687/']}
|
jdg_372997
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25321139
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Anaconda python is installed (in linux) via a bash script. I am trying to use Vagrant provisioning to get Anacaonda Python installed. In the bash script (following the documentation bootstrap.sh example ) I have a bootstrap.sh script that: wget the install script chmod +x to make it executable ./<script>.sh to install. Installing this way fails as the installation has a few prompts, one of which requires the non-default answer. Is it possible to automate the installation via a bash script? If not, is it necessary to use something like Puppet? I do not know Puppet at all, so have tried to avoid using...perhaps it is time to dig in? The end goal is to ship the Vagrantfile and not host a Vagrant box. P.S. My initial, feeble attempts made use of the linux yes command, but a better way has to exist!
Now provide the response and nothing else.
|
In your bootstrap.sh just include something like: miniconda=Miniconda3-3.7.4-Linux-x86_64.shcd /vagrantif [[ ! -f $miniconda ]]; then wget --quiet http://repo.continuum.io/miniconda/$minicondafichmod +x $miniconda./$miniconda -b -p /opt/anacondacat >> /home/vagrant/.bashrc << END# add for anaconda installPATH=/opt/anaconda/bin:\$PATHEND The -b option runs in batch mode and is what you are looking for: >>>> ./Miniconda-3.7.0-Linux-x86_64.sh -h usage: ./Miniconda-3.7.0-Linux-x86_64.sh [options]Installs Miniconda 3.7.0 -b run install in batch mode (without manual intervention), it is expected the license terms are agreed upon -f no error if install prefix already exists -h print this help message and exit -p PREFIX install prefix, defaults to /Users/phil/miniconda I also typically put Miniconda (or a link to it) directly in the " vagrant " where the bootstrap.sh is. That way, you are not downloading from the web during each vagrant up (after init or destroy).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25321139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/839375/']}
|
jdg_372998
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25995
|
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Well, the title pretty much says it all. The interesting question above was asked by commenter Jay on my blog (see here and here ). I'm guessing both that the answer is yes and that there's a relatively simple proof, but I couldn't see it offhand. (Very roughly, though, one could try to show that, if a language in $P^R$ were not in $BPP$, then it must have infinite algorithmic mutual information with $R$, in which case it wouldn't be computable. Also, note that one direction is trivial: the computable languages in $P^R$ certainly contain $BPP$.) Note that I'm not asking about the class AlmostP , which consists of those languages that are in $P^R$ for almost every $R$ (and is well-known to equal $BPP$). In this question, we first fix $R$, then look at the set of computable languages in $P^R$. On the other hand, one could try to show that, if a language in $P^R$ is computable, even for a fixed random oracle $R$, then in fact that language must be in $AlmostP$. A closely-related question is whether, with probability 1 over a random oracle $R$, we have $ AM = NP^R \cap Computable.$ If so, then we get the following interesting consequence: if $P=NP$, then with probability 1 over a random oracle $R$, the only languages that witness the oracle separation $P^R \ne NP^R$ are uncomputable languages.
Now provide the response and nothing else.
|
Yes. First, since it took me a minute to figure this out myself, let me formalize the difference between your question and $\mathsf{AlmostP}$; it's the order of quantifiers. $\mathsf{AlmostP} := \{L : Pr_R(L \in \mathsf{P}^R) = 1\}$, and the result you allude to is $\forall L\, L \in \mathsf{BPP} \iff Pr_R(L \in \mathsf{P}^R) = 1$. If I've understood correctly, you are asking if $Pr_R(\forall L\, L \in \mathsf{P}^R \cap \mathsf{COMP} \iff L \in \mathsf{BPP}) = Pr_R(\mathsf{P}^R \cap \mathsf{COMP} = \mathsf{BPP}) = 1$. Consider $p := 1-Pr_R(\mathsf{P}^R\cap \mathsf{COMP} = \mathsf{BPP}) = Pr_R(\exists L \in \mathsf{P}^R \cap \mathsf{COMP} \backslash \mathsf{BPP})$. By the union bound, the $p$ is upper-bounded by $\sum_{L \in \mathsf{COMP}} Pr_R(L \in \mathsf{P}^R \backslash \mathsf{BPP})$. (Note that the latter sum is countable.) Now, by the 0-1 law - which applies since all the relevant statements do not change if we change $R$ finitely much - each individual probability in this sum is either 0 or 1. If the answer to your question is no, then $p=1$, so there must be some $L \in \mathsf{COMP}$ such that $Pr_R(L \in \mathsf{P}^R \backslash \mathsf{BPP}) = 1$. But this contradicts the fact that $\mathsf{AlmostP} = \mathsf{BPP}$. Update Oct 10, 2014 : As pointed out in the comment by Emil Jeřábek, the same argument applies to $\mathsf{AM}$ vs. $\mathsf{NP}^R$, since we also know that $\mathsf{AlmostNP} = \mathsf{AM}$. He also points out that we didn't use anything about $\mathsf{COMP}$ other than that it is a countable class that contains $\mathsf{BPP}$ (resp., $\mathsf{AM}$). So the "interesting conclusion" in the OQ actually applies to any countable class of languages $\mathcal{C}$ that contains $\mathsf{AM}$: if $\mathsf{P} = \mathsf{NP}$, the "only" languages that witness the oracle separation $\mathsf{P}^R \neq \mathsf{NP}^R$ are outside of $\mathcal{C}$. But the latter statement feels somewhat misleading to me (it makes it sound like, for any $L_0$ we could consider $\mathcal{C} = \mathsf{AM} \cup \{L_0\}$, and thereby "show" that no $L_0$ realizes $\mathsf{NP}^R \neq \mathsf{P}^R$, contradicting the well-known theorem). Rather, writing it out symbolically, we've shown: If $\mathsf{P} = \mathsf{NP}$, then $\forall \text{countable } \mathcal{C} \supseteq \mathsf{AM}\, Pr_R(\mathsf{NP}^R \neq \mathsf{P}^R \text{ and } \mathsf{NP}^R \cap \mathcal{C} = \mathsf{P}^R \cap \mathcal{C}) = 1$. Note that, crucially, probability 1 is not the same thing as all $R$, and which full-measure set of $R$ satisfy the argument to $Pr_R$ can depend on $\mathcal{C}$. So if we try to alter $\mathcal{C}$ to $\mathcal{C} \cup \{L_0\}$, it at most removes a measure 0 set of $R$ that satisfy this statement.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/25995', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/1575/']}
|
jdg_372999
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47012200
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created a text box in run time using XAML. I need to make the text box as read only. So I have used a code Browsable[True] & ReadOnly[True] to achieve this.So now the style of the text box is changed. Initially, the data in the text box were in bold. But now it is bit lite not in bold text. Now how to make it as bold. Thanks much. [DisplayName("Name"), Browsable(true), ReadOnly(true)]
Now provide the response and nothing else.
|
The reason is, in state you defined: this.state = { fields: {} } fields as a blank object, so during the first rendering this.state.fields.name will be undefined , and the input field will get its value as: value={undefined} Because of that, the input field will become uncontrolled. Once you enter any value in input, fields in state gets changed to: this.state = { fields: {name: 'xyz'} } And at that time the input field gets converted into a controlled component; that's why you are getting the error: A component is changing an uncontrolled input of type text to be controlled. Possible Solutions: 1- Define the fields in state as: this.state = { fields: {name: ''} } 2- Or define the value property by using Short-circuit evaluation like this: value={this.state.fields.name || ''} // (undefined || '') = ''
|
{}
|
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/47012200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373000
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1036666
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For example we can construct such an array like this: new ElementType[0]; I seen such a construct, but I don't understand why this might be useful.
Now provide the response and nothing else.
|
An example. Say, you have a function public String[] getFileNames(String criteria) { to get some filenames. Imagine that you don't find any filenames satisfying criteria. What do you return? You have 2 choices - either return null , or 0-sized array . The variant with 0-sized array is better, because your caller doesn't need to check for NULL and can process the array in a consistent way - say, in a loop (which would be empty in this case). There's a chapter on this in Effective Java, Item 27
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1036666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124339/']}
|
jdg_373001
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
114217
|
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 have a complicated function that is a combination of floating-point numbers and variables. I want all the numbers rounded off, but I have no clue how to do this. For example I would want f[x_,y_]:=3.23425124`x^2 + 5.8978587`y To become f[x_,y_]:=3.2x^2 + 5.9y If it were an array I could have something like Thread[Round[#],array] But with a function what to do is not clear.
Now provide the response and nothing else.
|
3.23425124` x^2 + 5.8978587` y /. Times[a_, b_] :> Times[Round[a, 0.1], b](*3.2 x^2 + 5.9 y*) coefficient * variable is of Times[coefficient, variable] in full form, therefore you can use this pattern to match and round only the coefficient.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/114217', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/19330/']}
|
jdg_373002
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47366
|
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:
There is hint: Prove $H^{n-1}(N) \to H^{n-1}(M)$ is trivial. Just don't know how to prove this.
Now provide the response and nothing else.
|
So that we're not worried about orientability, I will work with $\mathbb Z_2$ coefficients. Also, I will assume that $M$ and $\partial M$ is connected. (If $\partial M$ is not connected, $H_{n-1}(\partial M)\to H_{n-1}(M)$ isn't necessarily $0$.) If you look at the long exact sequence of the pair $(M,\partial M)$, you discover that $H_{n-1}(\partial M;\mathbb Z_2)\to H_{n-1}(M;\mathbb Z_2)$ is $0$ if and only if the boundary map $$H_{n}(M,\partial M;\mathbb Z_2)\to H_{n-1}(\partial M;\mathbb Z_2)$$ is surjective. Well by Lefschetz duality $H_{n}(M,\partial M;\mathbb Z_2)\cong H^0(M)=\mathbb Z_2$. Similarly by Poincare duality $H_{n-1}(\partial M;\mathbb Z_2)\cong H^0(\partial M;\mathbb Z_2)=\mathbb Z_2$. In the long exact sequence, since $H_n(M;\mathbb Z_2)=0$, the boundary homomorphism is injective, implying that it is surjective since the codomain is $\mathbb Z_2$. If you assume that your manifolds can be triangulated, then this is easy to see geometrically. The fundamental class of $H_{n-1}(\partial M;\mathbb Z_2)$ is the sum of simplices in the triangulation, which is the boundary of the sum of the simplices in $M$, implying that the inclusion $\partial M\to M$ is trivial in $n-1$-dimensional homology. This works for most manifolds, but unfortunately there are manifolds which cannot be triangulated, so you need the more subtle Poincare duality argument.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/47366', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12466/']}
|
jdg_373003
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6988823
|
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 does one add a variable string in this javascript statement?where name may correspond to any valid string , say WebkitTransform or Moztransform,etc document.getElementById('test').style.VARIABLE_NAME = 'rotate(15deg)'; My code doesn't seem to work when i set the VARIABLE_NAME to WebkitTransform, but it works fine if I use WebkitTransform directly, as in without naming it via a variable.Thanks in advance :)
Now provide the response and nothing else.
|
There are two ways to access members of a Javascript object. Dot notation , which uses an identifier to access the member: obj.member; Bracket notation , which uses a string to access the member: obj['member'] The latter uses a string to locate the member and you can just as easily use any expression. The value of the expression will be converted to a string so these are equivalent: obj[{}]obj['[object Object]'] If your expression is already a string it will be used as is, and in your case your variable holds a string so you can just do: document.getElementById('test').style[VARIABLE_NAME] = 'rotate(15deg)';
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6988823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/884759/']}
|
jdg_373004
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1114254
|
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 popular browsers' user agent strings, even Internet Explorer's, start with Mozilla/ . Why is this the case?
Now provide the response and nothing else.
|
It is a long and sad story . In summary: Mozilla browser gets released, with User-Agent Mozilla/1.0 (Win3.1) . It is publicly renamed to Netscape, but in its User-Agent it keeps its original name . Internet Explorer is released. It spoofs Netscape by starting its User-Agent with Mozilla/ because web servers were routinely browser sniffing and serving pages with frames - a feature supported by both Netscape and IE, but not other browsers of the era - to Netscape only. Over time, Gecko, Konqueror, Opera, Safari and Chrome each decide to similarly spoof the User-Agent of some previous browser in order to manipulate browser-sniffing web pages into correctly understanding their browser's features. As part of this spoofing, all the browsers start their User-Agents with Mozilla/ , like the browsers before them had done. Plenty of other nonsense also results, like modern Chrome's User-Agent simultaneously claiming to be Mozilla, Chrome, Safari, and 'like Gecko'.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1114254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111040/']}
|
jdg_373005
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
868164
|
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 write in C# method in such a way that when I write String contestId = getParameter("contestId") i get contestId in string, but when I write: int contestId = getParameter("contestId") i get contestId parsed to integer? This is only simple example showing what i try to achieve.
Now provide the response and nothing else.
|
Nope it's not possible to overload methods solely based on their return type. You could, however, introduce a generic parameter: T getParameter<T>(string input) { // ... do stuff based on T ...} And if you were using C# 3.0 you could use this method as: var str = getParameter<string>("contestid");var integer = getParameter<int>("contestid"); thus saying the actual type only once.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/868164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59666/']}
|
jdg_373006
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20497778
|
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 ResultSet Methods which I am closing the Connection in a finallly Block: public static ResultSet countdrcountcr(String vforacid) throws SQLException { ResultSet rs = null; Connection conn = null; try { conn = db.getDbConnection(); String sql = "SELECT NVL (SUM (DECODE (part_tran_type, 'D', 1, 0)), 0), " + " NVL (SUM (DECODE (part_tran_type, 'C', 1, 0)), 0) " + " FROM tbaadm.htd WHERE acid IN (SELECT acid " + " FROM tbaadm.gam WHERE foracid = '" + vforacid + "') " + " AND tran_date >= '22-NOV-2013' AND tran_date <= '30-NOV-2013' " + " AND pstd_flg = 'Y' AND del_flg != 'Y'"; PreparedStatement ps = conn.prepareStatement(sql); rs = ps.executeQuery(); return rs; } finally { conn.close(); } } But I am getting the error : edit The whole ErrorTrace Exception in thread "main" java.sql.SQLException: Closed Connection: nextat oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)at oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java:181)at statement.Statement.main(Statement.java:34)Java Result: 1 What am I not doing right?
Now provide the response and nothing else.
|
You're returning a ResultSet for future use but after using it you're closing the connection, so you have no way to retrieve the data since the resource is already closed. Note that finally is always called, even if you return something in the try or catch code block, refer to Does finally always execute in Java? In detail, this is the problem: Open the connection Prepare a statement Get the result set Return the result set Close the connection (that may close the associated resources i.e. it may close the PreparedStatement and the ResultSet associated with the current Connection ) because, as noted in the link before, finally block is always executed at least that the JVM crashes or you manually finish the application using System.exit . Using a closed ResultSet . It is closed due to the previous step. A possible solution would be that your countdrcountcr method and all other methods that return a ResultSet receive the Connection as parameter, so the method that calls it will handle the connection opening and closing. Also, take note that you should not use static methods to handle your database operations if you're working in a multi threaded environment e.g. a web application.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20497778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1197359/']}
|
jdg_373007
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14222090
|
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 spreadsheet in google docs that I'd want to integrate in a git workflow (and push to github). Are there any tools (or even libraries that are gdoc version aware) that do, or help me do, that? I have some old ruby hacks lying around based on the google_spreadsheet gem that reads and writes current versions of a csv gdoc, but nothing which extracts revision history.
Now provide the response and nothing else.
|
I was intrigued by your question, so I hacked together a little project today: https://github.com/larsks/gitdriver Given a document id, it will create a git repository using either the plain text or HTML content of a Google Docs document. This could easily be extended to work with other file types. It looks something like this when it works: $ python gitdriver.py -T 1j6Ygv0ow5A8_ywTMwJbuKVrxrSsSH2wJs3a8Q66mvt4Create repository "Untitled"Initialized empty Git repository in /home/lars/projects/gitdriver/Untitled/.git/[master (root-commit) 24d35e7] revision from 2013-01-08T21:57:38.837Z 1 file changed, 1 insertion(+) create mode 100644 content[master fd243ee] revision from 2013-01-08T21:57:45.800Z 1 file changed, 1 insertion(+), 1 deletion(-) rewrite content (95%)[master 5ad1a26] revision from 2013-01-09T01:47:29.593Z 1 file changed, 1 insertion(+), 1 deletion(-) rewrite content (92%)$ cd Untitled$ git log --oneline5ad1a26 revision from 2013-01-09T01:47:29.593Zfd243ee revision from 2013-01-08T21:57:45.800Z24d35e7 revision from 2013-01-08T21:57:38.837Z This requires you to set up the necessary application credentials with Google. And it doesn't do any error checking. And may eat your goldfish. This is meant as a demonstration of the API and how you might do something like this; it's not intended to be a functional product.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14222090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1130377/']}
|
jdg_373008
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20264
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
According to my textbook, Davson-Danielli's model of a phospholipid bilayer sandwiched between two layers of globular protein was incorrect. The nonpolar protein portions would separate the polar portions of the phospholipids from water, causing the bilayer to dissolve. Meaning, the Davson-Danielli model is not only incorrect, but it is also impossible. I understand why the model is incorrect, but not why it is impossible. In my view, the nonpolar proteins would remain together in a micelle shape due to hydrophobic exclusion. Because of this, the phospholipid bilayer sandwiched on the inside would remain isolated from the water. Why would a bilayer dissolve if the proteins were in contact with water and the phospholipids were isolated from the water? I think that my confusion stems from many misunderstandings about the chemistry and structure of the cell membrane. In depth illustration of the error that my book mentioned would be most helpful.
Now provide the response and nothing else.
|
The original figure that Danielli and Davson proposed looks like this (from the original publication ): It shows the phospholipid bilayer of the membrane (which is correct) embedded between two layers of globular proteins. The hydrophobic tails of the lipids are orientated towards each other, while the hydrophilic heads are oriented to the outside. Although the membrane composition is correct (this was already published 1925 by Gorter and Grendel ), there are some problems with the proposed model: Membranes are not identical. The differ in thickness and the ratio ofproteins:lipids. Membranes have distinct inside and outside layers (defined by themembrane proteins which are present on the surface of the membrane) Other than predicted by the model, the membrane proteins do not havea very good solubility in water - in fact they are amphiphatic,meaning they have hydrophilic and hydrophobic regions. Thehydrophobic side is anchored inside the membrane. When the membrane proteins would cover the lipid bilayer, theirhydrophobic regions would be in contact with water, whichdestabilizes this construct. Even if they would be oriented towardsthe membrane, they would face towards the hydrophilic heads of thephospholipids causing the same effect. Additionally the proteinswould also seperate the hydrophilic phospholipid heads from thewater. So there is no real stable solution in embedding the membranewith proteins.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/20264', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/5179/']}
|
jdg_373009
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2611205
|
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 got a Python program that stores and writes data to a file. The data is raw binary data, stored internally as str . I'm writing it out through a utf-8 codec. However, I get UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 25: character maps to <undefined> in the cp1252.py file. This looks to me like Python is trying to interpret the data using the default code page. But it doesn't have a default code page. That's why I'm using str , not unicode . I guess my questions are: How do I represent raw binary data in memory, in Python? When I'm writing raw binary data out through a codec, how do I encode/unencode it?
Now provide the response and nothing else.
|
NOTE: this was written for Python 2.x. Not sure if applicable to 3.x. Your use of str for raw binary data in memory is correct. [If you're using Python 2.6+, it's even better to use bytes which in 2.6+ is just an alias to str but expresses your intention better, and will help if one day you port the code to Python 3.] As others note, writing binary data through a codec is strange. A write codec takes unicode and outputs bytes into the file. You're trying to do it backwards, hence our confusion about your intentions... [And your diagnosis of the error looks correct: since the codec expects unicode, Python is decoding your str into unicode with the system's default encoding, which chokes.] What you want to see in the output file? If the file should contain the binary data as-is : Then you must not send it through a codec; you must write it directly to the file. A codec encodes everything and can only emit valid encodings of unicode (in your case, valid UTF-8).There is no input you can give it to make it emit arbitrary byte sequences! If you require a mixture of UTF-8 and raw binary data, you should open the file directly, and intermix writes of some_data with some_text.encode('utf8') ... Note however that mixing UTF-8 with raw arbitrary data is very bad design, because such files are very inconvenient to deal with! Tools that understand unicode will choke on the binary data, leaving you with not convenient way to even view (let alone modify) the file. If you want a friendly representation of arbitrary bytes in unicode : Pass data.encode('base64') to the codec. Base64 produces only clean ascii (letters, numbers, and a little punctuation) so it can be clearly embedded in anything, it clearly looks to people as binary data, and it's reasonably compact (slightly over 33% overhead). P.S. you may note that data.encode('base64') is strange. .encode() is supposed to take unicode but I'm giving it a string?! Python has several pseudo-codecs that convert str->str such as 'base64' and 'zlib'. .encode() always returns an str but you'll feed it into a codec expecting unicode?! In this case it will only contain clean ascii, so it doesn't matter. You may write explicitly data.encode('base64').encode('utf8') if it makes you feel better. If you need a 1:1 mapping from arbitrary bytes to unicode : Pass data.decode('latin1') to the codec. latin1 maps bytes 0-255 to unicode characters 0-255, which is kinda elegant. The codec will, of course, encode your characters - 128-255 are encoded as 2 or 3 bytes in UTF-8 (surprisingly, the average overhead is 50%, more than base64!). This quite kills the "elegance" of having a 1:1 mapping. Note also that unicode characters 0-255 include nasty invisible/control characters (newline, formfeed, soft hyphen, etc.)making your binary data annoying to view in text editors. Considering these drawbacks, I do not recommend latin1 unless you understand exactly why you want it. I'm just mentioning it as the other "natural" encoding that springs to mind.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2611205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9161/']}
|
jdg_373010
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21386768
|
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 few problems with some VERY simple lines of code. Let me detail the facts and see if anyone else can replicate this behavior. If any one can replicate I would like to get an explanation of why it is happening. So lets me start with a very simple line of code THAT WORKS: Dim arr() As Variantarr = Range("A1:A10") this does as expected, arr is assigned the Values of A1:A10 now why won't the following line of code work? Dim arr() As Variantarr = WorkSheets("Sheet1").Range("A1:A10") I get a Run-Time Error '13' Type mismatch, even though the same range was successfully assigned to the array, just without the Worksheet value. But Dim arr As Variantarr = Worksheets("Sheet1").Range("A1:A10") And Dim arr() As Variantarr = Application.Transpose(Application.Transpose(Worksheets("Sheet1").Range("A1:A10"))) DOES WORK Now before you answer please let me give you some more facts. Dim arr() As Variantarr = Worksheets(1).Range("A1:A10") Does Not Work and using Sheets in place of Worksheets also all give the same error. I have made sure it is the same sheet as the active referenced sheet by using Range("A1:A10").Worksheet.Name Following the working code and it indeed says Sheet1 in the output. No other workbooks are open so it can't be referencing another workbook either. Now this last bit of code only adds to my confusion as it totally works! Dim arr() As VariantDim SampleRange As RangeSet SampleRange = Worksheets("Sheet1").Range("A1:A10")arr = SampleRange So using the SAME RANGE defined the same way on the same sheet now works when I assign it to a Range Variable. and use that! And as expected this works with both the WorkSheets and Sheets function regardless of how I define the sheet (I can use the index or the Name of the worksheet and all work fine) If it helps anyone, I am testing this with Excel 2007 on a Windows XP machine. I have not yet tested it on any other machines but I plan to test on 2003 and 2010 on Windows 7 and 8, just haven't had the chance yet. UPDATE: Not 100% sure if this is the same exact issue as with the array but from a shallow view it seems to be: Range("B1:B3") = Range("A1:A3") The above code will not work, even if A1:A3 is populated, dates, numeric values, strings, formula anything, it will write blanks into B1:B3 But Range("B1:B3").Value = Range("A1:A3").Value And Range("B1") = Range("A1") does work! Also working is: Range("B1:B3") = Application.Transpose(Application.Transpose(Range("A1:A3")))
Now provide the response and nothing else.
|
No it is not a bug. The point is that Value is the default property of the Range Object, so why isn't it implicitly used? Did you have a look at the question I linked? (FROM CHAT ) The experts posting previous answers have already explained very well in details. I will keep the explanation to minimal and hence let me know if you still have any questions. Let's understand our objects first. I created this small table which clearly shows what are we handling so that there is no confusion. You could also add a Watch to see the Type for a particular object as shown in the pic below. So when you say arr = Range("A1:A10") Excel knows that the default property is .Value . However in other case, it doesn't know because Excel is not a mind reader or let's say intelligent enough to understand whether you want to use Worksheets("Sheet1").Range("A1:A10") as a Range or a Variant Once you explicitly specify your object as a Range then Excel knows what you want. For example this works. Dim arr() As VariantDim Rng As Range Set Rng = Worksheets("Sheet1").Range("A1:A10")arr = Rng
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21386768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2140261/']}
|
jdg_373011
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60487010
|
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 method that returns an object by value. The method comes from a library that I have no control over. For the further handling of the object I want to continue working with a unique_ptr on this object. Here is an example: #include <iostream>#include <memory>class Bla { public: Bla() { std::cout << "Constructor!\n"; } ~Bla() { std::cout << "Destructor!\n"; }};Bla GetBla() { Bla bla; return std::move(bla);}int main() { auto bla = std::make_unique<Bla>(GetBla());} The example produces the following output: Constructor!Destructor!Destructor!Destructor! Why is the destructor of Bla called 3 times here? Is the way I create the unique_prt correct?
Now provide the response and nothing else.
|
There are indeed 3 times that an instance of Bla is constructed. Bla GetBla() { Bla bla; // 1st construction return std::move(bla); // 2nd construction (return by copy)} Don't return by move. Just return bla , in most cases the copy will be elided. auto bla = std::make_unique<Bla>(GetBla()); // 3rd construction - Bla copy construction Note that make_unique<Bla> always constructs a new instance. In this case because you're passing another instance, it becomes copy-construction. A hint that copy construction takes place is that your default constructor is invoked only once, while the destructor is invoked 3 times. That's because in the other 2 cases the implicit copy (or move) constructor is invoked ( Bla::Bla(Bla const&) ).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60487010', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6518452/']}
|
jdg_373012
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12103953
|
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 app I have two fragments say fragmentA and FragmentB . When I click on a button in fragmetA , a list is opened in fragmentB . Now when I select an item from list in fragmentB I want the result to be passed to fragmentA . I am using only one TabActivity for all fragments. When list item is selected in fragmentB I am popping out fragmentB from stack so that I can directly go back to fragmentA . Does anyone knows how to pass result to previous fragment. Thanks.
Now provide the response and nothing else.
|
Update Activity is the parent controller and should take responsibility for handling those events raised by its fragments/views, which concern something outside of the scope of fragment/view itself. A Fragment is to act as a sub-controller of Views it hosts. All the events and communication between its own views, the fragment should handle itself. When there is an event outside of a fragment's scope and responsibilities (like sending data to another fragment), that event should be escalated to its parent controller, the Activity. Old From this tutorial : http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity Its better to let the activity apply changes to its fragment than passing values directly between fragments. Let your Activity implement a FragmentListener interface with onQuery(Bundle data) and onResult(Bundle data) methods. Create a FragmentListener varaible in each of your fragments and then override onAttach() of each fragment as: public void onAttach(Activity activity) { super.onAttach(activity); //---register parent activity for events--- try{ fragmentListener = (FragmentListener) activity; }catch (ClassCastException e) { throw new ClassCastException("Parent activity must implement interface FragmentListener."); } } This will enforce your child fragments to be automatically registered to parent Activity. Also, remember to release fragmentListener reference in onDetach() . Now you can call your Activity from fragments. On the other side, your Activity can always search for a fragment using getFragmentManager().findFragmentByTag("fragmentA") or findFragmentById("FragmentA") . If it can find your Fragment, Then it can cast it into your FragmentA class and call its methods. Same can be done with FragmentB or any other fragment..
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12103953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1122546/']}
|
jdg_373013
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12001953
|
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 string: var string = "aaaaaa<br />† bbbb<br />‡ cccc" And I would like to split this string with the delimiter <br /> followed by a special character. To do that, I am using this: string.split(/<br \/>&#?[a-zA-Z0-9]+;/g); I am getting what I need, except that I am losing the delimiter.Here is the example: http://jsfiddle.net/JwrZ6/1/ How can I keep the delimiter?
Now provide the response and nothing else.
|
I was having similar but slight different problem. Anyway, here are examples of three different scenarios for where to keep the deliminator. "1、2、3".split("、") == ["1", "2", "3"]"1、2、3".split(/(、)/g) == ["1", "、", "2", "、", "3"]"1、2、3".split(/(?=、)/g) == ["1", "、2", "、3"]"1、2、3".split(/(?!、)/g) == ["1、", "2、", "3"]"1、2、3".split(/(.*?、)/g) == ["", "1、", "", "2、", "3"] Warning: The fourth will only work to split single characters. ConnorsFan presents an alternative : // Split a path, but keep the slashes that follow directoriesvar str = 'Animation/rawr/javascript.js';var tokens = str.match(/[^\/]+\/?|\//g);
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/12001953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1018270/']}
|
jdg_373014
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4320630
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As per this how-to , I've successfully configured IIS on my XP-SP3 dev box for SQL Server 2008 Express to save ASP.NET session state information. I'm just using SQL Server because otherwise on every recompile, I was losing the session state which was obnoxious (having to re-login). But, I'm facing an annoying issue in that every time I restart SQL there's this error, and sometimes one or two other very similar friends: The SELECT permission was denied on the object 'ASPStateTempSessions',database 'tempdb', schema 'dbo'. To fix the error, I just open Management Studio and edit the User Mapping for the login/dbo I'm using on the ASPState db, and re-add tempdb to that user with all but deny permissions. Apparently, once the right permissions are there, ASP.NET is able to automatically create the tables it uses. It just can't run that CreateTempTables sproc until the right security is there. THE QUESTION... Is there a way to not have to re-do this on every restart of the SQL Server? I don't really care right now about keeping the temp data across restarts, but I would like to not have to go through this manual step just to get my web app working on localhost, which uses session state variables throughout. I suppose one could resort to some kind of stored procedure within SQL Server to accomplish the task for this machine when the service starts, to not have to do it manually. I'd accept such an answer as a quick fix. But, I'm also assuming there's a better recommended configuration or something. Not seeing an answer to this on the how-to guide or elsewhere here on StackOverflow.
Now provide the response and nothing else.
|
Both answers seem valid; but with most things Microsoft, its all in the setup... First uninstall the ASPState database by using the command: aspnet_regsql –ssremove –E -S . Note: -E is to indicate you want to use integrated security connection. -S informs what SQL server and SQL instance to use, and the "." (dot) specifies default local instance Then re-install using the command: aspnet_regsql –ssadd –sstype p –E -S . Note: The sstype has three options, t | p | c ... the first "t", tells the installer to host all stored procedures in the ASPState database, and all data in the tempdb. The second option "p" tells the installer to persist data to the ASPState database. The last option "c" allows you to specify a different 'custom' database to persist the session state data. If you reinstall using the "-sstype p" you then need only to supply datareader/datawriter to the ASPState database for the user that's making the connection (in most cases, the application pool's identity in IIS). The added benefit of persisting the data is that session state is retained even after a restart of the service. The only drawback is that you need to ensure the agent cleanup job is pruning old sessions regularly (it does this by default, every minute). Important: If you are running a cluster, you must persist session data. You're only option is to use sstype 'p' or 'c'. Hope this sheds light on the issue!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4320630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/512671/']}
|
jdg_373015
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17152976
|
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 simple WCF POST that posts a simple XML to the service. This is the service contract. [ServiceContract]public interface ITest{ [OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "PostTest")] Stream PostTest(Stream testInfo); } And the configuration, nothing fancy. <system.serviceModel><services> <service name="T.Test" behaviorConfiguration="ServiceBehaviour"> <!-- Service Endpoints --> <!-- Unless fully qualified, address is relative to base address supplied above --> <endpoint address ="" binding="webHttpBinding" contract="T.ITest" behaviorConfiguration="web"> <!-- Upon deployment, the following identity element should be removed or replaced to reflect the identity under which the deployed service runs. If removed, WCF will infer an appropriate identity automatically. --> </endpoint> </service></services><behaviors> <serviceBehaviors> <behavior name="ServiceBehaviour"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="web"> <webHttp/> </behavior> </endpointBehaviors></behaviors><serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> Everything works when I test it from a simple client as long as I don't mention the content type. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST"; req.ContentType = "text/xml; charset=utf-8"; var xmlDoc = new XmlDocument { XmlResolver = null };xmlDoc.Load("../../PostData.xml");string sXml = xmlDoc.InnerXml;Console.Write(sXml + Environment.NewLine + Environment.NewLine);req.ContentLength = sXml.Length;var sw = new StreamWriter(req.GetRequestStream());sw.Write(sXml);sw.Close();HttpWebResponse res = (HttpWebResponse)req.GetResponse(); After some research I understand this is a compatibility issue between soap 1.1 vs soap 1.2. But how do I fix this on server side?
Now provide the response and nothing else.
|
The error results from the fact that a call to myMethod will be ambiguous - which of the two methods should be called? From JLS §8.4.2 : It is a compile-time error to declare two methods with override-equivalent signatures in a class. The return type of a method is not a part of its signature, so you are receiving an error in accordance with the statement above. Assuming you can't simply rename the conflicting methods, you can't use inheritance in this case, and will need to use an alternative like composition : class DerivedClass implements MyInterface { private SuperClass sc; public String myMethod1() { return sc.myMethod(); } public int myMethod() { return 0; }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17152976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132985/']}
|
jdg_373016
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38829153
|
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 to test a web-application which contains a drag and drop area for uploading files from the local file system. My test environment is based on C#. For the automation testing I have used Selenium, but it is not possible to drag files from the file system. The upload area is a div tag (no input tag). So what's the best way to do it? AutoIt (is it possible to drop in a web browser)? Sikuli?
Now provide the response and nothing else.
|
It's possible with Selenium alone, but it's not simple. It requires to inject a new INPUT element in the page to receive the file through SendKeys . Then, the script needs to simulate the drop by sending the dragenter , dragover , drop events to the targeted area. static void Main(string[] args){ var driver = new ChromeDriver(); driver.Url = "https://react-dropzone.js.org/"; IWebElement droparea = driver.FindElementByCssSelector("[data-preview='Basic example'] [style]"); DropFile(droparea, @"C:\Users\florent\Desktop\capture.png"); driver.Quit();}const string JS_DROP_FILE = "for(var b=arguments[0],k=arguments[1],l=arguments[2],c=b.ownerDocument,m=0;;){var e=b.getBoundingClientRect(),g=e.left+(k||e.width/2),h=e.top+(l||e.height/2),f=c.elementFromPoint(g,h);if(f&&b.contains(f))break;if(1<++m)throw b=Error('Element not interractable'),b.code=15,b;b.scrollIntoView({behavior:'instant',block:'center',inline:'center'})}var a=c.createElement('INPUT');a.setAttribute('type','file');a.setAttribute('style','position:fixed;z-index:2147483647;left:0;top:0;');a.onchange=function(){var b={effectAllowed:'all',dropEffect:'none',types:['Files'],files:this.files,setData:function(){},getData:function(){},clearData:function(){},setDragImage:function(){}};window.DataTransferItemList&&(b.items=Object.setPrototypeOf([Object.setPrototypeOf({kind:'file',type:this.files[0].type,file:this.files[0],getAsFile:function(){return this.file},getAsString:function(b){var a=new FileReader;a.onload=function(a){b(a.target.result)};a.readAsText(this.file)}},DataTransferItem.prototype)],DataTransferItemList.prototype));Object.setPrototypeOf(b,DataTransfer.prototype);['dragenter','dragover','drop'].forEach(function(a){var d=c.createEvent('DragEvent');d.initMouseEvent(a,!0,!0,c.defaultView,0,0,0,g,h,!1,!1,!1,!1,0,null);Object.setPrototypeOf(d,null);d.dataTransfer=b;Object.setPrototypeOf(d,DragEvent.prototype);f.dispatchEvent(d)});a.parentElement.removeChild(a)};c.documentElement.appendChild(a);a.getBoundingClientRect();return a;";static void DropFile(IWebElement target, string filePath, double offsetX = 0, double offsetY = 0){ if (!File.Exists(filePath)) throw new FileNotFoundException(filePath); IWebDriver driver = ((RemoteWebElement)target).WrappedDriver; IJavaScriptExecutor jse = (IJavaScriptExecutor)driver; IWebElement input = (IWebElement)jse.ExecuteScript(JS_DROP_FILE, target, offsetX, offsetY); input.SendKeys(filePath);} Source: https://gist.github.com/florentbr/349b1ab024ca9f3de56e6bf8af2ac69e
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38829153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5166670/']}
|
jdg_373017
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27011921
|
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 setting up a simple program that collects your name and then returns it in the console. The window opens successfully but when I enter text into ' jTextFieldPlayerName ' and press 'continue' The console prints 'Your name is: null' . I am trying to make the console print out what you entered in 'jTextFieldPlayerName' (ex. Your name is: CrashDive) rather than 'Your name is: null'. -Thanks package bin;import javax.swing.*;import java.awt.*;import java.awt.event.*;public class main extends JPanel implements ActionListener {protected JLabel text1;protected JButton continue;protected JTextField jTextFieldPlayerName;protected String playerName;public main() { text1 = new JLabel("<html><center>Before we can start we need to know your name.<br><html>"); startText1.setVerticalTextPosition(JLabel.TOP); startText1.setHorizontalTextPosition(JLabel.CENTER); jTextFieldPlayerName = new JTextField(); jTextFieldPlayerName.setPreferredSize(new Dimension(300,20)); continue = new JButton("Continue"); continue.setMnemonic(KeyEvent.VK_D); continue.addActionListener(this); continue.setVerticalTextPosition(AbstractButton.CENTER); continue.setHorizontalTextPosition(AbstractButton.CENTER); add(text1); add(jTextFieldPlayerName); add(continue); String playerName = jTextFieldPlayerName.getText();}public void actionPerformed(ActionEvent evt) { Object src = evt.getSource(); if (src == startText1Continue && jTextFieldPlayerName.getText().length() > 0) { System.out.println("Your name is: " +playerName); }}private static void createAndShowGUI() { JFrame frame = new JFrame("Test Game"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); main newContentPane = new main(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.setSize(1400, 700); frame.setVisible(true);}public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } });} }
Now provide the response and nothing else.
|
TLDR: No, but there's a hack There's no true interprocess communication for iOS apps, with or without extensions. NSDistributedNotification still hasn't made the trip from OS X to iOS, and probably won't. With some extension types you can open URLs via NSExtensionContext and use them to pass data to an app that handles the URL. This brings the app to the foreground, which doesn't sound like what you want. There is a hack that might get you what you need, though. Instead of writing to user defaults, write to a file in your app group directory. Don't just write the file directly-- use NSFileCoordinator to do coordinated writes to the file. Implement NSFilePresenter on an object that wants to know about changes to the file, and make sure to call [NSFileCoordinator addFilePresenter:someObject] Implement the optional presentedItemDidChange method on your file presenter. If you do all of this right, you can write to this file from either the app or the extension, and then have presentedItemDidChange be automatically called in the other one. As a bonus you can of course read the contents of that file, so you can pass arbitrary data back and forth.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27011921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4217962/']}
|
jdg_373018
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
137077
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any way to serialize a shell variable? Suppose I have a variable $VAR , and I want to be able to save it to a file or whatever, and then read it back later to get the same value back? Is there a portable way of doing this? (I don't think so) Is there a way to do it in bash or zsh?
Now provide the response and nothing else.
|
Warning: With any of these solutions, you need to be aware that you are trusting the integrity of the data files to be safe as they will get executed as shell code in your script. Securing them is paramount to your script's security! Simple inline implementation for serializing one or more variables Yes, in both bash and zsh you can serialize the contents of a variable in a way that is easy to retrieve using the typeset builtin and the -p argument. The output format is such that you can simply source the output to get your stuff back. # You have variable(s) $FOO and $BAR already with your stuff typeset -p FOO BAR > ./serialized_data.sh You can get your stuff back like this either later in your script or in another script altogether: # Load up the serialized data back into the current shellsource serialized_data.sh This will work for bash, zsh and ksh including passing data between different shells. Bash will translate this to its builtin declare function while zsh implements this with typeset but as bash has an alias for this to work either way for we use typeset here for ksh compatibility. More complex generalized implementation using functions The above implementation is really simple, but if you call it frequently you might want to give yourself a utility function to make it easier. Additionally if you ever try to include the above inside custom functions you will run into issues with variable scoping. This version should eliminate those issues. Note for all of these, in order to maintain bash/zsh cross-compatibility we will be fixing both the cases of typeset and declare so the code should work in either or both shells. This adds some bulk and mess that could be eliminated if you were only doing this for one shell or another. The main problem with using functions for this (or including the code in other functions) is that the typeset function generates code that, when sourced back into a script from inside a function, defaults to creating a local variable rather than a global one. This can be fixed with one of several hacks. My initial attempt to to fix this was parse the output of the serialize process through sed to add the -g flag so the created code defines a global variable when sourced back in. serialize() { typeset -p "$1" | sed -E '0,/^(typeset|declare)/{s/ / -g /}' > "./serialized_$1.sh"}deserialize() { source "./serialized_$1.sh"} Note that the funky sed expression is to only match the first occurrence of either 'typeset' or 'declare' and add -g as a first argument. It is necessary to only match the first occurrence because, as Stéphane Chazelas rightly pointed out in comments, otherwise it will also match cases where the serialized string contains literal newlines followed by the word declare or typeset. In addition to correcting my initial parsing faux pas , Stéphane also suggested a less brittle way to hack this that not only side steps the issues with parsing the strings but could be a useful hook to add additional functionality by using a wrapper function to redefine the actions taken when sourcing the data back in. This assumes you are not playing any other games with the declare or typeset commands, but this technique would be easier to implement in a situation where you were including this functionality as part of another function of your own or you were not in control of the data being written and whether or not it had the -g flag added. Something similar could also be done with aliases, see Gilles's answer for an implementation. To make the result even more useful, we can iterate over multiple variables passed to our functions by assuming that each word in the argument array is a variable name. The result becomes something like this: serialize() { for var in $@; do typeset -p "$var" > "./serialized_$var.sh" done}deserialize() { declare() { builtin declare -g "$@"; } typeset() { builtin typeset -g "$@"; } for var in $@; do source "./serialized_$var.sh" done unset -f declare typeset} With either solution, usage would look like this: # Load some test data into variablesFOO=(an array or something)BAR=$(uptime)# Save it out to our serialized data filesserialize FOO BAR# For testing purposes unset the variables to we know if it workedunset FOO BAR# Load the data back in from out data filesdeserialize FOO BARecho "FOO: $FOO\nBAR: $BAR"
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/137077', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/72485/']}
|
jdg_373019
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3759933
|
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:
$\textbf{Problem}$ $\bullet~$ Let $X$ denote the closed unit interval, and let $R$ be the ring of continuous functions $X \to \mathbb{R}$ . $\textbf{(a)}~$ Let $f_{1}, f_{2}, \dots, f_{n}$ be functions with no common zero on $X$ . Prove that the ideal generated by these functions is the unit ideal. $%\boxed{\textit{Hint: }~ \text{ Consider the sum } \sum_{i = 1}^{n}f_{i}^{2}.}$$\textbf{(b)}~$ Establish a bijective correspondence between maximal ideals of $R$ and points on the interval. Any sort of Idea?
Now provide the response and nothing else.
|
I think that the comments suffice to solve this particular exercise, but more generally, any time you want to proof divisibility criteria for integers, the solution usually lies in manipulating the decimal expansion of numbers, as in (using your notation): $$\overline{abcdef}= 10^5 a+10^4 b+10^3 c +10^2 d+10^1 e + 10^0 f$$ As you can see from the comments, you can also manipulate "bigger chunks" of the expansion, as in $$\overline{abcdef}=10^4\cdot\overline{ab}+10^2\cdot\overline{cd}+10^0\cdot\overline{ef}$$ In this case, the solution comes from simply noticing that $\overline{abcdef}=10^3\cdot\overline{abc}+10^0\cdot\overline{def}$ , thus giving: $$ \overline{abcdef}=1000\overline{abc}+\overline{def}=1001\overline{abc}+(\overline{def}-\overline{abc}) $$ Since $1001$ is divisible by $7$ , you get the characterization you were looking for: $\overline{abcdef}\equiv\overline{def}-\overline{abc}\mod 7$ , or in other words, $\overline{abcdef}$ is divisible by $7$ if and only if $\overline{def}-\overline{abc}$ is (sign doesn't matter in this case).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3759933', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/745108/']}
|
jdg_373020
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14470111
|
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 understanding so far is on our controller request mapping method we can specify RedirectAttributes parameter and populate it with attributes for when the request gets redirected. Example : @RequestMapping(value="/hello", method=GET)public String hello(RedirectAttributes redirAttr){ // should I use redirAttr.addAttribute() or redirAttr.addFlashAttribute() here ? // ... return "redirect:/somewhere";} The redirect attributes will then be available on the target page where it redirects to. However RedirectAttributes class has two methods: addAttribute() addFlashAttribute() Have been reading Spring documentation for a while but I'm a bit lost. What is the fundamental difference between those two, and how should I choose which one to use?
Now provide the response and nothing else.
|
Here is the difference : addFlashAttribute() actually stores the attributes in a flashmap (which is internally maintained in the users session and removedonce the next redirected request gets fulfilled) addAttribute() essentially constructs request parameters out ofyour attributes and redirects to the desired page with the requestparameters. So the advantage of addFlashAttribute() will be that you can store pretty much any object in your flash attribute (as it is not serialized into request params at all, but maintained as an object), whereas with addAttribute() since the object that you add gets transformed to a normal request param, you are pretty limited to the object types like String or primitives.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14470111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179630/']}
|
jdg_373021
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4696907
|
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 started to use zlib 1.2.5 and I do not see any routine to extract from a zip file? I read about a minizip application, part of the distribution. Is that how it is supposed to be done?
Now provide the response and nothing else.
|
Yes, it does it well. (But if ever you don't like C code, you should look at 7-zip SDK that have code in C++ and C#.) All the functions to browse and uncompress the files from a zip archive are in unzip.h All the functions to compress and add files to a zip archive are in zip.h (look at contrib\minizip\unzip.h and contrib\minizip\zip.h ) For example, decompressing:the unzOpen() functions of your zip file returns a unzFile then use unzGoToFirstFile() and unzGoToNextFile() on this unzFile to browse through all files in the archive. then you get the file info for each file with unzGetCurrentFileInfo() , namely for its size, surely you should call unzOpenCurrentFile() at some moment. and call unzReadCurrentFile() using the size from file info, retrieving the binary content of the archived file. optionally, there is an opaque structure you can provide so as to use your own i/o function, but obviously, there is a default win32 implementation for file access, so you could even not worry about that. PS: and dont forget to call unzCloseCurrentFile() .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4696907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496136/']}
|
jdg_373022
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7711978
|
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 Apache CXF 2.4.2 and when I'm returnimg some object from the database to user I want to exclude some properties (for instance, password). How I can do that without creating temporary class? Is there annotation for this?
Now provide the response and nothing else.
|
As per @tomasz-nurkiewicz comment I should use @XmlTransient annotation. But as noted in documentation By default, if @XmlAccessorType on a class is absent, and none of its super classes is annotated with @XmlAccessorType, then the following default on the class is assumed: @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) Where XmlAccessType.PUBLIC_MEMBER means that: Every public getter/setter pair and every public field will be automatically bound to XML, unless annotated by XmlTransient. Fields or getter/setter pairs that are private, protected, or defaulted to package-only access are bound to XML only when they are explicitly annotated by the appropriate JAXB annotations. So this is why @XmlTransient for private field doesn't work in example from Tomasz Nurkiewicz. There are two possible ways to fix that: 1) Add annotation to public getter: private String password;@XmlTransientpublic String getPassword() { return password;} 2) Add @XmlAccessorType to class: @XmlAccessorType(XmlAccessType.FIELD)public User { @XmlTransient private String password;} Found at: http://old.nabble.com/@XmlTransient-ignored-td7406659.html
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7711978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/352708/']}
|
jdg_373023
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
374047
|
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:
There're two versions of Gödel Completeness theorem: If $\Gamma \vDash \phi$, then $\Gamma \vdash \phi$. Any consistent set of fomulas is satisfiable. I've seen a proof of the second version which is extending a consistent set of fomulas to a maximal set of consistent fomulas with the help of Henkin constants. But I can't see how they're equivalent.
Now provide the response and nothing else.
|
Suppose any consistent set of formulae is satisfiable. Suppose $\Gamma \not\vdash \phi$. Then by definition, $\Gamma \cup \{\neg\phi\}$ is consistent. By assumption, $\Gamma \cup \{\neg\phi\}$ has a model, so not every model of $\Gamma$ is a model of $\phi$, i.e. $\Gamma \not\vDash \phi$. Suppose instead that $\Gamma \vDash \phi$ implies $\Gamma \vdash \phi$. Take any (non-empty) consistent set of sentences, say $\Sigma = \Gamma \cup \{\phi\}$. Since $\Gamma \cup \{\phi\}$ is consistent, $\Gamma \not\vdash \neg\phi$. By assumption, $\Gamma \not\vDash \neg\phi$, i.e. $\Gamma \cup \{\phi\}$ has a model. (Note, we can always write a non-empty consistent set this way, even if $\Gamma$ here is empty).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/374047', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50681/']}
|
jdg_373024
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30048
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In reading Blake Master's notes on Peter Thiel's lecture on start ups, I came across this metaphor of the technology frontier: Picture the world as being covered by ponds, lakes, and oceans. You’re in a boat, in a body of water. But it’s extremely foggy, so you don’t know how far it is to the other side. You don’t know whether you’re in a pond, a lake, or an ocean. If you’re in a pond, you might expect the crossing to take about an hour. So if you’ve been out a whole day, you’re either in a lake or an ocean. If you’ve been out for a year, you’re crossing an ocean. The longer [the] journey, the longer your expected remaining journey. It’s true that you’re getting closer to reaching the other side as time goes on. But here, time passing is also indicative that you still have quite a ways to go. My question: is there a probability distribution or statistical framework that best models this situation, especially the bolded part?
Now provide the response and nothing else.
|
The exponential distribution has the property of being "memoryless," i.e. (using your analogy) the length of your journey so far has no effect on the length of the remaining journey. If the density of distribution decays faster than that of the exponential distribution, then a longer journey will mean a shorter remaining journey; conversely, a density that decays slower than exponential (see e.g. subexponetial distributions ) will have the property you describe. Since I think the comparison with memorylessness is clearest, my first suggestion would be to look at other distributions for which the exponential distribution is a special case. That will allow you to control fairly intuitively the magnitude of this effect. The Weibull distribution with shape parameter $<1$ would be a good choice.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/30048', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/2073/']}
|
jdg_373025
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56478759
|
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 entities, Question and Alternative where Question has a OneToMany relation with Alternative and I'm trying to send a JSON with a nested document of Alternative on it via POST to Question API Platform. The API Platform returns that error below : Nested documents for "alternatives" attribute are not allowed. Use IRIs instead. Searching about it I've found some people saying that is only possible using IRIs and some other people saying that is possible to use Denormalization and Normalization contexts to solve this problem but I can't find some example or tutorial about it. TL;DR; Is there a way to send a nested relation into an entity POST on API Platform without using IRIs? UPDATE: As asked, please see below the two mappings of Question and Alternative entities. Question <?phpnamespace App\Entity;use ApiPlatform\Core\Annotation\ApiResource;use DateTimeInterface;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity(repositoryClass="App\Repository\QuestionRepository") * @ApiResource() */class Question implements CreatedAtEntityInterface, UpdatedAtEntityInterface{ /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\ManyToOne(targetEntity="App\Entity\Token", inversedBy="questions") * @ORM\JoinColumn(nullable=false) * @Assert\NotBlank() */ private $token; /** * @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="question_versions") */ private $question; /** * @ORM\OneToMany(targetEntity="App\Entity\Question", mappedBy="question") */ private $question_versions; /** * @ORM\Column(type="integer") * @Assert\NotBlank() */ private $version; /** * @ORM\Column(type="string", length=100) * @Assert\Length(max="100") * @Assert\NotBlank() * */ private $name; /** * @ORM\Column(type="integer") * @Assert\NotBlank() */ private $type; /** * @ORM\Column(type="text", length=65535) * @Assert\NotBlank() * @Assert\Length(max="65535") */ private $enunciation; /** * @ORM\Column(type="string", length=255, nullable=true) * @Assert\Length(max="255") */ private $material; /** * @ORM\Column(type="text", length=65535, nullable=true) * @Assert\Length(max="65535") */ private $tags; /** * @ORM\Column(type="boolean") * @Assert\NotNull() */ private $public; /** * @ORM\Column(type="boolean") * @Assert\NotNull() */ private $enabled; /** * @ORM\Column(type="datetime") * @Assert\DateTime() */ private $createdAt; /** * @ORM\Column(type="datetime") * @Assert\DateTime() */ private $updatedAt; /** * @ORM\OneToMany(targetEntity="App\Entity\Alternative", mappedBy="question") */ private $alternatives; /** * @ORM\OneToMany(targetEntity="App\Entity\QuestionProperty", mappedBy="question") */ private $properties; /** * @ORM\OneToMany(targetEntity="App\Entity\QuestionAbility", mappedBy="question") */ private $abilities; /** * @ORM\OneToMany(targetEntity="QuestionCompetency", mappedBy="question") */ private $competencies;} Alternative <?phpnamespace App\Entity;use ApiPlatform\Core\Annotation\ApiResource;use DateTimeInterface;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity(repositoryClass="App\Repository\AlternativeRepository") * @ORM\Table(name="alternatives") * @ApiResource() */class Alternative implements CreatedAtEntityInterface, UpdatedAtEntityInterface{ /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="alternatives") * @ORM\JoinColumn(nullable=false) * @Assert\NotBlank() */ private $question; /** * @ORM\Column(type="text", length=65535) * @Assert\NotBlank() * @Assert\Length(max="65535") */ private $enunciation; /** * @ORM\Column(type="datetime") * @Assert\DateTime() */ private $createdAt; /** * @ORM\Column(type="datetime") * @Assert\DateTime() */ private $updatedAt; /** * @ORM\OneToMany(targetEntity="App\Entity\AlternativeProperty", mappedBy="alternatives") */ private $properties;}
Now provide the response and nothing else.
|
you can try implement Denormalization Question: <?phpnamespace App\Entity;use ApiPlatform\Core\Annotation\ApiResource;use DateTimeInterface;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity(repositoryClass="App\Repository\QuestionRepository") * @ApiResource( * denormalizationContext={"groups"={"post"}} * ) */class Question implements CreatedAtEntityInterface, UpdatedAtEntityInterface{ /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\ManyToOne(targetEntity="App\Entity\Token", inversedBy="questions") * @ORM\JoinColumn(nullable=false) * @Assert\NotBlank() * @Groups({"post"}) */ private $token; /** * @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="question_versions") * @Groups({"post"}) */ private $question; /** * @ORM\OneToMany(targetEntity="App\Entity\Question", mappedBy="question") * @Groups({"post"}) */ private $question_versions; /** * @ORM\Column(type="integer") * @Assert\NotBlank() * @Groups({"post"}) */ private $version; /** * @ORM\Column(type="string", length=100) * @Assert\Length(max="100") * @Assert\NotBlank() * @Groups({"post"}) */ private $name; /** * @ORM\Column(type="integer") * @Assert\NotBlank() * @Groups({"post"}) */ private $type; /** * @ORM\Column(type="text", length=65535) * @Assert\NotBlank() * @Assert\Length(max="65535") * @Groups({"post"}) */ private $enunciation; /** * @ORM\Column(type="string", length=255, nullable=true) * @Assert\Length(max="255") * @Groups({"post"}) */ private $material; /** * @ORM\Column(type="text", length=65535, nullable=true) * @Assert\Length(max="65535") * @Groups({"post"}) */ private $tags; /** * @ORM\Column(type="boolean") * @Assert\NotNull() * @Groups({"post"}) */ private $public; /** * @ORM\Column(type="boolean") * @Assert\NotNull() * @Groups({"post"}) */ private $enabled; /** * @ORM\Column(type="datetime") * @Assert\DateTime() * @Groups({"post"}) */ private $createdAt; /** * @ORM\Column(type="datetime") * @Assert\DateTime() * @Groups({"post"}) */ private $updatedAt; /** * @ORM\OneToMany(targetEntity="App\Entity\Alternative", mappedBy="question") * @Groups({"post"}) */ private $alternatives; /** * @ORM\OneToMany(targetEntity="App\Entity\QuestionProperty", mappedBy="question") * @Groups({"post"}) */ private $properties; /** * @ORM\OneToMany(targetEntity="App\Entity\QuestionAbility", mappedBy="question") * @Groups({"post"}) */ private $abilities; /** * @ORM\OneToMany(targetEntity="QuestionCompetency", mappedBy="question") * @Groups({"post"}) */ private $competencies;} Alternative: <?phpnamespace App\Entity;use ApiPlatform\Core\Annotation\ApiResource;use DateTimeInterface;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity(repositoryClass="App\Repository\AlternativeRepository") * @ORM\Table(name="alternatives") * @ApiResource() */class Alternative implements CreatedAtEntityInterface, UpdatedAtEntityInterface{ /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="alternatives") * @ORM\JoinColumn(nullable=false) * @Assert\NotBlank() * @Groups({"post"}) */ private $question; /** * @ORM\Column(type="text", length=65535) * @Assert\NotBlank() * @Assert\Length(max="65535") * @Groups({"post"}) */ private $enunciation; /** * @ORM\Column(type="datetime") * @Assert\DateTime() * @Groups({"post"}) */ private $createdAt; /** * @ORM\Column(type="datetime") * @Assert\DateTime() * @Groups({"post"}) */ private $updatedAt; /** * @ORM\OneToMany(targetEntity="App\Entity\AlternativeProperty", mappedBy="alternatives") * @Groups({"post"}) */ private $properties;} Now you can this send JSON to POST/PUT without IRI: { "token": "/api/tokens/1", "question": "string", "version": "string", "name": "string", "type": 0, "enunciation": "string", "public": true, "enabled": true, "alternatives": [ { "enunciation": "String", "createdAt": "2018-01-01 11:11:11", "updatedAt": "2018-01-01 11:11:11" } ]}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56478759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10210549/']}
|
jdg_373026
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
711618
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need a collection that can lookup a value based on the key and vice versa. For every value there is one key and for every key there is one value. Is there a ready to use data structure out there that does this?
Now provide the response and nothing else.
|
The BiMap from Google Guava looks like it will suit you. A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values. Or the BidiMap from Apache Commons Collections : Defines a map that allows bidirectional lookup between key and values. This extended Map represents a mapping where a key may lookup a value and a value may lookup a key with equal ease. This interface extends Map and so may be used anywhere a map is required. The interface provides an inverse map view, enabling full access to both directions of the BidiMap .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/711618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21410/']}
|
jdg_373027
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
407383
|
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 book Lectures on modular forms , one finds the statement at page 8 that If $(a,b,c)=1$ then there is $n\in \mathbb Z$ such that $(a,b+nc)=1$. I know that, if $(a,b)=1$, then we can take $n=0$. But, if $(a,b)\not=1$, then what could we do? Further, I tried to look at the linear combinations of $a, b, c$ which are $=1$, but to no avail have I discovered anything. The main difficulty I encountered is that the coefficient of $b$ might not be $1$. Any hint is well-appreciated. Thanks in advance.
Now provide the response and nothing else.
|
Let $\rm n$ be the product of all primes that divide $\rm a$ but not $\rm b$. Assume $\rm p\mid a,b+nc$ with $\rm p$ prime. Suppose $\rm p\mid b$. Then $\rm p$ cannot divide $\rm c$ (since $\rm p\mid a,b,c\implies p\mid(a,b,c)$) nor does it divide $\rm n$, by definition, but $\rm p\mid b\implies\rm p\mid (b+nc)-b=nc\implies p\mid n$ or $\rm p\mid c$, impossible. Suppose $\rm p\nmid b$. But then $\rm p\mid a,p\nmid b\implies p\mid n\implies\rm p\mid (b+nc)-nc=b$, impossible. Therefore the gcd $\rm(a,b+nc)$ is $1$ as it is not divisible by any prime $\rm p$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/407383', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6792/']}
|
jdg_373028
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12355212
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have the string rgba(111,222,333,0.5) how can i extract the individual colours from the string, i.e. red => 111green => 222blue => 333opacity => 0.5 I would like to be able to use a neat clean solution for this so I am assuming a regular expression would be best?
Now provide the response and nothing else.
|
I'd avoid regex for a predictable string, and suggest: // assigning the rgb() colour to a variable:var colorString = "rgba(111,222,333,0.5)", // using String.prototype.substring() to retrieve // the substring between the indices of the opening // and closing parentheses: colorsOnly = colorString.substring( // here we find the index of the opening // parenthesis, and add 1 to that index // so that the substring starts after that // parenthesis: colorString.indexOf('(') + 1, // and terminating the substring at the // index of the closing parenthesis: colorString.lastIndexOf(')') // here we split that substring on occurrence // of a comma followed by zero or more white- // space characters: ).split(/,\s*/), // String.prototype.split() returns an Array, // here we assign those Array-elements to the // various colour-, or opacity-, variables: red = colorsOnly[0], green = colorsOnly[1], blue = colorsOnly[2], opacity = colorsOnly[3]; JS Fiddle demo . Or, given that you want an object returned: var colorString = "rgba(111,222,333,0.5)", colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/), // here we initialise an empty Object: components = {};// here we assign the Array-elements to the// named properties of that Object:components.red = colorsOnly[0];components.green = colorsOnly[1];components.blue = colorsOnly[2];components.opacity = colorsOnly[3];console.log(colorsOnly, components); JS Fiddle demo . Edited to use more contemporary JavaScript: const colorString = "rgba(111,222,333,0.5)", // here we use destructuring assignment to assign the returned Array-elements // - in respective order - to the named variables: [red, green, blue, opacity] = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/), // passing the variables into the Object Literal; in this instance // we're passing in the variables which are the literal name of the // properties they define and which also contain the relevant value: colorObject = { red, green, blue, opacity };console.log(red, green, blue, opacity, colorObject); References: Array.prototype.indexOf() . Destructuring assignment . String.prototype.split() . String.prototype.substring() .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12355212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/729789/']}
|
jdg_373029
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6768474
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Newer versions of Android ( > 2.2) include the v8 javascript engine, while older versions only had JSC. However, according to http://blogs.nitobi.com/joe/2011/01/14/android-your-js-engine-is-not-always-v8/ , which javascript engine is used at runtime seems to depend on an environment variable present at build-time ( JS_ENGINE ), as well as the hardware specs of the device: # The default / alternative engine depends on the device class.# On devices with a lot of memory (e.g. Passion/Sholes), the# default is V8. On everything else, the only choice is JSC. My question is this: is there any way that I can determine which javascript engine is in use from within a webpage, an embedded WebView, or an application? If the answer is no, does anybody know which JS engine is used by the Android emulator? The reason I'm asking this is because of this issue: http://code.google.com/p/android/issues/detail?id=12987 Basically, it may be that the javascript-to-java bridge in JSC is broken on Android 2.3.X, and this impacts the application I'm trying to write. I'm seeing a segfault from somewhere deep in the JNI on my emulator, but not on the handful of physical devices I've tested. I'm trying to determine if this is an emulator-only thing, a JSC-only thing, or something different altogether.
Now provide the response and nothing else.
|
I think the better question is: Why do you care? You're basically falling into the "browser detection" trap that a lot of people fell into in the late 90's / early 00's. Since then, though, we've learned that it's feature detection that's the more useful approach, not least because the features supported in a given browser were (mostly) a moving target. There's code now, running on IE9 with its dramatically-improved DOM and JavaScript support, that's not using those features because it's doing browser detection and falling back on IE6 techniques. So rather than worrying about V8 vs. JSC, just worry about the features you want. I don't know anything about JSC, but for instance let's assume it doesn't have the forEach method on arrays that V8 has (part of the ECMAScript 5th edition standard). Rather than throwing a big "V8 vs. JSC" lever, you'd do: if (typeof Array.prototype.forEach === "function") { // Code that expects `forEach`}else { // Code that falls back} (Your "code that falls back" might add forEach to the prototype, or maybe this test is in your own iterator function and you want to know whether to defer to a native implementation or supply your own.) And similarly for other features you want to use that may or may not be present. But if you really need to detect V8 vs. JSC (and from your comment it seems you may), this page seems to demonstrate a means of doing so, though it seems awfully fragile. Here's my slightly-edited version (not least to replace window.devicePixelRatio with the test for WebkitAppearance — the former gives false positives on at least some other browsers [Firefox, for instance, which uses Gecko, not WebKit]): var v8string = 'function%20javaEnabled%28%29%20%7B%20%5Bnative%20code%5D%20%7D';if ('WebkitAppearance' in document.documentElement.style) { //If (probably) WebKit browser if (escape(navigator.javaEnabled.toString()) === v8string) { console.log('V8 detected'); } else { console.log('JSC detected'); }} else { console.log("Not a WebKit browser");} Works for me detecting the difference between Chrome (which also uses V8) and Safari (which also uses JSC).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6768474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758244/']}
|
jdg_373030
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53304
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The answer to What is the probability P(X > Y) given X ~ Be(a1, b1), and Y ~ Be(a2, b2), and X and Y are independent? provides an analytical solution for this, but is there a less computationally intensive expression if one is willing to lose some precision? Assume integer a and b, if that helps.
Now provide the response and nothing else.
|
Use this close-form approximation approximation. The author claim it is 2 orders of magnitude faster to evaluate. To abide by CV rules I will be citing key infosfrom the intro of this very clear paper: The key idea is that: The key idea in that paper is that $$P(X_B>Y_B)\approx P(X_N>Y_N)$$ where $X_B$ and $Y_B$ are independent beta random variables and $X_N$ and $Y_N$ are their normal approximations formed by moment matching.The author shows that these approximations are rather accurate, evenfor small values of $(a_1,b_1)$ and $(a_2,b_2)$ . For example: whenthese parameters take integer values between 1 and 10 inclusive, theaverage absolute error is 0.006676. Edit:updated link.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/53304', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/20598/']}
|
jdg_373031
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6409167
|
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 quite new to SF2 and I was wondering how I could manage connections to severals databases into ONE bundle.For the moment I have this solution - which works fine - but I don't know if it is the right way to do it.... in myBundle\Ressource\config\config.yml : doctrine:dbal: default_connection: default connections: default: dbname: SERVER user: root password: null host: localhost client: dbname: CLIENT_134 user: root password: null host: localhostorm: default_entity_manager: default entity_managers: default: connection: default mappings: MyBundle: ~ client: connection: client mappings: MyBundle: ~ And then, in order to switch to one of the BD or the other, I do : $O_ressource= $this->get('doctrine')->getEntityManager('client');$O_ressource= $this->get('doctrine')->getEntityManager('default'); So guys, do you think it is a good way to manage this? And my second question is : how to set up dynamic database connection?I mean I have 100 databases in my system and I can't set all them in my config.yml file.So I would like to be able to change database on the fly. Thanks for the help!
Now provide the response and nothing else.
|
If you use ConnectionFactory , your event subscribers attached to the connection will stop working, for example stofDoctrineExtensions. Here is my method. I have as with ConnectionFactory have empty connection and EntityManager. While working I just replace connection configuration by Reflections. Works on SF 2.0.10 ;) class YourService extends ContainerAware{ public function switchDatabase($dbName, $dbUser, $dbPass) { $connection = $this->container->get(sprintf('doctrine.dbal.%s_connection', 'dynamic_conn')); $connection->close(); $refConn = new \ReflectionObject($connection); $refParams = $refConn->getProperty('_params'); $refParams->setAccessible('public'); //we have to change it for a moment $params = $refParams->getValue($connection); $params['dbname'] = $dbName; $params['user'] = $dbUser; $params['password'] = $dbPass; $refParams->setAccessible('private'); $refParams->setValue($connection, $params); $this->container->get('doctrine')->resetEntityManager('dynamic_manager'); // for sure (unless you like broken transactions) }} UPDATE : More elegant solution for doctrine 2.2 / sf 2.3 (without relection), created for php5.4 (I love new array initializer :D)We can use doctrine feature called connection wrapper, see http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/portability.html This example use session service for temporary storing connection details. At first we have to create special connection wrapper: namespace w3des\DoctrineBundle\Connection;use Doctrine\DBAL\Connection;use Symfony\Component\HttpFoundation\Session\Session;use Doctrine\Common\EventManager;use Doctrine\DBAL\Events;use Doctrine\DBAL\Event\ConnectionEventArgs;/* * @author Dawid zulus Pakula [zulus@w3des.net] */class ConnectionWrapper extends Connection{const SESSION_ACTIVE_DYNAMIC_CONN = 'active_dynamic_conn';/** * @var Session */private $session;/** * @var bool */private $_isConnected = false;/** * @param Session $sess */public function setSession(Session $sess){ $this->session = $sess;}public function forceSwitch($dbName, $dbUser, $dbPassword){ if ($this->session->has(self::SESSION_ACTIVE_DYNAMIC_CONN)) { $current = $this->session->get(self::SESSION_ACTIVE_DYNAMIC_CONN); if ($current[0] === $dbName) { return; } } $this->session->set(self::SESSION_ACTIVE_DYNAMIC_CONN, [ $dbName, $dbUser, $dbPass ]); if ($this->isConnected()) { $this->close(); }}/** * {@inheritDoc} */public function connect(){ if (! $this->session->has(self::SESSION_ACTIVE_DYNAMIC_CONN)) { throw new \InvalidArgumentException('You have to inject into valid context first'); } if ($this->isConnected()) { return true; } $driverOptions = isset($params['driverOptions']) ? $params['driverOptions'] : array(); $params = $this->getParams(); $realParams = $this->session->get(self::SESSION_ACTIVE_DYNAMIC_CONN); $params['dbname'] = $realParams[0]; $params['user'] = $realParams[1]; $params['password'] = $realParams[2]; $this->_conn = $this->_driver->connect($params, $params['user'], $params['password'], $driverOptions); if ($this->_eventManager->hasListeners(Events::postConnect)) { $eventArgs = new ConnectionEventArgs($this); $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs); } $this->_isConnected = true; return true;}/** * {@inheritDoc} */public function isConnected(){ return $this->_isConnected;}/** * {@inheritDoc} */public function close(){ if ($this->isConnected()) { parent::close(); $this->_isConnected = false; }}} Next register it in your doctrine configuration: …connections: dynamic: driver: %database_driver% host: %database_host% port: %database_port% dbname: 'empty_database' charset: UTF8 wrapper_class: 'w3des\DoctrineBundle\Connection\ConnectionWrapper' And our ConnectionWrapper is properly registered. Now session injection. First create special CompilerPass class: namespace w3des\DoctrineBundle\DependencyInjection\CompilerPass;use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;use Symfony\Component\DependencyInjection\ContainerBuilder;use Symfony\Component\DependencyInjection\Definition;use Symfony\Component\DependencyInjection\Reference;class ConnectionCompilerPass implements CompilerPassInterface{/** * {@inheritDoc} */public function process(ContainerBuilder $container){ $connection = $container ->getDefinition('doctrine.dbal.dynamic_connection') ->addMethodCall('setSession', [ new Reference('session') ]);}} And we record our new compiler class in *Bundle class: public function build(ContainerBuilder $container){ parent::build($container); $container->addCompilerPass(new ConnectionCompilerPass());} And that its all! Connection will be created on demand, based on session properties. To switch database, just use: $this->get('doctrine.dbal.dynamic_connection')->forceSwitch($dbname, $dbuser, $dbpass); Advantages No more reflection Creation on demand Elegant and powerfull Disadvantages You have to manualy cleanup your entity manager, or create special doctrine event for this Much more code
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6409167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/806346/']}
|
jdg_373032
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6983892
|
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 downloaded WinHugs 2 hours ago and still can't figure out how to declare simple things. I'm trying to follow the book "7 languages in 7 weeks", but stuff like let x = 10 and double x = x * 2 gives syntax errors.
Now provide the response and nothing else.
|
I'm not 100% sure what you're trying to do that doesn't work. You can't declare bindings in a WinHugs session, you can only evaluate full expressions. So you could do things like let x = 10 in x * x + x , but you can't say let x = 10 in an interactive session. In other words, you can't make the declaration 'stick'. To get around this, either put your declarations in a .hs file and load it in WinHugs, or use GHCi instead (this is the better option, in my opinion - WinHugs is pretty dated). You can install GHCi by downloading Haskell Platform .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6983892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/723107/']}
|
jdg_373033
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
139910
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
It seems that usually smooth structures on compact 4-manifolds are distinguished by Seiberg-Witten/Donaldson invariants. And I don't know another direct way to do that. But in the case when $b_2^+$ is even the invariants vanish identically. Does there exist an example of smooth compact exotic 4-manifold with $b_2^+$ even?
Now provide the response and nothing else.
|
An often-overlooked invariant of a closed oriented 4-manifold $X$ is the closed oriented 4-manifold $\overline{X}$: the orientation-reversed manifold. Taking the Seiberg-Witten invariants of $\overline{X}$, one can distinguish smooth structures on manifolds $X$ with $b^->0$ odd, regardless of the parity of $b^+$. For instance, $\mathbb{C}P^2\# \overline{K3}$ has $b^+ = 20$ and infinitely many smooth structures (perform knot surgery on a K3 surface, blow up once, reverse orientation). The real problem, then, is to understand what happens when both $b^+$ and $b^-$ are even. I think one can distinguish infinitely many smooth structures on the connected sum of two K3 surfaces (so $b^+=6$, $b^-=38$) along the lines Tom Leness suggests in his answer. The non-equivariant Bauer-Furuta invariant of a $\mathrm{Spin}^c$-structure $\mathfrak{s}$ on a closed oriented 4-manifold $X$ is a stable map $S^{(c_1(\mathfrak{s})^2−σ)/4}\to S^{b^+}$. When $X$ is a homotopy K3 surface, and $c_1(\mathfrak{s})^2=0$, we get the stable homotopy class of a map $S^4\to S^3$; this lives in $\mathbb{Z}/2$, and is actually in this case the mod 2 Seiberg-Witten invariant (I'm going on memory here, so this is a point to check). By Bauer's theorem, the invariant for a connected sum is the smash product of the invariants of the summands. Now, the smash-square of the Hopf map is the generator for $π^s_2(S^0)=\mathbb{Z}/2$. Hence, if $X_1$ and $X_2$ are homotopy K3's, and $s(X_i)$ is the number of $\mathrm{Spin}^c$-structures with $c_1(\mathfrak{s})^2=0$ and odd SW invariant, the product $s(X_1)s(X_2)$ is an invariant of $X_1\#X_2$. Via Fintushel-Stern knot surgery along on K3 along knots with suitable Alexander polynomials, one can make $s(X_i)$ arbitrarily large, and thereby distinguish infinitely many smooth structures on $K3 \# K3$. As so often in this subject, one has the feeling that information is being lost: maybe $X_1\#X_2$ actually knows $X_1$ and $X_2$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/139910', 'https://mathoverflow.net', 'https://mathoverflow.net/users/38637/']}
|
jdg_373034
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7760286
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Alright with the way below it is extracting only referring url like this the extraction code : foreach (HtmlNode link in hdDoc.DocumentNode.SelectNodes("//a[@href]")){ lsLinks.Add(link.Attributes["href"].Value.ToString());} The url code <a href="Login.aspx">Login</a> The extracted url Login.aspx But i want to get real link what browser parsed like http://www.monstermmorpg.com/Login.aspx I can do it with checking the url whether containing http and if not add the domain value but it may cause some problems at some occasions and i think not a very wise solution. c# 4.0 , HtmlAgilityPack.1.4.0
Now provide the response and nothing else.
|
Assuming you have the original url, you can combine the parsed url something like this: // The address of the page you crawledvar baseUrl = new Uri("http://example.com/path/to-page/here.aspx");// root relativevar url = new Uri(baseUrl, "/Login.aspx");Console.WriteLine (url.AbsoluteUri); // prints 'http://example.com/Logon.aspx'// relativeurl = new Uri(baseUrl, "../foo.aspx?q=1");Console.WriteLine (url.AbsoluteUri); // prints 'http://example.com/path/foo.aspx?q=1'// absoluteurl = new Uri(baseUrl, "http://stackoverflow.com/questions/7760286/");Console.WriteLine (url.AbsoluteUri); // prints 'http://stackoverflow.com/questions/7760286/'// other...url = new Uri(baseUrl, "javascript:void(0)");Console.WriteLine (url.AbsoluteUri); // prints 'javascript:void(0)' Note the use of AbsoluteUri and not relying on ToString() because ToString decodes the URL (to make it more "human-readable"), which is not typically what you want.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7760286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/310370/']}
|
jdg_373035
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37227425
|
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 checked a bunch of answers here but i still ran into troubles. I have dozens of table and matrix to assign so I want to achieve it in a automated fashion. But I got error when I ran this code. a <- paste("wiot_table_",substr(as.character(year),3,4),sep="")assign(a,read.csv("/Users/Dreamland/Desktop/Replication_JEP/WIOD\ database\ 1995-2011/2009/wiot2009.csv",header=F, colClass=c(rep("character",2),rep("num.with.commas",1641))))mat <- paste("matrix_",substr(as.character(year),3,4),sep="")eval(parse(paste(mat,"<-as.matrix(",a,"[1:1400,3:1402])",sep=""))) error is In file(filename, "r") : cannot open file 'matrix_09<-as.matrix(wiot_table_09[1:1400,3:1402])': No such file or directory I 've check the paste(mat,"<-as.matrix(",a,"[1:1400,3:1402])",sep="") and wiot_table_09 and they both have the value as I've expected, which is "matrix_09<-as.matrix(wiot_table_09[1:1400,3:1402])" and a dataframe respectively. Due to the complexity of my work, I couldn't use assign here anymore. Any ideas here? Thanks a lot.
Now provide the response and nothing else.
|
Random.int is a primitive generator that gives you a single random int. You need a generator that gives you exactly two random integers. Random number generators can be built up from more primitive generators to create more complex generators. Fortunately, Elm has just such a function, Random.pair which lets you specify which two generators you want for each part of the tuple. Let's pull the die generator into its own function to avoid repeating ourselves: dieGenerator : Random.Generator IntdieGenerator = Random.int 1 6 Now we can build another generator that gives us the random value of a pair of die: diePairGenerator : Random.Generator (Int, Int)diePairGenerator = Random.pair dieGenerator dieGenerator Since we're dealing with a tuple of ints, let's update your Msg definition of NewFace Int Int to NewFaces (Int, Int) . That will allow your Roll handler to be nice and clean: Roll -> (model, Random.generate NewFaces diePairGenerator) If you want to try moving beyond this, think about what it would take to allow for any number of die to be rolled. Take this idea of building complex generators from more primitive generators and use the documentation for the Random module us a guide.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37227425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5316867/']}
|
jdg_373036
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2260446
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Dictionary<string,double> myDict = new Dictionary();//...foreach (KeyValuePair<string,double> kvp in myDict) { kvp.Value = Math.Round(kvp.Value, 3);} I get an error:"Property or indexer 'System.Collections.Generic.KeyValuePair.Value' cannot be assigned to -- it is read only." How can I iterate through myDict and change values?
Now provide the response and nothing else.
|
According to MSDN : The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it. Use this: var dictionary = new Dictionary<string, double>();// TODO Populate your dictionary herevar keys = new List<string>(dictionary.Keys);foreach (string key in keys){ dictionary[key] = Math.Round(dictionary[key], 3);}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2260446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187644/']}
|
jdg_373037
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17439629
|
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 return a randomized result of a filter query to give all my documents a fair chance of being on the first page results. In an effort to not confuse users during repeated searches (and to easily support pagination) the results should stay consistent for the current day. To do this I have developed the following script sort query. It combines the document id (a guid, so already fairly random) with a daily salt (just the day of year and current year combined) and hashes the result to produce what I would expect to be a fairly random string, that only changes as the 'daily salt' changes each day (ignore the extraneous elements in this specific query, it's generated from code). { "from": 0, "size": 20, "sort": { "_script": { "order": "asc", "type": "string", "script": "org.elasticsearch.common.Digest.md5Hex(dailySalt + doc['id'].value)", "params": { "dailySalt": "184-2013" } } }, "query": { "filtered": { "query": { "match_all": {} }, "filter": { "bool": { "must": [ { "term": { "tag_id": "Some Tag" } }, { "match_all": {} } ] } } } }, "fields": [ "id" ]} Inspired from this similar question and answer It works, but not very well. I get slightly different results as I increment the daily salt, but the same documents keep appearing around the top results. They move slightly, but there's definitely a consistent pattern. I've tried to change the hash function to another I found: org.elasticsearch.cluster.routing.operation.hash.djb.DjbHashFunction.DJB_HASH but it gives very similar results of common top results. I'm no cryptography expert so I presume this is a behavior of common hash functions and there must be some special hash functions to use for more randomized results based on similar inputs? Is anyone familiar with one available in ElasticSearch? I'm using Searchbox.io (cloud hosted elastic search service) so installing my own custom function is not an option. Or am I approaching this problem from a completely wrong angle? Edit I just looked at the resultant sort keys produced by the script, and it appears that the script is only being applied to the first page of results, and then sorting that first page (rather than applying to the full result set and therefor changing the documents within the first page). Here's my first page results (edited for brevity). But you can see on the first page alone that the sort key varies from 0c*** to fa***, for the first 0 - 20 docs, with a total of ~200 docs. Using 'dailySalt' = 185-2013 {"took": 2,"timed_out": false,"_shards": { "total": 1, "successful": 1, "failed": 0},"hits": { "total": 196, "max_score": null, "hits": [{ "fields": { "id": "27662ef8-d2a7-4fde-80f6-1571b83c4cde" }, "sort": ["0cbf8b4e7927f0a53a5b82f2630ff9ad"] }, { "fields": { "id": "d9b11797-053f-495e-a676-0ec959dba879" }, "sort": ["0fa8730a5239f8a3d1286cbe16619bfa"] }, { "fields": { "id": "482c893f-1083-4860-892e-1b25cf442199" }, "sort": ["295edd71cc48ac41c5e2f91315abf5ce"] }, { "fields": { "id": "581fd0f1-9ecb-4e5c-920b-06413bfbf4f7" }, "sort": ["4b9f0d17bc2333d13a1963b4f6afb829"] }, { "fields": { "id": "de3dddb8-e296-4446-ac4c-135cc925669d" }, "sort": ["4c5d0bcb50f5b600e539ba46b33b1007"] }, { "fields": { "id": "c83ad22e-80b4-40f1-8e56-2153a1a1f9e8" }, "sort": ["55efe0a692ab3205405f1c74732b8205"] }, { "fields": { "id": "7bd19829-4f37-4e02-9fd1-0239b8ae8db4" }, "sort": ["5adcd22c7c507244d7ba382812accdf3"] }, { "fields": { "id": "42fcec43-851f-4133-a8db-1d2bf0b86ec8" }, "sort": ["6757f46bd554e3353a2ebf35c6b3d24c"] }, { "fields": { "id": "e119132b-4e93-4047-8513-1ce2452f0cdd" }, "sort": ["6dbcb59a2b5e91523896d57695251b29"] }, { "fields": { "id": "7d0acf5d-7c14-45a2-97b7-17939ff512f4" }, "sort": ["9d99752ec0802e55dcfb3c83bcd2e4bb"] }, { "fields": { "id": "2cdc21e4-3312-460b-9a18-094e4f95a56c" }, "sort": ["9dc43d1d39e64cfe04c6d7b8f565faaa"] }, { "fields": { "id": "0f665cb3-5648-416c-b08f-146d2a019319" }, "sort": ["b61bb718fe63a287b6fcdc8bcd638604"] }, { "fields": { "id": "1e852d49-2b3b-4d7a-9f1b-1495b94e723e" }, "sort": ["ba7ad8a3a6e195a6bc28e341f9d6965b"] }, { "fields": { "id": "ca2a5922-bb42-4317-b61c-129925436a1f" }, "sort": ["bca0411cf8d67b4dcd5b205a5010367f"] }, { "fields": { "id": "b1dac760-7d73-4b60-bd6d-08ea9453e68c" }, "sort": ["be3714cfb2517e98d525aaea6e40cfa5"] }, { "fields": { "id": "c4b08def-59db-4ac0-b16f-0c3fae4c01f2" }, "sort": ["c4220b31c305d536c7a7d1639da32c66"] }, { "fields": { "id": "cc7ac1fd-3e88-4503-a837-2000ebb6e2d9" }, "sort": ["ceb5710fe2418fe3b353bf7b1f737570"] }, { "fields": { "id": "5a5f90c9-b44f-4ca2-9d16-117c8e9fd388" }, "sort": ["dc5fea76598633cb08c1459983ebca62"] }, { "fields": { "id": "6d811d5b-4138-4a41-a186-1b9aa2b65623" }, "sort": ["ea3c55ac123ac9e819b145402407d1de"] }, { "fields": { "id": "b489d2da-b4a1-44de-acde-219109edd42f" }, "sort": ["fab53cc11983b45b081d4b01df555c59"] }]}}
Now provide the response and nothing else.
|
You need to set hideUserNotFoundExceptions property of AbstractUserDetailsAuthenticationProvider to false. (This means this solution is dependent on the Spring Security code which might change in the future). Here are the steps: (1) Define a DaoAuthenticationProvider bean (if you already have one then set its hideUserNotFoundExceptions property to false). Here is Java config style: @Beanpublic AuthenticationProvider daoAuthenticationProvider() { DaoAuthenticationProvider impl = new DaoAuthenticationProvider(); impl.setUserDetailsService(yourUserDetailsService()); impl.setHideUserNotFoundExceptions(false) ; return impl ;} (2) Configure authentication manager with above provider: <authentication-manager alias="authenticationManager"> <authentication-provider ref="daoAuthenticationProvider"/><!-- other providers if any --></authentication-manager> (3) Create an exception extending the UsernameNotFoundException : public class DisabledException extends UsernameNotFoundException { public DisabledException(String msg) { super(msg); } /* other constructors */ } (4) In your UserDetailsService, throw the above exception with any message key you like: throw new DisabledException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled")); Here messages is SpringSecurityMessageSource.getAccessor()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17439629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/505457/']}
|
jdg_373038
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9949633
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ok.. So probably an example is a good way to explain this problem So I have something like this: if __name__=="__main__" result = foobar() sys.stdout.write(str(result)) sys.stdout.flush() sys.exit(0) Now this script is being called from a ruby script.. and basically it parses the result there.But foobar() has a lot of print statments.. and stdout flushes all those prints as well.Is there a way (besides logging mathods) I can modify something over here which automatically suppresses those prints and just flushes this result??Thanks
Now provide the response and nothing else.
|
You want to shadow (or otherwise hide) the stdout temporarily. Something like this: actualstdout = sys.stdoutsys.stdout = StringIO()result = foobar()sys.stdout = actualstdoutsys.stdout.write(str(result))sys.stdout.flush()sys.exit(0) You need to assign something that is file-like to sys.stdout so that other methods can use it effectively. StringIO is a good candidate because it doesn't require disk access (it'll just collect in memory) and then is discarded.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9949633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/902885/']}
|
jdg_373039
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
217897
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $X$ is a discrete and $Y$ is a continuous random variable then what can we say about the distribution of $X+Y$? Is it continuous or is it mixed? What about the product $XY$?
Now provide the response and nothing else.
|
Suppose $X$ assumes values $k \in K$ with discrete distribution $(p_k)_{k \in K}$, where $K$ is a countable set, and $Y$ assumes values in $\mathbb R$ with density $f_Y$ and CDF $F_Y$. Let $Z = X + Y$. We have$$ \mathbb P( Z \leq z) = \mathbb P(X + Y \leq z) = \sum_{k \in K} \mathbb P(Y \leq z - X \mid X = k) \mathbb P(X = k) = \sum_{k \in K} F_Y(z-k) p_k,$$ which can be differentiated to obtain a density function for $Z$ given by $$ f_Z(z) = \sum_{k \in K} f_Y(z-k) p_k.$$ Now let $R = X Y$ and assume $p_0 = 0$. Then$$ \mathbb P(R \leq r) = \mathbb P(X Y \leq r) = \sum_{k \in K} \mathbb P(Y \leq r/X) \mathbb P(X= k) = \sum_{k \in K} F_Y(r/k) p_k,$$which again can be differentiated to obtain a density function. However if $p_0 > 0$, then $\mathbb P(X Y = 0) \geq \mathbb P(X = 0) = p_0 > 0$, which shows that in this case $XY$ has an atom at 0.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/217897', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/111986/']}
|
jdg_373040
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.