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
17481716
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: During development, how our local WAMP servers get up-to-date data from the test server is that a dump of the database is made and we upload that dump using the source command to load the .sql file. Recently, at the very end of the import we have been getting errors about the @old variables which stored the original settings like foreign key constraints before they’re changed (so turning off foreign key constraints so that the import doesn’t throw errors when it recreates tables and attempts to create foreign keys when one of the tables has yet to be created). I have worked out that the cause is that the product table is getting more and more data and at a point the session has timed out during the import. I’m wondering what setting can I set (either as part of the SQL query on in the my.ini file) that will stop all timeouts, in effect making a session last forever while we are signed in. Now provide the response and nothing else.
Strategies for importing large MySQL databases PHPMyAdmin Import Chances are if you’re reading this, PHPMyAdmin was not an option for your large MySQL database import. Nonetheless it is always worth a try, right? The most common cause of failure for PHPMyAdmin imports is exceeding the import limit. If you’re working locally or have your own server, you can try changing the MySQL ini settings usually found in the my.ini file located in the MySQL install folder. If you’re working with WAMP on Windows, you can access that file using the WAMP control panel under MySQL > my.ini. Remember to restart WAMP so your new settings will be used. Settings you may want to increase here include: max_allowed_packetread_buffer_size Even with enhanced MySQL import settings you may still find that imports time out due to PHP settings. If you have access to PHP.ini, you can make edits to the maximum execution time and related settings. In WAMP, access the PHP.ini file under the WAMP control panel at PHP > php.ini. Consider raising the limits on the following settings while trying large MySQL imports: max_execution_timemax_input_timememory_limit Using Big Dump staggered MySQL dump importer If basic PHPMyAdmin importing does not work, you may want to try the Big Dump script from Ozerov.de for staggered MySQL imports. What this useful script does is run your import in smaller blocks, which is exactly what is often needed to successfully import a large MySQL dump. It is a free download available at http://www.ozerov.de/bigdump/ . The process of using Big Dump is fairly simple: you basically position your SQL import file and the Big Dump script together on the server, set a few configs in the Big Dump script and then run the script. Big Dump handles the rest! One key point about this otherwise great option, is that it will not work at all on MySQL exports that contain extended inserts. So if you have the option to prevent extended inserts, try it. Otherwise you will have to use another method for importing your large MySQL file. Go command line with MySQL console If you’re running WAMP (and even if you’re not) there is always the option to cut to the chase and import your large MySQL database using the MySQL console. I’m importing a 4GB database this way as I write this post. Which is actually why I have some time to spend writing, because even this method takes time when you have a 4GB SQL file to import! Some developers (usually me) are intimidated by opening up a black screen and typing cryptic commands into it. But it can be liberating, and when it comes to MySQL databases it often the best route to take. In WAMP we access the MySQL console from the WAMP control panel at MySQL > MySQL Console. Now let’s learn the 2 simple MySQL Console commands you need to import a MySQL database, command-line style: use `db_name` Command use followed by the database name will tell the MySQL console which database you want to use. If you have already set up the database to which you are importing, then you start by issuing the use command. Suppose your database is named my_great_database . In this case, issue the following command in the MySQL Console. Note that commands must end with a semi-colon. mysql-> use my_great_database;mysql-> source sql_import_file.sql Command source followed by the location of a SQL file will import the SQL file to the database you previously specified with the use command. You must provide the path, so if you’re using WAMP on your local server, start by putting the SQL file somewhere easy to get at such as C:\sql\my_import.sql. The full command with this example path would be: mysql-> source C:\sql\my_import.sql; After you run that command, the SQL file should begin to be imported. Let the queries run and allow the import to complete before closing the MySQL console. Further documentation for MySQL command line can be found here: http://dev.mysql.com/doc/refman/5.5/en/mysql.html . Another solution is to use MySQL Workbench .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17481716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1028804/']}
jdg_85141
stackexchange
llm_judgeable_groundtruth_similarity
52534910
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems import x = require('x') is an invalid syntax in es6, and there is no clear explanation in typescript documentation. Now provide the response and nothing else.
Q1: import … = require(…) versus const … = require(…) At runtime (or once the code is compiled), there is no difference between the two syntaxes, the first one is converted to the second one. With import : import x = require('x') This syntax is specific to TypeScript. The constant x is of type given by some typing defined in the imported package or in a package @types/x . With const : const x = require('x') This is a valid syntax in JavaScript and of course in TypeScript. In TypeScript, the constant x is of type any . Q2: import … from … versus import … = require(…) How about difference between import x from 'x' and import x = require('x') The syntax import … from … is from the ES6 standard. I suggest to read this introduction to ES6 modules and how to import and export them. But, in short, the syntax import x from 'x' is equivalent to: import x = require('x').default (Notice the .default member.) How to convert import … = require(…) to the ES6 syntax The ES6 standard states that all exported members can be imported into a single "namespace object module" . Then the closest standard syntax of import x = require('x') is: import * as x from 'x' This syntax currently works well with the TypeScript transpilation because the code is converted to a const … = require(…) . However: This syntax should be used only in the context defined by the standard. Because, when your code will use a native version of ES6 modules, you won't be able to import a function or a class that way .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52534910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/351545/']}
jdg_85142
stackexchange
llm_judgeable_groundtruth_similarity
27382147
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 ListView inside a PopupWindow, and I want to click on the second item on the list. I've tried the following: // Open the popupwindowonView(withId(R.id.popupwindow_open)).perform(click()); And now that the popup window appears, I tried: onData(anything()).inAdapterView(withContentDescription("delete")).atPosition(1).perform( click()); or this: onView(withContentDescription("delete"))).perform(click()); But I always get that the view isn't found. How can I do this in Espresso? Now provide the response and nothing else.
The Android System Popups and Alerts are displayed in a different window. So, you have to try to find the view in that particular window rather than the main activity window. Espresso provides a convenient method to find the root view for popup windows. Try this. onView(ViewMatchers.withContentDescription("delete")) .inRoot(RootMatchers.isPlatformPopup()) .perform(ViewActions.click());
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27382147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4340737/']}
jdg_85143
stackexchange
llm_judgeable_groundtruth_similarity
1085464
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 validate string containing only numbers. Easy validation? I added RegularExpressionValidator, with ValidationExpression="/d+". Looks okay - but nothing validated when only space is entered! Even many spaces are validated okay. I don't need this to be mandatory. I can trim on server, but cannot regular expression do everything! Now provide the response and nothing else.
This is by design and tends to throw many people off. The RegularExpressionValidator does not make a field mandatory and allows it to be blank and accepts whitespaces. The \d+ format is correct. Even using ^\d+$ will result in the same problem of allowing whitespace. The only way to force this to disallow whitespace is to also include a RequiredFieldValidator to operate on the same control. This is per the RegularExpressionValidator documentation , which states: Validation succeeds if the input control is empty. If a value is required for the associated input control, use a RequiredFieldValidator control in addition to the RegularExpressionValidator control. A regular expression check of the field in the code-behind would work as expected; this is only an issue with the RegularExpressionValidator. So you could conceivably use a CustomValidator instead and say args.IsValid = Regex.IsMatch(txtInput.Text, @"^\d+$") and if it contained whitespace then it would return false. But if that's the case why not just use the RequiredFieldValidator per the documentation and avoid writing custom code? Also a CustomValidator means a mandatory postback (unless you specify a client validation script with equivalent javascript regex).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1085464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/129193/']}
jdg_85144
stackexchange
llm_judgeable_groundtruth_similarity
41672
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: Was the Irish backstop asked for by the UK Government or was it was it an imposition by the EU? Now provide the response and nothing else.
It was a bit of both. The EU insisted, from the earliest hours, on avoiding a hard border between Ireland and Northern Ireland. Moreover, its position at the time was that under no circumstances should the whole of the UK be subjected to the same. There were a few back and forth conversations that eventually led to the joint declaration in December 2017 to that effect. The commentary at the time from observers on both sides of the Channel was that this meant Northern Ireland would remain aligned with the EU for all practical intents, and I'd wager as an opinion that this registered on the UK government's end too but for political posturing reasons they didn't shout it right left and center. At any rate, when the EU published its draft legislation on what this meant the UK government finally took a public position and said that it was unacceptable . The DUP, of course, would have none of it either -- on the basis that this would put the Union in jeopardy. From that point onward, from the public viewpoint at least (many points were agreed upon in the background while the political theatrics were in full swing), the negotiation revolved around the Irish backstop and ways to work around it or avoid it. To May's credit, the EU eventually dropped its redline and agreed that the whole of the UK could be subjected to the Irish backstop legalese, rather than just Northern Ireland. Just to be clear here, this was a major concession and May deserves credit for getting it. As an outside observer, I sincerely hope that history books will be kind to her in the sense that she was stuck between a rock and a hard place, and she basically achieved the impossible by getting that concession in Nov 2018. The result of that concession was a backstop that applied to the UK as a whole, which is what your question is about. So... no, the Irish backstop wasn't the UK's idea... but it kind of was in that it agreed with it in principle... and then definitely yes, in that it insisted that the backstop apply to the UK as a whole.
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/41672', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/6116/']}
jdg_85145
stackexchange
llm_judgeable_groundtruth_similarity
44791224
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: for visual reference please click on this image: https://i.gyazo.com/d17f94a4cf87dfb555780717773f49b3.jpg I am trying to get the text shown in the picture to be right next to its respective picture, they are all "h2" elements. Both the img and h2 elements are stored inside of an un-ordered list. The html looks roughly like this with some basic resizing CSS: #container{ margin:auto; width:70%; height: 100%; border: 3px solid green; padding:10px;}img{ height: 40%; width: 40%;}h1{ text-align: center;}h2{ text-align: right;}<nav> <div id ="container"> <ul id = "list"> img1 title1 img2 title2 </ul> </div> To reiterate, how can I get the titles to be to the side of the images. Also, is it possible to put a different colored background to distinguish between two separate images in the list and alternate between something like light gray and blue? Now provide the response and nothing else.
If you don't need the CSV in memory, just copying from input to output, it'll be a lot cheaper to avoid parsing at all, and copy without building up in memory: import shutilimport glob#import csv files from folderpath = r'data/US/market/merged_data'allFiles = glob.glob(path + "/*.csv")allFiles.sort() # glob lacks reliable ordering, so impose your own if output order matterswith open('someoutputfile.csv', 'wb') as outfile: for i, fname in enumerate(allFiles): with open(fname, 'rb') as infile: if i != 0: infile.readline() # Throw away header on all but first file # Block copy rest of file from input to output without parsing shutil.copyfileobj(infile, outfile) print(fname + " has been imported.") That's it; shutil.copyfileobj handles efficiently copying the data, dramatically reducing the Python level work to parse and reserialize. Don't omit the `allFiles.sort()!† This assumes all the CSV files have the same format, encoding, line endings, etc., the encoding encodes such that newlines appear as a single byte equivalent to ASCII \n and it's the last byte in the character (so ASCII and all ASCII superset encodings work, as does UTF-16-BE and UTF-32-BE, but not UTF-16-LE and UTF-32-LE) and the header doesn't contain embedded newlines, but if that's the case, it's a lot faster than the alternatives. For the cases where the encoding's version of a newline doesn't look enough like an ASCII newline, or where the input files are in one encoding, and the output file should be in a different encoding, you can add the work of encoding and decoding without adding CSV parsing/serializing work, with (adding a from io import open if on Python 2, to get Python 3-like efficient encoding-aware file objects, and defining known_input_encoding to some string representing the known encoding for input files, e.g. known_input_encoding = 'utf-16-le' , and optionally a different encoding for output files): # Other imports and setup code prior to first with unchanged from before# Perform encoding to chosen output encoding, disabling line-ending # translation to avoid conflicting with CSV dialect, matching raw binary behaviorwith open('someoutputfile.csv', 'w', encoding=output_encoding, newline='') as outfile: for i, fname in enumerate(allFiles): # Decode with known encoding, disabling line-ending translation # for same reasons as above with open(fname, encoding=known_input_encoding, newline='') as infile: if i != 0: infile.readline() # Throw away header on all but first file # Block copy rest of file from input to output without parsing # just letting the file object decode from input and encode to output shutil.copyfileobj(infile, outfile) print(fname + " has been imported.") This is still much faster than involving the csv module, especially in modern Python (where the io module has undergone greater and greater optimization, to the point where the cost of decoding and reencoding is pretty minor, especially next to the cost of performing I/O in the first place). It's also a good validity check for self-checking encodings (e.g. the UTF family) even if the encoding is not supposed to change; if the data doesn't match the assumed self-checking encoding, it's highly unlikely to decode validly, so you'll get an exception rather than silent misbehavior. Because some of the duplicates linked here are looking for an even faster solution than copyfileobj , some options: The only succinct, reasonably portable option is to continue using copyfileobj and explicitly pass a non-default length parameter, e.g. shutil.copyfileobj(infile, outfile, 1 << 20) ( 1 << 20 is 1 MiB, a number which shutil has switched to for plain shutil.copyfile calls on Windows due to superior performance). Still portable, but only works for binary files and not succinct, would be to copy the underlying code copyfile uses on Windows, which uses a reusable bytearray buffer with a larger size than copyfileobj 's default (1 MiB, rather than 64 KiB), removing some allocation overhead that copyfileobj can't fully avoid for large buffers. You'd replace shutil.copyfileobj(infile, outfile) with (3.8+'s walrus operator, := , used for brevity) the following code adapted from CPython 3.10's implementation of shutil._copyfileobj_readinto (which you could always use directly if you don't mind using non-public APIs): buf_length = 1 << 20 # 1 MiB buffer; tweak to preference# Using a memoryview gets zero copy performance when short reads occurwith memoryview(bytearray(buf_length)) as mv: while n := infile.readinto(mv): if n < buf_length: with mv[:n] as smv: outfile.write(smv) else: outfile.write(mv) Non-portably, if you can (in any way you feel like) determine the precise length of the header, and you know it will not change by even a byte in any other file, you can write the header directly, then use OS-specific calls similar to what shutil.copyfile uses under the hood to copy the non-header portion of each file, using OS-specific APIs that can do the work with a single system call (regardless of file size) and avoid extra data copies (by pushing all the work to in-kernel or even within file-system operations, removing copies to and from user space) e.g.: a. On Linux kernel 2.6.33 and higher (and any other OS that allows the sendfile(2) system call to work between open files), you can replace the .readline() and copyfileobj calls with: filesize = os.fstat(infile.fileno()).st_size # Get underlying file's sizeos.sendfile(outfile.fileno(), infile.fileno(), header_len_bytes, filesize - header_len_bytes) To make it signal resilient, it may be necessary to check the return value from sendfile , and track the number of bytes sent + skipped and the number remaining, looping until you've copied them all (these are low level system calls, they can be interrupted). b. On any system Python 3.8+ built with glibc >= 2.27 (or on Linux kernel 4.5+), where the files are all on the same filesystem, you can replace sendfile with copy_file_range : filesize = os.fstat(infile.fileno()).st_size # Get underlying file's sizeos.copy_file_range(infile.fileno(), outfile.fileno(), filesize - header_len_bytes, header_len_bytes) With similar caveats about checking for copying fewer bytes than expected and retrying. c. On OSX/macOS, you can use the completely undocumented, and therefore even less portable/stable API shutil.copyfile uses, posix._fcopyfile for a similar purpose, with something like (completely untested, and really, don't do this; it's likely to break across even minor Python releases): infile.seek(header_len_bytes) # Skip past headerposix._fcopyfile(infile.fileno(), outfile.fileno(), posix._COPYFILE_DATA) which assumes fcopyfile pays attention to the seek position (docs aren't 100% on this) and, as noted, is not only macOS-specific, but uses undocumented CPython internals that could change in any release. † An aside on sorting the results of glob : That allFiles.sort() call should not be omitted; glob imposes no ordering on the results, and for reproducible results, you'll want to impose some ordering (it wouldn't be great if the same files, with the same names and data, produced an output file in a different order simply because in-between runs, a file got moved out of the directory, then back in, and changed the native iteration order). Without the sort call, this code (and all other Python+glob module answers) will not reliably read from a directory containing a.csv and b.csv in alphabetical (or any other useful) order; it'll vary by OS, file system, and often the entire history of file creation/deletion in the directory in question. This has broken stuff before in the real world, see details at A Code Glitch May Have Caused Errors In More Than 100 Published Studies .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44791224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8133186/']}
jdg_85146
stackexchange
llm_judgeable_groundtruth_similarity
1714405
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 creating a custom UISlider to test out some interface ideas. Mostly based around making the thumb image larger. I found out how to do that, like so: UIImage *thumb = [UIImage imageNamed:@"newThumbImage_64px.png"]; [self.slider setThumbImage:thumb forState:UIControlStateNormal]; [self.slider setThumbImage:thumb forState:UIControlStateHighlighted]; [thumb release]; To calculate a related value I need to know where the center point of the thumb image falls when it's being manipulated. And the point should be in it's superview's coordinates. Looking at the UISlider docs, I didn't see any property that tracked this. Is there some easy way to calculate this or can it be derived from some existing value(s)? Now provide the response and nothing else.
This will return the correct X position of center of thumb image of UISlider in view coordinates: - (float)xPositionFromSliderValue:(UISlider *)aSlider { float sliderRange = aSlider.frame.size.width - aSlider.currentThumbImage.size.width; float sliderOrigin = aSlider.frame.origin.x + (aSlider.currentThumbImage.size.width / 2.0); float sliderValueToPixels = (((aSlider.value - aSlider.minimumValue)/(aSlider.maximumValue - aSlider.minimumValue)) * sliderRange) + sliderOrigin; return sliderValueToPixels;} Put it in your view controller and use it like this: (assumes property named slider) float x = [self xPositionFromSliderValue:self.slider];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1714405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23973/']}
jdg_85147
stackexchange
llm_judgeable_groundtruth_similarity
54242775
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I use Angular 7 and I would like have a button for put my app in fullscreen. I use the HTML5 Fullscreen API and I've make 2 functions : openfullscreen() { // Trigger fullscreen console.log('gg'); if (document.documentElement.requestFullscreen) { document.documentElement.requestFullscreen(); } else if (document.documentElement.mozRequestFullScreen) { /* Firefox */ document.documentElement.mozRequestFullScreen(); } else if (document.documentElement.webkitRequestFullscreen) { /* Chrome, Safari and Opera */ document.documentElement.webkitRequestFullscreen(); } else if (document.documentElement.msRequestFullscreen) { /* IE/Edge */ document.documentElement.msRequestFullscreen(); } this.isfullscreen = true; } closefullscreen(){ if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { /* Firefox */ document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */ document.webkitExitFullscreen(); } else if (document.msExitFullscreen) { /* IE/Edge */ document.msExitFullscreen(); } this.isfullscreen = false; } It worked in the beginning but I had a lot of error : error TS2339: Property 'mozRequestFullScreen' does not exist on type 'HTMLElement'. error TS2339: Property 'mozRequestFullScreen' does not exist on type 'HTMLElement'. error TS2339: Property 'webkitRequestFullscreen' does not exist on type 'HTMLElement'. error TS2339: Property 'webkitRequestFullscreen' does not exist on type 'HTMLElement'. error TS2551: Property 'msRequestFullscreen' does not exist on type 'HTMLElement'. Did you mean 'requestFullscreen'? error TS2551: Property 'msRequestFullscreen' does not exist on type 'HTMLElement'. Did you mean 'requestFullscreen'? error TS2339: Property 'mozCancelFullScreen' does not exist on type 'Document'. error TS2339: Property 'mozCancelFullScreen' does not exist on type 'Document'. error TS2339: Property 'webkitExitFullscreen' does not exist on type 'Document'. error TS2339: Property 'webkitExitFullscreen' does not exist on type 'Document'. error TS2551: Property 'msExitFullscreen' does not exist on type 'Document'. Did you mean 'exitFullscreen'? error TS2551: Property 'msExitFullscreen' does not exist on type 'Document'. Did you mean 'exitFullscreen'? When I restart my code I've the same errors but, in addition, I've that : Failed to compile. And my app don't work. How I can compile without errors? Now provide the response and nothing else.
You can tell typescript about the methods that you're going to use by using the as keyword to cast the interface of document and document.documentElement . Like this: const docElmWithBrowsersFullScreenFunctions = document.documentElement as HTMLElement & { mozRequestFullScreen(): Promise<void>; webkitRequestFullscreen(): Promise<void>; msRequestFullscreen(): Promise<void>;};const docWithBrowsersExitFunctions = document as Document & { mozCancelFullScreen(): Promise<void>; webkitExitFullscreen(): Promise<void>; msExitFullscreen(): Promise<void>;}; Please note that this just prevents compile error and you still should check if the methods exist like you did. So your methods will be like this: openfullscreen() { // Trigger fullscreen const docElmWithBrowsersFullScreenFunctions = document.documentElement as HTMLElement & { mozRequestFullScreen(): Promise<void>; webkitRequestFullscreen(): Promise<void>; msRequestFullscreen(): Promise<void>; }; if (docElmWithBrowsersFullScreenFunctions.requestFullscreen) { docElmWithBrowsersFullScreenFunctions.requestFullscreen(); } else if (docElmWithBrowsersFullScreenFunctions.mozRequestFullScreen) { /* Firefox */ docElmWithBrowsersFullScreenFunctions.mozRequestFullScreen(); } else if (docElmWithBrowsersFullScreenFunctions.webkitRequestFullscreen) { /* Chrome, Safari and Opera */ docElmWithBrowsersFullScreenFunctions.webkitRequestFullscreen(); } else if (docElmWithBrowsersFullScreenFunctions.msRequestFullscreen) { /* IE/Edge */ docElmWithBrowsersFullScreenFunctions.msRequestFullscreen(); } this.isfullscreen = true;}closefullscreen(){ const docWithBrowsersExitFunctions = document as Document & { mozCancelFullScreen(): Promise<void>; webkitExitFullscreen(): Promise<void>; msExitFullscreen(): Promise<void>; }; if (docWithBrowsersExitFunctions.exitFullscreen) { docWithBrowsersExitFunctions.exitFullscreen(); } else if (docWithBrowsersExitFunctions.mozCancelFullScreen) { /* Firefox */ docWithBrowsersExitFunctions.mozCancelFullScreen(); } else if (docWithBrowsersExitFunctions.webkitExitFullscreen) { /* Chrome, Safari and Opera */ docWithBrowsersExitFunctions.webkitExitFullscreen(); } else if (docWithBrowsersExitFunctions.msExitFullscreen) { /* IE/Edge */ docWithBrowsersExitFunctions.msExitFullscreen(); } this.isfullscreen = false;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54242775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10343053/']}
jdg_85148
stackexchange
llm_judgeable_groundtruth_similarity
230903
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am completely new to mathematica. I am not sure how to calculate the expression 2F1. Is it possible to a closed form solution in terms of z of the hypergeometric series 2F1(-a, N/2-a, N/2; z) and 2F1(1-a, N/2-a, 1+N/2; z) when N>2a and N is any positive natural number. Now provide the response and nothing else.
If you use the Finite Element Method, no flux is the default boundary condition, so there is no need to specify. An alternative to Daniel's answer would be: (* Define parameters *)l = 6;tend = 0.1;parms = {d -> 2, da -> 5.5, h -> 0.5, k -> 0.5, x0 -> 0.2};(* Create Parametric PDE operators for n and a *)parmnop = D[n[t, x], t] - d D[n[t, x], x, x] + x0 D[n[t, x] D[a[t, x], x], x];parmaop = D[a[t, x], t] - da D[a[t, x], x, x] + k a[t, x] - h n[t, x];(* Setup PDE System *)pden = (parmnop == 0) /. parms;pdea = (parmaop == 0) /. parms;icn = n[0, x] == Exp[-x^2];ica = a[0, x] == Cos[π x];(* Solve System *){nif, aif} = NDSolveValue[{pden, pdea, icn, ica}, {n, a}, {t, 0, tend}, {x, -l, l}, Method -> {"MethodOfLines", "SpatialDiscretization" -> {"FiniteElement", "MeshOptions" -> MaxCellMeasure -> 0.1}}];(* Display results *)Manipulate[ Plot[{nif[t, x], aif[t, x]}, {x, -l, l}, PlotRange -> All], {t, 0, tend}, ControlPlacement -> Top]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/230903', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/74828/']}
jdg_85149
stackexchange
llm_judgeable_groundtruth_similarity
121293
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to write a Bash script to convert every .pdf filein the current directory into a .png file. For example: $ls .a.pdf b.pdf$./pdf2png.shConverting pdfs to pngsa.pdf -> a.pngb.pdf -> b.png This is my best attempt: #!/bin/bashconvert -verbose -density 500 -resize '800' a.pdf a.pngconvert -verbose -density 500 -resize '800' b.pdf b.png Now provide the response and nothing else.
If you have really strange names, ones that contain newlines or backslashes and the like, you could do something like this: find . -type f -name '*.pdf' -print0 | while IFS= read -r -d '' file do convert -verbose -density 500 -resize 800 "${file}" "${file%.*}.png" done That should be able to deal with just about anything you throw at it. Tricks used: find ... -print0 : causes find to print its results separated by the null character, let's us deal with newlines. IFS= : this will disable word splitting, needed to deal with white space. read -r : disables interpreting of backslash escape characters, to deal with files that contain backslashes. read -d '' : sets the record delimiter to the null character, to deal with find's output and correctly handle file names with newline characters. ${file%.*}.png : uses the shell's inbuilt string manipulation abilities to remove the extension.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/121293', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/55996/']}
jdg_85150
stackexchange
llm_judgeable_groundtruth_similarity
9040
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am tackling the halting problem right now and its remarkable theorem. My book states $\text{HALT}(x,y)$ is true if $\psi^{(1)}_{\mathcal P}$ is defined and conversely $\text{HALT}(x,y)$ is false if $\psi^{(1)}_{\mathcal P}$ is undefined. The purpose of the theorem, of course, is showing that $\text{HALT}(x,y)$ is a not computable predicate. I will report the extract of the proof given: Suppose $\text{HALT}(x,y)$ were computable. Then we could construct the program $\mathcal P$: $$[A]\;\;\;\;\;\text{IF HALT}(X,X)\text{ GOTO } A$$ It is quite clear that $\mathcal P$ has been constructed so that \begin{equation}\psi^{(1)}_{\mathcal P}=\begin{cases}\text{undefined} \;\;\; \text{if HALT}(x,x) \\0 \;\;\;\;\;\;\;\;\;\;\;\;\;\;\text{if ~HALT}(x,x)\end{cases}\end{equation} I don't understand how $\psi^{(1)}_{\mathcal P}$ is undefined if $\text{HALT}(x,x)$ is true, shouldn't $Y$ be equal to $0$ by default and moreover how could a non-terminating program be defined can have $0$ as output value. What am I missing here? Edit : $\psi^{(1)}_{\mathcal P}(x)$ is the value of the output variable $Y$ at the terminal snapshot. Now provide the response and nothing else.
Let's walk through the proof given by [Davis94]. I am familiar with this text and have it in front of me. The HALT predicate is defined: $$HALT(x,y) \Longleftrightarrow \text{program number $y$ eventually halts on input $x$.}$$ Given this defintion of HALT, don't worry about how such a program would be defined. It is not important. Just assume that HALT exists, that it works, and that this is what it does: It uses $y$ (a Gödel number -- see Section 8 of Ch. 3) which represents a particular program, and $x$, an input to that program, and tells us if that program halts when it is run with that input. It can do this for any program, with any input. Now, let's define a new program called $P$: $$[A]~\text{IF}~HALT(X,X)~\text{GOTO A}$$ Look at how we are using HALT here: we are asking "Does program X halt when given an input of X (itself)?" And if it does halt, we loop infinitely -- creating a program that does not terminate -- a program that does not halt. In other words: $$\psi_P^{(1)}(x) =\begin{cases}\text{undefined} & \text{if} & ~~~~HALT(x,x) \\0 & \text{if} & \sim HALT(x,x)\end{cases}$$ Let's pause and answer your first question about $\psi_P^{(m)}$ being undefined: this is part of the definition given in Section 4 of Chapter 2: $\psi_P^{(m)}(r_1,...,r_m)$ is undefined if $P$ never terminates. And our program never terminates when $HALT(x,x)$ is true because we have written it that way, it loops infinitely. As to your second question about the default output of 0: this happens when the program $P$ does terminate. Now let the Gödel number of our new program $P$ be $y_0$. This means that $$HALT(x,y_0) \Longleftrightarrow ~ \sim HALT(x,x).$$ (we are taking the left side from the definition of HALT and the right side from our program $P$). Since this is true for any input $x$ we could also write: $$HALT(y_0,y_0) \Longleftrightarrow ~ \sim HALT(y_0,y_0),$$ which is clearly a contradiction; HALT cannot exist.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/9040', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/2778/']}
jdg_85151
stackexchange
llm_judgeable_groundtruth_similarity
19236748
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 seen several places that have simply stated that it's known that P is a subset of the intersection of NP and co-NP. Proofs that show that P is a subset of NP are not hard to find. So to show that it's a subset of the intersection, all that's left to be done is show that P is a subset of co-NP. What might a proof of this be like? Thank you much! Now provide the response and nothing else.
The class P is closed under complementation: if L is a language in P , then the complement of L is also in P . You can see this by taking any polynomial-time decider for L and switching the accept and reject states; this new machine now decides the complement of L and does so in polynomial time. A language L is in co- NP iff its complement is in NP . So consider any language L ∈ P . The complement of L is also in P , so the complement of L is therefore in NP (because P ⊆ NP ). Therefore, L is in co- NP . Consequently, P ⊆ co- NP . Hope this helps!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19236748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1191087/']}
jdg_85152
stackexchange
llm_judgeable_groundtruth_similarity
98105
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 way I understand things, roughly speaking, the importance of smooth manifolds is that they form the category of topological spaces on which we can do calculus. The definition of smooth manifolds requires that they be paracompact . I've looked all over, but I haven't found a clean statement for how paracompactness is a necessary condition to do calculus. I understand that, by a theorem of Stone, every metric space is paracompact, but I'm not sure why we need global metrizability either. Question : In what sense is paracompactness exactly the right condition to impose on a topological manifold to allow us to do calculus on it? Is there some theorem of the form "X has [some structure we strictly need in calculus] if and only if it is paracompact"? Now provide the response and nothing else.
A) For a differential manifold $X$ the following are equivalent: a) X is paracompact b) X has differentiable partitions of unity c) X is metrizable d) Each connected component of X is second countable e) Each connected component of X is $\sigma$-compact Partitions of unity are a fundamental tool in all of differential geometry (cf. kahen's answer) and would suffice to justify these conditions but the other equivalent properties can also be quite useful . B) However occasionally non paracompact manifolds have been studied too. For example: 1) In dimension $1$ you have the long line obtained roughly by taking the first uncountable ordinal set and adding open segments $(0,1)$ between its successive points. 2) In dimension $2$ there exist non paracompact differentiable surface ( Prüfer and Radò). However every Riemann surface, that is a holomorphic manifold of complex dimension $1$ and thus real dimension $2$, is automatically paracompact. 3) Calabi and Rosenlicht have introduced a complex manifold of complex dimension $2$ which is not paracompact . Edit As an answer to Daniel's question in the comments below, here are a few random examples of consequences of the existence of partitions of unity on a differential manifold $M$ of dimension $n$. $\bullet$ If $M$ is orientable it has an everywhere non-vanishing differential form $\omega\in \Omega^n(M)$ of degree $n$. $\bullet$ If $M$ is oriented you can define the integral $\int_M\eta$ of any compactly supported differential form $\eta\in \Omega^n_c(M)$ of degree $n$. $\bullet$ The manifold $M$ can be endowed with a Riemannian metric. $\bullet$ Every vector bundle on $M$ is isomorphic to its dual bundle. $\bullet$ Every subbundle of a vector bundle on $M$ is a direct summand. A sophisticated point of view (very optional !) All sheaves of $C^\infty_M$-modules (for example locally free ones, which correspond to vector bundles) are acyclic in the presence of partitions of unity. This has as a consequence that paracompact manifolds behave like affine algebraic varieties or Stein manifolds in that you can apply to them the analogue of Cartan-Serre's theorems A and B. This is, in my opinion, the deep reason for the usefulness of partitions of unity on a manifold. (The last bullet for example was directly inspired from its analogue on affine varieties or Stein manifolds)
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/98105', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7803/']}
jdg_85153
stackexchange
llm_judgeable_groundtruth_similarity
41174045
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 the new Jenkins2 pipeline to build a composed project with: node frontend php backend both are in different repositories hence, the need to use pipeline to sync them, compile, and prepare them to deploy. I cannot find a simple way to deploy using FTP. My script looks something like this: node { // uncomment these 2 lines and edit the name 'node-4.4.5' according to what you choose in configuration def nodeHome = tool name: 'NodeJS 7.2.1', type: 'jenkins.plugins.nodejs.tools.NodeJSInstallation' env.PATH = "${nodeHome}/bin:${env.PATH}" stage("front") { dir('front') { // switch to subdir git url: ... sh "npm install" sh "npm run build --prod" sh "cp -R * ../dist" } } stage("back") { dir('back') { git url: ... sh 'curl -sS https://getcomposer.org/installer | php' sh 'php composer.phar install' sh "cp -R * ../dist" } } stage("upload via ftp") { // IM NOT SURE WHAT TO DO HERE }} UPDATE 2016-12-16 To clarify what I need is a way to run something similar to "Publish via FTP" like older versions of Jenkins. Now provide the response and nothing else.
The Jenkins Publish Over FTP plugin has Pipeline support as of version 1.15. A snippet from my Jenkinsfile that sends some files to our server: stage('Upload'){ ftpPublisher alwaysPublishFromMaster: true, continueOnError: false, failOnError: false, publishers: [ [configName: 'YOUR_CONFIG_HERE', transfers: [ [asciiMode: false, cleanRemote: false, excludes: '', flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: "YOUR_DIRECTORY_HERE", remoteDirectorySDF: false, removePrefix: '', sourceFiles: '**.exe, **.txt'] ], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true] ]} I generated this code snippet using the Jenkins snippet generator found under "Pipeline Syntax". Choose "ftpPublisher: send build artifacts over FTP" in the menu at "Sample Step", enter all details in the form and press "Generate Pipeline Script".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41174045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1098814/']}
jdg_85154
stackexchange
llm_judgeable_groundtruth_similarity
25373055
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been trying to figure out why g++ cannot link a program with the armadillo library. The problem is simple: macbook-pro:arma-xc jmlopez$ g++-4.9 inputs-arma.cpp -larmadillold: library not found for -larmadillocollect2: error: ld returned 1 exit status Perhaps I did specify where the library should be macbook-pro:arma-xc jmlopez$ ls -l /usr/lib/libarma*-rwxr-xr-x 1 root wheel 37928 Aug 18 14:30 /usr/lib/libarmadillo.4.32.2.dyliblrwxr-xr-x 1 root wheel 25 Aug 18 14:30 /usr/lib/libarmadillo.4.dylib -> libarmadillo.4.32.2.dyliblrwxr-xr-x 1 root wheel 20 Aug 18 14:30 /usr/lib/libarmadillo.dylib -> libarmadillo.4.dylib Let us try again macbook-pro:arma-xc jmlopez$ g++-4.9 -L/usr/lib inputs-arma.cpp -larmadillold: library not found for -larmadillocollect2: error: ld returned 1 exit status Ok, that did not fix it. Let us see what is going on, for this we will use the -v option which will generate some long output. macbook-pro:arma-xc jmlopez$ g++-4.9 -L/usr/lib inputs-arma.cpp -larmadillo -vUsing built-in specs.COLLECT_GCC=g++-4.9COLLECT_LTO_WRAPPER=/usr/local/Cellar/gcc/4.9.1/libexec/gcc/x86_64-apple-darwin13.3.0/4.9.1/lto-wrapperTarget: x86_64-apple-darwin13.3.0Configured with: ../configure --build=x86_64-apple-darwin13.3.0 --prefix=/usr/local/Cellar/gcc/4.9.1 --enable-languages=c,c++,objc,obj-c++,fortran --program-suffix=-4.9 --with-gmp=/usr/local/opt/gmp --with-mpfr=/usr/local/opt/mpfr --with-mpc=/usr/local/opt/libmpc --with-cloog=/usr/local/opt/cloog --with-isl=/usr/local/opt/isl --with-system-zlib --enable-version-specific-runtime-libs --enable-libstdcxx-time=yes --enable-stage1-checking --enable-checking=release --enable-lto --disable-werror --with-pkgversion='Homebrew gcc 4.9.1' --with-bugurl=https://github.com/Homebrew/homebrew/issues --enable-plugin --disable-nls --enable-multilib --with-native-system-header-dir=/usr/include --with-sysroot=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdkThread model: posixgcc version 4.9.1 (Homebrew gcc 4.9.1) COLLECT_GCC_OPTIONS='-mmacosx-version-min=10.9.3' '-L/usr/lib' '-v' '-shared-libgcc' '-mtune=core2' /usr/local/Cellar/gcc/4.9.1/libexec/gcc/x86_64-apple-darwin13.3.0/4.9.1/cc1plus -quiet -v -D__DYNAMIC__ inputs-arma.cpp -fPIC -quiet -dumpbase inputs-arma.cpp -mmacosx-version-min=10.9.3 -mtune=core2 -auxbase inputs-arma -version -o /var/folders/6x/ss29s2r51z5cv0_g1ffx0c0c0000gn/T//ccApA95Q.sGNU C++ (Homebrew gcc 4.9.1) version 4.9.1 (x86_64-apple-darwin13.3.0) compiled by GNU C version 4.9.1, GMP version 6.0.0, MPFR version 3.1.2-p8, MPC version 1.0.2GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/local/include"ignoring nonexistent directory "/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/../../../../x86_64-apple-darwin13.3.0/include"ignoring nonexistent directory "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/Library/Frameworks"#include "..." search starts here:#include <...> search starts here: /Users/jmlopez/github/excentury/excentury/extern/include /usr/include /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/include/c++ /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/include/c++/x86_64-apple-darwin13.3.0 /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/include/c++/backward /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/include /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/include-fixed /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/FrameworksEnd of search list.GNU C++ (Homebrew gcc 4.9.1) version 4.9.1 (x86_64-apple-darwin13.3.0) compiled by GNU C version 4.9.1, GMP version 6.0.0, MPFR version 3.1.2-p8, MPC version 1.0.2GGC heuristics: --param ggc-min-expand=100 --param ggc-min-heapsize=131072Compiler executable checksum: 5a051bcf2be886a5c6eb8ba33f338693COLLECT_GCC_OPTIONS='-mmacosx-version-min=10.9.3' '-L/usr/lib' '-v' '-shared-libgcc' '-mtune=core2' as -arch x86_64 -force_cpusubtype_ALL -o /var/folders/6x/ss29s2r51z5cv0_g1ffx0c0c0000gn/T//cchm9rVF.o /var/folders/6x/ss29s2r51z5cv0_g1ffx0c0c0000gn/T//ccApA95Q.sCOMPILER_PATH=/usr/local/Cellar/gcc/4.9.1/libexec/gcc/x86_64-apple-darwin13.3.0/4.9.1/:/usr/local/Cellar/gcc/4.9.1/libexec/gcc/x86_64-apple-darwin13.3.0/4.9.1/:/usr/local/Cellar/gcc/4.9.1/libexec/gcc/x86_64-apple-darwin13.3.0/:/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/:/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/LIBRARY_PATH=/usr/lib/:/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/:/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/../../../:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib/COLLECT_GCC_OPTIONS='-mmacosx-version-min=10.9.3' '-L/usr/lib' '-v' '-shared-libgcc' '-mtune=core2' /usr/local/Cellar/gcc/4.9.1/libexec/gcc/x86_64-apple-darwin13.3.0/4.9.1/collect2 -dynamic -arch x86_64 -macosx_version_min 10.9.3 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk -weak_reference_mismatches non-weak -o a.out -L/usr/lib -L/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1 -L/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/../../.. -L/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /var/folders/6x/ss29s2r51z5cv0_g1ffx0c0c0000gn/T//cchm9rVF.o -larmadillo -lstdc++ -no_compact_unwind -lSystem -lgcc_ext.10.5 -lgcc -lSystem -vcollect2 version 4.9.1/usr/bin/ld -dynamic -arch x86_64 -macosx_version_min 10.9.3 -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk -weak_reference_mismatches non-weak -o a.out -L/usr/lib -L/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1 -L/usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1/../../.. -L/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /var/folders/6x/ss29s2r51z5cv0_g1ffx0c0c0000gn/T//cchm9rVF.o -larmadillo -lstdc++ -no_compact_unwind -lSystem -lgcc_ext.10.5 -lgcc -lSystem -v@(#)PROGRAM:ld PROJECT:ld64-236.4configured to support archs: armv6 armv7 armv7s arm64 i386 x86_64 armv6m armv7m armv7emLibrary search paths: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1 /usr/local/Cellar/gcc/4.9.1/lib /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/libFramework search paths: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/ld: library not found for -larmadillocollect2: error: ld returned 1 exit status The important information is here: Library search paths: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1 /usr/local/Cellar/gcc/4.9.1/lib /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib Somehow it is not looking in /usr/lib . I have tried specifying this directory by firstexporting the variable LD_LIBRARY_PATH macbook-pro:arma-xc jmlopez$ export LD_LIBRARY_PATH=/usr/libmacbook-pro:arma-xc jmlopez$ g++-4.9 -L/usr/lib inputs-arma.cpp -larmadillold: library not found for -larmadillocollect2: error: ld returned 1 exit status No luck. Finally, thinking that ld might be broken I did this: macbook-pro:arma-xc jmlopez$ ln -s /usr/lib/libarmadillo.dylib /usr/local/Cellar/gcc/4.9.1/lib/libarmadillo.dylibmacbook-pro:arma-xc jmlopez$ g++-4.9 inputs-arma.cpp -larmadillo Now it works. I'm not sure if there is something wrong with my system but it seems that I have no way of specifying other paths for ld to look for my libraries. Instead I have to use any of the following: Library search paths: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1 /usr/local/Cellar/gcc/4.9.1/lib /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib Is there a way to fix this? Notice that I'm using the g++ from homebrew since I thought that the one that came with xcode was broken. In any case, no luck, at least the homebrew g++ told me the paths where the library was being searched. Update: I decided to see if I could add another path: g++-4.9 -L/Users/jmlopez/ -L/Users/jmlopez/Desktop -L/usr/lib inputs-arma.cpp -larmadillo -v Now the list of paths where it searches for the libraries is: Library search paths: /Users/jmlopez/ /Users/jmlopez/Desktop /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /usr/local/Cellar/gcc/4.9.1/lib/gcc/x86_64-apple-darwin13.3.0/4.9.1 /usr/local/Cellar/gcc/4.9.1/lib /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/lib Where is /usr/lib ? What is so special about this directory that ld refuses to look in this directory. It searches in my home directory and in my Desktop. I tried adding /usr/local and it adds it to the list of directories. I'm now starting to wonder about the permissions on the directories... Any ideas? Now provide the response and nothing else.
Alternative to Filters, you can use HandlerInterceptor . public class SessionManager implements HandlerInterceptor{ // This method is called before the controller @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String xHeader = request.getHeader("X-Auth-Token"); boolean permission = getPermission(xHeader); if(permission) { return true; } else { response.setStatus(HttpStatus.UNAUTHORIZED.value()); return false; // Above code will send a 401 with no response body. // If you need a 401 view, do a redirect instead of // returning false. // response.sendRedirect("/401"); // assuming you have a handler mapping for 401 } return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { }} And then add this interceptor to your webmvc config. @EnableWebMvc@Configurationpublic class WebConfig extends WebMvcConfigurerAdapter { @Bean SessionManager getSessionManager() { return new SessionManager(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getSessionManager()) .addPathPatterns("/**") .excludePathPatterns("/resources/**", "/login"); // assuming you put your serve your static files with /resources/ mapping // and the pre login page is served with /login mapping }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25373055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/788553/']}
jdg_85155
stackexchange
llm_judgeable_groundtruth_similarity
39905719
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 PDF and some doc files kept in firebase storage. How can I download the file from Firebase Storage to the External storage of my device? public void writeExternalStorage() { String filename; String completepath; mref = FirebaseStorage.getInstance().getReference(); StorageReference filepath = mref.child("MyFiles").child("firstFile.pdf"); InputStream inputStream = null; File file = null; FileOutputStream fileOutputStream = null; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { try { file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + "/TestPurpose"); // Log.d("PATH", file.toString()); } catch (Exception e) { e.printStackTrace(); } }} I want to download the Firstfile.pdf file to the External_storage's Document/TestPurpose/ Folder. How it can be done?? Now provide the response and nothing else.
private void downloadFile() { FirebaseStorage storage = FirebaseStorage.getInstance(); StorageReference storageRef = storage.getReferenceFromUrl("<your_bucket>"); StorageReference islandRef = storageRef.child("file.txt"); File rootPath = new File(Environment.getExternalStorageDirectory(), "file_name"); if(!rootPath.exists()) { rootPath.mkdirs(); } final File localFile = new File(rootPath,"imageName.txt"); islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() { @Override public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) { Log.e("firebase ",";local tem file created created " +localFile.toString()); // updateDb(timestamp,localFile.toString(),position); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { Log.e("firebase ",";local tem file not created created " +exception.toString()); } });}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39905719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6934293/']}
jdg_85156
stackexchange
llm_judgeable_groundtruth_similarity
2707340
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know there are two questions which are same with mine, but their hints and comments are not clear enough for me. Let $(X,\|.\|)$ is a normed space over $\mathbb F$ field $M \subset X$ is a vector subspace of $X.$ Show that if $M$ is open vector subspace of $X$ then $X=M$ First I tried obtaining a contradiction via using Let $M$ is open and $X\neq M$ . Since $M$ is open $M=int(M)$ . Hence $\exists x\in X\setminus int(M)$ but I couldn't obtain from there. Then, I have tried to prove it directly but I couldn't see why $\forall x \in X$ then $x \in M$ I've written $M$ is open $\Rightarrow$ $\exists r\gt0$ $\forall m \in M$ , $B(m,r)\subseteq M$ $B(m,r):= \{n \in M : \|n-m\| \lt r\}$ and Since $M$ is vector subspace - $\forall m,n \in M \subset X$ , $m+n \in M$ - $\forall m \in M \subset X$ , $\forall \lambda \in \mathbb F$ , $\lambda m \in M$ I cannot combine being vector subspace and being open. Could someone help me about seeing why " $\forall x \in X$ then $x \in M$ " or obtainig contradiction in the easiest and clearest way without topological terms please? Thanks in advance Now provide the response and nothing else.
Let $\mathbb{F}\in \{ \mathbb{R}, \mathbb{C} \}$, let $(X, \ \Vert \cdot \Vert)$ be a normed space over $\mathbb{F}$ and $V\subseteq X$ an open subspace of $X$. As $V$ is open, there exists $\varepsilon>0$ such that $$ B_\varepsilon (0) = \{ x \in X \ : \ \Vert x \Vert < \varepsilon \} \subseteq V.$$ Let $0\neq x\in X$, then we have $$ x=\underbrace{\left(\frac{2\Vert x \Vert}{\varepsilon} \right)}_{\in \mathbb{F}} \underbrace{\left( \frac{\varepsilon x}{2\Vert x \Vert }\right)}_{\in B_\varepsilon(0)\subseteq V} \in V.$$ Where we used, that $V$ is a vector space and hence scalar multiple of a vector in $V$ lie again in $V$. As $V$ is a vector space, we also have $0\in V$. Thus, $V=X$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2707340', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/450011/']}
jdg_85157
stackexchange
llm_judgeable_groundtruth_similarity
9605
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to detect from a shell script (more specifically .zshrc) if it is controlled through SSH. I tried the HOST variable but it's always the name of the computer which is running the shell. Can I access the hostname where the SSH session is coming from? Comparing the two would solve my problem. Every time I log in there is a message stating the last login time and host: Last login: Fri Mar 18 23:07:28 CET 2011 from max on pts/1Last login: Fri Mar 18 23:11:56 2011 from max This means the server has this information. Now provide the response and nothing else.
Here are the criteria I use in my ~/.profile : If one of the variables SSH_CLIENT or SSH_TTY is defined, it's an ssh session. If the login shell's parent process name is sshd , it's an ssh session. if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then SESSION_TYPE=remote/ssh# many other tests omittedelse case $(ps -o comm= -p "$PPID") in sshd|*/sshd) SESSION_TYPE=remote/ssh;; esacfi (Why would you want to test this in your shell configuration rather than your session startup?)
{}
{'log_upvote_score': 8, 'links': ['https://unix.stackexchange.com/questions/9605', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/4477/']}
jdg_85158
stackexchange
llm_judgeable_groundtruth_similarity
2666792
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 wanting to create a view (UIControl) which blocks all input and shows a UIActivityIndicatorView while authenticating a user. The UIActionSheet and UIAlertView both manage to add a black semi-transparent view over the top of all other views to block input and I'd like to do similar. I've tried adding my view to the top UIWindow in the [[UIApplication sharedApplication] windows] array, and while this does place it above the UIKeyboard if it's visible, it doesn't place it over the StatusBar (which makes sense). My next attempt was to extend UIAlertView, remove all of its subviews and set its layer.contents = nil, then add the ActivityIndicator as a subview. This works well, but I can't seem to kill the default bouncy transition of the UIAlertView when you call it to "show". Does anyone have any pointers towards the best way tackle this problem that gives me full control? Oh and I know blocking input is not great but I do ensure it's for a short period of time and it has the benefit of making it clear to the user that their action, which must complete for them to progress, is processing. Now provide the response and nothing else.
I've done some more digging around the API's and believe I've worked it out. In order to display a view over the entire screen you need to create your own UIWindow and set its windowLevel property to be UIWindowLevelStatusBar. You can then add your custom subviews to this window. Note that Apple does not encourage, but neither do they prohibit the creation of multiple windows. UIWindow *statusWindow = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];statusWindow.windowLevel = UIWindowLevelStatusBar;statusWindow.hidden = NO;statusWindow.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7];[statusWindow makeKeyAndVisible]; When you want to remove the window from the screen it looks as though you release it from memory. [statusWindow release]; This doesn't feel totally safe, but I don't get any errors and it seems to drop it out of the UIApplication's windows array. Please let me know if this is wrong. Update: One other issue I came across was the UIStatusBar not taking touch events to scroll the active UIScrollView to the top after I had displayed and removed this overlay window. The solution was to set the primary window back to the key window once the overlay had been released. [primaryWindow makeKeyWindow];
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2666792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83030/']}
jdg_85159
stackexchange
llm_judgeable_groundtruth_similarity
472256
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: Suppose I apply some force on one side of hydraulic lift where area is less, and the fluid in the lift raises some heavier object on the other side where area is more. Now, work done is $\text{Force}\times \text{Displacement}$ and displacement on both side is same (incompressible liquid) but the force on one side is less, so we get more energy on other side. Then why doesn't the law of conservation of energy fail here? Now provide the response and nothing else.
Displacement in both sides is not same. If on one side of lift the area is $A_1$ , and on other side it is $A_2$ , and we apply a force $F_1$ on one side to distance $d_1$ then volume decreased in one side is $=A_1 d_1$ Equal amount of volume will raise in the other side. So $$A_1 d_1=A_2 d_2$$ $A_1 \not= A_2$ , so $d_1 \not=d_2$ . Actually, we need to apply the little force $F_1$ for a greater distance $d_1$ .
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/472256', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/226827/']}
jdg_85160
stackexchange
llm_judgeable_groundtruth_similarity
164465
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: On Arch Linux, whenever a kernel upgrade is applied (via pacman -Su ), problems occur. For example, iptables can no longer be used: # iptables -Liptables v1.4.21: can't initialize iptables table `filter': Table does not exist (do you need to insmod?)Perhaps iptables or your kernel needs to be upgraded. VMWare can't find the kernel headers: Now, I want to have kernel upgrades applied, but I'd like to defer them until I can (or want to) restart the system (remind anyone of Windows?). Otherwise, if my work is blocked on iptables or VMWare or some other program, I have no choice but to restart and rebuild a session. How can I do that? Ideally I'd like to continue using pacman -Su , but have certain upgrades deferred. I believe Is it normal that a restart is required to mount USB after a kernel upgrade? is caused by the same problem. Now provide the response and nothing else.
If you want to keep pacman from up/down grading some package(s), you put a line in /etc/pacman.conf : # Pacman won't upgrade packages listed in IgnorePkg and members of IgnoreGroup#IgnorePkg =#IgnoreGroup = I think you want to have a line like this in pacman.conf : IgnorePkg = linux linux-headers linux-api-headers As you point out, that just keeps pacman from any upgrading. You could probably write some code like this: if pacman -Qu | egrep -q -s 'linux|linux-headers|linux-api-headers'then pacman -S --noconfirm linux pacman -S --noconfirm linux-headers pacman -S --noconfirm linux-api-headersfi It looks like you have to write a " systemd unit file " - that part's a bit beyond what I have confidence in telling you what to do. My thought is that the Before=shutdown.target line in the unit file is what makes it run at shutdown. The only unit file I wrote took me several tries to get correct, so I really don't think you want my advice on that.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/164465', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/70524/']}
jdg_85161
stackexchange
llm_judgeable_groundtruth_similarity
44738273
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am currently working in torch to implement a random shuffle (on the rows, the first dimension in this case) on some input data. I am new to torch, so I have some troubles figuring out how permutation works.. The following is supposed to shuffle the data: if argshuffle then local perm = torch.randperm(sids:size(1)):long() print("\n\n\nSize of X and y before") print(X:view(-1, 1000, 128):size()) print(y:size()) print(sids:size()) print("\nPerm size is: ") print(perm:size()) X = X:view(-1, 1000, 128)[{{perm},{},{}}] y = y[{{perm},{}}] print(sids[{{1}, {}}]) sids = sids[{{perm},{}}] print(sids[{{1}, {}}]) print(X:size()) print(y:size()) print(sids:size()) os.exit(69)end This prints out Size of X and y before 99 1000128[torch.LongStorage of size 3]99 1[torch.LongStorage of size 2]99 1[torch.LongStorage of size 2]Perm size is: 99 [torch.LongStorage of size 1]5[torch.LongStorage of size 1x1]5[torch.LongStorage of size 1x1]99 1000128[torch.LongStorage of size 3]99 1[torch.LongStorage of size 2]99 1[torch.LongStorage of size 2] Out of the value, I can imply that the function did not shuffle the data. How can I make it shuffle correctly, and what is the common solution in lua/torch? Now provide the response and nothing else.
I also faced a similar issue. In the documentation, there is no shuffle function for tensors (there are for dataset loaders ). I found a workaround to the problem using torch.randperm . >>> a=torch.rand(3,5)>>> print(a)tensor([[0.4896, 0.3708, 0.2183, 0.8157, 0.7861], [0.0845, 0.7596, 0.5231, 0.4861, 0.9237], [0.4496, 0.5980, 0.7473, 0.2005, 0.8990]])>>> # Row shuffling... >>> a=a[torch.randperm(a.size()[0])]>>> print(a)tensor([[0.4496, 0.5980, 0.7473, 0.2005, 0.8990], [0.0845, 0.7596, 0.5231, 0.4861, 0.9237], [0.4896, 0.3708, 0.2183, 0.8157, 0.7861]])>>> # column shuffling... >>> a=a[:,torch.randperm(a.size()[1])]>>> print(a)tensor([[0.2005, 0.7473, 0.5980, 0.8990, 0.4496], [0.4861, 0.5231, 0.7596, 0.9237, 0.0845], [0.8157, 0.2183, 0.3708, 0.7861, 0.4896]]) I hope it answers the question!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44738273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3262787/']}
jdg_85162
stackexchange
llm_judgeable_groundtruth_similarity
310391
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This preprint claims that, for finite kinetic energy initial solutions, uniqueness of weak solutions to the Navier-Stokes equations doesn't hold: https://arxiv.org/abs/1709.10033 What's the current consensus of the community? Is the proof considered to be correct? Does this imply that the Navier-Stokes equations are not a valid model of fluid flow, or do we need a similar result for the smooth solutions of NS before we have to abandon/modify them? Now provide the response and nothing else.
In regards to the question of the "consensus" or "correctness", I will only point out that Tristan Buckmaster has had a proven record of studying nonuniqueness problems for low-regularity solutions in incompressible fluids, and contributed significantly to the settling of Onsager's Conjecture on the nonuniqueness problem for incompressible Euler. In regards to Navier-Stokes: weak solutions are called weak for a reason. To put it in simplest terms: the "solvability" of a PDE depends on what you accept as a valid solution. (As a digression, this is not a problem unique to PDEs. Even in arithmetic if you work over $\mathbb{Q}$ the equation $x^2 = 2$ is not solvable, and if you work over $\mathbb{R}$ the equation $x^2 = -1$ is not solvable. Mathematics has a long history of "completing" the "space of admissible solutions" to solve previously unsolvable problems.) There's an obvious trade off: if you enlarge the admissible solution space, you make it easier to solve an equation. But by making it easier to find a solution, you risk making it possible to find more than one solution. (As an example, consider $x^3 = 3$. It is not solvable in $\mathbb{Q}$, it has a unique solution in $\mathbb{R}$, and it has three solutions in $\mathbb{C}$.) In some sense you can think of existence and uniqueness as competing demands; a lot of PDE theory is built on figuring out how to restrict to a reasonable set of "admissible solutions" while guaranteeing both existence AND uniqueness. In the context of Navier-Stokes, Leray (and Hopf) figured out a way to guarantee existence. People however have long suspected that their method does not guarantee uniqueness (in other words, that they are too generous when admitting something as a solution). Buckmaster and Vicol's work tries to carve away at this problem, by proving that for an even more generous notion of solution non-uniqueness can arise. So no, we are absolutely nowhere near saying anything useful about physics or engineering; we are merely calibrating PDE theory. As an aside, local existence and uniqueness for smooth solutions of NS hold. So a "similar result for smooth solutions" is in fact, impossible . This brings me back to the point of calibration: We know for sufficiently regular initial values, local-in-time existence and uniqueness of solutions to Navier-Stokes hold. We know that if we sufficiently relax the notion of solutions, global -in-time existence of solutions to Navier-Stokes hold. We know further that if an initial data admits a global weak solution that is in fact sufficiently regular, then that is the unique weak solution (in the sense of Leray-Hopf). The main question on Navier-Stokes existence and uniqueness can be reformulated as: does there exist a sense of weak solution which guarantees global, unique solutions for all initial data, or is there a dichotomy where a sense of weak solutions that guarantees global solutions for all initial data is always too weak to guarantee uniqueness, and any sense of solutions guaranteeing uniqueness of solutions is always too strong to guarantee global solutions.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/310391', 'https://mathoverflow.net', 'https://mathoverflow.net/users/88142/']}
jdg_85163
stackexchange
llm_judgeable_groundtruth_similarity
243974
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: A finite group acting on a complex vector space of dimension $n$ can be seen as acting on a real vector space of dimension $2n$ just by forgetting the complex structure of the space. My question is, if I am handed a real vector space $V$ of dimension $2n$, and a group $G$ acting on it, is there a test I can perform to determine if the action arose from a complex action in this way? Sometimes it is easy to rule out: for example, if $G$ contains anything orientation-reversing, then clearly it doesn't arise in this way. Or if one knows enough about $G$ (abstractly as a group) to know it doesn't have any faithful $n$-dimensional representation. But I would like an if-and-only-if criterion: Is there a test I can perform on the pair $G,V$ to determine whether the action of $G$ can be obtained by beginning with a complex $n$-dimensional representation and forgetting the complex structure of the vector space? To make a little more precise what I mean by "can be obtained": if there is an element $J\in GL(V)$ that commutes with the action of $G$ and satisfies $J^2 = - I$, then the action of $G$ "can be obtained from a complex $n$-dimensional action by forgetting the complex structure", since one can regard $V$ as a complex vector space via the action of $J$. So the question is, if I am handed $G$ and $V$, is there a test for the existence of such a $J$? Now provide the response and nothing else.
It's cleaner to ask about an arbitrary finite-dimensional real representation $V$ of a finite group $G$; the hypothesis that $V$ is faithful isn't particularly helpful. $V$ has a decomposition $\bigoplus_i n_i V_i$ into irreducible components with multiplicities, and so its endomorphism algebra takes the form $$\text{End}(V) \cong \prod_i M_{n_i}(D_i)$$ where $D_i = \text{End}(V_i)$ are division algebras over $\mathbb{R}$ by Schur's lemma, so either $\mathbb{R}$, $\mathbb{C}$, or $\mathbb{H}$. The question is when there is a morphism (necessarily a monomorphism) $\mathbb{C} \to \text{End}(V)$ of $\mathbb{R}$-algebras, and the answer is iff there is such a morphism into each $M_{n_i}(D_i)$, hence for each $i$ either $D_i = \mathbb{R}$ and $n_i$ is even, or $D_i = \mathbb{C}$ or $\mathbb{H}$. We can test for this as follows. If $W$ is an irreducible real representation, then $\text{End}(W \otimes \mathbb{C}) \cong \text{End}(W) \otimes \mathbb{C}$ (all tensor products here and below taken over $\mathbb{R}$), and so exactly one of three things happens: $\text{End}(W) \cong \mathbb{R}$, so $\text{End}(W \otimes \mathbb{C}) \cong \mathbb{C}$, meaning that $W \otimes \mathbb{C}$ remains irreducible. $\text{End}(W) \cong \mathbb{C}$, so $\text{End}(W \otimes \mathbb{C}) \cong \mathbb{C} \otimes \mathbb{C} \cong \mathbb{C} \times \mathbb{C}$, meaning that $W \otimes \mathbb{C}$ is a direct sum of two complex conjugate and nonisomorphic irreducibles. $\text{End}(W) \cong \mathbb{H}$, so $\text{End}(W \otimes \mathbb{C}) \cong \mathbb{H} \otimes \mathbb{C} \cong M_2(\mathbb{C})$, meaning that $W \otimes \mathbb{C}$ is a direct sum of two isomorphic irreducibles. These three cases can be distinguished by the value of $$\langle W, W \rangle = \frac{1}{|G|} \sum_{g \in G} \chi_W(g)^2$$ as Claudio says; it takes the values $1, 2, 4$ in the above three cases. With this modification to the orthogonality relations you can try to figure out the decomposition of $V$ into real irreducible representations and then compute the $n_i$ and the $D_i$ using the above test. See also the Frobenius-Schur indicator for some discussion of how to classify the real irreducible representations given knowledge of the complex irreducible representations.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/243974', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12419/']}
jdg_85164
stackexchange
llm_judgeable_groundtruth_similarity
50440420
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to list only the directories that were changed? If I'm at the git root say, ~/project Files I changed are ~/project/subtool/file1 ~/project/subtool/file2 ~/project/subtool3/file1 I just want ~/project/subtool ~/project/subtool3 Now provide the response and nothing else.
You could use git-diff with the --dirstat parameter. In your scenario, let's say you have the following commit: $ git diff --name-status HEAD~1M subtool/file1M subtool/file2M subtool3/file1 It would produce the following output: $ git diff --dirstat=files,0 HEAD~1 66.6% subtool/ 33.3% subtool3/ Make sure to add ,0 , otherwise git diff will by default only show directories with at least 3% changes. I also chose files as this is the computationally cheapest option and you do not seem to care about specific changes anyway. If you are able to use sed you can get rid of the percentage values (you may want to tweak the regular expression a bit to fit your needs): $ git diff --dirstat=files,0 HEAD~1 | sed 's/^[ 0-9.]\+% //g'subtool/subtool3/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50440420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4509355/']}
jdg_85165
stackexchange
llm_judgeable_groundtruth_similarity
39566809
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: New to dask ,I have a 1GB CSV file when I read it in dask dataframe it creates around 50 partitions after my changes in the file when I write, it creates as many files as partitions. Is there a way to write all partitions to single CSV file and is there a way access partitions? Thank you. Now provide the response and nothing else.
Short answer No, Dask.dataframe.to_csv only writes CSV files to different files, one file per partition. However, there are ways around this. Concatenate Afterwards Perhaps just concatenate the files after dask.dataframe writes them? This is likely to be near-optimal in terms of performance. df.to_csv('/path/to/myfiles.*.csv')from glob import globfilenames = glob('/path/to/myfiles.*.csv')with open('outfile.csv', 'w') as out: for fn in filenames: with open(fn) as f: out.write(f.read()) # maybe add endline here as well? Or use Dask.delayed However, you can do this yourself using dask.delayed , by using dask.delayed alongside dataframes This gives you a list of delayed values that you can use however you like: list_of_delayed_values = df.to_delayed() It's then up to you to structure a computation to write these partitions sequentially to a single file. This isn't hard to do, but can cause a bit of backup on the scheduler. Edit 1: (On October 23, 2019) In Dask 2.6.x, there is a parameter as single_file . By default, It is False . You can set it True to get single file output without using df.compute() . For Example: df.to_csv('/path/to/myfiles.csv', single_file = True) Reference: Documentation for to_csv
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39566809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5946185/']}
jdg_85166
stackexchange
llm_judgeable_groundtruth_similarity
485664
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: This has been asked, or brushed by before, but not really answered, for instance, here: SMD LED footprint I still don't know what the 3rd footprint pad for some SMD LEDs (like the Vishay VSMG10850 ; the red bit in the image) is for, do I need to add one on the board, and if so, do I leave it unconnected, connect it to the GND for instance, or what? Some of the explanations mentioned it might be for heat dissipation. If so, how should it be connected to anything larger than the small pad for actually dissipating some of the heat? Another guess is that it has to do with just mechanical attachment to the board, especially for automated layout hardware. Now provide the response and nothing else.
The shown pads are the area you need for soldering. The pads don't have to be exactly that size, but the openings in the soldermask should have the given sizes and positions. The "third pad" on many LEDs is so that you can connect the LED to a large surface for cooling - you use a copper area on your PCB as a heat sink. Whether the third pin may be connected to ground or not depends on how it is connected inside the LED. You must check the datasheet. In some LEDs, the thermal pin is connected to the cathode - you can connect it to ground if the cathode is grounded. In other LEDs, the thermal pin is electrically neutral (not connected electrically) so you can connect the thermal pin to any convenient large copper area. In the case of your VSMG10850, the third pin is given as "reinforcing pin," which I take to mean it is mechanical only. The datasheet says it is "non-electrode" so it has no electrical connection. As it is mechanical only, it won't work as a heat sink so there's no advantage to connecting it to a large copper area. Relevant section of the datasheet:
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/485664', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/244944/']}
jdg_85167
stackexchange
llm_judgeable_groundtruth_similarity
16995534
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 attempting to create a 'Pick your hero' thing. There are a total of 113 heroes, each are given tags respective to them, for example: wizard, fighter etc. The way I've done it so far is create a container and add 114 total div's to that container. I have this: .heroPics { background-image: url(newHeroes.jpg); background-size: 792px 792px; width: 72px; height: 72px; float: left; margin-left: 5px; margin-top: 20px; text-align: center; line-height: 11; font-size: 15px; position: relative;}for (var i = 1; i < 114; i++) { srsHeroes[i] = document.createElement("div"); srsHeroes[i].textContent = theNames[i]; srsHeroes[i].className = "championPics " + theNames[i] + "-sprite"; srsHeroes[i].draggable = false; srsHeroes[i].name = theNames[i]; srsHeroes[i].num = i; heroSelection.appendChild(srsHeroes[i]);} I was thinking of creating an array, for example wizard = [ 14, 17, 28, 34, 69, 90, 101 ]; and once they click on a checkbox to show only wizard heroes it would do a for loop to hide all 113 divs and then do: for (var i = 50; i < 70; i++) { heroSelection.insertBefore(srsHeroes[wizard[i]], srsHeroes[115]);//and also do style.visiblity = "visible"; } But it just seems like this is a bad approach to it, or really messy/ugly. I don't really like using library's, including jquery. Is using div's even the right approach? Can anyone with experience give me some advice or links to follow since I must be searching the wrong terms for this. Also can someone give me some intro on how to create a search bar where they can write hero names and it does the same thing? Reordering and hiding everything properly. Could be cool to have a transition too but not necessary lol. Thanks in advance for reading and all your help. EDIT: Added my own post since it would have made this too long, let me know what you think Now provide the response and nothing else.
I'm assuming you only see this exception when your insert fails; you then try to reuse the UserDetail model in the view for the same page. The error you are seeing is due to the nature of working with HTTP - anything that is not directly bound to an input is not retained. So, when you attempt to rebuild the view, the list you are trying to bind the drop-down helper to is null, since UserDetail.ProjectDetail has not been repopulated. You can fix this like so: [HttpPost]public ActionResult Create(UserDetail userdetail){ if (ModelState.IsValid) { db.UserDetails.Add(userdetail); db.SaveChanges(); return RedirectToAction("SearchCust"); } userdetail.ProjectDetail = db1.ProjectDetails.ToList(); return View(userdetail);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16995534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2359884/']}
jdg_85168
stackexchange
llm_judgeable_groundtruth_similarity
27670365
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried to install Scrapy for Python 2.7.8 (anaconda 2.1.0) 32-bit using pip install scrapy And I got this error error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat). I have followed the solutions found in these stackover flow questions. Nothing worked. Microsoft Visual C++ Compiler for Python 2.7 Can't find vcvarsall.bat file error: Unable to find vcvarsall.bat Getting "error: Unable to find vcvarsall.bat" when running "pip install numpy" on windows7 64bit pip install gives error: Unable to find vcvarsall.bat How do I point easy_install to vcvarsall.bat? pip install MySQL-python returns unable to find vcvarsall.bat This is the error, and a few lines above and below it: copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt-> build\lib.win32-3.4\lxml\isoschematron\resources\xsl\iso-schematron-xslt1running build_extbuilding 'lxml.etree' extensionC:\Python34\lib\distutils\dist.py:260: UserWarning: Unknown distribution option: 'bugtrack_url' warnings.warn(msg)error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat).----------------------------------------Command "C:\Python34\python.exe -c "import setuptools, tokenize;__file__='C:\\Users\\San\\AppData\\Local\\Temp\\pip-build-wp6ei6r9\\lxml\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\Users\San\AppData\Local\Temp\pip-kfkzr_67-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\San\AppData\Local\Temp\pip-build-wp6ei6r9\lxml I have both Microsoft Visual Studio 12.0, and Microsoft visual C++ compiler package for Python 2.7, both of which have the vcvarsall.bat file. I have a system variable that is called 'VS120COMNTOOLS' and is its path is set to C:\Program Files\Microsoft Visual Studio 12.0\Common7\Tools\ I also added both paths to my environment variables. I've also tried just adding one, and then the other. My Path looks like this C:\Program Files\Java\jdk1.7.0_25\bin;\Python27;\Python2\python.exe;C:\Python27\Scripts\;C:\Users\San\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\;C:\Program Files\Microsoft Visual Studio 12.0\VC\; I also updated by my setup tools (I think to version 8), which should autodetect Microsoft Visual C++ Compiler for Python 2.7. However, I'm still getting the same error. I have also tried using easy_install scrapy And I get this error error: Setup script exited with error: Microsoft Visual C++ 10.0 is required (Un able to find vcvarsall.bat). I also have the following in my registry HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\9.0\Setup\VC\ProductDirHKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\12.0\Setup\VC\ProductDir Now provide the response and nothing else.
I have tried all suggestions and found my own simple solution. The problem is that codes written in external environment like C need compiler. Look for its own VS environment, i.e. VS 2008. Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat .I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS as variable name and gave the value of VS120COMNTOOLS . You can find my step by step solution below: Right click on My Computer. Click Properties Advanced system settings Environment variables Add New system variable Enter VS90COMNTOOLS to the variable name Enter the value of current version to the new variable. Close all windows Now open a new session and pip install your-package
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27670365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3259896/']}
jdg_85169
stackexchange
llm_judgeable_groundtruth_similarity
4301064
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to get the following fields from Android contacts? I used Android 2.2. Name prefix First name Middle name Last name Name prefix Phonetic given name Phonetic middle name Phonetic family name Now provide the response and nothing else.
Look at ContactsContract.CommonDataKinds.StructuredName class. You can find there all columns you are looking for. Try sth like this: String whereName = ContactsContract.Data.MIMETYPE + " = ?"; String[] whereNameParams = new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }; Cursor nameCur = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, whereName, whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME); while (nameCur.moveToNext()) { String given = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME)); String family = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)); String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME)); } nameCur.close(); It returns all names in contacts. To be more precise you can add a contact id as an additional parameter to the query - you will get address for particular contact.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4301064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/488433/']}
jdg_85170
stackexchange
llm_judgeable_groundtruth_similarity
37649340
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a custom view which automatically animates. It uses an AnimatorSet which calls Animator.start() in onAnimationEnd() in order to repeat endlessly. This is automatically started when the view is created. These views are used in a ListAdapter (actually a SackOfViewsAdapter so there is no recycling going on). So it's important to manage when to cancel (or pause) the animation. Maybe the animator should be registered with the adapter and then the Activity should call some method on that adapter to cancel any animations? Another idea is to check, in onAnimationEnd() whether the View isShowing() (i.e. don't restart animation if not showing) but then this would cause issues when the View comes back into view. This seems a little hacky to me, so I'm interested if there are better solutions. Also, what happens if an animator is paused? I guess it will not be garbage collected? Now provide the response and nothing else.
Do not use php's date() function, it's not as accurate as the below solution and furthermore it is unreliable in the future. Use the DateTime class <?php$date = new DateTime('2016-06-06'); // Y-m-d$date->add(new DateInterval('P30D'));echo $date->format('Y-m-d') . "\n";?> The reason you should avoid anything to do with UNIX timestamps ( time() , date() , strtotime() etc) is that they will inevitably break in the year 2038 due to integer limitations. The maximum value of an integer is 2147483647 which converts to Tuesday, 19 January 2038 03:14:07 so come this time; this minute; this second; everything breaks Source Another example of why I stick to using DateTime is that it's actually able to calculate months correctly regardless of what the current date is: $now = strtotime('31 December 2019');for ($i = 1; $i <= 6; $i++) { echo date('d M y', strtotime('-' . $i .' month', $now)) . PHP_EOL;} You'd get the following sequence of dates: 31 December31 November31 October31 September31 August31 July31 June PHP conveniently recognises that three of these dates are illegal and converts them into its best guess, leaving you with: 01 Dec 1931 Oct 1901 Oct 1931 Aug 1931 Jul 1901 Jul 19
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37649340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4542387/']}
jdg_85171
stackexchange
llm_judgeable_groundtruth_similarity
9505862
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 a formula to find the shortest distance in degrees between two degree marks on a circle: for instance, 30 degrees and 170 degrees (140 degrees). The two degree marks can be virtually any real number, and isn't necessarily between 0 and 360 (can be negative, or much greater than 360, for instance -528.2 and 740 (which is 171.8 degrees)). However, the distance should always be <= 180 degrees and >= 0 degrees. It sounds simple enough. But, I've been trying to find a good solution for this and I've tried a lot of different code but nothing I've found so far works in all the cases I've tried. I'm working in c++. Does anyone have any ideas? Now provide the response and nothing else.
Step 1: Get the "raw" difference. For example, given -528.2 and 740.0 , this is 1268.2 . one way: raw_diff = first > second ? first - second : second - first another way: raw_diff = std::fabs(first - second) Step 2: Subtract a multiple of 360.0 to get a value between 0.0 (inclusive) and 360.0 (exclusive). mod_diff = std::fmod(raw_diff, 360.0) Step 3: If this value is greater than 180.0 , subtract it from 360.0 . one way: dist = mod_diff > 180.0 ? 360.0 - mod_diff : mod_diff another way: dist = 180.0 - std::fabs(mod_diff - 180.0) It's probably most readable as a series of statements: double raw_diff = first > second ? first - second : second - first;double mod_diff = std::fmod(raw_diff, 360.0);double dist = mod_diff > 180.0 ? 360.0 - mod_diff : mod_diff; But if desired, it's not hard to put it all into a single expression: 180.0 - std::fabs(std::fmod(std::fabs(first - second), 360.0) - 180.0)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9505862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/823790/']}
jdg_85172
stackexchange
llm_judgeable_groundtruth_similarity
19182900
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an ashx file that serves PDF documents. Our environment is we develop locally, and the web app is moved to different environments: test and then production. What is the best way to access a path on the server? How can I use Server.MapPath() in an .ashx handler. Now provide the response and nothing else.
I'd like to add another case to the scenario Case one: For example if you know the path to deploy and this isn't under the context of your application:from VS 2010 you can add a web.config transform depending on your build configuration to keep it simple you can have a web.debug.config (let's assume development) and web.release.config (production) or you can set up your own build configuration as web.production.config if you want. you can create an application setting for referencing the full path of the folder and do a transformation depending on which environment you are going to deploy something like <appSettings> <add key="folderPath" value="c:\dev" /> // other keys here</appSettings><?xml version="1.0" encoding="utf-8"?><configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <appSettings> <add key="folderPath" value="c:\production" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/> </appSettings></configuration> Case two: using the server mapPath as you mentioned System.Web.HttpContext.Current.Server.MapPath() or context.Server.MapPath()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19182900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1272419/']}
jdg_85173
stackexchange
llm_judgeable_groundtruth_similarity
535816
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have as an input File1 which looks like this: A,22,1,2,3,4,5G,26,5,6,7X,28,10,20,10 I would like to apply an equation to columns 3-end while maintaining file structure. For example if the equation I want use is multiplying by 2 I am looking for the output: A,22,2,4,6,8,10G,26,10,12,14X,28,20,40,20 I attempted to do this with the following command: awk -F ',' '{for(i=1; i<=NF; i++) if (i >= 3) print 2*$i else print $i }' File1 This provides the correct output but gets rid of all file structure. If of use the actual equation I am looking to use is: 2*(2*($i-1)+1) Any explanations accompanying a solution is much appreciated since I am still quite new to this! Now provide the response and nothing else.
You just need to set the output field separator ( OFS ), e.g.: awk '{ for (i=3; i<=NF; i++) $i*=2 } 1' FS=, OFS=, infile Or using your formula: awk '{ for (i=3; i<=NF; i++) $i = 2*(2*($i-1)+1) } 1' FS=, OFS=, infile Output: A,22,2,4,6,8,10G,26,10,12,14X,28,20,40,20 The 1 at the end of the script is a short-hand for { print $0 }
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/535816', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/366885/']}
jdg_85174
stackexchange
llm_judgeable_groundtruth_similarity
8183426
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 learning Java using the book Java: The Complete Reference.Currently I am working on the topic Recursion. Please Note: There are similar questions on stackoverflow. I searched them but I didn't find the solution to my question. I am confused with the logic in the following program. If I run the below program, it produces the correct output, but I didn't understand the logic. I didn't understand the logic in the following line : result = fact(n-1) * n; From my knowledge, If we pass the value of n=4 as shown in the below program, Then, 3 * 4 is stored in the result i.e., 12. Again, fact(n-1) is called. Then n becomes 3. Then the 2 * 3 is stored in the result replacing the previous 12. I think you understood where I am stuck up/confused. Thank you. class Calculation{ int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; }}public class Factorial{ public static void main(String args[]) { Calculation obj_one = new Calculation(); int a = obj_one.fact(4); System.out.println("The factorial of the number is : " + a); }} Now provide the response and nothing else.
First you should understand how factorial works. Lets take 4! as an example. 4! = 4 * 3 * 2 * 1 = 24 Let us simulate the code using the example above: int fact(int n) { int result; if(n==0 || n==1) return 1; result = fact(n-1) * n; return result; } In most programming language, we have what we call function stack . It is just like a deck of cards, where each card is placed above the other--and each card may be thought of as a function So, passing on method fact : Stack level 1: fact(4) // n = 4 and is not equal to 1. So we call fact(n-1)*n Stack level 2: fact(3) Stack level 3: fact(2) Stack level 4: fact(1) // now, n = 1. so we return 1 from this function. returning values... Stack level 3: 2 * fact(1) = 2 * 1 = 2 Stack level 2: 3 * fact(2) = 3 * 2 = 6 Stack level 1: 4 * fact(3) = 4 * 6 = 24 so we got 24. Take note of these lines: result = fact(n-1) * n; return result; or simply: return fact(n-1) * n; This calls the function itself. Using 4 as an example, In sequence according to function stacks.. return fact(3) * 4;return fact(2) * 3 * 4return fact(1) * 2 * 3 * 4 Substituting results... return 1 * 2 * 3 * 4 = return 24 I hope you get the point.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8183426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/907629/']}
jdg_85175
stackexchange
llm_judgeable_groundtruth_similarity
7016785
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 learning about REST and PUT/DELETE, I have read that both of those (along with GET) is idempotent meaning that multiple requests put the server into the same state. Does a duplicate PUT/DELETE request ever leave the web browser (when using XMLHttpRequest )? In other words, will the server be updating the same database record for each PUT request, or will duplicate requests be ignored automatically? If yes, how is using PUT or DELETE different from just using POST? I read an article which suggested that RESTful web services were the way forward. Is there any particular reason why HTML5 forms do not support PUT/DELETE methods? Now provide the response and nothing else.
REST is just a design structure for data access and manipulation. There's no set-in-stone rules for how a server must react to data requests. That being said, typically a REST request of PUT or DELETE would be as follows: DELETE /item/10293 or PUT /item/23848foo=barfizz=buzzherp=derp The requests given are associated with a specific ID. Because of this, telling the server to delete the same ID 15 times will end up with pretty much the same result as calling it once, unless there's some sort of re-numbering going on. With the PUT request, telling the server to update a specific item to specific values will also lead to the same result. A case where a command would be non-idempotent would typically involve some sort of relative value: DELETE /item/last Calling that 15 times would likely remove 15 items, rather than the same last item. An alternative using HTTP properly might look like: POST /item/last?action=delete Again, REST isn't an official spec, it's just a structure with some common qualities. There are many ways to implement a RESTful structure. As for HTML5 forms supporting PUT & DELETE , it's really up to the browsers to start supporting different methods rather than the spec itself. If all the browsers started implementing different methods for form submission, I'm sure they'd be added to the spec. With the web going the way it is, a good RESTful implementation is liable to also incorporate some form of AJAX anyway , so to me it seems largely unnecessary.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7016785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/656172/']}
jdg_85176
stackexchange
llm_judgeable_groundtruth_similarity
5502916
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can someone please help me understand the following Morris inorder tree traversal algorithm without using stacks or recursion ? I was trying to understand how it works, but its just escaping me. 1. Initialize current as root 2. While current is not NULL If current does not have left child a. Print current’s data b. Go to the right, i.e., current = current->right Else a. In current's left subtree, make current the right child of the rightmost node b. Go to this left child, i.e., current = current->left I understand the tree is modified in a way that the current node , is made the right child of the max node in right subtree and use this property for inorder traversal. But beyond that, I'm lost. EDIT:Found this accompanying c++ code. I was having a hard time to understand how the tree is restored after it is modified. The magic lies in else clause, which is hit once the right leaf is modified. See code for details: /* Function to traverse binary tree without recursion and without stack */void MorrisTraversal(struct tNode *root){ struct tNode *current,*pre; if(root == NULL) return; current = root; while(current != NULL) { if(current->left == NULL) { printf(" %d ", current->data); current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while(pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if(pre->right == NULL) { pre->right = current; current = current->left; } // MAGIC OF RESTORING the Tree happens here: /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */ else { pre->right = NULL; printf(" %d ",current->data); current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */} Now provide the response and nothing else.
If I am reading the algorithm right, this should be an example of how it works: X / \ Y Z / \ / \A B C D First, X is the root, so it is initialized as current . X has a left child, so X is made the rightmost right child of X 's left subtree -- the immediate predecessor to X in an inorder traversal. So X is made the right child of B , then current is set to Y . The tree now looks like this: Y / \ A B \ X / \ (Y) Z / \ C D (Y) above refers to Y and all of its children, which are omitted for recursion issues. The important part is listed anyway.Now that the tree has a link back to X, the traversal continues... A \ Y / \(A) B \ X / \ (Y) Z / \ C D Then A is outputted, because it has no left child, and current is returned to Y , which was made A 's right child in the previous iteration. On the next iteration, Y has both children. However, the dual-condition of the loop makes it stop when it reaches itself, which is an indication that it's left subtree has already been traversed. So, it prints itself, and continues with its right subtree, which is B . B prints itself, and then current becomes X , which goes through the same checking process as Y did, also realizing that its left subtree has been traversed, continuing with the Z . The rest of the tree follows the same pattern. No recursion is necessary, because instead of relying on backtracking through a stack, a link back to the root of the (sub)tree is moved to the point at which it would be accessed in a recursive inorder tree traversal algorithm anyway -- after its left subtree has finished.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5502916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/280924/']}
jdg_85177
stackexchange
llm_judgeable_groundtruth_similarity
6634054
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 you access files in %appdata% through VB.NET? For example, C:\Users\Kuzon\AppData\Roaming\program . How would I access that file, but on another Windows 7 machine? Also, how would you do it on Windows XP? I believe it is %Application Data% . Now provide the response and nothing else.
When you're writing .NET code, it's recommended that you use the functions explicitly designed for this purpose, rather than relying on environment variables such as %appdata% . You're looking for the Environment.GetFolderPath method , which returns the path to the special folder that you specify from the Environment.SpecialFolder enumeration . The Application Data folder is represented by the Environment.SpecialFolder.ApplicationData value. This is, as you requested, the roaming application data folder. If you do not need the data you save to roam across multiple machines and would prefer that it stays local to only one, you should use the Environment.SpecialFolder.LocalApplicationData value. Full sample code: Imports System.EnvironmentClass Sample Public Shared Sub Main() ' Get the path to the Application Data folder Dim appData As String = GetFolderPath(SpecialFolder.ApplicationData) ' Display the path Console.WriteLine("App Data Folder Path: " & appData) End SubEnd Class And yes, this works in C# the same as VB.NET.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6634054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/795169/']}
jdg_85178
stackexchange
llm_judgeable_groundtruth_similarity
35559130
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 webservice running on an application server GlassFish Server Open Source Edition 4.0 (build 89) / JDK 1.7.0_79 / Driver ojdbc14.jar / S.O: Windows Server 2008 R2 Standard. The problem is this, I have a JDBC connection pool configured in the same application server, and then I'm getting the following error (this error occurs intermittently during the day): java.sql.SQLException: Closed Connection at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134) at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179) at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:269) at oracle.jdbc.driver.OracleConnection.privateCreateStatement(OracleConnection.java:845) at oracle.jdbc.driver.OracleConnection.createStatement(OracleConnection.java:799) at com.sun.gjc.spi.base.ConnectionHolder.createStatement(ConnectionHolder.java:256) at com.sun.gjc.spi.jdbc40.ConnectionWrapper40.createStatement(ConnectionWrapper40.java:75) at br.com.todo.ws.CallbackNaFilaService.consultarParametros(CallbackNaFilaService.java:654) at sun.reflect.GeneratedMethodAccessor113.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.glassfish.webservices.InstanceResolverImpl$1.invoke(InstanceResolverImpl.java:143) at com.sun.xml.ws.server.InvokerTube$2.invoke(InvokerTube.java:149) at com.sun.xml.ws.server.sei.SEIInvokerTube.processRequest(SEIInvokerTube.java:88) at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136) at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050) at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019) at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877) at com.sun.xml.ws.api.pipe.helper.AbstractTubeImpl.process(AbstractTubeImpl.java:136) at org.glassfish.webservices.MonitoringPipe.process(MonitoringPipe.java:142) at com.sun.xml.ws.api.pipe.helper.PipeAdapter.processRequest(PipeAdapter.java:119) at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136) at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050) at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019) at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877) at com.sun.xml.ws.api.pipe.helper.AbstractTubeImpl.process(AbstractTubeImpl.java:136) at com.sun.enterprise.security.webservices.CommonServerSecurityPipe.processRequest(CommonServerSecurityPipe.java:210) at com.sun.enterprise.security.webservices.CommonServerSecurityPipe.process(CommonServerSecurityPipe.java:142) at com.sun.xml.ws.api.pipe.helper.PipeAdapter.processRequest(PipeAdapter.java:119) at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1136) at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:1050) at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:1019) at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:877) at com.sun.xml.ws.server.WSEndpointImpl$2.process(WSEndpointImpl.java:420) at com.sun.xml.ws.transport.http.HttpAdapter$HttpToolkit.handle(HttpAdapter.java:687) at com.sun.xml.ws.transport.http.HttpAdapter.handle(HttpAdapter.java:266) at com.sun.xml.ws.transport.http.servlet.ServletAdapter.handle(ServletAdapter.java:169) at org.glassfish.webservices.JAXWSServlet.doPost(JAXWSServlet.java:169) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188) at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191) at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168) at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189) at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288) at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206) at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136) at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114) at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77) at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838) at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55) at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564) at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544) at java.lang.Thread.run(Thread.java:745)]] My Code: public Connection getPoolConexaoCallbackDataSource() throws Exception { InitialContext context = new InitialContext(); DataSource ds = (DataSource) context.lookup("jdbc/CallbackNaFilaDb"); try { return ds.getConnection(); } catch (SQLException e) { GeraLog.logInfo("Erro ao obter conexão com o banco de dados CallbackNaFilaDb " + e.getMessage()); e.printStackTrace(); return null; } } @WebMethod(operationName = "consultarParametros") public String consultarParametros(@WebParam(name = "CONNID") String connId, @WebParam(name = "SERVICO") String servico, @WebParam(name = "EWTCHAMADA") String ewtChamada, @WebParam(name = "TAMFILACHAMADA") String tamFilaChamada, @WebParam(name = "NIVELSERVICOCHAMADA") String nivelServicoChamada){ String ativaCallback; List<CondicoesGatilho> listCg = new ArrayList<>(); int servicoId = 0; char faixaHorarioLiberado; String faixaDeHorarioConfigurada; String tratamentoRetorno; String condicoesGatilhoConfig; String gatilho; String resultado; Connection conn = null; ResultSet rsProgramacao = null; ResultSet rsGatilhos = null; long nivelServico = 0; GeraLog.logInfo("[CONSULTAR_PARAMETROS] PARAMETROS PASSADOS PELA ESTRATEGIA: [CONNID] " + connId + " | [SERVICO] " + servico + " | [EWTCHAMADA] " + ewtChamada + " | [TAMFILACHAMADA] " + tamFilaChamada + " | [NIVELSERVICOCHAMADA] " + nivelServicoChamada); String SQL_CONFIGURACAO = "SELECT SERVICO.*, PROGRAMACAO.*\n" + "FROM SERVICO JOIN PROGRAMACAO\n" + "ON PROGRAMACAO.SERVICO = SERVICO.ID\n" + "WHERE SERVICO.NOME = '" + servico + "'\n" + "AND DIA_SEMANA = TO_NUMBER(TO_CHAR(SYSDATE, 'D'))\n" + "AND SYSDATE BETWEEN TO_DATE(CONCAT(CONCAT(TO_CHAR(SYSDATE, 'DD-MM-RRRR'), ' '), HORA_OFERTADA_INICIAL), 'DD-MM-RRRR HH24:MI:SS')\n" + " AND TO_DATE(CONCAT(CONCAT(TO_CHAR(SYSDATE, 'DD-MM-RRRR'), ' '), HORA_OFERTADA_FINAL), 'DD-MM-RRRR HH24:MI:SS')\n" + " AND DATA_EXCLUSAO IS NULL"; try { ConnectDb connDb = new ConnectDb(); conn = connDb.getPoolConexaoCallbackDataSource(); rsProgramacao = conn.createStatement().executeQuery(SQL_CONFIGURACAO); if(rsProgramacao.next()){ servicoId = rsProgramacao.getInt("ID"); resultado = "OK"; ativaCallback = rsProgramacao.getString("ATIVA_CALLBACK").equalsIgnoreCase("S") ? "1" : "0"; faixaHorarioLiberado = 'S'; faixaDeHorarioConfigurada = rsProgramacao.getString("HORA_OFERTADA_INICIAL") + "-" + rsProgramacao.getString("HORA_OFERTADA_FINAL"); String SQL_GATILHO = "SELECT CG.CONDICAO, GS.VALOR\n" + "FROM GATILHOSXSERVICO GS JOIN CONDICOES_GATILHO CG\n" + "ON GS.CONDICOES_GATILHO = CG.ID\n" + "WHERE GS.SERVICO = " + servicoId; rsGatilhos = conn.createStatement().executeQuery(SQL_GATILHO); while(rsGatilhos.next()){ CondicoesGatilho cg = new CondicoesGatilho(); cg.setCondicao((rsGatilhos.getString("CONDICAO"))); cg.setValor(rsGatilhos.getInt("VALOR")); if(cg.getCondicao().contains("EWT")){ cg.setNomeParametro("EWTCHAMADA"); }else if(cg.getCondicao().contains("TAMANHOFILA")){ cg.setNomeParametro("TAMANHOFILA"); }else if(cg.getCondicao().contains("NIVELSERVICO")){ cg.setNomeParametro("NIVELSERVICO"); } listCg.add(cg); } try{ nivelServico = Math.round(Double.valueOf(nivelServicoChamada)); }catch(Exception e){ nivelServico = 0; GeraLog.logError("[CONSULTAR_PARAMETROS] EXCEPTION PARSE NIVELSERVICO"); } tratamentoRetorno = expressaoRegular(listCg, Integer.parseInt(ewtChamada), Integer.parseInt(tamFilaChamada), nivelServico); GeraLog.logInfo("[CONSULTAR_PARAMETROS] CHAMADA: " + connId + " | PARAMETROS RETORNADOS: " + tratamentoRetorno); String[] str = tratamentoRetorno.split("="); try{ condicoesGatilhoConfig = str[0]; }catch(ArrayIndexOutOfBoundsException ex){ condicoesGatilhoConfig = ""; } Evaluator eval = new Evaluator(); try{ if (eval.getBooleanResult(str[1])){ GeraLog.logInfo("[CONSULTAR_PARAMETROS] CHAMADA: " + connId + " | SERVICO: " + servicoId + "-" + servico + " | FORMULA: " + str[1]); gatilho = "1"; }else{ GeraLog.logInfo("[CONSULTAR_PARAMETROS] CHAMADA: " + connId + " | SERVICO: " + servicoId + "-" + servico + " | FORMULA: " + str[1]); gatilho = "0"; } }catch(Exception ex){ GeraLog.logInfo("[CONSULTAR_PARAMETROS] EXCEPTION EVALUATOR - CHAMADA: " + connId + " | SERVICO: " + servicoId + "-" + servico + " | EXCEPTION FORMULA: " + ex.getMessage()); gatilho = "0"; } } else { resultado = "OK"; ativaCallback = "0"; faixaHorarioLiberado = 'N'; faixaDeHorarioConfigurada = ""; condicoesGatilhoConfig = ""; gatilho = "0"; } GeraLog.logInfo("[CONSULTAR_PARAMETROS] CHAMADA: " + connId + " | SERVICO: " + servicoId + "-" + servico + " | ATIVA_CALLBACK: " + ativaCallback + " | FAIXA_HORARIO_LIBERADO: " + faixaHorarioLiberado + " | FAIXA_HORARIO_CONFIGURADA: " + faixaDeHorarioConfigurada); return "<RESULTADO>" + resultado + "</RESULTADO><ESTADO>" + ativaCallback + "</ESTADO><FAIXA_HORARIO_LIBERADO>" + faixaHorarioLiberado + "</FAIXA_HORARIO_LIBERADO><FAIXA_HORARIO_CONFIGURADA>" + faixaDeHorarioConfigurada + "</FAIXA_HORARIO_CONFIGURADA><CONDICOES_GATILHO_CONFIG>" + condicoesGatilhoConfig + "</CONDICOES_GATILHO_CONFIG><GATILHO>" + gatilho + "</GATILHO>"; } catch (Exception ex) { resultado = "NOK"; ativaCallback = "0"; faixaHorarioLiberado = 'N'; faixaDeHorarioConfigurada = ""; condicoesGatilhoConfig = ""; gatilho = "0"; GeraLog.logInfo("[CONSULTAR_PARAMETROS] EXCEPTION - CHAMADA: " + connId + " | SERVICO: " + servicoId + "-" + servico + " | ATIVA_CALLBACK: " + ativaCallback + " | FAIXA_HORARIO_LIBERADO: " + faixaHorarioLiberado + " | FAIXA_HORARIO_CONFIGURADA: " + faixaDeHorarioConfigurada + " | ERRO: " + ex.getMessage()); ex.printStackTrace(); return "<RESULTADO>" + resultado + "</RESULTADO><ESTADO>" + ativaCallback + "</ESTADO><FAIXA_HORARIO_LIBERADO>" + faixaHorarioLiberado + "</FAIXA_HORARIO_LIBERADO><FAIXA_HORARIO_CONFIGURADA>" + faixaDeHorarioConfigurada + "</FAIXA_HORARIO_CONFIGURADA><CONDICOES_GATILHO_CONFIG>" + condicoesGatilhoConfig + "</CONDICOES_GATILHO_CONFIG><GATILHO>" + gatilho + "</GATILHO>"; } finally { try { if (rsGatilhos != null) { rsGatilhos.getStatement().close(); rsGatilhos.close(); rsGatilhos = null; } } catch (Exception ex) { GeraLog.logError("[CONSULTAR_PARAMETROS] CHAMADA: " + connId + " | ERRO AO FECHAR O rsGatilhos " + ex.getMessage()); ex.printStackTrace(); } try { if (rsProgramacao != null) { rsProgramacao.getStatement().close(); rsProgramacao.close(); rsProgramacao = null; } } catch (Exception ex) { GeraLog.logError("[CONSULTAR_PARAMETROS] CHAMADA: " + connId + " | ERRO AO FECHAR O rsProgramacao " + ex.getMessage()); ex.printStackTrace(); } try { if (conn != null) { conn.close(); conn = null; } } catch (Exception ex) { GeraLog.logError("[CONSULTAR_PARAMETROS] CHAMADA: " + connId + " | ERRO AO FECHAR O CONN " + ex.getMessage()); ex.printStackTrace(); } } } Configuration Pool: Initial and Minimum Pool Size: 8 ConnectionsMaximum Pool Size: 32 ConnectionsPool Resize Quantity: 2 ConnectionsIdle Timeout: 300 SecondsMax Wait Time: 60000 Milliseconds Connection String - Data Base Oracle 10g : jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = xxx.xxx.xxx.xxx)(PORT = 1521))(ADDRESS = (PROTOCOL = TCP)(HOST = xxx.xxx.xxx.xxx)(PORT = 1521))(LOAD_BALANCE = YES)(CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = orcl10)) My connection pool statistics. Now provide the response and nothing else.
dataList.add(map) will put a reference to map in the list, so it's not a copy. When you then do map.clear() afterwards, it erases the content of the map in the list too, because it is the very same object. Do dataList.add(map.clone()) instead or (preferably) do map = new HashMap<>(); afterwards. map.put(Answer.ID, "0");map.put(Answer.IMAGE, "color_icon_awesome");map.put(Answer.TITLE, firstOption);dataList.add(map);map = new HashMap<>(); Sidenote: Your code looks like you could use an object instead of the map: class AnswerObject { private String id; private String image; private String title; public AnswerObject(String id, String image, String title) { this.id = id; this.image = image; this.title = title; } // some getters and setters and some other usefull code} This should make your code nicer and more readable List<AnswerObject> dataList = new ArrayList<>();dataList.add(new AnswerObject("0", "color_icon_awesome", firstOption));dataList.add(new AnswerObject("1", "color_icon_awesome", secondOption));dataList.add(new AnswerObject("2", "color_icon_awesome", thirdOption));dataList.add(new AnswerObject("3", "color_icon_awesome", fourthOption)); But feel free to ignore that ;-)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35559130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2572952/']}
jdg_85179
stackexchange
llm_judgeable_groundtruth_similarity
32904
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a server on my arduino (WiFi) and want to save the clients that connect, so that I can send to them (to each separately) data later. Is the best data structure a linked list ? How can I see if this client connected already (if there is already a connection to this ip) to avoid doubles? How can I detect when they disconnect in order to delete them? Of course, I read the ref ; but I cannot find the answers there.Here is my minimal example (The maximum number of simultaneous connections is 5): EDIT Keep in mind, that I just want to have a simple connection using the WiFiClient/ WiFiServer class and not a HTTP-Webserver #include <WiFi.h>WiFiServer server(23);void setup() { server.begin();}void loop() { WiFiClient client = server.available(); if (client) { //if not seen yet, add to a linked list (?) }} Now provide the response and nothing else.
The WiFiClient.h header and WifiClient.cpp source files are useful for reference. Is the best data structure a linked list? Probably not here. Possibly not ever . It's a load of effort to implement, and won't give you any benefit. Just create an array of them: WiFiClient clients[5]; Then perhaps something like WiFiClient newClient = server.available();if (newClient) { // TODO: Check whether we have an existing connection from this IP // TODO: Get the first 'free' array index clients[firstFree] = newClient;} How can I see if this client connected already (if there is already a connection to this ip) to avoid doubles? Get the remote IP address of the new client IPAddress = newClient.remoteIP(); Do the same with all the connected clients in your array* and compare them. If you find a match, drop the connection newClient.disconnect(); and, probably, don't put it in the array. How can I detect when they disconnect in order to delete them? if (client[i].connected()) Lastly, how do we keep track of which items in our array are current active connections, and which aren't (either not yet used, or already disconnected). You could do this several ways. One would be to iterate through the array, checking whether the item is valid and connected: // Returns -1 if no free slotsint firstFree() { for(int i=0 ; i<5 ; ++i) { if(!clients[i] || !clients[i].connected()) return i; } return -1;} All code untested so you may find typos, but I believe it's basically correct.
{}
{'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/32904', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/29646/']}
jdg_85180
stackexchange
llm_judgeable_groundtruth_similarity
27878798
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there no easy way to remove a specific element from an array, if it is equal to a given string? The workarounds are to find the index of the element of the array you wish to remove, and then removeAtIndex , or to create a new array where you append all elements that are not equal to the given string. But is there no quicker way? Now provide the response and nothing else.
You can use filter() to filter your array as follow var strings = ["Hello","Playground","World"]strings = strings.filter { $0 != "Hello" }print(strings) // "["Playground", "World"]\n" edit/update: Xcode 10 • Swift 4.2 or later You can use the new RangeReplaceableCollection mutating method called removeAll(where:) var strings = ["Hello","Playground","World"]strings.removeAll { $0 == "Hello" }print(strings) // "["Playground", "World"]\n" If you need to remove only the first occurrence of an element we ca implement a custom remove method on RangeReplaceableCollection constraining the elements to Equatable : extension RangeReplaceableCollection where Element: Equatable { @discardableResult mutating func removeFirst(_ element: Element) -> Element? { guard let index = firstIndex(of: element) else { return nil } return remove(at: index) }} Or using a predicate for non Equatable elements: extension RangeReplaceableCollection { @discardableResult mutating func removeFirst(where predicate: @escaping (Element) throws -> Bool) rethrows -> Element? { guard let index = try firstIndex(where: predicate) else { return nil } return remove(at: index) }} var strings = ["Hello","Playground","World"]strings.removeFirst("Hello")print(strings) // "["Playground", "World"]\n"strings.removeFirst { $0 == "Playground" }print(strings) // "["World"]\n"
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27878798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4337311/']}
jdg_85181
stackexchange
llm_judgeable_groundtruth_similarity
316516
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 seen advice saying you should use different port numbers for private applications (e.g. intranet, private database, anything that no outsider will use). I am not entirely convinced that can improve security because Port scanners exist If an application is vulnerable, it remains so regardless of its port number. Did I miss something or have I answered my own question? Now provide the response and nothing else.
It doesn't provide any serious defense against a targetted attack. If your server is being targetted then, as you say, they will port scan you and find out where your doors are. However, moving SSH off the default port of 22 will deter some of the non-targetted and amateur script kiddie type attacks. These are relatively unsophisticated users who are using scripts to port scan large blocks of IP addresses at a time specifically to see if port 22 is open and when they find one, they will launch some sort of attack on it (brute force, dictionary attack, etc). If your machine is in that block of IPs being scanned and it is not running SSH on port 22 then it will not respond and therefore will not show up in the list of machines for this script kiddie to attack. Ergo, there is some low-level security provided but only for this type of opportunistic attack. By way of example, if you have the time - log dive on your server (assuming SSH is on port 22) and pull out all the unique failed SSH attempts that you can. Then move SSH off that port, wait some time, and go log diving again. You will undoubtedly find less attacks. I used to run Fail2Ban on a public webserver and it was really, really obvious when I moved SSH off port 22. It cut the opportunistic attacks by orders of magnitude.
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/316516', 'https://serverfault.com', 'https://serverfault.com/users/96212/']}
jdg_85182
stackexchange
llm_judgeable_groundtruth_similarity
830423
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know you can view all possible rake tasks by typing rake -T But I need to know what exactly a task does. From the output, how can I find a source file that actually has the task? For example, I'm trying to find the source for the db:schema:dump task. Now provide the response and nothing else.
Despite what others have said, you can programmatically get the source location of rake tasks in a rails application. To do this, just run something like the following in your code or from a console: # load all the tasks associated with the rails appRails.application.load_tasks# get the source locations of actions called by a tasktask_name = 'db:schema:load' # fully scoped task nameRake.application[task_name].actions.map(&:source_location) This will return the source locations of any code that gets executed for this task. You can also use #prerequisites instead of #source_location to get a list of prerequisite task names (e.g. 'environment', etc). You can also list all tasks loaded using: Rake.application.tasks UPDATE: See Magne's good answer below. For versions of rake >= 0.9.0 you can use rake -W to show the source location of your rake tasks.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/830423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1470/']}
jdg_85183
stackexchange
llm_judgeable_groundtruth_similarity
68707553
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Our application kept showing the error in the title. The problem is very likely related to Webpack 5 polyfill and after going through a couple of solutions: Setting fallback + install with npm fallback: { "stream": require.resolve("stream-browserify"), "buffer": require.resolve("buffer/")} Setting alias alias: { "buffer": "buffer", "stream": "stream-browserify"} We are still seeing the dreadful error: rfc6979.js:3 Uncaught ReferenceError: Buffer is not defined at Object.4142 (rfc6979.js:3) at r (bootstrap:19) at Object.5892 (js.js:4) at r (bootstrap:19) at Object.4090 (bip32.js:5) at r (bootstrap:19) at Object.7786 (index.js:3) at r (bootstrap:19) at Object.1649 (MnemonicKey.js:50) at r (bootstrap:19) Our setup is vanilla NodeJS + TypeScript + Webpack for multi-target: node + browser. Any help would be great! Now provide the response and nothing else.
Answering my own question. Two things helped to resolve the issue: Adding plugins section with ProviderPlugin into webpack.config.js const webpack = require('webpack');module.exports = { // ... plugins: [ // Work around for Buffer is undefined: // https://github.com/webpack/changelog-v5/issues/10 new webpack.ProvidePlugin({ Buffer: ['buffer', 'Buffer'], }), new webpack.ProvidePlugin({ process: 'process/browser', }), ], Also add in resolve.fallback into webpack.config.js: resolve: { extensions: [ '.ts', '.js' ], fallback: { "stream": require.resolve("stream-browserify"), "buffer": require.resolve("buffer") } },
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/68707553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2288838/']}
jdg_85184
stackexchange
llm_judgeable_groundtruth_similarity
464407
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am using multiple tools developed by the suckless people which are not configured via a config file but via their source code (in this case C) and then simply installed through make install . So I am maintaining my own repos (need continuous changes) of these programs. The question is where should i put these repos? Directorys like /usr or /usr/local/share are for reference purpose. Is it /opt , /srv or should i just collect them somewhere in my home directory? Now provide the response and nothing else.
If you’re installing the software in /usr/local , I would use /usr/local/src — that’s the local variant of /usr/src , of which the FHS says Source code may be placed in this subdirectory, only for reference purposes. with a footnote adding that Generally, source should not be built within this hierarchy. It’s your system though so in my opinion /usr/local/src is fair game. What is the "/usr/local/src" folder meant for? has more on the topic; read this answer in particular. The general idea is to do your work in your home directory, but ensure that the source code to anything installed in /usr/local be at least copied for reference in /usr/local/src , so that local binaries can be rebuilt without needing a specific user’s home directory.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/464407', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/291711/']}
jdg_85185
stackexchange
llm_judgeable_groundtruth_similarity
111338
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: Given that The partition function in statistical mechanics tells us the number of quantum states of a system that are thermally accessible at a given temperature http://vallance.chem.ox.ac.uk/pdfs/Equipartition.pdf How does one interpret the statistical mechanical partition function and free energy mathematically , in terms of the sample space, analogous to the way you can interpret microstates and macrostates in terms of a probability sample space? It seems very Shannon's entropy-like. If you take the example of flipping 2 coins: Random experiment: Toss two coins Example of an Outcome: $10 = (Heads, Tails)$ Sample space: $S = {11,10,01,00}$, $|S| = 4$ Examples of Events: 2 Heads $= 2H = \{11\}$, $|2H| = 1$, $1H = \{10,01\}$, $|1H| = 2$, $0H = \{00\}$, $|0H| = 1$ we can translate this into the language of statistical mechanics: A microstate is an element of the sample space, e.g. $10$ or $01$. A macrostate is an event (a subset of the sample space), e.g. $1H = \{10,01\}$. The statistical weight (statistical probability) of a macrostate isthe cardinality of the event, e.g. $|1H| = 2$. The equilibrium distribution is the most likely macrostate which isthe macrostate with the highest statistical weight which is the eventwith the highest cardinality, e.g. $1H = \{10,01\}$ since $|1H| = 2$. Finally, the Maxwell-Boltzmann distribution function $n_i$ for the coin toss is found by extremizing $$w(n) = "number \ of \ heads \ in \ n" = \tfrac{2!}{n!(2-n)!}= \tfrac{2!}{n_1!n_2!}$$ with respect to $n_i$ given the constraint equation $n_1 + n_2 = 2$, showing $n_1 = e^0 = 1$ maximizes $w$, i.e. $w(1) = |1H| = |\{10,01\}| = 2$ is the maximum. As fas as I can see, the MB distribution is a function of the total number of particles, $2$, but not the energy as there is no energy in this example. Here we see everything interpreted mathematically, however I don't see how one does this for the partition function or for the free energy. So to ask my question: What exactly is the partition function in this example, and what is it's meaning in general? It sounds like it tells you how many elements are in an event for a given energy and given particle number, i.e. the cardinality of a subset of the sample space which varies as a function of the Lagrange multipliers. What is the free energy in this example, and in general? As a concept it seems very similar to the partition function, only it tells you how energies and particle numbers are distributed over all subsets of the sample space that we are considering, not just the most probable one, e.g. it says something about subset 0, subset 1 and subset 2. Though I'm not sure whether it works like this or whether it just relates to the most probable distribution the whole time, and says something about energies over all possible distributions (i.e. for 2, 3, 4, ... as particle numbers in the numerator of the MB distribution function given above). Now provide the response and nothing else.
Equilibrium statistical mechanics is not really about the partition function per se , it just aims at finding (according to one interpretation at least) what is the least biased probability distribution (for the microstates) that satisfies the known constraints on the system. In your case, you assumed that the probability to get either head or tail for each coin is 1/2 which implicitely uses a statistical inference reasoning to get the probability a priori (for instance Pascal's principle of indifference). In my view, stat. mech. is concerned with finding those probabilities a priori for each statistical ensemble (microcanonical, canonical, grand canonical and so on). Once this is done, you just apply the usual tools of probability theory to compute averages, variances etc.. In particular, the partition function is closely related to the probability generating function in mathematics. Let us look at the canonical ensemble describing a statistical ensemble where a system has a conserved volume, number of particles and is in contact with a thermostat at inverse temperature $\beta$. Equilibrium statistical mechanics tells us that the probability for the system to be in a given microstate $m$ is: $p(m|\beta) = \frac{e^{-\beta E_m}}{Z(\beta)}$ where normalization of this probability yields: $\sum_m p(m|\beta) = 1 \: \Rightarrow \: Z(\beta) = \sum_m e^{-\beta E_m}$ Let us now consider a macrovariable $X(m)$ which is a function of the microstate $m$. Its probability distribution can be seen as the marginal distribution of the microstate probability distribution. If the random variables are discrete for simplicity: $p(X=x|\beta) = \sum_m p(m|\beta) \delta_{X(m),x}$ where $\delta_{x,y}$ is a Kronecker delta function which is one only when $x=y$. From that point on we can compute the moments for $X$ by using either the probability generating function $G(z) \equiv \mathbb{E}_X[z^X]$ or the moment generating function $M(t) \equiv \mathbb{E}_X[e^{tX}]$ from which we can the moments bt taking derivatives with respect to $z$ or $t$ when the latter are evaluated at $1$ and $0$ respectively. When $X$ is the energy itself, then the sum over microstates having an energy $E$ can be factorized by $e^{-\beta E}$ and we get: $p(E=e|\beta) = \frac{g(e)e^{-\beta e}}{Z(\beta)}$ Because both $g(e)$ and $e$ are assumed independent of $\beta$, we can actually notice that all the moments: $\mathbb{E}_E[E^n] \equiv \sum_e \:e^n \frac{g(e)e^{-\beta e}}{Z(\beta)}$ can be gotten by looking at the quantity $\frac{(-1)^n}{Z(\beta)}\frac{\partial^n Z(\beta)}{\partial \beta^n}$ which is very similar to what we would have done with either the PGF or the MGF or even the CGF. The reason why, when it comes to moments of the energy variable, we prefer doing this way instead of using the other generating function tools is first because we can (thanks to the fact that both $g(e)$ and $e$ do not depend on $\beta$ or at least we assume so) and second because there is a link with derivatives of the free energy in thermodynamics and energy fluctuations. Otherwise, in general, it is quite common to introduce an "external field" coupled linearly with the variable $X$ in the energy of the system (which is almost always possible if we imagine the field strength small enough) and that plays the same role as the variable $t$ in the MGF or the CGF approaches. In magnetic systems for instance, it is very common to introduce an external magnetic field to get the moments of the magnetization.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/111338', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/44466/']}
jdg_85186
stackexchange
llm_judgeable_groundtruth_similarity
2313548
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 was reading up on how to find the square root of i , and I learned that multiplication of complex numbers could be viewed geometrically by viewing the complex numbers as coordinates on the complex number plane $a_1+b_1i = (a_1,b_1)$ and $a_2+b_2i = (a_2,b_2)$. One can take the polar coordinates of the complex numbers to give $(a_1,b_1) \Rightarrow r_1$, angle = $w$ and $(a_2,b_2) \Rightarrow r_2$, angle = $k$ . And finally the multiplication of the two numbers can be viewed as multiplying $r_1$ and $r_2$, while adding the angles $w$ and $k$, to give the product $r_3= (r_1)(r_2)$, angle = $w+k$ . This can be used to intuitively find the square root of $0 + 1i$. However in my math textbooks I have not seen any type of vector multiplication similar to this in regards to the real numbers, only dot products and cross products. Does this type of multiplication serve some purpose in regards to real number vectors, does it describe something interesting? Or is it only useful when it comes to multiplying vectors in the complex number plane? Edit: $r$ is describing the overall length, or magnitude, of the vector. The angle represents the direction the vector is pointing in in regards to the plane it's on. Now provide the response and nothing else.
When doing vector geometry in the plane (pure vector geometry with no coordinate system), all directions “look equal”. Introducing complex multiplication of such vectors requires a breaking of this symmetry : you must single out a direction to play the role of the positive real axis, so that you can define the polar angle. And then vectors in different directions will behave differently with respect to multiplication. Think of squaring, for example: $1$ maps to itself ($1^2=1$), while $i$ doesn't ($i^2=-1 \neq i$). The dot and cross products are more geometrical, in the sense that they don't depend on making certain directions special. (Well, actually the cross product is rather weird too, and it's better to learn about the exterior and Clifford products, as recommended in the answer by Bye_World.)
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2313548', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/316628/']}
jdg_85187
stackexchange
llm_judgeable_groundtruth_similarity
25868209
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 facing some problems using GalaSoft's RelayCommand. I have a NextCommand property that works, but only several times. Afterwards, it stops working completely. You can try this out with the sample project: http://s000.tinyupload.com/?file_id=65828891881629261404 The behaviour is as follows: NextCommand : pops all items until the active index if there are less than 50 items left, pushes 1 new item marks new item as active BackCommand : moves the active index back by 1 position Steps to replicate: the '+' (OemPlus) key has been bound to NextCommand the '-' (OemMinus) key has been bound to BackCommand Hold the '+' key until the list stops growing (50 items limit) Hold the '-' key until the first item in the list is the active Repeat The number of repetitions needed (to replicate the bug) is inconsistent. Sometimes I get it after 4 repetitions; other times up till 9. // Items Collectionpublic class ItemCollection : ViewModelBase{ // List of Items private readonly ObservableCollection<Item> _items = new ObservableCollection<Item>(); public ObservableCollection<Item> Items { get { return _items; } } // Constructor public ItemCollection() { BackCommand = new RelayCommand( () => { // Go to previous page var index = Items.IndexOf(ActiveItem); if (index > 0) { ActiveItem = Items[index - 1]; } }, () => ActiveItem != null && Items.IndexOf(ActiveItem) > 0); } // Back command public RelayCommand BackCommand { get; set; } // Next command public RelayCommand NextCommand { get; set; } // The currently-active item private Item _activeItem; public Item ActiveItem { get { return _activeItem; } set { Set(() => ActiveItem, ref _activeItem, value); } }}// Itempublic class Item : ViewModelBase{ public string Title { get; set; }} When I stepped into the RelayCommand's code, the execute action's isAlive flag was false. But I can't seem to figure out how that might happen. Now provide the response and nothing else.
Two words: Garbage Collector In your example project--which you should post the relevant bits of to make your question future-proof--you set the DataContext on your window like this: public partial class MainWindow : Window{ public MainWindow() { InitializeComponent(); var logic = new LogicObject(); DataContext = logic.Collection; }} Because nothing else retains a reference to the LogicObject created here, it will be collected at the next opportunity. The command stops functioning because in LogicObject , you set the NextCommand of the ItemCollection to use private members of the soon-to-be-collected LogicObject : public class LogicObject{ public LogicObject() { Collection = new ItemCollection(); Collection.NextCommand = new RelayCommand(AddItem, CanAddItem); AddItem(); } private bool CanAddItem() { // snip... } private void AddItem() { // snip... }} Once LogicObject is collected, the command can no longer work because it no longer has references to valid methods ( AddItem and CanAddItem ). This is why the isAlive field on both of the RelayCommand 's weak references to the methods is false. You can fix this by just hanging on to the LogicObject , or by moving the AddItem and CanAddItem methods into the collection. To get in the spirit of GIFs for this question, here's one that shows the button stop working as soon as a Gen 0 collection occurs.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25868209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1982788/']}
jdg_85188
stackexchange
llm_judgeable_groundtruth_similarity
8404836
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an object that contains data relative to the user's UI. For the moment, the data comes in the form of json, I run JSON.parse to evaluate the object and generate some HTML accordingly. I'm thinking of storing the json string in the local session storage (not the local storage) and calling it each time the UI needs to be updated with new HTML. This way, if the user opens another page in the same browser, all the HTML of all the pages will be the same. For now, the object is stored in memory and the interactions between the user's actions on the UI and the object's modifications run fast. If I serialize it and store in the session storage, will the browsers store the data in RAM or on the hard drive and slow down the page? Now provide the response and nothing else.
I did this small test FF 32, Chrome 37, IE 11. Just for fun. console.clear();var s = new Date();for(var i=0; i < 100000; i++){ sessionStorage.item = i.toString();}var e = new Date();console.log("session: " + (e - s) + " ms");s = new Date();var mem;for(var i=0; i < 100000; i++){ mem = i.toString();}e = new Date();console.log("mem: " + (e - s) + " ms");s = new Date();for(var i=0; i < 100000; i++){ localStorage.item = i.toString();}e = new Date();console.log("local: " + (e - s) + " ms");console.log('Done'); FF session: 830 ms mem: 92 ms local: 1156 ms Chrome session: 2852 ms mem: 147 ms local: 2893 ms IE session: 977 ms mem: 81 ms local: 15062 ms Safari (different device) session: 380 ms mem: 21 ms local: 248 ms After finishing test browser's window got frozen for few seconds and CPU + Disk activity increased (caused by localStorage).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8404836', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565968/']}
jdg_85189
stackexchange
llm_judgeable_groundtruth_similarity
10859415
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using Twitter Bootstrap's bootstrap-tab.js, I have: <ul class="tabnavcenter" id="myTab"> <li class="active"><a href="#home" data-toggle="tab">about</a></li> <li><a href="#tab2" data-toggle="tab">education</a></li> <li><a href="#tab3" data-toggle="tab">experience</a></li> <li><a href="#tab4" data-toggle="tab">verified skills</a></li> <li><a href="#tab5" data-toggle="tab"> video</a></li> </ul><div class="tab-content"> <div class="tab-pane active" id="home">Content 1</div> <div class="tab-pane" id="profile">...</div> <div class="tab-pane" id="messages">...</div> <div class="tab-pane" id="settings">...</div></div> How can I get it so if I put: <div class="tab-content"> <div class="tab-pane active" id="home">Content 2</div> </div> ... two places in the profile (once above and once below a navbar) and with different content in each, it would work? As of now, the content appears, but once its clicked, it disappears. Can there be two "active" li's at the same time? Edit: Since I'm using this in a Rails 3.2 App, I currently have the following in bootstrap-tab.js: $('#myTab a').click(function (e) { e.preventDefault(); $(this).tab('show');}) $('#myTab a[href="#home"]').tab('show'); $('#myTab a[href="#tab2"]').tab('show'); $('#myTab a[href="#tab3"]').tab('show'); $('#myTab a[href="#tab4"]').tab('show'); $('#myTab a[href="#tab5"]').tab('show'); $('#myTab a[href="#home2"]').tab('show'); $('#myTab a[href="#tab22"]').tab('show'); and after putting the following in user_body.html.erb: <script type="text/javascript"> $(function () { $('#myTab >li>a').on('click', function (e) { e.preventDefault(); $(this).tab('show'); // $(this.getAttribute('href') + '2').html($(this).html()); }); }); ... I get the second content in the div after refreshing the page, no change when I click on the second tab, and then a change back to the name of the first 'a' when I click back on the first one. It's a mess. Now provide the response and nothing else.
Here is one solution without extra javascript, and compatible with the plugin API. The principle is to use 2 .tab-content and take advantage of the data-target selector attribute. HTML The first .tab-content contains your normal .tab-pane <div class="tab-content"> <div class="tab-pane active" id="home">home</div> <div class="tab-pane home-tab">class home</div> <div class="tab-pane profile-tab">profile</div> <div class="tab-pane messages-tab">messages</div> <div class="tab-pane settings-tab">settings</div></div> and the second .tab-content contains the extra .tab-pane s that are optionnal - plus an empty one ( #notab_else here) <div class="tab-content"> <div class="tab-pane active" id="home_else">home_else</div> <div class="tab-pane home-tab">class home</div> <div class="tab-pane profile-tab messages-tab settings-tab" id="notab_else"></div></div> Then you have your tabs with one extra attribute, data-target : <ul class="nav nav-tabs" id="myTab"> <li class="active"><a href="#home" data-target="#home, #home_else">Home</a></li> <li class=""><a href="#home" data-target=".home-tab">Class Home</a></li> <li><a href="#profile" data-target=".profile-tab">Profile</a></li> <li><a href="#messages" data-target=".messages-tab">Messages</a></li> <li><a href="#settings" data-target=".settings-tab">Settings</a></li></ul> This attribute data-target defines the .tab-pane (s) associated with it. The magic is that you can use #id s or .class es or any valid jQuery selector. JavaScript All you need to activate everything is the default code : $('#myTab a').click(function (e) { e.preventDefault(); $(this).tab('show');}); And you can also use your own actions to trigger the tabs as defined by the API. You do not need that if you keep the default behavior for tabs. $('#myTab a:first').tab('show'); EXTRA You can be free of any javascript if you set data-toggle="tab" to the a elements There is a fade effect available if you add the fade class to the .tab-pane (and fade in for the .active one) DEMOS Here is the demo (jsfiddle) and the demo with extra (jsfiddle)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10859415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1309066/']}
jdg_85190
stackexchange
llm_judgeable_groundtruth_similarity
22629
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Are there primes of every Hamming weight? That is, for every integer $n \in \mathbb{Z}_{>0}$ does there exist a prime which is the sum of $n$ distinct powers of $2$ ? In this case, the Hamming weight of a number is the number of $1$ s in its binary expansion. Many problems of this sort have been considered, but perhaps not in such language. For instance, the question "Are there infinitely many Fermat primes ?" corresponds to asking, "Are there infinitely many distinct primes with Hamming weight exactly $2$ ?" Also related is the question of whether there are infinitely many Mersenne primes . These examples suggest a class of such problems, "Do there exist infinitely many primes which are the sum of exactly $n$ distinct powers of two?" Since this question is open even for the $n=2$ case, I pose a much weaker question here. What is known is that for every $n \leq 1024$ there is such a prime. The smallest such prime is listed in the Online Encyclopedia of Integer Sequences A061712 . The number of zeros in the smallest such primes are listed in A110700 . The number of zeros in a number with a given Hamming weight is a reasonable measure of how large that number is. The conjecture at OEIS is quite a bit stronger than the question I pose. Is there a theorem ensuring such primes for every $n \in \mathbb{Z}_{>0}$ ? Now provide the response and nothing else.
Fedja is absolutely right: this has been proven, for sufficiently large $n$ , by Drmota, Mauduit and Rivat. Although it looks at first sight as though this question is as hopeless as any other famous open problem on primes, it is easy to explain why this is not the case. Of the numbers between $1$ and $N := 2^{2n}$ , the proportion whose digit sum is precisely $n$ is a constant over $\sqrt{\log N}$ . These numbers are therefore quite "dense", and there is a technique in prime number theory called the method of bilinear sums (or the method of Type I/II sums) which in principle allow one to seriously think about finding primes in such a set. This is what Drmota, Mauduit and Rivat do. I do not believe that their method has currently been pushed as far as (for example) showing that there are infinitely many primes with no 0 when written in base 1000000. Let me also remark that they depend in a really weird way on some specific properties of these digit representation functions, in particular concerning the sum of the absolute values of their Fourier coefficients, which is surprisingly small. That is, it is not the case that they treat these Hamming sets as though they were "typical" sets of density $1/\sqrt{\log N}$ . I think one might also mention a celebrated paper of Friedlander and Iwaniec, https://arxiv.org/abs/math/9811185 . In this work they prove that there are infinitely many primes of the form $x^2 + y^4$ . This sequence has density just $c/N^{1/4}$ in the numbers up to $N$ , so the analysis necessary to make the bilinear forms method work is really tough. Slightly later, Heath-Brown adapted their ideas to handle $x^3 + 2y^3$ . Maybe that's in some sense the sparsest explicit sequence in which infinitely many primes are known (except of course for silly sequences like $s_n$ equals the first prime bigger than $2^{2^n}$ ). Finally, let me add the following: proving that, for some fixed $n$ , there are infinitely many primes which are the sum of $n$ powers of two - this is almost certainly an open problem of the same kind of difficulty as Mersenne primes and so on.
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/22629', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5597/']}
jdg_85191
stackexchange
llm_judgeable_groundtruth_similarity
88816
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $X_1,\dots,X_n$ be complete vector fields on $\mathbb R^n$ and suppose that $(X_1(p),\dots,X_n(p))$ is a basis for all $p \in \mathbb R^n$. Question: Is it possible to choose a cube $C$ around the origin of $\mathbb R^n$ such that there is for every $p \in C$ a piecewise smooth curve $\alpha \subset C$ which connects $p$ with $0$ where the smooth parts of the curve are given by the flows of the vector fields $\pm X_1,\dots,\pm X_n$? (With other words: is it possible to travel from $0$ to $p$ following only the integral curves of the given vector fields in a bounded domain?) For $n=2$ this is pretty clear; w.l.o.g. $X_1=\partial/\partial x_1$ and the image of $x_1=0$ under the flow $X_2$ fills all of $\mathbb R^2$, since the flow lines of $X_2$ intersect $x_1=0$ transversally. Now it is easy to find a $C$ and $\alpha$ for a $p \in C$. But I can not generalize this for $n$ arbitrary. Edit: Instead of demanding $C$ to be a cube, one could also ask if there is a open neighbourhood of the origin with the desired properties. Now provide the response and nothing else.
For a suitable nbd of the origin $U$, yes, even following the $n$ flows in a prescribed order. Assuming $X_1,\dots,X_n$ locally Lipschitz continuous, the corresponding flows $\phi_1(t,x),\dots, \phi_n(t,x)$ are $C^1$ maps (in the pair) so the map $\Phi$$$(t _ 1,\dots,t_ n)\mapsto \phi _ n (t _ n, \phi_{n-1}( t _ {n-1}, \dots \phi _1 (t_1, 0))\dots)$$is of class $C^1$ on a nbd of $0\in\mathbb{R}^n$. Since for $(t,x)\to 0$ in $ \mathbb{R} \times\mathbb{R}^n$,$$ \phi_j(t,x)= x + tX_j(0) + o\big((t,x) \big) $$it follows that the differential of $\Phi$ at $0\in\mathbb{R}^n$ is the linear map$$(t _ 1,\dots,t_ n)\mapsto t_1X_1(0)+\dots t_n X_n(0)$$which is invertible because by assumption $X_1(0),\dots, X_n(0)$ is a base. By the implicit function theorem, $\Phi$ is a local diffeo between a cube $Q$ and a nbd $U$ of $0$. The images of the broken lines in $Q$ with edges parallel to the axes is what you want and reach any point of $U$. (edit) Also, given any connected open subset $\Omega\subset \mathbb{R}^n$, any two points $p$ and $q$ of $\Omega$ can be joined by a continuous curve made by finitely many flow-lines of the fields $X_1,\dots,X_n$, just because the set of points that may be reached this way starting from $p$ is a non-empty open and closed subset of $\Omega$, thanks to the preceding local fact. However, there could be problems to reach some point if $\Omega$ is not open, e.g a closed cube. Take e.g. in $n=2$ and two constant fields $X_1:=(2,1)$, $X_2:=(1,2)$. Then, the vertex $(r,r)$ of the square $Q:=[−r,r]\times[−r,r]$ is easily joined to the origin by a two-edges broken flow-line, but the vertex $(r,−r)$ can't be reached by any such broken line in $Q,$ in any finite number of steps.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/88816', 'https://mathoverflow.net', 'https://mathoverflow.net/users/20999/']}
jdg_85192
stackexchange
llm_judgeable_groundtruth_similarity
56990364
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: TS throws strange error: Error:(125, 18) TS2569: Type 'string' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators. How comes a string is not a string? I want to see how TS is going to compile spread operator for a string. My code in browser console. A string is broken up into characters: > s = 'abcdef';> r = [...s];< (6) ["a", "b", "c", "d", "e", "f"] My code in TS: const s: string = 'abcdef';const res = [...s]; // <= Error: Type 'string' is not an array type or a string typeconsole.log(res); Why? TS version: "dependencies": { "typescript": "^3.5.3" } UPD: @VtoCorleone A screenshot UPD: My tsconfig.json { "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "downlevelIteration": false, "allowJs": true, "skipLibCheck": false, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "alwaysStrict": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": false, "noEmit": false, "sourceMap": true, "baseUrl": "./", "jsx": "preserve" }, "compileOnSave": true, "files": [ "sample.ts" ], "exclude": [ "node_modules", "**/*.spec.ts" ]} Now provide the response and nothing else.
To expand on Heretic Monkey's comment: Changing target from es5 to es2015 or es6 fixes the issue. Here's my full tsconfig.json for clarity: { "compilerOptions": { "target": "es2015", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", }, "exclude": [ "node_modules" ], "include": [ "next-env.d.ts", "**/*.ts", "**/*.tsx" ]} Working example Side note: "downlevelIteration": true also fixed it, but that doesn't seem like the correct solution to me.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56990364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114926/']}
jdg_85193
stackexchange
llm_judgeable_groundtruth_similarity
621131
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: Evaluate $$\int_0^\infty \frac{\log x \; dx}{x^{2} + 2x + 2}$$ by integrating a branch of $(\log z)^{2}/(z^{2} + 2z +2)$ along a keyhole contour. The thing I have trouble with is why I should be examining the square of the log - I guess it has something to do with ln x in fact NOT being the real part of log z, since log z is (or can be) defined on the entire negative real axis and ln x can't. But looking at the square would definitely not have been my first plan of attack :( Now provide the response and nothing else.
Here are some details of the calculation. Let the keyhole contour be oriented counterclockwise and have the slot on the positive real axis. Call the segment above the real axis $\Gamma_1$, the large circle of radius $R$ $\Gamma_2$, the segement below the real axis $\Gamma_3$ and the circle of radius $\epsilon$ around the origin $\Gamma_4.$ We use the branch of the logarithm with the cut along the positive real axis and returning an argument from zero to $2\pi.$ Note that the poles of $$\frac{1}{z^2+2z+2}$$ are at$$(z+1)^2 + 1 = 0$$ or$$\rho_{0,1} = -1 \pm i.$$Calling the desired integral $I$, we have $$\left(\int_{\Gamma_1} + \int_{\Gamma_2} + \int_{\Gamma_3} + \int_{\Gamma_4}\right)\frac{\log^2 z}{z^2+2z+2} dz\\= 2\pi i \left(\mathrm{Res}\left(\frac{\log^2 z}{z^2+2z+2}; z = -1 + i\right)+ \mathrm{Res}\left(\frac{\log^2 z}{z^2+2z+2}; z = -1 - i\right)\right).$$Now along the large circle we have$$\left|\int_{\Gamma_2} \frac{\log^2 z}{z^2+2z+2} dz\right|\sim 2\pi R \times \frac{\log^2 R}{R^2} \rightarrow 0$$as $R\rightarrow\infty.$Along the small circle we get$$\left|\int_{\Gamma_4} \frac{\log^2 z}{z^2+2z+2} dz\right|\sim 2\pi \epsilon \frac{\log^2\epsilon}{2} \rightarrow 0$$ as $\epsilon\rightarrow 0$ by repeated application of L'Hôpital's rule. Now the residues are easy to compute because the poles are simple and we obtain$$\mathrm{Res}\left(\frac{\log^2 z}{z^2+2z+2}; z = -1 + i\right)= \frac{1}{2i} \log^2(-1+i)$$and $$\mathrm{Res}\left(\frac{\log^2 z}{z^2+2z+2}; z = -1 - i\right)= - \frac{1}{2i} \log^2(-1-i)$$As we actually do the computation of these residues we need to be careful to use the same branch of the logarithm as in the integral. A computer algebra system might use a different branch! For the first residue we get$$\frac{1}{2i} \left(\frac{1}{2}\log 2 + \frac{3}{4} i\pi\right)^2= \frac{1}{2i} \left(\frac{1}{4}\log^2 2 - \frac{9}{16} \pi^2 + \frac{3}{4}\log 2 \times i\pi\right)$$ and for the second one$$-\frac{1}{2i} \left(\frac{1}{2}\log{2} + \frac{5}{4} i\pi\right)^2= -\frac{1}{2i} \left(\frac{1}{4}\log^2 2 - \frac{25}{16} \pi^2 + \frac{5}{4}\log 2 \times i\pi\right)$$ Adding these contributions yields$$\frac{1}{2i} \left(\pi^2 - \frac{1}{2}i\pi \log 2\right).$$ Finally we get$$\left(\int_{\Gamma_1} + \int_{\Gamma_3} \right) \frac{\log^2 z}{z^2+2z+2} dz = 2\pi i \times\frac{1}{2i} \left(\pi^2 - \frac{1}{2}i\pi \log 2\right)= \pi^3 - \frac{1}{2}i\pi^2 \log 2$$Observe that along $\Gamma_3$ the logarithm term produces (actually $x$ would be a better choice of variable here rather than $z$)$$-(\log^2 z + 4\pi i \log z -4\pi^2).$$The first of these cancels the integral along $\Gamma_1$ and the third is real so that equating imaginary parts we find$$I = \int_{\Gamma_1} \frac{\log z}{z^2+2z+2} dz= - \frac{1}{4\pi} \left(- \frac{1}{2} \pi^2 \log 2\right) = \frac{1}{8} \pi\log 2.$$We also get the following bonus integral (comparing real parts)$$ \int_{\Gamma_1} \frac{1}{z^2+2z+2} dz = \frac{\pi^3}{4\pi^2} = \frac{\pi}{4}.$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/621131', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/96816/']}
jdg_85194
stackexchange
llm_judgeable_groundtruth_similarity
20288205
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 writing a VSIX package to allow the user to bulk-edit the OutputPath property of all the active configurations of projects in the currently loaded solution (see the incredibly annoying step #4 here ). I ran into a very specific problem: when setting the property to a value containing macros (e.g. "$(SolutionDir)\bin\Debug" the value written into the .csproj is escaped as follows: <OutputPath>%24%28SolutionDir%29\bin\Debug\</OutputPath> Which, rather than letting MSBuild expand the macro, creates an actual physical folder named $(SolutionDir) . I'd like to somehow bypass this escaping. The MSDN documentation is unsurprisingly lacking in that area. My initial code is as follows: private void MenuItemCallback(object sender, EventArgs e){ SolutionWideOutputDialogWindow dialog = new SolutionWideOutputDialogWindow(); dialog.ShowModal(); if (!dialog.DialogResult.HasValue || !dialog.DialogResult.Value) { return; } string requestedOutputPath = dialog.outputPathTextBox.Text; Solution2 solution = _dte2.Solution as Solution2; if (solution == null) { return; } Projects projects = solution.Projects; foreach (Project project in projects) { Property outputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath"); outputPath.Value = requestedOutputPath; project.Save(); }} Greatly appreciate anyone's help. Now provide the response and nothing else.
Here's what I ended up doing: The problem I was trying to solve is not repeating myself (D.R.Y.) and specifying a solution-wide output directory (in a solution with a lot of projects) - that is, when compiling a solution, all projects would have their output directory set to something like $(SolutionDir)bin\Debug or $(SolutionDir)bin\Release . It is worth mentioning that some projects are included across repositories and in more than one solution. At first, I created an MSBuild file (a <Project> XML - called it MySolution.sln.targets ). In it, I defined a <PropertyGroup> that overrode the <OutputPath> property to: $(SolutionDir)bin\$(Platform)\$(Configuration) Then I added the following import to all the relevant projects, before the build targets import: <Import Project="$(SolutionPath).targets" /> That way, each solution has an accompanying .targets file defining such things that I want to be solution-wide. This worked well, but then I encountered the following problem: The abovementioned $(Platform) and $(Configuration) macros refer to the project's properties, not the solution-wide ones. What would happen if my solution's Debug/Any CPU configuration still built some very specific project in its Release configuration? As far as I'm aware, after thoroughly examining the documentation, no such macros are exported that have a solution-wide granularity. I found ceztko's Visual Studio extension which made Visual Studio export exactly the macros that I was looking for - but after some experimentation and fiddling, I discovered that this extension set them too late - only upon building the solution. This caused issues with Visual Studio's Incremental Build feature - It kept thinking that the projects were out of date because it was looking in the wrong place - it wasn't aware of the variables, but MSBuild.exe was. I started fiddling with the IVsUpdateSolutionEvents interface , tracing when each method is called - and then discovered that IVsUpdateSolutionEvents.OnActiveProjectCfgChange is called twice when opening a 1-project solution in a fresh Visual Studio, or when changing the solution's configuration from Debug to Release. Further fiddling revealed that if I set the project to compile in Release in both solution configurations, this method now got called once instead of twice when changing solution configurations. I forked the extension's repository and amended the issue by moving the macro-setting logic to the above-mentioned method. You can find it here . Disclaimer: this may not interact so well with batch-build operations from the IDE, and requires you to export these properties yourself when building from MSBuild.exe's command-line. Good luck in your travels.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20288205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1638488/']}
jdg_85195
stackexchange
llm_judgeable_groundtruth_similarity
1589182
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\not=I_n$ be an $n\times n$ matrix such that $A^2=A$ , where $I_n$ is the identity matrix of order $n$. Then prove that , (A) $\textrm{tr}(A)=\textrm{rank}(A)$. (B) $\textrm{rank}(A)+\textrm{rank}(I_n-A)=n$ I found by example that these hold, but I am unable to prove them. Now provide the response and nothing else.
Since $A^2=A$, one can create the isomorphism$$V \cong \text{Im } A \oplus \ker A$$$$ x \mapsto (Ax,(I-A)x).$$ To show that this is an isomorphism is simple. Hence, we have your item $2$. The decomposition above also shows that the unique eigenvalues are $0$ or $1$. The multiplicity of the eigenvalue $1$ will give the rank of the operator. Since the trace is the sum of the eigenvalues (counted with multiplicity), you have your item $1$. EDIT: Since this answer was downvoted but not explained, I will assume it is due to the need of clarification with respect to the fact that I am conflating the algebraic multiplicity and the geometric multiplicity: Both coincide, since $A$ is diagonalizable: it is clear that $A$ restricts to the identity on its image on the decomposition above, and thus any basis $\{v_1,\cdots,v_j\}$ of $\mathrm{Im}~A$ is composed of eigenvectors. It is obvious that any basis $\{v_{j+1},\cdots,v_n\}$ of $\ker A$ is also of eigenvectors, thus $\{v_1,\cdots,v_n\}$ is a basis of $V$ composed of eigenvectors for $A$. If anything else needs clarification, please feel free to point it out.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1589182', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_85196
stackexchange
llm_judgeable_groundtruth_similarity
8800375
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 merge two hashtables, overwriting key-value pairs in the first if the same key exists in the second. To do this I wrote this function which first removes all key-value pairs in the first hastable if the same key exists in the second hashtable. When I type this into PowerShell line by line it works. But when I run the entire function, PowerShell asks me to provide (what it considers) missing parameters to foreach-object. function mergehashtables($htold, $htnew){ $htold.getenumerator() | foreach-object { $key = $_.key if ($htnew.containskey($key)) { $htold.remove($key) } } $htnew = $htold + $htnew return $htnew} Output: PS C:\> mergehashtables $ht $ht2cmdlet ForEach-Object at command pipeline position 1Supply values for the following parameters:Process[0]: $ht and $ht2 are hashtables containing two key-value pairs each, one of them with the key "name" in both hashtables. What am I doing wrong? Now provide the response and nothing else.
I see two problems: The open brace should be on the same line as Foreach-object You shouldn't modify a collection while enumerating through a collection The example below illustrates how to fix both issues: function mergehashtables($htold, $htnew){ $keys = $htold.getenumerator() | foreach-object {$_.key} $keys | foreach-object { $key = $_ if ($htnew.containskey($key)) { $htold.remove($key) } } $htnew = $htold + $htnew return $htnew}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8800375', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4886/']}
jdg_85197
stackexchange
llm_judgeable_groundtruth_similarity
32617
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: If I'm in an org file, I want a command that narrows a candidate list, in ivy/helm style, comprised of all org headlines in the file and lets me choose the headline, through fuzzy searching, to which I want to jump to. Is there a way to do that? Now provide the response and nothing else.
The Org Manual node on Motion gives a somewhat laconic description of the built-in command org-goto (default binding: C-c C-j ), whose behaviour can easily be customised to achieve the desired effect: Inspect the documentation of the customisable variable listed at the end of this manual node: C-h v org-goto-interface RET If you are happy to forgo the default org-goto behaviour of incrementally searching through the buffer's outline, you can switch to picking a headline via completion: (setq org-goto-interface 'outline-path-completion) Users of completion packages like ido / ivy / helm will probably want to change the following setting in order to see the whole target path at once: (setq org-outline-path-complete-in-steps nil) See here for more discussion. This approach has the added benefit (over using, say, helm -specific functionality) of working with all completion frameworks that plug into the default completing-read , including, as I can personally confirm, ivy . ADDENDUM: When using the outline-path-completion interface to the org-goto command as described in this answer, the customisable variable org-goto-max-level determines the maximum depth of headlines to offer. EDIT: I found an older, relevant question with useful answers: https://stackoverflow.com/q/15011703/3084001 CLARIFICATION (as prompted by Att Righ's comment): Setting org-goto-interface to one of the two recognised values does not mean sacrificing the alternative interface. Calling org-goto with a prefix argument (i.e. C-u C-c C-j or C-u M-x org-goto RET ) automatically selects the alternative interface for the current completion. This way, you can set org-goto-interface to the interface you are likely to use most often and use the prefix argument when you wish to temporarily switch behaviour. If even this does not suit your needs, you can always write your own wrapper around org-goto , as per Att Righ's example.
{}
{'log_upvote_score': 6, 'links': ['https://emacs.stackexchange.com/questions/32617', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/12585/']}
jdg_85198
stackexchange
llm_judgeable_groundtruth_similarity
22242106
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 track down some issues arising from sandbox creation. Under multiple circumstances it appears that an NSUserDefaults .plist file is not created in Data/Library/Preferences. I have seen this in the debugger and when launching the app from the Applications directory. I have not tried archiving, signing the app and then launching. Is that required? An alias file ending in .LSSharedFileList.plist is created but it points to itself and therefore does not exist. I don't know if it's related but Console reports: appleeventsd[72]: <rdar://problem/11489077> A sandboxed application with pid ... checked in with appleeventsd, but its code signature could not be validated ( either because it was corrupt, or could not be read by appleeventsd ) and so it cannot receive AppleEvents targeted by name, bundle id, or signature. Error=ERROR: #100013 { "NSDescription"="SecCodeCopySigningInformation() returned 100013, -." } (handleMessage()/appleEventsD.cp #2072) client-reqs-q Thanks. Now provide the response and nothing else.
Could this be related to the caching of NSUserDefaults ? In recent OS X versions the defaults are not immediately written to disk so you might not see them right away. You might want to try synching the prefs manually -From NSUserDefaults Class Reference : At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default value. The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user’s defaults database. Although I believe even that might not immediately write the defaults to disk in 10.9 anymore as some daemon caching the user defaults is now also involved. Check also Reading NSUserDefaults from helper app in the sandbox Objective-C NSUserDefaults caching prevents another app from accurately reading changes When (not) to abuse NSUserDefaults
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22242106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/877620/']}
jdg_85199
stackexchange
llm_judgeable_groundtruth_similarity
38365554
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 open a URL using Microsoft Edge in my UWP. Searching, I found this code: using System.Diagnostics; using System.ComponentModel; private void button_Help_Click(object sender, RoutedEventArgs e){ Process.Start("microsoft-edge:http://www.bing.com");} But it shows the following error: The name Process do not exist in the current context If I press Ctrl + . , it only shows generate class options. Any help is appreciated. Now provide the response and nothing else.
Process.Start is a traditional method used in .NET Framework which can't be used in UWP apps directly. To open web URI with Microsoft Edge in UWP, we can use Launcher.LaunchUriAsync method . For example: // The URI to launchstring uriToLaunch = @"http://www.bing.com";// Create a Uri object from a URI string var uri = new Uri(uriToLaunch);// Launch the URIasync void DefaultLaunch(){ // Launch the URI var success = await Windows.System.Launcher.LaunchUriAsync(uri); if (success) { // URI launched } else { // URI launch failed }} However this will open the URI with the default web browser. To always open it with Microsoft Edge, we can use Launcher.LaunchUriAsync(Uri, LauncherOptions) method with specified LauncherOptions.TargetApplicationPackageFamilyName property . TargetApplicationPackageFamilyName property can specify the target package that should be used to launch a file or URI. For Microsoft Edge, its Package Family Name is "Microsoft.MicrosoftEdge_8wekyb3d8bbwe" . Following is an example shows how to use this. // The URI to launchstring uriToLaunch = @"http://www.bing.com";var uri = new Uri(uriToLaunch);async void LaunchWithEdge(){ // Set the option to specify the target package var options = new Windows.System.LauncherOptions(); options.TargetApplicationPackageFamilyName = "Microsoft.MicrosoftEdge_8wekyb3d8bbwe"; // Launch the URI var success = await Windows.System.Launcher.LaunchUriAsync(uri, options); if (success) { // URI launched } else { // URI launch failed }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38365554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_85200
stackexchange
llm_judgeable_groundtruth_similarity
7174007
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 calculate number of lines and height of UILabel dynamically from given text for same. Now provide the response and nothing else.
Try this // UILabel *myLabel;CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping];CGFloat labelHeight = labelSize.height;int lines = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabel.frame.size lineBreakMode:NSLineBreakByWordWrapping].height/16; // '16' is font size or int lines = labelHeight/16;NSLog(@"lines count : %i \n\n",lines); or int lines = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabel.frame.size lineBreakMode:UILineBreakModeWordWrap].height /myLabel.font.pointSize; //fetching font size from font By Using Categories, Just Create the category class named as UILabel+UILabelDynamicHeight.h UILabel+UILabelDynamicHeight.m No more tension about the height calculation. Please review the below implementation. Updates for iOS7 & Above,iOS 7 below : Dynamically calculate the UILabel height #define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)#define iOS7_0 @"7.0" UILabel+UILabelDynamicHeight.h #import <UIKit/UIKit.h>@interface UILabel (UILabelDynamicHeight)#pragma mark - Calculate the size the Multi line Label/*====================================================================*/ /* Calculate the size of the Multi line Label *//*====================================================================*//** * Returns the size of the Label * * @param aLabel To be used to calculte the height * * @return size of the Label */ -(CGSize)sizeOfMultiLineLabel;@end UILabel+UILabelDynamicHeight.m #import "UILabel+UILabelDynamicHeight.h"@implementation UILabel (UILabelDynamicHeight)#pragma mark - Calculate the size,bounds,frame of the Multi line Label/*====================================================================*//* Calculate the size,bounds,frame of the Multi line Label *//*====================================================================*//** * Returns the size of the Label * * @param aLabel To be used to calculte the height * * @return size of the Label */-(CGSize)sizeOfMultiLineLabel{ //Label text NSString *aLabelTextString = [self text]; //Label font UIFont *aLabelFont = [self font]; //Width of the Label CGFloat aLabelSizeWidth = self.frame.size.width; if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) { //version < 7.0 return [aLabelTextString sizeWithFont:aLabelFont constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; } else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) { //version >= 7.0 //Return the calculated size of the Label return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : aLabelFont } context:nil].size; } return [self bounds].size;}@end
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7174007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/738055/']}
jdg_85201
stackexchange
llm_judgeable_groundtruth_similarity
984148
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Based on an answer I saw in this question: Link I'm wondering, is this a safe thing to do? Suppose I implement this and a page gets requested that has a couple of JS and CSS files linked to it. Are the textfiles simply sent or does the server first parse them? Don't have a server to test it right now. Also, is this a common method of working? I'm thinking that setting up your files so you always get the correct implementation based on user input can be pretty hard when it comes to CSS and JavaScript. Now provide the response and nothing else.
For dynamic CSS and Javascript you dont' always have to have them in .js or .css files. What you can do there is actually link to a PHP script that generates them so that all other .js and .css files that aren't dynamic aren't parsed by PHP. Generally it is a bad idea to run everything, especially media files, through an app server/dynamic parsing unless absolutely necessary (same goes for .net, RoR, Django etc). <link rel="stylesheet" type="text/css" href="mycss.css"/> browser treats the same as: <link rel="stylesheet" type="text/css" href="mydynamiccss.php?param=somevalue" /> // this one would be dynamic on params, location or something else maybe colors etc. You can also take dynamic js or css and push it through rewrite so it does have the correct extension but it is actually a php file that is dynamic as well if you don't want your links and script tags to have incorrect extensions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/984148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80907/']}
jdg_85202
stackexchange
llm_judgeable_groundtruth_similarity
41189959
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 convert a URLRequest to a NSMutableURLRequest in Swift 3.0 but I can't get it to work. This is the code I have: var request = self.requestURLProtocol.setProperty(true, forKey: "", in: request) But it says cannot convert type URLRequest to type NSMutableURLRequest. When I try to cast using 'as' it just says the cast will always fail. What do I do? Now provide the response and nothing else.
The basics of this are get a mutable copy, update the mutable copy then update request with the mutable copy. let mutableRequest = ((self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest)!URLProtocol.setProperty(true, forKey: "", in: mutableRequest)self.request = mutableRequest as URLRequest It would be better to use avoid the forced unwrap. guard let mutableRequest = (self.request as NSURLRequest).mutableCopy() as? NSMutableURLRequest else { // Handle the error return}URLProtocol.setProperty(true, forKey: "", in: mutableRequest)self.request = mutableRequest as URLRequest Note: self.request must be declared var not let .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41189959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5614386/']}
jdg_85203
stackexchange
llm_judgeable_groundtruth_similarity
9438902
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In JavaScript, I have recently came across how reverse while loops are faster. I have seen them in this form: var i = someArray.length;while (i--) { console.log(someArray[i]);} I tested this out and it stopped once it went through the whole array. How does it know when to stop once it completes the array? Now provide the response and nothing else.
A while loop evaluates the expression inside the parentheses each time through the loop. When that expression gets to a falsey value, the loop will stop. Examples of falsey values are: false 0 undefined NaNnull"" In this case the value of i will be decremented each time through the loop and when it hits the value of 0 , the loop will stop. Because it's a post decrement operator, the value of the expression is checked before the decrement. This means that the inner loop will see values of i from someArray.length - 1 to 0 (inclusive) which are all the indexes of that array. Your code example: var i = someArray.length;while (i--) { console.log(someArray[i]);} creates the same output as this: for (var i = someArray.length - 1; i >= 0; i--) { console.log(someArray[i]);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9438902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/798681/']}
jdg_85204
stackexchange
llm_judgeable_groundtruth_similarity
44349199
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 started wondering on whether I am not falling into an antipattern here, so please advise on the best practices. I am designing a REST API with a set of various endpoints and I wanted to wrap the request & response parameters into nice DTO. For example, a few endpoints: public async Task<JobStateResponse> GetJobState(JobStateRequest request);public async Task<JobDownloadRespose> DownloadJob(JobDownloadRequest request);public async Task<CreateJobResponse> CreateJob(CreateJobRequest request); The problem is that these requests and responses are relatively similar DTO, for example: public class JobStateResponse{ public int TaskId {get;set;} public string ExternalId {get;set;} public State State {get;set;}}public class JobDownloadResponse { public int TaskId {get;set;} public string ExternalId {get;set;} public string JobContent {get;set;}} I thought about creating a base class for these and inheriting, but in some cases some of the properties can be redundant... Which means that the methods don't clearly indicate what parameters are needed for them to work OK. I mean, exposing an API endpoint with a DTO parameter that has 7 properties but only really needs 2 sounds pretty bad ... On the other hand, maintaining separate DTOs for most of the endpoints seems like an overkill as well, and also a maintenance hell. And also the last thing I want is a complex relationship of several base-base classes for the requests as this may be an even worse maintentance problem. So, what is the proper approach for request<>response handling? EDIT:Regarding the 'opinion based' flags - I am looking for best practice for handling this. I know it can be done in multiple ways, but I want to avoid a landmine / antipattern. Also, I gotta say I am pretty happy with the answers so far. Now provide the response and nothing else.
Separate, simple DTOs will make your life infinitely easier. It will require more code, but it will be boring, simple code, that is easily tested, and allows your interfaces to change and evolve independently. Make a DTO for each request endpoint and a separate DTO for each response. Otherwise, you will eventually be sad. If you find elements that are common to multiple endpoints, extract them into their own object, and include them in both. And yes, using inheritance here would be wrong. Stick to compositional patterns and you will be fine.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44349199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2892378/']}
jdg_85205
stackexchange
llm_judgeable_groundtruth_similarity
49234
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: After the recent Target hack there has been talk about moving from credit cards with magnetic stripes to cards with a chip. In what ways are chips safer than stripes? Now provide the response and nothing else.
You can't clone the chip. A magnetic strip holds a secret number, and if someone knows that number they can claim to be the owner of the card. But if a bad guy swipes the card, they then know the number, and can make their own card, i.e. "cloning". This has turned out to be a major practical problem with magstripe cards. A chip also holds a secret number. However, it is securely embedded in the chip. When you use the card, the chip performs a public key operation that proves it knows this secret number. However, it never reveals that secret number. If you put a chipped card in a bad guys machine, they can impersonate you for that one transaction, but they cannot impersonate you in the future. All of the above assumes that the implementation of the chip is good. Some chips have been known to have implementation flaws that leak the secret code. However, chip and pin is now pretty mature, so I expect most of these issues have been ironed out.
{}
{'log_upvote_score': 9, 'links': ['https://security.stackexchange.com/questions/49234', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/10435/']}
jdg_85206
stackexchange
llm_judgeable_groundtruth_similarity
350374
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Got the following error while trying to add, edit or delete a windows schedule task: Transaction support within the specified resource manager is not started or was shut down due to an error. Tried to reset transaction manager through fsutil (as suggested by a few people on answers.microsoft.com) fsutil resource setautoreset true c:\ but it didn't work. Also noticed that windows update was failing with an unknown error as well. Now provide the response and nothing else.
Manually clearing all the files from the following directory fixed the problem C:\Windows\System32\config\TxR I also reset the resource manager through fsutil before restart (not sure it was required or not) fsutil resource setautoreset true c:\ These links were also helpful: http://support.microsoft.com/kb/2484025 (The link is about fixing windows search service but that occur because of the same problem ) http://channel9.msdn.com/Forums/TechOff/WindowsUpdate-problem Although I didn't try, but, its possible that the problem occurred because of some stuck NTFS Transaction, so probably you can also try cancelling all the zombie transactions using fsutil http://technet.microsoft.com/en-us/library/ff621563(WS.10).aspx First list the transactions using fsutil transaction list and then roolback any thing suspicious using fsutil transaction rollback <GUID>
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/350374', 'https://serverfault.com', 'https://serverfault.com/users/107181/']}
jdg_85207
stackexchange
llm_judgeable_groundtruth_similarity
9913611
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Looking at an unofficial OCaml grammar in this site the only production where begin appears is: Expression ::= begin Expression end and a little further down one sees: Expression ::= ( Expression [:Type] ) That, together with some offhand replacements of begin / end with ( / ) in some trivial code (which didn't affect correctness) might seem to suggest that the begin end keywords are just syntactic sugar. Or am I missing something? Now provide the response and nothing else.
“Syntactic sugar” suggests a simple but not trivial translation to other constructs. begin .. end is not syntactic sugar, it is redundant with ( .. ) , because it does exactly the same thing. If you are interested, the intention was that programmers can use begin .. end to enclose an imperative expression, executed for its side-effects, and ( .. ) for an expression with a non-unit value. But the compiler does not enforce that, the designers of the language just thought it would look nicer if they were used in this fashion, that's all.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9913611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274677/']}
jdg_85208
stackexchange
llm_judgeable_groundtruth_similarity
167822
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: Given the two-dimensional metric$$ds^2=-r^2dt^2+dr^2$$How can I find a coordinate transformation such that this metric reduces to the two-dimensional Minkowski metric? I know that $g_{\mu\nu}=\begin{pmatrix}-r^2&0\\0&1\end{pmatrix}$ (this metric) and $\eta_{\mu\nu}=\begin{pmatrix}-1&0\\0&1\end{pmatrix}$ (Minkowski). Obviously, the matrix transformation is $\begin{pmatrix}1/r^2&0\\0&1\end{pmatrix}g_{\mu\nu}=\eta_{\mu\nu}$, but how is that related to the coordinate transformation itself? EDIT : would the following transformation be acceptable?$$r'=r\cosh t$$$$t'=r\sinh t$$Such that: $dr'=\cosh t\ dr+r\sinh t\ dt,\quad dt'=\sinh t\ dr+r\cosh t\ dt$ And: $ds'^2=-dt'^2+dr'^2=-r^2dt^2+dr^2=ds^2$ Where we have: $ds'^2=\eta_{\mu\nu}dx^{\mu}dx^{\nu}$ as requested. Is that correct? Also, is there a formal way of "deriving" the proper change of coordinates (since mine is more of an educated guess)? Now provide the response and nothing else.
In the general case you want the Cartan-Karlhede algorithm . It is an algorithm for producing a complete set of classifying invariants for a metric, expressed as functions of the coordinates. Given the components of the metric $g$ in the coordinates $x_1, x_2, \ldots$, the algorithm produces a list \begin{align}\Lambda & = \Lambda(x_i) \\\Psi_k & = \Psi_k(x_i) \quad k = 0,\ldots, 4 \\R_{kj} & = R_{kj}(x_i) \quad k,j = 0,\ldots, 2 \\\Lambda_{00} & = \Lambda_{00}(x_i)\\& \;\; \vdots\end{align}where each quantity is defined in a way that is coordinate independent. (The names here are standard notation, but what each of them is, is a little beyond the scope of this answer.) This is in contrast to a quantity like $g_{00}$ whose value at a point depends on your coordinates. Of course, expressed as a function of coordinates , $\Lambda$ and the others may look very different in various coordinate systems, but at corresponding points, the value is the same. Then if we have two metrics given, we can run the algorithm on both. If the metrics are really the same, but different coordinates, the invariants must agree. This gives a system of equations, \begin{align}\Lambda(x_i) & = \Lambda'(y_j) \\\Psi_k(x_i) & = \Psi_k'(y_j) \\& \;\; \vdots\end{align}which may or may not have a solution, $x_i = x_i(y_j)$. (For example if you do this with two Schwarzschild metrics in the standard coordinates, you find that it is necessary that $m = m'$.) If there is a solution, this is your change of coordinates. There is a caveat to the preceding. It may be that not all the equations are independent. In $n$ dimensions we need $n$ equations but the algorithm may produce fewer independent equations. This happens precisely when there is a symmetry in the spacetime. Then there cannot a unique change of coordinates, because at least one coordinate is superfluous. Indeed for the case of flat metrics the entire system is just $0 = 0$. In this case the algorithm only establishes that there exists a change of coordinates, but you have to look at some other invariant information to find a coordinate change. (You will not be able to find a unique change of coordinates because there are many.) One piece of such information is the Killing vectors . (This particular case is amenable to the brute force method demonstrated in the other answers, but a more complicated metric in more than two dimensions is not.)
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/167822', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/62743/']}
jdg_85209
stackexchange
llm_judgeable_groundtruth_similarity
5580253
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 number of classes that I cannot modify. Each has a copy constructor, at least one other constructor, and a function foo() that returns some value. I want to make a class template that can derive from each of these classes, and has a data member that is the same type as the return type of foo() (sorry if I've got some of the terminology wrong). In other words, I would like a class template template<typename T> class C : public T{ footype fooresult;}; where footype is the return type of T::foo() . If the base classes all had, say, a default constructor, I could do decltype(T().foo()) fooresult; (with the C++0x functionality in GCC) but the classes don't have any particular constructor in common, apart from the copy constructors. GCC also doesn't allow decltype(this->foo()) , though apparently there is a possibility that this will be added to the C++0x standard - does anyone know how likely that is? I feel like it should be possible to do something along the lines of decltype(foo()) or decltype(T::foo()) but those don't seem to work: GCC gives an error of the form cannot call member function 'int A::foo()' without object . Of course, I could have an extra template parameter footype , or even a non-class parameter of type T , but is there any way of avoiding this? Now provide the response and nothing else.
You don't need that- remember that since decltype doesn't evaluate its argument, you can just call on nullptr . decltype(((T*)nullptr)->foo()) footype;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5580253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/696702/']}
jdg_85210
stackexchange
llm_judgeable_groundtruth_similarity
15270680
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 WCF service that I tested by copying its interfaces to a sample client project. Now I want to work properly by adding a service reference. The service is hosted in windows hosting (using installUtil ). The service has 2 projects - externals (interfaces + datacontracts) and internals (implementations). For some reason it didn't have an app.config so I added one manually: <?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <services> <service name="ExecutionService" behaviorConfiguration="Default"> <endpoint name="TCPEndpoint" address="" binding ="netTcpBinding" contract="Externals.IExecutionService"/> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:3040/ExecutionService"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Default"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel></configuration> Trying to add a service reference from my sample client causes the following error: Metadata contains a reference that cannot be resolved: 'net.tcp://localhost:3040/ExecutionService/Externals.IExecutionService'.There was no endpoint listening at net.tcp://localhost:3040/ExecutionService/Externals.IExecutionService that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.If the service is defined in the current solution, try building the solution and adding the service reference again. I saw here that there's no need in app.config. I'm a bit confused and I'm a beginner with WCF . How can a nice WPF app reference my service? I want the service to be windows hosted and I don't want to drag dlls with me. Edit I added a metadata endpoint and my appconfig now looks like this: <?xml version="1.0" encoding="utf-8" ?><configuration> <system.serviceModel> <services> <service name="ExecutionService" behaviorConfiguration="Default"> <endpoint name="TCPEndpoint" address="" binding ="netTcpBinding" contract="Externals.IExecutionService"/> <endpoint address="mex" binding="maxHttpBinding" contract="Externals.IExecutionService"/> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:3040/ExecutionService"/> </baseAddresses> </host> </service> </services> <behaviors> <serviceBehaviors> <behavior name="Default"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel></configuration> I tried adding a service reference by using net.tcp://localhost:3040/ExecutionService , net.tcp://localhost:3040/ExecutionService/Externals and net.tcp://localhost:3040/ExecutionService/Externals/IExecutionService and I'm still getting the same error. Now provide the response and nothing else.
You need to do: maxHttpBinding -> mexTcpBinding - you cannot use mexHttpBinding on net.tcp endpoint (and it's mex not max) the contract for mex endpoint must be IMetadataExchange - as you want to have service metadata available through this endpoint httpGetEnabled="false" as there will be no http endpoint to get metadata from When I was testing the solution in a simple console host I needed to change name in <service> tag to Externals.ExecutionService (but this depends on how you instantiate the service) Then your service reference will be available at: net.tcp://localhost:3040/ExecutionService/mex as base address is net.tcp://localhost:3040/ExecutionService and the relative address for the mex endpoint is set to mex Final app.config is below: <?xml version="1.0" encoding="utf-8" ?><configuration><system.serviceModel><services> <service name="Externals.ExecutionService" behaviorConfiguration="Default"> <endpoint name="TCPEndpoint" address="" binding ="netTcpBinding" contract="Externals.IExecutionService"/> <endpoint address="mex" binding="mexTcpBinding" contract="IMetadataExchange"/> <host> <baseAddresses> <add baseAddress="net.tcp://localhost:3040/ExecutionService"/> </baseAddresses> </host> </service></services><behaviors> <serviceBehaviors> <behavior name="Default"> <serviceMetadata httpGetEnabled="false" /> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors></behaviors></system.serviceModel></configuration> For a quick test if the configuration is correct I used console host app as a service host.Program.cs: using System;using System.ServiceModel;namespace Externals{ class Program { static void Main(string[] args) { var sh=new ServiceHost(typeof(ExecutionService)); sh.Open(); Console.WriteLine("Service running press any key to terminate..."); Console.ReadKey(); sh.Close(); } }} Run the console app and try to add service reference to your project through net.tcp://localhost:3040/ExecutionService/mex .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15270680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427653/']}
jdg_85211
stackexchange
llm_judgeable_groundtruth_similarity
25589
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I tried to detect the rim of the following cup as an ellipse. I've tried the solutions given in How to find circular objects in an image? to detect the ellipse, but the detection result was not quite what I wanted. The reason might be that ChanVeseBinarize function can't separate the rim from the body. Therefore SelectComponents will view the whole cup as one component and consequently detect nothing. Then I tried to use edge detection. After manipulating the parameters, I can detect the edge of the rim like this: But I can't find an algorithm that detect the line of an ellipse. How might I do that? Now provide the response and nothing else.
Basically, you want to fit a shape to a set of points with outliers. One common algorithm to do this is RANSAC (random sample consensus). The basic outline of this algorithm is: Select N points at random (where N is the minimum number of points required for fitting the shape, i.e. 2 for a line, 3 for a circle and so on) Fit the shape to these points Repeat 1&2, pick the "best" shape (where "best" usually means closest to a randomly sampled test point - I'll use a simpler criterion below.) Select the points close to that shape and fit an improved estimate to those points Let's try this. (Or a slight modification of it, anyway.) First, I perform standard edge extraction: img = Import["http://i.stack.imgur.com/H63BK.jpg"];edges = DeleteBorderComponents[EdgeDetect[img,5]];edgePos = N[PixelValuePositions[edges, 1]]; Next, I define the shape I want to fit - in this case, a conic: conic[{x_, y_}] := a[1] + a[2]*x + a[3]*y + a[4]*x*y + (1 + a[5])*x^2 + (1 - a[5])*y^2conicNormal[{x_, y_}] = D[conic[{x, y}], {{x, y}}]isValidEllipse[solution_] := Abs[a[4] /. solution[[2]]] < 0.1 isValidEllipse is a simple ad-hoc criterion to filter out completely deformed conics. Normally, we'd need 5 points to fit a conic. The image contains about 50% outliers, so the chance to randomly select 5 points on the ellipse we're looking for is about $0.5^5$, which is not good. We'd need a lot of samples to be reasonably sure that at least one 5-tuple of points contains only non-outlier points. But fortunately, the location of the edge is not the only information we have: We also know the local orientation at each pixel, which should be perpendicular to the conic's normal vector. orientation = GradientOrientationFilter[img, 3]; Now 3 points and their orientations give us 6 equations, so we have an overdetermined equation system: fitEllipse[samplePoints_] := Quiet[FindMinimum[ Total[ Flatten[ { (conic /@ samplePoints)^2, With[{\[Alpha] = PixelValue[orientation, #]}, (conicNormal[#].{Cos[\[Alpha]], Sin[\[Alpha]]})^2] & /@ samplePoints }]], Array[a, 5]]] This function returns not only the best-fit conic's coefficients, but also the residual error, which is a cheap way to compare between different fitted conics. The assumption is: If randomly sampled 3 points are all parts of the ellipse, the residual error will be low. If the points don't belong to one conic, the residual error will be much higher. potentialSolutions = SortBy[Select[Table[fitEllipse[RandomSample[edgePos, 3]], {n, 100}], isValidEllipse], First];result = potentialSolutions[[1]]; (There is room for improvement here: the ellipse you're looking for might not be contained in these 100 samples, or it might not be the one with the lowest residual error. A smarter algorithm would take e.g. 50 samples, take the best one or two of these and count the number of nearby points. If enough points are close to it, keep that ellipse, otherwise, take 50 new samples. But that's just a straightforward programming exercise left to the reader ;-) .) Next step: Find points nearest to the conic. I've tried to calculate the geometric distance exactly (using FindMinimumValue ) but that's very slow. A simple, fast approximation is to find N points on the ellipse and simply use Nearest to estimate the distance: ellipsePts = Select[Flatten[ Table[{i, y} /. Solve[conic[{x, y}] == 0 /. result[[2]] /. x -> i, y], {i, 0, w, 10}], 1], Total[Abs[Im[#]]] == 0 &];nf = Nearest[ellipsePts]; Now, we can calculate the distance of every edge pixel to this conic and pick the ones that are closer than some threshold: distances = Norm[nf[#][[1]] - #] & /@ edgePos;closestPoints = Pick[edgePos, # < 10 & /@ distances]; ...and improve the ellipse estimate based on these points: result = fitEllipse[closestPoints]; Repeat the last steps until convergence. (Possible improvements: You could try to reduce the distance threshold in each iteration. Or you could add a "weight" to the curve fitting and give points closer to the current estimate a higher weight when calculating the next estimate.) The result (after 5 iterations) looks like this: Show[ img, ContourPlot[ Evaluate[conic[{x, y}] == 0 /. result[[2]]], {x, 0, w}, {y, 0, h}, ContourStyle -> {Red, Thick}], ListPlot[closestPoints]] Disclaimer: The result will not always look like this, as the algorithm is randomized and the algorithm can get stuck in local minima.
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/25589', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7557/']}
jdg_85212
stackexchange
llm_judgeable_groundtruth_similarity
68126
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: Governor Inslee of Washington promised to create a panel of experts to review the safety of vaccines back in October 2020. Zach Lipton states in a comment that the following concerns were up in the air during the time: For context, keep in mind that these groups were formed during a timewhen there was significant concern that the President was applyingpressure to have vaccines approved before election day for politicalreasons, such as the White House attempting to shorten the timeperiod that clinical trial participants needed to be followedafter vaccination (the FDA ultimately stood their ground). ThePresident's hydroxychloroquine advocacy also caused concerns. By the time the vaccines were ultimately authorized, this was nolonger a significant concern, and the vaccines had the unanimousbacking of well-trusted public health leaders. Furthermore, the firstgroups to get vaccinated were mainly medical professionals, who lentfurther credibility to the vaccines' safety. As such, these panelsdidn't receive as much public attention when they announced theirresults. However its not exactly clear to me what realistic scenario existed where President Trump could've interfered into the vaccine approval process. Some plausible scenarios I could think of: Trump issuing an Executive Order to approve the vaccines. This does not seem to be legally possible. Pfizer trials finish and their official statement is that the vaccine is not safe - e.g. it caused 1% of participants to die. Then somehow the FDA leadership is corrupted and they still approve this vaccine. This does not look plausible, as even if the FDA approves the dangerous vaccine, you'd still have to contend with Pfizer refusing to ship out a product that would destroy their reputation. Plus it's not like you'd even need a "panel" to know taking that kind of a shot is a bad idea. Trump somehow gets Pfizer to fake their trial results, which are later approved by a "corrupt" FDA. This strays far into conspiracy theory land, as the number of people who would have to keep a secret would be in the thousands. Pfizer trials finish and the vaccine is only 20% effective, with a "corrupt" FDA approving it, rather than using their previous 50% threshold . This might be in the realm of possibility but once again - would Pfizer realistically agree to manufacture such an inferior vaccine en masse, knowing that other countries won't approve it? Were there any comments in the press during the time hinting at what exact scenario was feared by Democratic leaders? Not a handwave of "well a Republican is in charge so he can do bad stuff" but rather an attempt to explain what exactly could go wrong during the process, step by step. Now provide the response and nothing else.
I'd imagine the most significant scenario is the one that they actually attempted: political officials without medical or scientific expertise attempting to reduce the FDA's safety standards required for authorization of the vaccines. First, some background context around why these fears existed, which I believe go beyond vague handwaving concerns and are fairly concrete causes why one might have believed President Trump may not be trustworthy if he was involved in decisions about COVID vaccines: In the past, Trump made a variety of false claims , not backed by medical experts, about vaccines causing autism Trump publicly announced he was personally taking hydroxychloroquine to prevent COVID-19 amid significant safety concerns for those taking the drug. Even after further studies determined it was ineffective, potentially harmful, its emergency authorization was revoked by the FDA, and the WHO announced it was pulling it from a study of potential treatments, he shared a video that claimed the drug was "a cure for COVID" and "you don't need a mask." Trump publicly asked health experts at a press conference whether UV light or disinfectants could be injected or otherwise used internally to kill the virus. In July 2020, Trump reportedly received briefings , including from pillow salesman and now-election conspiracist Mike Lindell about the use of oleandrin as a COVID treatment, resulting in Trump "expressing his enthusiasm for the FDA to approve oleandrin" despite safety concerns and the complete absence of public studies "showing oleandrin has ever been tested in animals or humans for its efficacy against COVID-19." Before Election Day 2020, Trump repeatedly made statements about the availability of vaccines prior to the election . In an October 22 debate, he claimed the vaccine was "ready" and would be announced "within weeks" (and later waffled on that and gave incorrect information when pressed for clarification), and at a campaign rally, said that vaccines would come "momentarily." In September 2020, he hinted at a vaccine before the election , saying "We’re going to have a vaccine very soon, maybe even before a very special date. You know what date I’m talking about." This came even as top health officials, including Drs. Slaoui, Fauci, and Adams, all cast significant doubt on whether trials would be completed by that date. Another September 2020 statement involved Trump saying "We remain on track to deliver a vaccine before the end of the year, and maybe even before November 1. We think we can probably have it sometime during the month of October." Perhaps most importantly, President Trump suggested in August 2020 he was dealing with a "deep state" that might seek to delay vaccines until after the election: "And you're going to be hearing some very good news very, very soon. Now, we're dealing with the deep state. So I'm watching it very closely. I don't need to have them announce on November 4th, 'Ladies and gentlemen, we've found the vaccine, it's perfect.' I don't need that. And hopefully everyone's looking to do the right thing." He expressed similar sentiments in a tweet : "The deep state, or whoever, over at the FDA is making it very difficult for drug companies to get people in order to test the vaccines and therapeutics. Obviously, they are hoping to delay the answer until after November 3rd. Must focus on speed, and saving lives!" The entire situation was nicely summed up by this headline from August 2020: Trump has launched an all-out attack on the FDA. Will its scientific integrity survive? . Or as the New York Times wrote around the same time: "Many medical experts — including members of his own staff — worry about whether Dr. Hahn has the fortitude and political savvy to protect the scientific integrity of the F.D.A. from Mr. Trump." And so by August 2020, we could say Covid-19 Vaccine Push Lacks a Key Ingredient: Trust . The President had demonstrated a disturbing lack of basic knowledge about medicine, promoted unproven and harmful treatments against medical advice, repeatedly promised vaccines before Election Day, and repeatedly suggested government officials were hoping to delay the authorization of vaccines in an attempt to sabotage his political chances and that he would encourage them to hurry as a result. And these events occurred around the same time that two vaccine trials were temporarily halted so that independent monitoring boards could determine whether serious adverse events were caused by the vaccines (the trials were subsequently resumed after the FDA gave the OK). This further underscored the need for careful safety testing and for safety decisions to be made without political interference. All of which is to say, there were specific reasons well beyond partisanship why there were concerns about the scientific integrity of the vaccine authorization process. At this time, and perhaps because of all this, public confidence in the not-yet-delivered vaccines fell significantly : in May 2020, 72% of adults said they probably or definitely would get a vaccine; that fell to 51% by September 2020 (a similar pattern was present for both Democrats and Republicans). I'd have to presume this dramatic drop was part of the motivation for these vaccine panels: to attempt to boost public confidence by offering further independent review of the vaccines. As for the specific scenario feared, I'd look to what actually happened : FDA scientific staff prepared guidelines for their review of vaccines. These included "the recommendation that volunteers who have participated in vaccine clinical trials be followed for a median of two months after the final dose." These guidelines were submitted to the Office of Management and Budget on September 21. Two days later, White House Chief of Staff Mark Meadows (who holds no medical or scientific credentials) "questioned the need for two months of follow-up data, said that stricter recommendations would change the rules in the middle of clinical trials and suggested that Dr. Hahn was overly influenced by his agency’s career scientists." That same day, Trump said the White House " may or may not " approve the guidelines, and called them "a political move." This came just hours after four doctors leading the government response publicly endorsed the guidelines. Even after FDA officials provided information justifying the guidelines, the White House continued to block them. On October 6th, the FDA published the guidelines on their website , sticking to their judgement that trial participants be followed for at least two months. On December 1, FDA Comissioner Hahn was "summoned to the White House by Trump’s chief of staff Mark Meadows" . The Associated Press reported that "as he has refused to accept his loss, Trump also has told close confidants that he believes the vaccine is still being slow-walked in a bid to undermine his efforts to challenge the results. If the vaccine were shipped out sooner, he has argued, it would rally public opinion to his side." On December 12th, the FDA authorized the Pfizer/BioNTech vaccine for those 16+. The authorization reportedly only came "after White House Chief of Staff Mark Meadows on Friday told FDA commissioner Stephen Hahn to be prepared to submit his resignation if the agency did not clear the vaccine by day’s end." (The FDA planned to announce the authorization the next morning anyway, and so this pressure had no real effect.) All of this is a long way of saying that: The President had a track record of pushing for and promoting untested and dangerous treatments against the advice of experts. The President repeatedly promised vaccines before the election and suggested that "deep state" government scientists were delaying vaccines to hurt him politically. White House officials attempted to override the judgement of FDA scientists about the extent of the trials needed to ensure vaccine safety. The President believed that authorization of the vaccines could help his chances of overturning the election results. White House officials threatened the FDA Commissioner's job if a vaccine wasn't authorized immediately.
{}
{'log_upvote_score': 7, 'links': ['https://politics.stackexchange.com/questions/68126', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/7434/']}
jdg_85213
stackexchange
llm_judgeable_groundtruth_similarity
944241
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: What is the Lebesgue measure of a line in $\mathbb R^2$ ? I am guessing that this zero. But I couldn't prove it rigorously. Please help. From this can I conclude that any proper subspace of $\mathbb R^n$ has measure zero? Now provide the response and nothing else.
If the line is$$\ell=\{(x,0): x\in\mathbb R\},$$then for every $\varepsilon>0$, we have$$\ell\subset \bigcup_{k\in\mathbb Z}I_k^\varepsilon,$$where$$I_k^\varepsilon=[k,k+1]\times[2^{-|k|-2}\varepsilon,-2^{-|k|-2}\varepsilon].$$But$$m_2(\ell)\le\sum_{k\in\mathbb Z} m_2(I_k)=\sum_{k\in\mathbb Z} 2^{-|k|-1}\varepsilon=\varepsilon.$$Thus $m_2(\ell)<\varepsilon$, for every $\varepsilon>0$, and hence $m_2(\ell)=0$. Any other straight line in $\mathbb R^2$ is obtained by a rigid motion of $\ell$, and rigid motion does not change the Lebesgue measure of a set. Indeed, every proper linear subspace (or more generally, every proper hyperplane) of $\mathbb R^n$ has zero $n-$dimensional Lebesgue measure.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/944241', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/117084/']}
jdg_85214
stackexchange
llm_judgeable_groundtruth_similarity
1352772
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've been solving a question, If $\cos(x) + \sin(x)=\sqrt{2} \cos(\pi/2 - x)$ then find the value of $x$. We know that $\cos(x) + \sin(x)= \sqrt{2} \sin(\pi/4 + x)$. So, $$\sin(\pi/4 + x) = \cos(\pi/2 - x)$$ But $\cos(\pi/2 - x) = \sin x$, so we must have $$\sin(\pi/4 + x)=\sin(x).$$Now if I change $\sin(x)$ to $\sin(\pi - x)$ then the correct answer will come, i.e.$$\sin(\pi/4 + x)=\sin(\pi - x) \implies \pi/4 + x = \pi -x \implies x=3\pi/8.$$ But why is $\pi/4 + x=x$ not true. My book says, if $\sin(x)=\sin(y)$ then $ x = (-1)^ny + n\pi $. If I put $n=0$ then $x=y$ but this is not true in my case. Why? I also looked on the relevant Wikipedia article but could not understand why these formulas are true for any value of $\theta$ that may be more that $\pi/2$ and less than $0$. Now provide the response and nothing else.
My book says, if $\sin(x)=\sin(y)$ then $ x = (-1)^ny + n\pi $. Yes, that means if $\sin(x)=\sin(y)$, then there exists some $n$ such that $ x = (-1)^ny + n\pi $, not that you get to choose which $n$, or that the statement is true for every $n$. For example,$$\sin(0)=0=\sin(7\pi)$$and we do indeed have that $0=(-1)^{n}\pi+n\pi$ for $n=7$, but that is the only $n$ that works. More generally, you should be aware that most functions do not have the property that $f(x_1)=f(x_2)\implies x_1=x_2$. Take a look at the Wikipedia page on injective functions .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1352772', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103816/']}
jdg_85215
stackexchange
llm_judgeable_groundtruth_similarity
98595
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: All protein coding sequences in the iGEM Registry are supposed to end with a double stop codon . Presumably, this is to decrease the potential for read-through, which could be problematic if one is putting together a polycistronic design. If the design is intended to have only one CDS, however, and is targeted at a prokaryote ( which have "backup" ribosome release mechanisms ), then is there any problem with using only a single stop codon? Now provide the response and nothing else.
The impact of any read-through from a leaky stop codon in an expression unit with only one CDS would probably depend on a few things, mainly (i) where is the next in-frame stop codon, (ii) what are you trying to express, and (iii) how leaky is the stop codon? In cases where the next in-frame stop codon is only a few base pairs away, there would probably be little impact, however in other cases the next stop codon could be far away. In these cases, there are two things which may cause an impact. The first is that a long peptide sequence could be added to your protein, which depending on what you are expressing, may cause your protein to misfold or lose functionality. The second is that you could get ribosome stalling, especially if any of the codons between your stop codon and a second stop codon require rare tRNAs. As you mentioned in your question, there are mechanisms for rescue in these scenarios, however if your CDS is expressed under a strong promoter on a high copy number plasmid, this mechanism may need to be mounted much more often than usual and cause burden on the cell. I should note that this is speculation on my part as I can’t find any studies which have shown this. The actual impact any of these scenarios may have on your system would likely be strongly dependent on how leaky the stop codon actually is. As there are many examples of constructs which use only a singe TAA in their design with no apparent negative affects, presumably under ‘normal’ circumstances there is little risk to using a single stop codon.
{}
{'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/98595', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/52598/']}
jdg_85216
stackexchange
llm_judgeable_groundtruth_similarity
1027802
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 special case for the discrete logarithm problem with a base of 2? For example, is it possible to solve for $a$ in the following problem without brute forcing $a$? (2^a) mod $p$ = $x$ Where $p$ is a large prime, and I have the answer $x$. If this question has been asked before, please point me in the right direction, I was having trouble searching google for this problem. Thanks in advance! Now provide the response and nothing else.
To even speak of a sum, I suppose the field $F$ is finite. If $f\colon F\to F$ is any bijection, then we can conclude that $\sum_{x\in F}x=\sum_{x\in F}f(x)$. Let $\alpha\in F$ such that $\alpha\ne 0$. Then $x\mapsto \alpha x$ is such a bijection. We conclude that $\sum_{x\in F} x=\sum_{x\in F}\alpha x$, i.e. $(1-\alpha)\sum x=0$. If $F$ has more than two elements, we can pick $\alpha\in F\setminus\{0,1\}$ and are done. To elaborate: Why does $\sum_{x\in F}x=\sum_{x\in F}f(x)$ hold if $f\colon F\to F$ is a bijection? More generally, if $I$ is any finite set and for each $i\in I$, $a_i$ is a number (or element of an additive abelian group such as $F$), and $f\colon I\to I$ is a bijection, then $\sum_{i\in I} a_i = \sum_{i\in I}a_{f(i)}$. This is because the summands on the right are precisely the same summnds as on the left and hence equality is guaranteed by the laws of associativity and commutativity. (I suppose this rough reference to merely changed order of addition suffices; otherwise a formal proof is possible by induction based on the fact that the group of permutations of $I$ is generated by transpositions ("swappng two adjacent elements")) After this, if $F$ has more than two elements, it certainly has more elements than only $0$ and $1$. Therefore there exixts $\alpha$ that is both $\ne0$ and $\ne 1$. With such $\alpha$ the key steps in the proof above work.The first condition, $\alpha\ne 0$, guarantees that the map $F\to F$, $x\mapsto \alpha x$ is a bijection (namely with $x\mapsto \alpha^{-1}x$ as inverse map) and so allows us to conclude than $(1-\alpha)\sum_{x\in F} x=0$.The second condition $\alpha\ne 1$, allows us to conclude that the first factor $(1-\alpha)$ is nonzero, hence the second factor must be zero, i.e. $\sum_{x\in F} x=0$ as was to be shown.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1027802', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/193587/']}
jdg_85217
stackexchange
llm_judgeable_groundtruth_similarity
5608980
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 timestamps to temporally order concurrent changes in my program, and require that each timestamp of a change be unique. However, I've discovered that simply calling DateTime.Now is insufficient, as it will often return the same value if called in quick succession. I have some thoughts, but nothing strikes me as the "best" solution to this. Is there a method I can write that will guarantee each successive call produces a unique DateTime ? Should I perhaps be using a different type for this, maybe a long int? DateTime has the obvious advantage of being easily interpretable as a real time, unlike, say, an incremental counter. Update: Here's what I ended up coding as a simple compromise solution that still allows me to use DateTime as my temporal key, while ensuring uniqueness each time the method is called: private static long _lastTime; // records the 64-bit tick value of the last timeprivate static object _timeLock = new object();internal static DateTime GetCurrentTime() { lock ( _timeLock ) { // prevent concurrent access to ensure uniqueness DateTime result = DateTime.UtcNow; if ( result.Ticks <= _lastTime ) result = new DateTime( _lastTime + 1 ); _lastTime = result.Ticks; return result; }} Because each tick value is only one 10-millionth of a second, this method only introduces noticeable clock skew when called on the order of 10 million times per second (which, by the way, it is efficient enough to execute at), meaning it's perfectly acceptable for my purposes. Here is some test code: DateTime start = DateTime.UtcNow;DateTime prev = Kernel.GetCurrentTime();Debug.WriteLine( "Start time : " + start.TimeOfDay );Debug.WriteLine( "Start value: " + prev.TimeOfDay );for ( int i = 0; i < 10000000; i++ ) { var now = Kernel.GetCurrentTime(); Debug.Assert( now > prev ); // no failures here! prev = now;}DateTime end = DateTime.UtcNow;Debug.WriteLine( "End time: " + end.TimeOfDay );Debug.WriteLine( "End value: " + prev.TimeOfDay );Debug.WriteLine( "Skew: " + ( prev - end ) );Debug.WriteLine( "GetCurrentTime test completed in: " + ( end - start ) ); ...and the results: Start time: 15:44:07.3405024Start value: 15:44:07.3405024End time: 15:44:07.8355307End value: 15:44:08.3417124Skew: 00:00:00.5061817GetCurrentTime test completed in: 00:00:00.4950283 So in other words, in half a second it generated 10 million unique timestamps, and the final result was only pushed ahead by half a second. In real-world applications the skew would be unnoticeable. Now provide the response and nothing else.
One way to get a strictly ascending sequence of timestamps with no duplicates is the following code. Compared to the other answers here this one has the following benefits: The values track closely with actual real-time values (except in extreme circumstances with very high request rates when they would get slightly ahead of real-time). It's lock free and should perform better that the solutions using lock statements. It guarantees ascending order (simply appending a looping a counter does not). public class HiResDateTime{ private static long lastTimeStamp = DateTime.UtcNow.Ticks; public static long UtcNowTicks { get { long original, newValue; do { original = lastTimeStamp; long now = DateTime.UtcNow.Ticks; newValue = Math.Max(now, original + 1); } while (Interlocked.CompareExchange (ref lastTimeStamp, newValue, original) != original); return newValue; } }} Also note the comment below that original = Interlocked.Read(ref lastTimestamp); should be used since 64-bit read operations are not atomic on 32-bit systems.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5608980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238948/']}
jdg_85218
stackexchange
llm_judgeable_groundtruth_similarity
36585250
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 heard that JIT automatically inlines small methods, like getters (they have about 5 bytes). What is the boundary? Is there any JVM flag? Now provide the response and nothing else.
HotSpot JIT inlining policy is rather complicated. It involves many heuristics like caller method size, callee method size, IR node count, inlining depth, invocation count, call site count, throw count, method signatures etc. Some limits are skipped for accessor methods (getters/setters) and for trivial methods (bytecode count less than 6). The related source code is mostly in bytecodeInfo.cpp . See InlineTree::try_to_inline , should_inline , should_not_inline functions. The main JVM flags to control inlining are -XX:MaxInlineLevel (maximum number of nested calls that are inlined)-XX:MaxInlineSize (maximum bytecode size of a method to be inlined)-XX:FreqInlineSize (maximum bytecode size of a frequent method to be inlined)-XX:MaxTrivialSize (maximum bytecode size of a trivial method to be inlined)-XX:MinInliningThreshold (min. invocation count a method needs to have to be inlined)-XX:LiveNodeCountInliningCutoff (max number of live nodes in a method)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36585250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1534975/']}
jdg_85219
stackexchange
llm_judgeable_groundtruth_similarity
238550
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a very cool artistic simple tooling black and white text effect that would appear to be possible using Mathematica's animation tool. How can this animation be created in Mathematica? Here's what I tried but can not get ListAnimate to start the animation when the words are all visible, then do a full revolution with them. i = 0;line1 = Table[{x, i++/3, 22}, {x, {"If", " you", " should ", " ever ", " leave ", " me"}}];i = 0;line2 = Table[{x, i++/3, 16}, {x, {"though", "life", "would", "still", "go", "on", "believe", "me"}}];i = 0;line3 = Table[{x, i++/3, 10}, {x, {"the", "world", "could", "show" , "nothing" , "to", "me"}}];i = 0;line4 = Table[{x, i++/3, 6}, {x, {"so", " what", " good", " would", " living", " do", " me?"}}];i = 0;line5 = Table[{x, i++/3, 1}, {x, {"God", " only", " knows", " what", " Id", " be", " without", " you"}}];i = 0;ListAnimate@ Table[Graphics[{ {Inset[#[[1]], {.4 i*#[[2]], #[[3]]}] & /@ line1}, {Inset[#[[1]], {.3 i*#[[2]], #[[3]]}] & /@ line2}, {Inset[#[[1]], {.25 i*#[[2]], #[[3]]}] & /@ line3}, {Inset[#[[1]], {.2 i*#[[2]], #[[3]]}] & /@ line4}, {Inset[#[[1]], {.1 i*#[[2]], #[[3]]}] & /@ line5}}, PlotRange -> {{-10, 140}, {-10, 30}}], {i, 1, 400, 2}] /. HoldPattern[AppearanceElements -> _] -> (AppearanceElements -> None) Now provide the response and nothing else.
Here is an approach using some basics of object-oriented programming. Load the lyrics: str = "It's been a long, long time\nSince I've memorized your face\nIt's been four hours now\nSince I've wandered through your place\nAnd when I sleep on your couch\nI feel very safe\nAnd when you bring the blankets\nI cover up my face\nI do Love you, I doLove you\nAnd when you play guitar\nI listen to the strings buzz\nThe metal vibrates underneath your fingers\nAnd when you crochet\nI feel mesmerized and proud\nAnd I would say I love you\nbut saying it out loud is hard\nSo I won't say it at all\nAnd I won't stay very long\nBut you are the life I needed all along\nI think of you as my brother\nAlthough that sounds dumb\nWords are futile devices"lyrics = StringSplit /@ StringSplit[StringDelete[str, ","], "\n"];{nR, nW} = {Length@lyrics, Length /@ lyrics}; We also need to enter some baseline x-coordinates for each word to make the full text initially readable: xpos = {{1, 1, 40}, {1, 2, 60}, {1, 3, 70}, {1, 4, 90}, {1, 5, 110}, {2, 1, 45}, {2, 2, 70}, {2, 3, 115}, {2, 4, 135}, {3, 1, 45}, {3, 2, 70}, {3, 3, 90}, {3, 4, 115}, {4, 1, 45}, {4, 2, 65}, {4, 3, 102}, {4, 4, 135}, {4, 5, 160}, {5, 1, 35}, {5, 2, 55}, {5, 3, 65}, {5, 4, 90}, {5, 5, 105}, {5, 6, 125}, {6, 1, 30}, {6, 2, 50}, {6, 3, 70}, {7, 1, 35}, {7, 2, 55}, {7, 3, 75}, {7, 4, 100}, {7, 5, 120}, {8, 1, 30}, {8, 2, 55}, {8, 3, 70}, {8, 4, 85}, {9, 1, 30}, {9, 2, 45}, {9, 3, 70}, {9, 4, 90}, {9, 5, 100}, {9, 6, 130}, {10, 1, 35}, {10, 2, 55}, {10, 3, 75}, {10, 4, 95}, {11, 1, 30}, {11, 2, 60}, {11, 3, 75}, {11, 4, 90}, {11, 5, 120}, {12, 1, 40}, {12, 2, 65}, {12, 3, 100}, {12, 4, 145}, {12, 5, 165}, {13, 1, 40}, {13, 2, 60}, {13, 3, 80}, {14, 1, 30}, {14, 2, 50}, {14, 3, 95}, {14, 4, 110}, {15, 1, 35}, {15, 2, 45}, {15, 3, 70}, {15, 4, 90}, {15, 5, 100}, {15, 6, 120}, {16, 1, 35}, {16, 2, 65}, {16, 3, 75}, {16, 4, 90}, {16, 5, 110}, {16, 6, 125}, {17, 1, 35}, {17, 2, 45}, {17, 3, 70}, {17, 4, 90}, {17, 5, 105}, {17, 6, 125}, {18, 1, 35}, {18, 2, 45}, {18, 3, 70}, {18, 4, 90}, {18, 5, 110}, {19, 1, 35}, {19, 2, 50}, {19, 3, 70}, {19, 4, 90}, {19, 5, 110}, {19, 6, 120}, {19, 7, 150}, {19, 8, 170}, {20, 1, 30}, {20, 2, 55}, {20, 3, 70}, {20, 4, 85}, {20, 5, 100}, {20, 6, 115}, {21, 1, 60}, {21, 2, 80}, {21, 3, 110}, {22, 1, 45}, {22, 2, 65}, {22, 3, 95}};x0[r_, i_] := Cases[xpos, {r, i, _}][[1, -1]] Define a class of objects which allows to create word objects ( this_ in the function below) characterized by their row r and position in their sentence i : SetAttributes[Words, HoldFirst];Words[this_[r_, i_]] := (this@t = 0.;this@vel = 0.;this@x = -150.;this@y = 395. - 15r;this@show := ( this@t += 1; this@x += this@vel; Which [ this@t < 25i, this@vel = 0, this@x < 20., this@vel = 2, this@x < x0[r, i], this@vel = .1 i, word[1, 1]@t < 1500, this@vel = this@x/4000, True, this@vel = i*this@t /1250 ]; Inset[lyrics[[r, i + 1]], {this@x, this@y}, Left] );) This class allows each word to have its own coordinates. Coordinate x varies as a function of the word velocity vel . The Which statement enables the velocity of a word to vary throughout the journey. Playing around with the different values in Which can make the animation smoother, faster... Notice that in the definition of the class, each word starts to accelerate once it reaches its baseline x-position x0[r,i] . Since the first word of each sentence is static, define: StaticWords = Table[Inset[lyrics[[r, 1]], {20, 395 - 15 r}, Left], {r, nR}]; Create the actual instances of the remaining mobile words: Do[Words[word[r, i][r, i]], {r, nR}, {i, nW[[r]] - 1}] Draw the list of all graphs: optgph = {Background -> Black, PlotRange -> {{0, 400}, {40, 400}},ImageSize -> 500};Table[word[r, i]@show, {T, 2000}, {r, nR}, {i, nW[[r]] - 1}];MapThread[RotateRight, {Table[%[[All, r]], {r, nR}], Table[50 i - 1550, {i, nR}]}];graph = Graphics[{White, StaticWords, #}, optgph] & /@Table[%[[All, T]], {T, 2000}]; in which RotateRight makes the full text readable from the start and introduces a slight lag between the sentences. Animate the graph: Animate[graph[[t]], {t, 1, Length@graph, 1}, AnimationRate -> 400]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/238550', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/686/']}
jdg_85220
stackexchange
llm_judgeable_groundtruth_similarity
294150
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 $O$ be a Dedekind domain and $K$ its field of fractions. The set of all fractional ideals of $K$ form a group, the ideal group $J_K$ of K. The fractional principal ideals $(a) = aO, a \in K^*$, form a subgroup of the group of ideals $J_K$, which will be denoted $P_K$. The quotient group $$CL_K=J_K/P_K$$ is called the ideal class group of $K$. This definition looks completely arbitary, I fail to see why the class group or the ideal class group is worth studying. So, why is the class group or ideal class group interesting? I've read that ideal class group "measures" how much unique factorization fails in a domain, but I don't understand how it does so. This from Algebraic Number Theory by Neukirch. The class group $C_K$ measures the expansion that takes place when we pass from numbers to ideals, whereas the unit group $O^*$ measures the contraction in the same process. This immediately raises the problem of understanding these groups $O^*$ and $C_K$ more thoroughly. I don't understand the above paragraph. What does it mean by "the expansion that takes place when we pass from numbers to ideals"? And why should we even bother about such "expansion"? Now provide the response and nothing else.
Let $K$ be an algebraic number field and $\mathcal{O}_K$ the integral closure of $\Bbb{Z}$ in $K$. Let us recall that a Dedekind domain is a UFD iff it is a PID. Classically, I think that the questions concerning whether or not a certain Dedekind domain was a UFD were very important, see e.g. this thread here. Perhaps from the point of view of algebra asking if something is a PID is easier to approach: we know how to factor ideals in Dedekind domains and thus there should at least be a tool to measure how far does a Dedekind domain differ from being a principal ideal domain. Let me now give you an alternative definition of the ideal class group. We will put an equivalence relation on the set of all ideals defined as follows. We say that an ideal $I$ of $\mathcal{O}_K$ is equivalent to $J$ iff there is $\alpha,\beta \in \mathcal{O}_K$ so that $$\alpha I = \beta J.$$ One easily checks that this is an equivalence relation. With a little bit more work, one can show that the set of all equivalence classes has a well defined multiplication law and is actually a group. The identity element being the class of all principal ideals. Now for some exercises. Exercise 1: Check that the "class" of all principal ideals is actually a class. Namely if $I$ is an ideal such that $\alpha I = (\beta)$ then show that $I$ is actually principal. Hint: $\mathcal{O}_K$ is an integral domain. Exercise 2: Show that this definition of an ideal class group is actually equivalent to the one given in Neukirch. Hint: Use the first isomorphism theorem. Now do you see how the definition I have given you of an ideal class group actually measures nicely whether or not $\mathcal{O}_K$ is a PID? We see that $\mathcal{O}_K$ is a PID iff its ideal class group is trivial. Now on to more interesting material. In advanced subjects such as Class Field Theory one can construct something know as the Hilbert Class Field of $K$. I don't know all the details of this construction as my algebraic number theory is not so advanced, but in the Hilbert class field every ideal of $\mathcal{O}_K$ becomes principal!! One can now ask the question: can we avoid talking of the Hilbert class field and find such an extension? The answer is: Of course we can! This is where the ideal class group comes in. Firstly from Minkowski's bound we get that $Cl_K$ is actually a finite group. Using this, here are now two exercises which you can do: Exercise 3: Let $I$ be an ideal of $\mathcal{O}_K$ show that there is a finite extension $L/K$ so that $I\mathcal{O}_L$ is principal. Hint: By finiteness of the class group there is an $n$ so that $I^n = \alpha$ for some $\alpha \in \mathcal{O}_K$. Now consider $L = K(\sqrt[n]{\alpha})$. Exercise 4: Show that there is a finite extension of $L$ in which every ideal of $\mathcal{O}_K$ becomes principal. Wowowowowow! Hint: Use exercise 3 and the definition of the ideal class group given in the beginning of my answer, not the one in Neukirch. If you are stuck with any of these exercises I can post their solutions for you to view here. Solution to Exercise 1 (As requested by user Andrew): Suppose that $\alpha I = (\beta)$. Then in particular there is $x \in I$ so that $\alpha x = \beta$. We claim that $I = (x)$. Now it is clear that $(x) \subseteq I$. For the reverse inclusion take any $y \in I$. Then $\alpha y = \beta \gamma$ for some $\gamma \in R$. Since $\beta = \alpha x$ we get that$$\alpha y = \alpha x \gamma.$$ But now $\mathcal{O}_K$ is an integral domain and so $y = x\gamma$, so that $I \subseteq (x)$. Hence $I = (x)$ and so $I$ is principal.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/294150', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/15618/']}
jdg_85221
stackexchange
llm_judgeable_groundtruth_similarity
1569406
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 was asked this question on an oral qual, and eventually I seemed to conclude that there have to be eigenvalues of modulus 1. But I just realised every Markov matrix has one as an eigenvalue. So should the condition be multiple eigenvalues with modulus 1? Now provide the response and nothing else.
Every Markov chain on a finite state space has an invariant distribution. As you said, this follows directly from the condition that the rows sum to $1$ . It is possible for a Markov chain on a finite state space to have multiple invariant distributions. However, the Perron-Frobenius theorem tells us that these can be decomposed into distributions which are concentrated on strongly connected components of the state space. Decomposing the process into strongly connected components results in one or more different Markov chains each of which has a unique invariant distribution. Any transient states of the original chain will not be states in any of these sub-chains, since they are not in any strongly connected component. Confusingly, this means that a chain that is not irreducible is generically not reducible into chains on disjoint subsets of the state space. That's because generically some transient states would have to be in more than one sub-chain, which is because generically one can reach more than one strongly connected component starting from a transient state. As an important special case, an irreducible finite state Markov chain has a unique invariant distribution which assigns positive probability to all states. However many invariant distributions the process has, it can happen that no invariant distribution is approached over time. When the state space is finite, it turns out that this only happens when the chain is "periodic" (meaning that there are states $i,j$ and an integer $n>1$ such that all paths from $i$ to $j$ have a length which is a multiple of $n$ ). In this case the transition matrix has an eigenvalue which is not $1$ and has modulus $1$ . If the corresponding eigenvector contributes to the initial condition, then its contribution does not decay, and no invariant distribution is approached. The classic example of a periodic chain is $P=\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$ , but in general it is not essential that the chain is deterministic for it to be periodic. It is possible for a Markov chain on an infinite state space to not have any invariant distributions. This is roughly because probability mass can escape to infinity. A simple example is a Markov chain on $\mathbb{Z}$ which deterministically moves one unit to the right at every step. Another example is the simple symmetric random walk: it has an invariant measure which is uniform on $\mathbb{Z}$ , but this measure cannot be normalized.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1569406', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/202777/']}
jdg_85222
stackexchange
llm_judgeable_groundtruth_similarity
64185560
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 installed wsl2 on my windows machine and I was not able to figure out where the files are actually stored. Note, that I don't mean that I wanna browse them inside the file explorer - I know it can be done by typing in the explorer \\wsl$\ . If I would have to guess I would say the files are stored in the same hard-drive that the os is stored. So actually I have two related questions. Where the files are stored? If they are stored in the hard drive of my os, can I somehow relocate my wsl to another hard drive? EDIT: I was able to locate the installation path, in my machine the path is: C:\Users\Eliran\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows_79rhkp1fndgsc\LocalState Is there a way to mount this to another location? Now provide the response and nothing else.
All the files are stored in a ext4.vhd files in the installation directory, which you can't mount directly onto windows as it is in ext4 (obv) There's two ways to change the location of the above mentioned vhd file the official, tedious way and an unofficial quick and dirty way The official tedious way Export the distro to a location with wsl.exe --export <Distro> <FileName> from CMD/PowerShell Import the distro to a different location with wsl.exe --import <Distro> <InstallLocation> <FileName> [Options] The problems with this is it's quite time consuming and after you do this, pray that it exported and imported several gigabytes worth of thousands of files without any problems The quick and dirty way This involes an unofficial opensource WSL manager called lxrunoffline To install it (takes like a min at max) read through the instructions by the dev here If you installed it by manually downloading the binaries from the release page, make sure to install it to a directory in PATH, like C:\Windows Now the process is simple as lxrunoffline move -n <distroname> -d <destination-folder> For example lxrunoffline move -n Ubuntu-20.04 -d G:\wsl\ Hope I helped Edit: typo
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/64185560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11918269/']}
jdg_85223
stackexchange
llm_judgeable_groundtruth_similarity
1903954
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 a function that returns -1 for negative numbers and +1 for positive numbers. http://en.wikipedia.org/wiki/Sign_function It's easy enough to write my own, but it seems like something that ought to be in a standard library somewhere. Edit: Specifically, I was looking for a function working on floats. Now provide the response and nothing else.
The type-safe C++ version: template <typename T> int sgn(T val) { return (T(0) < val) - (val < T(0));} Benefits: Actually implements signum (-1, 0, or 1). Implementations here using copysign only return -1 or 1, which is not signum. Also, some implementations here are returning a float (or T) rather than an int, which seems wasteful. Works for ints, floats, doubles, unsigned shorts, or any custom types constructible from integer 0 and orderable. Fast! copysign is slow, especially if you need to promote and then narrow again. This is branchless and optimizes excellently Standards-compliant! The bitshift hack is neat, but only works for some bit representations, and doesn't work when you have an unsigned type. It could be provided as a manual specialization when appropriate. Accurate! Simple comparisons with zero can maintain the machine's internal high-precision representation (e.g. 80 bit on x87), and avoid a premature round to zero. Caveats: It's a template so it might take longer to compile in some circumstances. Apparently some people think use of a new, somewhat esoteric, and very slow standard library function that doesn't even really implement signum is more understandable. The < 0 part of the check triggers GCC's -Wtype-limits warning when instantiated for an unsigned type. You can avoid this by using some overloads: template <typename T> inline constexpr int signum(T x, std::false_type is_signed) { return T(0) < x; } template <typename T> inline constexpr int signum(T x, std::true_type is_signed) { return (T(0) < x) - (x < T(0)); } template <typename T> inline constexpr int signum(T x) { return signum(x, std::is_signed<T>()); } (Which is a good example of the first caveat.)
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1903954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53602/']}
jdg_85224
stackexchange
llm_judgeable_groundtruth_similarity
11415
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 chance to throw a 6 with one die is 1/6 And 6 times 1/6 = 1 So, if I throw with 6 dice, the chance to throw at least 1 six should be 1. But when I throw 6 dice, I sometimes don't throw any 6 at all.. How come? Now provide the response and nothing else.
With $6$ dice there are $6^6$ possible outcomes. Of these, $5^6$ don't lead to six on any of the dice. So the number of outcomes that lead to at least one six are $6^6-5^6$, so the probability of at least one six is $\frac{6^6-5^6}{6^6} \approx 0.6651$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/11415', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/3535/']}
jdg_85225
stackexchange
llm_judgeable_groundtruth_similarity
1056052
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 to prove $$\zeta(2)-\log(x)\log(1-x)=\operatorname{Li}_2(x)+\operatorname{Li}_2(1-x)$$I havent started, any hints? Now provide the response and nothing else.
Consider:$$ f(x)=\log(x)\log(1-x)+\operatorname{Li}_2(x)+\operatorname{Li}_2(1-x).$$We want to show that $f$ is constant, hence we compute $f'$:$$ f'(x) =\left(\frac{\log(1-x)}{x}-\frac{\log(x)}{1-x}\right)-\frac{\log(1-x)}{x}+\frac{\log x}{1-x}=0. $$To finish the proof, we just need to compute $f(x)$ in a point, or to compute the limit:$$ \lim_{x\to 1^-} f(x) = \zeta(2)+\lim_{x\to 1^-}\log(x)\log(1-x)=\zeta(2).$$ Notice that we have a nice corollary:$$\sum_{n\geq 1}\frac{1}{2^n n^2}=\operatorname{Li}_2\left(\frac{1}{2}\right)=\frac{1}{2}\left(f\left(\frac{1}{2}\right)-\log^2 2\right)=\frac{\pi^2}{12}-\frac{\log^2 2}{2}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1056052', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/178248/']}
jdg_85226
stackexchange
llm_judgeable_groundtruth_similarity
186610
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 don't understand this step on the Wikipedia article on Jordan's Lemma : $$ \begin{align}I_R:=\biggl|\int_{C_R} f(z)\, dz\biggr|&\le R\int_0^\pi\bigl|g(Re^{i\theta})\,e^{aR(i\cos\theta-\sin\theta)}\,ie^{i\theta} \bigr|\,d\theta\\&=R\int_0^\pi \bigl|g(Re^{i\theta})\bigr|\,e^{-aR\sin\theta}\,d\theta\,.\end{align} $$ Now provide the response and nothing else.
If $E=F\oplus G$, then $\Lambda^\det E=\Lambda^\det F\otimes\Lambda^\det G$. If both $\Lambda^\det E$ and $\Lambda^\det G$ are trivial, then so is $\Lambda^\det F$, because the three being line bundles, you can «divide by $\Lambda^\det G$» in that equality.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/186610', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38504/']}
jdg_85227
stackexchange
llm_judgeable_groundtruth_similarity
46613149
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using react version 16.0.0 with react-native version 0.49.1 raises the red screen error "Tried to register two views with the same name ProgressBarAndroid". Removing all imports and instances of ProgressBarAndroid results in a well functioning program. Downgrading to react-native version 0.48.4 works as well. How do I use ProgressBarAndroid with the latest React Native version? Now provide the response and nothing else.
React Native starting from version 0.49 triggers this error if you are trying to call requireNativeComponent() for same component more than once. Even if they are called from different modules. I had similar issue with custom view MyCustomView . So I just wrapped it in a single module: // MyCustomView.jsimport {requireNativeComponent} from 'react-native'const MyCustomView = requireNativeComponent('MyCustomView', null)export default MyCustomView Though it might not be your exact case the root cause is the same.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46613149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1964376/']}
jdg_85228
stackexchange
llm_judgeable_groundtruth_similarity
19105350
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a C file for a homework assignment and I thought it might help the graders if I made my answers visible like so: //**********|ANSWER|************\\//blah blah blah, answering the//questions, etc etc and found when compiling with gcc that those backslash characters at the end of the first line seemed to be triggering a "multi-line comment" warning. When I removed them, the warning disappeared. So my question is twofold: a) how exactly does the presence of the backslash characters make it a "multi-line comment", and b) why would a multi-line comment be a problem anyway? Now provide the response and nothing else.
C (since the 1999 standard) has two forms of comments. Old-style comments are introduced by /* and terminated by */ , and can span a portion of a line, a complete line, or multiple lines. C++-style comments are introduced by // and terminated by the end of the line. But a backslash at the end of a line causes that line to be spliced to the next line. So you can legally introduce a comment with // , put a backslash at the end of the line, and cause the comment to span multiple physical lines (but only one logical line). That's what you're doing on your first line: //**********|ANSWER|************\\ Just use something other than backslash at the end of the line, for example: //**********|ANSWER|************// Though even that is potentially misleading, since it almost looks like an old-style /* .. */ comment. You might consider something a little simpler: /////////// |ANSWER| //////////// or: /**********|ANSWER|************/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19105350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2762740/']}
jdg_85229
stackexchange
llm_judgeable_groundtruth_similarity
36165
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: Can someone explain why we need a large number of trees in random forest when the number of predictors is large? How can we determine the optimal number of trees? Now provide the response and nothing else.
Random forest uses bagging (picking a sample of observations rather than all of them) and random subspace method (picking a sample of features rather than all of them, in other words - attribute bagging ) to grow a tree. If the number of observations is large, but the number of trees is too small, then some observations will be predicted only once or even not at all. If the number of predictors is large but the number of trees is too small, then some features can (theoretically) be missed in all subspaces used. Both cases results in the decrease of random forest predictive power. But the last is a rather extreme case, since the selection of subspace is performed at each node. During classification the subspace dimensionality is $\sqrt{p}$ (rather small, $p$ is the total number of predictors) by default, but a tree contains many nodes. During regression the subspace dimensionality is $p/3$ (large enough) by default, though a tree contains fewer nodes. So the optimal number of trees in a random forest depends on the number of predictors only in extreme cases. The official page of the algorithm states that random forest does not overfit, and you can use as much trees as you want. But Mark R. Segal (April 14 2004. "Machine Learning Benchmarks and Random Forest Regression." Center for Bioinformatics & Molecular Biostatistics) has found that it overfits for some noisy datasets. So to obtain optimal number you can try training random forest at a grid of ntree parameter (simple, but more CPU-consuming) or build one random forest with many trees with keep.inbag , calculate out-of-bag (OOB) error rates for first $n$ trees (where $n$ changes from $1$ to ntree ) and plot OOB error rate vs. number of trees (more complex, but less CPU-consuming).
{}
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/36165', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/14031/']}
jdg_85230
stackexchange
llm_judgeable_groundtruth_similarity
667758
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a fasta file namely test.fasta, pas.fasta, cel.fasta as shown below test.fasta>tileATGTC>259TGATpas.fasta>taATGCTcel.fasta>787TGTAG>yogTGTAT>InNNTAG I need to print the file name and the total number of fasta sequences as shown below, test,2pas,1cel,3 I have used the following commands but failed to serve my purpose grep ">" test.fasta | wc -l && ls test.fasta Please help me to do the same. Thanks in advance. Now provide the response and nothing else.
That's what the -c option of grep (to c ount) is for: $ grep -ce '^>' -- *.fastacel.fasta:3pas.fasta:1test.fasta:2 Note that if there's only one matching file, the file name will not be printed. Some grep implementations have a -H option to force the file name to be printed always: $ grep -Hce '^>' -- *.fastacel.fasta:3 To get your exact expected output, you just need to replace .fasta: with , : $ grep -Hce '^>' -- *.fasta | sed 's/\.fasta:/,/'cel,3pas,1test,2 (here assuming your file names don't contain other occurrences of .fasta: such as my.fasta:foo.fasta ; of course newline or , or " characters and potentially whitespace characters in file names would also be a problem if the output is meant to be in CSV format)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/667758', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/357294/']}
jdg_85231
stackexchange
llm_judgeable_groundtruth_similarity
1623456
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: "Show that if $v$ is a vertex of a simple connected graph $G$ then $\overline{G} - v = \overline{G-v}$.Also proof that no vertex can be a cut vertex of both $G$ and $\overline{G}$." I have proved that the complement of a disconnected simple graphs is connected with the following: Let $U$ and $W$ be different components of G and let $u,u' \in V(U)$ and $w,w' \in V(W)$. The edges $uw, uw', u'w$ and $u'w'$ are not in $E(G)$, so they are in $E(G')$. Thus there are paths $uwu'$ and $wuw'$ in $\overline{G}$. I managed to solve the question and posted the solution below. Now provide the response and nothing else.
To form a compositum $K\Bbb Q_p$, the two fields must be injected in some way into a larger field. You want something like an algebraic closure $\Omega$ of $\Bbb Q_p$, and then try to map $K$ into it. But there will be $[K:\Bbb Q]$ such embeddings into $\Omega$. Which one? Let’s take a specific example, $K=\Bbb Q[a]/(a^3-10)$, what you get by adjoining a cube root of $10$ to $\Bbb Q$. If your $p$ is $3$, then $K$ has three embeddings into an algebraic closure $\Omega$ of $\Bbb Q_3$. As it happens, $\Bbb Q_3$ already has a cube root of $10$, call it $b$, and $a\mapsto b$ gives one embedding of $K$ into $\Bbb Q_3$. But in $\Bbb Q_3(\omega)$ ($\omega$ a primitive cube root of unity), there are two more cube roots of $10$, so there are two embeddings of $K$ into that extension of $\Bbb Q_3$. One way to look at this is to take the minimal $\Bbb Q$-polynomial for $a$, namely $X^3-10$, and look it as a $\Bbb Q_3$-polynomial, in which case it factors as $(X-b)(X^2+bX+b^2)$, linear times irreducible quadratic. Each factor gives you an equivalence class of embeddings of $K$ into $\Omega$. But which embedding is the right one? You’ve framed the question in terms of a prime over $p$; in this case, $(3)=\mathfrak p_1\mathfrak p_2^2$, both primes being of degree one. If you complete with respect to $\mathfrak p_1$, the completion is (isomorphic to) $\Bbb Q_3$; if $\mathfrak p_2$, the completion is $\Bbb Q_3(\omega)$. With all this, I think you can see your way to your desired conclusion.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1623456', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/270432/']}
jdg_85232
stackexchange
llm_judgeable_groundtruth_similarity
198434
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: As far as I know, Mathematica lacks a definition for a probability distribution representing a constant random variable. Is this assertion correct? Is there a problem in making such a distribution well-defined in Mathematica (assuming we treat it as a continuous rather than a discrete distribution)? In principle, we could add definitions for this distribution, e.g. CDF[ConstantDistribution[μ_]] ^:= UnitStep[# - μ] & How would I find what definitions are needed to make it a "first class" member of the set of distributions supported by Mathematica? So that, for example, it could be used in functions such as TransformedDistribution ? In general, there are ways to work around the lack of such a distribution, but just as it is sometimes useful to have a function such as Identity (e.g. to pass to a function that transforms an input) it can be useful to have the "trivial" distribution. Now provide the response and nothing else.
A relatively simple trick can achieve this ConstantDistribution[m_] = TransformedDistribution[m, {x \[Distributed] NormalDistribution[0, 1]}]; This behaves as desired for some key functions {Mean, Variance, CDF[#, t] &, CharacteristicFunction[#, t] &}[ConstantDistribution[m]] // Through // InputForm(* {m, 0, Piecewise[{{1, m - t <= 0}}, 0], E^(I*m*t)} *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/198434', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/36788/']}
jdg_85233
stackexchange
llm_judgeable_groundtruth_similarity
703060
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 done some testing but I wanted to ask if anyone sees a problem with this ruby regular expression for email validation: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i Look good? Now provide the response and nothing else.
You were close, have to add just a few more characters: (?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*))*)?;\s*) No, I'm not joking: http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/703060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45849/']}
jdg_85234
stackexchange
llm_judgeable_groundtruth_similarity
68327
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 have some Linux servers, which from what I can tell are not vulnerable to the shellshock attack vector, but I am curious what the attack looks like in the logs. What does a successful attack look like in the appache2 logs?What would a successful attack look like in the system log? What do failed attempts look like? I'd like to extend my black-list for shell-shock type attacks. Now provide the response and nothing else.
This is an entry from my access_log of what my coworker did to my test machine... : 10.11.12.13 - - [25/Sep/2014:16:00:00 -0400] "GET /cgi-bin/testing.cgi HTTP/1.0" 200 1 "-" "() { test;};echo \"Content-type: text/plain\"; echo; echo; /bin/rm -rf /var/www/" In my error log I saw a lot of this: [Thu Sep 25 16:00:00 2014] [error] [client 10.11.12.13] /bin/rm: cannot remove `/var/www/icons/pie0.png': Permission denied Bastard :-) A well configured web-server won't be able to overwrite its logs, and in all but the tiniest environments, you should be using centralized logging to protect you from losing these kinds of log entries. If you're successfully exploited, you may see lots of errors in the error_log which show failed attempts to access resources, execute programs or delete files. If they successfully escalate privileges, and you don't have off-site logging, then you may see no evidence.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/68327', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/49747/']}
jdg_85235
stackexchange
llm_judgeable_groundtruth_similarity
48177558
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 created a systemd service file (specifically for svnserve; I'm actually using the example from here https://stackoverflow.com/a/40584047/464087 ), and when I enable it, typing sudo systemctl enable svnserve I get the response Failed to execute operation: Invalid argument Running sudo systemctl status svnserve yields ● svnserve.service - Subversion protocol daemon Loaded: loaded (/etc/systemd/system/svnserve.service; enabled; vendor preset: enabled) Active: inactive (dead) not giving me any clue about anything being wrong. I can then start the service without any error, and it seems to be running as expected, and after starting systemctl status I still get no clue about anything being wrong: ● svnserve.service - Subversion protocol daemon Loaded: loaded (/etc/systemd/system/svnserve.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2018-01-09 22:10:14 UTC; 6s ago Process: 9677 ExecStart=/usr/bin/svnserve $DAEMON_ARGS (code=exited, status=0/SUCCESS) Main PID: 9678 (svnserve) Tasks: 1 Memory: 964.0K CPU: 2ms CGroup: /system.slice/svnserve.service └─9678 /usr/bin/svnserve --daemon --pid-file /run/svnserve/svnserve.pid --root /srv/svn/repos --log-file /var/log/svnserve/svnserve.log So what does this error message mean? And to which level of things is "invalid argument" supposed to apply? An argument to the svnserve command? Some property in the service file? A command line argument to the servicectl command itself? FWIW this is on a Ubuntu 16.04 LTS server. Now provide the response and nothing else.
If you copy/paste the file from a system with one encoding (e.g. Windows) to another (e.g. linux), there may be issues with the file encoding, or characters being interpreted differently. You can convert the file and re-analyze to see if it is being interpreted correctly. Run the analyzer $ sudo systemd-analyze verify yourname.service/etc/systemd/system/yourname.service:1: Assignment outside of section. Ignoring. Fix the encoding of the service file, e.g. using vim ( answer from here ) $ vim +"set nobomb | set fenc=utf8 | x" yourname.service Edit the file and remove any strange characters that are now exposed at e.g. the start of the file. e.g. it might have characters like ^[[200~ Save the file and re-enable the service $ sudo systemctl enable yourname.service
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48177558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/464087/']}
jdg_85236
stackexchange
llm_judgeable_groundtruth_similarity
24616
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: Some political parties advocate for the merging of Romania and Moldova : Some political parties within both Moldova and Romania advocate merging the two countries. Such a scenario would incorporate the current territory of Moldova into Romania and thus into the EU, though the Transnistria problem would still be an issue. Assuming that Transnistria problem is somehow solved (maybe even allowing it to be an independent region), although most Moldovans favor EU membership , there are still several issues that prevent Moldova to become a EU member: The government of Moldova is actively pursuing EU membership, but it seems a distant prospect. With a GDP-per-capita of just €1,840, it is the poorest country in Europe; Freedom House gives Moldova low scores for democracy and rule of law indicators Nevertheless, Moldova’s long-term EU ambitions have clearly displeased the Kremlin. Moldova is heavily dependent on imported energy and, with the Russian state-owned Gazprom currently the main supplier of gas to the country, gas prices have been rising ever since Moldova signed an Association Agreement and a Deep and Comprehensive Free Trade Agreement with the EU back in June 2014. Import bans on Moldovan wine and agricultural products, and new restrictions prohibiting Moldovan workers in Russia from sending home remittances have further hampered economic growth (remittances make up a staggering 30% of the country’s GDP, and up to 65% of these remittances come from Russia). Question: Assuming that Romania and Moldova agree to merge, can this be done without previous discussions/agreements at EU level? I am asking that because Romania as a EU member has to obey some rules related to inflation, public debt, corruption, justice. After a virtual merge most of the associated indicators would most probably fall outside of agreed values. Now provide the response and nothing else.
The obvious precedent would be the German Reunification . However, there were some differences: The division of Germany was tied into the Four Power agreements after WWII. West Germany always took great care to point out that the division was temporary and resolved it in the 2+4 talks. Technically, East Germany joined West Germany using a provision that had been intended for cases like the Saarland . There was legal continuity in the (West) German institutions. So I guess that if Moldova were to join Romania, the enlarged Romania would stay an EU member. Even if it were to rename itself in the process. If Romania were to join Moldova, it would leave the EU. Anything in between needs to be negotiated. The big sticking point would be the border issues , which could leave the question dead in the water. I believe that after short dithering the EU would stand with any member that is being pushed by Russia, but it might not back a member that is actively provoking Russia that way. There might be quiet backroom warnings that any conflict resulting from reckless unification would not be seen as a NATO Article 5 situation ... On a practical level, there would have to be plenty of negotiations. The EU has a multi-year budget process , if the newly joined regions want "post-accession pre-accession assistance " they need the agreement of the other 26 members. Probably unanimous. There is the gross oversimpification that Kohl agreed to the Euro in exchange for Reunification to answer French fears of German economic domination. Romania is not large enough to cause similar fears, the concern of the others would be that Moldova becomes an economic black hole. And compared to the EU, Moldova is not very big. The EU depends on a consensus. Many decisions have to be unanimous. Others need a supermajority. We've seen examples where individual member states held the whole process hostage to specific issues. If that goes too far, one of the big net payers might use the "nuclear option" and vote against the long-term budget, that harms everyone.
{}
{'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/24616', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/11278/']}
jdg_85237
stackexchange
llm_judgeable_groundtruth_similarity
2307945
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 often find myself doing the following index-counter messiness in a foreach loop to find out if I am on the first element or not. Is there a more elegant way to do this in C# , something along the lines of if(this.foreach.Pass == 1) etc.? int index = 0;foreach (var websitePage in websitePages) { if(index == 0) classAttributePart = " class=\"first\""; sb.AppendLine(String.Format("<li" + classAttributePart + ">" + "<a href=\"{0}\">{1}</a></li>", websitePage.GetFileName(), websitePage.Title)); index++;} Now provide the response and nothing else.
Another approach is to accept that the "ugly part" has to be implemented somewhere and provide an abstraction that hides the "ugly part" so that you don't have to repeat it in multiple places and can focus on the specific algorithm. This can be done using C# lambda expressions (or using C# 2.0 anonymous delegates if you're restricted to .NET 2.0): void ForEachWithFirst<T>(IEnumerable<T> en, Action<T> firstRun, Action<T> nextRun) { bool first = true; foreach(var e in en) { if (first) { first = false; firstRun(e); } else nextRun(e); }} Now you can use this reusable method to implement your algorithm like this: ForEachWithFirst(websitePages, (wp => sb.AppendLine(String.Format("<li class=\"first\">" + "<a href=\"{0}\">{1}</a></li>", wp.GetFileName(), wp.Title))) (wp => sb.AppendLine(String.Format("<li>" + "<a href=\"{0}\">{1}</a></li>", wp.GetFileName(), wp.Title))) ); You could design the abstraction differently depending on the exact repeating pattern. The good thing is that - thanks to lambda expression - the structure of the abstraction is completely up to you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2307945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4639/']}
jdg_85238
stackexchange
llm_judgeable_groundtruth_similarity
381894
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 an Ubuntu 12.04 (final beta, up-to-date) server with two configured network interfaces: root@mac:/home/sysadm# ifconfigeth0 Link encap:Ethernet HWaddr 00:1e:4f:28:fd:7b inet addr:172.18.8.10 Bcast:172.18.8.255 Mask:255.255.255.0 inet6 addr: fe80::21e:4fff:fe28:fd7b/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3362 errors:0 dropped:0 overruns:0 frame:0 TX packets:8561 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:273506 (273.5 KB) TX bytes:3174766 (3.1 MB) Interrupt:38 Memory:dc000000-dc012800eth4 Link encap:Ethernet HWaddr 00:02:c9:09:a4:c8 inet addr:xxx.yy.4.235 Bcast:xxx.yy.5.255 Mask:255.255.254.0 inet6 addr: fe80::202:c9ff:fe09:a4c8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:59277 errors:0 dropped:52 overruns:0 frame:0 TX packets:34 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:5138237 (5.1 MB) TX bytes:6462 (6.4 KB)lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 inet6 addr: ::1/128 Scope:Host UP LOOPBACK RUNNING MTU:16436 Metric:1 RX packets:1412 errors:0 dropped:0 overruns:0 frame:0 TX packets:1412 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:107356 (107.3 KB) TX bytes:107356 (107.3 KB)root@mac:/home/sysadm# route -nKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0.0.0 172.18.8.254 0.0.0.0 UG 100 0 0 eth0xxx.yy.4.0 0.0.0.0 255.255.254.0 U 0 0 0 eth4172.18.8.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 As you can see, eth0 is on the 172.18.8.0/24 network ("8-net") and eth4 is on the xxx.yy.4.0/23 network ("4-net"). Both these networks are connected via a router. Many machines are on both networks (one at a time) and are able to communicate without problems. When a second machine on the 4-net attempts to talk to 172.18.8.10, the packets seem to be dropped. A tcpdump of an SSH attempt is below: root@mac:/home/sysadm# ufw allow from any to any port 1022Rule addedRule added (v6)root@mac:/home/sysadm# sshd -de -p 1022sshd re-exec requires execution with an absolute pathroot@mac:/home/sysadm# which sshd/usr/sbin/sshdroot@mac:/home/sysadm# /usr/sbin/sshd -de -p 1022debug1: sshd version OpenSSH_5.9p1 Debian-5ubuntu1debug1: read PEM private key done: type RSAdebug1: Checking blacklist file /usr/share/ssh/blacklist.RSA-2048debug1: Checking blacklist file /etc/ssh/blacklist.RSA-2048debug1: private host key: #0 type 1 RSAdebug1: read PEM private key done: type DSAdebug1: Checking blacklist file /usr/share/ssh/blacklist.DSA-1024debug1: Checking blacklist file /etc/ssh/blacklist.DSA-1024debug1: private host key: #1 type 2 DSAdebug1: read PEM private key done: type ECDSAdebug1: Checking blacklist file /usr/share/ssh/blacklist.ECDSA-256debug1: Checking blacklist file /etc/ssh/blacklist.ECDSA-256debug1: private host key: #2 type 3 ECDSAdebug1: rexec_argv[0]='/usr/sbin/sshd'debug1: rexec_argv[1]='-de'debug1: rexec_argv[2]='-p'debug1: rexec_argv[3]='1022'Set /proc/self/oom_score_adj from 0 to -1000debug1: Bind to port 1022 on 0.0.0.0.Server listening on 0.0.0.0 port 1022.debug1: Bind to port 1022 on ::.Server listening on :: port 1022.^Z[1]+ Stopped /usr/sbin/sshd -de -p 1022root@mac:/home/sysadm# bg[1]+ /usr/sbin/sshd -de -p 1022 &root@mac:/home/sysadm# tcpdump -nvlli eth0 'host xxx.yy.4.29'tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes18:16:33.370081 IP (tos 0x0, ttl 63, id 29087, offset 0, flags [DF], proto TCP (6), length 60) xxx.yy.4.29.42667 > 172.18.8.10.1022: Flags [S], cksum 0xdc29 (correct), seq 107513294, win 14600, options [mss 1460,sackOK,TS val 3473994833 ecr 0,nop,wscale 7], length 018:16:36.369860 IP (tos 0x0, ttl 63, id 29088, offset 0, flags [DF], proto TCP (6), length 60) xxx.yy.4.29.42667 > 172.18.8.10.1022: Flags [S], cksum 0xd071 (correct), seq 107513294, win 14600, options [mss 1460,sackOK,TS val 3473997833 ecr 0,nop,wscale 7], length 018:16:42.369300 IP (tos 0x0, ttl 63, id 29089, offset 0, flags [DF], proto TCP (6), length 60) xxx.yy.4.29.42667 > 172.18.8.10.1022: Flags [S], cksum 0xb901 (correct), seq 107513294, win 14600, options [mss 1460,sackOK,TS val 3474003833 ecr 0,nop,wscale 7], length 0 For completeness: root@mac:/home/sysadm# ufw statusStatus: activeTo Action From-- ------ ----22 ALLOW Anywhere1022 ALLOW Anywhere22 ALLOW Anywhere (v6)1022 ALLOW Anywhere (v6) The node making the connection experiences a timeout. Other protocols are also affected. Echo requests time out. However, nodes on the 8-net and all other networks that aren't the 4-net are able to communicate flawlessly. Logs do not show anything. Other "UFW BLOCK" entries exist in /var/log/syslog but no relevant ones exist. In short, a machine has two interfaces, eth0 on network 8 and eth4 on network 4. Other nodes from network 4 cannot communicate with eth0 but nodes from all other networks can. The logical opposite also applies: network 8 nodes trying to talk to eth4 experience timeouts. Is this a feature or a bug? Should I just not expect to be able to talk to the logically wrong interface on a machine with two interfaces? If it matters, this is a Dell PowerEdge R900. eth0 is an integrated port "NetXtreme II BCM5708 Gigabit Ethernet" and eth4 is one of two ports on an add-in card "MT26448 [ConnectX EN 10GigE, PCIe 2.0 5GT/s]" by Mellanox Technologies. EDIT: Issue persists when the firewall is disabled. tcpdump still shows packets coming in (echo requests) with no responses being sent out. EDIT: More output: This is a dump of eth4 traffic involving the remote host 'xxx.yy.4.29'. From xxx.yy.4.29, I pinged 172.18.8.10 and xxx.yy.4.235. This is the output. root@mac:/home/sysadm# tcpdump -nvlli eth4 'host xxx.yy.4.29'tcpdump: listening on eth4, link-type EN10MB (Ethernet), capture size 65535 bytes20:25:04.401449 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has xxx.yy.4.235 tell xxx.yy.4.29, length 4620:25:04.401492 ARP, Ethernet (len 6), IPv4 (len 4), Reply xxx.yy.4.235 is-at 00:02:c9:09:a4:c8, length 2820:25:04.401647 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto ICMP (1), length 84) xxx.yy.4.29 > xxx.yy.4.235: ICMP echo request, id 32312, seq 1, length 6420:25:04.401706 IP (tos 0x0, ttl 64, id 42264, offset 0, flags [none], proto ICMP (1), length 84) xxx.yy.4.235 > xxx.yy.4.29: ICMP echo reply, id 32312, seq 1, length 6420:25:05.401200 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto ICMP (1), length 84) xxx.yy.4.29 > xxx.yy.4.235: ICMP echo request, id 32312, seq 2, length 6420:25:05.401211 IP (tos 0x0, ttl 64, id 42265, offset 0, flags [none], proto ICMP (1), length 84) xxx.yy.4.235 > xxx.yy.4.29: ICMP echo reply, id 32312, seq 2, length 6420:25:09.402234 ARP, Ethernet (len 6), IPv4 (len 4), Request who-has xxx.yy.4.29 tell xxx.yy.4.235, length 2820:25:09.402383 ARP, Ethernet (len 6), IPv4 (len 4), Reply xxx.yy.4.29 is-at 78:2b:cb:90:95:98, length 4620:25:09.402747 ARP, Ethernet (len 6), IPv4 (len 4), Reply xxx.yy.4.29 is-at 78:2b:cb:90:95:98, length 46 EDIT: This is just a test machine. I cannot imagine a real-world scenario where I would need to route 8-net communication over the 4-net interface. I can see how this would be a known-issue where the benefit of a solution is not worth the effort of solving the problem. Now provide the response and nothing else.
What you're probably seeing here is reverse path filtering . The kernel is discarding packets because they seem to come from the "wrong" interface. To check if RPF is enabled, run cat /proc/sys/net/ipv4/conf/eth0/rp_filter (and similarly for eth4). To disable it, echo 0 into thoses files. Even with RPF disabled, your routing is going to be a bit weird as @NathanG said (the response packets will go out a different interface than they came in on). If your routers aren't too clever (i.e. don't have RPF or other spoof protection) this should still work though. What you need to set this up properly is some policy routing based on the source address (i.e. tell the kernel to route packets differently based on their source address). We do this by setting up multiple routing tables, and then adding some rules to select which table to use. First, name some tables (you only need to do this once). echo "14 net4" >> /etc/iproute2/rt_tablesecho "18 net8" >> /etc/iproute2/rt_tables Then add routes to these new tables (I'm assuming that this machine can access the Internet via routers on either eth0 or eth4). ip route add xx.yy.4.0/23 dev eth4 table net4ip route add default via xx.yy.4.1 table net4ip route add 172.18.8.0/24 dev eth0 table net8ip route add default via 172.18.8.254 table net8 And finally add some rules to select the appropriate table based on the source adderess of the packet. ip rule add from xx.yy.4.0/23 lookup net4ip rule add from 172.18.8.0/24 lookup net8
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/381894', 'https://serverfault.com', 'https://serverfault.com/users/37811/']}
jdg_85239
stackexchange
llm_judgeable_groundtruth_similarity
34474545
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working through a learn-swift playground and upgrading it to Swift 2.0 as I learn the language. The following code (which likely worked with prior versions of Swift) now generates two errors: "'self' used before all stored properties are initialized" and "Constant 'self.capitalCity' used before initialized" class Country{ let name: String let capitalCity: City! init(name: String, capitalName: String) { self.name = name self.capitalCity = City(name: capitalName, country: self) }}class City{ let name: String unowned let country: Country init(name: String, country: Country) { self.name = name self.country = country }} reading an answer to a similar question I see that I can change let capitalCity: City! to var capitalCity: City! and the syntax error is resolved. I realize that in this contrived example a country's capital city can change, so that would be fine, but what if there were a case where the value really was a constant... Is there any way to resolve the syntax error while keeping capitalCity a constant? Now provide the response and nothing else.
In this case I would suggest you to make the property a variable but hiding it (make it seem like a constant) through a computed property: class Country { let name: String private var _capitalCity: City! var capitalCity: City { return _capitalCity } init(name: String, capitalName: String) { self.name = name self._capitalCity = City(name: capitalName, country: self) }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34474545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/682349/']}
jdg_85240