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
|
26308
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As my designs (and PCB designs too) become more complicated, I'm interested if there are best practices or industry standards for schematic design. I know there's a schematic checklist but I'm looking to go further with my designs. I've been following a simple design methodology based on signal inputs & outputs go left to right, with power flowing from top to bottom, which has worked well for simple schematics. Some of the questions I have thought about but can't find an answer: What's considered the maximum number of parts on a single page? What to consider when making a schematic multiple pages? When should I consider putting multiple tracks into a buss? How should I name busses, netlists, and the references to other pages? How should I place components to minimize the number of nets? What kind of comments should I include on a schematic? Where should I place the designation and value for horizontal and vertical components? Does it matter as long as I stay consistent? Should I note component packaging & rating on the schematic? Meaning discrete vs SMD or if a specific resistor is high powered? Should I customize nets in different colors or widths? How should I version control schematics? What workflow should a single person use to keep designs organized? I'm sure there's more to consider on schematic design, this is just what I've run into with my own work. I'd appreciate additional topics on schematic design too.
Now provide the response and nothing else.
|
What's considered the maximum number of parts on a single page? Depends on the size of the page. You can fit more on a D-sized plotter sheet than a B-sized (roughly A4) sheet. Don't crowd things to the point it gets difficult to read. What to consider when making a schematic multiple pages? Almost all my designs end up as multiple sheets. Sometimes the manufacturing guys cut them all up and paste them together in one big plotter sheet to make it easier to follow the signal flow. But normally I don't print out bigger than 11x17 so I work at that size. Something you didn't ask: I tend to make the first sheet be the critical input and output connections of my circuit, and work up towards more complex circuits on later pages. Other people like to put the critical signal path parts on the first page, and the input and output connections end up deep in the stack of schematics. I'm not sure which is really better. When should I consider putting multiple tracks into a buss? I rarely do this, but its a matter of style (and convention in your workgroup). How should I name busses, netlists, and the references to other pages? I tend toward all-caps net names, but otherwise I don't have fixed rules. More disciplined organizations might have more detailed rules. How should I place components to minimize the number of nets? I prefer to place components to make the signal flow clear. I don't worry about the number of named nets. What kind of comments should I include on a schematic? Anything important for the layout guy to know (matched length traces, place bypass caps near ICs, etc.) Anything a future engineer might need to know if they're looking to replace an obsolete part. Non-obvious critical specs like higher-than-normal resistor power requirements or tight tolerances. Anything that has to be tuned in production (Like "tune pot to achieve 50% duty cycle" or whatever). Where should I place the designation and value for horizontal and vertical components? Does it matter as long as I stay consistent? I use vertical text for vertical components to allow more parts to fit cleanly on a sheet. Others (apparently) consider this a grave sin. Be consistent and be consistent with others in your organization. Should I note component packaging & rating on the schematic? Meaning discrete vs SMD or if a specific resistor is high powered? Specifying the package type for each part visibly on the schematic would be clutter. But obviously that information has to be in the design to get transferred to layout. As mentioned above mention nonobvious specs that might trip someone up if they have to replace an obsolete part or find an alternate vendor due to a shortage. Your BOM (Bill of Materials) will need to specify an exact manufacturers part number (or a list of acceptable alternates called an AVL "approved vendor list") for each part. Should I customize nets in different colors or widths? I don't recommend this. I'd prefer to get schematics that make sense if printed out in black & white. How should I version control schematics? I store datecoded backups (like "mydesign_20120205.zip" on my own pc and a remote share drive. Definitely store a backup whenever you release a design (either to layout or to manufacturing). Edit : There are better ways to do this (see comments) but a simple process like dated zip files is also perfectly workable. What workflow should a single person use to keep designs organized? Keep backups. Use all the tools you have available. If you aren't doing your own layout, keep good communication with the layout guy.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/26308', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7213/']}
|
jdg_371141
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26144305
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
pip is not able to find this module, as well as me on pypi website.Could you please tell me the secret, how to install it? I need the module to spawn new shell process via subprocess.call. I have seen a lot of examples, where people use import subprocess , but no one shows how it was installed. Error, that i got (just in case i've lost my mind and does not understand what is going on): Microsoft Windows [Version 6.3.9600](c) 2013 Microsoft Corporation. All rights reserved.C:\Users\Alexander\Desktop\tests-runner>python run.pyTraceback (most recent call last): File "run.py", line 165, in <module> main() File "run.py", line 27, in main subprocess.call('py.test') File "C:\Python27\lib\subprocess.py", line 522, in call return Popen(*popenargs, **kwargs).wait() File "C:\Python27\lib\subprocess.py", line 710, in __init__ errread, errwrite) File "C:\Python27\lib\subprocess.py", line 958, in _execute_child startupinfo)WindowsError: [Error 2] The system cannot find the file specified
Now provide the response and nothing else.
|
There is no need to install this module in Python 2.7. It is a standard module that is built in. The documentation shows that it was added to the library for Python version 2.4. It's been with us for a long time now. The error that you show in your question update is nothing more prosaic than a file not found error. Likely the executable file that you are attempting to call Popen on cannot be found. That traceback indicates that subprocess is installed and has been imported. The problem is simply that the call to subprocess.call('py.test') is failing. For future reference, this is the type of traceback you encounter when attempting to import a module that has not been installed: >>> import fooTraceback (most recent call last): File "", line 1, in ImportError: No module named foo
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26144305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1391074/']}
|
jdg_371142
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14038002
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a newbie in OpenCV. I am working with the following formula to calculate distance: distance to object (mm) = focal length (mm) * real height of the object (mm) * image height (pixels) ---------------------------------------------------------------- object height (pixels) * sensor height (mm) Is there a function in OpenCV that can determine object distance? If not, any reference to sample code?
Now provide the response and nothing else.
|
How to calculate distance given an object of known size You need to know one of 2 things up front Focal-length (in mm and pixels per mm) Physical size of the image sensor (to calculate pixels per mm) I'm going to use focal-length since I don't want to google for the sensor datasheet. Calibrate the camera Use the OpenCV calibrate.py tool and the Chessboard pattern PNG provided in the source code to generate a calibration matrix. I took about 2 dozen photos of the chessboard from as many angles as I could and exported the files to my Mac. For more detail check OpenCV's camera calibration docs . Camera Calibration Matrix (iPhone 5S Rear Camera) RMS: 1.13707201375camera matrix:[[ 2.80360356e+03 0.00000000e+00 1.63679133e+03] [ 0.00000000e+00 2.80521893e+03 1.27078235e+03] [ 0.00000000e+00 0.00000000e+00 1.00000000e+00]]distortion coefficients: [ 0.03716712 0.29130959 0.00289784 -0.00262589 -1.73944359] f_x = 2803 f_y = 2805 c_x = 1637 c_y = 1271 Checking the details of the series of chessboard photos you took, you will find the native resolution (3264x2448) of the photos and in their JPEG EXIF headers , visible in iPhoto, you can find the Focal Length value (4.15mm). These items should vary depending on camera. Pixels per millimeter We need to know the pixels per millimeter (px/mm) on the image sensor. From the page on camera resectioning we know that f_x and f_y are focal-length times a scaling factor. f_x = f * m_xf_y = f * m_y Since we have two of the variables for each formula we can solve for m_x and m_y. I just averaged 2803 and 2805 to get 2804. m = 2804px / 4.15mm = 676px/mm Object size in pixels I used OpenCV (C++) to grab out the Rotated Rect of the points and determined the size of the object to be 41px. Notice I have already retrieved the corners of the object and I ask the bounding rectangle for its size. cv::RotatedRect box = cv::minAreaRect(cv::Mat(points)); Small wrinkle The object is 41px in a video shot on the camera @ 640x480. Convert px/mm in the lower resolution 3264/676 = 640/xx = 133 px/mm So given 41px/133px/mm we see that the size of the object on the image sensor is .308mm . Distance formula distance_mm = object_real_world_mm * focal-length_mm / object_image_sensor_mmdistance_mm = 70mm * 4.15mm / .308mmdistance_mm = 943mm This happens to be pretty good. I measured 910mm and with some refinements I can probably reduce the error. Feedback is appreciated. Similar triangles approach Adrian at pyimagesearch.com demonstrated a different technique using similar triangles . We discussed this topic beforehand and he took the similar triangles approach and I did camera intrinsics.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14038002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1164331/']}
|
jdg_371143
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
138674
|
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 the textbook Forecasting: principles and practice by Hyndman and Athanasopoulos, in the moving average smoothing section (Sec 6.2), the authors speak of even order moving average smoothing not being symmetric. What is the importance of symmetry in the sense that the text talks about? Why should it be desirable? Any help would be appreciated.
Now provide the response and nothing else.
|
Suppose you have an increasing trend, say $y_t=t$, i.e., $1, 2, 3, 4, ...$ and a moving window of length 4. Then at time $t$, the actual value is $y_t=t$. But the moving average is$$ \frac{1}{4}(y_{t-1}+y_t+y_{t+1}+y_{t+2}) = \frac{1}{4}(t-1+t+t+1+t+2)=t+0.5\neq t=y_t.$$So your moving average is biased upward by $0.5$. And completely needlessly so: if you use a symmetric moving window of length $5$ (from $t-2$ to $t+2$), the bias will disappear. The same happens if you have seasonal data, e.g., a sine curve. Then a moving average from a rolling window of length 4 (e.g., from $t-1$ to $t+2$) will anticipate the seasonality. It will be "ahead of its time", so to say. If you use a window from $t-2$ to $t+1$, the moving average will lag the seasonality. To be honest, the effect will likely be minor, especially for real data where the signal is obscured by noise. But it's an unnecessary ugliness, so we like to avoid it.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/138674', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/40252/']}
|
jdg_371144
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17462802
|
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 DB2 database containing millions of records.I found that some char() or varchar() fields contain special characters which shouldn't be stored.I guess application received broken data or some code made it. Anyway, I want to find records that have these broken data, which are special characters (not alphabetic). I tried to find the way using query but couldn't.Does someone know the good query or advice?
Now provide the response and nothing else.
|
You can use the DB2 TRANSLATE() function to isolate non-alphanumeric characters. Note that this will not work in the Oracle compatibility mode, because in that case DB2 will treat empty strings as NULLs, as Oracle would do. SELECT *FROM yourtableWHERE LENGTH(TRANSLATE( yourcolumn, '', -- empty string 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')) > 0 -- after translating ASCII characters to empty strings -- there's still something left
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17462802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1636342/']}
|
jdg_371145
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9499216
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a C programmer and just learning some java recently because I am developing one android application. Currently I am in a situation. Following is the one. public Class ClassA{public ClassA();public void MyMethod(){ try{ //Some code here which can throw exceptions } catch(ExceptionType1 Excp1){ //Here I want to show one alert Dialog box for the exception occured for the user. //but I am not able to show dialog in this context. So I want to propagate it //to the caller of this method. } catch(ExceptionType2 Excp2){ //Here I want to show one alert Dialog box for the exception occured for the user. //but I am not able to show dialog in this context. So I want to propagate it //to the caller of this method. } }} Now I wan to use call the method MyMethod() somewhere else in another class. If some one can provide me some code snippet how to propagate the exceptions to the caller of MyMethod() so that I can display them in a dialog box in the caller method. Sorry If I am not so much clear and weird in the way of asking this question.
Now provide the response and nothing else.
|
Just don't catch the exception in the first place, and change your method declaration so that it can propagate them: public void myMethod() throws ExceptionType1, ExceptionType2 { // Some code here which can throw exceptions} If you need to take some action and then propagate, you can rethrow it: public void myMethod() throws ExceptionType1, ExceptionType2 { try { // Some code here which can throw exceptions } catch (ExceptionType1 e) { log(e); throw e; }} Here ExceptionType2 isn't caught at all - it'll just propagate up automatically. ExceptionType1 is caught, logged, and then rethrown. It's not a good idea to have catch blocks which just rethrow an exception - unless there's some subtle reason (e.g. to prevent a more general catch block from handling it) you should normally just remove the catch block instead.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9499216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218284/']}
|
jdg_371146
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44992868
|
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 thought it would be easy to get the shareable link for a file, like file.getShareableLink() but it seems that things are not so simple. I've come across similar posts here but nothing that I can understand ( alternativeLink and Shareable link for Google Drive file ). Is there really no straightforward way to do this? I've got hundreds of images to extract a shareable link for so they can be displayed online.
Now provide the response and nothing else.
|
How about following sample script? In this sample, it retrieves shared URLs of images in a specific folder. Sample Script : function myFunction() { var folderId = "### Specific folder ID ###"; var files = DriveApp.getFolderById(folderId).getFiles(); var result = []; while (files.hasNext()) { var file = files.next(); file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); var temp = { file_name: file.getName(), url: "http://drive.google.com/uc?export=view&id=" + file.getId(), }; result.push(temp); }; Logger.log(JSON.stringify(result))} Result : [ { "file_name": "filename1", "url": "http://drive.google.com/uc?export=view&id=### file ID 1###" }, { "file_name": "filename2", "url": "http://drive.google.com/uc?export=view&id=### file ID 2###" }] Flow : Retrieve files in a folder which was set by folderId . Modify the permission of files. By this, users who don't login can also see the files. Only users who know the URLs can see them. Retrieve filename and file ID. And Retrieve file URLs using file ID. The URLs are the direct links for images. In this sample, folders in the folder cannot be checked. If you also want to check folders in the folder which was set by folderId , please tell me. If I misunderstand your question, I'm sorry.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44992868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/97855/']}
|
jdg_371147
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
249164
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Mathworld's discussion of the Gamma function has the pleasant formula: $$ \frac{\Gamma(\frac{1}{24})\Gamma(\frac{11}{24})}{\Gamma(\frac{5}{24})\Gamma(\frac{7}{24})} = \sqrt{3}\cdot \sqrt{2 + \sqrt{3}} $$ This may have been computed algorithmically, according to the page. So I ask how one might derive this? My immediate thought was to look at $(\mathbb{Z}/24\mathbb{Z})^\times= \big( \{ 1,5,7,11 \big| 13, 17, 19 , 23 \}, \times \big)$ where $1,5,7,11$ are relatively prime to 24. And the other half? We could try to use the mirror formula $$ \Gamma(z) \Gamma(1-z) = \frac{\pi}{\sin(\pi z)} $$or the Euler beta integral but nothing has come up yet:$$ \int_0^1 x^a (1-x)^b \, dx = \frac{\Gamma(a) \Gamma(b)}{\Gamma(a+b)} $$ I am lucky the period integral of some Riemann surface will be the ratio of Gamma functions:$$ \int_0^1 (x - a)^{1/12}(x - 0)^{11/12} (x - 1)^{-5/12}(x - d)^{-7/12} \, dx $$these integrals appear in the theory of hypergeometric function In light of comments, I found a paper of Benedict Gross and the paper of Selberg and Chowla $$ F( \tfrac{1}{4},\tfrac{1}{4};1;\tfrac{1}{64}) = \sqrt{\frac{2}{7\pi}} \times \left[\frac{ \Gamma(\frac{1}{7})\Gamma(\frac{2}{7})\Gamma(\frac{4}{7})}{\Gamma(\frac{3}{7})\Gamma(\frac{5}{7})\Gamma(\frac{6}{7})}\right]^{1/2} $$ so in our case we are looking at quadratic residues mod 12. However, however it does not tell us that LHS evaluates to RHS.
Now provide the response and nothing else.
|
This formula can actually be proved using only properties of the Gammafunction already known to Gauss, with no need to invoke special values ofDirichlet series. The relevant identities are$$\Gamma(z) \, \Gamma(1-z) = \frac\pi{\sin(\pi z)},$$already cited by john mangual as the "mirror formula", and the triplication formula for the Gamma function, i.e. the case$k=3$ of Gauss'smultiplication formula :$$\Gamma(z) \, \Gamma\bigl(z+\frac13\bigr) \, \Gamma\bigl(z+\frac23\bigr)= 2\pi \cdot 3^{\frac12-3z} \Gamma(3z)$$[the $k=2$ case is the more familiar duplication formula$\Gamma(z) \, \Gamma(z+\frac12) = 2^{1-2z} \sqrt{\pi}\, \Gamma(2z)$]. Take $z=1/24$ and $z=1/8$ in the triplication formula, multiply,and remove the common factors $\Gamma(1/8) \, \Gamma(3/8)$ to deduce$$\Gamma\bigl(\frac{1}{24}\bigr)\Gamma\bigl(\frac{11}{24}\bigr)\Gamma\bigl(\frac{17}{24}\bigr)\Gamma\bigl(\frac{19}{24}\bigr)= 4 \pi^2 \sqrt{3}.$$Take $z=5/24$ and $z=7/24$ in the mirror formula and multiply to deduce$$\Gamma\bigl(\frac{5}{24}\bigr)\Gamma\bigl(\frac{7}{24}\bigr)\Gamma\bigl(\frac{17}{24}\bigr)\Gamma\bigl(\frac{19}{24}\bigr)= \frac{\pi^2}{ \sin (5\pi/24) \sin (7\pi/24) }.$$Hence$$\frac{\Gamma(1/24) \, \Gamma(11/24)} {\Gamma(5/24) \, \Gamma(7/24)}= 4 \sqrt{3} \sin (5\pi/24) \sin (7\pi/24),$$which is soon reduced to the radical form $\sqrt3 \cdot \sqrt{2+\sqrt3}$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/249164', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1358/']}
|
jdg_371148
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29562471
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
First to say is that I've been searching for a solution for a while now and I'm quite desperate now. I cannot get the css file to be accessible from html page when run by Spring Boot. html.file <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head lang="en"> <title th:text='#{Title}'>AntiIntruder</title> <meta charset="UTF-8" /> <link rel="stylesheet" type="text/css" media="all" href="../assets/css/style.css" th:href="@{/css/style.css}" /> </head> <body>... Application.java @SpringBootApplication // adds @Configuration, @EnableAutoConfiguration, @ComponentScan@EnableWebMvcpublic class Application extends WebMvcConfigurerAdapter { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/*"); }} folder structure: I've tried putting the css folder into a static folder and/or removing the addResourcesHandlers, referencing to the css by relative path and some other things. Nothing seems to resolve this.Please, let me know also if you tried to solve this but did not find a solution, so that I know, that I'm not ignored.
Now provide the response and nothing else.
|
1. Using Custom Resource Path In your Web Config @Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) { if (!registry.hasMappingForPattern("/assets/**")) { registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/assets/"); }} Put your style.css file inside this folder src/main/resources/assets/css/ After that in your views <link rel="stylesheet" type="text/css" th:href="@{/assets/css/style.css}" /> . 2. Using predefined paths in spring boot Remove addResourceHandlers from your web config Put the style.css inside any of the following folders src/main/resources/META-INF/resources/assets/css src/main/resources/resources/assets/css/ src/main/resources/static/assets/css/ src/main/resources/public/assets/css/ And in the view <link rel="stylesheet" type="text/css" th:href="@{/assets/css/style.css}" /> . NOTE: You can remove the assets folder here. If you want to do it, remove it from the predefined resource folder and also from the view th:href . But i kept it as it is because, you explicitly mentioned the assets/ path in your question. So I belive it's your requirement to have assets/ in your resource URL.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29562471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3129549/']}
|
jdg_371149
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26728333
|
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 wanna print variable value without specifying its type. In c, I can do int main(int argc, char **argv) { int i = 1; float f = 0.1; char s[] = "s"; printf("%i\n", i); printf("%f\n", f); printf("%s", s); return 0;} but I expect: int main(int argc, char **argv) { int i = 1; float f = 0.1; char s[] = "s"; printf("%any_type\n", i); printf("%any_type\n", f); printf("%any_type", s); return 0;} question: is there %any_type in C?
Now provide the response and nothing else.
|
In C11 you can write a generic function to print any type and keep adding your custom type to that function. #define print_any(X) _Generic((X), int: print_int, \ default: print_unknown, \ float: print_float)(X)int print_int(int i){ return printf("%d\n", i);}int print_float(float f){ return printf("%f\n", f);}int print_unknown(...){ return printf("ERROR: Unknown type\n");} You can also automate the function generation as shown below. #define GEN_PRINT(TYPE, SPECIFIER_STR) int print_##TYPE(TYPE x) { return printf(SPECIFIER_STR "\n", x);}GEN_PRINT(int, "%d");GEN_PRINT(char, "%c");GEN_PRINT(float, "%f"); Usage will be: int main(int argc, char **argv) { int i = 1; float f = 0.1; char s[] = "s"; print_any(i); print_any(f); print_any(s); return 0;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26728333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3370849/']}
|
jdg_371150
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2337630
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given absolute or relative position (top & left) is there any way to get the nearest html element to these co-ordinates? Or alternately, is there any way to craft a selector (or use some jQuery construct) to enumerate elements and then find which is closes to the provided co-ordinates? Assume that the set of elements is small and finite.
Now provide the response and nothing else.
|
I've built a jQuery method that returns closest element to offset, within the collection: jQuery.fn.closestToOffset = function(offset) { var el = null, elOffset, x = offset.left, y = offset.top, distance, dx, dy, minDistance; this.each(function() { var $t = $(this); elOffset = $t.offset(); right = elOffset.left + $t.width(); bottom = elOffset.top + $t.height(); if ( x >= elOffset.left && x <= right && y >= elOffset.top && y <= bottom ) { el = $t; return false; } var offsets = [ [elOffset.left, elOffset.top], [right, elOffset.top], [elOffset.left, bottom], [right, bottom], ]; for (var off in offsets) { dx = offsets[off][0] - x; dy = offsets[off][1] - y; distance = Math.sqrt(dx * dx + dy * dy); if (minDistance === undefined || distance < minDistance) { minDistance = distance; el = $t; } } }); return el;}; Notes: If the offset is inside one of the elements, it will be returned. I'm looping through four offsets, because this gives the best accuracy. Use it like this: $('div.myCollection').closestToOffset({left: 5, top: 5});
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2337630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106095/']}
|
jdg_371151
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
486100
|
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:
Is the following defined: (Dirac delta function divided by Dirac delta function) $$f = \frac{\delta}{\delta} = ?$$
Now provide the response and nothing else.
|
I don't know if the following is what you are looking for, but: To give the division a sense, what you can do is look for functions $\phi \in \mathcal E^0(\mathbb R)$ (that is continuous functions $\mathbb R \to \mathbb R$ that fulfill $\phi \delta = \delta$. As for any $\psi \in \mathcal D(\mathbb R)$ we have $$(\phi \delta)(\psi) =\delta(\phi\psi) = \phi(0)\psi(0) = \phi(0)\delta(\psi), $$that is $\phi \delta = \phi(0)\delta$, so we have $$\phi \delta = \delta \iff \phi(0) = 1. $$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/486100', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71957/']}
|
jdg_371152
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19407472
|
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 restrict access to my site to allow only specific IPs and I've got the following problem: when I access www.example.com deny works perfectly, but when I try to access www.example.com/index.php it returns "Access denied" page AND php file is downloaded directly in browser without processing.I do want to deny access to all the files on the website for all IPs but mine. How should I do that? Here's the config I have: server {listen 80;server_name example.com; root /var/www/example;location / { index index.html index.php; ## Allow a static html file to be shown first try_files $uri $uri/ @handler; ## If missing pass the URI to front handler expires 30d; ## Assume all files are cachable allow my.public.ip; deny all;}location @handler { ## Common front handler rewrite / /index.php;}location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler rewrite ^(.*.php)/ $1 last;}location ~ .php$ { ## Execute PHP scripts if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss expires off; ## Do not cache dynamic content fastcgi_pass 127.0.0.1:9001; fastcgi_param HTTPS $fastcgi_https; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; ## See /etc/nginx/fastcgi_params }}
Now provide the response and nothing else.
|
How to reproduce and fix this error: Open the python interpreter, try to import xlrt, you get an error: python>>> import xlrtTraceback (most recent call last): File "<stdin>", line 1, in <module>ImportError: No module named xlrt 1. Install, or make sure pip is installed: What is the official "preferred" way to install pip and virtualenv systemwide? 2. Install xlrd pip install xlrd Protip: If you feel you have to use sudo pip install .... to get this to work then you need to stop and learn why this is dangerous. See: What are the risks of running 'sudo pip'? Workarounds are to install pip using a certain user: pip install --user myuser ... use your own best judgment here. Make sure the directory your pip is operating in is owned by the user trying to install packages there. Use: chown -R $USER /Library/Python/2.7/site-packages . 3. Test it on the python interpreter: python>>> import xlrd>>> type(xlrd)<type 'module'>>>> Now it is imported it without a problem, xlrd is a python module. Troubleshooting: If your PYTHONPATH is not defined, you should define it: PYTHONPATH=:/home/el/wherever/where_to_find_modules
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19407472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2887023/']}
|
jdg_371153
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46907881
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using keras package in R to train a deep learning model. My data set is highly imbalanced. Therefore, I want to set class_weight argument in the fit function. Here is the fit function and its arguments that I used for my model history <- model %>% fit( trainData, trainClass, epochs = 5, batch_size = 1000, class_weight = ????, validation_split = 0.2) In python I can set class_weight as follow: class_weight={0:1, 1:30} But I am not sure how to do it in R. In the help menu of R it describes class_weight as follow: Optional named list mapping indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class. Any idea or suggestions?
Now provide the response and nothing else.
|
Class_weight needs to be a list, so history <- model %>% fit( trainData, trainClass, epochs = 5, batch_size = 1000, class_weight = list("0"=1,"1"=30), validation_split = 0.2 ) seems to work. Keras internally uses a function called as_class_weights to change the list to a python-dictionary (see https://rdrr.io/cran/keras/src/R/model.R ). class_weight <- dict(list('0'=1,'1'=10)) class_weight >>> {0: 1.0, 1: 10.0} Looks just like the python dictionary that you mentioned above.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46907881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1358185/']}
|
jdg_371154
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25916851
|
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 inject a custom middleware into my OWIN pipeline that wraps the StaticFileMiddleware available from MS in order to support HTML 5 mode in AngularJS. I've been following this guide: http://geekswithblogs.net/shaunxu/archive/2014/06/10/host-angularjs-html5mode-in-asp.net-vnext.aspx From what I can gather of how this is supposed to work, my middleware is passing along requests to the static file middleware, and then if it can't resolve those requests (i.e., a request for an HTML 5 angular path, "/whatever"), it instead returns the base angular page so that a hard request for an HTML 5 path will work. My problem is that the result of invoking the inner middleware always seems to be a 200 status code, even though in my browser I get a 404, which leaves me scratching my head. Here's my code for reference: public static class AngularServerExtension{ public static IAppBuilder UseAngularServer(this IAppBuilder builder, string rootPath, string entryPath) { var options = new AngularServerOptions() { FileServerOptions = new FileServerOptions() { EnableDirectoryBrowsing = false, FileSystem = new PhysicalFileSystem(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootPath)) }, EntryPath = new PathString(entryPath) }; builder.UseDefaultFiles(options.FileServerOptions.DefaultFilesOptions); return builder.Use(new Func<AppFunc, AppFunc>(next => new AngularServerMiddleware(next, options).Invoke)); }}public class AngularServerMiddleware{ private readonly AngularServerOptions _options; private readonly AppFunc _next; private readonly StaticFileMiddleware _innerMiddleware; public AngularServerMiddleware(AppFunc next, AngularServerOptions options) { _next = next; _options = options; _innerMiddleware = new StaticFileMiddleware(_next, options.FileServerOptions.StaticFileOptions); } public async Task Invoke(IDictionary<string, object> environment) { IOwinContext context = new OwinContext(environment); // try to resolve the request with default static file middleware await _innerMiddleware.Invoke(environment); Debug.WriteLine(context.Request.Path + ": " + context.Response.StatusCode); // *** Right here is where I would expect a 404 but I get a 200 when debugging, // even though my browser eventually returns a 404 // route to root path if the status code is 404 // and need support angular html5mode if (context.Response.StatusCode == 404 && _options.Html5Mode) { context.Request.Path = _options.EntryPath; await _innerMiddleware.Invoke(environment); Console.WriteLine(">> " + context.Request.Path + ": " + context.Response.StatusCode); } }}public class AngularServerOptions{ public FileServerOptions FileServerOptions { get; set; } public PathString EntryPath { get; set; } public bool Html5Mode { get { return EntryPath.HasValue; } } public AngularServerOptions() { FileServerOptions = new FileServerOptions(); EntryPath = PathString.Empty; }}
Now provide the response and nothing else.
|
From your question I am not sure whether you are using IIS or selfhost. If you are using IIS, there is a much cleaner/faster solution than messing up with owin middleware:You can use IIS rewrite engine, copy the following inside your web config. <system.webServer><rewrite> <rules> <!--Redirect selected traffic to index --> <rule name="Index Rule" stopProcessing="true"> <match url=".*" /> <conditions logicalGrouping="MatchAll"> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" negate="true" /> </conditions> <action type="Rewrite" url="/index.html" /> </rule> </rules></rewrite>...</system.webServer> This line allows all files to be served normally: <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> this line allows the api to be served normally <add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" negate="true" /> Everything else gets index.html
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25916851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221851/']}
|
jdg_371155
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1267415
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $\left(A,+, \cdot\right)$ be a ring with $1$ that satisfies the following condition: For any nonzero $a\in A$, there exists a unique $b\in A$ such that $aba = a$. Show that $b$ also satisfies $bab = b$, and that all nonzero elements of $A$ are invertible.
Now provide the response and nothing else.
|
The ring has no nonzero zero divisors: if $ac=0$ for nonzero $a,c$, then you can find a unique $b$ such that $a=aba=a(b+c)a$. But then $b=b+c$ implies $c=0$, a contradiction. At this point, you can even prove that $A$, as long as it is not equal to zero, has an identity without assuming so in the hypotheses. Given any $a=aca\neq 0$, we see that $ac$ is an idempotent, and verify that $ac(acx-x)=0=(xac-x)ac$ implies $ac$ is an identity element for the ring. We write "$1$" for $ac$ hereafter. Knowing this, you can conclude that $a(ba-1)=0=(ab-1)a$ implies $ba=ab=1$ when a is nonzero. Clearly then $b$ can only be $a^{-1}$ and it follows that $bab=b$ also holds.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1267415', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49768/']}
|
jdg_371156
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8645361
|
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 successfully built a login form using ajax and want to add a shake effect to the form when the user enters incorrect details. I have the function in place that will fire but just need to build the jquery effect (note I know of jquery UI but don't want to use it! I don't want to use ANY plugins for this) So far I have: function shakeForm() { var p = new Array(15, 30, 15, 0, -15, -30, -15, 0); p = p.concat(p.concat(p)); $('form').css('left',p);} From what I understand I need to loop the array of values but how do I do that? Note that the element form has a position of relative already. So it's just a case of running those values as the left value in a random sequence? Thanks
Now provide the response and nothing else.
|
Why bother? Animations are queued.More - instead a left attribute you can use margin-left what prevents to adding position attribute :) function shakeForm() { var l = 20; for( var i = 0; i <= 10; i++ ) { $( 'form' ).animate( { 'margin-left': '+=' + ( l = -l ) + 'px', 'margin-right': '-=' + l + 'px' }, 50); }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8645361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302533/']}
|
jdg_371157
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27103278
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a custom cell for my UITableView but I am having some difficulty. First off I cannot use the Interface Builder, as I am experiencing a variation on this bug in Xcode . Every time I click on an element in the Interface Builder everything in that view gets a height and width of zero and gets repositioned outside of the view. Besides, I would like to learn how to do this programmatically. Secondly I am using the Swift language for my project. I have been trying to follow this demonstration , and doing my best to convert the Objective C code over to Swift, but whenever I run into problems I end up being stuck. I presume this is because I am not converting the code over correctly. Thirdly I found this video but despite being fairly difficult to follow (lots of the code is just copied and pasted without much explanation to what it does or why), it still ends up using the Interface Builder to change various parts. I have a basic UITableView set up fine. I just want to be able to add a custom cell to that table view. Can this be done using pure programming, or do I need to use the Interface Builder? Can anyone point me in the right direction or help me out in creating a custom cell programmatically in Swift? Many thanks.
Now provide the response and nothing else.
|
Ah, welcome to the least documented parts of the PHP manual! [I opened a bug report about it; maybe this answer will be helpful for documenting it: https://bugs.php.net/bug.php?id=69966 ] The bucket brigade To start with your initial question, the bucket brigade is just a name to the resource named userfilter.bucket brigade . You are passed two different brigades in as first and second parameters to php_user_filter::filter() . The first brigade is the input buckets you read from, the second brigade is initially empty; you write to it. Regarding your update about the data structure… It's really just a doubly linked list with strings basically. But it may well be that the name was stolen from there ;-) stream_bucket_prepend() / stream_bucket_append() stream_bucket_prepend(resource $brigade, stdClass $bucket): nullstream_bucket_append(resource $brigade, stdClass $bucket): null The expected $brigade is the output brigade aka the second parameter on php_user_filter::filter() . The $bucket is a stdClass object like it is returned by stream_bucket_make_writable() or stream_bucket_new() . These two functions just prepend or append the passed bucket to the brigade. stream_bucket_new() To demystify this function, analyze first what it's function signature is: stream_bucket_new(resource $stream, string $buffer): stdClass First argument is the $stream you're writing this bucket to. Second is the $buffer this new bucket will contain. [I'd like to note here that the $stream parameter actually is not very significant; it's just used to check whether we need to allocate memory persistently so that it survives through requests. I just suppose that you can make PHP nicely segfault by passing a persistent stream in here, when operating on a non-persistent filter...] There is now an userfilter.bucket resource created which is assigned to a property of a ( stdClass ) object named bucket .That object has also two other properties: data and datalen , which contain the buffer and the buffer size of this bucket. It will return you a stdClass which you can pass in to stream_bucket_prepend() and stream_bucket_append() . stream_bucket_make_writable() stream_bucket_make_writeable(resource $brigade): stdClass|null It shifts the first bucket from the $brigade and returns it. If the $brigade was emptied, it returns null . Further notes When php_user_filter::filter() is called, the $stream property on the object filter() is called on will be set to the stream we're currently working on. That's also the stream you need to pass to stream_bucket_new() when calling it. (The $stream property will be unset again after the call. You can't reuse it in e.g. php_user_filter::onClose() ). Also note that even when you're returned a $datalen property, you do not need to set that property in case you change $data property before passing it to stream_bucket_prepend() or stream_bucket_append() . The implementation requires you (well, it expects that or will throw a warning) that you read all the data from the $in bucket before returning. There is another case of the documentation lying to us: in php_user_filter::onCreate() , the $stream property is not set. It will only be set during filter() method call. Generally, don't use filters with non-blocking streams. I tried that once and it went horribly wrong … And it's not likely that's ever going to be fixed... Sum up (examples) Let's start with the simplest case: writing back what we got in. class simple_filter extends php_user_filter { function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { $consumed += $bucket->datalen; stream_bucket_append($out, $bucket); } return PSFS_PASS_ON; }}stream_filter_register("simple", "simple_filter") All what happens here is getting buckets from $in bucket brigade and putting it back into $out bucket brigade. Okay, now try to manipulate our input. class reverse_filter extends php_user_filter { function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { $consumed += $bucket->datalen; $bucket->data = strrev($bucket->data); stream_bucket_prepend($out, $bucket); } return PSFS_PASS_ON; }}stream_filter_register("reverse", "reverse_filter") Now we registered the reverse:// protocol, which reverses your string (each write is being reversed on it's own here; write order is still preserved). So, we obviously now need to manipulate the bucket data and prepend it here. Now, what's the use case for stream_bucket_new() ? Usually you can just append to $bucket->data ; yes, you even can concatenate all the data into the first bucket, but when flush() 'ing it might be possible that nothing is in bucket brigade and you want to send a last bucket, then you need it. class append_filter extends php_user_filter { public $stream; function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { $consumed += $bucket->datalen; stream_bucket_append($out, $bucket); } // always append a terminating \n if ($closing) { $bucket = stream_bucket_new($this->stream, "\n"); stream_bucket_append($out, $bucket); } return PSFS_PASS_ON; }}stream_filter_register("append", "append_filter") With that (and the existing documentation about php_user_filter class ), one should be able to do all sorts of magic userland stream filtering by combining all these powerful possibilities into even stronger code.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27103278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1037617/']}
|
jdg_371158
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
870751
|
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:
Calculate the following integral: \begin{equation}\int_1^{\sqrt{2}}\frac{1}{x}\ln\left(\frac{2-2x^2+x^4}{2x-2x^2+x^3}\right)dx\end{equation} I am having trouble to calculate the integral. I tried to use by parts method but it didn't help. Wolfram Alpha gives me $0$ as the answer but I don't know how to get it. I also tried to search the similar question here and I got this: $$I=\int_{-1}^1\frac1x\sqrt{\frac{1+x}{1-x}}\ln\left(\frac{2\,x^2+2\,x+1}{2\,x^2-2\,x+1}\right)\ \mathrm dx,$$ yet it didn't help much. Besides, I don't understand the answers there. Could anyone here please help me to calculate the integral preferably ( if possible ) with elementary ways (high school methods)? Any help would be greatly appreciated. Thank you.
Now provide the response and nothing else.
|
Update : Finally, a complete solution. Sorry it took so long. Split the integral up into 3.\begin{align}I&=-\int^{\sqrt{2}}_1\frac{\log{x}}{x}dx+\int^{\sqrt{2}}_1\frac{\log{((x^2-1)^2+1)}}{x}dx-\int^{\sqrt{2}}_1\frac{\log{((x-1)^2+1)}}{x}dx\\&=-\frac{1}{8}(\log{2})^2+\frac{1}{2}\int^1_0\frac{\log(1+x^2)}{1+x}dx-\int^{\sqrt{2}-1}_0\frac{\log(1+x^2)}{1+x}dx\end{align}The second integral is rather easy to evaluate.\begin{align}\frac{1}{2}\int^1_0\frac{\log(1+x^2)}{1+x}dx&=\frac{1}{2}\int^1_0\int^1_0\frac{x^2}{(1+x)(1+ax^2)}dx \ da\tag1\\&=\frac{1}{2}\int^1_0\frac{1}{1+a}\int^1_0\frac{1}{1+x}+\frac{x-1}{1+ax^2}dx \ da\\&=\frac{1}{2}\int^1_0\frac{\log{2}}{1+a}+\frac{\log(1+a)}{2a(1+a)}-\underbrace{\frac{\arctan(\sqrt{a})}{\sqrt{a}(1+a)}}_{\text{Let} \ y=\arctan{\sqrt{a}}}da\\&=\frac{1}{2}\left[(\log{2})^2+\frac{1}{2}\underbrace{\int^1_0\frac{\log(1+a)}{a}da}_{-\operatorname{Li}_2(-1)=\frac{\pi^2}{12}}-\frac{1}{2}\underbrace{\int^1_0\frac{\log(1+a)}{1+a}da}_{\frac{1}{2}(\log{2})^2}-\frac{\pi^2}{16}\right]\\&=\frac{3}{8}(\log{2})^2-\frac{\pi^2}{96}\end{align}The third integral can be evaluated using dilogarithms.\begin{align}\int^{\sqrt{2}-1}_0\frac{\log(1+x^2)}{1+x}dx&=\sum_{r=\pm i}\int^{\sqrt{2}-1}_0\frac{\log(r+x)}{1+x}dx\tag2\\&=-\sum_{r=\pm i}\int^{\frac{\lambda}{\sqrt{2}}}_{\lambda}\log\left(r-1+\frac{\lambda}{y}\right)\frac{dy}{y}\tag3\\&=-\sum_{r=\pm i}\int^{\frac{r-1}{\sqrt{2}}}_{r-1}\frac{\log(1+y)}{y}-\frac{1}{y}\log\left(\frac{y}{r-1}\right)dy\tag4\\&=\frac{1}{4}(\log{2})^2+\sum_{r=\pm i}\mathrm{Li}_2\left(\frac{1-r}{\sqrt{2}}\right)-\mathrm{Li}_2(1-r)\tag5\\&=\frac{1}{4}(\log{2})^2+\mathrm{Li}_2(e^{i\pi/4})+\mathrm{Li}_2(e^{-i\pi/4})-\mathrm{Li}_2(\sqrt{2}e^{i\pi/4})-\mathrm{Li}_2(\sqrt{2}e^{-i\pi/4})\\&=\frac{1}{4}(\log{2})^2-\frac{\pi^2}{96}\tag6\\\end{align}It follows that$$I=-\frac{1}{8}(\log{2})^2+\frac{3}{8}(\log{2})^2-\frac{\pi^2}{96}-\frac{1}{4}(\log{2})^2+\frac{\pi^2}{96}=0$$Explanation $(1)$: Differentiate under the integral sign $(2)$: Factorise $1+x^2$, let $r=\pm i$ $(3)$: Let $\displaystyle y=\frac{\lambda}{1+x}$ $(4)$: Let $\lambda=r-1$ $(5)$: Recognise that $\displaystyle\int\frac{\ln(1+y)}{y}dy=-\mathrm{Li}_2(-y)+C$ and $\displaystyle\int\frac{\ln(ay)}{y}dy=\frac{1}{2}\ln^2(ay)+C$ $(6)$: Use the identities here
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/870751', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/133248/']}
|
jdg_371159
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3941
|
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like the period at the end of a sentence to be added automatically when two spaces are typed (similar to how typing works in iPhones). I use two spaces between sentences, so the transformation I would like to happen would look like this: b l a h SPC SPC --> b l a h . SPC SPC I plan to use this along with the auto-capitalize mode. Many thanks!
Now provide the response and nothing else.
|
Give this a go: (defun freaky-space () (interactive) (cond ((looking-back "\\(?:^\\|\\.\\) +") (insert " ")) ((eq this-command last-command) (backward-delete-char 1) (insert ". ")) (t (insert " "))))(define-key text-mode-map " " 'freaky-space)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/3941', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/2728/']}
|
jdg_371160
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35033
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Today I had an interview, there they asked me, if given a microcontroller and Battery then how do you measure the voltage level. Write the steps from scratch with pseudo code. How can this be done?
Now provide the response and nothing else.
|
If they were after the pseudo code then that was a bad question; it all depends on the microcontroller. I probably would have given the candidate the microcontroller's datasheet and observe how he works his way through that 300 pages document. Anyway, you connect the battery to an ADC input (assumptions: microcontroller has ADC on board and battery voltage is less than microcontroller supply voltage). Set pin mode for that pin to ADC Select this ADC input if multiple ADC inputs Start ADC conversion Wait for end of conversion flag read ADC register calculate Vbat = Vcc x (ADC reading)/(2^ADC resolution)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/35033', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7976/']}
|
jdg_371161
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4917827
|
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 wondering how I can go about creating an arrary of the last month of days "Jan 21" style etc. automatically in ruby (in rails3)? If today is Feb 6th, then the arrary would have ["Jan 6", "Jan 7"..."Feb 6"]
Now provide the response and nothing else.
|
I don't know if I completely understood the question, but here's an answer that might help (1.month.ago.to_date..Date.today).map{ |date| date.strftime("%b %d") } outputs ["Jan 07", "Jan 08", "Jan 09", "Jan 10", "Jan 11", "Jan 12", "Jan 13", "Jan 14", "Jan 15", "Jan 16", "Jan 17", "Jan 18", "Jan 19", "Jan 20", "Jan 21", "Jan 22", "Jan 23", "Jan 24", "Jan 25", "Jan 26", "Jan 27", "Jan 28", "Jan 29", "Jan 30", "Jan 31", "Feb 01", "Feb 02", "Feb 03", "Feb 04", "Feb 05", "Feb 06"] You can create a range of dates, and then convert them to the desired format using strftime Just make sure you use Date objects on your range instead of Time objects, otherwise you will create an array of every second included in that lapse.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4917827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132331/']}
|
jdg_371162
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
120556
|
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's use Traveling Salesman as the example, unless you think there's a simpler, more understable example. My understanding of P=NP question is that, given the optimal solution of a difficult problem, it's easy to check the answer, but very difficult to find the solution. With the Traveling Salesman, given the shortest route, it's just as hard to determine it's the shortest route, because you have to calculate every route to ensure that solution is optimal. That doesn't make sense. So what am I missing? I imagine lots of other people encounter a similar error in their understanding as they learn about this.
Now provide the response and nothing else.
|
Your version of the TSP is actually NP-hard, exactly for the reasons you state. It is hard to check that it is the correct solution. The version of the TSP that is NP-complete is the decision version of the problem (quoting Wikipedia): The decision version of the TSP (where given a length L, the task is to decide whether the graph has a tour of at most L) belongs to the class of NP-complete problems. In other words, instead of asking "What is the shortest possible route through the TSP graph?", we're asking "Is there a route through the TSP graph that fits within my budget?".
|
{}
|
{'log_upvote_score': 7, 'links': ['https://cs.stackexchange.com/questions/120556', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/115485/']}
|
jdg_371163
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
459734
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The quick version: I want to point my '/volume1/Plex/Library/Application Support/Plex Media Server/Logs/' directory to a black hole, so nothing gets written to it. Is there a way to do this? Will it stop Plex from keeping my hard drives spinning all day? The long version: I'm running a Synology NAS with lots of movies etc. I was using Synology's "DS Video" app on my Roku TV, which worked great until I started ripping my blu-rays with DTS audio. Unfortunately, DS Video can't play DTS audio for whatever reason. To make matters worse, DS Video is going to be discontinued on Roku TVs as of 12/31/2018 (according to the support rep who got back to me about the audio issue). So I'm back to using Plex, which I stopped using months ago because it has a god-awful "feature" where it writes to log files on a regular basis, because stupid. See this , this , and this for just a few examples of people who don't like this "feature", with Plex basically refusing to change it. Because Plex writes to the log files so often, my hard drives never spin down. When Plex is disabled, the disks spin down and stay nice and quiet until I need the NAS. So I'm in the same boat as other Plex users who don't want Plex spinning up the drives all day. Is there a way to point the log directory that Plex uses to a black hole, like /dev/null or something? Will this allow the drives to spin down? Other notes / disclaimers: I know that NAS hard disks are perfectly ok with spinning all daylong. I don't care. They make noise and I want them quiet until Ineed them. I don't need them often, so at most I might spin them uponce a day. FWIW I'm using two Seagate 10TB IronWolf Pro drives. I don't care about the log files or Plex's reasoning for wanting themenabled.
Now provide the response and nothing else.
|
The commands cd and pwd have two operational modes. -L logical mode: symlinks are not resolved -P physical mode: symlinks are resolved before doing the operation The important thing to know here is that cd .. does not call the syscall chdir("..") but rather shortens the $PWD variable of the shell and then chdirs to that absolute path. If you are in physical mode, this is identical to calling chdir("..") , but when in logical mode, this is different. The main problem here: POSIX decided to use the less safe logical mode as default. If you call cd -P instead of just cd , then after a chdir() operation, the return value from getcwd() is put into the shell variable $PWD and a following cd .. will get you to the directory that is physically above the current directory. So why is the POSIX default less secure? If you crossed a symlink in POSIX default mode and do the following: ls ../*.ccd ..rm *.c you will probably remove different files than those that have been listed by the ls command before. If you like the safer physical mode, set up the following aliases: alias cd='cd -P'alias pwd='pwd -P' Since when using more than one option from -L and -P the last option wins, you still may be able to get the other behavior. Historical background: The Bourne Shell and ksh88 did get directory tracking code at the same time. The Bourne Shell did get the safer physical behavior while ksh88 at the same time did get the less safe logical mode as default and the options -L and -P . It may be that ksh88 used the csh behavior as reference. POSIX took the ksh88 behavior without discussing whether this is a good decision. BTW: some shells are unable to keep track of $PWD values that are longer than PATH_MAX and drive you crazy when you chdir into a directory with an absolute path longer than PATH_MAX . dash is such a defective shell.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/459734', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/303146/']}
|
jdg_371164
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7933121
|
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 the topic says, I want to be able to run a specific command during build, and have its output be the definition of a preprocessor macro. Right now, I have several user-defined variables (in project.pbxproj) and I am able to use their values to fill macro definitions, as follows: GCC_PREPROCESSOR_DEFINITIONS = ( "STRINGIFY(x)=@#x", "_MACRO=STRINGIFY(${MACRO})", ); MACRO = foo; I can set MACRO to a different value per scheme (e.g Debug vs. Release) which is very useful. But, I cannot figure out how to set it by running a command.
Now provide the response and nothing else.
|
I can think of 3 options: Environment variable : If you build from command line you can export a variable ( export ENVMACRO=superfoo ) before invoking the build command and use it in an Xcode configuration file OTHER_CFLAGS=-DMACRO=$(ENVMACRO) . You need to configure the target with the .xcconfig file. Run Script Build Phase : Custom script that generates a header file. MACROVALUE=$(run-command-to-obtain-value)echo "#define MACRO ($MACROVALUE)" > $(SRCROOT)/path/to/header.h In my tests you need an empty header file to be able to compile properly. There are other options like modifying an existing file using sed or any other command. Custom Build Rule : Custom script that process an input file and creates an output file. Similar to Run Script build phase but slightly better because it will run the script only when the input file has been modified. For example, create a .macro file and process it to update a header file. In Xcode > Target > Build rules, add new custom rule. Process : *.macro Custom script: HEADER="${SRCROOT}/Config.h"cd ${SRCROOT}echo "// Do not edit" > $HEADERcat "${INPUT_FILE_PATH}" | while read linedo macro="`echo $line | cut -d= -f1`" cmd="`echo $line | cut -d= -f2-`" value=$($cmd) echo "#define ${macro} @\"${value}\"" >> $HEADERdoneecho "// Updated on "`date` >> $HEADER Output files : $(SRCROOT)/Project.h Project.macro contains pairs MACRO=one-liner-command . Like these two non-sense examples: COMMIT=git log --pretty=format:%h -n 1BUILDYEAR=date +%Y Generated file will look like: // Do not edit#define COMMIT @"c486178"#define BUILDYEAR @"2011"// Updated on Sat Oct 29 14:40:41 CEST 2011 Each time Project.macro changes, the generated header will be updated.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7933121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/833989/']}
|
jdg_371165
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41395
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In many areas of mathematics (PDE, Algebra, combinatorics, geometry) when we have difficulty in coming with a solution to a problem we consider various notions of "generalized solutions". (There are also other reasons to generalize the notion of a solution in various contexts.) I would like to collect a list of "generalized solutions" concepts in various areas of mathematics, hoping that looking at these various concepts side-by side can be useful and interesting. Let me demonstrate what I mean by an example from graph theory: A perfect matching in a graph is a set of disjoint edges such that every vertex is included in precisely one edge. A fractional perfect matching is an assignment of non negative weights to the edges so that for every vertex, the sum of weights is 1. In combinatorics, moving from a notion described by a 0-1 solution for a linear programming problem to the solution over the reals is called LP relaxation of a problem and it is quite important in various contexts. (There are, of course, useful papers or other resources on generalized solutions in specific areas. It will be useful to have links to those but not as a substitute for actual answers with some details.)
Now provide the response and nothing else.
|
Partial Differential Equations (PDE) is a topic where generalizing the notion of solutions is a daily activity. The most obvious generalization has been the notion of weak solutions, which means that a solution $u$ is not necessarily differentiable enough times for the derivatives involved in the equation to make sense; but an integration against test functions , followed by an integration by parts, cures the problem. The most known example is that of the Laplace equation$$\Delta u=f\qquad\hbox{over }\Omega,$$where it is enough for $u$ to have locally integrable first-order derivatives, by rewriting the equation as a variational formulation (Dirichlet principle)$$\int_\Omega \nabla u\cdot\nabla vdx=-\int_\Omega fvdx$$for every $v\in{\mathcal C}^1_c(\Omega)$ (subscript $c$ means compact support ). What is important in this process is to satisfy the rule If $u$ has enough derivatives that the equation makes sense pointwise, then it is a weak solution if and only if it is a classical solution. Let us mention in passing that in order to use the full strength of functional analysis and operator theory, this weak notion of solutions led to the birth of Sobolev spaces and Distribution theory (L. Schwartz). This framework has been used for nonlinear equations and systems too, for instance for the Navier-Stokes, Euler, Schrödinger equations, ... An important question is whether this framework is accurate or not. By accurate , we mean that boundary and/or initial data yield a unique solution, which depends continuously on the data. This is the question of well-posedness . In many cases, functional analysis, sometimes associated to topological arguments, yield an existence theorem. A celebrated one is J. Leray's existence result to the Navier-Stokes equation of an incompressible fluid. However, uniqueness is often an other matter, a difficult one. For a $3$-dimensional fluid, the uniqueness to Navier-Stokes is a $1$M US Dollar open question. Uniqueness is often (but not always) associated to regularity. In many situations, there are weak-strong uniqueness result, which state that if a classical, or a regular enough solution exists, then there does not exist any other weak solution (say in a class where we do have an existence result). It is an if-theorem , in the absence of an existence result of strong solutions. For elliptic and parabolic equations, the regularity theory is a topic of its own. Whereas regularity is often expected in elliptic or parabolic equations and systems, it is not for hyperbolic ones, because we know that singularities do propagate, and that they can even be created in finite time thanks to nonlinear effects. Then the notion of weak solutions becomes meaningful, in that it translates in mathematical terms the physical notion of conserved quantities. It gives algebraic relation for the jump of the solution and its derivatives across discontinuities (Rankine-Hugoniot relations). Finally, I like a lot the way the theory of nonlinear elliptic equations, and of Hamilton-Jacobi equations have develloped in the past decades. At the beginning, it was observed that the maximum principle , known for classical solutions, remains valid for weak ones. This suggested, when the nonlinearity is so strong that a variational formulation is not available, that the maximum principle itself be used to define a notion of viscosity solution. The idea is to test at $x_0$ the PDE with a test function $\phi$ being comparable to $u$ (either $\phi\le u$ or $\phi\ge u$ locally) and touching $u$ at $x_0$. This has been extremely powerfull.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/41395', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1532/']}
|
jdg_371166
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
777849
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I am thinking about building a hobby project, one off kind of thing, just to brush up on my programming/design. It's basically a multi threaded web spider, updating the same data structure object->int. So it is definitely overkill to use a database for this, and the only thing I could think of is a thread-safe singleton used to contain my data structure. http://web.archive.org/web/20121106190537/http://www.ibm.com/developerworks/java/library/j-dcl/index.html Is there a different approach I should look in to?
Now provide the response and nothing else.
|
Double-checked locking has been proven to be incorrect and flawed (as least in Java). Do a search or look at Wikipedia's entry for the exact reason. First and foremost is program correctness. If your code is not thread-safe (in a multi-threaded environment) then it's broken. Correctness comes first before performance optimization. To be correct you'll have to synchronize the whole getInstance method public static synchronized Singleton getInstance() { if (instance==null) ...} or statically initialize it private static final Singleton INSTANCE = new Singleton();
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/777849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75174/']}
|
jdg_371167
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6551786
|
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 getting the ID of an entry in a database table in my codebehind, and am trying to find a simple LINQ query to delete the entry based on the ID. Here is what I have: DataContext.Items.DeleteObject((Item)DataContext.Items.Where(item => item.ItemId == selectedId)); This gives me a casting error however, and I am wondering if there is a better way to accomplish this? I've looked at similar questions and every answer I see seems to be more complicated than this should actually be, so any suggestions would be great!
Now provide the response and nothing else.
|
You currently have an IQueryable<Item> , not and Item - use Single() to get the item itself: var item = DataContext.Items.Where(item => item.ItemId == selectedId).Single();DataContext.Items.DeleteObject(item); This assumes a single matching item (ID as primary key), otherwise consider using First() of FirstOrDefault() with a null check instead or if you have a collection of item, just delete them in a loop: var items = DataContext.Items.Where(item => item.ItemId == selectedId);foreach(var item in items) DataContext.Items.DeleteObject(item);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6551786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/782884/']}
|
jdg_371168
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
90753
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What happens if we only use 2 resistors in the figure. Why do we use capacitor if we have a DC source already? And whats the easy way to calculate capacitor capacitance for given R and Vin?
Now provide the response and nothing else.
|
At the end of the day, this circuit forms a low pass filter. The corner frequency is: \$f_o = \dfrac{1}{2\pi RC}\$. The capacitors are there to help stabilize the virtual ground. Practically \$1-10\mu F\$ with \$R=10k\Omega\$ is a good place to start. If your virtual ground is noisy relative to the system ground, look at the spectral content, and adjust R and C values to minimize it.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/90753', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/16307/']}
|
jdg_371169
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38202897
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to perform an aggregation operation using in Java using the mongo-java-driver. I've performed some other find operations, but I'm unable to do the following aggregation correctly in Java: db.I1.aggregate([ { "$match": { "ci": 862222} }, { "$match": { "gi": { "$ne": null } }}, { "$group": { "_id": { "ci": "$ci", "gi": "$gi", "gn": "$gn", "si": "$si" } }}, { "$group": { "_id": { "ci": "$_id.ci", "gi": "$_id.gi", "gn": "$_id.gn" }, "sn": { "$sum": 1 } }}, { "$sort" : { "_id.gi" : 1}}]) I've tried several ways and methods to perform that aggregation in Java, but I'm unable to include the group fields "ci", "gi", "gn","si" correctly in the coll.aggregate(asList()) method. What I got so far, is the following: MongoCollection<Document> coll = mongo.getCollection("I1");Document matchCourse = new Document("$match", new Document("ci", Integer.parseInt(courseid)));Document matchGroupNotNull = new Document("$match", new Document("gi", new Document("$ne", null)));List<Object> list1 = new BasicDBList(); list1.add(new BasicDBObject("ci", "$ci")); list1.add(new BasicDBObject("gi", "$gi")); list1.add(new BasicDBObject("gn", "$gn")); list1.add(new BasicDBObject("si", "$si"));Document group1 = new Document( "_id", list1).append("count", new Document("$sum", 1));List<Object> list2 = new BasicDBList();list2.add(new BasicDBObject("ci", "$_id.ci"));list2.add(new BasicDBObject("gi", "$_id.gi"));list2.add(new BasicDBObject("gn", "$_id.gn"));Document group2 = new Document( "_id", list2).append("sn", new Document("$sum", 1));Document sort = new Document("$sort", new Document("_id.gi", 1));AggregateIterable<Document> iterable = coll.aggregate(asList(matchCourse, matchGroupNotNull, group1, group2, sort)); I know it's not correct, but I included it to give you an idea of what I am doing. I've googled this in many different ways and read several pages, but I didn't find any solution. The available documentation for MongoDB-Java( 1 , 2 ) is too short for me and doesn't include this case. How can I perform that query in Java? Any help would be appreciated. Thank you very much!!
Now provide the response and nothing else.
|
Finally I've come to a solution. There were some errors in the question that I posted, as it was the last attempt after reaching some point of desperation, but finally, here is the final solution: MongoDatabase mongo = // initialize your connection;Document matches = new Document("$match", new Document("gi", new Document("$ne", null)) .append("ci", Integer.parseInt(courseid)));Document firstGroup = new Document("$group", new Document("_id", new Document("ci", "$ci") .append("gi", "$gi") .append("gn", "$gn") .append("si", "$si")) .append("count", new Document("$sum", 1)));Document secondGroup = new Document("$group", new Document("_id", new Document("ci", "$_id.ci") .append("gi", "$_id.gi") .append("gn", "$_id.gn")) .append("ns", new Document("$sum", 1))); Document sort = new Document("$sort", new Document("_id.gi", 1)); List<Document> pipeline = Arrays.asList(matches, firstGroup, secondGroup, sort);AggregateIterable<Document> cursor = mongo.getCollection("I1") .aggregate(pipeline);for(Document doc : cursor) { // do stuff with doc } Instead of trying to create lists of key-values, I just appended the elements to the documents. Hope it will be useful for somebody!!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38202897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4269576/']}
|
jdg_371170
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26930692
|
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 know why lodash doesn't sort array of dates in string format as compared with plain javascript sort() . Is it expected behavior or a bug? var array = ["2014-11-11", "2014-11-12", null, "2014-11-01", null, null, "2014-11-05"];_.sortBy(array);// ["2014-11-11", "2014-11-12", null, "2014-11-01", null, null, "2014-11-05"]_.sortBy(array, function(value) {return new Date(value);});// [null, null, null, "2014-11-01", "2014-11-05", "2014-11-11", "2014-11-12"]array.sort();// ["2014-11-01", "2014-11-05", "2014-11-11", "2014-11-12", null, null, null] Version used: Lo-Dash v2.4.1 – Modern build.
Now provide the response and nothing else.
|
If you take a look to lodash code you may see how it's implemented. Function _.sortBy inside uses native Array.prototype.sort (see source ). But the root is not there. More interesting is function compareAscending that is passed as a callback to native sort ( source ). So in a few words your _.sortBy(array, function(value) {return new Date(value);}); is converted to: array.sort(function(a, b) { var aa = new Date(a), bb = new Date(b); if (aa !== bb) { if (aa > bb) { return 1; } if (aa < bb) { return -1; } } return aa - bb;}) So why null s are in the beginning? Because new Date(null) returns Thu Jan 01 1970 01:00:00 which is less than any other date in your array. What about native sort ? According to spec (see here ) The default sort order is according to string Unicode code points. If simply - native sort converts items to strings and compares strings. So native sort is smth like: _.sortBy(array, function(value) {return value + ''; }); As soon as 'null' string is always "bigger" than date string (like '2014-11-11') - null s will be in the tail of the result array.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26930692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/480410/']}
|
jdg_371171
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27869722
|
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 regex something like /scheduling/groups/members/[list*|get*|search*].json which should match with string /scheduling/groups/list.json or /scheduling/groups/getGroup.json or /scheduling/groups/searchMember.json and should not match with /scheduling/groups/save.json
Now provide the response and nothing else.
|
The problem is that a string literal is not of type std::string or subclass thereof - it is of type char const[N] . Thus the type of the initializer is not reference compatible with the target type of the reference, and a temporary must be created and bound to the reference. However, temporaries cannot be bound to non-const lvalue references. I.e. your case is equivalent to std::string& s = std::string("Abcdefg"); which is, even according to you, clearly ill-formed. Actually the precise reason it doesn't work is not because temporaries cannot be bound to non-const lvalue references, but rather that the initializer of a non-const lvalue reference is subject to certain requirements that char const[N] cannot meet in this case, [dcl.init.ref]/5: A reference to type “ cv1 T1 ” is initialized by an expression of type “ cv2 T2 ” as follows: If the reference is an lvalue reference and the initializer expression is an lvalue (but is not a bit-field), and “ cv1 T1 ” is reference-compatible with “ cv2 T2 ” or has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, and can be implicitly converted to an lvalue of type “cv3 T3,” where “ cv1 T1 ” is reference-compatible with “ cv3 T3 ” 106 (this conversion is selected by enumerating the applicable conversion functions (13.3.1.6) and choosing the best one through overload resolution (13.3)), then the reference is bound to the initializer expression lvalue in the first case and to the lvalue result of the conversion in the second case (or, in either case, to the appropriate base class subobject of the object). Otherwise, the reference shall be an lvalue reference to a non-volatile const type (i.e., cv1 shall be const), or the reference shall be an rvalue reference. [..] 106) This requires a conversion function (12.3.2) returning a reference type.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27869722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1861140/']}
|
jdg_371172
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22181713
|
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 using swipejs from swipejs.com , the home page slider uses this logic to highlight the active un-ordered list element and I'd like to know how this while condition works. <ul id="bullets"> <li></li> ....</ul>var bullets = document.getElementById('bullets').getElementsByTagName('li');var elem = document.getElementById('mySwipe');window.mySwipe = Swipe(elem, {callback: function(index, element) { var i = bullets.length; while (i--) { bullets[i].className = ' '; } bullets[index].className = 'on'; }});
Now provide the response and nothing else.
|
var i = bullets.length;while (i--) { ...do stuff...} is essentially equivalent to: var i = bullets.length;while (true) { if (i === 0) { i = i - 1; break; } i = i - 1; ...do stuff...} This style of looping tends to be used where performance is super important, as it's slightly faster than iterating indices from 0 to length-1 , and is relatively straight-forward to implement. Generally speaking, you shouldn't use it unless you're improving a known bottleneck and have verified that it improves performance in a significant way.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22181713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1793374/']}
|
jdg_371173
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51468
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If two similar sized atoms have different electronegativity values, the atom with higher electronegativity holds the electrons more tightly, and thus is more stable. Example: hydroxide vs azanide (NH2-). If two atoms have different sizes (down the periodic table), the larger atom has electrons more spread out and thus is more stable.Example: fluoride vs iodide anion To me, these two statements are contradictory. One says tight electron cloud means not reacting while the other says spread electron cloud means stability (less repulsion). Is one of the statements wrong? I'm sure I am missing something here. Thank you in advance for your help.
Now provide the response and nothing else.
|
When you have a ring that has $4n$ π electrons it's anti-aromatic if you force it into a fully conjugated cycle . Often such rings find a way to break the unfavorable (or at least, less favored) anti-aromatic conjugation. Large ones like cyclooctatetraene are likely to bend so all ring atoms are no longer in the same plane. Small ones like the cyclopropenyl anion shown here can't bend the ring out of planarity easily (or do it at all with only three atoms), but they can still break the conjugation by using unequal bond lengths or moving a ligand out of the plane giving that ring atom a pyramidal bonding geometry. The pyramidal bonding geometry seems to be what cyclopropenyl anion actually does. A computational result is shown by Kass [1] ; the top carbon atom has its bonds directed towards the observer indicating a pyramidal geometry (see below, from https://comporgchem.com/blog/archives/2987 and [1]): Reference 1.Kass, S. R. "Cyclopropenyl Anion: An Energetically Nonaromatic Ion," J. Org. Chem. 2013, 78 , 7370-7372, https://doi.org/10.1021/jo401350m .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/51468', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/30271/']}
|
jdg_371174
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37029385
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've tried everything in this very related question: Why can I not create a wheel in python? But I still get: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --helperror: invalid command 'bdist_wheel' Context: $ pip --versionpip 8.1.1 from /home/bdillman/proj/fashion/lib/python3.5/site-packages (python 3.5)$ python -c "import setuptools; print(setuptools.__version__)"18.2$ python --versionPython 3.5.1$ which python/home/bdillman/workspace/fashion/bin/python$ pip listMako (1.0.4)MarkupSafe (0.23)peewee (2.8.0)pip (8.1.1)PyYAML (3.11)setuptools (21.0.0)wheel (0.29.0) So it looks like everything is installed and the versions look good (I think). Anyone have ideas of things to check to further the diagnosis here? The exact command is: $ python setup.py bdist_wheel I've also tried $ sudo python setup.py bdist_wheel I've also done pip install --upgrade setuptools and pip install --upgrade wheel , and they're up-to-date.
Now provide the response and nothing else.
|
I had this happen to me on a recent Ubuntu using python3 -m venv (for which you must install python3-venv ), where no matter how many times I cleared the environment and retried, I was getting bdist_wheel errors installing the dependencies for Flask. In addition to not having venv by default as normal for a Python 3 install, for some reason on Ubuntu I also seem to have to explicitly install wheel . For clarity, the following did not work : python3 -m venv . . bin/activate pip install Flask However, the following does work : python3 -m venv . . bin/activate pip install wheel (never had to do this on, say, Arch Linux) pip install Flask
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37029385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155063/']}
|
jdg_371175
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3923864
|
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 interested if it's possible using C# to write a code analogous to this Javascript one: var v = (function(){ return "some value";})() The most I could achieve is: Func<string> vf = () =>{ return "some value";};var v = vf(); But I wanted something like this: // Gives error CS0149: Method name expectedvar v = (() =>{ return "some value";})(); Are there some way to call the function leaving it anonymous?
Now provide the response and nothing else.
|
Yes, but C# is statically-typed, so you need to specify a delegate type. For example, using the constructor syntax: var v = new Func<string>(() =>{ return "some value";})();// shorter versionvar v = new Func<string>(() => "some value")(); ... or the cast syntax, which can get messy with too many parentheses :) var v = ((Func<string>) (() =>{ return "some value";}))();// shorter versionvar v = ((Func<string>)(() => "some value"))();
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3923864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11256/']}
|
jdg_371176
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19394141
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does this compile: char ch = '1234'; //no error But not anything more than 4 char s : char ch = '12345'; //error: Too many chars in constant (Yes I know ' ' is used for one char and " " is for strings; I was just experimenting) Does this have anything to do with the fact that char s are represented using ASCII numbers?
Now provide the response and nothing else.
|
It's a multicharacter literal, and has a type of int . C++11 §2.13.2 Character literals A character literal is one or more characters enclosed in single quotes, as in ’x’ , optionally preceded by the letter L , as in L’x’ . A character literal that does not begin with L is an ordinary character literal, also referred to as a narrow-character literal. An ordinary character literal that contains a single c-char has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set. An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal has type int and implementation-defined value.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19394141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2533949/']}
|
jdg_371177
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1831820
|
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:
Is there a closed form for this infinite product? : $$\prod_{n=1}^{\infty}\operatorname{sinc}\left(\frac{\alpha}{n}\right)$$ where $\operatorname{sinc}(x)=\sin(x)/x$ is the familiar "sinc" function and $\alpha$ is some real parameter. I would be rather surprised there is, but nevertheless ... SIDE NOTE : I perform a numerical analysis and my guess for its taylor series in terms of $\alpha$ upto second power may be : $1-\alpha^2\zeta(2)/6$
Now provide the response and nothing else.
|
Since $$\frac{\sin x}{x}=\prod_{n\geq 1}\left(1-\frac{x^2}{\pi^2 n^2}\right) $$we have:$$ \log\text{sinc}(x) = -\sum_{n\geq 1}\sum_{m\geq 1}\frac{x^{2m}}{m\pi^{2m} n^{2m}}=-\sum_{m\geq 1}\frac{\zeta(2m)}{m\pi^{2m}}x^{2m}$$and $$ \sum_{n\geq 1}\log\text{sinc}\left(\frac{\alpha}{n}\right) = -\sum_{m\geq 1}\frac{\color{red}{\zeta(2m)^2}}{m\pi^{2m}}\alpha^{2m}.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1831820', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/240067/']}
|
jdg_371178
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
574953
|
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 a user user1 that is not in the sudoers file (nor belonging to groups in sudoer) but can still use sudo. How is it possible ? user1~$ groups user1 www-data My sudoer conf root ALL=(ALL) ALL %sudo ALL=(ALL) ALL #includedir /etc/sudoers.duser1~$ sudo -l User user1 may run the following commands on this host: (ALL) ALL
Now provide the response and nothing else.
|
As you can see, your sudoers file contains a line above which includes a number of other files from /etc/sudoers.d . You may be thinking that the hash symbol in front is a comment, but from man sudoers : It is possible to include other sudoers files from within the sudoers file currently being parsed using the #include and #includedir directives. You will need to show us the contents of all files in /etc/sudoers.d/ before we can comment on why user1 has sudo privileges.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/574953', 'https://serverfault.com', 'https://serverfault.com/users/209061/']}
|
jdg_371179
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34338840
|
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 split LinearLayout or RelativeLayout diagonally into two varying sizes and each having different child view. Example ViewPager in upper half section and a different LinearLayout in bottom section. something like this : How can i achieve this? Please help
Now provide the response and nothing else.
|
The easiest approach is to just make a background image with that skewed cut. If you wish to have a dynamic layout and you want to really cut widgets, use Canvas.saveLayer/restore. Like this: private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);private Xfermode pdMode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);private Path path = new Path();protected void dispatchDraw(Canvas canvas) { int saveCount = canvas.saveLayer(0, 0, getWidth(), getHeight(), null, Canvas.ALL_SAVE_FLAG); super.dispatchDraw(canvas); paint.setXfermode(pdMode); path.reset(); path.moveTo(0, getHeight()); path.lineTo(getWidth(), getHeight()); path.lineTo(getWidth(), getHeight() - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics())); path.close(); canvas.drawPath(path, paint); canvas.restoreToCount(saveCount); paint.setXfermode(null);} Gist: https://gist.github.com/ZieIony/8480b2d335c1aeb51167 <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main"> <com.example.marcin.splitlayout.CutLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:scaleType="centerCrop" android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/mazda" /> </com.example.marcin.splitlayout.CutLayout> <TextView android:layout_margin="16dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Mazda 3" /></LinearLayout> Btw. This thing is very popular recently :)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34338840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3140227/']}
|
jdg_371180
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20253652
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to pass errors to an alert to warn the user they made mistake in their code even if they don't have console open. var doc=(frame.contentWindow.document || obj.contentDocument|| obj.contentWindow); var head = doc.getElementsByTagName('head')[0]; var scriptElement = doc.createElement('script'); scriptElement.setAttribute('type', 'text/javascript'); scriptElement.text = scripts; try{ head.appendChild(scriptElement); } catch(e){ alert("error:"+e.message +" linenumber:"+e.lineNumber);} The appendChild throws an error when the scripts contain an error. It goes straight to the console though, and I want it to display in an alert, because it is for kids and they might not check the console. The try catch block does not catch the error. I tried it with eval(scripts). try{ eval(scripts);} catch(e){ alert("error:"+e.message +" linenumber:"+e.lineNumber);} this does work but it means that the code is executed twice, and that is very inconvenient in some cases. I tried monkey patching the console.error: console.log=function(){alert("taking over the log");} console.error=function(){alert("taking over the log");} but that only works when I literally use console.error. Not when an actual error is thrown.What function sends the error to the console in the case of a real error,if it isn't console.error? and can I access it and change it?Any ideas? Help would be really appreciated. Thanks Jenita
Now provide the response and nothing else.
|
Whilst try ... catch will work on the code that the script runs initially, as Jenita says it won't catch Syntax Errors, and also it won't catch errors thrown by callback functions which execute later (long after the try-catch has finished). That means no errors from any functions passed to setTimeout or addEventListener . However, you can try a different approach. Register an error listener on the window. window.addEventListener("error", handleError, true);function handleError(evt) { if (evt.message) { // Chrome sometimes provides this alert("error: "+evt.message +" at linenumber: "+evt.lineno+" of file: "+evt.filename); } else { alert("error: "+evt.type+" from element: "+(evt.srcElement || evt.target)); }} This will be called when an exception is thrown from a callback function. But it will also trigger on general DOM errors such as images failing to load, which you may not be interested in. It should also fire on Syntax Errors but only if it was able to run first so you should put it in a separate script from the one that may contain typos! (A Syntax Error later in a script will prevent valid lines at the top of the same script from running.) Unfortunately, I never found a way to get a line number from the evt in Firefox. (Edit: Poke around, I think it might be there now.) I discovered this when trying to write FastJSLogger , an in-page logger I used back when the browser devtools were somewhat slow. Desperate to catch line numbers, I started to experiment with wrappers for setTimeout and addEventListener that would re-introduce try-catch around those calls. For example: var realAddEventListener = HTMLElement.prototype.addEventListener;HTMLElement.prototype.addEventListener = function(type,handler,capture,other){ var newHandler = function(evt) { try { return handler.apply(this,arguments); } catch (e) { alert("error handling "+type+" event:"+e.message +" linenumber:"+e.lineNumber); } }; realAddEventListener.call(this,type,newHandler,capture,other);}; Obviously this should be done before any event listeners are registered, and possibly even before libraries like jQuery are loaded, to prevent them from grabbing a reference to the real addEventListener before we have been able to replace it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20253652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2403690/']}
|
jdg_371181
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
708994
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How would I prove that given a square matrix $A$ and non-zero scalar $c$ that $$(cA)^{-1}=c^{-1}A^{-1}$$
Now provide the response and nothing else.
|
Assuming $A$ is invertible, so that $A^{-1}$ actually exists, you can simply check this directly. Is it true that $(cA)(c^{-1}A^{-1})=(c^{-1}A^{-1})(cA)=I$? Why?
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/708994', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/115688/']}
|
jdg_371182
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51896862
|
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 looking for the right way to create a singleton class that accepts arguments in the first creation.My research lead me to 3 different ways: Metaclass class Singleton(type): instance = None def __call__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instanceclass ASingleton(metaclass=Singleton): pass __new__ class Singleton(object): instance = None def __new__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super().__new__(cls, *args, **kwargs) return cls.instance Decorator def Singleton(myClass): instances={} def getInstance(*args, **kwargs): if myClass not in instances: instances[myClass] = myClass(*args, **kwargs) return instances[myClass] return getInstance@Singletonclass SingletonTest(object): pass All of them work fine, but when it comes to initiation (like using __init__ in normal class) I can't figure out the right way to implement it.The only solution I can think about is using the metaclass method in this way: class Singleton(type): instance = None def __call__(cls, *args, **kwargs): if cls.instance is None: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cls.instanceclass ASingleton(metaclass=Singleton): def __init__(self,j): self.j=j I don't know if this is the correct way to create singleton that accepts arguments.
Now provide the response and nothing else.
|
I've found out that the best way to implement Singleton is by using meta classes: class Singleton (type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]# Python 2class MyClass(): __metaclass__= Singleton# Python 3class MyClass(metaclass=Singleton): pass
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51896862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4882880/']}
|
jdg_371183
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26191404
|
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 sort an array of optionals that holds an optional NSdate? class HistoryItem { var dateCompleted: NSDate?}let firstListObject = someListOfObject.lastlet secondListObject = someOtherListOfObject.lastlet thirdListObject = evenSomeOtherListOfObject.last //Last returns 'T?'var array = [firstListObject , secondListObject, thirdListObject] How can I sort array based on dateCompleted?
Now provide the response and nothing else.
|
Your sort function could use a combination of optional chaining and the nilcoalescing operator: sort(&array) { (item1, item2) -> Bool in let t1 = item1?.dateCompleted ?? NSDate.distantPast() as! NSDate let t2 = item2?.dateCompleted ?? NSDate.distantPast() as! NSDate return t1.compare(t2) == NSComparisonResult.OrderedAscending} This would sort the items on the dateCompleted value, and all items thatare nil and items with dateCompleted == nil are treated as "in the distant past"so that they are ordered before all other items. Update for Swift 3 (assuming that dateCompleted is a Date ): array.sort { (item1, item2) -> Bool in let t1 = item1?.dateCompleted ?? Date.distantPast let t2 = item2?.dateCompleted ?? Date.distantPast return t1 < t2}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26191404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591137/']}
|
jdg_371184
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15177987
|
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 currently looking into String concat options and the penalty they have on the overall performance. And my test-case creates results that blow my mind, I'm not sure if I'm overlooking something. Here is the deal: Doing "something"+"somethingElse" in java will (at compile-time) create a new StringBuilder every time this is done. For my test-case, I'm loading a file from my HDD that has 1661 lines of example data (classic "Lorem Ipsum"). This question is not about the I/O performance , but about the performance of the different string concat methods. public class InefficientStringConcat { public static void main(String[] agrs) throws Exception{ // Get a file with example data: System.out.println("Starting benchmark"); // Read an measure: for (int i = 0; i < 10; i++){ BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(new File("data.txt"))) ); long start = System.currentTimeMillis(); // Un-comment method to test: //inefficientRead(in); //betterRead(in); long end = System.currentTimeMillis(); System.out.println("Took "+(end-start)+"ms"); in.close(); } } public static String betterRead(BufferedReader in) throws IOException{ StringBuilder b = new StringBuilder(); String line; while ((line = in.readLine()) != null){ b.append(line); } return b.toString(); } public static String inefficientRead(BufferedReader in) throws IOException { String everything = "", line; while ((line = in.readLine()) != null){ everything += line; } return everything; }} As you can see, the setup is the same for both tests. Here are the results: Using inefficientRead() -method : Starting benchmark#1 Took 658ms#2 Took 590ms#3 Took 569ms#4 Took 567ms#5 Took 562ms#6 Took 570ms#7 Took 563ms#8 Took 568ms#9 Took 560ms#10 Took 568ms Using betterRead() -method Starting benchmark#1 Took 42ms#2 Took 10ms#3 Took 5ms#4 Took 7ms#5 Took 16ms#6 Took 3ms#7 Took 4ms#8 Took 5ms#9 Took 5ms#10 Took 13ms I'm running the tests with no extra parameters to the java -command. I'm running a MacMini3,1 from early 2009 and Sun JDK 7: [luke@BlackBox ~]$ java -versionjava version "1.7.0_09"Java(TM) SE Runtime Environment (build 1.7.0_09-b05)Java HotSpot(TM) Client VM (build 23.5-b02, mixed mode) This strikes me as a very heavy difference. Am I doing something wrong in measuring this, or is this supposed to happen?
Now provide the response and nothing else.
|
Am I doing something wrong in measuring this, or is this supposed to happen? It's supposed to happen. Constructing a long string using repeated string concatenation is a known performance anti-pattern: every concatenation has to create a new string with a copy of the original string and also a copy of the additional string. You end up with O(N 2 ) performance. When you use StringBuilder , most of the time you're just copying the additional string into a buffer. Occasionally the buffer will need to run out space and need to be expanded (by copying the existing data into a new buffer) but that doesn't happen often (due to the buffer expansion strategy). See my article on string concatenation for details - it's a very old article, so predates StringBuilder , but the fundamentals haven't changed. (Basically StringBuilder is like StringBuffer , but without synchronization.)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15177987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/717341/']}
|
jdg_371185
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14476757
|
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 looking to find a way of disabling a plugin execution if running with a particular profile. This is the opposite of running a plugin if a profile is selected . My use case: My Maven build has a whole load of plugins, but when running on my dev machine, I want to skip some of them. Instead of commenting those plugins out locally, I want to be able just run the build with a "dev" profile. The plugins would continue to run on my continuous build. Ideas?
Now provide the response and nothing else.
|
There is a neat way to disable plugin execution when specific profile is active. Firstly you need to add an identifier to plugin execution like: <build> <plugins> <!-- (...) --> <plugin> <groupId>nl.geodienstencentrum.maven</groupId> <artifactId>sass-maven-plugin</artifactId> <version>2.1</version> <executions> <execution> <id>styles-compilation</id> <!-- plugin execution identifier --> <phase>generate-resources</phase> <goals> <goal>update-stylesheets</goal> </goals> </execution> </executions> </plugin> Then you need to define a profile in which this plugin will NOT be executed: <profiles> <profile> <id>no-sass</id> <build> <plugins> <plugin> <groupId>nl.geodienstencentrum.maven</groupId> <artifactId>sass-maven-plugin</artifactId> <version>2.1</version> <executions> <execution> <id>styles-compilation</id> <!-- here there must be the same identifier as defined in <build><plugins> section --> <phase>none</phase> <!-- this disables plugin --> </execution> </executions> </plugin> </plugins> </build> </profile></profiles> Now if you run standard maven build: mvn clean package the sass-maven-plugin will be executed, yet when running: mvn clean package -P no-sass the sass-maven-plugin will not be executed.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14476757', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2119053/']}
|
jdg_371186
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
976667
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am studying for a SAT II Math2C and I came across this question in Barron's book. Solve $2 \sin(x) + \cos2(x) = 2 \sin^2(x) - 1$ [$0\le x \le 2\pi$] The solution says put the equations in a calculator and you'll get the intersection points. Solutions (x - coordinates of intersection points) are 1.57, 3.67, 5.76. How to reach the solution without a graphing calculator ? I can try equating them further; $2 \sin(x) + 1 - 2 \sin^2(x) = 2 \sin^2(x) - 1$ $2\sin x - 2\sin^2(x) - 2\sin^2(x) = -2$ $ 2 \sin x - 4\sin^2(x) = - 2 $ $ \sin x - 2 \sin^2(x) = -1 $ If I put this equation in my scientific calculator I get -0.52. I have no idea how to get those three intersection points, it must be possible..
Now provide the response and nothing else.
|
In general$$0\le \lfloor 2x\rfloor -2\lfloor x\rfloor\le 1.$$Proof. Either $x\in [k,k+1/2)$ or $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$. If $x\in [k,k+1/2)$, then$$ \lfloor 2x\rfloor=2k\quad\text{and}\quad 2\lfloor x\rfloor=2k,$$while $x\in [k+1/2,k+1)$, for some $k\in\mathbb Z$, then$$\lfloor 2x\rfloor=2k+1\quad\text{and}\quad 2\lfloor x\rfloor=2k.$$So the inequalities hold in both cases.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/976667', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/184843/']}
|
jdg_371187
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30444466
|
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 merge keypress and on click? I mean when a user press enter and click somewhere in the same time I need to invoke a function. $(document).keypress(function(e) { var code = e.keyCode || e.which; if(code == 13) { alert('keypress'); }});$(document).on( "click", function() { alert('click');}); I have this code but I am not able to merge it (usually I don't work with jQuery/javascript).
Now provide the response and nothing else.
|
Something like this may do the trick var pressingEnter = false;$(document).on({ keydown: function(e) { if(e.which == 13) { // enter is being pressed, set true to flag variable pressingEnter = true; } }, keyup: function(e) { if(e.which == 13) { // enter is no longer pressed, set false to flag variable pressingEnter = false; } }, click: function() { if (pressingEnter) { console.log('click and enter pressed'); } }}); BTW: there is no need to do var code = e.keyCode || e.which; since jQuery resolves that for you. You can use e.which on any browser. EDIT This version should allow any order of key pressed / mouse click. I'm assuming only left click is captured. Logic to handle enter + mouse click is placed on keydown and mousedown (it could be moved to keyup and mouseup if makes more sense) Changed alert by console.log since the first prevents mouseup event to be triggered. Nowdays we have hundred of better ways to show a message to user than built-in alert pop ups so I'll assume making it work for it is not a requirement. var pressingEnter = false;var clickingMouseButton = false;$(document).on({ keydown: function(e) { if(e.which == 13) { pressingEnter = true; } if (clickAndEnterPressing()) { console.log('click and enter pressed'); } }, keyup: function(e) { if(e.which == 13) { pressingEnter = false; } }, mousedown: function(e) { if (e.which == 1) { clickingMouseButton = true; } if (clickAndEnterPressing()) { console.log('click and enter pressed'); } }, mouseup: function(e) { if (e.which == 1) { clickingMouseButton = false; } }});function clickAndEnterPressing() { return pressingEnter && clickingMouseButton;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30444466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2317085/']}
|
jdg_371188
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20495
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why can't an enolate anion successfully displace a halogen from a benzene? I am told that the geometry is incorrect; that such S N 2 substitutions take place on $\mathrm{sp^3}$ hybridized (i.e. tetrahedral) substrates. This reasoning is circular. So what's a better reason? I can think of one reason but it is not satisfactory; it's still a bit circular. S N 2 = backside attack; how would one attack a planar bromobenzene? From within the ring? Seems like there would be a lot of possibly unfavorable interactions with the p-orbitals for something to get within the ring. Also this doesn't explain why substitution reactions with enolate anions don't take place at other $\mathrm{sp^2}$ carbon atoms - i.e. bromoethene.
Now provide the response and nothing else.
|
explain why substitution reactions with enolate anions don't take place at other sp2 carbon atoms As explained in this earlier answer , $\ce{S_{N}2}$ reactions do occur at $\ce{sp^2}$ carbons, they're just higher energy and consequently, less common. So the question becomes, " why is this pathway higher in energy? " Since the $\ce{S_{N}2}$ reaction involves "backside" approach to the carbon undergoing substitution, steric considerations play a role. However, the attacking reagent could alter its approach by 15 degrees or so lessening steric interactions (e.g. in benzene the attacking nucleophile could approach at an angle of 15 degrees above the plane of the benzene) and not increasing the activation energy too much. One way to explain the high energy associated with $\ce{S_{N}2}$ attack at a vinylic carbon is as follows. Consider the ethylenic double bond as a bent bond system, that is, we have a two-membered ring (instead of a traditional sigma-pi double bond) and each carbon in the ring is $\ce{sp^{4.3}}$ hybridized. This bent bond description is equivalent to the alternate pi bond description in all regards including electronic (btw, it makes the reason [strain] for the high heat of combustion of olefins more palpable). If possible, build a model to help visualize the situation. As the attacking nucleophile approaches and begins to interact with one of the ring carbons, that carbon will attempt to rehybridize to an $\ce{sp^2}$ carbon (just like in the traditional case of $\ce{S_{N}2}$ attack on an $\ce{sp^3}$ carbon). In this case we're forcing the already highly strained bond angle in our two-membered ring to try and open further - towards 120 degrees. Hence, this is a high-energy pathway that is not often observed. Alternately, this same concept can be rephrased in terms of traditional $\ce{sp^2}$ sigma-pi hybridization, by noting that we start with an $\ce{sp^2}$ hybridized carbon which becomes $\ce{sp}$ hybridized in the transition state. It is known that $\ce{sp}$ hybridized carbons are roughly 5 kcal/m less stable than $\ce{sp^2}$ hybridized carbons (more electrons in higher energy p orbitals, not offset by the energy lowering of the electrons shifting from $\ce{sp^2}$ bonds to $\ce{sp}$ bonds) thereby increasing the energy required to reach the transition state. Another point to consider is that since the $\ce{S_{N}2}$ reaction proceeds with inversion of configuration, such a reaction in a ring system would lead to the formation of a trans-double bond. This would be an extremely high energy process in the case of a small ring system such as benzene. Finally, $\ce{sp^2}$ hybridized carbon is more electronegative than $\ce{sp^3}$ hybridized carbon due to the increased s-character. This will increase the electron density around an $\ce{sp^2}$ carbon and, as a nucleophile approaches, the increased electron repulsion will make this a higher energy pathway that nucleophilic attack at a less electron rich $\ce{sp^3}$ carbon.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/20495', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/5084/']}
|
jdg_371189
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
146615
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider a pair of matrices $(c_1, c_2)$. The words "it generates the 2-dimensional Lie algebra", means that there exists a pair of scalars $k_1$, $k_2$, such that $$[c_1, c_2] = k_1 c_1 + k_2 c_2,$$ where $[a,b]$ is the "commutator" $ab-ba$. Not any pair generates 2-d Lie algebra. Question : what is the dimension of the subset of matrices $(c_1,c_2)$ which generate 2-d Lie algebra? at least for $2\times 2$ matrices ? It is clearly greater than $n^2+n$ since I can take - $c_1$ - arbitrary (so $n^2$) and $c_2$ - commuting with $c_1$, which gives ($+n$ for generic matrices). But in this way I get only $[c_1, c_2] =0$. The motivation for the question comes from this question on MathOverflow .
Now provide the response and nothing else.
|
I hope the follows help clear up things a bit. First of all, some corrections/suggestions to your typos/writings. (1) (just a personal preference, but I think this is a better practice) the $V^{\otimes n}$ is a right $\mathbb{C}S_n$-module. And $\phi: \mathbb{C}S_n\to \mathrm{End}_{\mathbb{C}}(V^{\otimes n})$ is given by $\sigma \mapsto (v \mapsto v\sigma)$. (2) $\psi:\mathbb{C}GL(V) \to \mathrm{End}_{\mathbb{C}}(V^{\otimes n})$ is given by $g \mapsto (v\mapsto gv)$, where $gv$ is given in your first paragraph. (3) Therefore, in the paragraph preceeding the statement of S-W duality, it should be: by commutation of action of $S_n$ and $GL(V)$, $\phi$ induces (by abusing notation) $\phi: \mathbb{C}S_n\to \mathrm{End}_{\mathbb{C}GL(V)}(V^{\otimes n})$ and similarly by swapping $S_n$ and $GL(V)$, we have $\psi:\mathbb{C}GL(V)\to \mathrm{End}_{\mathbb{C}S_n}(V^{\otimes n})$ (3.5) your $\eta$ in that paragraph should be either $\phi$ in my (1) or $\psi$ in my (2) above, depending on which correction to choose. (4) The fact that the invariant subspace of $\mathrm{End}_{\mathbb{C}}(V^{\otimes n})$ is the same as $\mathrm{End}_{\mathbb{C}S_n}(V^{\otimes n})$ is due to a Weyl. I don't think it is obvious (?). Question 1 and 2: Why conjugation? And what is the action of $S_n$ on $\mathrm{End}_{\mathbb{C}}(V^{\otimes n})$ In short (as always in mathematics...) this is the action that makes everything correct, and it wasn't given clearly in the proof of the Lemma of $W^{\otimes n}\cong \mathrm{End}_{\mathbb{C}}(V^{\otimes n})$. The motivation is that we need commutation: $x \theta = \theta x$ where $x$ is elements of $GL(V)$ or $S_n$ to get something in $\mathrm{End}_{\mathbb{C}G}(V^{\otimes n})$ for $G = S_n$ or $GL(V)$. This transform into $\theta = x\theta x^{-1}$. Note this is also where your guess for the action of $S_n$ on $\mathrm{End}_{\mathbb{C}}(V^{\otimes n})$ is wrong. Explicity, for $S_n$ side of the story: Action of $S_n$ on $W^{\otimes n}$: same as you said $(f_1\otimes \cdots\otimes f_n)\cdot\sigma = f_{\sigma^{-1}(1)}\otimes\cdots\otimes f_{\sigma^{-1}(n)}$ Action of $S_n$ on $\mathrm{End}_{\mathbb{C}}(V^{\otimes n})$: $\theta\cdot\sigma = \phi(\sigma)\theta\phi(\sigma^{-1})$ Proof of commutation of $S_n$-action: $\alpha((f_1\otimes\cdots f_n))\cdot\sigma\\=(v_1\otimes\cdots v_n\mapsto f_1(w_1)\otimes \cdots \otimes f_n(w_n))\cdot\sigma \\= v_1\otimes\cdots \otimes v_n\\\quad \mapsto v_{\sigma(1)}\otimes \cdots v_{\sigma(n)}\\\quad \mapsto f_1(v_{\sigma(1)})\otimes \cdots f_n(v_{\sigma(n)})\\\quad \mapsto f_{\sigma^{-1}(1)} (v_{\sigma(\sigma^{-1}1)})\otimes \cdots f_{\sigma^{-1}(n)} (v_{\sigma(\sigma^{-1}n)}) = f_{\sigma^{-1}(1)} (v_1)\otimes \cdots f_{\sigma^{-1}(n)} (v_n))\\=\alpha((f_1\otimes\cdots f_n)\cdot\sigma)$ Now you see where conjugation plays a part (in $S_n$ side of the story). So it is a good exercise for you to check the same thing in $GL(V)$. Question 3: What's wrong? You are correct $S(m,n)=\{ x\in \mathrm{End}_{\mathbb{C}}(V^{\otimes n})| \phi(\sigma) x = x \phi(\sigma) \; \forall \sigma \in S_n\} = \mathrm{End}_{\mathbb{C}}(V^{\otimes n})^{S_n}$ (this is the notation for saying "the subspace that is invariant under the action of $S_n$) On the other hand, the symmetric power part is correct. Now recall the symmetric power is the invariant space under permutation action of $S_n$, therefore $S^n(W)$ (in your notation $T^n W_{sym}$) is $(W^{\otimes n})^{S_n}$. So now everything follows from the isomorphism $\alpha$. Note: $y\cdot \sigma$ in $W^{\otimes n}$ corresponds to $\phi(\sigma)\alpha(y)\phi(\sigma^{-1})$ in $\mathrm{End}_{\mathbb{C}}(V^{\otimes n})$. P.S. If you have a typeset version of this lecture notes, would you mind sending me a copy (with the correction if it is possible)? I am also a graduate student learning things in related area, and I like this proof more than the usual reference from Goodman-Wallach (apart from the point (4) mentioned above).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/146615', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21498/']}
|
jdg_371190
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2377145
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
can anybody explain this why its happening int i=0;i=i++;i=i++;i=i++;System.out.println(i); it prints zero.
Now provide the response and nothing else.
|
i++ is a postincrement ( JLS 15.14.2 ). It increments i , but the result of the expression is the value of i before the increment. Assigning this value back to i in effect keeps the value of i unchanged. Break it down like this: int i = 0;int j = i++; It's easy to see why j == 0 in this case. Now, instead of j , we substitute the left hand side with i . The right hand side value is still 0 , and that's why you get i == 0 in your snippet.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2377145', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/195504/']}
|
jdg_371191
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
106746
|
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 want to monitor vsftpd server from monit on CentOS 5.4 but somehow vsftpd does not create pid file in /var/run (nor in any other place). Is this behavior normal for this distro?How should I configure monit to watch for vsftpd, should I create pid file manually in /etc/init.d/vsftpd script? Thanks.
Now provide the response and nothing else.
|
You can try this: monit: check process without pidfile check process vsftpd matching vsftpd start program = "/etc/init.d/vsftpd start" stop program = "/etc/init.d/vsftpd stop" Alternatively you can follow the guide I put together using aforementioned init file.Created RPM to keep the system consistent across updates (via fpm).New init file has modified service name vsftpd-pid so you can keep vsftpd stopped and vsftpd-pid running. Remember to change your monit start and stop commands too. More info here: http://bemehow.github.com/2012/11/15/monit-vsftpd/
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/106746', 'https://serverfault.com', 'https://serverfault.com/users/40645/']}
|
jdg_371192
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12021730
|
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 textfile where columns are separated by variable amounts of whitespace. Is it possible to load this file directly as a pandas dataframe without pre-processing the file? In the pandas documentation the delimiter section says that I can use a 's*' construct but I couldn't get this to work. ## sample datahead sample.txt# --- full sequence --- -------------- this domain ------------- hmm coord ali coord env coord# target name accession tlen query name accession qlen E-value score bias # of c-Evalue i-Evalue score bias from to from to from to acc description of target#------------------- ---------- ----- -------------------- ---------- ----- --------- ------ ----- --- --- --------- --------- ------ ----- ----- ----- ----- ----- ----- ----- ---- ---------------------ABC_membrane PF00664.18 275 AAF67494.2_AF170880 - 615 8e-29 100.7 11.4 1 1 3e-32 1e-28 100.4 7.9 3 273 42 313 40 315 0.95 ABC transporter transmembrane regionABC_tran PF00005.22 118 AAF67494.2_AF170880 - 615 2.6e-20 72.8 0.0 1 1 1.9e-23 6.4e-20 71.5 0.0 1 118 402 527 402 527 0.93 ABC transporterSMC_N PF02463.14 220 AAF67494.2_AF170880 - 615 3.8e-08 32.7 0.2 1 2 0.0036 12 4.9 0.0 27 40 391 404 383 408 0.86 RecF/RecN/SMC N terminal domainSMC_N PF02463.14 220 AAF67494.2_AF170880 - 615 3.8e-08 32.7 0.2 2 2 1.8e-09 6.1e-06 25.4 0.0 116 210 461 568 428 575 0.85 RecF/RecN/SMC N terminal domainAAA_16 PF13191.1 166 AAF67494.2_AF170880 - 615 3.1e-06 27.5 0.3 1 1 2e-09 7e-06 26.4 0.2 20 158 386 544 376 556 0.72 AAA ATPase domainYceG PF02618.11 297 AAF67495.1_AF170880 - 284 3.4e-64 216.6 0.0 1 1 2.9e-68 4e-64 216.3 0.0 68 296 53 274 29 275 0.85 YceG-like familyPyr_redox_3 PF13738.1 203 AAF67496.2_AF170880 - 352 2.9e-28 99.1 0.0 1 2 2.8e-30 4.8e-27 95.2 0.0 1 201 4 198 4 200 0.85 Pyridine nucleotide-disulphide oxidoreductase#load datafrom pandas import *data = read_table('sample.txt', skiprows=3, header=None, sep=" ")ValueError: Expecting 83 columns, got 91 in row 4#load data part 2data = read_table('sample.txt', skiprows=3, header=None, sep="'s*' ")#this mushes some of the columns into the first column and drops the rest. X.11 ABC_tran PF00005.22 118 AAF67494.2_2 SMC_N PF02463.14 220 AAF67494.2_3 SMC_N PF02463.14 220 AAF67494.2_4 AAA_16 PF13191.1 166 AAF67494.2_5 YceG PF02618.11 297 AAF67495.1_6 Pyr_redox_3 PF13738.1 203 AAF67496.2_7 Pyr_redox_3 PF13738.1 203 AAF67496.2_8 FMO-like PF00743.14 532 AAF67496.2_9 FMO-like PF00743.14 532 AAF67496.2_ While I can preprocess the files to change the whitespace to commas/tabs it would be nice to load them directly. (FYI this is the *.hmmdomtblout output from the hmmscan program )
Now provide the response and nothing else.
|
I think there's just a missing \ in the docs (maybe because it was interpreted as an escape marker at some point?) It's a regexp, after all: In [68]: data = read_table('sample.txt', skiprows=3, header=None, sep=r"\s*")In [69]: dataOut[69]: <class 'pandas.core.frame.DataFrame'>Int64Index: 7 entries, 0 to 6Data columns:X.1 7 non-null valuesX.2 7 non-null valuesX.3 7 non-null valuesX.4 7 non-null valuesX.5 7 non-null valuesX.6 7 non-null values[...]X.23 7 non-null valuesX.24 7 non-null valuesX.25 5 non-null valuesX.26 3 non-null valuesdtypes: float64(8), int64(10), object(8) Because of the delimiter problem noted by @MRAB, it has some trouble with the last few columns: In [73]: data.ix[:,20:]Out[73]: X.21 X.22 X.23 X.24 X.25 X.260 315 0.95 ABC transporter transmembrane region1 527 0.93 ABC transporter None None2 408 0.86 RecF/RecN/SMC N terminal domain3 575 0.85 RecF/RecN/SMC N terminal domain4 556 0.72 AAA ATPase domain None5 275 0.85 YceG-like family None None6 200 0.85 Pyridine nucleotide-disulphide oxidoreductase None but that can be patched up at the end.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12021730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/983191/']}
|
jdg_371193
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25232921
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Highcharts v4.0.3 with exporting.js in my web app, and I want to be able to just provide the end user with the following download options: Download Chart as JPG Download Chart as PNG However, the standard options are: Print Chart Download Chart as JPG Download Chart as PNG Download Chart as PDF Download Chart as SVG Vector Graphic How can I customise it so that it just gives the user JPG and PNG options?
Now provide the response and nothing else.
|
You can manually set exporting.buttons.contextButton.menuItems ( API ) to contain whatever buttons you want. You'll want to set it to only contain JPG and PNG like this (short form, textKey only): menuItems: ['downloadPNG','downloadJPEG'] Or for more explicit function calls (long form with objects and onclick ): menuItems: [{ textKey: 'downloadPNG', onclick: function () { this.exportChart(); }}, { textKey: 'downloadJPEG', onclick: function () { this.exportChart({ type: 'image/jpeg' }); }}] As in these JSFiddle demonstrations: short form and long form . The default for exporting.js is: menuItems: [{ textKey: 'printChart', onclick: function () { this.print(); }}, { separator: true}, { textKey: 'downloadPNG', onclick: function () { this.exportChart(); }}, { textKey: 'downloadJPEG', onclick: function () { this.exportChart({ type: 'image/jpeg' }); }}, { textKey: 'downloadPDF', onclick: function () { this.exportChart({ type: 'application/pdf' }); }}, { textKey: 'downloadSVG', onclick: function () { this.exportChart({ type: 'image/svg+xml' }); }}] The additional ones for export-data.js are: menuItems: [{ textKey: 'downloadCSV', onclick: function () { this.downloadCSV(); }}, { textKey: 'downloadXLS', onclick: function () { this.downloadXLS(); }},{ textKey: 'viewData', onclick: function () { this.viewData(); }},{ textKey: 'openInCloud', onclick: function () { this.openInCloud(); }}]
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25232921', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/395729/']}
|
jdg_371194
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2183936
|
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 make my iframe fill the window and not display any scrollbars? This works for IE6, I would like to get it to work for all browsers if possible: <iframe name=iframe1 src="theSiteToShow.html" width="100%" height="100%" frameborder="0" marginheight="10" marginwidth="10"></iframe><script type="text/javascript">function resizeIframe() { var height = document.documentElement.clientHeight; height -= document.getElementById('frame').offsetTop; // not sure how to get this dynamically height -= 20; /* whatever you set your body bottom margin/padding to be */ document.getElementById('frame').style.height = height +"px";};document.getElementById('frame').onload = resizeIframe;window.onresize = resizeIframe;</script>
Now provide the response and nothing else.
|
You should be able to do this using CSS only, without any need for javascript. The following works for me in IE6+, Google Chrome and Safari: <style type="text/css">body { margin: 0; overflow: hidden;}#iframe1 { position:absolute; left: 0px; width: 100%; top: 0px; height: 100%;}</style><iframe id="iframe1" name="iframe1" frameborder="0" src="theSiteToShow.html"></iframe> Your frame margins should be set in the body of theSiteToShow.html . UPDATE Following your comment, I used the following as a test page: <html> <head><style type="text/css">body { margin: 0; overflow: hidden;}#iframe1 { position:absolute; left: 0px; width: 100%; top: 0px; height: 100%;}</style></head> <body> <iframe id="iframe1" src="http://stackoverflow.com" frameborder="0"></iframe></body> </html> Tested in IE6+, Chrome, Safari and Firefox, it works just fine and fills the entire window.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2183936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182153/']}
|
jdg_371195
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
45055402
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here (and in a few SO questions) I see that C++ doesn't support something like lock-free std::atomic<double> and can't yet support something like atomic AVX/SSE vector because it's CPU-dependent (though nowadays of CPUs I know, ARM, AArch64 and x86_64 have vectors). But is there assembly-level support for atomic operations on double s or vectors in x86_64? If so, which operations are supported (like load, store, add, subtract, multiply maybe)? Which operations does MSVC++2017 implement lock-free in atomic<double> ?
Now provide the response and nothing else.
|
C++ doesn't support something like lock-free std::atomic<double> Actually, C++11 std::atomic<double> is lock-free on typical C++ implementations, and does expose nearly everything you can do in asm for lock-free programming with float / double on x86 (e.g. load, store, and CAS are enough to implement anything: Why isn't atomic double fully implemented ). Current compilers don't always compile atomic<double> efficiently, though. C++11 std::atomic doesn't have an API for Intel's transactional-memory extensions (TSX) (for FP or integer). TSX could be a game-changer especially for FP / SIMD, since it would remove all overhead of bouncing data between xmm and integer registers. If the transaction doesn't abort, whatever you just did with double or vector loads/stores happens atomically. Some non-x86 hardware supports atomic add for float/double, and C++ p0020 is a proposal to add fetch_add and operator+= / -= template specializations to C++'s std::atomic<float> / <double> . Hardware with LL/SC atomics instead of x86-style memory-destination instruction, such as ARM and most other RISC CPUs, can do atomic RMW operations on double and float without a CAS, but you still have to get the data from FP to integer registers because LL/SC is usually only available for integer regs, like x86's cmpxchg . However, if the hardware arbitrates LL/SC pairs to avoid/reduce livelock, it would be significantly more efficient than with a CAS loop in very-high-contention situations. If you've designed your algorithms so contention is rare, there's maybe only a small code-size difference between an LL/add/SC retry-loop for fetch_add vs. a load + add + LL/SC CAS retry loop. x86 natually-aligned loads and stores are atomic up to 8 bytes, even x87 or SSE . (For example movsd xmm0, [some_variable] is atomic, even in 32-bit mode). In fact, gcc uses x87 fild / fistp or SSE 8B loads/stores to implement std::atomic<int64_t> load and store in 32-bit code. Ironically, compilers (gcc7.1, clang4.0, ICC17, MSVC CL19) do a bad job in 64-bit code (or 32-bit with SSE2 available), and bounce data through integer registers instead of just doing movsd loads/stores directly to/from xmm regs ( see it on Godbolt ): #include <atomic>std::atomic<double> ad;void store(double x){ ad.store(x, std::memory_order_release);}// gcc7.1 -O3 -mtune=intel:// movq rax, xmm0 # ALU xmm->integer// mov QWORD PTR ad[rip], rax// retdouble load(){ return ad.load(std::memory_order_acquire);}// mov rax, QWORD PTR ad[rip]// movq xmm0, rax// ret Without -mtune=intel , gcc likes to store/reload for integer->xmm. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80820 and related bugs I reported. This is a poor choice even for -mtune=generic . AMD has high latency for movq between integer and vector regs, but it also has high latency for a store/reload. With the default -mtune=generic , load() compiles to: // mov rax, QWORD PTR ad[rip]// mov QWORD PTR [rsp-8], rax # store/reload integer->xmm// movsd xmm0, QWORD PTR [rsp-8]// ret Moving data between xmm and integer register brings us to the next topic: Atomic read-modify-write (like fetch_add ) is another story : there is direct support for integers with stuff like lock xadd [mem], eax (see Can num++ be atomic for 'int num'? for more details). For other things, like atomic<struct> or atomic<double> , the only option on x86 is a retry loop with cmpxchg (or TSX) . Atomic compare-and-swap (CAS) is usable as a lock-free building-block for any atomic RMW operation, up to the max hardware-supported CAS width. On x86-64, that's 16 bytes with cmpxchg16b (not available on some first-gen AMD K8, so for gcc you have to use -mcx16 or -march=whatever to enable it). gcc makes the best asm possible for exchange() : double exchange(double x) { return ad.exchange(x); // seq_cst} movq rax, xmm0 xchg rax, QWORD PTR ad[rip] movq xmm0, rax ret // in 32-bit code, compiles to a cmpxchg8b retry loopvoid atomic_add1() { // ad += 1.0; // not supported // ad.fetch_or(-0.0); // not supported // have to implement the CAS loop ourselves: double desired, expected = ad.load(std::memory_order_relaxed); do { desired = expected + 1.0; } while( !ad.compare_exchange_weak(expected, desired) ); // seq_cst} mov rax, QWORD PTR ad[rip] movsd xmm1, QWORD PTR .LC0[rip] mov QWORD PTR [rsp-8], rax # useless store movq xmm0, rax mov rax, QWORD PTR [rsp-8] # and reload.L8: addsd xmm0, xmm1 movq rdx, xmm0 lock cmpxchg QWORD PTR ad[rip], rdx je .L5 mov QWORD PTR [rsp-8], rax movsd xmm0, QWORD PTR [rsp-8] jmp .L8.L5: ret compare_exchange always does a bitwise comparison, so you don't need to worry about the fact that negative zero ( -0.0 ) compares equal to +0.0 in IEEE semantics, or that NaN is unordered. This could be an issue if you try to check that desired == expected and skip the CAS operation, though. For new enough compilers, memcmp(&expected, &desired, sizeof(double)) == 0 might be a good way to express a bitwise comparison of FP values in C++. Just make sure you avoid false positives; false negatives will just lead to an unneeded CAS. Hardware-arbitrated lock or [mem], 1 is definitely better than having multiple threads spinning on lock cmpxchg retry loops. Every time a core gets access to the cache line but fails its cmpxchg is wasted throughput compared to integer memory-destination operations that always succeed once they get their hands on a cache line. Some special cases for IEEE floats can be implemented with integer operations . e.g. absolute value of an atomic<double> could be done with lock and [mem], rax (where RAX has all bits except the sign bit set). Or force a float / double to be negative by ORing a 1 into the sign bit. Or toggle its sign with XOR. You could even atomically increase its magnitude by 1 ulp with lock add [mem], 1 . (But only if you can be sure it wasn't infinity to start with... nextafter() is an interesting function, thanks to the very cool design of IEEE754 with biased exponents that makes carry from mantissa into exponent actually work.) There's probably no way to express this in C++ that will let compilers do it for you on targets that use IEEE FP. So if you want it, you might have to do it yourself with type-punning to atomic<uint64_t> or something, and check that FP endianness matches integer endianness, etc. etc. (Or just do it only for x86. Most other targets have LL/SC instead of memory-destination locked operations anyway.) can't yet support something like atomic AVX/SSE vector because it's CPU-dependent Correct. There's no way to detect when a 128b or 256b store or load is atomic all the way through the cache-coherency system. ( https://gcc.gnu.org/bugzilla/show_bug.cgi?id=70490 ). Even a system with atomic transfers between L1D and execution units can get tearing between 8B chunks when transferring cache-lines between caches over a narrow protocol. Real example: a multi-socket Opteron K10 with HyperTransport interconnects appears to have atomic 16B loads/stores within a single socket, but threads on different sockets can observe tearing. But if you have a shared array of aligned double s, you should be able to use vector loads/stores on them without risk of "tearing" inside any given double . Per-element atomicity of vector load/store and gather/scatter? I think it's safe to assume that an aligned 32B load/store is done with non-overlapping 8B or wider loads/stores, although Intel doesn't guarantee that. For unaligned ops, it's probably not safe to assume anything. If you need a 16B atomic load, your only option is to lock cmpxchg16b , with desired=expected . If it succeeds, it replaces the existing value with itself. If it fails, then you get the old contents. (Corner-case: this "load" faults on read-only memory, so be careful what pointers you pass to a function that does this.) Also, the performance is of course horrible compared to actual read-only loads that can leave the cache line in Shared state, and that aren't full memory barriers. 16B atomic store and RMW can both use lock cmpxchg16b the obvious way. This makes pure stores much more expensive than regular vector stores, especially if the cmpxchg16b has to retry multiple times, but atomic RMW is already expensive. The extra instructions to move vector data to/from integer regs are not free, but also not expensive compared to lock cmpxchg16b . # xmm0 -> rdx:rax, using SSE4movq rax, xmm0pextrq rdx, xmm0, 1# rdx:rax -> xmm0, again using SSE4movq xmm0, raxpinsrq xmm0, rdx, 1 In C++11 terms: atomic<__m128d> would be slow even for read-only or write-only operations (using cmpxchg16b ), even if implemented optimally. atomic<__m256d> can't even be lock-free. alignas(64) atomic<double> shared_buffer[1024]; would in theory still allow auto-vectorization for code that reads or writes it, only needing to movq rax, xmm0 and then xchg or cmpxchg for atomic RMW on a double . (In 32-bit mode, cmpxchg8b would work.) You would almost certainly not get good asm from a compiler for this, though! You can atomically update a 16B object, but atomically read the 8B halves separately . (I think this is safe with respect to memory-ordering on x86: see my reasoning at https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80835 ). However, compilers don't provide any clean way to express this. I hacked up a union type-punning thing that works for gcc/clang: How can I implement ABA counter with c++11 CAS? . But gcc7 and later won't inline cmpxchg16b , because they're re-considering whether 16B objects should really present themselves as "lock-free". ( https://gcc.gnu.org/ml/gcc-patches/2017-01/msg02344.html ).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45055402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1915854/']}
|
jdg_371196
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55554431
|
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 run the code below to create a virtual Python environment from a YAML file. I’m running the code in the command line on Ubuntu server. The virtual environment is named py36. When I run the code below, I get the message below. The environment also doesn’t get created. Is this problem caused because I have several packages that I had to install using pip instead of Anaconda? Does anyone know how to solve this issue? I created the YAML file following the example from: https://datascience.stackexchange.com/questions/24093/how-to-clone-python-working-environment-on-another-machine Code: conda env create -f py36.yml py36.yml name: py36channels: - anaconda - cvxgrp - conda-forge - defaultsdependencies: - beautifulsoup4=4.6.3=py36_0 - patsy=0.5.1=py36_0 - sqlite=3.25.3=ha441bb4_0 - tk=8.6.8=ha441bb4_0 - asn1crypto=0.24.0=py36_1003 - ca-certificates=2018.11.29=ha4d7672_0 - certifi=2018.11.29=py36_1000 - cffi=1.11.5=py36h5e8e0c9_1 - clangdev=4.0.0=default_0 - cryptography=2.3.1=py36hdbc3d79_1000 - cryptography-vectors=2.3.1=py36_1000 - cycler=0.10.0=py_1 - fftw=3.3.8=h470a237_0 - freetype=2.9.1=h6debe1e_4 - glpk=4.65=h16a7912_1 - gmp=6.1.2=hfc679d8_0 - icu=58.2=h0a44026_1000 - idna=2.8=py36_1000 - kiwisolver=1.0.1=py36h2d50403_2 - lapack=3.6.1=1 - libiconv=1.15=h1de35cc_1004 - libpng=1.6.35=ha92aebf_2 - libxml2=2.9.8=hf14e9c8_1005 - lightgbm=2.2.1=py36hfc679d8_0 - llvmdev=4.0.0=default_0 - matplotlib=2.2.3=py36h0e0179f_0 - metis=5.1.0=3 - mkl_fft=1.0.6=py36_0 - mkl_random=1.0.1=py36_0 - mlxtend=0.13.0=py_1 - openblas=0.2.20=8 - openmp=4.0.0=1 - openssl=1.0.2p=h1de35cc_1002 - pandas=0.23.4=py36hf8a1672_0 - pycparser=2.19=py_0 - pyopenssl=18.0.0=py36_1000 - pyparsing=2.2.0=py_1 - pysocks=1.6.8=py36_1002 - python=3.6.6=h4a56312_1003 - pytz=2018.5=py_0 - selenium=3.141.0=py36h470a237_0 - tbb=2018_20171205=0 - urllib3=1.24.1=py36_1000 - cvxcanon=0.1.1=py36_0 - cvxpy=1.0.6=py36_0 - ecos=2.0.5=py36hf9b3073_0 - multiprocess=0.70.4=py36_0 - scs=1.2.6=py36_0 - appnope=0.1.0=py36hf537a9a_0 - backcall=0.1.0=py36_0 - blas=1.0=mkl - cvxopt=1.2.0=py36hb579ef3_0 - decorator=4.3.0=py36_0 - dill=0.2.8.2=py36_0 - dsdp=5.8=hb579ef3_0 - fastcache=1.0.2=py36h1de35cc_2 - gsl=2.4=h1de35cc_4 - intel-openmp=2019.0=117 - ipykernel=4.8.2=py36_0 - ipython=6.4.0=py36_0 - ipython_genutils=0.2.0=py36h241746c_0 - jedi=0.12.0=py36_1 - jupyter_client=5.2.3=py36_0 - jupyter_core=4.4.0=py36h79cf704_0 - libcxx=4.0.1=h579ed51_0 - libcxxabi=4.0.1=hebd6815_0 - libedit=3.1.20170329=hb402a30_2 - libffi=3.2.1=h475c297_4 - libgcc=4.8.5=hdbeacc1_10 - libgfortran=3.0.1=h93005f0_2 - libopenblas=0.3.3=hdc02c5d_2 - libsodium=1.0.16=h3efe00b_0 - mkl=2018.0.3=1 - ncurses=6.1=h0a44026_0 - numpy=1.15.4=py36h6a91979_0 - numpy-base=1.15.4=py36h8a80b8c_0 - parso=0.2.1=py36_0 - pexpect=4.6.0=py36_0 - pickleshare=0.7.4=py36hf512f8e_0 - pip=10.0.1=py36_0 - prompt_toolkit=1.0.15=py36haeda067_0 - ptyprocess=0.5.2=py36he6521c3_0 - pygments=2.2.0=py36h240cd3f_0 - python-dateutil=2.7.3=py36_0 - pyzmq=17.0.0=py36h1de35cc_1 - readline=7.0=hc1231fa_4 - scikit-learn=0.20.1=py36h4f467ca_0 - scipy=1.1.0=py36h28f7352_1 - setuptools=39.2.0=py36_0 - simplegeneric=0.8.1=py36_2 - six=1.11.0=py36h0e22d5e_1 - suitesparse=5.2.0=he235d88_0 - toolz=0.9.0=py36_0 - tornado=5.0.2=py36_0 - traitlets=4.3.2=py36h65bd3ce_0 - wcwidth=0.1.7=py36h8c6ec74_0 - wheel=0.31.1=py36_0 - xz=5.2.4=h1de35cc_4 - zeromq=4.2.5=h378b8a2_0 - zlib=1.2.11=hf3cbc9b_2 - pip: - absl-py==0.2.2 - astor==0.6.2 - bleach==1.5.0 - cython==0.28.3 - gast==0.2.0 - grpcio==1.12.1 - h5py==2.8.0 - html5lib==0.9999999 - keras==2.2.0 - keras-applications==1.0.2 - keras-preprocessing==1.0.1 - markdown==2.6.11 - pillow==5.1.0 - protobuf==3.5.2.post1 - pyramid-arima==0.6.5 - pyyaml==3.12 - sklearn==0.0 - statsmodels==0.9.0 - tensorboard==1.8.0 - tensorflow==1.8.0 - termcolor==1.1.0 - tqdm==4.23.4 - werkzeug==0.14.1 - xlrd==1.1.0prefix: /Users/username/anaconda2/envs/py36 Command line conda env create -f py36.ymlCollecting package metadata: doneSolving environment: failedResolvePackageNotFound: - libgfortran==3.0.1=h93005f0_2 - pyzmq==17.0.0=py36h1de35cc_1 - python==3.6.6=h4a56312_1003 - prompt_toolkit==1.0.15=py36haeda067_0 - libiconv==1.15=h1de35cc_1004 - sqlite==3.25.3=ha441bb4_0 - six==1.11.0=py36h0e22d5e_1 - cryptography==2.3.1=py36hdbc3d79_1000 - openssl==1.0.2p=h1de35cc_1002 - libxml2==2.9.8=hf14e9c8_1005 - libcxxabi==4.0.1=hebd6815_0 - matplotlib==2.2.3=py36h0e0179f_0 - ptyprocess==0.5.2=py36he6521c3_0 - readline==7.0=hc1231fa_4 - libedit==3.1.20170329=hb402a30_2 - libgcc==4.8.5=hdbeacc1_10 - xz==5.2.4=h1de35cc_4 - pickleshare==0.7.4=py36hf512f8e_0 - appnope==0.1.0=py36hf537a9a_0 - scipy==1.1.0=py36h28f7352_1 - cvxopt==1.2.0=py36hb579ef3_0 - jupyter_core==4.4.0=py36h79cf704_0 - dsdp==5.8=hb579ef3_0 - ncurses==6.1=h0a44026_0 - tk==8.6.8=ha441bb4_0 - ecos==2.0.5=py36hf9b3073_0 - wcwidth==0.1.7=py36h8c6ec74_0 - scikit-learn==0.20.1=py36h4f467ca_0 - libopenblas==0.3.3=hdc02c5d_2 - traitlets==4.3.2=py36h65bd3ce_0 - libsodium==1.0.16=h3efe00b_0 - ipython_genutils==0.2.0=py36h241746c_0 - fastcache==1.0.2=py36h1de35cc_2 - numpy==1.15.4=py36h6a91979_0 - numpy-base==1.15.4=py36h8a80b8c_0 - zlib==1.2.11=hf3cbc9b_2 - libffi==3.2.1=h475c297_4 - pygments==2.2.0=py36h240cd3f_0 - icu==58.2=h0a44026_1000 - gsl==2.4=h1de35cc_4 - libcxx==4.0.1=h579ed51_0 - suitesparse==5.2.0=he235d88_0 - zeromq==4.2.5=h378b8a2_0
Now provide the response and nothing else.
|
No, PyPI is not the issue. Instead, it fails because the YAML includes platform-specific build constraints, but you are transferring across platforms . Specifically, examining the build numbers on the failed packages (e.g., six=py36h0e22d5e_1 ), I can see that they correspond to packages from the osx-64 platform, but you are trying to install on a linux-64 platform, hence the build constraints are unresolvable. Omit Build Info The simplest solution to this is to omit the build info from the environment definition export. conda env export -n py36 -f py36.yml --no-builds There can still be issues if some of the packages are not available on linux-64 through Conda. If this is the case, you may need to find other channels (or check PyPI), switch versions, or remove the dependency altogether. Most of the packages look standard though. Not so important, but you can safely remove cvxgrp from your channels. That channel only serves an outdated version of cvxopt and only for osx-64 . Explicit Specifications Only Another, even more loosely defined option, is to output only what Conda refers to as explicit specifications . These indicate only those requirements that have been explicitly requested by the user. This includes packages, but also captures any version constraints, etc., that were provided by the user at some point. conda env export -n py36 -f py36.yml --from-history The advantage here is that any platform-specific dependencies will be ignored.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55554431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3476463/']}
|
jdg_371197
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8312659
|
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 read the "What's new in iOS 5" documentation and there it is stated, that changing the background of some UI-Elements is now better supported. I couldn't find the correct way for iOS 5 to change the background image of an UIToolbar. Is there a special new iOS 5 way of doing this? Or do i still have to subclass the UIToolbar?
Now provide the response and nothing else.
|
Yes, there is a new way to do this. You can use appearance to make all UIToolBar s have the same appearance. First, you have to make sure your class follows the UIAppearanceContainer protocol. Here I have done it in my app delegate: @interface AppDelegate : UIResponder <UIApplicationDelegate, UIAppearanceContainer>@property (strong, nonatomic) UIWindow *window;@end Then you can set the appearance in, for example, application:didFinishLaunchingWithOptions: or viewDidLoad . Like this: UIImage *image = [UIImage imageNamed:@"myimage.png"];[[UIToolbar appearance] setBackgroundImage:image forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault]; You only have to do this once to get the same appearance for all UIToolBar s in your app. You can also set many of (if not all?) the properties of your UIToolBar . As a sidenote, there are many classes that can follow the UIAppearanceContainer protocol. To find out what can be customized using the appearance protocol, you can open the header file of the class you want to customize, if you can set a property with UIAppearance , then the property has UI_APPEARANCE_SELECTOR written behind the property declaration.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8312659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474499/']}
|
jdg_371198
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
402315
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This: $ echo {{a..c},{1..3}} produces this: a b c 1 2 3 Which is nice, but hard to explain given that $ echo {a..c},{1..3} gives a,1 a,2 a,3 b,1 b,2 b,3 c,1 c,2 c,3 Is this documented somewhere? The Bash Reference doesn't mention it (even though it has an example using it).
Now provide the response and nothing else.
|
Well, it is unravelled one layer at a time: X{{a..c},{1..3}}Y is documented as being expanded to X{a..c}Y X{1..3}Y (that's X{A,B}Y expanded to XA XB with A being {a..c} and B being {1..3} ), themselves documented as being expanded to XaY XbY XcY X1Y X2Y X3Y . What may be worth documenting is that they can be nested (that the first } does not close the first { in there for instance). I suppose shells could have chosen to resolve the inner braces first, like by acting upon each closing } in turn: X{{a..c},{1..3}} X{a,{1..3}}Y X{b,{1..3}}Y X{c,{1..3}}Y (that is A{a..c}B expanded to AaB AbB AcB , where A is X{ and B is ,{1..3}Y ) X{a,1}Y X{a,2}Y X{a,3}Y X{b,1}Y X{b,2}Y X{b,3}Y X{c,1}Y X{c,2}Y X{c,3}Y XaY X1Y XaY Xa2 ... But I don't find that particularly more intuitive nor useful (see Kevin's example in comments for instance), there would still be some ambiguity as to the order in which the expansions would be done, and that's not how csh (the shell that introduced brace expansion in the late 70s, while the {1..3} form came later (1995) from zsh and {a..c} yet later (2004) from bash ) did it. Note that csh (from the start, see the 2BSD (1979) man page ) did document the fact that brace expansions could be nested, though did not explicitly say how nested brace expansions would be expanded. But you can look at the csh code from 1979 to see how it was done then. See how it does explicitly handle nesting indeed, and how it's resolved starting from the outer braces. In any case, I don't really see how the expansion of {a..c},{1..3} could have any bearing. In there, the , is not an operator of a brace expansion (as it's not inside braces), so is treated like any ordinary character.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/402315', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/171560/']}
|
jdg_371199
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6956264
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We cleaned up a large number of warnings. In several cases, we replaced %s with %d. Everything seemed OK until we realized that the generated code wouldn't compile - strings had been replaced by numbers. NOTE: I had the wrong revision checked out when I did the copy&paste. The fprintf string has been edited! GCC output fedex_plus/classes.c:2425:3: warning: format ‘%s’ expects argument of type ‘char *’ , but argument 3 has type ‘int’ [-Wformat] lines 2424 and 2425: fprintf(file, "\n//\t%s_ptr create_TIE();\n\tIDL_Application_instance_ptr create_TIE();\n", ENTITYget_CORBAname(entity)); function ENTITYget_CORBAname: const char *ENTITYget_CORBAname (Entity ent){ static char newname [BUFSIZ]; strcpy( newname, ENTITYget_name(ent) ); newname[0] = ToUpper (newname [0]); return newname;}
Now provide the response and nothing else.
|
My bet is that no declaration of ENTITYget_CORBAname is available at the fprintf spot. Should this be the case, it defaults to the implicit signature: int ENTITYget_CORBAname(...); hence the warning about the result type being an int . Check your code with -Wimplicit (implied by -Wall ), or try to put const char *ENTITYget_CORBAname (Entity ent); before the fprintf line and check if the warning disappears. If it does, then you're likely missing a header.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6956264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/382458/']}
|
jdg_371200
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
910483
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently I have found a question like following: In triangle $ABC$, $AB=AC=2$. Which of the following could be the area of triangle $ABC$? Indicate all possible areas: [A] $0.5$ [B] $1.0$ [C] $1.5$ [D] $2.0$ [E] $2.5$ [F] $3.0$ From my points of view, I can only guess one answer if I assume the triangle is a right angle triangle. In that case, the area will be $2$. But the answer showed the result, [A][B][C][D]. So, my question this is there any axiom that the area of the right angle will be the highest area of any type of triangle with the expressing two lengths of it? Thanks in advance.
Now provide the response and nothing else.
|
Not an axiom, but yes: The area of a triangle is $\frac{1}{2}ab \sin \theta$, where $a$ and $b$ are two known side lengths and $\theta$ is the angle between the two given side lengths. Since $\sin \theta$ reaches its maximum value when $\theta=90°$ (in which case we have $\sin 90° = 1$), the largest possible area is indeed attained for the case of a right angle.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/910483', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45862/']}
|
jdg_371201
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39791634
|
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 Web application needs to read the Document DB keys from appsettings.json file. I have created a class with the key names and reading the Config section in ConfigureServices() as: public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build();}public IConfigurationRoot Configuration { get; }public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); services.AddSession(); Helpers.GetConfigurationSettings(services, Configuration); DIBuilder.AddDependency(services, Configuration);} I'm looking for the ways to read the Key values in Test project.
Now provide the response and nothing else.
|
This is based on the blog post Using Configuration files in .NET Core Unit Test Projects (written for .NET Core 1.0). Create (or copy) the appsettings.test.json in the Integration test project root directory, and in properties specify "Build Action" as Content and "Copy if newer" to Output Directory. Note that it’s better to have file name (e.g. appsettings.test.json ) different from normal appsettings.json , because it is possible that a file from the main project override the file from the test project, if the same name will be used. Include the JSON Configuration file NuGet package (Microsoft.Extensions.Configuration.Json) if it's not included yet. In the test project create a method, public static IConfiguration InitConfiguration() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.test.json") .AddEnvironmentVariables() .Build(); return config; } AddEnvironmentVariables (suggested in @RickStrahl blog ) is useful if you want to pass some secrets, that you prefer not store in appsettings.test.json Use the configuration as usual var config = InitConfiguration(); var clientId = config["CLIENT_ID"] BTW: You also may be interesting in reading the configuration into the IOptions class as described in Integration test with IOptions<> in .NET Core : var options = config.Get<MySettings>();
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39791634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/289436/']}
|
jdg_371202
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41556
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be a ring, $x$ a nonzero element of $A$ and consider the annihilator of $x$, i.e $Ann(x)$. Now let $S$ denote the collection of all prime ideals of $A$ containing $Ann(x)$. It can be shown using Zorn's lemma that $S$ contains minimal elements (with respect the inclusion $\subseteq$). My question is about the following argument: Let $P$ be a minimal prime ideal in the set of all prime ideals that contain $Ann(x)$ and suppose $z \in P$. My question is: why does it follows that $z \in \sqrt{Ann(x)}$ ? We know that $\sqrt{Ann(x)}$ consists of all prime ideals of $A$ that contain $Ann(x)$. So let $P$ be a minimal prime ideal in the set of all prime ideals that contain $Ann(x)$ and assume $z \in P$. Now let $J$ be any prime ideal of $A$ that contains $Ann(x)$. We need to show that $z \in J$. Since $P$ is minimal with respect the inclusion we can't have that $J$ is properly contained in $P$. Why does it follows then that $P$ must contain $J$ ? Can you please explain?
Now provide the response and nothing else.
|
Unless I'm doing something silly, I think the claim is incorrect. Let $A=\mathbb{Z}/36\mathbb{Z}$, and let $x=6+36\mathbb{Z}$. The annihilator of $x$ consists of all $m+36\mathbb{Z}$ such that $6m$ is divisible by $36$, equivalently, such that $m$ is divisible by $6$; that is, $\mathrm{Ann}(6+36\mathbb{Z}) = (x)$. The prime ideals of $A$ are the images of the prime ideals of $\mathbb{Z}$ that contain $36$, namely $(2+36\mathbb{Z})$ and $(3+36\mathbb{Z})$; they are both minimal elements of the set of all prime ideals that contain $(x)$. Now take $z=2+36\mathbb{Z}$. Then $z$ is not in the radical of the annihilator: if $2^n+36\mathbb{Z} \in 6+36\mathbb{Z}$, then $9|2^n-6$ and $4|2^n-6$. The latter requires $n=1$, in which case the former cannot hold.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/41556', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6495/']}
|
jdg_371203
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32894901
|
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 framework which I want to use in my OS X app. Since updating to Xcode 7 on El Capitan , when I try to command-click on the import statement, Xcode goes to the following view. How can I get Xcode to display the Swift representation properly? I've had it happen before, and my solution was to recreate every project file which I don't want to do again.
Now provide the response and nothing else.
|
From my experience there are two possible causes for this issue.The first one is that your framework can't be located. To fix this you need to go to target's Build Settings and add a path to Framework Search Paths either an absolute: /Users/{user}/path-to-framework-parent-directory or relative to project directory: $(PROJECT_DIR)/path-to-framework-parent-directory Another possible cause is that the path to your framework contains a space in it. I found that it doesn't matter whether you try to escape it with backslash ../Project\ Name/frameworks or take the whole path in double-quotes "../Project Name/frameworks" . The result would be that SourceKit could not load the module. Note that $(PROJECT_DIR) could expand to a path with a space in it and it would too result in the same error. So it looks like a bug in Xcode/SourceKit (I tried the latest Xcode 7.2-beta3 and the bug is still there). My repository was on the second hard drive /Voluems/Macintosh HD/Repos . I just renamed the hard drive to HD , so the path looks like /Volumes/HD/Repos and the problem was gone.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32894901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/393009/']}
|
jdg_371204
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4510682
|
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:
Find positive integer $x$ with $x>1$ and $\dfrac{x^6-1}{x-1}$ is perfect square. My try: Let $\dfrac{x^6-1}{x-1}=y^2$ , so $(x^4+x^2+1)(x+1)=y^2$ . Let $d= \gcd(x+1,x^4+x^2+1)$ .And $d \vert x^4+x^2+1=(x^2+x+1)(x^2-x+1)$ , because $d\vert x+1$ so $d\vert 2$ . Case 1: $d=1$ . If $d=1$ so $(x^4+x^2+1)$ , $(x+1)$ is perfect square and $(x^2+\dfrac{1}{2})^2\le x^4+x^2+1\le(x^2+1)^2$ so no satisfactory solution. Case 2: $d=2$ . If $d=2$ so $\dfrac{x^4+x^2+1}{2}$ , $\dfrac{x+1}{2}$ is perfect square. But now I stuck. Please give me a hint. Thank you.
Now provide the response and nothing else.
|
You've got the right idea, but as Kenta S's comment indicates, it's $d \mid 3$ (since $x \equiv -1 \pmod{x+1}$ means $x^4 + x^2 + 1 \equiv (-1)^4 + (-1)^2 + 1 \equiv 3 \pmod{x + 1}$ ), not $d \mid 2$ , so the other option is $d = 3$ . For that case, for some integers $m$ and $n$ , we have $$x^4 + x^2 + 1 = 3m^2, \; \; x + 1 = 3n^2 \; \; \to \; \; x \equiv -1 \pmod{3} \tag{1}\label{eq1A}$$ With your factorization of $$x^4+x^2+1=(x^2+x+1)(x^2-x+1) \tag{2}\label{eq2A}$$ note that $$\begin{equation}\begin{aligned}\gcd(x^2+x+1,x^2-x+1) & = \gcd(x^2+x+1,x^2+x+1-(x^2-x+1)) \\& = \gcd(x^2+x+1,2x)\end{aligned}\end{equation}\tag{3}\label{eq3A}$$ Since $x^2 + x + 1 = x(x+1) + 1$ is always odd, and $\gcd(x^2+x+1,x) = 1$ , this means that $x^2+x+1$ and $x^2-x+1$ are always relatively prime. With \eqref{eq1A} giving that $x \equiv -1 \pmod{3}$ , then $x^2 - x + 1 \equiv (-1)^2 - (-1) + 1 \equiv 3 \equiv 0 \pmod{3}$ . Thus, from the first part of \eqref{eq1A} and using \eqref{eq2A}, there are integers $s$ and $t$ where $m = st$ and $$x^2 + x + 1 = s^2, \; \; x^2 - x + 1 = 3t^2 \tag{4}\label{eq4A}$$ However, $x^2 \lt x^2 + x + 1 \lt (x + 1)^2$ , so the first part of \eqref{eq4A} is not possible. This means there are no integers $x \gt 1$ where $\frac{x^6 - 1}{x - 1}$ is a perfect square.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4510682', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/840155/']}
|
jdg_371205
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
728662
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
In ansible, I would like to manipulate files/directories/archive that are composed or to composed like this: How would I do that. It seem Ansible is not able to handler that. (I doubt).So, what I do wrong ? Ex: - name: create file with a date in name file: path=/path/somefile.`date +%y_%m_%d`- name: unzip a file unarchive: path=/path/zomezip.`date +%y_%m_%d`.tar.gz bla bla....
Now provide the response and nothing else.
|
Set a variable, then use it with Ansible's Jinja2 templating system (it looks like you're trying to do PHP with the dot operator and the backticks) vars: date: "{{ lookup('pipe', 'date +%Y%m%d-%H%M') }}"tasks: - name: create file with a date in name file: path="/path/somefile{{ date }}" Or use the lookup itself in the templates: - name: create file with a date in name file: path="/path/somefile{{ lookup('pipe', 'date +%Y%m%d-%H%M') }}"
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/728662', 'https://serverfault.com', 'https://serverfault.com/users/98608/']}
|
jdg_371206
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2187666
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does JS support two functions with the same name and different parameters ? function f1(a, b){// a and b are numbers}function f1(a, b, c){// a is a string//b and c are numbers} Can I use those JS function for IE7, FF, Opera with no problem?
Now provide the response and nothing else.
|
JavaScript doesn't support what you would call in other languages method overloading , but there are multiple workarounds, like using the arguments object, to check with how many arguments a function has been invoked: function f1(a, b, c) { if (arguments.length == 2) { // f1 called with two arguments } else if (arguments.length == 3) { // f1 called with three arguments }} Additionally you could type-check your arguments, for Number and String primitives is safe to use the typeof operator: function f1(a, b, c) { if (typeof a == 'number' && typeof b == 'number') { // a and b are numbers } else if (typeof a == 'string' && typeof b == 'number' && typeof c == 'number') { // a is a string, b and c are numbers }} And there are much more sophisticated techniques like the one in the following article, that takes advantage of some JavaScript language features like closures, function application, etc, to mimic method overloading : JavaScript method overloading
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2187666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113934/']}
|
jdg_371207
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
799825
|
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, and I think many others, have had great success using smart pointers to wrap up unsafe memory operations in C++, using things like RAII, et cetera. However, wrapping memory management is easier to implement when you have destructors, classes, operator overloading, et cetera. For someone writing in raw C99, where could you point (no pun intended) to help with safe memory management? Thanks.
Now provide the response and nothing else.
|
The question is a bit old, but I figured I would take the time to link to my smart pointer library for GNU compilers (GCC, Clang, ICC, MinGW, ...). This implementation relies on the cleanup variable attribute, a GNU extension, to automatically free the memory when going out of scope, and as such, is not ISO C99, but C99 with GNU extensions. Example: simple1.c: #include <stdio.h>#include <csptr/smart_ptr.h>int main(void) { smart int *some_int = unique_ptr(int, 1); printf("%p = %d\n", some_int, *some_int); // some_int is destroyed here return 0;} Compilation & Valgrind session: $ gcc -std=gnu99 -o simple1 simple1.c -lcsptr$ valgrind ./simple1==3407== Memcheck, a memory error detector==3407== Copyright (C) 2002-2013, and GNU GPL\'d, by Julian Seward et al.==3407== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info==3407== Command: ./simple1 ==3407==0x53db068 = 1==3407====3407== HEAP SUMMARY:==3407== in use at exit: 0 bytes in 0 blocks==3407== total heap usage: 1 allocs, 1 frees, 48 bytes allocated==3407====3407== All heap blocks were freed -- no leaks are possible==3407====3407== For counts of detected and suppressed errors, rerun with: -v==3407== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/799825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47937/']}
|
jdg_371208
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
519758
|
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:
Update 2019-05-21 19:37 EST : My motherboard is on the latest BIOS available, released 2019-03-06 , but still has the install problems described below. Update : I burned the Arch ISO to a CD then tried booting from it, both in UEFI and legacy. Same type of result: Original question : I used dd to put this Arch ISO (Version 2019.05.02) on a USB stick, then attempted to boot from it on my desktop computer. When the Arch menu comes up, I choose "Boot Arch Linux (x86_64)." But what follows is a bunch of error messages, then the process just hangs there doing nothing. Here's a pic: The messages start off as "AMD-Vi: Completion-Wait loop timed out" The messages include "kernel panic." My motherboard is an MSI B450 Tomahawk with a Ryzen 5 2600 CPU. I've tried booting via UEFI and legacy with the same result. How do I install Arch Linux?
Now provide the response and nothing else.
|
Linux Kernel With MSI B450 The kernel fail in this case because of the support of the iommu feature; you can use some specific kernel adjustment (parameter) to fix your booting issue, this video demonstrate how to edit/apply the kernel parameters; here are some possibles solutions, try the different proposed parameters and choose the one that match best your needs. also you may turn off SVE in the bios. Possible Solutions: Kernel Parameters iommu=off iommu=off and amd_iommu=fullflush amd_iommu=off mem_encrypt=off amdgpu.runpm=0 pci=noats Involved Technology Definition Kernel Parameters: (aka Boot Options) Kernel command line parameters are parameters that you pass on to the kernel during the boot process to adjust its features or capabilities. IOMMU: is a memory management unit that basically increase performance and security; additional details can be found here IOMMU State: on, off or fullflush (detail on the linked article) mem_encrypt: Add support for Secure Memory Encryption (SME). and defines the memory encryption mask that will be used in subsequent patches to mark pages as encrypted. amdgpu.runpm=0: disable the graphical power management in the linux kernel (it will be then handled at the hardware/firmware/bios level) pci=noats: disable PCI Address Translation Services Note After the install you will need to be very careful on kernel updates Advanced technical users may build their own kernel with this or that patch Arch Boot Disk: To apply the parameters to the boot disk, on the boot menu, push "tab" to edit the boot command, hit space (to add a space) then write the parameter for instance "iommu=off" without quotes then hit enter to boot Sources: launchpad , freedesktop , freedesktop , freedesktop , askubuntu , wikipedia , artofcode , archlinux , linuxfoundation , fclose , youtube , youtube
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/519758', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/148559/']}
|
jdg_371209
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
465305
|
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:
If you were to globally set alias ':(){ :|:& };:'='echo fork bomb averted' would that be an effective security strategy to avoid the Bash fork bomb execution or would there still be a way to execute it? I suppose the question cashes out to: is there a way to execute a command when it's aliased to something else?
Now provide the response and nothing else.
|
The two , no, three , ... Amongst the main obstacles to that are: It's not a valid name for an alias. Bash's online manual : The characters ... and any of the shell metacharacters or quoting characters listed above may not appear in an alias name. ( , ) , & , | and whitespace are out in Bash 4.4. That particular string is not the only way to write a fork bomb in the shell, just famous because it looks obscure. For example, there's no need to call the function : instead of something actually composed of letters. If you could set the alias, the user could unset the alias, circumvent it by escaping the alias name on the command line, or disable aliases altogether, possibly by running the function in a script (Bash doesn't expand aliases in noninteractive shells). Even if the shell is restricted enough to stop all versions of a fork bomb, a general purpose system will have other programmable utilities that can recurse and fork off subprocesses. Got Perl or a C compiler? Easy enough. Even awk could probably do it. Even if you don't have those installed, you'll also need to stop the user from bringing in compiled binaries from outside the system, or running /bin/sh which probably needs to be a fully operational shell for the rest of the system to function. Just use ulimit -u (i.e. RLIMIT_NPROC ) or equivalent to restrict the number of processes a user can start. On most Linux systems there's pam_limits that can set the process count limit before any commands chosen by the user are started. Something like this in /etc/security/limits.conf would put a hard limit of 50 processes to all users: * hard nproc 50 (Stephen Kitt already mentioned point 1, Jeff Schaller mentioned 2 and 3.)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/465305', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/288980/']}
|
jdg_371210
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
151170
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a basic circuit for converting the 3.3V signal of a microcontroller board to a 24V constant voltage needed to control a device switched by voltage. When I measure voltage at the output while the transistor is on, it's 0V, and when it's off I get 24V, as expected. The problem is, whenever I connect the output to the device while the transistor is off, the voltage drops to 14.8V. The voltage I'm getting seems to be dependent on the load resistor, smaller resistor gives less voltage drop, but increases current when the transistor is closed. So the question - what causes the voltage drop and how can I avoid it? In my eyes, the resistor appears to be causing the voltage drop, but why is it not the case while the external circuit is disconnected? Is the only way to avoid this using less resistance at the emitter? Thank you.
Now provide the response and nothing else.
|
The problem is that R2 (oh, right, you don't have component designators, you'll just have to figure out from context which one that is) is the impedance of your signal when high. This together with the input ipedance of whatever is being connected to your output form a voltage divider. For example, using the circuit you show, let's say the output is 7 V when connected to the device. That means R2 is dropping 5 V, which means 5 mA is flowing thru it, which also means that is how much current the input of your device is sinking when held at 7 V. To compute the input resistance of the device at this operating point, use Ohm's law. (7 V)/(5 mA) = 1.4 kΩ. To get a higher output voltage, lower R2. However, keep in mind that this comes at the cost of higher current when the output is low. Also keep the dissipation of R2 in mind. In your example, the current thru R2 when the output is low is (12 V)/(1 kΩ) = 12 mA, and the dissipation is (12 V) 2 (1 kΩ) = 144 mW. Note that the power increases with the square of the supply voltage. Doubling that while keeping R2 the same will cause 4x the dissipation, or 576 mW. Even a ½ W resistor would be too small in that case. Added: Here is one way to fix your circuit without using a lot of current when the output is low: R1, Q1, and R2 are basically what you have now. Q2 is a emitter follower that provides much more current output than the bare R2. The output will be about 700 mV lower than the bottom end of R2, but I expect that small amount is irrelevant for a digital signal that swings to 24 V. If you can arrange the output from the microcontroller to be the opposite polarity, then you can use this circuit: This circuit is non-inverting, unlike your original and my example above. This has both higher output current capability and lower output voltage drop compared to the circuit above.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/151170', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/38958/']}
|
jdg_371211
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
78444
|
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am building a Smart Mirror for a school project and I need a way to give the user an interface where they can search and connect to a network. Unfortunately, my Raspberry Pi stopped working (doesn’t boot for some reason) to overcome this, I am going to code and test on my Windows laptop, then run the code on another Raspberry Pi that I will be borrowing from elsewhere. I am quite new to Python, and I want to know if there is a way to use a universal module where I can test this on Windows while knowing that it will work on a Raspberry Pi. Any help and suggestions are much appreciated, Sid.
Now provide the response and nothing else.
|
You can do it all on the Pi if you have SSH or terminal access, below are some notes I made when I first did it, you shouldn't lose any data if you do it correctly but as always it pays to have a backup just in case : At a terminal prompt (you may need to amend the partition names depending on your layout/requirements) N.B. the results in this example were based on resizing the partition on an attached 500Gb USB hard drive Expand partition and filesystem List existing devices and partitions with sudo fdisk -l $ sudo fdisk -l Disk /dev/mmcblk0: 7861 MB, 7861174272 bytes 4 heads, 16 sectors/track, 239904 cylinders, total 15353856 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x00000000 Disk /dev/sda: 500.1 GB, 500107862016 bytes 255 heads, 63 sectors/track, 60801 cylinders, total 976773168 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x0002c262 Device Boot Start End Blocks Id System /dev/sda1 8192 122879 57344 c W95 FAT32 (LBA) /dev/sda2 122880 5785599 2831360 83 Linux Partition to resize is /dev/sda2 make note of Start (122880) Now run this command: sudo fdisk /dev/sda At the prompt ( Command (m for help): ) type the next letters and then press enter after each: p Disk /dev/sda: 500.1 GB, 500107862016 bytes 255 heads, 63 sectors/track, 60801 cylinders, total 976773168 sectors Units = sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x0002c262 Device Boot Start End Blocks Id System /dev/sda1 8192 122879 57344 c W95 FAT32 (LBA) /dev/sda2 122880 5785599 2831360 83 Linux d delete partition 2 partition to delete i.e /dev/sda2 p to confirm the deletion n new partition (default) p primary (default) 2 partition number (default) 122880 first sector as noted above (N.B. not default) +50G last sector make size 50Gb (N.B. not default) or take default to use the remainder of the disk p to confirm new partition is created w writes the partition information, reboot required if the partition was already mounted (as it was in this instance) After exit, run: sudo resize2fs /dev/sda2 to expand the file system to fill the new partition
|
{}
|
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/78444', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/38584/']}
|
jdg_371212
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3158369
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The primes contain finite arithmetic progressions of arbitrary length, but not an infinite arithmetic progression. Say we define an almost arithmetic progression to be a sequence $a_k$ , $k \geq 0$ , such that there exist $a,d$ such that $a_k = a+kd + O(\sqrt{k})$ . Do the primes contain an infinite almost arithmetic progression? (The definition is ad hoc and just made up out of curiosity. I wrote the “error term” $O(\sqrt{k})$ in analogy to the expectation of a random walk. An obvious generalization of the question is to replace this with some other “small” error term like $O(\ln k)$ or whatever.)
Now provide the response and nothing else.
|
Note: I allow for $a_k$ to repeat. If you wish to keep them distinct, the answer by N. S. gives a negative answer. The answer is: we don't know, but probably . Indeed, your question is equivalent to the question of whether the prime gaps satisfy $p_{n+1}-p_n=O(\sqrt{p_n})$ , as I explain below. This bound is widely believed to hold - indeed, the running conjecture ( Cramér's conjecture ) is that we even have $p_{n+1}-p_n=O((\log p_n)^2)$ , but we are quite far from proving it. The best unconditional bound we have is $p_{n+1}-p_n=O(p_n^{0.525})$ , and assuming the Riemann hypothesis we can push this to $O(p_n^{1/2+\varepsilon})$ , but not to $O(\sqrt{p_n})$ . (see Wikipedia ) To see the equivalence, take some infinite almost arithmetic progression. Suppose the $O(\sqrt{k})$ term is bounded by $M\sqrt{k}$ . For any prime $p_n$ , let $k$ be the least such that $a+dk>p_n+M\sqrt{k}$ . Then $p_{n+1}\leq a_k\leq a+dk+M\sqrt{k}\leq d+p_n+M\sqrt{k}+M\sqrt{k}=p_n+O(\sqrt{k})=p_n+O(\sqrt{p_n})$ . Conversely, suppose gaps between primes are $O(\sqrt{p_n})$ . Take $a=0,d=1$ and $a_k$ the smallest prime greater than $k$ . The assumption trivially implies $a_k=k+O(\sqrt{k})$ .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3158369', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/343280/']}
|
jdg_371213
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
745172
|
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 is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is int test = int.Parse(string.Format("{0}", myobject)) Is there a cleaner way to do this? Thanks
Now provide the response and nothing else.
|
You have several options: (int) — Cast operator. Works if the object already is an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined. int.Parse()/int.TryParse() — For converting from a string of unknown format. int.ParseExact()/int.TryParseExact() — For converting from a string in a specific format Convert.ToInt32() — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined. as int? — Note the "?". The as operator is only for reference types, and so I used "?" to signify a Nullable<int> . The " as " operator works like Convert.To____() , but think TryParse() rather than Parse() : it returns null rather than throwing an exception if the conversion fails. Of these, I would prefer (int) if the object really is just a boxed integer. Otherwise use Convert.ToInt32() in this case. Note that this is a very general answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the specifics here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails (int)(short) might work instead, and for recommending you check your debugger to find out the actual runtime type.
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/745172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48552/']}
|
jdg_371214
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25548045
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The Code #include <iostream>#include <type_traits>template<typename T, typename = typename std::enable_if<std::is_pod<T>::value>::type >T foo(T t) { return t; }template<typename T>void foo(T t) { }int main(){ foo<int>(5);} The Error main.cpp: In function 'int main()':main.cpp:14:15: error: call of overloaded 'foo(int)' is ambiguous foo<int>(5); ^main.cpp:14:15: note: candidates are:main.cpp:7:3: note: T foo(T) [with T = int; <template-parameter-1-2> = void] T foo(T t) { return t; } ^main.cpp:10:6: note: void foo(T) [with T = int] void foo(T t) { } ^ The question Is it possible to solve The Error in The Code?
Now provide the response and nothing else.
|
Constraining functions with SFINAE does not introduce an ordering, it just means a constrained function is callable or not callable, so when the first overload is enabled you have two ambiguous functions. The simplest solution is to use the inverse of the same constraint to disable the second overload, so that only one is viable for a given type. To make that work you will need to move the enable_if to the return type, rather than a default template argument (because default template arguments are not part of a function's signature and so can't be used for overloading, only constraining with SFINAE). This solution won't work for lots of overloads unless you can come up with a separate predicate (i.e. combination of type traits) for each overload such that none of the argument types matches more than one predicate. This means the predicates must be mutually exclusive, you cannot have a predicate testing a concept such as signed integral type that is a more refined version of another one testing a concept such as integral type , because both predicates would be true for int and more than one function would be enabled. One important reason that C++ Concepts are a better solution than SFINAE is that functions constrained by concepts are ordered, so that a more constrained function is a better match than a less constrained one. That means you don't need to play these SFINAE games and have mutually exclusive constraints, the compiler will Do The Right Thing.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25548045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/752976/']}
|
jdg_371215
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1630669
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to show that: $$A \subset B \implies A \cap B = A$$ So far I got: $$A \subset B$$$$A \cap B \subset A$$$$A \cap B \subset B$$$$A \cap B \subset A \subset B$$
Now provide the response and nothing else.
|
$A\cap B \subset A$. On the other hand if $x\in A $ then $x\in B$ (because $A\subset B$). Since $x\in A$ and $x\in B$ we have $x\in A\cap B$, so $A\subset A\cap B$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1630669', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/113873/']}
|
jdg_371216
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51940
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
If $R$ is a commutative ring (with $1$), then an $R$-algebra $A$ is said to be separable if $A$ is projective as an $A$-$A$-bimodule. (The notion of an "$A$-$A$-bimodule" includes the requirement that $R$ acts the same way from the left and from the right. The notion of "projective $A$-$A$-bimodule" is defined in the same way as the notions of "projective $A$-left module" and "projective $A$-right module". If you are unhappy with this definition, you can rewrite any $A$-$A$-bimodule as an $A\otimes_R A^{\mathrm{op}}$-left module, and then use the notion of a projective left module.) There is a criterion stating that an $R$-algebra $A$ is separable if and only if there is an element $e\in A\otimes_R A$ such that the multiplication map $A\otimes_R A\to A$ sends $e$ to $1\in A$, and such that $ae=ea$ for all $a\in A$. Equivalently, an $R$-algebra $A$ is separable if and only if the $A$-$A$-bimodule epimorphism $A\otimes_R A\to A$ given by multiplication of the two tensorands has a section in the category of $A$-$A$-bimodules. (This is both in Crawley-Boevey , chapter 4. I have difficulties finding other literature which does the notion of separability in full generality. For some reason, most books consider it enough to talk about separable $k$-algebras with $k$ a field.) Now my question is, is there a transitivity theorem like this: If $B$ is a separable commutative $R$-algebra, and $A$ is a separable $B$-algebra, then $A$ is a separable $R$-algebra as well? Maybe some conditions like projectivity (of $B$ as $A$-module and $A$ as $R$-module) must be added; that would be ok for me. If something like this holds, then the proof that separability of a field extension as algebra is just Galois-theoretical separability could be simplified (most importantly, the ugly Primitive Element Theorem would not be needed anymore).
Now provide the response and nothing else.
|
inkspot is indeed correct that the component graphs are indeed not generally trees. As you seem to have deduced for yourself, Cerednik–Drinfeld uniformization is a highly nontrivial concept, and it really helps to have some examples to set it in your mind. Most helpful in this direction is Ogg's "Mauvaise réduction des courbes de Shimura" ( Zbl 0581.14024 ) where he draws out a few of these dual graphs. In general the dual graphs have $2h$ vertices $x$ where $h$ is the class number of $\mathcal{O}_x$ , a level $H$ Eichler order in $D$ (your totally definite quaternion algebra, so note there's a choice of which $x$ to make here, but as long as the level is squarefree all orders are hereditary and it doesn't make a difference). An orbit-stabilizer theorem computation then shows that for instance when $B$ is a quaternion algebra over $\mathbf{Q}$ , $p+1$ (the size of the set of edges $y$ stemming from a particular vertex $x$ in the Bruhat–Tits tree) is equal to $\sum_{e(y) = x} \frac{\mathcal{O}_x^\times}{\mathcal{O}_y^\times}$ . So it's not just that there are edges, but we know exactly how many there are! (For a readable account of details of this, see Kurihara's paper on Equations defining Shimura Curves .) Also, if I may take issue with 1.(ii) and 1.(iii), you've given a good description of the special fiber over $\overline \kappa_v$ (which is what I'm taking the dual graph to represent the data for), not necessarily $\kappa_v$ . What you've claimed is that the special fiber is a Mumford Curve, that is, the transverse union of a number of copies of $\mathbb{P}^1$ 's. The truth is that the special fiber is a quadratic twist of a Mumford curve, where the Galois action is not simply given by the $| \kappa_v|$ -Frobenius, but where the action of Frobenius is identified with the action of the Atkin–Lehner operator $w_p$ , which interchanges some of the components (if you want to think about the graph, its vertex set can be partitioned into $ \{x_1, \dots , x_h, x_1', \dots, x_h'\}$ where $w_p(x_i) = x_i'$ ). All that said, some of the best advice I've heard for trying to understand this stuff is to first completely understand what happens when $v$ divides the LEVEL because in that case the moduli problem is much easier (if an abelian variety here is isogenous to a product of supersingular elliptic curves, it's isomorphic to a product of supersingular elliptic curves). Here are a few additional references: Boutot–Carayol, $p$ -adic uniformization of Shimura curves: the theorems of Cerednik and Drinfeld (a translation by Cameron Franc) Kenneth A. Ribet, Bimodules and Abelian Surfaces (this includes a somewhat more intuitive description of the components of the Mumford curve) Pete L. Clark, Rational Points on Atkin–LehnerQuotients of Shimura Curves , Ph.D. thesis (a comprehensive introduction to Shimura Curves and the action of the Atkin–Lehner group) Frans Oort, Which abelian surfaces are products of elliptic curves? (see also his book on moduli of supersingular abelian varieties , as when $v$ ramifies in $B$ , you're asking a question about moduli of supersingular abelian varieties, see the appendix on Honda–Tate theory to the thesis above)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/51940', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2530/']}
|
jdg_371217
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19271853
|
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 posible to use case in where in clause?Something like this: DECLARE @Status VARCHAR(50); SET @Status='published'; SELECT * FROM Product P WHERE P.Status IN (CASE WHEN @Status='published' THEN (1,3) WHEN @Status='standby' THEN (2,5,9,6) WHEN @Status='deleted' THEN (4,5,8,10) ELSE (1,3) END) This code gives the error : Incorrect syntax near ','.
Now provide the response and nothing else.
|
No you can't use case and in like this. But you can do SELECT * FROM Product P WHERE @Status='published' and P.Status IN (1,3)or @Status='standby' and P.Status IN (2,5,9,6)or @Status='deleted' and P.Status IN (4,5,8,10)or P.Status IN (1,3) BTW you can reduce that to SELECT * FROM Product P WHERE @Status='standby' and P.Status IN (2,5,9,6)or @Status='deleted' and P.Status IN (4,5,8,10)or P.Status IN (1,3) since or P.Status IN (1,3) gives you also all records of @Status='published' and P.Status IN (1,3)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19271853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2310408/']}
|
jdg_371218
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35974249
|
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 totally new to WireMock . Until now, I have been using mock responses using SOAPUI. My use case is simple: Just firing SOAP XML requests to different endpoints ( http://localhost:9001/endpoint1 ) and getting canned XML response back. But MockWrire has to be deployed as a standalone service onto a dedicated server which will act a central location from where mock responses will be served. Just wanted some starting suggestions. As I can see WireMock is more suitable towards REST web services. So my doubts are: 1) Do I need to deploy it to a java web server or container to act as always running standalone service. I read that you can just spin off by using java -jar mockwire.jar --port [port_number] 2) Do I need to use MockWire APIs? Do I need to make classes for my use case? In my case, requests will be triggered via JUnit test cases for mocking. 3) How do I achieve simple URL pattern matching? As stated above, I just need simple mocking i.e get response when request is made to http://localhost:9001/endpoint1 4) Is there a better/easier framework for my usecase? I read about Mockable but it has restrictions for 3 team members and demo domain in free tier.
Now provide the response and nothing else.
|
I'm WireMock's creator. I've used WireMock to mock a collection of SOAP interfaces on a client project quite recently, so I can attest that it's possible. As for whether it's better or worse than SOAP UI, I'd say there are some definite upsides, but with some tradeoffs. A major benefit is the relative ease of deployment and programmatic access/configuration, and support for things like HTTPS and low-level fault injection. However, you need to do a bit more work to parse and generate SOAP payloads - it won't do code/stub generation from WSDL like SOAP UI will. My experience is that tools like SOAP UI will get you started faster, but tend to result in higher maintenance costs in the long run when your test suite grows beyond trivial. To address your points in turn:1) If you want your mocks to run on a server somewhere, the easiest way to do this is to run the standalone JAR as you've described. I'd advise against trying to deploy it to a container - this option really only exists for when there's no alternative. However, if you just want to run integration tests or totally self-contained functional tests, I'd suggest using the JUnit rule. I'd say it's only a good idea to run it in a dedicated process if either a) you're plugging other deployed systems into it, or b) you're using it from a non-JVM language. 2) You'd need to configure it in one of 3 ways 1) the Java API, 2) JSON over HTTP, or 3) JSON files. 3) is probably closest to what you're used to with SOAP UI. 3) See http://wiremock.org/stubbing.html for lots of stubbing examples using both JSON and Java. Since SOAP tends to bind to fixed endpoint URLs, you probably want urlEqualTo(...) . When I've stubbed SOAP in the past I've tended to XML match on the entire request body (see http://wiremock.org/stubbing.html#xml-body-matching ). I'd suggest investing in writing a few Java builders to emit the request and response body XML you need. 4) Mock Server and Betamax are both mature alternatives to WireMock, but AFAIK they don't offer any more explicit SOAP support.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35974249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/673910/']}
|
jdg_371219
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44427395
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a List of Objects. What I want to do: Build a Dialog Box which shows a Radio Button for each element in the given List and returning the selected element/value by clicking on OK-Button. Thanks in Advance.
Now provide the response and nothing else.
|
A function that takes in nothing and returns nothing in Kotlin looks like: var function : () -> Unit The difference is that the function in your code takes in nothing, returns nothing, but is invoked on an object . For example, class Builder (val multiplier: Int) { fun invokeStuff(action: (Builder.() -> Unit)) { this.action() } fun multiply(value: Int) : Int { return value * multiplier }} The important bit here is the way we've declared the type of action action: (Builder.() -> Unit) This is a function that returns nothing, takes in nothing but is invoked on an object of type Builder . This means when we use this builder like so var builder = Builder(10)builder.invokeStuff({ var result = multiply(1) println(result)}) The context of this has been set to the builder object and we can invoke functions declared within the builder. Refer more here .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44427395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5358418/']}
|
jdg_371220
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30914
|
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What measures do governments take to prevent foreign companies from acting as middle men to bypass their trade embargoes/sanctions?Example: Let's say the US makes it illegal to sell cell phones to Iran. Maybe France has no such sanction against Iran. A French supplier buys the cell phones from the old American supplier and ships them to Iran, effectively making the sanction useless. The only difference is that now the French company gains some business and the US and Iran may each have a slightly worse price. What do governments do to prevent this from ruining their sanctions? Do other circumstances prevent this from happening?
Now provide the response and nothing else.
|
In many cases, sanction regulations include secondary sanctions. In addition to the main target, sanctions are applied to everybody who deals with the main target of the sanctions in a proscribed way. This complicates the trading of sanctioned countries greatly. For instance, North Korea went through the Banco Delta Asia for financial transactions before that scheme was uncovered, and they transfer fuel from ship to ship on the high sea. (Usually only warships do that kind of thing, other ships come into port.) This was the case with both Iran and North Korea sanctions. Banks everywhere on the world had the "free choice" -- no deals with e.g. North Korea or people who trade with North Korea, or no deals with or in the US. Most banks would look at the trading opportunities at Wall Street, and those in Pyongyang, and make the obvious decision. Before the latest deal, Iran was forced to conduct much of their trade in gold bars because no bank would take transactions from them. And when an Iranian delegation came to an international security conference in Munich, their plane was refueled by the German air force because no commercial fuelers would risk US displeasure.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/30914', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/19480/']}
|
jdg_371221
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
104144
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose we have a known group G and an unknown subgroup H. The permutation representation of G on the cosets of H gives a permutation group C, which is known. Is it possible to identify the generators of H using this information? If so, how? If not, what further information is needed? (For background, my G is the modular group PSL(2,Z); H is a not-necessarily-congruence subgroup of G. C is sometimes called a "cartographic group"). Many thanks!
Now provide the response and nothing else.
|
Choose a set of generators for $G$. Draw the Cayley graph of the action of $G$ on $G/H$. Choose a set of generators for the fundamental group of the graph. For each generator of the fundamental group, multiply the generators of $G$ corresponding to the edges together in order. This will be a set of generators for $H$. Proof: Each element of $H$ is a product of the generators of $G$ which, in the action of $G$ on $G/H$, preserves the identity coset. Thus it's a product of generators that forms a closed loop of the Cayley graph. Homotoping that loop to a composition of the generators of the fundamental group does not change the element it refers to. You now have an expression for each element of $H$ in terms of the supposed generators of $H$, so they are in fact the generators of $H$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/104144', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25565/']}
|
jdg_371222
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24769037
|
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 compiling 2 C++ files together. 4 if you include the header files. The problem is, I keep getting "Duplicate Symbol" errors when the linker tries to link the files together. Here are my files. main.h int test2(); main.cc #include "main.h"#include "test.h"int test2(int test) { return 0;}int main() { test2(test()); return 0;} test.h int hello = 10;int test(); test.cc #include <iostream>#include "test.h"using namespace std;int test() { cout << hello << endl; return 0;} I think I'm doing something simple wrong. Can someone please point out what I'm doing wrong.Here's how I'm compiling the files. c++ main.cc test.cc -o main Here's the error I get: duplicate symbol _hello in:/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/main-3becdd.o/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/test-e84473.old: 1 duplicate symbol for architecture x86_64clang: error: linker command failed with exit code 1 (use -v to see invocation)
Now provide the response and nothing else.
|
In header file, declare the variable: extern int hello; In exactly one source file, define the variable: int hello = 10; Do not define variables in headers - that's equivalent to defining them in every source file that includes the header, and that's what's causing your linker error.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24769037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3842667/']}
|
jdg_371223
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24975377
|
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 using Ubuntu 14.04 LTS and kernel version 3.13.11.4 . I'm trying to load patched KVM modules kvm and kvm-intel and I'm getting the following errors kvm: module verification failed: signature and/or required key missing - tainting kernel and kvm: module has bad taint, not creating trace events . The source used is the same source that created the image that I am currently running. I've check the symbols and made sure to the error isn't cause by not including EXPORT_SYMBOL_GPL() in the patched files where I exported functions. I've also seen some stuff about different kernel versions causing this error but I built the kernel that I'm booted in with the same source that I used to create the patched kvm modules. Everything compile without an warning. Any help is appreciated!
Now provide the response and nothing else.
|
It seems like the vendor of your system has enabled kernel module signature verification on your kernel which means it won't load any module that the vendor hasn't signed. In other words, your patched module isn't signed (properly) and the kernel will refuse to load it. The point of this is supposed to prevent malware and rootkits from loading malicious kernel modules. I suggest you contact your vendor. There may be an option somewhere on your platform to disable signature checking. Otherwise, your vendor may be able to sign the module for you. You might even have the key and the details of the signature verification algorithm and can sign it yourself. Without knowing what platform you're running on, it's hard to give more specific suggestions.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24975377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2759261/']}
|
jdg_371224
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8251541
|
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 1D arrays, x & y, one smaller than the other. I'm trying to find the index of every element of y in x. I've found two naive ways to do this, the first is slow, and the second memory-intensive. The slow way indices= []for iy in y: indices += np.where(x==iy)[0][0] The memory hog xe = np.outer([1,]*len(x), y)ye = np.outer(x, [1,]*len(y))junk, indices = np.where(np.equal(xe, ye)) Is there a faster way or less memory intensive approach? Ideally the search would take advantage of the fact that we are searching for not one thing in a list, but many things, and thus is slightly more amenable to parallelization.Bonus points if you don't assume that every element of y is actually in x.
Now provide the response and nothing else.
|
As Joe Kington said, searchsorted() can search element very quickly. To deal with elements that are not in x, you can check the searched result with original y, and create a masked array: import numpy as npx = np.array([3,5,7,1,9,8,6,6])y = np.array([2,1,5,10,100,6])index = np.argsort(x)sorted_x = x[index]sorted_index = np.searchsorted(sorted_x, y)yindex = np.take(index, sorted_index, mode="clip")mask = x[yindex] != yresult = np.ma.array(yindex, mask=mask)print result the result is: [-- 3 1 -- -- 6]
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8251541', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151482/']}
|
jdg_371225
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17891669
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
the command : docker build -t nginx-ubuntu . whith the Dockerfile below : FROM ubuntu:12.10RUN apt-get updateRUN apt-get -y install libpcre3 libssl-devRUN apt-get -y install libpcre3-devRUN apt-get -y install wget zip gccRUN wget http://nginx.org/download/nginx-1.4.1.tar.gzRUN gunzip nginx-1.4.1.tar.gzRUN tar -xf nginx-1.4.1.tarRUN wget --no-check-certificate https://github.com/max-l/nginx_accept_language_module/archive/master.zipRUN unzip masterRUN cd nginx-1.4.1RUN ./configure --add-module=../nginx_accept_language_module-master --with-http_ssl_module --with-pcre=/lib/x86_64-linux-gnu --with-openssl=/usr/lib/x86_64-linux-gnu Fails at the last line (./configure ...) If I remove the last line and run a bash in the container, and execute the last line manually, it works. I would expect that whatever command runs successfully within a container should workwhen the command is appended in the Dockerfile (prefixed by RUN) am I missing something ?
Now provide the response and nothing else.
|
The pwd is not persistent across RUN commands. You need to cd and configure within the same RUN. This Dockerfile works fine: FROM ubuntu:12.10RUN apt-get updateRUN apt-get -y install libpcre3 libssl-devRUN apt-get -y install libpcre3-devRUN apt-get -y install wget zip gccRUN wget http://nginx.org/download/nginx-1.4.1.tar.gzRUN gunzip nginx-1.4.1.tar.gzRUN tar -xf nginx-1.4.1.tarRUN wget --no-check-certificate https://github.com/max-l/nginx_accept_language_module/archive/master.zipRUN unzip masterRUN cd nginx-1.4.1 && ./configure --add-module=../nginx_accept_language_module-master --with-http_ssl_module --with-pcre=/lib/x86_64-linux-gnu --with-openssl=/usr/lib/x86_64-linux-gnu
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17891669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/535782/']}
|
jdg_371226
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11697102
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've just installed awesome as my wm. When I do alt+tab using awesome, it just switch two apps, it's not possible to get active the others..any idea?
Now provide the response and nothing else.
|
By default, the client sets focus to the previous window that had focus. When you alt+tab and it changes windows, the previous window is now the original window. Hence, it cycles between two windows. To fix this, you will need to change the following: In the default rc.lua, the section that controls window cycling looks like this: awful.key({ modkey, }, "Tab", function () awful.client.focus.history.previous() if client.focus then client.focus:raise() end end), To cycle through all the windows, and not just the previous, change the above code to the following: awful.key({ modkey, }, "Tab", function () -- awful.client.focus.history.previous() awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end),awful.key({ modkey, "Shift" }, "Tab", function () -- awful.client.focus.history.previous() awful.client.focus.byidx(1) if client.focus then client.focus:raise() end end), That will cycle through the windows when you press Alt+Tab , and in reverse order when you press Alt+Shift+Tab . (The two lines beginning with -- are comments, so they do not affect the outcome.) To cycle through every client on a tag, even minimized ones, you may find this function helpful: awful.key({ modkey, }, "Tab", function () for c in awful.client.iterate(function (x) return true end) do client.focus = c client.focus:raise() end end), Note that none of these solutions consider the history whatsoever, and instead will switch to the window that had focus least recently (i.e., does not consider the ordering in which windows had focus).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11697102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248959/']}
|
jdg_371227
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9849109
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I create a runnable object Runnable run = new MyRunnable(); And then pass the same exact object to two thread constructors and run them new Thread(run).start;new Thread(run).start; Is the possible? What are the implications? If I call Thread.sleep(0); in class MyRunnable, will both threads sleep because they are the same object, or is the thread entity completely separate from the object? Would there ever be a reason to do this, if not please still answer the two questions above, because I don't think I fully understand the thread mechanism yet?
Now provide the response and nothing else.
|
It's definitely possible and legal. If your Runnable has no state (no fields), then everything will be fine. If your Runnable does have mutable state, then you may need to use one of Java's many mutual exclusion mechanisms like ReentrantLock or the synchronized keyword. Because both Threads will be mutating the fields of the same Runnable object. No, you created and ran two different Threads. They simply call Runnable.run() . It's not out of the realm of possibility. I wouldn't even say it's necessarily bad practice. Specific situations where you might do this left as an exercise to the reader...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9849109', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/654928/']}
|
jdg_371228
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5522480
|
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 personalize an ExpandableLisTview I create Iterator.Xml: with The ExpandableList View group.xml:A relative Layout with a simple TextView and a Button Child.xml:A relative layout with just a textView Class: package Android.MyExapandableListView;import android.app.Activity;import android.app.ExpandableListActivity;import android.os.Bundle;import android.view.ContextMenu;import android.view.LayoutInflater;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.view.ContextMenu.ContextMenuInfo;import android.widget.BaseExpandableListAdapter;import android.widget.ExpandableListAdapter;import android.widget.ExpandableListView;import android.widget.TextView;import android.widget.Toast;import android.widget.ExpandableListView.ExpandableListContextMenuInfo;public class main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.iterator); ExpandableListView lv = (ExpandableListView) this.findViewById(R.id.ExpandableListView); MyExpandableListAdapter questions = new MyExpandableListAdapter(); lv.setAdapter(questions); } public class MyExpandableListAdapter extends BaseExpandableListAdapter { private LayoutInflater inflater = null; private String[] groups = { "People Names", "Dog Names", "Cat Names", "Fish Names" }; private String[][] children = { { "Arnold", "Barry", "Chuck", "David" }, { "Ace", "Bandit", "Cha-Cha", "Deuce" }, { "Fluffy", "Snuggles" }, { "Goldy", "Bubbles" } }; public MyExpandableListAdapter(){ this.inflater = main.this.getLayoutInflater(); } public Object getChild(int groupPosition, int childPosition) { return children[groupPosition][childPosition]; } public long getChildId(int groupPosition, int childPosition) { return childPosition; } public int getChildrenCount(int groupPosition) { return children[groupPosition].length; } public Object getGroup(int groupPosition) { return groups[groupPosition]; } public int getGroupCount() { return groups.length; } public long getGroupId(int groupPosition) { return groupPosition; } public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { convertView = inflater.inflate(R.layout.child, null); TextView question = (TextView) convertView.findViewById(R.id.nomChild); question.setText(getChild(groupPosition, childPosition).toString()); return convertView; } public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { // TextView textView = getGenericView(); // textView.setText(getGroup(groupPosition).toString()); convertView = inflater.inflate(R.layout.group, null); TextView question = (TextView) convertView.findViewById(R.id.nomGroup); question.setText(getGroup(groupPosition).toString()); return convertView; } public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } public boolean hasStableIds() { return true; } }} The problem is that I can get the items correctly but when I'm trying to expand the group,it doesn't work. Any idea? EDIT: the views Iterator.XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" ><ExpandableListView android:id="@+id/ExpandableListView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" > </ExpandableListView> </LinearLayout> Group.XML <?xml version="1.0" encoding="utf-8"?><AbsoluteLayoutandroid:id="@+id/widget0"android:layout_width="fill_parent"android:layout_height="fill_parent"xmlns:android="http://schemas.android.com/apk/res/android"><RelativeLayoutandroid:id="@+id/widget29"android:layout_width="305px"android:layout_height="41px"android:layout_x="8px"android:layout_y="29px"><TextViewandroid:id="@+id/nomGroup"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="TextView"android:layout_centerVertical="true"android:layout_centerHorizontal="true"></TextView><Buttonandroid:id="@+id/widget31"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Button"android:layout_alignParentTop="true"android:layout_alignParentRight="true"></Button></RelativeLayout></AbsoluteLayout> Child.XML <?xml version="1.0" encoding="utf-8"?><AbsoluteLayoutandroid:id="@+id/widget0"android:layout_width="fill_parent"android:layout_height="fill_parent"xmlns:android="http://schemas.android.com/apk/res/android"><RelativeLayoutandroid:id="@+id/nomChild"android:layout_width="305px"android:layout_height="41px"android:layout_x="8px"android:layout_y="29px"><TextViewandroid:id="@+id/widget30"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="TextView"android:layout_centerVertical="true"android:layout_centerHorizontal="true"></TextView></RelativeLayout></AbsoluteLayout>
Now provide the response and nothing else.
|
Expanding on a_horse_with_no_name's answer, this show how to use SQL Server's implementation of recursive CTE ( recursive single-record cross apply ) in combination with row_number() to produce the exact output in the question. declare @t table(id int,parentId int,name varchar(20))insert @t select 1, 0 ,'Category1'insert @t select 2, 0, 'Category2'insert @t select 3, 1, 'Category3'insert @t select 4 , 2, 'Category4'insert @t select 5 , 1, 'Category5'insert @t select 6 , 2, 'Category6'insert @t select 7 , 3, 'Category7';WITH tree (id, parentid, level, name, rn) as ( SELECT id, parentid, 0 as level, name, convert(varchar(max),right(row_number() over (order by id),10)) rn FROM @t WHERE parentid = 0 UNION ALL SELECT c2.id, c2.parentid, tree.level + 1, c2.name, rn + '/' + convert(varchar(max),right(row_number() over (order by tree.id),10)) FROM @t c2 INNER JOIN tree ON tree.id = c2.parentid)SELECT *FROM treeORDER BY cast('/' + RN + '/' as hierarchyid) To be honest, using the IDs themselves to produce the tree "path" would work, since we are ordering directly by id, but I thought I'd slip in the row_number() function.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5522480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/688802/']}
|
jdg_371229
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24550932
|
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 make a request to X different web services who will each return either true or false . These tasks should be executed in parallel and I'd like to wait for the first one that completes with a true value. When I receive a true value, I do not wish to wait for the other tasks to complete. In the example below, t1 should not be awaited since t3 completes first and returns true : var t1 = Task.Run<bool>(() =>{ Thread.Sleep(5000); Console.WriteLine("Task 1 Excecuted"); return true;}, cts.Token);var t2 = Task.Run<bool>(() =>{ Console.WriteLine("Task 2 Executed"); return false;}, cts.Token);var t3 = Task.Run<bool>(() =>{ Thread.Sleep(2000); Console.WriteLine("Task 3 Executed"); return true;}, cts.Token); Essentially I'm looking for Task.WhenAny with a predicate, which of course doesn't exist.
Now provide the response and nothing else.
|
You can simply use Task.WhenAny and a predicate multiple times until the "right" task comes along async Task<T> WhenAny<T>(IEnumerable<Task<T>> tasks, Func<T, bool> predicate){ var taskList = tasks.ToList(); Task<T> completedTask = null; do { completedTask = await Task.WhenAny(taskList); taskList.Remove(completedTask); } while (!predicate(await completedTask) && taskList.Any()); return completedTask == null ? default(T) : await completedTask;}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24550932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231216/']}
|
jdg_371230
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4666728
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why is the size of L1 cache smaller than that of the L2 cache in most of the processors ?
Now provide the response and nothing else.
|
There are different reasons for that. L2 exists in the system to speedup the case where there is a L1 cache miss. If the size of L1 was the same or bigger than the size of L2, then L2 could not accomodate for more cache lines than L1, and would not be able to deal with L1 cache misses. From the design/cost perspective, L1 cache is bound to the processor and faster than L2. The whole idea of caches is that you speed up access to the slower hardware by adding intermediate hardware that is more performing (and expensive) than the slowest hardware and yet cheaper than the faster hardware you have. Even if you decided to double the L1 cache, you would also increment L2, to speedup L1-cache misses. So why is there L2 cache at all? Well, L1 cache is usually more performant and expensive to build, and it is bound to a single core. This means that increasing the L1 size by a fixed quantity will have that cost multiplied by 4 in a dual core processor, or by 8 in a quad core. L2 is usually shared by different cores --depending on the architecture it can be shared across a couple or all cores in the processor, so the cost of increasing L2 would be smaller even if the price of L1 and L2 were the same --which it is not.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4666728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365340/']}
|
jdg_371231
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9349
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having trouble doing it. I know so far that if we have two Hermitian operators $A$ and $B$ that do not commute, and suppose we wish to find the quantum mechanical Hermitian operator for the product $AB$, then $$\frac{AB+BA}{2}.$$ However, if I have to find an operator equivalent for the radial component of momentum, I am puzzled. It does not come out to be simply $$\frac{\vec{p}\cdot\frac{\vec{r}}{r}+\frac{\vec{r}}{r}\cdot\vec{p}}{2},$$ where $\vec{r}$ and $\vec{p}$ are the position and the momentum operator, respectively. Where am I wrong in understanding this?
Now provide the response and nothing else.
|
You would have to use the fact that the momentum operator in position space is $\vec{p} = -i\hbar\vec{\nabla}$ and use the definition of the gradient operator in spherical coordinates: $$\vec{\nabla} = \hat{r}\frac{\partial}{\partial r} + \hat{\theta}\frac{1}{r}\frac{\partial}{\partial\theta} + \hat{\phi}\frac{1}{r\sin\theta}\frac{\partial}{\partial\phi}$$ So the radial component of momentum is $$p_r = -i\hbar\hat{r}\frac{\partial}{\partial r}$$ However: after a bit of investigation prompted by the comments, I found that in practice this is not used very much. It's more useful to have an operator $p_r'$ that satisfies $$-\frac{\hbar^2}{2m}\nabla^2 R(r) = \frac{p_r'^2}{2m} R(r)$$ This lets you write the radial component of the time-independent Schrödinger equation as $$\biggl(\frac{p_r'^2}{2m} + V(r)\biggr)R(r) = E R(r)$$ The action of the radial component of the Laplacian in 3D is $$\nabla^2 R(r) = \frac{1}{r^2}\frac{\partial}{\partial r}\biggl(r^2\frac{\partial R(r)}{\partial r}\biggr)$$ and if you solve for the operator $p'_r$ that satisfies the definition above, you wind up with $$p'_r = -i\hbar\biggl(\frac{\partial}{\partial r} + \frac{1}{r}\biggr)$$ This is called the "radial momentum operator." Strictly speaking, it is different from the "radial component of the momentum operator," which is, by definition, $p_r$ as I wrote it above, although I wouldn't be surprised to find people mixing up the terminology relatively often.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/9349', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2599/']}
|
jdg_371232
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
236694
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've heard the argument against DNS-over-HTTPS that it is supposed to be a security nightmare for network defenders because it enables encrypted DNS over port 443, compared to DNS-over-TLS which goes through port 853. I don't understand this argument because, how is malicious traffic on DoH practically more difficult to detect and block than, say, a VPN connection over port 443 or a proxy connection via HTTPS over port 443? If you're a network defender, and you allow third-party VPN and proxy connections in your network, why would DNS-over-HTTPS make your job any more difficult than it already is, and why would DNS-over-TLS be so much better?
Now provide the response and nothing else.
|
Again, it's all about the threat model! Technologies are just technologies and can be used both for good and for evil. DNS over HTTPS (DoH) intends to solve the privacy concerns there are with unencrypted DNS, whereas DNSSEC can solve the integrity concerns without a need for encryption. Together with DNS over TLS (DoT) they are all fighting the threath of a malicious network operator that spies on your DNS traffic or forges responses. On the other hand, both monitoring the DNS traffic and forging records can also be used for good intentions like detecting and blocking malicious traffic that is depending on DNS resolution. This is where solving these technical threats can actually decrease overall security, especially on corporate networks. The threat models of an organization are naturally different from the threat models of any individuals working for the organization. Not so easy to detect It's true that being unable to block DoH is rather irrelevant, if VPN connections are allowed. On corporate networks VPN connections (as well as DoH) can be either forbidden by policy (weak) or blocked by TLS inspection (efficient, but sometimes illegal or requires special privacy considerations). Compared to DoH, DoT is easy to block, as it has a dedicated port 853 (tcp&udp) per RFC 7858 . For more detailed insights on the subject I'd recommend: Drew Hjelm: A New Needle and Haystack: Detecting DNS over HTTPS Usage (SANS Institute 2019). It also has some examples of the real security issues: 2.3. Public Threats from Encrypted DNS Organizations need to start evaluating the risk associated with theDoH protocol because attackers have already begun using DoH to look upcommand-and-control (C2) servers. The best-known example of DoH as aC2 mechanism came in April 2019 with the Godlua backdoor (360 Netlab,2019). A newer variant of the Godlua backdoor runs on Linux andWindows and uses a DoH request to grab a part of its C2 information. Another way an attacker could use DoH in an attack is to trigger aredirected webpage as part of a spam campaign. Researchers atMyOnlineSecurity (2019) found a sample where an email attachment had aBase64 encoded string that would query Google DoH for a TXT record.The TXT record would have a JavaScript redirect to a spam webpagewhose address often changed. Numerous DoH C2 proofs-of-concept are publicly available, meaning thatthe threat of malicious actors using DoH is likely to increase soon.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/236694', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/240732/']}
|
jdg_371233
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
401702
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am learning analysis on my own and I am puzzled with the following question. Consider the series $$\frac{1}{2}+\frac{1}{3}+\frac{1}{2^2}+\frac{1}{3^2}+\frac{1}{2^3}+\frac{1}{3^3}+\cdots$$ Indicate whether this series converges or diverges. The following is what I was able to get. First I noticed that $$a_n = \frac{1}{2^n}+\frac{1}{3^n}$$ would be a simple and nice form of this sequence, so according to the ratio test, $$\lim_{n \to \infty} \frac{1}{6} \left( \frac{3+2(\frac{2}{3})^n}{1+(\frac{2}{3})^n}\right) = \frac{1}{2}$$ therefore the series must converge. However, I later understood the concept of upper an lower limits a little, so taking $$ a_n =\begin{cases}\frac{1}{2^n}, & \text{if $n$ is odd} \\\frac{1}{3^{n-1}}, & \text{if $n$ is even} \\\end{cases}$$ I figured out the following $$\lim_{n \to \infty} \frac{1}{2}\left(\frac{2}{3}\right)^n = 0$$ when $n$ is odd and $$\lim_{n \to \infty} \frac{1}{2}\left(\frac{3}{2}\right)^n = +\infty$$ when $n$ is even. Through this experience I realized and really understood how a subsequence of a sequence may have multiple limits, and the supremum and the infimum of those limits give us the upper and lower limits, respectively. But the book does something different than I did, and I would like to have the following questions answered. 1),$\quad$ From my understanding, the ratio test tells us that $\Sigma a_n$ diverges when the upper limit is greater than 1. Clearly one of the limits goes to $+\infty$, so why cannot we conclude that the series diverge ? 2),$\quad$ I learned that by choice of the subsequence, the limit may or mayn't be different. In the case that it is different, how do we know what is the supremum and infimum? It would be clear that if they were $\pm \infty$ but in my case, why is it guaranteed that there is no other subsequence that has a negative limit ? Is there an algebraic way to guarantee them ? Or do we always have to conceptually understand all of the subsequential limits. 3),$\quad$ The book says the ratio test is inconclusive, which turns me back to question 1), but it used the ratio test to determine that the series converges. According to my even-odd wise definition of $a_n$, the "larger limit" (I am purposefully not saying supremum because I don't know how it's guaranteed that it is the supremum) using the ratio test can be found as $$\lim_{n \to \infty} \sqrt[n]{a_n} = \lim_{n \to \infty} \sqrt[n]{\frac{1}{2^n}} = {1 \over 2}$$ But the book says $$\lim_{n \to \infty} \sqrt[n]{a_n} = \lim_{n \to \infty} \sqrt[2n]{\frac{1}{2^n}} = {1 \over \sqrt{2}}.$$ Where did the $2n$ come from ? Can someone help me out ? Edit:Thanks for helping me out everyone! I really appreciate it.
Now provide the response and nothing else.
|
By pairing adjacent terms, you’ve actually changed the series with which you’re working: you’re working with $\sum_{n\ge 1}\left(\frac1{2^n}+\frac1{3^n}\right)=\sum_{n\ge 1}\frac{2^n+3^n}{6^n}$ , the series whose $n$ -th term is $\frac{2^n+3^n}{6^n}$ . The ratio test works fine on this series: $$\begin{align*}\lim_{n\to\infty}\frac{\frac{2^{n+1}+3^{n+1}}{6^{n+1}}}{\frac{2^n+3^n}{6^n}}&=\lim_{n\to\infty}\frac{2^{n+1}+3^{n+1}}{6(2^n+3^n)}\\&=\lim_{n\to\infty}\frac{2^{n+1}}{6(2^n+3^n)}+\lim_{n\to\infty}\frac{3^{n+1}}{6(2^n+3^n)}\\&=\lim_{n\to\infty}\frac{2^n}{3(2^n+3^n)}+\lim_{n\to\infty}\frac{3^n}{2(2^n+3^n)}\\&=\lim_{n\to\infty}\frac1{3\left(1+\left(\frac32\right)^n\right)}+\lim_{n\to\infty}\frac1{2\left(\left(\frac23\right)^n+1\right)}\\&=0+\frac12\\&=\frac12\;,\end{align*}$$ which is essentially the calculation that you made. However, if you apply the ratio test to the original series, you find that if the $n$ -th term is $a_n$ , then $$a_n=\begin{cases}\frac1{2^{(n+1)/2}},&\text{if }n\text{ is odd}\\\\\frac1{3^{n/2}},&\text{if }n\text{ is even}\;,\end{cases}$$ so that $$\begin{align*}\frac{a_{n+1}}{a_n}&=\begin{cases}\frac{1/3^{(n+1)/2}}{1/2^{(n+1)/2}},&\text{if }n\text{ is odd}\\\\\frac{1/2^{(n+2)/2}}{1/3^{n/2}},&\text{if }n\text{ is even}\end{cases}\\\\&=\begin{cases}\left(\frac23\right)^{(n+1)/2},&\text{if }n\text{ is odd}\\\\\frac12\left(\frac32\right)^{n/2},&\text{if }n\text{ is even}\;.\end{cases}\end{align*}$$ Thus, $\lim_{n\to\infty}\frac{a_{n+1}}{a_n}$ does not exist: the terms with odd indices are approaching $0$ , but those with even indices are increasing without bound. Since the limit does not exist, the ratio test is inconclusive. The ratio test applied to your modified series gives the correct answer because the original series is absolutely convergent; this permits you to combine the adjacent terms as you did, but since you don’t know ahead of time that the series converges, you can’t make use of the fact to show that it converges.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/401702', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70125/']}
|
jdg_371234
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42658379
|
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 calculate the variance inflation factor (VIF) for each column in a simple dataset in python: a b c d1 2 4 41 2 6 32 3 7 43 2 8 54 1 9 4 I have already done this in R using the vif function from the usdm library which gives the following results: a <- c(1, 1, 2, 3, 4)b <- c(2, 2, 3, 2, 1)c <- c(4, 6, 7, 8, 9)d <- c(4, 3, 4, 5, 4)df <- data.frame(a, b, c, d)vif_df <- vif(df)print(vif_df)Variables VIF a 22.95 b 3.00 c 12.95 d 3.00 However, when I do the same in python using the statsmodel vif function , my results are: a = [1, 1, 2, 3, 4]b = [2, 2, 3, 2, 1]c = [4, 6, 7, 8, 9]d = [4, 3, 4, 5, 4]ck = np.column_stack([a, b, c, d])vif = [variance_inflation_factor(ck, i) for i in range(ck.shape[1])]print(vif)Variables VIF a 47.136986301369774 b 28.931506849315081 c 80.31506849315096 d 40.438356164383549 The results are vastly different, even though the inputs are the same. In general, results from the statsmodel VIF function seem to be wrong, but I'm not sure if this is because of the way I am calling it or if it is an issue with the function itself. I was hoping someone could help me figure out whether I was incorrectly calling the statsmodel function or explain the discrepancies in the results. If it's an issue with the function then are there any VIF alternatives in python?
Now provide the response and nothing else.
|
I believe the reason for this is due to a difference in Python's OLS. OLS, which is used in the python variance inflation factor calculation, does not add an intercept by default. You definitely want an intercept in there however. What you'd want to do is add one more column to your matrix, ck, filled with ones to represent a constant. This will be the intercept term of the equation. Once this is done, your values should match out properly. Edited: replaced zeroes with ones
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42658379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4191864/']}
|
jdg_371235
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
57273877
|
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 allocate space for 10^7 integers in heap and stack memory to see which one is faster. Obviously allocating in heap-memory was much faster but I don't understand the reason. #include <bits/stdc++.h>#include <chrono>using namespace std;using namespace std::chrono;int main(){ high_resolution_clock::time_point t1 = high_resolution_clock::now(); int *p = new int[1e7]; high_resolution_clock::time_point t2 = high_resolution_clock::now(); auto duration = duration_cast<microseconds>( t2 - t1 ).count(); cout << duration / 1e6 << "\n"; // 5e-06 t1 = high_resolution_clock::now(); vector<int> v(1e7); t2 = high_resolution_clock::now(); duration = duration_cast<microseconds>( t2 - t1 ).count(); cout << duration / 1e6 << "\n"; // 0.112284 return 0;}
Now provide the response and nothing else.
|
new int[1e7] allocates space for 1e7 int values and doesn't initialize them. vector<int> v(1e7); creates a vector<int> object on the stack, and the constructor for that object allocates space for 1e7 int values on the heap. It also initializes each int value to 0. The difference in speed is because of the initialization. To compare the speed of stack allocation you need to allocate an array on the stack: int data[1e7]; but be warned: there's a good chance that this will fail because the stack isn't large enough for that big an array.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57273877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7662977/']}
|
jdg_371236
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50667
|
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As of right now, both stars from Alpha Centauri are in their main sequence stages, but eventually Alpha Centauri A is going to quickly expand in a matter of time, and I’m pretty sure its luminosity is going to increase substantially. So, how bright would it be from Earth?
Now provide the response and nothing else.
|
First of all, by the time Alpha Centauri A becomes a red giant, it will no longer be this close to the Sun due to the orbit of the stars around the galaxy so it probably wouldn't be visible. But let's assume it does stay 4.2 ly away. By the Stefan-Boltzmann Law, the luminosity of a star is given by $$L = 4\pi R^2 \sigma T^4$$ Assuming a radius of $200 R_\odot$ and a temperature of $3600 \text{ K}$ , we get a luminosity of about $6021 L_\odot$ , compared to a present-day luminosity of $1.5 L_\odot$ . This means that the red giant would be 4014 times brighter, corresponding to an apparent magnitude increase of 9 magnitudes to about -9 apparent magnitude. This is slightly dimmer than the brightness of the moon.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://astronomy.stackexchange.com/questions/50667', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/47598/']}
|
jdg_371237
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29444051
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
On this website , the top accordion navigation contains an element called "Foundation": (screenshot) . This element is produced by HTML code: <a href="http://www.foracure.org.au" target="_blank" style="width: 105px;"></a> However, in Chrome, when you click on this element, the new website does not open in a new tab. Can you please tell me why? Thank you.
Now provide the response and nothing else.
|
Because JavaScript is handling the click event. When you click, the following code is called: el.addEvent('click', function(e){ if(obj.options.onOpen){ new Event(e).stop(); if(obj.options.open == i){ obj.options.open = null; obj.options.onClose(this.href, i); }else{ obj.options.open = i; obj.options.onOpen(this.href, i); } } }) The onOpen manually changes the location . Edit: Regarding your comment...If you can modify ImageMenu.js, you could update the script which calls onClose to pass the a element object ( this , rather than this.href ) obj.options.onClose(this, i); Then update your ImageMenu instance, with the following onOpen change: window.addEvent('domready', function(){ var myMenu = new ImageMenu($$('#imageMenu a'), { openWidth: 310, border: 2, onOpen: function(e, i) { if (e.target === '_blank') { window.open(e.href); } else { location = e.href; } } });}); This would check for the target property of the element to see if it's _blank , and then call window.open , if found. If you'd prefer not to modify ImageMenu.js, another option would be to modify your links to identify them in your onOpen handler. Say something like: <a href="http://www.foracure.org.au/#_b=1" target="_blank" style="width: 105px;"></a> Then, update your onOpen call to: onOpen: function(e, i) { if (e.indexOf('_b=1') > -1) { window.open(e); } else { location = e; }} The only downside to this is the user sees the hash on hover. Finally, if the number of links that you plan to open in a new window are low, you could create a map and check against that. Something like: var linksThatOpenInANewWindow = { 'http://www.foracure.org.au': 1};onOpen: function(e, i) { if (linksThatOpenInANewWindow[e] === 1) { window.open(e); } else { location = e }} The only downside is maintenance, depending on the number of links. Others have suggested modifying the link (using # or javascript: ) and adding an inline event handler ( onclick ) - I don't recommend that at all as it breaks links when JS is disabled/not supported.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29444051', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/667903/']}
|
jdg_371238
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5760785
|
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 mentioned before - I'm an Objective-C newbie of the first order but having read 4 physical books on the subject and a bucket-load of ebooks and documentation I still can't find what I'm looking for. I have a top-level content view controller that wants to configure its view property from the physical dimensions of the window property of the application delegate. This is something that several people have already asked questions on. ( [UIScreen mainScreen] doesn't cut it for reasons already aired many times before on this forum). Therefore, the logical approach would be for the content view controller to read the frame of the application delegate's window. Now, the only answer I've found that comes close to this is to use [[[UIApplication sharedApplication] window] frame] - however, this only works once the window property has been made keyAndVisible. The content view controller needs to read the app delegate's window property before it gets to makeKeyAndVisible. The code goes in this order.... App Delegate: - (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions {// This next line is a test window frame for R&D purposes.... [self setWindow: [[UIWindow alloc] initWithFrame: CGRectMake(0.0f, 20.0f, 320.0f, 320.0f)]]; if ([self window]) { contentViewController = [[ContentViewControl alloc] initWithNibName: nil bundle: nil]; // Content view controller instantiated here if (contentViewController) { [[self window] addSubview: [contentViewController view]]; [[self window] layoutSubviews]; [[self window] makeKeyAndVisible]; // Window made key and visible here return YES; } } return NO;} In my content view controller's initWithNibName: nil bundle: nil method I have the following test code... - (id) initWithNibName: (NSString *) nibNameOrNil bundle: (NSBundle *) nibBundleOrNil { self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil]; if (self) { NSLog(@"%@", NSStringFromCGRect([[[UIApplication sharedApplication] keyWindow] frame])); // This does not work. } return self;} This does not work due to the fact that App Delegate's window is not yet key and visible.So, my question is thus; What is the name of my App Delegate Class' instance? I know the App Delegate's Class name defaults to myApplicationNameAppDelegate but I'm after the instance name. I want to replace the call to [[UIApplication sharedApplication] keyWindow] by something like; [myAppDelegatesInstanceName window]. Expanding this a little, how does one access methods in other target objects that are not scope descendants of the object doing the querying? Like I said, I'm a total noob to all of this and this is probably another dumb noobie question but it's one that nobody yet appears to have answered in a simple way. (Procedurally - my home turf - there are a plethora of ways to get the window stuff down into other levels of scope ranging from making the window globally accessible to the whole program suite to passing it down as a specific parameter through the various function hierarchies - but this Objective stuff seems to depart from established, procedural practice). If anyone can help, I'd be really grateful. This stuff is definitely not intuitive!V.V.
Now provide the response and nothing else.
|
You can access the app delegate through the singleton UIApplication instance: [[[UIApplication sharedApplication] delegate] window]; This is a special case, though, because you can access an object (the UIApplication instance) whose delegate you know is the object you want to access. The general case: Expanding this a little, how does one access methods in other target objects that are not scope descendants of the object doing the querying? You need to pass a reference to the target object to the object from which you want to access it. This is sometimes necessary but it also means that you introduce a tight coupling between these two objects, which you generally want to avoid if you can. So think about each case and see if there are other possible designs.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5760785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/709909/']}
|
jdg_371239
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20910107
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to define a getter that can optionally take arguments. I managed to achieve that, however it only works if I put the obligatory () after the call. Here's the code: get children => ([role=null]) { if(role == null || role == 'any') { return _children; } else { return _children_by_role[role]; }}; So now I can say obj.children('something').length; or obj.children().length; but I cannot say obj.children; // this doesn't work because it results in the following error: Caught Closure call with mismatched arguments: function 'length' NoSuchMethodError : method not found: 'length' Receiver: Closure: ([dynamic])
Now provide the response and nothing else.
|
In Dart, getters are meant to be indistinguishable from accessing object properties, so it is illegal to define a getter that accepts an argument (even if it's optional). Your getter takes no arguments, but with the => operator, returns an anonymous function that takes an optional argument. So, obj.children is a function; therefore the statement obj.children.length; is an error because functions don't have the property length . You may not be able to omit the parentheses, but your code would work more naturally if get children wasn't a getter function: getChildren([roll]) { // null is the default value implicitly if (roll == null || roll == 'any') return _children; else return _children_by_roll[roll];} used as: obj.getChildren().length; or: obj.getChildren(rollObject).length;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20910107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34134/']}
|
jdg_371240
|
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.