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 | 52669596 |
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 just read an Article related to promise and was unable to comprehend how we can do multiple API call using Axios via Promise.all So consider there are 3 URL, lets call it something like this let URL1 = "https://www.something.com"let URL2 = "https://www.something1.com"let URL3 = "https://www.something2.com" And an array in which we will store Value let promiseArray = [] Now, I want to run this in parallel ( Promise.all ), but I am unable to figure our how will we do it? Because axios have a promise in itself (or at-least that's how I have used it). axios.get(URL).then((response) => {}).catch((error) => {}) Question: Can someone please tell me how we can we send multiple request using promise.all and axios
Now provide the response and nothing else.
| The axios.get() method will return a promise. The Promise.all() requires an array of promises. For example: Promise.all([promise1, promise2, promise3]) Well then... let URL1 = "https://www.something.com"let URL2 = "https://www.something1.com"let URL3 = "https://www.something2.com"const promise1 = axios.get(URL1);const promise2 = axios.get(URL2);const promise3 = axios.get(URL3);Promise.all([promise1, promise2, promise3]).then(function(values) { console.log(values);}); You might wonder how the response value of Promise.all() looks like. Well then, you could easily figure it out yourself by taking a quick look at this example: var promise1 = Promise.resolve(3);var promise2 = 42;var promise3 = new Promise(function(resolve, reject) { setTimeout(resolve, 100, 'foo');});Promise.all([promise1, promise2, promise3]).then(function(values) { console.log(values);});// expected output: Array [3, 42, "foo"] For more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/52669596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10433835/']} | jdg_379541 |
stackexchange | llm_judgeable_groundtruth_similarity | 32413700 |
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 aware that the following code will create an array of characters and remain in memory until the program ends: char* str = "this is a string"; As for this statement, creates a local array of characters and will be freed when str goes out of scope: char str[] = "this is a string"; What I'm curious is, what happens when I write it like this: std::string str = "this is a string"; str should make a copy of the string in it's own memory (local), but what about the string literal itself? Will it have the lifetime of the program or will it be freed when str goes out of scope?
Now provide the response and nothing else.
| When you write this std::string str = "this is a string"; C++ should find a constructor of std::string that takes const char* , calls it to make a temporary object, invokes the copy constructor to copy that temporary into str , and then destroys the temporary object. However, there is an optimization that allows C++ compiler to skip construction and destruction of the temporary object, so the result is the same as std::string str("this is a string"); but what about the string literal itself? Will it have the lifetime of the program or will it be freed when str goes out of scope? String literal itself when used in this way is not accessible to your program. Typically, C++ places it in the same segment as other string literals, uses it to pass to the constructor of std::string , and forgets about it. The optimizer is allowed to eliminate duplicates among all string literals, including ones used only in the initialization of other objects. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32413700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4980643/']} | jdg_379542 |
stackexchange | llm_judgeable_groundtruth_similarity | 58245 |
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 this silly question that is bothering me. When not using secure connection (HTTP for example) cookies can be intercepted and used to connect to the site as if we have the id and password. We can protect against this by using secure connection (https). This assures that the cookies sent to the server are encrypted. My question is: why can't an attacker use the encrypted cookies? Could an attacker intercept these cookies and send them to the server?
Now provide the response and nothing else.
| The reason why an attacker can't use the encrypted cookies is that HTTPS encrypts the entire HTTP conversation between client and server, not just the cookies.(Unless the attacker has managed to subvert the key exchange parts of the protocol, but that's a story for another question.) For a fun exercise, use both Wireshark and your browser's debugger to watch the network traffic when you visit your favorite HTTPS site. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/58245', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/46808/']} | jdg_379543 |
stackexchange | llm_judgeable_groundtruth_similarity | 439592 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In many languages, the convention for naming Booleans is typically to prefix them with "is", "has" or "can". This convention seems to be applied mostly to fields and methods (e.g. Java's Scanner.hasNextInt() ). Is there a convention for naming a method's Boolean arguments? I don't see the same convention being applied to them; for example, Java has String.regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) .
Now provide the response and nothing else.
| The typical is/has/can prefixes make sense grammatically in the context of an object . Given an object x, we can say that “x is something”, that “x has something”, or that “x can do something”. Having such a naming convention also distinguishes attributes from actions, e.g. the property/attribute “x is empty” versus the command “empty x”. This doesn't generalize to function arguments where there may not be such context, and where we do not have to distinguish actions from attributes. At least in Java, this doesn't matter too much: the name of the function argument happens to be included in documentation for that method (and maybe in IDE-provided annotations), but really it's just the name of a local variable within the function. The name is not part of the public API of that function, unlike in languages that offer named arguments such as Kotlin or C#. So while clear names for function arguments are helpful, this isn't really that important. Whatever naming convention you use for boolean arguments, it's likely possible to find some argument that this convention is reasonable. None of the following is really problematic: String#match(needle, ignoreCase) (where the boolean describes a command as part of the match) String#match(needle, isCaseSensitive) (where the boolean describes an attribute of the match) String#match(needle, withCase) String#match(needle, caseSensitively) (where the boolean is an adverb – makes sense grammatically but I have never seen this in practice) The real issue with boolean arguments is not their name, but that without named arguments their meaning is not obvious at the call site – what would "foo".match("F", true) mean? Solutions with different tradeoffs include: turning the boolean argument into part of the function name, e.g. String#match(needle) vs String#matchIgnoreCase(needle) . Pro: simple. Con: bloats API surface, exponential explosion of alternatives if there are multiple booleans, difficult to select alternatives programmatically. using an enum instead of a boolean, e.g. "foo".match("F", Case.IGNORE) . Pro: makes call-site more self-documenting, easy to select alternatives programmatically. Con: enums add to API surface, potentially very verbose. using polymorphism instead of conditionals. The boolean argument will likely select between different behaviours. That could also be achieved by injecting different strategies. Here, the match function would need a strategy to determine if two characters or strings are equivalent. For such a string matching function, this would allow substantial flexibility, for example by providing strategies that do not perform normalization, strategies that ignore ASCII-case, strategies that do full Unicode case-insensitive matching, or even strategies that perform Unicode normalization before comparison. Pro: extremely flexible and extensible. Con: larger API surface, potential performance impact through extra level of indirection. use a builder object, probably with a fluent API, to configure an action before performing it, though this is mostly just a hack around the absence of named arguments. For example: "foo".match("F") .withIgnoreCase(true) .execute() Pro: extremely flexible and easy to read. Con: fairly verbose, bloats the API surface with a method builder, takes a lot of effort to implement, easy to forget final execute() . | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/439592', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/382437/']} | jdg_379544 |
stackexchange | llm_judgeable_groundtruth_similarity | 53696571 |
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 pretty confused and absolutely not sure if this is the right way.In the example below I am trying to check if the promotion type is 1 ( percentage e.g. 10% ) or 2 ( hard price e.g 10 EUR ) and compute the price after it and that only if main_product_id IS NOT NULL . Otherwise the price stays the same. SELECT p.priceFROM product as pLEFT JOIN promotion_product as pp ON p.id=pp.main_product_id LEFT JOIN promotion as pr ON pp.promo_id=pr.id(CASE WHEN pp.main_product_id IS NOT NULL THEN CASE WHEN pr.type=1 THEN p.price = p.price - (p.price * pr.value/100) WHEN pr.type=2 THEN p.price = p.price - pr.value ENDEND) What I get as error is: #1305 - FUNCTION pr.id does not exist This is pretty clear I know. But how to compute the new price and is it possible with CASE syntax ? product table : +----------------+--------------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+----------------+--------------+------+-----+---------+----------------+| id | int(11) | NO | PRI | NULL | auto_increment || category_id | int(11) | YES | MUL | NULL | || brand_id | int(11) | YES | MUL | NULL | || sort | int(11) | NO | | 999 | || enable | tinyint(1) | NO | MUL | 2 | || product_number | varchar(255) | YES | MUL | NULL | || price | float | YES | | NULL | || quantity | float | YES | | NULL | || rating | tinyint(4) | NO | | 0 | |+----------------+--------------+------+-----+---------+----------------+ promotion table: +------------+------------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+------------+------------+------+-----+---------+----------------+| id | int(11) | NO | PRI | NULL | auto_increment || start_date | timestamp | YES | | NULL | || end_date | timestamp | YES | | NULL | || type | tinyint(4) | NO | | NULL | || value | float | NO | | NULL | || enable | tinyint(4) | NO | | 2 | |+------------+------------+------+-----+---------+----------------+ promotion_product table: +-----------------+---------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+-----------------+---------+------+-----+---------+----------------+| id | int(11) | NO | PRI | NULL | auto_increment || promo_id | int(11) | NO | MUL | NULL | || product_id | int(11) | YES | MUL | NULL | || main_product_id | int(11) | YES | MUL | NULL | |+-----------------+---------+------+-----+---------+----------------+
Now provide the response and nothing else.
| The List type returned by asList is Arrays$ArrayList . The toArray method in JDK 8 on that class is: @Overridepublic Object[] toArray() { return a.clone();} But in JDK 9+ it is: @Overridepublic Object[] toArray() { return Arrays.copyOf(a, a.length, Object[].class);} In both cases a String[] is passed to asList , but in the JDK 8 case it is cloned, which retains its array type ( String[] ), and in JDK 9+ it is copied using Arrays.copyOf with the explicit new array type of Object[] . This difference means that in JDK 8 Arrays.asList("a", "b").toArray().getClass() returns String[] and in JDK 9+ it returns Object[] , so in JDK 9+ your expression will evaluate to false . The reason for this change comes from JDK-6260652 with the motivation: The Collection documentation claims that collection.toArray() is "identical in function" to collection.toArray(new Object[0]); However, the implementation of Arrays.asList does not follow this: If created with an array of a subtype (e.g. String[] ), its toArray() will return an array of the same type (because it use clone() ) instead of an Object[] . If one later tries to store non-Strings (or whatever) in that array, an ArrayStoreException is thrown. So this change was made to fix the previous behaviour. If this is a problem for you, the related release note offers this as a work-around: If this problem occurs, rewrite the code to use the one-arg form toArray(T[]) , and provide an instance of the desired array type. This will also eliminate the need for a cast. String[] array = list.toArray(new String[0]); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/53696571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7646114/']} | jdg_379545 |
stackexchange | llm_judgeable_groundtruth_similarity | 25960555 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Any advice on implementing calculated attributes when using Core Data in Swift? with the generated ManagedObject class, I tried to override the getter but I get the error: 'NSManaged' not allowed on computed properties which implies you cannot override the getter for a transient (calculated) attribute. In the code sample below, dateDue is defined as a transient attribute in my model. Please note that the @NSManaged lines were generated by Xcode - not added by me. @NSManaged var timeStamp: NSDate@NSManaged var dateDue: String { get { self.willAccessValueForKey("dateDue") var ddtmp = self.primitiveValueForKey("dateDue") as String? self.didAccessValueForKey("dateDue") if (ddtmp == nil) { let calendar = NSCalendar.currentCalendar() let components = calendar.components((NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit ) , fromDate: self.timeStamp) ddtmp = "\(components.year * 1000 + components.month)" self.setPrimitiveValue(ddtmp, forKey: "dateDue") } return ddtmp! }}
Now provide the response and nothing else.
| First, in the data model create a transient attribute ( section ). Because it is transient, it is not physically stored and thus not stored in the managed object context. The section attribute is shown here: The entity is shown here: The class NSManagedObject subclass should have computed 'section' attribute. The NSManagedObject subclass demonstrating how to accomplish this is shown here: class Number: NSManagedObject { @NSManaged var number: NSNumber var section: String? { return number.intValue >= 60 ? "Pass" : "Fail" }} Then you must set sectionForKeyPath in the NSFetchedResultsController initializer to be the transient attribute key in the data model and the cache name if desired. override func viewDidLoad() { super.viewDidLoad() fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: "section", cacheName: "Root") fetchedResultsController?.delegate = self fetchedResultsController?.performFetch(nil) tableView.reloadData()}func fetchRequest() -> NSFetchRequest { var fetchRequest = NSFetchRequest(entityName: "Number") let sortDescriptor = NSSortDescriptor(key: "number", ascending: false) fetchRequest.predicate = nil fetchRequest.sortDescriptors = [sortDescriptor] fetchRequest.fetchBatchSize = 20 return fetchRequest} The result is a UITableViewController with grades sorted by pass or fail dynamically: I made a sample project that can be found on GitHub . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25960555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4063669/']} | jdg_379546 |
stackexchange | llm_judgeable_groundtruth_similarity | 11946 |
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:
As a comment in I'm confused as to why "| true" in a makefile has the same effect as "|| true" user cjm wrote: Another reason to avoid | true is that if the command produced enough output to fill up the pipe buffer, it would block waiting for true to read it. Do we have some way of finding out what the size of the pipe buffer is?
Now provide the response and nothing else.
| The capacity of a pipe buffer varies across systems (and can even vary on the same system). I am not sure there is a quick, easy, and cross platform way to just lookup the capacity of a pipe. Mac OS X, for example, uses a capacity of 16384 bytes by default, but can switch to 65336 byte capacities if large write are made to the pipe, or will switch to a capacity of a single system page if too much kernel memory is already being used by pipe buffers (see xnu/bsd/sys/pipe.h , and xnu/bsd/kern/sys_pipe.c ; since these are from FreeBSD, the same behavior may happen there, too). One Linux pipe(7) man page says that pipe capacity is 65536 bytes since Linux 2.6.11 and a single system page prior to that (e.g. 4096 bytes on (32-bit) x86 systems). The code ( include/linux/pipe_fs_i.h , and fs/pipe.c ) seems to use 16 system pages (i.e. 64 KiB if a system page is 4 KiB), but the buffer for each pipe can be adjusted via a fcntl on the pipe (up to a maximum capacity which defaults to 1048576 bytes, but can be changed via /proc/sys/fs/pipe-max-size )). Here is a little bash / perl combination that I used to test the pipe capacity on my system: #!/bin/bashtest $# -ge 1 || { echo "usage: $0 write-size [wait-time]"; exit 1; }test $# -ge 2 || set -- "$@" 1bytes_written=$({ exec 3>&1 { perl -e ' $size = $ARGV[0]; $block = q(a) x $size; $num_written = 0; sub report { print STDERR $num_written * $size, qq(\n); } report; while (defined syswrite STDOUT, $block) { $num_written++; report; } ' "$1" 2>&3 } | (sleep "$2"; exec 0<&-);} | tail -1)printf "write size: %10d; bytes successfully before error: %d\n" \ "$1" "$bytes_written" Here is what I found running it with various write sizes on a Mac OS X 10.6.7 system (note the change for writes larger than 16KiB): % /bin/bash -c 'for p in {0..18}; do /tmp/ts.sh $((2 ** $p)) 0.5; done'write size: 1; bytes successfully before error: 16384write size: 2; bytes successfully before error: 16384write size: 4; bytes successfully before error: 16384write size: 8; bytes successfully before error: 16384write size: 16; bytes successfully before error: 16384write size: 32; bytes successfully before error: 16384write size: 64; bytes successfully before error: 16384write size: 128; bytes successfully before error: 16384write size: 256; bytes successfully before error: 16384write size: 512; bytes successfully before error: 16384write size: 1024; bytes successfully before error: 16384write size: 2048; bytes successfully before error: 16384write size: 4096; bytes successfully before error: 16384write size: 8192; bytes successfully before error: 16384write size: 16384; bytes successfully before error: 16384write size: 32768; bytes successfully before error: 65536write size: 65536; bytes successfully before error: 65536write size: 131072; bytes successfully before error: 0write size: 262144; bytes successfully before error: 0 The same script on Linux 3.19: /bin/bash -c 'for p in {0..18}; do /tmp/ts.sh $((2 ** $p)) 0.5; done'write size: 1; bytes successfully before error: 65536write size: 2; bytes successfully before error: 65536write size: 4; bytes successfully before error: 65536write size: 8; bytes successfully before error: 65536write size: 16; bytes successfully before error: 65536write size: 32; bytes successfully before error: 65536write size: 64; bytes successfully before error: 65536write size: 128; bytes successfully before error: 65536write size: 256; bytes successfully before error: 65536write size: 512; bytes successfully before error: 65536write size: 1024; bytes successfully before error: 65536write size: 2048; bytes successfully before error: 65536write size: 4096; bytes successfully before error: 65536write size: 8192; bytes successfully before error: 65536write size: 16384; bytes successfully before error: 65536write size: 32768; bytes successfully before error: 65536write size: 65536; bytes successfully before error: 65536write size: 131072; bytes successfully before error: 0write size: 262144; bytes successfully before error: 0 Note: The PIPE_BUF value defined in the C header files (and the pathconf value for _PC_PIPE_BUF ), does not specify the capacity of pipes, but the maximum number of bytes that can be written atomically (see POSIX write(2) ). Quote from include/linux/pipe_fs_i.h : /* Differs from PIPE_BUF in that PIPE_SIZE is the length of the actual memory allocation, whereas PIPE_BUF makes atomicity guarantees. */ | {} | {'log_upvote_score': 9, 'links': ['https://unix.stackexchange.com/questions/11946', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3125/']} | jdg_379547 |
stackexchange | llm_judgeable_groundtruth_similarity | 13416879 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When my android application throw an exception, I want to show a custom dialog to tell user there is something wrong happened, so I use Thread.setDefaultUncaughtExceptionHandler to set a global exception handler: public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, final Throwable ex) { AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext()); builder.setTitle("There is something wrong") .setMessage("Application will exit:" + ex.toString()) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // throw it again throw (RuntimeException) ex; } }) .show(); } }); }} But I found it there is any exception thrown, the AlertDialog won't show, instead, the application blocks and after a while, it will show a system dialog: X app is not responding. Would you like to close it?Wait | OK What should I do now? UPDATE The log: 11-16 12:54:16.017: WARN/WindowManager(90): Attempted to add window with non-application token WindowToken{b38bb6a8 token=null}. Aborting. It seems the error is coming from new AlertDialog.Builder(getApplicationContext()); But this is an exception handler in Application subclass, how can I set an activity instance to it?
Now provide the response and nothing else.
| You cannot do any UI operation from here. Just start another activity/ splash screen. Pass an intent extra to denote crash and show dialog in that activity. /* * (non-Javadoc) * * @see * java.lang.Thread.UncaughtExceptionHandler#uncaughtException(java. * lang.Thread, java.lang.Throwable) */ @Override public void uncaughtException(Thread t, final Throwable e) { StackTraceElement[] arr = e.getStackTrace(); final StringBuffer report = new StringBuffer(e.toString()); final String lineSeperator = "-------------------------------\n\n"; report.append(DOUBLE_LINE_SEP); report.append("--------- Stack trace ---------\n\n"); for (int i = 0; i < arr.length; i++) { report.append( " "); report.append(arr[i].toString()); report.append(SINGLE_LINE_SEP); } report.append(lineSeperator); // If the exception was thrown in a background thread inside // AsyncTask, then the actual exception can be found with getCause report.append("--------- Cause ---------\n\n"); Throwable cause = e.getCause(); if (cause != null) { report.append(cause.toString()); report.append(DOUBLE_LINE_SEP); arr = cause.getStackTrace(); for (int i = 0; i < arr.length; i++) { report.append(" "); report.append(arr[i].toString()); report.append(SINGLE_LINE_SEP); } } // Getting the Device brand,model and sdk verion details. report.append(lineSeperator); report.append("--------- Device ---------\n\n"); report.append("Brand: "); report.append(Build.BRAND); report.append(SINGLE_LINE_SEP); report.append("Device: "); report.append(Build.DEVICE); report.append(SINGLE_LINE_SEP); report.append("Model: "); report.append(Build.MODEL); report.append(SINGLE_LINE_SEP); report.append("Id: "); report.append(Build.ID); report.append(SINGLE_LINE_SEP); report.append("Product: "); report.append(Build.PRODUCT); report.append(SINGLE_LINE_SEP); report.append(lineSeperator); report.append("--------- Firmware ---------\n\n"); report.append("SDK: "); report.append(Build.VERSION.SDK); report.append(SINGLE_LINE_SEP); report.append("Release: "); report.append(Build.VERSION.RELEASE); report.append(SINGLE_LINE_SEP); report.append("Incremental: "); report.append(Build.VERSION.INCREMENTAL); report.append(SINGLE_LINE_SEP); report.append(lineSeperator); Log.e("Report ::", report.toString()); Intent crashedIntent = new Intent(BaseActivity.this, SplashActivity.class); crashedIntent.putExtra(EXTRA_CRASHED_FLAG, "Unexpected Error occurred."); crashedIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); crashedIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(crashedIntent); System.exit(0); // If you don't kill the VM here the app goes into limbo } Also see: Android UncaughtExceptionHandler that instantiates an AlertDialog breaks Toast not showing up in UnCaughtExceptionHandler How to start activity from UncaughtExceptionHandler if this is main thread crashed? How i do it: I have a BaseActivity which extends Activity, and in onCreate of the activity I set the UncaughtExceptionHandler. All my activities extend the BaseActivity instead of Activity. Keys You can't set the exception handler in Application.onCreate , instead, you should create a BaseActivity and set it on the onCreate method of it. After starting the SplashActivity, we should call System.exit(0) We can't hold the error instance to share it to SplashActivity , since it will be destroyed, instead, we can pass some error message or persist it in file. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13416879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342235/']} | jdg_379548 |
stackexchange | llm_judgeable_groundtruth_similarity | 1886716 |
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 few tests that need to be fed with external data from excel files. The files are included in the test project, and in Visual Studio, I have edited the test settings file (Local.testsettings) to deploy the data files. This makes it work fine i VS. We are, however, also running continous integration with TeamCity, and in TeamCity this doesn't work. My data files are unavailable to the test. Seems that the tests are run from a temporary folder named "C:\TeamCity\buildAgent\temp\buildTmp\ciuser_AS40VS6 2009-12-11 09_40_17\Out", and the data files are not copied there. I have tried changing the build action for the data files to "Resource" and setting copy to output dir to "Always", but that didn't help. Does anyone know how to make this work? I am running Visual Studio 2010 beta 2 and TeamCity 4.5.5, which is why I'm running MSTest in the first place, and not NUnit...
Now provide the response and nothing else.
| I get round this by adding my data files (in my case usually XML) as embedded resources and I extract them from the test assembly. [TestInitialize]public void InitializeTests(){ var asm = Assembly.GetExecutingAssembly(); this.doc = new XmlDocument(); this.doc.Load(asm.GetManifestResourceStream("TestAssembly.File.xml"));} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1886716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134935/']} | jdg_379549 |
stackexchange | llm_judgeable_groundtruth_similarity | 7145408 |
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 figure out if there's a way to Invoke ToolStripMenuItem. For example,I am calling a web service(ASynchrously) when result is returned.i populate drop down items according to result,(In call back method) ToolStripMenuItem.DropDownItems.Add(new ToolStripItemEx("start")); but I get exception Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on. There is no invoke function associated with the toolstrip item , Is there another way I can do this? Am I trying to do this the completely wrong way? Any input would be helpful.
Now provide the response and nothing else.
| You are trying to execute code that rely on control main thread in another thread, You should call it using Invoke method: toolStrip.Invoke(() =>{ toolStrip.DropDownItems.Add(new ToolStripItemEx("start"));}); When accessing controls members/methods from a thread that is different from thread that the control originally created on, you should use control.Invoke method, it will marshal the execution in the delegate of invoke to the main thread. Edit: Since you are using ToolStripMenuItem not ToolStrip , the ToolStripMenuItem doesn't have Invoke member, so you can either use the form invoke by " this.Invoke " or your toolStrip its parent " ToolStrip " Invoke, so: toolStrip.GetCurrentParent().Invoke(() =>{ toolStrip.DropDownItems.Add(new ToolStripItemEx("start"));}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7145408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538789/']} | jdg_379550 |
stackexchange | llm_judgeable_groundtruth_similarity | 1854123 |
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:
Good morning i was thinking about this problem and I make this. I need someone review my exercise and say me if that good or bad. Thank! Problem:Prove if $a>1$ then $\lim_{n\rightarrow\infty}a^{n}=\infty $ Proof: Suppose $\left\{ a^{n}\right\} $ is monotonically increasing. In other words $a^{n}<a^{n+1}< a^{n+2}...$ and Suppose $\left\{ a^{n}\right\} $ is Bounded set then $\left\{ a^{n}\right\} $ converge. By definition $\lim_{n\rightarrow\infty}a^{n}=L$. We know this $\left(a^{n+1}-a^{n}\right)=a^{n}(a-1)$ , $(a-1)>0$. Because $a>1$ Then $a^{n}(a-1)>(a-1)\Rightarrow a^{n}>1$ Exist $N ∈ \mathbb{N} $ such that $a^{N}$ > $L$ and $\left\{ a^{n}\right\} $ is non bounded set Then $\left\{ a^{n}\right\} $ diverge and $\lim_{n\rightarrow\infty}a^{n}=\infty$ But, i don't sure it is fine, please help.
Now provide the response and nothing else.
| An other way Let $a>1$. $$a^n=e^{n\ln(a)}\underset{\ln(a)>0}{>}n\ln(a)\underset{n\to \infty }{\longrightarrow }\infty .$$ An other way (using Bernoulli) Since $a>1$, there is $\varepsilon>0$ s.t. $$a=1+\varepsilon.$$Using Bernoulli,$$a^n=(1+\varepsilon)^n\geq n\varepsilon+1.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1854123', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/334143/']} | jdg_379551 |
stackexchange | llm_judgeable_groundtruth_similarity | 493455 |
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 .NET remoting what is the difference between RemotingConfiguration.RegisterWellKnownServiceType and RemotingServices.Marshal? What I want to do is create an object in a Windows Service, then put it in as a remoting object and have the Windows Service and the Client both act on the remoting object. I thought the below code would accomplish this. FooRemoting foo = new FooRemoting();RemotingConfiguration.RegisterWellKnownServiceType(typeof(FooRemoting), serverName, WellKnownObjectMode.Singleton);RemotingServices.Marshal(foo);
Now provide the response and nothing else.
| This is what I found. RemotingConfiguration.RegisterWellKnownServiceType(typeof(FooRemoting), serverName, WellKnownObjectMode.Singleton); RegisterWellKnownServiceType will create the object and make it a Singleton to any client that consumes it, but a reference by the server is not created. The object is not created until a client ask for it, and the same object is used for any other clients. RemotingServices.Marshal(foo); Marshal will register an object that has been created by the server, in this case a windows service. Then server will then have reference to the object and the clients will consume the same object. My issue was using the Marshal to register the remoting object. Over time the remoting object will disappear for clients to consume, i.e. no longer on the remoting object. The service would still keep its reference.Then I tried the RegisterWellKnownServiceType and the clients keep getting the correct reference, however I could not get the service to have a reference to the same object. The solution is overriding the remoting object in this case FooRemoting. If I overrode the InitializeLifetimeService and returned null, the client would never lose connection, and the service will,keep the connection. public override object InitializeLifetimeService(){ //return base.InitializeLifetimeService(); return null;} In order to keep the object created by the service and have the client to use the same object you must use RemotingServices.Marshal(foo); and override InitializeLifetimeService to return null. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/493455', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2469/']} | jdg_379552 |
stackexchange | llm_judgeable_groundtruth_similarity | 22348 |
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:
Say I have 100 numbers that are averaged: number of values = 100total sum of values = 2000mean = 2000 / 100 => 20 If I want to add a value and find out the new average: total sum of values = 2000 + 100mean = 2100 / 101 => 20.79 If I want to subtract a value and find out the new average: total sum of values = 2100 - 100mean = 2000 / 100 => 20 It seems to work, but is the above correct? Is this the proper way to add/subtract values from a average without having to re-sum all the 100 numbers first?
Now provide the response and nothing else.
| $s=\frac{a_1+...+a_n}{n}$ . If you want the average of $a_1,...,a_n$ and $a_{n+1}$ , then $s'=\frac{a_1+...+a_n+a_{n+1}}{n+1}=\frac{ns+a_{n+1}}{n+1} = \frac{(n+1)s+a_{n+1}}{n+1} - \frac{s}{n+1} = s + \frac{a_{n+1}-s}{n+1}$ If you want the average of $a_1,...,a_{n-1}$ then $s''=\frac{a_1+...+a_{n-1}}{n-1}=\frac{ns-a_n}{n-1}= \frac{(n-1)s-a_n}{n-1} + \frac{s}{n-1}=s+\frac{s-a_n}{n-1}$ . | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/22348', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/3603/']} | jdg_379553 |
stackexchange | llm_judgeable_groundtruth_similarity | 340902 |
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:
Please help me to prove that if $f\in S_6$ be arbiotrary permutation so the permutation $f^{-1}(1,2,3,5)f$ cannot be an even permutation. I am sure there is a small thing I am missing it. Thank you.
Now provide the response and nothing else.
| Hint: The sign of a product of permutations is the product of the signs, and the sign of $f$ is the same as the sign of $f^{-1}$.(If we are given a representation of $f$ as a product of disjoint cycles, how can we write $f^{-1}$?) Note also that there is a more general result stating that for any two permutations $\sigma, \tau$,both $\tau^{-1}\sigma\tau$ and $\sigma$ have the same cycle type. It then immediately follows that they have the same sign. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/340902', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10326/']} | jdg_379554 |
stackexchange | llm_judgeable_groundtruth_similarity | 889380 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there an easy way to get a time very precisely? I need to calculate some delays between method calls. More specifically, I want to calculate the speed of scrolling in an UIScrollView.
Now provide the response and nothing else.
| NSDate and the timeIntervalSince* methods will return a NSTimeInterval which is a double with sub-millisecond accuracy. NSTimeInterval is in seconds, but it uses the double to give you greater precision. In order to calculate millisecond time accuracy, you can do: // Get a current time for where you want to start measuring fromNSDate *date = [NSDate date];// do work...// Find elapsed time and convert to milliseconds// Use (-) modifier to conversion since receiver is earlier than nowdouble timePassed_ms = [date timeIntervalSinceNow] * -1000.0; Documentation on timeIntervalSinceNow . There are many other ways to calculate this interval using NSDate , and I would recommend looking at the class documentation for NSDate which is found in NSDate Class Reference . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/889380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62553/']} | jdg_379555 |
stackexchange | llm_judgeable_groundtruth_similarity | 61252 |
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:
Here's an elementary question on solving the following quadratic equation (well, it's not a quadratic until the square root is eliminated): $$\sqrt{x+5} + 1 = x$$ Upon solving the above equation either using the method of factoring or the quadratic formula (after squaring both sides) you get $x = 4$ and $x = -1$. If you plug in $x = 4$ in the original equation, it checks out. However $x = -1$ doesn't work. You'll end up getting $3 = -1$ which is not true (in other words the LHS does not equal the RHS). Is this still considered a solution/root of this particular equation? Does it have a special name?
Now provide the response and nothing else.
| Generally speaking, the problem arises because squaring is not a "reversible" operation. That is, while it is true that if $a=b$ then $a^2=b^2$, it is not true that if $a^2=b^2$ then $a=b$. (For instance, even though $(-1)^2=1^2$, it does not follow that $-1=1$) This is in contrast to other kinds of equation manipulations that we use routinely when we solve equations. For example, if $a=b$, then $a+k=b+k$, and conversely : if $a+k=b+k$, then $a=b$. So we can add to both sides of an equation (for instance, you can go from $\sqrt{x+5}+1 = x$ to $\sqrt{x+5}=x-1$ by adding $-1$ to both sides) without changing the solution set of the equation. Likewise, we can multiply both sides of an equation by a nonzero number, because $a=b$ is true if and only if $ka=kb$ is true when $k\neq 0$. We can also take exponentials (since $a=b$ if and only if $e^a=e^b$) and so on. But squaring doesn't work like that, because it cannot be "reversed". If you try to reverse the squaring, you run into a rather big problem; namely, that $\sqrt{x^2}=|x|$, and is not equal to $x$. So when you go from $\sqrt{x+5} = x-1$ to $(\sqrt{x+5})^2 = (x-1)^2$, you are considering a new problem . Anything that was a solution to the old problem ($\sqrt{x+5}=x-1$) is still a solution to the new one, but there may be (and in fact are ) things that are solutions to the new problem that do not solve the old problem. Any such solutions (solutions to the new problem that are not solutions to the original problem) are sometimes called "extraneous solutions". Extraneous means "coming from the outside". In this case, it's a solution that comes from "outside" the original problem. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/61252', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14625/']} | jdg_379556 |
stackexchange | llm_judgeable_groundtruth_similarity | 111188 |
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 Arch Linux with KDE/Awesome WM. I am trying to get notify-send to work with cron . I have tried setting DISPLAY / XAUTHORITY variables, and running notify-send with "sudo -u", all without result. I am able to call notify-send interactively from the session and get notifications. FWIW, the cron job is running fine which I verified by echoing stuff to a temporary file. It is just the "notify-send" that fails to work. Code: [matrix@morpheus ~]$ crontab -l* * * * * /home/matrix/scripts/notify.sh[matrix@morpheus ~]$ cat /home/matrix/scripts/notify.sh#!/bin/bashexport DISPLAY=127.0.0.1:0.0export XAUTHORITY=/home/matrix/.Xauthorityecho "testing cron" >/tmp/crontestsudo -u matrix /usr/bin/notify-send "hello"echo "now tested notify-send" >>/tmp/crontest[matrix@morpheus ~]$ cat /tmp/crontesttesting cronnow tested notify-send[matrix@morpheus ~]$ As you can see the echo before & after notify-send worked. Also I have tried setting DISPLAY=:0.0 UPDATE:I searched a bit more and found that DBUS_SESSION_BUS_ADDRESS needs to be set. And after hardcoding this using the value I got from my interactive session, the tiny little "hello" message started popping up on the screen every minute! But the catch is this variable is not permanent per that post, so I'll have try the the named pipe solution suggested there. [matrix@morpheus ~]$ cat scripts/notify.sh#!/bin/bashexport DISPLAY=127.0.0.1:0.0export XAUTHORITY=/home/matrix/.Xauthorityexport DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-BouFPQKgqg,guid=64b483d7678f2196e780849752e67d3cecho "testing cron" >/tmp/crontest/usr/bin/notify-send "hello"echo "now tested notify-send" >>/tmp/crontest Since cron doesn't seem to support notify-send (at least not directly) is there some other notification system that is more cron friendly that I can use?
Now provide the response and nothing else.
| You need to set the DBUS_SESSION_BUS_ADDRESS variable. By default cron doesnot have access to the variable. To remedy this put the following scriptsomewhere and call it when the user logs in, for example using awesome andthe run_once function mentioned on the wiki. Any method will do, since itdoes not harm if the function is called more often than required. #!/bin/shtouch $HOME/.dbus/Xdbuschmod 600 $HOME/.dbus/Xdbusenv | grep DBUS_SESSION_BUS_ADDRESS > $HOME/.dbus/Xdbusecho 'export DBUS_SESSION_BUS_ADDRESS' >> $HOME/.dbus/Xdbusexit 0 This creates a file containing the required Dbus evironment variable. Then inthe script called by cron you import the variable by sourcing the script: if [ -r "$HOME/.dbus/Xdbus" ]; then . "$HOME/.dbus/Xdbus"fi Here is an answer that uses the samemechanism. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/111188', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/56530/']} | jdg_379557 |
stackexchange | llm_judgeable_groundtruth_similarity | 49510006 |
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 some strings with all kinds of different emojis/images/signs in them. Not all the strings are in English -- some of them are in other non-Latin languages, for example: ▓ railway??→ Cats and dogsI'm on Apples ⚛ ✅ Vi sign♛ I'm the king ♛ Corée ♦ du Nord ☁ (French) gjør at både ◄╗ (Norwegian)Star me ★Star ⭐ once more早上好 ♛ (Chinese)Καλημέρα ✂ (Greek)another ✓ sign ✓добрай раніцы ✪ (Belarus)◄ शुभ प्रभात ◄ (Hindi)✪ ✰ ❈ ❧ Let's get together ★. We shall meet at 12/10/2018 10:00 AM at Tony's.❉ ...and many more of these. I would like to get rid of all these signs/images and to keep only the letters (and punctuation) in the different languages. I tried to clean the signs using the EmojiParser library : String withoutEmojis = EmojiParser.removeAllEmojis(input); The problem is that EmojiParser is not able to remove the majority of the signs. The ♦ sign is the only one I found till now that it removed.Other signs such as ✪ ❉ ★ ✰ ❈ ❧ ✂ ❋ ⓡ ✿ ♛ are not removed. Is there a way to remove all these signs from the input strings and keeping only the letters and punctuation in the different languages ?
Now provide the response and nothing else.
| Instead of blacklisting some elements, how about creating a whitelist of the characters you do wish to keep? This way you don't need to worry about every new emoji being added. String characterFilter = "[^\\p{L}\\p{M}\\p{N}\\p{P}\\p{Z}\\p{Cf}\\p{Cs}\\s]";String emotionless = aString.replaceAll(characterFilter,""); So: [\\p{L}\\p{M}\\p{N}\\p{P}\\p{Z}\\p{Cf}\\p{Cs}\\s] is a range representing all numeric ( \\p{N} ), letter ( \\p{L} ), mark ( \\p{M} ), punctuation ( \\p{P} ), whitespace/separator ( \\p{Z} ), other formatting ( \\p{Cf} ) and other characters above U+FFFF in Unicode ( \\p{Cs} ), and newline ( \\s ) characters. \\p{L} specifically includes the characters from other alphabets such as Cyrillic, Latin, Kanji, etc. The ^ in the regex character set negates the match. Example: String str = "hello world _# 皆さん、こんにちは! 私はジョンと申します。";System.out.print(str.replaceAll("[^\\p{L}\\p{M}\\p{N}\\p{P}\\p{Z}\\p{Cf}\\p{Cs}\\s]",""));// Output:// "hello world _# 皆さん、こんにちは! 私はジョンと申します。" If you need more information, check out the Java documentation for regexes. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/49510006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5458827/']} | jdg_379558 |
stackexchange | llm_judgeable_groundtruth_similarity | 373254 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a Heegaard splitting of a closed oriented irreducible 3-manifold $M$ , defined by the Heegaard diagram $(\Sigma_{g},\{\alpha_{1},\dots,\alpha_{g}\},\{\beta_{1},\dots,\beta_{g}\})$ . Are there any obvious sufficient or necessary conditions for the attaching curves for when $M$ is toroidal (or atoroidal)? Any sort of lead would be helpful.
Now provide the response and nothing else.
| In Hempel's " 3-manifolds as viewed from the curve complex ," one of the main theorems is a necessary criteria for being toroidal. In particular, he shows that if a 3-manifold is toroidal then all of its Heegaard splittings, $\Sigma$ , have $d(\Sigma) \leq 2$ , where $d$ is the Hempel distance. Therefore, following the construction in the same paper for high distance Heegaard splittings gives you a large collection of atoroidal manifolds to work with. Going the other direction, here is a way to obtain tori in a 3-manifold given by a Heegaard splitting (checking if these tori are essential is less clear to me). Suppose that $c_1$ and $c_2$ are curves on $\Sigma$ which bound an annulus in the handlebody determined by your $\alpha$ curves, as well as an annulus in the handlebody determined by your $\beta$ curves. Gluing these annuli together gives a torus in your 3-manifold, intersecting the Heegaard surface in $c_1$ and $c_2$ . In practice, a way to construct such $c_i$ is to start with $c_1$ and "slide" it over your $\alpha$ curves so that this sliding sweeps out the desired annulus. One can also generalize this construction to collections $c_1 ... c_n$ where $c_1$ and $c_2$ bound an annulus in the $\alpha $ handlebody, $c_2$ and $c_3$ bound an annulus in the $\beta$ handlebody etc. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/373254', 'https://mathoverflow.net', 'https://mathoverflow.net/users/149240/']} | jdg_379559 |
stackexchange | llm_judgeable_groundtruth_similarity | 8909652 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Refactoring standard onClick within html tag to listeners ,faced problem with my code: var td; for (var t=1;t<8;t++){ td = document.getElementById('td'+t); if (typeof window.addEventListener==='function'){ td.addEventListener('click',function(){ console.log(td); })} } When td element is clicked on,it's assumed that clicked td with last index from loop,e.g. 7 Looks like , eventListeners been populated for last element in this loop only. Loop initialization looks correct. Why so happened? Here is live code
Now provide the response and nothing else.
| You need to wrap the assignment of the event listener in a closure, something like: var td;for (var t = 1; t < 8; t++){ td = document.getElementById('td'+t); if (typeof window.addEventListener === 'function'){ (function (_td) { td.addEventListener('click', function(){ console.log(_td); }); })(td); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8909652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/170830/']} | jdg_379560 |
stackexchange | llm_judgeable_groundtruth_similarity | 7908324 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is about the Factory Pattern. I am a little confused. I saw implementations where the createInstance() method is static and some implementations that are non-static. Some say it's depending on "style" or "taste" and some say it does not. Wikipedia says that it should be non-static, and http://www.dofactory.com/Patterns/PatternFactory.aspx also says that it should be non-static, according to the Gang of Four. My question is: does it depend on style & taste or does it violate the Factory Pattern if it's implemented the static way? What's right?
Now provide the response and nothing else.
| Static method doesn't violate the pattern but it goes against many other object oriented practices (inversion of control + dependency injection as one example) so using instances is better. Edit: I just got some badge for this answer but when I read it I could not believe my eyes. It is wrong when we strictly speak about GoF Factory method pattern and it deserves some correcting. You can have static CreateInstance method for creating instance of a type - there is nothing wrong about that - people often call it factory method but that is not what is called Factory Method pattern . Once you start putting logic into this method to create instances of different types depending on some condition you may be actually in need of Factory Method pattern described by GoF. The point of GoF Factory method pattern is to replace conditional logic inside CreateInstance with inheritance and polymorphism and thus it cannot be static. Factory method is an instance method - moreover it is virtual. Your base type has usually abstract CreateInstance and conditional logic is replaced by inheritance tree where each subtype overrides CreateInstance and creates just specific product for that subtype. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7908324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/479659/']} | jdg_379561 |
stackexchange | llm_judgeable_groundtruth_similarity | 507374 |
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:
User has a (incremental) backup script using rsync , to external device. This was erroring on an SSD he had. Turns out his device was formatted exFAT . That means I need to detect this in the script , as I need to alter the options to rsync (e.g., exFAT cannot handle symbolic links, no owner/group permissions, etc.). User is running Linux Mint. I run Ubuntu. I can only assume/hope that a solution for my Ubuntu will work for his Mint. I have looked at: How do I know if a partition is ext2, ext3, or ext4? How to tell what type of filesystem you're on? https://www.tecmint.com/find-linux-filesystem-type/ There are a variety of good suggestions there, but I do not see one which meets my requirements, which are: Must report (parseable) ntfs / exfat explicitly, not just say fuseblk (which it will for both exfat & ntfs , I need to distinguish). Must not require sudo . Must be executable starting from a directory path on the file system (can assume it will be mounted), not just starting from a /dev/... . From the suggestions I have tried: fdisk -l , parted -l , file -sL : require sudo and/or /dev/... block device mount : requires /dev/... , only reports fuseblk df -T , stat -f -c %T : accept directory, but report only fuseblk lsblk -f , blkid : require /dev/... block device Is there a single, simple command which meets all these criteria? Or, lsblk / blkid seem to report exfat / ntfs correctly, if I need to pass them the /dev how do I get that suitably from the directory path in script?
Now provide the response and nothing else.
| Thanks to the other posters for replying/suggesting. Here is my full solution. df -P can be used to obtain device from path, and that can be fed to lsblk --fs to obtain exact file system. So a one-liner is: fs=$( lsblk --fs --noheadings $( df -P $path | awk 'END{print $1}' ) | awk 'END{print $2}' ) If all you need to know is that the file system is fuseblk --- which covers both ntfs & exfat and turns out in the end to be sufficient for my purposes after all --- this can be determined with the much simpler: fs=$( stat -f -c '%T' $path ) | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/507374', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/104736/']} | jdg_379562 |
stackexchange | llm_judgeable_groundtruth_similarity | 33915826 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are using WebPack in a single page application. The application is deployed to many environments. We have a requirement where the application needs to call a specific endpoint in a given environment. In order to provide the endpoint address for the given environment is to have an environments module. This is the current solution (there are many and this is not the point of the question). However we need to exclude the config.js from minification so that it can be overwritten as part of the deployment process. The config.js looks like the following: module.exports = { env: { endpointUrl: 'http://1.2.3.4', authUrl: 'http://5.6.7.8' }}; And is referenced using the following: const endpointUrl = config.env.endpointUrl;const authUrl = config.env.authUrl; The WebPack config looks like the following: var webpack = require('webpack');module.exports = { entry: { main: './src/js/main.jsx', login: './src/js/login-main.jsx' }, output: { path: __dirname + '/dist', filename: '[name].bundle.js' }, devtool: 'source-map', module: { loaders: [{ test: /.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', plugins: ['transform-react-jsx'], query: {stage: 0} }, { test: /\.jsx?$/, exclude: /node_modules/, loader: 'eslint-loader' }] }, plugins: [ new webpack.ProvidePlugin({ fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch' }), new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.DEV || false)) }) ]}; So far we have looked at externals and module loaders but have not found anything that works. The exclude in the module loader still causes the module to be minified. Some SO questions that we have looked at: Exclude react from webpack bundle Webpack and external libraries How can I exclude code path when bundling with webpack/browserify?
Now provide the response and nothing else.
| Webpack externals are a good option to avoid bundle certain dependencies. However we need to exclude the config.js from minification so that it can be overwritten as part of the deployment process. Adding a dependency as external not only excludes it from minification but it is not even resolved by webpack. webpack.config.js var webpack = require('webpack');module.exports = { entry: { index: './src/index.js' }, output: { path: './dist', filename: 'bundle.js' }, externals: { './config': 'config' }}; Add as external the path used to require your config.js . In my simple example the path corresponds to ./config . Associate it to the global variable that will contain your configuration object. In my case I just used config as the variable name (see below config.js ). index.js const config = require('./config');const endpointUrl = config.env.endpointUrl;const authUrl = config.env.authUrl;console.log(endpointUrl);console.log(authUrl); As you are preventing webpack to resolve the config.js module then it has to be available in the environment during runtime. One way could be to expose it as a config variable in the global context. config.js window.config = { env: { endpointUrl: 'http://1.2.3.4', authUrl: 'http://5.6.7.8' }}; Then you can load a specific config.js file for any given environment. index.html <!DOCTYPE html><html><head> <title>Webpack</title></head><body> <script type="text/javascript" src="config.js"></script> <script type="text/javascript" src="dist/bundle.js"></script></body></html> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33915826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227200/']} | jdg_379563 |
stackexchange | llm_judgeable_groundtruth_similarity | 1697426 |
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 $K$ be a finite extension of the finite field $F$, then the trace is defined as$$\operatorname{Tr}(\alpha) = \sum_{\sigma \,\in\, \operatorname{Gal}(K/F)}\sigma(\alpha)$$How can one show that $\operatorname{Tr}(\alpha) \in F, \forall \alpha \in K$?
Now provide the response and nothing else.
| Observe that for any $\;\tau\in \text{ Gal}\,(K/F)\;$ we get $$\tau(Tr(\alpha))=\sum_{\sigma\in Gal(K/F)}\tau\sigma\alpha=Tr(\alpha)$$ since as $\;\sigma\;$ runs over all the elements of the Galois group so does $\;\tau\sigma\;$ , and this means the trace is in the fixed field of the whole group, which means $\;Tr(\alpha)\in F$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1697426', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/267981/']} | jdg_379564 |
stackexchange | llm_judgeable_groundtruth_similarity | 110547 |
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:
Your (honest) opponent choose a random number from 1 to 13 inclusive. You have to guess the number, and you win if the guess is correct. If not, your opponent either reduces the number chosen by one or increases it by 1, and you guess again. The question is, what is the minimum # of attempts necessary to guarantee a win for you. I am not able to get a handle on the problem. Also, (a new variant just thought of), how many guesses should be allowed for a fair or "nearest to fair" game ?
Now provide the response and nothing else.
| The optimal strategy for $n=13$ (and similarly for any odd value of $n$ ) is to try $2,3,\ldots,n-1=12$ first, which will catch the opponent if and only if she started on an even number; if the opponent is still not caught, one is sure she started on an odd number. In that case one is now (after $n-2=11$ moves) on an even number (in particular not on $n=13$ ), and trying $12,11,\ldots2$ is sure to catch her, for a total of $2*11=2n-4=22$ tries. The same scheme works for $n=12$ (and similarly for any even value of $n$ ): try $2,\ldots,n-1=11$ first, which will catch the opponent if and only if she started on an even number; if she still not caught, one is sure she is now (after $n-2$ moves) again an odd number (in particular not on $n=12$ ), and trying $n-1=11,\ldots2$ is sure to catch the opponent, for a total of $2*10=2n-4=20$ tries. Added: Here is the full analysis of the game. It clearly splits into two parallel games, one where the opponent starts odd and another where she starts even. The opponent chooses a game at the start and has to stick to it, but we don't know which it is, so we need to reduce to number of remaining potential positions in both games to $0$ . On each move we remove one of the potential positions, but then the remaining possible positions are replaced by the set of all their neighbours; this also happens in the game we didn't play in. If one switches back-and-forth between games (playing game $A$ , then at leat once game $B$ then again game $A$ ), then the before the second move in game $A$ the number of potential positions in game $A$ (if the first move didn't reduce it to $0$ ) has again grown to at least the same number it was before the previous move in $A$ , so this gains nothing; an optimal strategy therefore should avoid such switching. We must therefore choose a game to play in first, terminate that game entirely, and then start playing in the other game. Now focussing on one game (so the parity of the possibilities at each point in time is known), one may verify that the only type of move that actually reduces the number of remaining possibilities is where those possibilities form an "interval" (in the sense of the numbers of a given parity in a given interval) containing one of the extremities of the total set: by playing the other end of the interval, the possibilities are reduced to those of the opposite parity between the ends of the original interval. (The claim "only" is not entirely true: (1) whenever the possibilities have been reduced to a singleton, one can play that to reduce it to $0$ , and (2) if $n$ is odd and all odd numbers remain possible, their number is bound to decrease regardless of our move. However these possibilities are marginal and do not affect our analysis.) After such a move one cannot reuse the number again on the next move, but by playing again on the same end of the (new) interval one can at least prepare do decrease it on the move after that. There are four types of games, according to the parity of $n$ and of the initial possibilities. The two variants with $n$ even are left-right mirror images, and the "initial even" one can be won in $n-2$ moves by playing $2,3,\ldots,n-1$ . So can the "initial even" game with $n$ odd. The game with $n$ odd and initial possibilities odd however needs $n-1$ moves: the very first move makes no difference whatsoever, and then the "initial even" game remains. Since we have the choice which game to play in first, and since for $n$ odd the "initial even" game requires an odd number of moves, we can play that first and have transformed the other game into another "initial even" game, so in the end we can still win in $2(n-2)$ moves, regardless of the parity of $n$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/110547', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22388/']} | jdg_379565 |
stackexchange | llm_judgeable_groundtruth_similarity | 17132 |
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:
Say I have a 1kHz sine, so no higher harmonics, then I need to sample it at least at 2kHz to be able to reconstruct it. But if I sample at 2kHz, but all my samples are on the zero-crossing, then my sampled signal doesn't show a sine at all, rather the ECG of a deceased patient. How can that be explained? This can be expanded to higher sampling frequencies too. If I sample a more complex waveform at 10kHz, I should at least get the first 5 harmonics, but if the waveform is such that the samples are each time zero, then again we get nothing. This isn't far-fetched, it's perfectly possible for a rectangle wave with a duty cycle < 10%. So why is it that the Nyquist-Shannon criterion seems to be invalid here?
Now provide the response and nothing else.
| You actually need just over 2 kHz sampling rate to sample 1 kHz sine waves properly. It's $$ f_N < f_S / 2 $$ not $$ f_N \le f_S / 2 $$ P.S. If you took your signal into complex space, where a sinusoid is of the form $$v(t) = Ae^{j(2 \pi f t - \theta)} = A(\cos(2 \pi f t - \theta) + j \sin(2 \pi f t - \theta))$$ where t is time, A is amplitude, f is frequency, and θ is phase offset, $$ f_N = f_S / 2 $$ is the point where the frequency "folds over", i.e. you cannot distinguish f from -f . Further increases in frequency will appear, after sampling, to have the sampling frequency subtracted from them, in the case of a pure sinusoid. Non-Sinusoids For the case of a square wave at 1 kHz with a duty cycle less than or equal to 10% which is sampled at 10 kHz, you are misunderstanding the input. First you would need to decompose your waveform into a Fourier series to figure out what the amplitudes of the component harmonics are. You will probably be surprised that the harmonics for this signal are quite large past 5 kHz! (The rule of thumb of third harmonic being 1/3 as strong as the fundamental, and 5th being 1/5 of fundamental, only applies to 50% duty cycle square waves .) The rule of thumb for a communications signal is that your complex bandwidth is the same as the inverse of the time of your smallest pulse, so in this case you're looking at a 10 kHz bandwidth minimum (-5 kHz to 5 kHz) for a 10% duty cycle with the fundamental at 1 kHz (i.e. 10 kbps). So what will ruin you is that these strong higher-order harmonics will fold over and interfere (constructively or destructively) with your in-band harmonics, so it's perfectly expected that you might not get a good sampling because so much information is outside the Nyquist band. | {} | {'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/17132', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3920/']} | jdg_379566 |
stackexchange | llm_judgeable_groundtruth_similarity | 3411888 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This has always lingered in the back of my mind, so I figure I might as well go ahead and ask. How does a wiki handle multiple edits on the same content? Here's a simplistic example of what I'm asking. Let's say that a page has the following content: I'm a page! And now let's say that two go to edit that page. Each person adds a sentence: Person one: I'm a page! I'm a second sentence in the same page! Person two: I'm a page! I'm a second sentence! Imagine each person's second sentence being an equally relevant but different fact about the topic of the page that each person wanted to add in. Now let's say that person one submits their changes before person two does, but person two doesn't even get a chance to see the changes that person one made. Does person two's changes overwrite those of person one when he finally goes to submit? Is there a diff / merge algorithm that could be used for this?
Now provide the response and nothing else.
| I believe Wikipedia uses a fairly simple diff/merge algorithm, similar to how most source code control software does it. In the example you gave, it would raise a merge conflict error, because there's no way for it to know which line should come first in the final markup. The second person to save their changes would be presented with a merge error page where they have to choose how to resolve the conflict. Keep in mind, though, that wikipedia is on the high-end of the concurrent users scale. For the majority of wikis, it would probably be acceptable to use a very simple "last save wins" algorithm, where the second person's edits simply overwrites the first person's. With the addition of history, it should be easy for the first person to spot that their changes have been overwritten and add them back again. I believe this solution is what Stack Overflow uses. SO has an additional feature where an Ajax call is used to notify the editor if someone else comes in and modifies the page before they're finished. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3411888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/355325/']} | jdg_379567 |
stackexchange | llm_judgeable_groundtruth_similarity | 28149 |
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:
Hexagon bin plots are a useful way of visualising large datasets of bivariate data. Here are a few examples: With bin frequency indicated by grey level... ..and by glyph size There are packages for creating this kind of plot in both "R" and Python . Obviously, the idea is similar to DensityHistogram plots. How would one go about generating hexagonal bins in Mathematica? Also, how would one control the size of a plotmarker based on the bin frequency? Update As a starting point I have tried to create a triangular grid of points: vert1 = Table[{x, Sqrt[3] y}, {x, 0, 20}, {y, 0, 10}];vert2 = Table[{1/2 x, Sqrt[3] /2 y}, {x, 1, 41, 2}, {y, 1, 21, 2}];verttri = Flatten[Join[vert1, vert2], 1]; overlaying some data.. data = RandomReal[{0, 20}, {500, 2}];ListPlot[{verttri, data}, AspectRatio -> 1] next step might involve using Nearest : nearbin = Nearest[verttri];ListPlot[nearbin[#] & /@ data, AspectRatio -> 1] This gives the location of vertices with nearby data points. Unfortunately, I can't see how to count those data points..
Now provide the response and nothing else.
| With the set-up you already have, you can do nearbin = Nearest[Table[verttri[[i]] -> i, {i, Length@verttri}]];counts = BinCounts[nearbin /@ data, {1, Length@verttri + 1, 1}]; which counts the number of data points nearest to each vertex. Then just draw the glyphs directly: With[{maxCount = Max@counts}, Graphics[ Table[Disk[verttri[[i]], 0.5 Sqrt[counts[[i]]/maxCount]], {i, Length@verttri}], Axes -> True]] The square root is so that the area of the glyphs, and the number of black pixels, corresponds to the number of data points in each bin. I used data = RandomVariate[MultinormalDistribution[{10, 10}, 7 IdentityMatrix[2]], 500] to get the following plot: As Jens has commented already, though, this is a unnecessarily slow way of going about it. One ought to be able to directly compute the bin index from the coordinates of a data point without going through Nearest . This way was easy to implement and works fine for a 500-point dataset though. Update: Here's an approach that doesn't require you to set up a background grid in advance. We'll directly find the nearest grid vertex for each data point and then tally them up. To do so, we'll break the hexagonal grid into rectangular tiles of size $1\times\sqrt3$. As it turns out, when you're in say the $[0,1]\times[0,\sqrt3]$ tile, your nearest grid vertex can only be one of the five vertices in the tile, $(0,0)$, $(1,0)$, $(1/2,\sqrt3/2)$, $(0,\sqrt3)$, and $(1,\sqrt3)$. We could work out the conditions explicitly, but let's just let Nearest do the work: tileContaining[{x_, y_}] := {Floor[x], Sqrt[3] Floor[y/Sqrt[3]]};nearestWithinTile = Nearest[{{0, 0}, {1, 0}, {1/2, Sqrt[3]/2}, {0, Sqrt[3]}, {1, Sqrt[3]}}];nearest[point_] := Module[{tile, relative}, tile = tileContaining[point]; relative = point - tile; tile + First@nearestWithinTile[relative]]; The point is that a NearestFunction over just five points ought to be extremely cheap to evaluate—certainly much cheaper than your NearestFunction over the several hundred points in verttri . Then we just have to apply nearest on all the data points and tally the results. tally = Tally[nearest /@ data];With[{maxTally = Max[Last /@ tally]}, Graphics[ Disk[#[[1]], 1/2 Sqrt[#[[2]]/maxTally]] & /@ tally, Axes -> True, AxesOrigin -> {0, 0}]] | {} | {'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/28149', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4626/']} | jdg_379568 |
stackexchange | llm_judgeable_groundtruth_similarity | 117725 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The reduction potentials of perchlorate, chlorate, chlorous acid and chlorine dioxide in acidic and basic solutions are listed in the table below: $$\begin{array}{lcc}\hline\text{Oxychloride} & E^\circ_\text{acidic}/\pu{V} & E^\circ_\text{basic}/\pu{V} \\\hline\ce{ClO4-} & 1.19 & 0.56 \\\ce{ClO3-} & 1.21 & 0.63 \\\ce{HClO2} & 1.65 & 0.78 \\\ce{ClO2} & 1.63 & 0.89 \\\hline\ce{}\end{array}$$ Why is $\ce{ClO-}$ such a strong oxidizing agent compared to other chloride oxyanions, despite its low oxidation number? Is oxidation number representative of oxidizing strength?
Now provide the response and nothing else.
| Besides the the thermodynamic aspects discussed by Matthew, consider the kinetic aspects. Oxidation by a chlorine oxyanion involves displacement of oxygen from its bond with the chlorine. Such a displacement, in a protic solvent such as water, must involve protonation of the oxygen: Oxygen without the proton would have to be displaced as oxide ion, which would be a high-energy intermediate in any protic solvent. In this article from the University of Utah[1] , molecular orbitals for some phosphorous-oxygen species are discussed. These show that oxygen can back-donate its $p$ electrons to phosphorous, strengthening the bond. A similar back-donation to chlorine would make the oxygen harder to displace in a redox reaction, but protonation would cut down on this back-donation. Given these considerations, oxidation by a chlorine oxyanion is kinetically favored if the oxygen can act as a base and thus form a species that is more easily displaced than a bare oxide ion. Hypochlorite ion does that relatively well, whereas in higher oxyanions the needed basic character weakens rapidly unless we force the issue with a strongly acidic solution. Reference 1.Benjamin Gamoke, Diane Neff, and Jack Simons, "Nature of PO Bonds in Phosphates", J. Phys. Chem. A 2009, 113 , 5677–5684. http://simons.hec.utah.edu/papers/317.pdf | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/117725', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/24079/']} | jdg_379569 |
stackexchange | llm_judgeable_groundtruth_similarity | 171066 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If four variables are cointegrated, does this mean that each two of them are cointegrated? Can we regress only two of the four variables assuming they are cointegrated, or do we need to check for cointegration of the two variables? For me if four variables are cointegrated this means that they move close to each other, to say it in crude way. This means that if four variables are moving together then each pair should be moving together, too. Is this a valid reasoning?
Now provide the response and nothing else.
| At least for the "Mann-Kendall Rank Test", the problem seems to be in the testing package you're using, and not in the data. Specifically, the Mann-Kendall test is supposed to detect monotone trends in the data by calculating the Kendall rank correlation coefficient between the data points and their position in the input sequence. However, looking at the source code of the randtests R package you're using, I see two problems with it: It's using a naïve $\mathrm O(n^2)$ algorithm to calculate the Kendall correlation coefficient, which means that it gets very slow for large data sets. Your data set, with 20 times 400,000 points, is just about at the limit of what it can handle. Also, it seems to be assuming that no two data points have identical values. For your data, this is patently false, leading to bogus results. I retested your data using a better implementation of the Kendall test , and got $\tau_B = -0.0012$, $p = 0.25$ for the whole data, and $\tau_B = -0.010$, $p = 0.03$ for the most strongly trended (i.e. lowest $p$ value) column (the last one, as it happens). For the lowest $p$ value out of 20, this is well within the bounds of reasonable random variation. It also took me only a few minutes to run this test on my laptop. FWIW, here's the Python code I used to run this test: import numpy as npimport scipy.stats as statsdata = np.loadtxt('data.csv', delimiter=',', dtype=int, skiprows=1)for col in range(1, len(data[0])): tau, p = stats.kendalltau(data[:,0], data[:,col]) print "column %2d: tau = %+g, p = %g" % (col, tau, p)for order in ('C', 'F'): flat = data[:,1:].flatten(order) tau, p = stats.kendalltau(flat, np.arange(len(flat))) print "full data (%s): tau = %+g, p = %g" % (order, tau, p) (For the full data tests, C means row-major order and F means column-major order; I tested them both for the sake of completeness.) | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/171066', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/88653/']} | jdg_379570 |
stackexchange | llm_judgeable_groundtruth_similarity | 9118183 |
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 admit significant bias toward liking PCRE regexps much better than emacs, if no no other reason that when I type a '(' I pretty much always want a grouping operator. And, of course, \w and similar are SO much more convenient than the other equivalents. But it would be crazy to expect to change the internals of emacs, of course. But it should be possible to convert from a PCRE experssion to an emacs expression, I'd think, and do all the needed conversions so I can write: (defun my-super-regexp-function ... (search-forward (pcre-convert "__\\w: \d+"))) (or similar). Anyone know of a elisp library that can do this? Edit: Selecting a response from the answers below... Wow, I love coming back from 4 days of vacation to find a slew of interesting answers to sort through! I love the work that went into the solutions of both types. In the end, it looks like both the exec-a-script and straight elisp versions of the solutions would both work, but from a pure speed and "correctness" approach the elisp version is certainly the one that people would prefer (myself included).
Now provide the response and nothing else.
| ERROR: type should be string, got "https://github.com/joddie/pcre2el is the up-to-date version of this answer. pcre2el or rxt (RegeXp Translator or RegeXp Tools) is a utility for working with regular expressions in Emacs, based on a recursive-descent parser for regexp syntax. In addition to converting (a subset of) PCRE syntax into its Emacs equivalent, it can do the following: convert Emacs syntax to PCRE convert either syntax to rx , an S-expression based regexp syntax untangle complex regexps by showing the parse tree in rx form and highlighting the corresponding chunks of code show the complete list of strings (productions) matching a regexp, provided the list is finite provide live font-locking of regexp syntax (so far only for Elisp buffers – other modes on the TODO list) The text of the original answer follows... Here's a quick and ugly Emacs lisp solution (EDIT: now located more permanently here ). It's based mostly on the description in the pcrepattern man page, and works token by token, converting only the following constructions: parenthesis grouping ( .. ) alternation | numerical repeats {M,N} string quoting \\Q .. \\E simple character escapes: \\a , \\c , \\e , \\f , \\n , \\r , \\t , \\x , and \\ + octal digits character classes: \\d , \\D , \\h , \\H , \\s , \\S , \\v , \\V \\w and \\W left as they are (using Emacs' own idea of word and non-word characters) It doesn't do anything with more complicated PCRE assertions, but it does try to convert escapes inside character classes. In the case of character classes including something like \\D , this is done by converting into a non-capturing group with alternation. It passes the tests I wrote for it, but there are certainly bugs, and the method of scanning token-by-token is probably slow. In other words, no warranty. But perhaps it will do enough of the simpler part of the job for some purposes. Interested parties are invited to improve it ;-) (eval-when-compile (require 'cl))(defvar pcre-horizontal-whitespace-chars (mapconcat 'char-to-string '(#x0009 #x0020 #x00A0 #x1680 #x180E #x2000 #x2001 #x2002 #x2003 #x2004 #x2005 #x2006 #x2007 #x2008 #x2009 #x200A #x202F #x205F #x3000) \"\"))(defvar pcre-vertical-whitespace-chars (mapconcat 'char-to-string '(#x000A #x000B #x000C #x000D #x0085 #x2028 #x2029) \"\"))(defvar pcre-whitespace-chars (mapconcat 'char-to-string '(9 10 12 13 32) \"\"))(defvar pcre-horizontal-whitespace (concat \"[\" pcre-horizontal-whitespace-chars \"]\"))(defvar pcre-non-horizontal-whitespace (concat \"[^\" pcre-horizontal-whitespace-chars \"]\"))(defvar pcre-vertical-whitespace (concat \"[\" pcre-vertical-whitespace-chars \"]\"))(defvar pcre-non-vertical-whitespace (concat \"[^\" pcre-vertical-whitespace-chars \"]\"))(defvar pcre-whitespace (concat \"[\" pcre-whitespace-chars \"]\"))(defvar pcre-non-whitespace (concat \"[^\" pcre-whitespace-chars \"]\"))(eval-when-compile (defmacro pcre-token-case (&rest cases) \"Consume a token at point and evaluate corresponding forms.CASES is a list of `cond'-like clauses, (REGEXP FORMS...). Considering CASES in order, if the text at point matchesREGEXP then moves point over the matched string and returns thevalue of FORMS. Returns `nil' if none of the CASES matches.\" (declare (debug (&rest (sexp &rest form)))) `(cond ,@(mapcar (lambda (case) (let ((token (car case)) (action (cdr case))) `((looking-at ,token) (goto-char (match-end 0)) ,@action))) cases) (t nil))))(defun pcre-to-elisp (pcre) \"Convert PCRE, a regexp in PCRE notation, into Elisp string form.\" (with-temp-buffer (insert pcre) (goto-char (point-min)) (let ((capture-count 0) (accum '()) (case-fold-search nil)) (while (not (eobp)) (let ((translated (or ;; Handle tokens that are treated the same in ;; character classes (pcre-re-or-class-token-to-elisp) ;; Other tokens (pcre-token-case (\"|\" \"\\\\|\") (\"(\" (incf capture-count) \"\\\\(\") (\")\" \"\\\\)\") (\"{\" \"\\\\{\") (\"}\" \"\\\\}\") ;; Character class (\"\\\\[\" (pcre-char-class-to-elisp)) ;; Backslash + digits => backreference or octal char? (\"\\\\\\\\\\\\([0-9]+\\\\)\" (let* ((digits (match-string 1)) (dec (string-to-number digits))) ;; from \"man pcrepattern\": If the number is ;; less than 10, or if there have been at ;; least that many previous capturing left ;; parentheses in the expression, the entire ;; sequence is taken as a back reference. (cond ((< dec 10) (concat \"\\\\\" digits)) ((>= capture-count dec) (error \"backreference \\\\%s can't be used in Emacs regexps\" digits)) (t ;; from \"man pcrepattern\": if the ;; decimal number is greater than 9 and ;; there have not been that many ;; capturing subpatterns, PCRE re-reads ;; up to three octal digits following ;; the backslash, and uses them to ;; generate a data character. Any ;; subsequent digits stand for ;; themselves. (goto-char (match-beginning 1)) (re-search-forward \"[0-7]\\\\{0,3\\\\}\") (char-to-string (string-to-number (match-string 0) 8)))))) ;; Regexp quoting. (\"\\\\\\\\Q\" (let ((beginning (point))) (search-forward \"\\\\E\") (regexp-quote (buffer-substring beginning (match-beginning 0))))) ;; Various character classes (\"\\\\\\\\d\" \"[0-9]\") (\"\\\\\\\\D\" \"[^0-9]\") (\"\\\\\\\\h\" pcre-horizontal-whitespace) (\"\\\\\\\\H\" pcre-non-horizontal-whitespace) (\"\\\\\\\\s\" pcre-whitespace) (\"\\\\\\\\S\" pcre-non-whitespace) (\"\\\\\\\\v\" pcre-vertical-whitespace) (\"\\\\\\\\V\" pcre-non-vertical-whitespace) ;; Use Emacs' native notion of word characters (\"\\\\\\\\[Ww]\" (match-string 0)) ;; Any other escaped character (\"\\\\\\\\\\\\(.\\\\)\" (regexp-quote (match-string 1))) ;; Any normal character (\".\" (match-string 0)))))) (push translated accum))) (apply 'concat (reverse accum)))))(defun pcre-re-or-class-token-to-elisp () \"Consume the PCRE token at point and return its Elisp equivalent.Handles only tokens which have the same meaning in characterclasses as outside them.\" (pcre-token-case (\"\\\\\\\\a\" (char-to-string #x07)) ; bell (\"\\\\\\\\c\\\\(.\\\\)\" ; control character (char-to-string (- (string-to-char (upcase (match-string 1))) 64))) (\"\\\\\\\\e\" (char-to-string #x1b)) ; escape (\"\\\\\\\\f\" (char-to-string #x0c)) ; formfeed (\"\\\\\\\\n\" (char-to-string #x0a)) ; linefeed (\"\\\\\\\\r\" (char-to-string #x0d)) ; carriage return (\"\\\\\\\\t\" (char-to-string #x09)) ; tab (\"\\\\\\\\x\\\\([A-Za-z0-9]\\\\{2\\\\}\\\\)\" (char-to-string (string-to-number (match-string 1) 16))) (\"\\\\\\\\x{\\\\([A-Za-z0-9]*\\\\)}\" (char-to-string (string-to-number (match-string 1) 16)))))(defun pcre-char-class-to-elisp () \"Consume the remaining PCRE character class at point and return its Elisp equivalent.Point should be after the opening \\\"[\\\" when this is called, andwill be just after the closing \\\"]\\\" when it returns.\" (let ((accum '(\"[\")) (pcre-char-class-alternatives '()) (negated nil)) (when (looking-at \"\\\\^\") (setq negated t) (push \"^\" accum) (forward-char)) (when (looking-at \"\\\\]\") (push \"]\" accum) (forward-char)) (while (not (looking-at \"\\\\]\")) (let ((translated (or (pcre-re-or-class-token-to-elisp) (pcre-token-case ;; Backslash + digits => always an octal char (\"\\\\\\\\\\\\([0-7]\\\\{1,3\\\\}\\\\)\" (char-to-string (string-to-number (match-string 1) 8))) ;; Various character classes. To implement negative char classes, ;; we cons them onto the list `pcre-char-class-alternatives' and ;; transform the char class into a shy group with alternation (\"\\\\\\\\d\" \"0-9\") (\"\\\\\\\\D\" (push (if negated \"[0-9]\" \"[^0-9]\") pcre-char-class-alternatives) \"\") (\"\\\\\\\\h\" pcre-horizontal-whitespace-chars) (\"\\\\\\\\H\" (push (if negated pcre-horizontal-whitespace pcre-non-horizontal-whitespace) pcre-char-class-alternatives) \"\") (\"\\\\\\\\s\" pcre-whitespace-chars) (\"\\\\\\\\S\" (push (if negated pcre-whitespace pcre-non-whitespace) pcre-char-class-alternatives) \"\") (\"\\\\\\\\v\" pcre-vertical-whitespace-chars) (\"\\\\\\\\V\" (push (if negated pcre-vertical-whitespace pcre-non-vertical-whitespace) pcre-char-class-alternatives) \"\") (\"\\\\\\\\w\" (push (if negated \"\\\\W\" \"\\\\w\") pcre-char-class-alternatives) \"\") (\"\\\\\\\\W\" (push (if negated \"\\\\w\" \"\\\\W\") pcre-char-class-alternatives) \"\") ;; Leave POSIX syntax unchanged (\"\\\\[:[a-z]*:\\\\]\" (match-string 0)) ;; Ignore other escapes (\"\\\\\\\\\\\\(.\\\\)\" (match-string 0)) ;; Copy everything else (\".\" (match-string 0)))))) (push translated accum))) (push \"]\" accum) (forward-char) (let ((class (apply 'concat (reverse accum)))) (when (or (equal class \"[]\") (equal class \"[^]\")) (setq class \"\")) (if (not pcre-char-class-alternatives) class (concat \"\\\\(?:\" class \"\\\\|\" (mapconcat 'identity pcre-char-class-alternatives \"\\\\|\") \"\\\\)\")))))" | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9118183', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/473770/']} | jdg_379571 |
stackexchange | llm_judgeable_groundtruth_similarity | 348922 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am writing a repository class with entity framework. One of the method is an update method, which simply updates an entity. The controller does not need the entity. However, from a testing perspective, it may be useful to just return the entity. Than I easily have something to assert. It may be even more useful to return two things (with a value tuple): the saved entity and the number of saved changes. Then I have more to assert. On the other hand, it is an update method, not a read method that sould absolutely return something. What choice should I make considering the good practices?
Now provide the response and nothing else.
| You should be returning values because you need them not because it makes testing easier. That being said, it is more valuable to know if the operation succeeded since you already know what's going to be updated. If something goes wrong you can use exceptions to communicate it to the upper layers. Also, I don't think that returning a value representing the number of affected records would provide much value since you'll probably be updating aggregates that have updated children. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/348922', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/147747/']} | jdg_379572 |
stackexchange | llm_judgeable_groundtruth_similarity | 1308509 |
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 I can get the "value" attribute of a radiobutton but I'm finding it strangely difficult to get the text of the radiobutton. Consider the example below. It has 3 radiobuttons and tries to alert the value of the first radio button, which is "red" and then trys to alert the text of the radiobutton, "apple" but that fails. Getting the text of almost any element can be done with elem.childNodes[0].nodeValue. Why doesn't it work for radiobuttons? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" ><head><title>Radio Buttons</title><style type="text/css"></style><script type="text/javascript">function start(){ var rblist = document.getElementsByName("colors"); var elem = rblist[0]; alert(elem.value); // PRINTS "RED" alert(elem.childNodes[0].nodeValue); //THROWS ERROR}</script> </head><body onload="start();"><input type="radio" name="colors" value="red" checked>apple</input><input type="radio" name="colors" value="blue">sky</input><input type="radio" name="colors" value="green">grass</input></body> </html>
Now provide the response and nothing else.
| It doesn't work because there is no such thing as text inside an <input> like that -- that's illegal in XHTML. It must be: <input type="radio" name="colors" value="red" id="radio1" checked="checked" /><label for="radio1">apple</label> Then you can look for the text inside the <label> . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1308509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/28565/']} | jdg_379573 |
stackexchange | llm_judgeable_groundtruth_similarity | 33760647 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Makefile's targets are available by completion on Linux but, AFAICS, not on Mac OS (10.8.5). Is it possible to get completion working with this OS?
Now provide the response and nothing else.
| This seems to achieve simple bash completions for me on El Capitan: # .bashrcfunction _makefile_targets { local curr_arg; local targets; # Find makefile targets available in the current directory targets='' if [[ -e "$(pwd)/Makefile" ]]; then targets=$( \ grep -oE '^[a-zA-Z0-9_-]+:' Makefile \ | sed 's/://' \ | tr '\n' ' ' \ ) fi # Filter targets based on user input to the bash completion curr_arg=${COMP_WORDS[COMP_CWORD]} COMPREPLY=( $(compgen -W "${targets[@]}" -- $curr_arg ) );}complete -F _makefile_targets make Here's how this works: complete -F [function name] [command name] -- this bash builtin register a new completion for [command name] which is generated by the bash function [function name]. So in my code above, if you type make [TAB][TAB] into your shell, you'll trigger the _makefile_targets() function. if [[ -e "$(pwd)/Makefile" ]]; then -- make sure there's a Makefile in the current directory, otherwise don't try a bash completion. grep -oE '^[a-zA-Z0-9_-]+:' Makefile -- filter every line of Makefile using the regex for a target name like "test:". -o means only return the part of the line that matches. For example, given a Makefile target like "test: build package", only "test:" will be returned | sed 's/://' -- taking the grep results, remove the colon from the end of line | tr '\n' ' ' -- smoosh all targets onto one line, separated by one space Inside a bash completion function, complete sets several environment variables for you. COMP_WORDS is an array of the list of available bash completion choises based on what the user typed. COMP_CWORD is the index of the currently selected word. Another very magical builtin compgen will take a list of space separately strings and filter them using the currently selected word. I'm not at all clear how that works. So, the bottom line is that the last two lines in the function filter our list of makefile targets (stored inside $targets ) and shoves them into an array COMPREPLY . The bash completion reads and displays COMPREPLY as choices in the shell. Inspired by: https://gist.github.com/tlrobinson/1073865 http://www.thegeekstuff.com/2013/12/bash-completion-complete/ (Esp 9.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33760647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1682470/']} | jdg_379574 |
stackexchange | llm_judgeable_groundtruth_similarity | 421991 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to PHP and JS and I'm currently working on a gym management web app for our project in school. I'm adding a bit of QR functionality that sees if the user is eligible to enter the gym or not by checking if the user has paid. I want to know if it is good to escape PHP code in inline JS, or would it be better to get the id via ajax and store it into a js variable? <script>// ...new QRCode(document.getElementById("qr-code"), "./functions/check_if_paid_qr.php?id=<?php echo $_SESSION["member_id"] ?>");// ...</script> I'm using qrcode.js btw.
Now provide the response and nothing else.
| No, it's usually a bad practice. The problem Any time you echo something from PHP into JavaScript what's happening is that you're trying to generate valid JavaScript code. There is no generic guarantee that you do produce syntactically and semantically valid JavaScript code that also does what you want. It might be easier to guess whether individual instances of code are going to work but it's definitely not a guarantee. Take for example the following code var someVariable = '<?php echo $someOtherVariable ?>'; This seems like it should work. And indeed it will if $someOtherVariable doesn't contain a newline or a single apostrophe. However, if it contains O'Brian or Hello\nWorld the generated JavaScript code would be invalid in either case: Early terminating of a string literal leads to invalid code after it: var someVariable = 'O'Brian'; Invalid multiline string: var someVariable = 'HelloWorld'; Looking at the code and determining whether the code is correct right now and will remain correct becomes very hard. What if the format of the data you're echoing changes? What if you get some data you didn't expect? To generalise, the issue is that you don't have a complete JavaScript source code. The source code is only complete when a user visits the page and the backend produces it for them. Until then it's in limbo and it's unknown whether it will work. Impeded code analysis Not only is it hard for humans to determine how a code would behave, but automated tools that are there to help you might also suffer. Some examples Syntax highlighters may break because of the mix of the two languages. This is often the first line of defence against defective code. For example, look at the line that says 'O'Brian' - you'd see that the highlighting is inconsistent between 'O' and Brian'; . Tools that analyse code for correctness like ESLint or Tern.js among others will not be able to analyse code that's not there. Is var someVariable = '<?php echo $someOtherVariable ?>")'; syntactically correct JavaScript? We, as humans, cannot say, an automated tool that merely follows some rules is completely unable to guess what the generated code would be. Tools that extract code metrics would similarly have a problem as they may not be able to parse the real JavaScript code produced. Hard to test code Automatic testing also suffers when you mix the two languages. You can test the code but you need to first need to boot up a PHP environment with enough data in order to generate you JavaScript code and then run tests on the JavaScript code. This is a full integration test with a lot of edge cases to cover and situations to account for. Unit test that focuses on only JavaScript and only PHP would be vastly simpler and you can make sure each fulfils their part of the contract first before checking how they work together. Hard to debug What all the above means is that when something happens that breaks JavaScript, you wouldn't be likely to know or even suspect. It's only going to break for some users only some of the time. How many would report it and how accurate the reports would be would vary but in my experience - don't expect much. So, if you'd know that something doesn't work is questionable to begin with. Moreover, even if you do find out that it doesn't work, you'd now have to track down which mixed JavaScript+PHP line is it. Unless there is a single one, you'd need to spend a non-zero time of investigation to find where it goes wrong. And another non-zero amount of time to find why . All that would likely happen after you've developed the application. Maybe a week, maybe a year. In the best case scenario it was you who wrote the code, so while it's still going to be quite hard, you might have some idea about where to start. However, you might have inherited this code. Or somebody else could have inherited it from you. Bundling Modern JavaScript is often passed through tools to produce a compact set of files from it. The bundling process will read the JavaScript source and produce a minified version of it. This can suffer if the JavaScript source is incomplete as the compilation happens before any user has ever interacted with the site. | {} | {'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/421991', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/384719/']} | jdg_379575 |
stackexchange | llm_judgeable_groundtruth_similarity | 50760024 |
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 installed ffmpeg (version 4) with Homebrew and I am trying to use the various ffmpeg libraries in a C++ project, but I am getting multiple errors during linking. Undefined symbols for architecture x86_64: "_av_free", referenced from: _main in main.cpp.o "_av_packet_alloc", referenced from: _main in main.cpp.o "_av_parser_init", referenced from:And so on ... I have included the libraries as follow extern "C" { #include <libavutil/frame.h> #include <libavutil/mem.h> #include <libavcodec/avcodec.h>} But still, this doesn't work. I think I might have missed something in my CMakeLists.txt file, which at the moment looks like that : cmake_minimum_required(VERSION 2.6)project(decode_encode)set(CMAKE_CXX_STANDARD 11)set(CMAKE_CXX_FLAGS "-D__STDC_CONSTANT_MACROS")add_executable(decode_encode main.cpp) I most likely need to specify additional linking flags, but is there is a better way to handle the linking part in a CMakeLists.txt file?
Now provide the response and nothing else.
| Ok, I've found the solution. It appears that FFmpeg doesn't support find_package in CMake. I had to manually link the libraries as suggested here . Final CMakeLists.txt looks like this cmake_minimum_required(VERSION 2.6)project(decode_encode)set(CMAKE_CXX_STANDARD 11)set(CMAKE_CXX_FLAGS "-D__STDC_CONSTANT_MACROS")find_path(AVCODEC_INCLUDE_DIR libavcodec/avcodec.h)find_library(AVCODEC_LIBRARY avcodec)find_path(AVFORMAT_INCLUDE_DIR libavformat/avformat.h)find_library(AVFORMAT_LIBRARY avformat)find_path(AVUTIL_INCLUDE_DIR libavutil/avutil.h)find_library(AVUTIL_LIBRARY avutil)find_path(AVDEVICE_INCLUDE_DIR libavdevice/avdevice.h)find_library(AVDEVICE_LIBRARY avdevice)add_executable(decode_encode main.cpp)target_include_directories(decode_encode PRIVATE ${AVCODEC_INCLUDE_DIR} ${AVFORMAT_INCLUDE_DIR} ${AVUTIL_INCLUDE_DIR} ${AVDEVICE_INCLUDE_DIR})target_link_libraries(decode_encode PRIVATE ${AVCODEC_LIBRARY} ${AVFORMAT_LIBRARY} ${AVUTIL_LIBRARY} ${AVDEVICE_LIBRARY}) I am sure there is a better way to aggregate all the libraries, though. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50760024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9720263/']} | jdg_379576 |
stackexchange | llm_judgeable_groundtruth_similarity | 2208690 |
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 have it such that left clicking on the NotifyIcon also causes the context menu (set with the ContextMenuStrip property) to open as well. How would I achieve this? Do I have to handle Click and figure out the positioning myself? Edit: showing the menu with trayIcon.ContextMenuStrip.Show() results is a few undesirable behaviors: The menu is not shown at the same location as if right click the NotifyIcon (it appears that you can't set the x and y coords to where the taskbar is, at least on Windows 7 which is what I'm running). It will appear above the task bar (not that big of a deal, but consistency would be nice). While the menu is shown, there is an extra icon added to the task bar. Clicking somewhere other than the menu does not close it (whereas if you right click to bring up the context menu clicking else where automatically closes the context menu). Is it at all possible to just invoke the menu however the built in right click handler is doing it?
Now provide the response and nothing else.
| You would normally handle the MouseClick event to detect the click and call the ContextMenuStrip.Show() method: private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) { contextMenuStrip1.Show(Control.MousePosition); } But that doesn't actually work properly, the CMS won't close when you click outside of it. Underlying issue is a Windows quirk (aka "bug") that is described in this KB article . Invoking this workaround in your own code is pretty painful, the pinvoke is unpleasant. The NotifyIcon class has this workaround in its ShowContextMenu() method , they just made it difficult to get to since it is a private method. Reflection can bypass that restriction. I discovered this hack 5 years ago and nobody reported a problem with it yet. Set the NFI's ContextMenuStrip property and implement the MouseUp event like this: using System.Reflection;... private void notifyIcon1_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { MethodInfo mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic); mi.Invoke(notifyIcon1, null); } } | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2208690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95636/']} | jdg_379577 |
stackexchange | llm_judgeable_groundtruth_similarity | 5930795 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between these 2? I found few results on google nothing conclusive. Here is a follow up question: Say I create spring mvc web app annotate couple of classes with @Controller annotation and create something that will successfully transfer some information from front end -> back end and vice versa and perhaps some database might be involved on the back end side. What would you call that? Rest web service or servlet or something else ?
Now provide the response and nothing else.
| A web service is a service that provides service methods to its clients using either the REST programming paradigm or the SOAP protocol for communication. There are several ways to implement a web service. The most simple way to write a web service would be to write a class and annotate it with the @WebService and @WebMethod annotations from javax.jws , and then launch it from a main -method with: Endpoint.publish("http://localhost:8089/myservice", new MyWebService()); The result is that you can view the WSDL at the registered URL and if you have SoapUI or any other SOAP client you can also test and use your web service. A servlet on the other hand is used to transport HTTP requests and responses. It can be used to write a web application with JSPs and HTML, or to serve XML and JSON responses (as in a RESTful service) and of course also to receive and return SOAP messages. You can think of it as one layer below web services . Servlets have their own standard which is currently the Java Servlet Specification Version 4.0 A more comprehensive and practical approach is to write a web service with a framework and to publish it on an application server or servlet container such as Tomcat or JBoss. In this case you would use a Servlet to handle the transport of the HTTP requests which transmit your SOAP or REST messages. To write a web service with servlet technology you can for example use JAX-WS (e.g. for SOAP). In order to write RESTful services, you can either use JAX-RS (with the reference implementation being Jersey ), or alternatively you can use Spring WebMVC , but as far as I know that is not the main purpose of this framework and Jersey is considerably easier to use. Regarding the second question:The @Controller annotation is a Spring specific stereotype annotation that tells Spring something about what your bean is supposed to do. What exactly a method of a controller will return depends on the actual implementation of your methods, you can configure Spring to return plain text, HTML, JSON, XML, binary data or what ever you want. A note on the side, a class that is annotated with @Controller is not yet a servlet, it is simply a bean. How you use servlets depends mainly on the Framework that you use. For example, when you use Spring, the servlet job is done by Springs DispatcherServlet which in turn forwards requests to the correct beans. If you use Tomcat, then you can directly write your own servlets by simply subclassing the javax.servlet.http.HttpServlet class and overwriting the necessary methods such as doGet which responds to HTTP GET requests from your browser. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5930795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190623/']} | jdg_379578 |
stackexchange | llm_judgeable_groundtruth_similarity | 15578946 |
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 debugging purposes, I would like to use Django's logging mechanism to log each and every incoming request when it "arrives" at django-rest-framework's doorstep. Djagno offers logging of its requests (only "warning" log level and above) in the following manner (from LOGGING section in settings.py): 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, I'm looking to achieve something like this (notice: log level is DEBUG): 'rest_framework.request': { 'handlers': ['logfile'], 'level': 'DEBUG', 'propagate': False, }, Is there a way I can do that without embedding a logger in to DRF's source code? Is there maybe some sort of "Logging Backend" option in DRF I'm not aware of?
Now provide the response and nothing else.
| I made a generic RequestLogMiddleware that can be hooked into any Django View using decorator_from_middleware . request_log/middleware.py import socketimport timeclass RequestLogMiddleware(object): def process_request(self, request): request.start_time = time.time() def process_response(self, request, response): if response['content-type'] == 'application/json': if getattr(response, 'streaming', False): response_body = '<<<Streaming>>>' else: response_body = response.content else: response_body = '<<<Not JSON>>>' log_data = { 'user': request.user.pk, 'remote_address': request.META['REMOTE_ADDR'], 'server_hostname': socket.gethostname(), 'request_method': request.method, 'request_path': request.get_full_path(), 'request_body': request.body, 'response_status': response.status_code, 'response_body': response_body, 'run_time': time.time() - request.start_time, } # save log_data in some way return response request_log/mixins.py from django.utils.decorators import decorator_from_middlewarefrom .middleware import RequestLogMiddlewareclass RequestLogViewMixin(object): """ Adds RequestLogMiddleware to any Django View by overriding as_view. """ @classmethod def as_view(cls, *args, **kwargs): view = super(RequestLogViewMixin, cls).as_view(*args, **kwargs) view = decorator_from_middleware(RequestLogMiddleware)(view) return view my_django_rest_api/views.py from rest_framework import genericsfrom ...request_log.mixins import RequestLogViewMixinclass SomeListView( RequestLogViewMixin, generics.ListAPIView): ... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15578946', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1918837/']} | jdg_379579 |
stackexchange | llm_judgeable_groundtruth_similarity | 9622967 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here I have a static reference the ranges I need to check: private static List<string> Ip_Range = new List<string>(){ "12.144.86.0/23", "31.201.1.176/30", "46.36.198.101/32", "46.36.198.102/31", "46.36.198.104/31", "46.136.172.0/24", "63.65.11.0/24", "63.65.12.0/25", "63.65.12.128/26", "63.65.12.192/27", "63.65.12.224/28", "63.65.12.240/29", "63.65.12.248/30", "63.65.12.252/31", "63.65.12.254/32", "65.173.56.0/21", "67.23.241.179/32", "67.23.241.180/30", "67.23.241.184/29", "67.23.241.192/30", "67.23.241.196/31", "67.23.241.198/32", "72.32.164.56/29", "72.46.244.32/28", "74.91.16.48/29", "74.91.16.208/29", "74.91.20.48/28", "74.91.20.64/29", "74.112.134.120/29", "74.112.135.104/29", "74.205.37.16/29", "78.24.205.32/28", "98.129.27.88/29", "98.129.91.40/29", "166.114.0.0/16", "167.157.0.0/16", "174.143.165.80/29", "186.0.156.0/22", "186.2.0.0/17", "186.27.0.0/17", "190.0.248.0/21", "190.3.184.0/21"}; Here's some pseudo code on how I see it working: public static bool IpIsWithinRange(string ip) //Something like 127.0.0.1 or 184.56.26.35{ IPAddress incomingIp = IPAddress.Parse(ip); foreach (var subnet in Ip_Range) { IPAddress sub = IPAddress.Parse(subnet); ????? if (incomingIp "is in" sub) ? return true; } return false;} Any suggestions on how to code up this functionality?
Now provide the response and nothing else.
| Decided to answer my own question so people can benefit. If it can be improved, please do! I used the IPNetwork library and it worked out fantastically! nuget install IPNetwork2 Below is the code I used: using System.Net;public static class RedirectHelpers{ public static bool IpIsWithinBoliviaRange(string ip) { IPAddress incomingIp = IPAddress.Parse(ip); foreach (var subnet in Bolivia_Ip_Range) { IPNetwork network = IPNetwork.Parse(subnet); if (IPNetwork.Contains(network, incomingIp)) return true; } return false; } private static List<string> Bolivia_Ip_Range = new List<string>() { "12.144.86.0/23", "31.201.1.176/30", "46.36.198.101/32", "46.36.198.102/31", "46.36.198.104/31", "46.136.172.0/24", "63.65.11.0/24", "63.65.12.0/25", "63.65.12.128/26", "63.65.12.192/27", "63.65.12.224/28", "63.65.12.240/29", "63.65.12.248/30", "63.65.12.252/31", "63.65.12.254/32", "65.173.56.0/21", "67.23.241.179/32", "67.23.241.180/30", "67.23.241.184/29", "67.23.241.192/30", "67.23.241.196/31", "67.23.241.198/32", "72.32.164.56/29", "72.46.244.32/28", "74.91.16.48/29", "74.91.16.208/29", "74.91.20.48/28", "74.91.20.64/29", "74.112.134.120/29", "74.112.135.104/29", "74.205.37.16/29", "78.24.205.32/28", "98.129.27.88/29", "98.129.91.40/29", "166.114.0.0/16", "167.157.0.0/16", "174.143.165.80/29", "186.0.156.0/22", "186.2.0.0/17", "186.27.0.0/17", "190.0.248.0/21", "190.3.184.0/21", "166.114.0.0/16", "167.157.0.0/16", "186.2.0.0/18", "190.11.64.0/20", "190.11.80.0/20", "190.103.64.0/20", "190.104.0.0/19", "190.107.32.0/20", "190.129.0.0/17", "190.181.0.0/18", "190.186.0.0/18", "190.186.64.0/18", "190.186.128.0/18", "200.7.160.0/20", "200.58.64.0/20", "200.58.80.0/20", "200.58.160.0/20", "200.58.176.0/20", "200.75.160.0/20", "200.85.128.0/20", "200.87.0.0/17", "200.87.128.0/17", "200.105.128.0/19", "200.105.160.0/19", "200.105.192.0/19", "200.112.192.0/20", "200.119.192.0/20", "200.119.208.0/20", "201.222.64.0/19", "201.222.96.0/19" };} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9622967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/699978/']} | jdg_379580 |
stackexchange | llm_judgeable_groundtruth_similarity | 311366 |
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've created custom MOTDs to be displayed at login via SSH by doing the following: create a text file in /etc/usermotd/<username> with the message inside Edit the user's .bashrc file and put the following code: if [ -f /etc/usermotd/`whoami` ]; thencat /etc/usermotd/<username>;fi It works like I want it to. However... I've now just found that when I try to SCP something, it doesn't work. I do the scp command and it exits without giving any sort of progress bar or saying that it transferred. When I do scp -vvv, I get debug1: Authentication succeeded (publickey).debug2: fd 4 setting O_NONBLOCKdebug2: fd 5 setting O_NONBLOCKdebug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug1: Requesting [email protected]: Entering interactive session.debug2: callback startdebug2: client_session2_setup: id 0debug1: Sending command: scp -v -t ~debug2: channel 0: request exec confirm 1debug2: fd 3 setting TCP_NODELAYdebug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel 0: rcvd adjust 2097152debug2: channel_input_status_confirm: type 99 id 0debug2: exec request accepted on channel 0WELCOMEdebug2: channel 0: read<=0 rfd 4 len 0debug2: channel 0: read faileddebug2: channel 0: close_readdebug2: channel 0: input open -> draindebug2: channel 0: ibuf emptydebug2: channel 0: send eofdebug2: channel 0: input drain -> closedBigBoss ~/.ssh:-$ debug1: client_input_channel_req: channel 0 rtype exit-status reply 0debug2: channel 0: rcvd eofdebug2: channel 0: output open -> draindebug2: channel 0: obuf emptydebug2: channel 0: close_writedebug2: channel 0: output drain -> closeddebug2: channel 0: rcvd closedebug3: channel 0: will not send data after closedebug2: channel 0: almost deaddebug2: channel 0: gc: notify userdebug2: channel 0: gc: user detacheddebug2: channel 0: send closedebug2: channel 0: is deaddebug2: channel 0: garbage collectingdebug1: channel 0: free: client-session, nchannels 1debug3: channel 0: status: The following connections are open: #0 client-session (t4 r0 i3/0 o3/0 fd -1/-1 cfd -1)debug3: channel 0: close_fds r -1 w -1 e 6 c -1 debug1: fd 0 clearing O_NONBLOCKdebug1: fd 1 clearing O_NONBLOCK Transferred: sent 2208, received 3352 bytes, in 0.2 secondsBytes per second: sent 13207.5, received 20050.5debug1: Exit status 0 Any Ideas why it's failing to send? Or is there another way I can do this?
Now provide the response and nothing else.
| It's failing to work because scp expects the remote side to behave exactly "just so", and not scream WELCOME back at it. (It would be nice if it would give an error message, but...). Use sftp (which doesn't spawn a login shell at all) instead of scp or have your .bashrc detect if it's in an interactive session or not. There seem to be a couple of ways to do this: if [ -n "$PS1" ]; then echo WELCOMEfi; The other method given there for looking to see if "$-" contains "i" appears to be broken, since [ doesn't do * in string comparisons. This should work though (it checks to make sure $- is set, then checks to see if $- with "i" removed is the same as $-. There's probably a better way but I can't think of it at the second) if [ -n "$-" -a "${-/i}" != "$-" ]; then echo WELCOMEfi; | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/311366', 'https://serverfault.com', 'https://serverfault.com/users/52589/']} | jdg_379581 |
stackexchange | llm_judgeable_groundtruth_similarity | 3683 |
Below is a question asked on the forum skeptics.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am referring to this question: Do the mother's genes almost exclusively determine the sons' intelligence? This question currently garners 9 votes, 1.3K++ views, which shows that this is a good, interesting question. And when you go through the question, you will see that this is also a notable question, fulfilling the criteria of Skeptic SE ; surely questioning a claim published in a highly regarded journal is a notable question, no? Then why it is closed for "being unclear"? The question is unclear about? I was asked to look at the comments, because they somehow addressed the issue why this question was closed. From what I can see the closure reason offered in the comments is very weak In the comments, OP asked: @Sklivvz Does being published in a well-regarded peer reviewed journal not qualify as notable? What kind of signs of notability do you require in order to reconsider your decision? Sklivvz replied Look at what people actually believe. That's the notability standard. What do you expect people will actually answer to your question? What makes the mod Skivvz thinks that only a negligible minority of people believe in this claim? Major newspaper reported the news, the claim was made in a well established journal, and yet the claim is not "notable" enough to be asked on this site? I can easily point out there are a lot of questions, which are even less notable than the above one, that are nonetheless well-received on this site. So if you would want to close this question, then you would have to close a lot more, and Skeptic SE as we know it might cease to exist. It seems very clear to me that mods made a mistake in closing this question. Not only that, my own similar, equally valid question ( I didn't notice this question when I wrote mine) was downvoted for no reason... not too sure what I did wrong. Can someone restore justice here? And if you feel that the question worth reopening, go there and cast a reopen vote/flag it for mod reopening attention, let's right the wrong!
Now provide the response and nothing else.
| I've voted to re-open, need four more votes. It's clearly true that there is some confusion about the implications of Prof. Turner's paper, with sources (including Turner herself writing in The Lancet and at least two major newspapers) talking as if it accounts for, variously, all a male's intelligence, all their genetically-derived intelligence, or ~70-80% of their intelligence; seemingly containing contradictory lines in different places in the same articles. On the face of it, it looks like a classic case of a researcher and reporters over-stating the implications of some research while summarising it. This seems to be why it was closed: a mod believes these quotes don't reflect the evidence presented in the body of the paper. A study being exaggerated by popularisers who stretch it to a more attention-grabbing but unwarranted conclusion is exactly the sort of thing Skeptics.SE exists to debunk, and the tool to clear up such a matter is an answer . If it's true that an author's summaries, press releases etc about their study aren't supported by the paper's own evidence, that's the answer to the question. Hiding that fact behind a close vote doesn't help anyone. 1: Sklivvz says: The claim seems to be scarcely notable. ...which makes no sense because the question quoted a highly respected academic journal (The Lancet) and a major newspaper (The Independent). Normally, just one of these would be enough. I've added a second quote from a major newspaper (Wall Street Journal). This is plenty of notability. Each contain at least one quote that appears to state the premise of the question as a matter of fact: The Lancet: "his sons’ intelligence, if that is important to him, is solely dependent on his partner" The Independent: "Intelligent men owe their brains to their mothers" Wall Street Journal: "...all the credit for the [son]'s genius goes to Mom" If for any reason they're wrong to say these things, and there's evidence demonstrating this, that's the answer to the question . 2: Sklivvz says: I see no evidence that a lot of people believe that intelligence is solely due to the X chromosome. Normally, when a mainstream source presents something as fact, we don't also need some kind of proof that readers believe what they read. The fact it's presented as fact is usually enough. Also, at least four variants of this question have been asked now. Two that asked if "80%" of intelligence is so explained are now closed as dupes of this one, and the question is "Do the mother's genes almost exclusively determine the sons' intelligence?" and says "supposedly his intelligence is dominated by his mother's genes". There's no need to get hung up on "solely". 3: Sklivvz says: That conclusion is present but it's not coherent with the rest of the paper. This is an answer not a close reason. Many researchers give their research attention-grabbing conclusions that stretch beyond the logical implications of the evidence, and that's exactly the sort of thing that skeptics should debunk , especially if it's being done in a highly respected journal like The Lancet and being repeated in major newspapers. A comment and a close vote are not the correct tools for debunking a researcher and several newspapers' excessive conclusions: not only is it opaque and doesn't contain space to summarise the evidence properly, but also, if it turned out Sklivvz was wrong and, surprisingly, the claim was actually true and was supported by evidence (unlikely but possible), it'd be impossible for someone to comment or write a better answer explaining this. 4: "closed as unclear what you're asking by Sklivvz" None of the stated reasons have anything to do with being unclear, and the fact that it's so easy to identify that a newer question is a duplicate of this one proves that the question is clear enough to understand what's being asked. 5: Latest comment: Here are a few suggestions on how to fix: (1) "Are the conclusions on this paper coherent with the evidence it presents" -> ask on Biology (2) "Is this reporting of a paper coherent with it" -> reword and ask here (3) "Is this claim in a newspaper coherent with evidence" -> reword and ask here (4) "is there any update on this paper's findings" ask on Biology This seems to suggest that you need to know what the answer to a question is in order to choose where to ask it and how to frame it, and overcomplicates things needlessly. Normally, what you need for a skeptics question is, a claim, and proof that the claim is notable. You don't also need to pick one possible reason out of many why the claim might not be true and narrow it to that. In fact, most times I've seen askers talk about why they think a claim might be mistaken, it's been edited out. The question is, "Do the mother's genes almost exclusively determine the sons' intelligence?". There are three sources proving the claim is notable. Is it true? The three sources happen to be different sources' comments on evidence presented in one Lancet paper; but the question would be just as valid if the three notable sources each cited different papers, or if they were unreferenced remarks in things like speeches or viral images. | {} | {'log_upvote_score': 5, 'links': ['https://skeptics.meta.stackexchange.com/questions/3683', 'https://skeptics.meta.stackexchange.com', 'https://skeptics.meta.stackexchange.com/users/214/']} | jdg_379582 |
stackexchange | llm_judgeable_groundtruth_similarity | 394168 |
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:
Shell: Bash. Goal: obtain time t in milliseconds since some fixed point in time, suitable for timestamping stuff with printf. Condition: the solution must pass the all-in-one-line-of-text test. Additional: the solution should be atomic (yeah, right!..), lightweight, keep quantization & rounding issues to a minimum, blah.. t=$[$(date +%s%N)/1000000] <--- my solution, the fixed point being Jan 1, 1970 in this case. BUT fundamentally bad due to the two date calls. printf "t=%d\n" $[$(date +%s%N)/1000000] <--- here it is, using printf. t=$(date +%s)$[10#$(date +%N)/1000000] <--- terrible example. Even seems to need de-pad of, then re-pad with, leading zeros. printf "t=%d%03d\n" $(date +%s) $[10#$(date +%N)/1000000] <--- here it is, using printf. Any better (sensible) suggestions? EDIT (appending): t=$(date +%s%N) and then printf "%s\n" ${t::13} <--- I guess, but not one line.
Now provide the response and nothing else.
| As noted by @Isaac, with date implementations that support %N like GNU's or ast-open's, you can use %s%3N to limit the precision, but except in ksh93 where date can be made to be the builtin version of ast-open's date , the date command is not builtin. It will take a few hundred if not thousand microseconds to start and a few more to print the date and return. bash did copy a subset of ksh93 printf '%(...)T' format, but not the %N part. Here it looks like you'd need to use more advanced shells like ksh93 or zsh . Those shells can make their $SECONDS variable which records the time since the shell started (and that you can also reset to any value) floating point: $ typeset -F SECONDS=0; date +%s%3N; echo $SECONDS15063187806470.0017870000 It took up to 1787 microseconds to run GNU date here. You can use $((SECONDS*1000)) to get a number of milliseconds as both shells support floating point arithmetic (beware ksh93 honours the locale's decimal mark). For the epoch time as a float, zsh has $EPOCHREALTIME : $ zmodload zsh/datetime$ echo $EPOCHREALTIME1506318947.2758708000 And ksh93 can use "$(printf '%(%s.%N)T' now)" (note that ksh93 's command substitution doesn't fork processes nor use pipes for builtins so is not as expensive as in other Bourne-like shells). You could also define the $EPOCHREALTIME variable there with: $ EPOCHREALTIME.get() { .sh.value=$(printf "%(%s.%6N)T");$ echo "$EPOCHREALTIME"1506333341.962697 For automatic timestamping, you can also use set -o xtrace and a $PS4 that prints the current time. In zsh : $ zsh -c 'PS4="+%D{%s.%.}> "; set -x; sleep 1; date +%s.%N'+1506332128.753> sleep 1+1506332129.754> date +%s.%N1506332129.755322928 In ksh93: $ ksh -c 'PS4="+\$(printf "%(%s.%3N)T")> "; set -x; sleep 1; date +%s.%N'+1506332247.844> sleep 1+1506332248.851> date +%s.%N1506332248.853111699 Depending on your use case, you may be able to rely on moreutils 's ts for your time-stamping: $ (date +%s.%6N; date +%s.%6N) | ts %.s1506319395.000080 1506319394.9706191506319395.000141 1506319394.971972 ( ts gives the time it read the line from date 's output through the pipe). Or for time between lines of output: $ (date +%s.%6N; date +%s.%6N) | ts -i %.s0.000011 1506319496.8065540.000071 1506319496.807907 If you want to get the time it took to run a given command (pipeline), you can also use the time keyword, adjusting the format with $TIMEFORMAT in bash : $ TIMEFORMAT=%E; time dateMon 25 Sep 09:51:41 BST 20170.002 Those time format directives initially come from csh (though bash , contrary to zsh or GNU time only supports a tiny subset). In (t)csh, you can time every command by setting the $time special variable: $ csh -xc 'set time = (0 %E); sleep 1; sleep 2'set time = ( 0 %E )sleep 10:01.00sleep 20:02.00 (the first number ( 0 here) tells that commands that take more than that many seconds should be timed, the second specifies the format). | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/394168', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/238486/']} | jdg_379583 |
stackexchange | llm_judgeable_groundtruth_similarity | 278281 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some data this dataABC = { {"a", 1, 2, 3}, {"b", 1, 3, 5}, {"c", 1, 2, 1}, {"a", 1, 2, 3}, {"a", 1, 1, 1}, {"c", 1, 1, 1}, {"b", 2, 2, 2} }; As you can see," a "," b" and "c" are followed by a series of numbers that represent their values. For example,if {"a",1,2,3} There are a lot of sublists like {"a",1,2,3} in the above data. So what I want to do now is take the average of a, b, c with respect to value1, value2, value3,My English is not very good, and the following picture can better illustrate what I mean. To find their average,I'm going to sort the data so that the "a", the "b", the "c" are all together,like this dataABC1 = dataABC // Sort Now what I'm going to do is I'm going to average them, and I don't know how to do that, right,I have tried using functions such as Select , Cases , etc. without success. What should I do?
Now provide the response and nothing else.
| GroupBy[dataABC, First -> Rest, Mean] <|"a" -> {1, 5/3, 7/3}, "b" -> {3/2, 5/2, 7/2}, "c" -> {1, 3/2, 1}|> Further, if required: FlattenAt[#, -1] & /@ (List @@@ Normal@GroupBy[dataABC, First -> Rest, Mean]) {{"a", 1, 5/3, 7/3}, {"b", 3/2, 5/2, 7/2}, {"c", 1, 3/2, 1}} More directly: (Mean of strings is a horrible idea but it works) ArrayReduce[Mean, #, 1] & /@ GatherBy[dataABC, First] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/278281', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/59284/']} | jdg_379584 |
stackexchange | llm_judgeable_groundtruth_similarity | 7936034 |
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 right-align the entries in a matplotlib axes legend (by default they are left-aligned), but can't seem to find any way of doing this. The setup I have is below: (I have added data and labels to my_fig axes using the ax.plot() command) ax = my_fig.get_axes()[0]legend_font = FontProperties(size=10)ax.legend(prop=legend_font, num_points=1, markerscale=0.5) There is a list of legend keyword arguments in the docs for matplotlib Axes , but there doesn't seem to be any straighforward way to set the alignment of the legend entries there. Anybody know of a backdoor way of doing this? Thanks. EDIT: To clarify what I am trying to achieve, right now my legend looks like: Maneuver: 12-OCT-2011 12:00 UTC Bias: 14-OCT-2011 06:00 UTC I want it to look like: Maneuver: 12-OCT-2011 12:00 UTC Bias: 14-OCT-2011 06:00 UTC
Now provide the response and nothing else.
| The backdoor you're looking for is the following: # get the width of your widest label, since every label will need # to shift by this amount after we align to the rightshift = max([t.get_window_extent().width for t in legend.get_texts()])for t in legend.get_texts(): t.set_ha('right') # ha is alias for horizontalalignment t.set_position((shift,0)) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7936034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/772487/']} | jdg_379585 |
stackexchange | llm_judgeable_groundtruth_similarity | 120019 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to understand the difference between procedural languages like C and object-oriented languages like C++. I've never used C++, but I've been discussing with my friends on how to differentiate the two. I've been told C++ has object-oriented concepts as well as public and private modes for definition of variables: things C does not have. I've never had to use these for while developing programs in Visual Basic.NET: what are the benefits of these? I've also been told that if a variable is public, it can be accessed anywhere, but it's not clear how that's different from a global variable in a language like C. It's also not clear how a private variable differs from a local variable. Another thing I've heard is that, for security reasons, if a function needs to be accessed it should be inherited first. The use-case is that an administrator should only have as much rights as they need and not everything, but it seems a conditional would work as well: if ( login == "admin") { // invoke the function} Why is this not ideal? Given that there seems to be a procedural way to do everything object-oriented, why should I care about object-oriented programming?
Now provide the response and nothing else.
| All answers so far have focused on the topic of your question as stated, which is "what is the difference between c and c++". In reality, it sounds like you know what difference is, you just don't understand why you would need that difference. So then, other answers attempted to explain OO and encapsulation. I wanted to chime in with yet another answer, because based on the details of your question, I believe you need to take several steps back. You don't understand the purpose of C++ or OO, because to you, it seems that your application simply needs to store data. This data is stored in variables."Why would I want to make a variable inaccessible? Now I can't access it anymore! By making everything public, or better yet global, I can read data from anywhere and there are no problems." - And you are right, based on the scale of the projects you are currently writing, there are probably not that many problems (or there are, but you just haven't become aware of them yet). I think the fundamental question you really need to have answered is: "Why would I ever want to hide data? If I do that, I can't work with it!"And this is why: Let's say you start a new project, you open your text editor and you start writing functions. Every time you need to store something (to remember it for later), you create a variable. To make things simpler, you make your variables global.Your first version of your app runs great. Now you start adding more features. You have more functions, certain data you stored from before needs to be read from your new code. Other variables need to be modified. You keep writing more functions. What you may have noticed (or, if not, you absolutely will notice in the future) is, as your code gets bigger, it takes you longer and longer to add the next feature. And as your code gets bigger, it becomes harder and harder to add features without breaking something that used to work.Why?Because you need to remember what all your global variables are storing and you need to remember where all of them are being modified. And you need to remember which function is okay to call in what exact order and if you call them in a different order, you might get errors because your global variables aren't quite valid yet.Have you ever run into this? How big are your typical projects (lines of code)?Now imaging a project 5000 to 50000 times as big as yours. Also, there are multiple people working in it. How can everyone on the team remember (or even be aware of) what all those variables are doing? What I described above is an example of perfectly coupled code. And since the dawn of time (assuming time started Jan 1, 1970), human kind has been looking for ways to avoid these problems. The way you avoid them is by splitting up your code into systems, subsystems and components and limiting how many functions have access to any piece of data. If I have 5 integers and a string that represent some kind of state, would it be easier for me to work with this state if only 5 functions set/get the values? or if 100 functions set/get these same values?Even without OO languages (i.e. C), people have been working hard on isolating data from other data and creating clean separation boundaries between different parts of the code. When the project gets to a certain size, ease of programming becomes not, "can I access variable X from function Y", but "how do I make sure ONLY functions A, B, C and no one else is touching variable X". This is why OO concepts have been introduced and this is why they are so powerful. They allow you to hide your data from yourself and you want to do it on purpose, because the less code that sees that data, the less chance there is, that when you add the next feature, you will break something. This is the main purpose for the concepts of encapsulation and OO programming. They allow you to break our systems/subsystems down into even more granular boxes, to a point where, no matter how big the overall project is, a given set of variables may only be accessed by 50-200 lines of code and that's it! There's obviously much more to OO programming, but, in essence, this is why C++ gives you options of declaring data/functions as private, protected or public. The second greatest idea in OO is the concept of abstraction layers. Although procedural languages can also have abstractions, in C, a programmer must make a conscious effort to create such layers, but in C++, when you declare a class, you automatically create an abstraction layer (it's still up to you whether or not this abstraction will add or remove value). You should read/research more about abstraction layers and if you have more questions, I'm sure this forum will be more than happy to answer those as well. | {} | {'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/120019', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/35064/']} | jdg_379586 |
stackexchange | llm_judgeable_groundtruth_similarity | 4601324 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$a_{n+1} = 0.25((a_n)^2+a_n+2)$ , where $a_1 = 3$ . By showing that $(a_n)$ is increasing, deduce that $(a_n)$ does not converge. I showed that it is increasing by induction. For base case $3.5 \geq 3$ so true for $n=1$ . Assume for some $k \in N$ that $a_{k+1} \geq a_k$ . Now for inductive step, by assumption $a_{k+1} \geq a_k$ , so $(a_{k+1})^2 \geq (a_k)^2$ , so $(a_{k+1})^2 + a_{k+1} \geq (a_k)^2$ using assumption. In all, we end up with $0.25((a_{k+1})^2+a_{k+1}+2) \geq 0.25((a_n)^2+a_n+2)$ as required. I then said that since $(a_n)$ is increasing and unbounded above, it clearly does not converge. However, am I not sure how to show that it is not unbounded above. Can someone help me please ?
Now provide the response and nothing else.
| The first definition is what I will call a sheaf (of Abelian groups). The second definition I will call an etale space (of Abelian groups). The two categories are equivalent. Let’s begin with an etale space. We can construct a sheaf by defining $\mathscr{F}(U) = \{f : U \to \mathcal{F} \mid f$ is continuous and $\pi \circ f = 1|_U\}$ . Here, $1|_U : U \to X$ is the inclusion function. Such an $f : U \to X$ is said to be a “partial section” of $\pi$ , and $\mathscr{F}$ is said to be the “sheaf of sections of $\pi$ ”. We then define the group operations in the obvious way. Note that this construction doesn’t require $\pi$ to be a local homeomorphism. $\DeclareMathOperator{colim}{colim}$ To go the other way, we begin with a sheaf $\mathscr{F}$ . Then we define $\mathcal{F}$ as follows. The underlying set is $\coprod\limits_{x \in X} \colim\limits_{x \in U} \mathscr{F}(U)$ . Recall that for a fixed $x$ , $\colim_{x \in U} \mathscr{F}(U)$ is the set of stalks at $x$ . So this space is the space of all stalks. The map $\pi : \mathcal{F} \to X$ is defined in the obvious way, sending a stalk at $x$ to point $x$ . And the topology on $\mathcal{F}$ has basic open sets of the form $\{(x, [S]) \mid x \in V\}$ , where $V \subseteq X$ is open and $S \in \mathscr{F}(V)$ . The group operations are just the stalkwise group operations. Note that this construction doesn’t require $\mathscr{F}$ to be a sheaf, merely a presheaf. These constructions are inverse equivalences of the category of sheaves and the category of etale spaces. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4601324', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1071088/']} | jdg_379587 |
stackexchange | llm_judgeable_groundtruth_similarity | 12466493 |
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 dataframe in a wide format, with repeated measurements taken within different date ranges. In my example there are three different periods, all with their corresponding values. E.g. the first measurement ( Value1 ) was measured in the period from DateRange1Start to DateRange1End : ID DateRange1Start DateRange1End Value1 DateRange2Start DateRange2End Value2 DateRange3Start DateRange3End Value31 1/1/90 3/1/90 4.4 4/5/91 6/7/91 6.2 5/5/95 6/6/96 3.3 I'm looking to reshape the data to a long format such that the DateRangeXStart and DateRangeXEnd columns are grouped,. Thus, what was 1 row in the original table becomes 3 rows in the new table: ID DateRangeStart DateRangeEnd Value1 1/1/90 3/1/90 4.41 4/5/91 6/7/91 6.21 5/5/95 6/6/96 3.3 I know there must be a way to do this with reshape2 / melt / recast / tidyr , but I can't seem to figure it out how to map the multiple sets of measure variables into single sets of value columns in this particular way.
Now provide the response and nothing else.
| Reshaping from wide to long format with multiple value/measure columns is possible with the function pivot_longer() of the tidyr package since version 1.0.0 . This is superior to the previous tidyr strategy of gather() than spread() (see answer by @AndrewMacDonald), because the attributes are no longer dropped (dates remain dates and numerics remain numerics in the example below). library("tidyr")library("magrittr")a <- structure(list(ID = 1L, DateRange1Start = structure(7305, class = "Date"), DateRange1End = structure(7307, class = "Date"), Value1 = 4.4, DateRange2Start = structure(7793, class = "Date"), DateRange2End = structure(7856, class = "Date"), Value2 = 6.2, DateRange3Start = structure(9255, class = "Date"), DateRange3End = structure(9653, class = "Date"), Value3 = 3.3), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame")) pivot_longer() (counterpart: pivot_wider() ) works similar to gather() .However, it offers additional functionality such as multiple value columns.With only one value column, all colnames of the wide data set would go into one long column with the name given in names_to .For multiple value columns, names_to may receive multiple new names. This is easiest if all column names follow a specific pattern like Start_1 , End_1 , Start_2 , etc.Therefore, I renamed the columns in the first step. (names(a) <- sub("(\\d)(\\w*)", "\\2_\\1", names(a)))#> [1] "ID" "DateRangeStart_1" "DateRangeEnd_1" #> [4] "Value_1" "DateRangeStart_2" "DateRangeEnd_2" #> [7] "Value_2" "DateRangeStart_3" "DateRangeEnd_3" #> [10] "Value_3"pivot_longer(a, cols = -ID, names_to = c(".value", "group"), # names_prefix = "DateRange", names_sep = "_")#> # A tibble: 3 x 5#> ID group DateRangeEnd DateRangeStart Value#> <int> <chr> <date> <date> <dbl>#> 1 1 1 1990-01-03 1990-01-01 4.4#> 2 1 2 1991-07-06 1991-05-04 6.2#> 3 1 3 1996-06-06 1995-05-05 3.3 Alternatively, the reshape may be done using a pivot spec that offers finer control (see link below): spec <- a %>% build_longer_spec(cols = -ID) %>% dplyr::transmute(.name = .name, group = readr::parse_number(name), .value = stringr::str_extract(name, "Start|End|Value"))pivot_longer(a, spec = spec) Created on 2019-03-26 by the reprex package (v0.2.1) See also: https://tidyr.tidyverse.org/articles/pivot.html | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12466493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/722869/']} | jdg_379588 |
stackexchange | llm_judgeable_groundtruth_similarity | 34523 |
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:
While looking for solutions to entropy pool depletion on virtual machines, I came across an interesting project called haveged , which is based on the HAVEGE algorithm (HArdware Volatile Entropy Gathering and Expansion). It makes a pretty fantastic claim. HAVEGE is a random number generator that exploits the modifications of the internal CPU hardware states (caches, branch predictors, TLBs) as a source of uncertainty. During an initialization phase, the hardware clock cycle counter of the processor is used to gather part of this entropy: tens of thousands of unpredictable bits can be gathered per operating system call in average. If this really produces nearly unlimited high-quality entropy on headless virtual machines, it should be included in every server distribution by default! And yet, some people have raised concerns. "At its heart, [HAVEGE] uses timing information based on the processor's high resolution timer (the RDTSC instruction). This instruction can be virtualized, and some virtual machine hosts have chosen to disable this instruction, returning 0s or predictable results." (Source: PolarSSL Security Advisory 2011-02 on polarssl.org). And furthermore, popular NIST and ENT tests will sometimes give haveged a PASS even when it's intentionally mis-configured, and not actually producing random numbers! I replaced the “HARDTICKS” macro in HAVEGE with the constant 0 (zero) rather than reading the time stamp counter of the processor. This immediately failed the randomness test. However, when I used the constant 1 (one) instead, the ent test passed. And even nist almost passed with only a single missed test out of the 426 tests executed. (Source: Evaluating HAVEGE Randomness on engbloms.se). So, which virtualization platforms/hypervisors are safe to use with haveged in a virtual machine? And is there a generally accepted best practice way to test whether a source of randomness is producing sufficiently high quality numbers?
Now provide the response and nothing else.
| ( Caveat: I certainly don't claim that HAVEGE lives up to its claims. I have not checked their theory or implementation.) To get randomness, HAVEGE and similar systems feed on "physical events", and in particular on the timing of physical events. Such events include occurrences of hardware interrupts (which, in turn, gathers data about key strokes, mouse movements, incoming ethernet packets, time for a hard disk to complete a write request...). HAVEGE also claims to feed on all the types of cache misses which occur in a CPU (L1 cache, L2 cache, TLB, branch prediction...); the behaviour of these elements depends on what the CPU has been doing in the previous few thousands clock cycles, so there is potential for some "randomness". This hinges on the possibility to measure current time with great precision (not necessarily accuracy), which is where the rdtsc instruction comes into play. It returns the current contents of an internal counter which is incremented at each clock cycle, so it offers sub-nanosecond precision. For a virtual machine system, there are three choices with regards to this instruction: Let the instruction go to the hardware directly. Trap the instruction and emulate it. Disable the instruction altogether. If the VM manager chooses the first solution, then rdtsc has all the needed precision, and should work as well as if it was on a physical machine, for the purpose of gathering entropy from hardware events. However, since this is a virtual machine, it is an application on the host system; it does not get the CPU all the time. From the point of view of the guest operating system using rdtsc , this looks as if its CPU was "stolen" occasionally: two successive rdtsc instructions, nominally separated by a single clock cycles, may report an increase of the counter by several millions . In short words, when rdtsc is simply applied on the hardware, then the guest OS can use it to detect the presence of an hypervisor. The second solution is meant to make the emulation more "perfect" by maintaining a virtual per-VM cycle counter, which keeps track of the cycles really allocated to that VM. The upside is that rdtsc , from the point of view of the guest, will no longer exhibit the "stolen cycles" effect. The downside is that this emulation is performed through triggering and trapping a CPU exception, raising the cost of the rdtsc opcode from a few dozen clock cycles (it depends on the CPU brand; some execute rdtsc in less than 10 cycles, other use 60 or 70 cycles) to more than one thousand of cycles. If the guest tries to do a lot of rdtsc (as HAVEGE will be prone to do), then it will slow down to a crawl. Moreover, the exception handling code will disrupt the measure; instead of measuring the hardware event timing, the code will measure the execution time of the exception handler, which can conceivably lower the quality of the extracted randomness. The third solution (disabling rdtsc ) will simply prevent HAVEGE from returning good randomness. Since it internally uses a PRNG , the output may still fool statistical analysis tools, because there is a huge difference between "looking random" and "being unpredictable" (statistical analysis tools follow the "look random" path, but cryptographic security relies on unpredictability). The VirtualBox manual claims that VirtualBox, by default, follows the first method ( rdtsc is unconditionally allowed and applied on the hardware directly), but may be configured to apply the second solution (which you don't want, in this case). To test what your VM does, you can try this small program (compile with gcc -W -Wall -O on Linux; the -O is important): #include <stdio.h>#if defined(__i386__)static __inline__ unsigned long long rdtsc(void){ unsigned long long int x; __asm__ __volatile__ (".byte 0x0f, 0x31" : "=A" (x)); return x;}#elif defined(__x86_64__)static __inline__ unsigned long long rdtsc(void){ unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );}#endifintmain(void){ long i; unsigned long long d; d = 0; for (i = 0; i < 1000000; i ++) { unsigned long long b, e; b = rdtsc(); e = rdtsc(); d += e - b; } printf("average : %.3f\n", (double)d / 1000000.0); return 0;} On a non-virtual machine, with the "true" rdtsc , this shall report a value between 10 and 100, depending on the CPU brand. If the reported value is 0, or if the program crashes, then rdtsc is disabled. If the value is in the thousands, then rdtsc is emulated, which means that the entropy gathering may not work as well as expected. Note that even getting a value between 10 and 100 is not a guarantee that rdtsc is not emulated, because the VM manager, while maintaining its virtual counter, may subtract from it the expected time needed for execution of the exception handler. Ultimately, you really need to have a good look at the manual and configuration of your VM manager. Of course, the whole premise of HAVEGE is questionable. For any practical security, you need a few "real random" bits, no more than 200, which you use as seed in a cryptographically secure PRNG . The PRNG will produce gigabytes of pseudo-alea indistinguishable from true randomness, and that's good enough for all practical purposes. Insisting on going back to the hardware for every bit looks like yet another outbreak of that flawed idea which sees entropy as a kind of gasoline, which you burn up when you look at it. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/34523', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/1092/']} | jdg_379589 |
stackexchange | llm_judgeable_groundtruth_similarity | 203318 |
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 read the following piece of code: dd if=/dev/urandom bs=16 count=1 2>/dev/null | md5sum Apparently, this code was used as a trick to produce a hex string key from a 128-bit binary pseudo-random value. Someone here claimed this is inherently insecure since it passes a cryptographically secure random value through an "insecure hash function". On my side, I would say the collision flaws in md5 are irrelevant here since the hash function input and output have the same size. And so, the hash function output is as random as its input. What's your opinion about that? Does hashing an N-bit random key to produce an N-bits hash change the randomness of the key?
Now provide the response and nothing else.
| Hashing is a deterministic process which means that it can never increase the randomness. But of course it can decrease the randomness: if you hash a 200 bit random value with some hash algorithms which only outputs 160 bits (like SHA-1) then of course the resulting value can never have 200 bits randomness. But as long as the number of input bits is significantly lower than the output size of the hash it will not reduce the randomness, providing a cryptographic hash is used. If the input size is exactly the same as the input size as in your example the resulting randomness is likely not significantly decreased when using a cryptographic hash. And you are right that collision resistance does not matter for this. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/203318', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/157534/']} | jdg_379590 |
stackexchange | llm_judgeable_groundtruth_similarity | 1385795 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A discrete random variable is said to have a Poisson distribution if its possible values are the non-negative integers and if, for any non-negative integer $k$, $$P(X=k)=e^{-\lambda}\frac{\lambda^k}{k!}$$ where $\lambda>0$. It turns out that $E(X)=\lambda$. Minitab has a calculator for calculating Poisson probabilities, which is very similar to the calculator for Binomial probabilities. The Poisson distribution model is widely used for modeling the number of "rare" events. Suppose we have a Poisson random variable $X$ with mean (or expected value) equal to $2$ and another Poisson random variable $Y$ with mean $3$. Suppose $X$ and $Y$ are independent random variables, in which case $W = X+Y$ will be a Poisson random variable with mean equal to $5 (= 2+3)$. Find the conditional probability that $X = 5$ given that $W = 10$.
Now provide the response and nothing else.
| $$\frac{\Pr(X=5\ \&\ W=10)}{\Pr(W=10)} = \frac{\Pr(X=5\ \&\ Y=5)}{\Pr(W=10)}$$ The event $(X=5\ \&\ W=10)$ is the same as $(X=5\ \&\ Y=5)$. Then use independence of $X$ and $Y$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1385795', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/237361/']} | jdg_379591 |
stackexchange | llm_judgeable_groundtruth_similarity | 34924581 |
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 add tape testing to my react/redux app. I can't find a way for my app to work both for testing and running. With this .babelrc configuration tests don't run but app works fine: { "stage": 2, "env": { "development": { "plugins": [ "react-transform" ], "extra": { "react-transform": { "transforms": [{ "transform": "react-transform-hmr", "imports": ["react"], "locals": ["module"] }] } } } }} With this .babelrc configuration tests work fine but npm start throws an error: Module build failed: ReferenceError: [BABEL] { "presets": ["es2015", "react"]} How to merge those two files so that both running and testing would work? Here is my package.json: { "name": "add-projects", "version": "0.0.0", "description": "Add projects", "scripts": { "start": "node server.js" }, "repository": { "type": "git", "url": "https://github.com/rackt/redux.git" }, "license": "MIT", "bugs": { "url": "https://github.com/rackt/redux/issues" }, "homepage": "http://rackt.github.io/redux", "dependencies": { "immutable": "^3.7.6", "react": "^0.14.0", "react-dom": "^0.14.0", "react-redux": "^4.0.0", "redux": "^3.0.0", "redux-thunk": "^0.1.0", "redux-undo": "^0.5.0" }, "devDependencies": { "babel-core": "^5.6.18", "babel-loader": "^5.1.4", "babel-plugin-react-transform": "^1.1.0", "babel-preset-es2015": "^6.3.13", "babel-preset-react": "^6.3.13", "babel-tape-runner": "^2.0.0", "enzyme": "^2.0.0-rc1", "expect": "^1.6.0", "express": "^4.13.3", "jsdom": "^7.2.2", "node-libs-browser": "^0.5.2", "react-addons-test-utils": "^0.14.6", "react-transform-hmr": "^1.0.0", "tape": "^4.4.0", "tape-run": "^2.1.2", "webpack": "^1.9.11", "webpack-dev-middleware": "^1.2.0", "webpack-hot-middleware": "^2.2.0" }} Here is the server.js: var webpack = require('webpack')var webpackDevMiddleware = require('webpack-dev-middleware')var webpackHotMiddleware = require('webpack-hot-middleware')var config = require('./webpack.config')var app = new (require('express'))()var port = 3000var compiler = webpack(config)app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath }))app.use(webpackHotMiddleware(compiler))app.get("/", function(req, res) { res.sendFile(__dirname + '/index.html')})app.listen(port, function(error) { if (error) { console.error(error) } else { console.info("==> Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port) }}) webpack.config.js: var path = require('path')var webpack = require('webpack')module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ 'webpack-hot-middleware/client', './index' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [{ test: /\.js$/, loaders: ['babel'], exclude: /node_modules/, include: __dirname }] }}// When inside Redux repo, prefer src to compiled version.// You can safely delete these lines in your project.var reduxSrc = path.join(__dirname, '..', '..', 'src')var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules')var fs = require('fs')if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) { // Resolve Redux to source module.exports.resolve = { alias: { 'redux': reduxSrc } } // Compile Redux from source module.exports.module.loaders.push({ test: /\.js$/, loaders: ['babel'], include: reduxSrc })}
Now provide the response and nothing else.
| Set up different environments in your .babelrc { "env": { "dev": { "presets": ["es2015"], "plugins":["x"] }, "test": { "presets": ["es2015"] } }} And then run babel after you have set your BABEL_ENV BABEL_ENV=test <commandhere> or BABEL_ENV=dev <commandhere> If you don't set BABEL_ENV , babel will use the NODE_ENV value.If you don't set either BABEL_ENV nor NODE_ENV , it will use 'development'. CODE BELOW: function getEnv(defaultValue = "development") { return process.env.BABEL_ENV || process.env.NODE_ENV || defaultValue;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34924581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5468128/']} | jdg_379592 |
stackexchange | llm_judgeable_groundtruth_similarity | 245059 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking to turn on and off the throughput of an HDMI signal via a microcontroller. Would four ICs such as the SN74LS08N AND gate be enough? Or do HDMI signals need something more complex?
Now provide the response and nothing else.
| Absolutely not. First: HDMI uses TMDS signaling. This is not compatible with TTL logic gates; it's a current-mode differential protocol, very different from the single-ended outputs used in TTL logic. Second: The TMDS signals used by HDMI run at over 1 GHz. This is far faster than the 74LS parts you're looking at can handle; indeed, I don't think it's compatible with through-hole parts at all. (The pins alone will have too much inductance for this fast of a signal.) Consider using a dedicated HDMI switching part, such as the TI TMDS261B ("2 to 1 HDMI switch") or the Fairchild FDHDMI08 ("Wide-Bandwidth Differential Signaling HDMI Switch"). | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/245059', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/89186/']} | jdg_379593 |
stackexchange | llm_judgeable_groundtruth_similarity | 200528 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I've been reading a little bit about the definition of symmetries on General Relativity, and they are related with the concept of Killing vector , i.e., vectors along which the Lie derivative of the metric vanishes $\mathcal{L}_X g =0$. However, afaik the most symmetric geometrical object is the Ricci tensor ( see the post ), and the a vector $X$ satisfying $\mathcal{L}_X \text{Ric} = 0$ is known as a collineation of the Ricci tensor. I'd like to know whether is possible to define a sort of Lie derivative for a (general) connection, or a way to somehow define the symmetries of a connection.
Now provide the response and nothing else.
| Of course, yes. Lie derivative is defined for any geometric object (= when it is defined what happends when we change a coordinate system): take the flow $\phi_t$ of the vector field, consider the pullback $\phi_t^*\Gamma$ of your geometric object $\Gamma$ and define Lie derivative as the $\tfrac{d}{dt}$-derviative at $t=0$ of $\phi_t^*\Gamma$. For affine connection its Lie derivative is an (1,2)-tensor field. It is because derivative is more or less the same as difference and difference of two connections is a (1,2)-tensor field. Of course if the Lie derivative of a connection is zero then the connection is presered by the flow so you vector field is a symmetry of the connection. Of course there exists an algebraic formula for the Lie derivative in terms of the components of an object in the coordinates ($\sim$ Christoffel symbols, for example), components of the vector field, and their first derivatives. I do not remember this formula by hart but Maples DifferentialGeometry package knows it. It is a sum of two terms, the first part is the usual formula of the Lie derivative for a (1,2)-tensorfield and the other part is something like the vector field plugged in the curvature. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/200528', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25356/']} | jdg_379594 |
stackexchange | llm_judgeable_groundtruth_similarity | 33243661 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My Django project structure is: /proj /frontend /server /proj /app1 /app2 manage.py How do I run python manage.py startapp app_name so that my newly created apps are within the /server directory? I tried running django-admin.py startapp appname within the server directory to create the app but I would end up with this error: $ ./manage.py runserverTraceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/django/core/management/__init__.py", line 343, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/django/core/management/__init__.py", line 177, in fetch_command commands = get_commands() File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/django/utils/lru_cache.py", line 101, in wrapper result = user_function(*args, **kwds) File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/django/core/management/__init__.py", line 72, in get_commands for app_config in reversed(list(apps.get_app_configs())): File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/django/apps/registry.py", line 137, in get_app_configs self.check_apps_ready() File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.")django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Now provide the response and nothing else.
| You can specify the path to ./server/appname directory after appname as the destination i.e. where the Django app directory structure will be created. From the startapp docs: startapp <app_label> [destination] # startapp command usage Creates a Django app directory structure for the given app name in thecurrent directory or the given destination. If only the app name is given, the app directory will be created inthe current working directory. If the optional destination is provided, Django will use that existingdirectory rather than creating a new one So, you can specify the path to your ./server/appname directory as the destination value. django-admin.py startapp appname [destination] # specify destination What you need to do? 1. You need to first create a directory appname inside /server . mkdir ./server/appname # create directory from root level 2. Then, run the startapp command to create the app. django-admin.py startapp appname ./server/appname | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33243661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1815710/']} | jdg_379595 |
stackexchange | llm_judgeable_groundtruth_similarity | 347450 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I recently took on this project: https://www.youtube.com/watch?v=WIMhraVcdTg Trying to use a disposable camera as an EMP generator. I wrapped my wire around a bottle, but it still won't do anything, except I do hear a little spark in the push button. It goes through the coil but doesn't seem to have any effect. I connected the coil directly to the capacitor leads with a button and ON/OFF switch. What are some things that would cause the capacitor and coil to not make the EM Field or EMP? I'm starting to think the coil is not correctly set up or is wound incorrectly. Is there a requirement I may be missing, for this coil to create the desired effect? Here is my schematic: simulate this circuit – Schematic created using CircuitLab Here is my coil and circuit, what do you guys think is the problem? Do I need a different coil or what? Here is a schematic of the camera, may not be exactly what I am using but a close equivalent:
Now provide the response and nothing else.
| Of course it is generating an EMP. I'm sure it works fine. The spark you mention when flipping the switch, that would only occur if it worked. The coil you've wound is a type of electromagnet called a solenoid. If the coil form that it is wrapped around is hollow (which it might be, it looks like a container for something, not sure what), try placing something magnetic (like a screw driver) near the middle of the coil, and flip the switch - you should feel a brief but sharp 'tug' on the screw driver. This way you can actually know for sure if everything is working or not. Believe it or not, I made something very similar to this, though it uses SCRs rather than a switch and has some larger but lower voltage capacitors, along with some circuitry that makes the thing auto-trigger once the capacitors reach a certain voltage. Using a beefy power supply, it pulses at maybe 2-3Hz. What do I use it for? Magnetizing screw drivers! Seriously. That's why I built it. Each pulse is like a turbocharged swipe along a magnet, only, in very little time, it will magnetize stuff very well instead of having to drag it against a magnet over and over 100 times. Honestly, what you have built right now is way more useful and you could use it to magnetize stuff... but it's going to be rather poor at generating EMPs. I'd stick with what you have, but if you really want to be the scourge of dollar store calculators.... well, we all need a hobby. The reason your device isn't causing any problems for whatever poor calculator you're testing it on is your coil geometry and coil inductance. What I don't understand is why you didn't simply follow the directions in the video. It would work if you did. He says wind about 5 turns, which is roughly what you'd want for a coil the size he's wound. But you inexplicably wound 40 turns. This should be self-evident, but its worth repeating: to get the same results, you have to actually follow the directions. 5 turns and 40 turns is going to be completely different in nature. Inductance is proportional to the square of the number of turns.. so your 40 turn coil has 64 times more inductance than the same sized coil, but with 5 turns. Of course it doesn't behave the same way. Inductance is measured in Henries, with a Henry being equal to a Volt-second per Ampere. Which probably sounds nonsensical at first. One way to look at it that is relevant to your project is this: Something with 1 Henry of inductance, if connected to 1V, will take one second for the current flowing through it to reach an amp. Or, more simply, lots of inductance makes current actually take time to build up. If you have a 1H inductor, then regardless of the voltage across it, it will take an entire second for the current to reach what ohm's law says it should be. Long story short, your coil has way too much inductance. It's slowing down the pulse, making it take much too long and instead of an EMP, which is like a balloon popping, you're doing something more like slowly letting the air out of an untied balloon. All of the 'destructive'/interference properties of EMPs are derived from the speed (or rather, short duration) of the pulse. Also, your coil geometry is the worst possible geometry for what you want to do. It is a solenoid geometry, which focuses most of the electromagnetic energy at the middle of the coil, directly at the half-way point along its length. Very little actually makes it outside the coil, and what does is concentrated at the top and bottom (axially) of the coil. And essentially zero field will be at the sides of coil, which is the only part of the coil you could even get near a calculator due to your construction. The white thing its wrapped around is filling all the spots where there is any useful amounts of anything going on, so even if it did have the right number of turns, you still couldn't get the calculator in the right spot. You want the coil to be as flat as possible. Like a pancake. In fact, they call them pancake coils. Pretty much the exact opposite of your current coil. But, that's not even really an issue since with approximately 5-6 turns, you can't really give the coil much shape anyway. Also, make sure to keep the air gap (the 'hole' at the coil center) close to what you see in the video. Make it too big, and you'll again have too much inductance. Too small, and not enough. But, this is good news, because it will take you like 15 seconds to construct the correct coil. If it doesn't work, well... it isn't going to work on every calculator. It almost certainly won't work on virtually everything except really cheap and small/thin give-way calculators. It needs to be directly on top of the calculator, and if its casing is too thick, this alone might introduce enough distance to prevent anything from happening. This thing cannot produce a meaningful amount of far-field electromagnetic radiation, so it works entirely on near-field stuff. Near-field falls off at radius cubed . It takes almost no distance at all to make it not work. With that in mind, experiment by slowly adding turns to the coil, one at a time, up to maybe as many as 10 turns. If that doesn't do anything to the calculator, you might try 4 or 3 turns, or add a second capacitor for more oomph and try again with 5 turns, slowly working up to 10 like before. If it won't kill (or at least noticeably affect) the calculator after that, it's simply because the EMP generated is incredibly weak and that calculator is not crappy enough to succumb to the interference. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/347450', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/134042/']} | jdg_379596 |
stackexchange | llm_judgeable_groundtruth_similarity | 41922 |
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:
Here is the module I am looking at: 1.8" Serial 128X160 SPI TFT LCD Module Display + PCB Adapter with SD Socket So my question is, is there any way I could convert a video signal from a composite source (i.e. DVD player, game console, etc.) to something which this module could process and display correctly? Or if you have any other suggestions for a similar sized display which can easily interface (or be made to interface) with a composite video source, please let me know. Thank you.
Now provide the response and nothing else.
| This is going to be an extremely tedious project to get working. Here's how to do it, though: Sample the composite video signal at 5.5 MHz (the bandwidth of composite video) using a high-bandwidth ADC. Look for the line sync pulse. Once you've got that, you have a line of video in your buffer. Looking in your buffer, find the colorburst section of the data. This will let you split up the data into the two parts (luminance and chrominance) Since your LCD is a 160 pixels long, bin the luminance signal into 160 bins. Average each bin's value. This is the value of the luminance at that pixel. The color burst is going to be tricky. You're going to need to demodulate the quadrature encoded signal into the two color signals by looking at the phase differences of the signals. That's going to be some hardcore DSP. Once you're done with that, you have your two extracted color signals. Repeat the binning process for the first extracted color signal. This is your Cb signal. Repeat the binning process for the second extracted color signal (the one that's quadrature-encoded). This is your Cr signal. Repeat this process for each line of video until you get to the end of the field. Now, you need to repeat this for the next field. Remember that NTSC composite sends video interlaced, and not progressive. After this is done, you should have an array of CIE YCbCr values that is 160 pixels wide by about 525 lines tall. You need to compress the lines of video down to 128 (the height of the display). Average over the vertical column in your pixel array to find the separate Y, Cb, and Cr values for each pixel. Since your display uses RGB instead of CIE YPbPr, you'll need to convert each pixel to RGB. There's fixed-point formulas available that are optimal for doing it on a computer. As soon as you've got the RGB array, you'll need to write the data out to the display using the SPI interface. The display will have a protocol that explains how to write data to it. Pitfalls By averaging and binning the pixels without doing bicubic or any other sort of smart sampling, you're going to get terrible aliasing that makes the video look jaggedy and weird. Since it's doubtful that your SPI clock is fast enough to write data to the display fast enough, you'll experience dropped frames. You'll need to ensure your controller can deal with that. Other ideas Don't reinvent the wheel. eBay sells a ton of wearable displays (with small screens) with composite inputs. I'd start with something like that and hack it to fit your application. Just remember to remove the optic in front of the piece that throws the image further away to make it easier for your eye to focus on (unless you want that, that is...) | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/41922', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/10917/']} | jdg_379597 |
stackexchange | llm_judgeable_groundtruth_similarity | 24045245 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Assume a setup like this: You have an Xcode 6 project, where you've implemented your own classes (say MyView and MyViewController) with both Objective-C and Swift You have added a Playground into your project In the Playground, it's possible to import modules (frameworks) like UIKit with the import keyword. How do you enable access to the project's other classes from the Playground? Just trying to access project classes directly results with an error message: Use of unresolved identifier 'MyView'
Now provide the response and nothing else.
| As of Xcode 6.0 Beta 5, it is now possible to import your own frameworks into a playground. This provides a way to share code between your applications and playgrounds, which can both import your frameworks. To do this: Your playground must be in the same workspace as the project that produces your framework. Your workspace must contain a target that produces the framework, instead of using a pre-built framework. You must have already built your framework. If it is an iOS framework, it must be built for a 64-bit run destination (e.g. iPhone 5s), and must be built for the Simulator. You must have an active scheme which builds at least one target (that target's build location will be used in the framework search path for the playground). Your "Build Location" preference (in advanced "Locations" settings of Xcode) should not be set to "Legacy". If your framework is not a Swift framework the "Defines Module" build setting must be set to "Yes". You must add an import statement to your playground for the framework. Once all these conditions are fulfilled, importing your framework will work in a playground. In Xcode 7 we introduced another mechanism that you can use to import your own classes as source, instead of importing a framework; you can read about this "Auxiliary Sources" support at http://help.apple.com/xcode/mac/8.0/#/devfa5bea3af | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24045245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2155985/']} | jdg_379598 |
stackexchange | llm_judgeable_groundtruth_similarity | 210891 |
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 $B$ be a commutative $A$-algebra, and let $M$, $N$ be two $B$-modules. We can talk about the set of $A$-linear module homomorphisms $M \to N$, i.e. the set $\text{Hom}_A(M, N)$. Differential operators of order zero should be the $B$-linear maps from $M$ to $N$, i.e. $\text{Hom}_B(M, N)$. First, note that the commutator $[f, b]$ (where $b \in B$) is a well-defined morphism $M \to N$. Then we make our first definition, the "Weyl Algebra" one. Definition 1 (Weyl Algebra). Let $\mathcal{D}_A^0(M, N) = \text{Hom}_B(M, N)$. Define $$\mathcal{D}_A^n(M, N) = \{f \in \text{Hom}_A(M, N) \text{ such that }[f, b] \in \mathcal{D}_A^{n-1}(M,N)\}.$$We set $\mathcal{D}_A(M, N) = \bigcup_{n \ge 0}\mathcal{D}_A^n(M, N)$. In order to formulate the crystalline definition, we introduce some notation. Let $D: M \to N$ be an $A$-linear map. Then, $D$ induces the map $\overline{D}: \delta_{B/A} \otimes_B M\to N$. We now have our "Crystalline" definition. Definition 2 (Crystalline). Let $I$ be the kernel of the diagonal map (i.e., the map $B \otimes_A B \to B, \ b \otimes b' \mapsto bb'$). Then $D: M \to N$ is said to be a differential operator of order $\le n$ if $\overline{D}$ annihilates $I^{n+1} \otimes_B M$. Let $\mathcal{D}_A^n(M, N)$ be the $B$-module of differential operators of order $\le n$. We define $\mathcal{D}_A(M, N) = \bigcup_{n \ge 0} \mathcal{D}_A^n(M, N)$. My question is, what is the easiest way to see that/the intuition behind the definitions of rings of differential operators between modules given above are equivalent? EDIT: In the comments, Michael Bächtold is asking me to spell out the definition of $\delta_{B/A}$ and $\overline{D}$. So say we have $B$ a commutative $A$-algebra. We want to formalize the notion of an $A$-linear endomorphism of $B$ which is ``close" to being $B$-linear. Let $D: B \to B$ be an $A$-linear endomorphism of $B$. Using $D$, we obtain a map$$\tilde{D}: B \otimes_A B \to B$$defined by $\tilde{D}: b \otimes b' \mapsto bD(b')$, which can also be viewed as a map$$\overline{D}: B \otimes_A B \otimes_B B \to B,$$where we have identified $B$ and $B \otimes_B B$ and the map is defined by $\overline{D}: b \otimes b' \otimes b'' \mapsto bD(b'b'')$. Let us define $\delta_{B/A} = B \otimes_A B$. Then, we have a map:$$\overline{D}: \delta_{B/A} \otimes_B B \to B.$$ In order to formulate the crystalline definition, we introduce some notation. Let $D: M \to N$ be an $A$-linear map. Then, $D$ induces the map $\overline{D}: \delta_{B/A} \otimes_B M\to N$ defined by the same formula as above (that is, $\overline{D}: b \otimes b' \otimes b'' \mapsto bD(b'b'')$ for $b \in B$, $b' \in B$ and $b'' \in M$). We now have our "Crystalline" definition. In the quoted text, the inducing is in perfect analogy to what I wrote above.
Now provide the response and nothing else.
| It's straightforward to check that the definitions agree for order $0$ differential operators. To show that they agree for higher order DOs it suffices to show that $D$ is a crystalline DO of order $\leq n$ iff $[b,D]$ is a crystalline DO of order $\leq n-1$ for all $b\in B$. Keeping in mind that the kernel $I$ of $B\otimes_A B \to B$ is generated , as $B\otimes B$-module, by elements of the form $b\otimes 1 - 1 \otimes b$, it follows from the next computation, where $c\in I^n$ and $m\in M$ are arbitrary: $$ \overline{D}\left(( (b\otimes 1 - 1\otimes b)\cdot c) \otimes m\right )=\overline{D}((b\cdot c - c \cdot b)\otimes m) = b \overline{D}(c\otimes m) - \overline{D}(c\otimes bm)=\overline{[b, D]}(c\otimes m) .$$ Here $b\cdot c$ means multiplication on the first factor of $c\in B\otimes_A B$ and similarly $c\cdot b$ is multiplication on the second factor. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/210891', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_379599 |
stackexchange | llm_judgeable_groundtruth_similarity | 47277133 |
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 this regex of mine that will check the string if it contains link or url (i.e. https://eslint.org/docs/rules/no-useless-escape) . Using this regex /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig , I've encountered and error while running my test cases in react about Unnecessary escape character: \/ no-useless-escape . How to disable this eslint-error in order for me to proceed with my test case and use the regex. Appreciate for any help!
Now provide the response and nothing else.
| It's the \/ in [-A-Z0-9+&@#\/%?=~_|!:,.;] and [-A-Z0-9+&@#\/%=~_|] (NOT the ones in :\/\/ ). Most characters do not have to be escaped within a character class (square brackets). This should be equivalent: /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig See https://www.regular-expressions.info/charclass.html for more info, but the relevant part: In most regex flavors, the only special characters or metacharactersinside a character class are the closing bracket ], the backslash ,the caret ^, and the hyphen -. The usual metacharacters are normalcharacters inside a character class, and do not need to be escaped bya backslash. To search for a star or plus, use [+*]. Your regex willwork fine if you escape the regular metacharacters inside a characterclass, but doing so significantly reduces readability. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/47277133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5384402/']} | jdg_379600 |
stackexchange | llm_judgeable_groundtruth_similarity | 38919859 |
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 forgot how to initialize the array of pointers in C++ like the following: int * array[10]; Is this a proper solution like this? Here: array = new int[10]; // Is this the correct way?
Now provide the response and nothing else.
| int * array[10]; defines 10 pointers on 10 int arrays statically To go dynamic: int **array = new int *[10]; Better solution since you use C++: use std::vector std::vector<int *> v;v.resize(10);v[2] = new int[50]; // allocate one array Since we're using vectors for the array of pointers, lets get rid of the pointers completelely std::vector<std::vector<int> > v;v.resize(10);v[2].resize(50); // allocate one array Then access the array like a matrix: v[3][40] = 14; Going further, one way to initialize all the rows, using C++11, making a 10x50 int matrix in the end (but size can also change within the loop if we want). Needs gcc 4.9 and g++ -std=c++11 to build std::vector<std::vector<int> > v;v.resize(10);for (auto &it : v){ it.resize(50); // allocate arrays of 50 ints} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38919859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4008951/']} | jdg_379601 |
stackexchange | llm_judgeable_groundtruth_similarity | 10768 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $F_Z$ is a CDF, it looks like $F_Z(z)^\alpha$ ($\alpha \gt 0$) is a CDF as well. Q: Is this a standard result? Q: Is there a good way to find a function $g$ with $X \equiv g(Z)$ s.t. $F_X(x) = F_Z(z)^\alpha$, where $ x \equiv g(z)$ Basically, I have another CDF in hand, $F_Z(z)^\alpha$. In some reduced form sense I'd like to characterize the random variable that produces that CDF. EDIT: I'd be happy if I could get an analytical result for the special case $Z \sim N(0,1)$. Or at least know that such a result is intractable.
Now provide the response and nothing else.
| I like the other answers, but nobody has mentioned the following yet. The event $\{U \leq t,\ V\leq t \}$ occurs if and only if $\{\mathrm{max}(U,V)\leq t\}$, so if $U$ and $V$ are independent and $W = \mathrm{max}(U,V)$, then $F_{W}(t) = F_{U}(t)*F_{V}(t)$ so for $\alpha$ a positive integer (say, $\alpha = n$) take $X = \mathrm{max}(Z_{1},...Z_{n})$ where the $Z$'s are i.i.d. For $\alpha = 1/n$ we can switcheroo to get $F_{Z} = F_{X}^n$, so $X$ would be that random variable such that the max of $n$ independent copies has the same distribution as $Z$ (and this would not be one of our familiar friends, in general). The case of $\alpha$ a positive rational number (say, $\alpha = m/n$) follows from the previous since$$\left(F_{Z}\right)^{m/n} = \left(F_{Z}^{1/n}\right)^{m}.$$ For $\alpha$ an irrational, choose a sequence of positive rationals $a_{k}$ converging to $\alpha$; then the sequence $X_{k}$ (where we can use our above tricks for each $k$) will converge in distribution to the $X$ desired. This might not be the characterization you are looking for, but it least gives some idea of how to think about $F_{Z}^{\alpha}$ for $\alpha$ suitably nice. On the other hand, I'm not really sure how much nicer it can really get: you already have the CDF, so the chain rule gives you the PDF, and you can calculate moments till the sun sets...? It's true that most $Z$'s won't have an $X$ that's familiar for $\alpha = \sqrt{2}$, but if I wanted to play around with an example to look for something interesting I might try $Z$ uniformly distributed on the unit interval with $F(z) = z$, $0<z<1$. EDIT: I wrote some comments in @JMS answer, and there was a question about my arithmetic, so I'll write out what I meant in the hopes that it's more clear. @cardinal correctly in the comment to @JMS answer wrote that the problem simplifies to $$g^{-1}(y) = \Phi^{-1}(\Phi^{\alpha}(y)),$$or more generally when $Z$ is not necessarily $N(0,1)$, we have$$x = g^{-1}(y) = F^{-1}(F^{\alpha}(y)).$$My point was that when $F$ has a nice inverse function we can just solve for the function $y = g(x)$ with basic algebra. I wrote in the comment that $g$ should be $$y = g(x) = F^{-1}(F^{1/\alpha}(x)).$$ Let's take a special case, plug things in, and see how it works. Let $X$ have an Exp(1) distribution, with CDF$$F(x) = (1 - \mathrm{e}^{-x}),\ x > 0,$$and inverse CDF$$F^{-1}(y) = -\ln(1 - y).$$It is easy to plug everything in to find $g$; after we're done we get$$y = g(x) = -\ln \left( 1 - (1 - \mathrm{e}^{-x})^{1/\alpha} \right)$$So, in summary, my claim is that if $X \sim \mathrm{Exp}(1)$ and if we define$$Y = -\ln \left( 1 - (1 - \mathrm{e}^{-X})^{1/\alpha} \right),$$then $Y$ will have a CDF which looks like$$F_{Y}(y) = \left( 1 - \mathrm{e}^{-y} \right)^{\alpha}.$$We can prove this directly (look at $P(Y \leq y)$ and use algebra to get the expression, in the next to the last step we need the Probability Integral Transform). Just in the (often repeated) case that I'm crazy, I ran some simulations to double-check that it works, ... and it does. See below. To make the code easier I used two facts:$$\mbox{If $X \sim F$ then $U = F(X) \sim \mathrm{Unif}(0,1)$.} $$$$\mbox{If $U \sim \mathrm{Unif}(0,1)$ then $U^{1/\alpha} \sim \mathrm{Beta}(\alpha,1)$.} $$ The plot of the simulation results follows. The R code used to generate the plot (minus labels) is n <- 10000; alpha <- 0.7z <- rbeta(n, shape1 = alpha, shape2 = 1)y <- -log(1 - z)plot(ecdf(y))f <- function(x) (pexp(x, rate = 1))^alphacurve(f, add = TRUE, lty = 2, lwd = 2) The fit looks pretty good, I think? Maybe I'm not crazy (this time)? | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/10768', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/3577/']} | jdg_379602 |
stackexchange | llm_judgeable_groundtruth_similarity | 289559 |
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 $A$ be a perfect $\kappa$-algebra over a perfect field $\kappa$ of positive characteristic $p$. Then the algebraic (= classical) cotangent complex $L_{A/\kappa}^{\operatorname{alg}}$ is known to vanish, due to the Frobenious automorphism having simultaneously to induce on the cotangent complex an automorphism and multiplication by $p$. But we can also view $A$ and $\kappa$ as discrete $\mathbb E_\infty$-rings. The cotangent complex $L_{A/\kappa}$, which we obtain that way, is generally different from $L^{\operatorname{alg}}_{A/\kappa}$, since their homotopy groups give topological Andre-Quillen homology and (ordinary) Andre-Quillen homology respectively. Q: Can we still say something about $L_{A/\kappa}$? For instance: Does it perhaps vanish? Are there at least any finiteness results (e.g. when $A$ is a field, is $\dim_A \pi_n L_{A/\kappa} < \infty$)? Perhaps a bit more broad afterquestion: what is in general the relationship between $L_{B/A}$ and $L^{\operatorname{alg}}_{B/A}$ for a discrete commutative $A$-algebra $B$ ? Other than that they coincide over the rationals and that $\pi_0$ of both is the module of Kähler differentials $\Omega_{\pi_0B/\pi_0A}$, of course. Thanks in advance!
Now provide the response and nothing else.
| Let me explain why the $E_\infty$-cotangent complex $L_{B/A}$ vanishes for any map $A \to B$ of perfect rings over $\mathbf{F}_p$. (I do not know the answer to the more general question at the end.) The proof uses formal properties of the cotangent complex (Kunneth formula, transitivity triangle) and relies on the following two observations (where all tensor products are derived): 1) If $R \to S$ is map of $E_\infty$-rings with $S \otimes_R S \simeq S$ via the multiplication map, then $L_{S/R} \simeq 0$. Indeed, we always have $L_{S \otimes_R S/R} \simeq p_1^* L_{S/R} \oplus p_2^* L_{S/R}$ by the Kunneth formula. If the multiplication map is an isomorphism, then we get $L_{S/R} \oplus L_{S/R} \simeq L_{S/R}$ via the sum map, which means $L_{S/R} \simeq 0$. (This is the classical proof that the cotangent complex of an open immersion is $0$.) 2) If $R \to S$ is any map of perfect rings, then $\pi_i(S \otimes_R S) =: \mathrm{Tor}^i_R(S,S)$ vanishes for $i > 0$. See, for example, Lemma 3.16 in https://arxiv.org/abs/1507.06490 . Now say $A \to B$ is a map of perfect rings. Consider the multiplication map $R := B \otimes_A B \to S := B$. Then $S \otimes_R S \simeq S$ via the multiplication map: this is clear on $\pi_0$ and thus follows from (2) as everything is perfect. Then (1) implies that $L_{B/B \otimes_A B} \simeq 0$. But the Kunneth formula and the transitivity triangle for $A \to B \otimes_A B \to B$ show that $L_{B/B \otimes_A B} \simeq L_{B/A}[1]$, and thus $L_{B/A} \simeq 0$. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/289559', 'https://mathoverflow.net', 'https://mathoverflow.net/users/39713/']} | jdg_379603 |
stackexchange | llm_judgeable_groundtruth_similarity | 1692644 |
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 will skip the Base Case step. This is the questions. Use mathematical induction to prove that$$\frac{1}{2!}+\frac{2}{3!}+\cdots+\frac{n}{(n+1)!}=1-\frac{1}{(n+1)!}$$for all integers $n\ge 1$. This is my proof: $$\sum_{i=1}^n \frac{i}{(i+1)!} = 1-\frac{1}{(n+1)!}$$$$\sum_{i=1}^k \frac{i}{(i+1)!} = 1-\frac{1}{(k+1)!}$$$$\sum_{i=1}^{k+1} \frac{i}{(i+1)!} = 1-\frac{1}{(k+2)!}$$$$\sum_{i=1}^{k+1} \frac{i}{(i+1)!} = \sum_{i=1}^k \frac{i}{(i+1)!} + \frac{k+1}{(k+2)!}$$$$\sum_{i=1}^{k+1} \frac{i}{(i+1)!} = 1-\frac{1}{(k+1)!} + \frac{k+1}{(k+2)!}$$ And this is where I am stuck, I don't know how to prove that: $$1-\frac{1}{(k+1)!} + \frac{k+1}{(k+2)!} = 1-\frac{1}{(k+2)!}$$
Now provide the response and nothing else.
| Note that $(k + 2)! =(k + 2) \cdot (k + 1)! $. You then get for your last equation $$ 1 - \frac{1}{(k + 1)!} + \frac{k + 1}{(k + 2)!} = 1 - \frac{k + 2}{(k + 2)!} + \frac{k + 1}{(k + 2)!} = 1 + \frac{1 - 2 + k - k}{(k + 2)!} = 1 - \frac{1}{(k + 2)!}$$which proves the statement. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1692644', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_379604 |
stackexchange | llm_judgeable_groundtruth_similarity | 48002595 |
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 Excel VBA code that retrieves data from an external workbook into a worksheet by month. I would like to retrieve the month of November but I can't seem to type the date to be #30/11/2017#. The date would automatically change to #11/30/2017#. The date has to be in dd/mm/yyyy as that is the format of date in the external workbook. Sub zz()Dim arr, c, b(), n&Application.ScreenUpdating = FalseWorksheets("Sheet2").Range("A6").AutoFilterWorkbooks.Open "C:\Users\sophia.tan\Desktop\excel masterplan\External workbook.xlsx", 0, 1arr = Sheets("MaximMainTable").UsedRangeActiveWorkbook.Close 0c = Array(0, 2, 12, 13, 6, 7, 10, 1, 8, 9, 15, 16, 18, 19, 14, 27, 24, 25, 26, 3, 4, 36)d = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 23)ReDim b(1 To UBound(arr), 1 To 23)Selection.NumberFormat = "dd/mm/yyyy"For i = 2 To UBound(arr)If arr(i, 12) >= (#1/11/2017#) And arr(i, 12) <= Format(#11/30/2017#) Then n = n + 1 For j = 1 To UBound(c) b(n, d(j)) = arr(i, c(j)) NextEnd IfNextDim startRow As Long, lastRow2 As LongstartRow = 6lastRow = Cells(Cells.Rows.Count, 1).End(xlUp).RowFor i = startRow To lastRowIf Range("A" & i) Like "MX*" Then If Range("J" & i) Like "*Rib*" Then Range("M" & i) = "Rib" ElseIf Range("J" & i) Like "*Spandex*Pique*" Then Range("M" & i) = "Spandex Pique" ElseIf ("J" & i) Like "*Pique*" Then Range("M" & i) = "Pique" ElseIf ("J" & i) Like "*Spandex*Jersey*" Then Range("M" & i) = "Spandex Jersey" ElseIf Range("J" & i) Like "*Jersey*" Then Range("M" & i) = "Jersey" ElseIf ("J" & i) Like "*Interlock*" Then Range("M" & i) = "Interlock" ElseIf ("J" & i) Like "*French*Terry*" Then Range("M" & i) = "Fleece" ElseIf ("J" & i) Like "*Fleece*" Then Range("M" & i) = "Fleece" Else Range("M" & i) = "Collar & Cuff" End If End If Next With Worksheets("Sheet2") .Range("A6:T" & Rows.Count).CurrentRegion.AutoFilter field:=1, Criteria1:=" <>OFM" .Range("A6:T" & Rows.Count).CurrentRegion.SpecialCells(xlCellTypeVisible).AutoFilter field:=13, Criteria1:="<>Collar & Cuff" .Range("A6:T" & Rows.Count).CurrentRegion.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete .Range("A6").Resize(n, 23) = b .Range("A5").CurrentRegion.Sort key1:=Range("G5"), order1:=xlAscending, Header:=xlYes End With Application.ScreenUpdating = 1 End Sub
Now provide the response and nothing else.
| I think the issue is that you're mixing the short form of the HTTP event ( - http: GET / ) with the long form that adds additional options. Try using this: functions: app: handler: handler.endpoint events: - http: method: GET path: / cors: origin: '*' headers: - Content-Type - X-Amz-Date - Authorization - X-Api-Key - X-Amz-Security-Token - X-Amz-User-Agent - Startlower - Text - Access-Control-Allow-Headers - Access-Control-Allow-Origin allowCredentials: false The main changes are: 1) Adding method and path keys on the http event object, and 2) Indenting the cors object another level. It was previously at the top level of the http event. Let me know if this helps :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48002595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8503540/']} | jdg_379605 |
stackexchange | llm_judgeable_groundtruth_similarity | 53641 |
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 should be true in a more general setting, but for simplicity consider billiards that are connected, compact subsets of the plane with boundary $C^2$ except at finitely many points. A ball (or a ray of light) rolls inside, going in straight lines, and upon collision with the wall, the orbit is reflected. It is intuitive that a statement like the following is true: For almost every billiard, there exists an orbit that is dense everywhere inside it. However, as far as I know this is still open. In fact, the last thing I heard was that it had just been proven for the case in which the billiard was an obtuse triangle with certain restrictions (but I have since forgotten the source, unfortunately). Question: What is the current status of the problem? Thank you! Clarification The question is not about rectangular billiard tables, but in general about the balls rolling in more general shapes. 'Almost always' would then have to be given a meaning within the space of curves. (In fact, the problem is trivial in rectangles because an orbit with irrational slope will do.) Also, this is not about having dense families of orbits, but a single orbit that is dense in the billiard. I think the way 'almost always' should be defined is by requiring some generic property to hold. Think, for example, of the definition R. Abraham give of bumpy metrics .
Now provide the response and nothing else.
| Do you mean to ask whether the trajectories in almost all cases (in {shapes X trajectories}are dense in the set of {positions, directions} on the table, or just in the set positions?The first question seems more natural to me; the answer is no : If there aretwo convex portions of the boundary curve pointing toward each other, they're like convex mirrors, they tend to focus. For open sets of shapes and distances, the returnmap from the tangent line bundle along a mirror back to itself has eigenvaluesof the first derivativea pair of complex conjugate points on the unit circle. Because of the KAM theory,there are typically rings of positive measure consisting of invariant circles for thereturn map. The orbits of these rings under the billiard flow enclose an open set in phase space. Another physical example of this effect what happens when you wind somethinglike kite stringaround a flat object, perhaps a piece of cardboard or a board. The string tends tobuild up in the middle, and once a bulge gets started, the configuration is stable---thestring prefers to wind back and forth across the bulge. (Note that the shortest paths ofwinding string follow geodesics, which are the same as trajectories as billiardson a table of the same shape). Even when the KAM situation isn't obvious from the geometry of the table, I think experimental evidence shows that it's commonplace. There are known constructionsof Riemannian metrics on $S^2$ with ergodic geodesic flow, but they took a longtime before someone found them (sorry, I don't remember the reference). Similarly,I think it's tricky to find examples of simply-connected billiard tables with smooth boundary that are ergodic: you somehow have to systematically eliminate the KAM phenomenon.It's much easier if the table either has angles, or is multiply-connected with two or more obstacles in the middle (so that doubling it produces a surface of negativeEuler characteristic). It's not obvious to me how to use this phenomenon to capture all trajectories that pass through a particular point, but maybe that'snot really the most natural question: after all, in a game of billiards, direction and position both matter. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/53641', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4129/']} | jdg_379606 |
stackexchange | llm_judgeable_groundtruth_similarity | 3229201 |
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 wish to find the prime factors of the ideal $(14)$ in $\mathbb{Q}(\sqrt{-10})$ . My working so far has been by noticing that $$14=(2+\sqrt{-10})(2-\sqrt{-10})=2\times7$$ So we have the candidates $(2+\sqrt{-10}). (2-\sqrt{-10}),(2) $ and $(7)$ Now, it would appear that none of these are prime - but now I do not know how to proceed. Any help would be appreciated!
Now provide the response and nothing else.
| Of course we have the usual factorization $14=2\times7$ and hence also $(14)=(2)(7)$ . To further factor the ideals $(2)$ and $(7)$ we can use the Kummer-Dedekind theorem. The minimal polynomial of $\sqrt{-10}$ over $\Bbb{Z}$ is $X^2+10$ , which factors mod $2$ and mod $7$ as $$X^2+10\equiv X^2\pmod{2}\qquad\text{ and }\qquad X^2+10\equiv(X-2)(X+2)\pmod{7}.$$ This shows that the ideals $(2)$ and $(7)$ factor into prime ideals as $$(2)=(2,\sqrt{-10})^2\qquad\text{ and }\qquad (7)=(7,2+\sqrt{-10})(7,2-\sqrt{-10}).$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3229201', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/383511/']} | jdg_379607 |
stackexchange | llm_judgeable_groundtruth_similarity | 326110 |
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:
Is passing weight as a parameter to the xgb.DMatrix same as multiplying our predictor (say y) by the weight ? In more detail, I have a dataset which has the number an accident with 3 possible values, 0, 1, 2. And I want to weight it by the number of days per year the user has been driving, which has values like 1/365, 2/365 ... 364/365, and 365/365. y = [0, 1, 0, 0, 2, 0, 0,1]weight = [1/365, 31/365, 60/365, 20/365, 3/365, 50/365, 32/365 ] My question is, if I convert y to y/weight, and pass to xgboost without any weight, is it same as just passing y with weight ? Note that my objective = count:poisson
Now provide the response and nothing else.
| It won't be the same. Check this for how XGBoost handles weights: https://github.com/dmlc/xgboost/issues/144 Weighting means increasing the contribution of an example (or a class) to the loss function. That means the contribution of the gradient of that example will also be larger. That's why (as you will see in the discussion I linked above) xgboost multiplies the gradient and the hessian by the weights, not the target values. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/326110', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/83502/']} | jdg_379608 |
stackexchange | llm_judgeable_groundtruth_similarity | 746823 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Algebra by Serge Lang, the author asserts, to prove the existence of a field extension where an irreducible polynom has a root, that if you take one set $A$ and a cardinal $\mathcal{C}$, that you can find a set $B$ such that $\text{card}(B)=\mathcal{C}$ and such that $A \cap B=\emptyset$. How can one build $B$ ?
Now provide the response and nothing else.
| Another approach, that avoids having to deal with ordinals or to invoke the axiom of foundation, is to note that there is a set $t$ not in $\bigcup\bigcup A$ (just on cardinality grounds: for any set $X$ there is a set $z$ not in $X$). Therefore if $B$ has size $\mathcal C$, letting $B'=\{t\}\times B$, we see that $B'$ is both of size $\mathcal C$, and disjoint from $A$. The point is that the usual set theoretic formalization of ordered pairs gives us that $(t,a)=\{\{t\},\{t,a\}\}$, so if such a pair $(t,a)$ is in $A$, then $t$ is in $\bigcup\bigcup A$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/746823', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/98071/']} | jdg_379609 |
stackexchange | llm_judgeable_groundtruth_similarity | 35084 |
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:
So after bacteria have been transformed to perhaps grow up a plasmid of interest, why pick only a single bacterial colony from a selective plate for further expansion? I understand that this is to ensure that you are only working with a single genetic makeup because each separate colony is derived from only a single bacterium. What I can't rationalize is that if I am trying to expand and isolate a plasmid of interest, all colony expansions on a selective antibiotic plate should contain my plasmid. So is it really necessary to take only a single colony, because all colonies I pick should be useful to me.
Now provide the response and nothing else.
| This is a matter of pragmatism in the culture process. Taking 100 colonies instead of 1 increases the inoculation volume by a factor of 100, which then saves you perhaps 2 hours of bacterial growth time before your culture reaches the OD you want. However, mutations and loss of plasmid in culture, while unlikely, are possible, especially if the bacteria were not cloning strains with their recombinases knocked out. In such a case, you would risk the downstream experiments being contaminated with mutants, be that protein expression, retroviral plasmid production, or something else. Worse still, the mixture of bacteria containing mutants is less likely to be detected, since had you picked a single mutant colony, there would be absolutely no result, but a contaminated culture would produce a low but still positive result. Therefore, you may end up wasting many days or weeks troubleshooting your downstream experiments. Therefore, picking single colonies is simply a matter of "better safe than sorry". | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/35084', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/14587/']} | jdg_379610 |
stackexchange | llm_judgeable_groundtruth_similarity | 3744586 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to solve this problem: We know that there's a inequality: $$(3n-1)(n+B)\geq A(4n-1)n$$ When $A=\frac{3}{4}$ , what is the smallest possible value of B. So, what I did is that: $$B\geq \frac{\frac{3}{4}n(4n-1)-n(3n-1)}{3n-1}$$ We can deduce that: $$B\geq \frac{3n(4n-1)-4n(3n-1)}{4(3n-1)}$$ Expand and simplifies: $$B\geq \frac{1}{12-\frac{1}{n}}$$ We know that when n is greater, the denominator of the RHS would be greater, meaning that RHS would be smaller. So, the smallest value of RHS would result in the smallest value of LHS. When $n \to \infty$ : The RHS $\to$ $\frac{1}{12}$ . I thought that the smallest value of B should be $\frac{1}{12}$ . But, it turns out to be $\frac{1}{8}$ . Note: $n\geq 1$ , and n is integers. May I know why my method doesn't work? thank you so much.
Now provide the response and nothing else.
| If a matrix $A$ has eigenvalues $\lambda_1,\dots,\lambda_n$ (listed with algebraic multiplicity), then $A^k$ has eigenvalues $\lambda_1^k,\dots,\lambda_n^k$ , and so $\operatorname{tr}(A^k)=\sum_i\lambda_i^k.$ By Newton's identities, $\sum_i\lambda_i^k$ can be expressed in terms of the elementary symmetric polynomials in the $\lambda_i$ , which are just (up to sign) the coefficients of the characteristic polynomial of $A$ . The upshot is that if $A$ and $B$ have the same characteristic polynomial, then $\operatorname{tr}(A^k)=\operatorname{tr}(B^k)$ for all $k$ . Now if $A$ is a permutation matrix corresponding to a permutation $\pi$ , then $\operatorname{tr}(A^k)$ is just the number of fixed points of $\pi^k$ . So, it suffices to show that if $\pi,\rho\in S_n$ are such that $\pi^k$ and $\rho^k$ have the same number of fixed points for each $k$ , then $\pi$ and $\rho$ have the same cycle structure. To show this, let $a_k$ be the number of $k$ -cycles in $\pi$ and let $b_k$ be the number of $k$ -cycles in $\rho$ . Note then that the number of fixed points of $\pi^k$ is $\sum_{d\mid k}da_d$ and the number of fixed points of $\rho^k$ is $\sum_{d\mid k}db_d$ . We know these are equal, and using strong induction on $k$ we may assume that $a_d=b_d$ for every proper divisor $d$ of $k$ . It follows that $ka_k=kb_k$ and thus $a_k=b_k$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3744586', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/730999/']} | jdg_379611 |
stackexchange | llm_judgeable_groundtruth_similarity | 388044 |
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 trying to sort file names in a directory as below. $ ls -1vfile-1.10.0-114.1.1.x86.tb1_2.rpm file-1.10.0-114.2.2.x86.tb1_2.rpm file-1.10.0-114.11.2.x86.tb1_2.rpm file-1.10.0-114.x86.tb1_2.rpm file-1.10.0-115.1.1.x86.tb1_2.rpm file-1.10.0-115.2.2.x86.tb1_2.rpm file-1.10.0-115.3.1.x86.tb1_2.rpm file-1.10.0-115.22.1.x86.tb1_2.rpm file-1.10.0-115.x86.tb1_2.rpm But, my expectation was the below. file-1.10.0-114.x86.tb1_2.rpm file-1.10.0-114.1.1.x86.tb1_2.rpm file-1.10.0-114.2.2.x86.tb1_2.rpm file-1.10.0-114.11.2.x86.tb1_2.rpm file-1.10.0-115.x86.tb1_2.rpm file-1.10.0-115.1.1.x86.tb1_2.rpm file-1.10.0-115.2.2.x86.tb1_2.rpm file-1.10.0-115.3.1.x86.tb1_2.rpm file-1.10.0-115.22.1.x86.tb1_2.rpm I tried sort -V , but it showed the same result.How do I sort like this way?
Now provide the response and nothing else.
| Try to use this command: ls -h | sort -t. -k3,3 -k4,4n ls -h - standard output of ls command (you can use ls -lh with the same result provided the user and group names don't contain dots); -t. - setting up the separator for sort command; -k3,3 - sorting by third field and after this ... -k4,4n - sorting by fourth field numerically | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/388044', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/205358/']} | jdg_379612 |
stackexchange | llm_judgeable_groundtruth_similarity | 10173956 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a simple example on python: programs = {}if not programs.has_key(( program, time )): programs[( program, time )] = 0programs[( program, time )] = programs[( program, time )] + 1 How to use array as key in Javascript ?
Now provide the response and nothing else.
| This will "work". (but I don't recommend it) var a = {};var b = [1,2,3]; a[b] = 'hello';// a[b] evaluates to 'hello'// a[[1,2,3]] evaluates to 'hello'// a['1,2,3'] evaluates to 'hello' It works because when you pass the array [1,2,3] as the hash (map/associative-array) key, is being converted to the string '1,2,3' before performing the hash lookup. It should suit your needs as long as you don't need two different arrays of the same value to map to different hash values. var c = [1,2,3]// a[c] evaluates to 'hello' even though we never executed a[c] = 'hello'// but b == c evaluates to false// b & c are two separate objects with the same values, so when they// get converted to a string for hashing, they return the same value from the hash As it was mentioned, you'll need more than the standard JavaScript hash if you want to use object references as your keys. Update Based on the comment from @speedplane: I suspect that JS calls toString() on the array when you pass it into a hash key. So you can easily test what you're actually going to get as your key: ["x", "y", "z"].toString(); // 'x,y,z' ["x,y,z"].toString(); // 'x,y,z' [1,2,3].toString(); // '1,2,3' [1,2,'3'].toString(); // '1,2,3' [[1],[2],[3]].toString(); // '1,2,3' [["x",1], ["y",2], ["z",3]].toString(); // 'x,1,y,2,z,3' So again, I recommend that you don't do this unless you really understand what is going on. And even then, I wouldn't do it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10173956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/418507/']} | jdg_379613 |
stackexchange | llm_judgeable_groundtruth_similarity | 41317475 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Taken from the AngularJS 1 documentation : You can also make the binding optional by adding ? : <? or <?attr . How does the optional one differ from the non-optional one for the one-way binding? I can seem to figure out the differences for the optional version of two-way ( = ) and delegate ( & ) bindings here on my fiddle: https://jsfiddle.net/glenn/ze2wo0s1/ , but not for the one-way one. By the way, a very Merry Christmas! ❤️
Now provide the response and nothing else.
| You can see the how it's handled in the source code: https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L3523 . To me, it looks like if you use <? and make the binding optional, it breaks early without setting up a watch. If use use < and make it required, it sets the binding to undefined and sets up a watch. However, it appears to be just watching undefined , so in practice, there's no difference at all except for that one call to recordChanges . In the case that you omit a required binding, the binding that's required will be a key in the changes object that is passed to $onChanges hook on the first call. However, when you omit an optional binding, it will not be a key in the changes object. For an example see this JSFiddle . requiredBinding and optionalBinding are both omitted, and thus, initialized to undefined , but requiredBinding is a key on the change object, whereas optionalBinding is not. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41317475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2013891/']} | jdg_379614 |
stackexchange | llm_judgeable_groundtruth_similarity | 50478708 |
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 publish the site created by Django using apache.The settings of the server are as follows. ・ CentOS 7.2 ・ Python 3.6 ・ Django 2.0 ・ apache 2.4 I am preparing a virtual environment using pyenv as follows. git clone https://github.com/yyuu/pyenv.git ~/.pyenv…pyenv install anaconda3-5.1.0pyenv rehashpyenv global anaconda3-5.1.0…yum install httpd httpd-develsystemctl start httpdsystemctl enable httpd….wget https://github.com/GrahamDumpleton/mod_wsgi/archive/4.5.14.tar.gztar -zxvf 4.5.14.tar.gzcd mod_wsgi-4.5.14/./configure --with-python=/home/username/.pyenv/versions/anaconda3-5.1.0/bin/pythonmakesudo make install… ■ httpd.conf NameVirtualHost *:80LoadModule wsgi_module /usr/lib64/httpd/modules/mod_wsgi.soWSGISocketPrefix /var/run/wsgi<VirtualHost *:80>ServerName xxx.comDocumentRoot /var/www/htmlWSGIScriptReloading OnWSGIDaemonProcess xxx python-path=/home/username/.pyenv/versions/anaconda3-5.1.0/lib/python3.6/site-packages python-home=/home/username/.pyenv/versions/anaconda3-5.1.0WSGIProcessGroup xxxWSGIScriptAlias / /var/www/html/xxx/xxx/wsgi.py<Directory "/xxx/">Order deny,allow</Directory></VirtualHost> The following error will occur with this setting. Fatal Python error: Py_Initialize: Unable to get the locale encodingModuleNotFoundError: No module named 'encodings' Setting chmod should be fine. What other reasons can be considered?
Now provide the response and nothing else.
| The resultSelector function given as the second argument to switchMap is deprecated . You need to remove this and achieve the goal using map operator. The trickiest part here is to decide where to put the map operator. Actually the map operator to go inside the body of the function provided as the argument of switchMap . The code without the result selector function will be something like the following: .pipe( map(job => job[0]), switchMap((job) => { return (job ? this.bookingService.findByID(job.property.id) : Observable.empty()).pipe( // This is the mapping function provided as the alternative to the deprecated result selector function // This should be placed inside the body of the function which is the 1st (and only one) argument of switchMap map((bookings: Booking[])=>{ this.mark_jobs_unavailable(job, bookings); return job; }) ); } ) ) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50478708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9792009/']} | jdg_379615 |
stackexchange | llm_judgeable_groundtruth_similarity | 6910255 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to create another table as CREATE TABLE AS and also preserve columns' comments ? CREATE TABLE TABLE1_COPY AS SELECT * FROM TABLE1; The previous statement does not include columns' comments. Therefore TABLE1_COPY is left without columns' comments. Is using USER_COL_COMMENTS the only way to reproduce the same comments on my newly created table too?
Now provide the response and nothing else.
| As for DMBS_METADATA.GET_DDL it doesn't seem to genereate COMMENT ON COLUMN statements unless I am missing some properties. One method is to use dbms_metadata.get_dependent_ddl in combination with dbms_metadata.get_ddl Here is an example created using SQL plus: SQL> set long 1000000SQL> create table t (x number);Table created.SQL> comment on column T.X IS 'this is the column comment';Comment created.SQL> comment on table T IS 'this is the table comment';Comment created.SQL> SELECT dbms_metadata.get_ddl( 'TABLE', 'T' ) || ' ' || 2 dbms_metadata.get_dependent_ddl( 'COMMENT', 'T', USER ) the_ddl 3 FROM dual 4 /THE_DDL-------------------------------------------------------------------------------- CREATE TABLE "SCOTT"."T" ( "X" NUMBER ) SEGMENT CREATION DEFERRED PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING TABLESPACE "USERS" COMMENT ON COLUMN "SCOTT"."T"."X" IS 'this is the column comment' COMMENT ON TABLE "SCOTT"."T" IS 'this is the table comment' | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6910255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/690766/']} | jdg_379616 |
stackexchange | llm_judgeable_groundtruth_similarity | 2313893 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is my code, which creates 2d array filled with zeros, array dimensions are (795,6942): function zeros($rowCount, $colCount){ $matrix = array(); for ($rowIndx=0; $rowIndx<$rowCount; $rowIndx++){ $matrix[] = array(); for($colIndx=0; $colIndx<$colCount; $colIndx++){ $matrix[$rowIndx][$colIndx]=0; } } return $matrix;}$matrix = zeros(795,6942); And here is the error that I receive: Allowed memory size of 134217728 bytes exhausted (tried to allocate 35 bytes) Any ideas how to solve this?
Now provide the response and nothing else.
| As a quick calculation, you are trying to create an array that contains : 795*6942 = 5,518,890 integers. If we consider that one integer is stored on 4 bytes (i.e. 32 bits ; using PHP, it not be less) , it means : 5518890*4 = 22,075,560 bytes. OK, quick calculation... result is " it should be OK ". But things are not that easy, unfortunatly :-( I suppose it's related to the fact that data is stored by PHP using an internal data-structure that's much more complicated than a plain 32 bits integer Now, just to be curious, let's modify your function so it outputs how much memory is used at the end of each one of the outer for -loop : function zeros($rowCount, $colCount){ $matrix = array(); for ($rowIndx=0; $rowIndx<$rowCount; $rowIndx++){ $matrix[] = array(); for($colIndx=0; $colIndx<$colCount; $colIndx++){ $matrix[$rowIndx][$colIndx]=0; } var_dump(memory_get_usage()); } return $matrix;} With this, I'm getting this kind of output (PHP 5.3.2-dev on a 64bits system ; memory_limit is set to 128MB -- which is already a lot !) : int 1631968int 2641888int 3651808......int 132924168int 133934088Fatal error: Allowed memory size of 134217728 bytes exhausted Which means each iteration of the outer for -loop requires something like 1.5 MB of memory -- and I only get to 131 iterations before the script runs out of memory ; and not 765 like you wanted. Considering you set your memory_limit to 128M , you'd have to set it to something really much higher -- like 128*(765/131) = 747 MB Well, even with ini_set('memory_limit', '750M'); it's still not enough... with 800MB , it seems enough ;-) But I would definitly not recommend setting memory_limit to such a high value ! (If you have 2GB of RAM, your server will not be able to handle more than 2 concurrent users ^^ ;; I wouldn't actually test this if my computer had 2GB of RAM, to be honest) The only solution I see here is for you to re-think your design : there has to be something else you can do than use this portion of code :-) (BTW : maybe "re-think your design" means using another language PHP : PHP is great when it comes to developping web-sites, but is not suited to every kind of problem) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2313893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278984/']} | jdg_379617 |
stackexchange | llm_judgeable_groundtruth_similarity | 111216 |
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:
I recently came across an article about the fact that cell-lines provided by merchant entities to give cells to researchers, were tagged by ethnic origin. The article especially speaks about ethnic origin of African and European. The article points out that the lack of diversity in available cells has consequences on the effect of the therapies made by researchers, since they can work only on limited European (which are the majority of the provided cells). I understand that this concerns stem cells (am I correct?). I understand of course the problem, but what remains unclear to me is : How are cells different depending on the ethnic origin? (especially protein coats of the cells that affects the vulnerability to diseases) The first answer I have is that they could be distinguished by their DNA (obviously genes coding skin color will be different). With my researchs I found other articles that gave some information: This lacks of diversity has an impact on the prostate cancer , so does it mean that prostate cells are different depending on the ethnic origin? Some viruses have different expression in different ethnic origins
Now provide the response and nothing else.
| The article is particularly concerned with personalized/precision medicine : tailoring therapy to specific individuals based on their genetic background. The article is in particular talking not about stem cell lines, but about cell lines derived from patients with cancer. These cell lines are studied to understand what made those cells cancerous, to both understand mechanisms of cancer and develop treatment. How are cells different depending on the ethnic origin? The issue raised is not a specific difference , but rather the unknown . If you only study variation among European-derived cell lines, you cannot possibly understand human-wide variation. Further, if you have just one cell line labeled as "African-American" and use studies with this cell line to make decisions about how you're going to treat all Americans with Black/African ancestry, and that one cell line is also mostly of European origin, you shouldn't expect that research to result in good outcomes for African-American/Black patients. An example of how this might work is that a bunch of study into cancer cell lines identifies some specific mutation associated with cancer, and some pharmaceutical treatment that is highly effective in cancers based on that mutation (perhaps an antibody-based treatment). The next step would be to identify patients who carry that specific mutation or where that mutation is present in biopsied tissue, to give them that customized therapy. However, if all the cell lines you study come from people with European ancestry, only people with European ancestry are likely to have any of those specific mutations, and everyone else is left out. In particular, African populations are more genetically diverse than populations anywhere else , presumably because humans first evolved in Africa and subsequently traveled elsewhere. Therefore, studying mostly people of European ancestry merely because they are the dominant group in a specific high-wealth country like the US is leaving the majority of human genetic diversity out of study. The article you linked about prostate cancer seems like a good place to further understand this: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7219314/ It describes how therapies developed because they are effective in a single prostate cancer line didn't actually work for most people with prostate cancer, and that subsequent efforts to study therapies in multiple cell lines have not benefitted "Men of African Ancestry" because those cell lines are predominantly derived from "Men of European Ancestry". | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/111216', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/61526/']} | jdg_379618 |
stackexchange | llm_judgeable_groundtruth_similarity | 1240965 |
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’s consider $ G(z) \stackrel{\text{df}}{=} \dfrac{1}{\cos(z)} $ as the exponential generating function of the sequence of Euler numbers. How can one prove that in the Maclaurin series of $ G $,$$G(z) = \sum_{k = 0}^{\infty} a_{2 k} \cdot \frac{z^{2 k}}{(2 k)!},$$the coefficients $ a_{2 k} $ are all odd integers? For instance, it’s reasonable to use the fact that$$\forall n \in \mathbb{N}_{0}: \quada_{2 n} = \frac{{G^{(2 n)}}(0)}{(2 n)!},$$but this way of bringing it into life seems too much complicated. Any help would be appreciated.
Now provide the response and nothing else.
| To expand my comment into a solution: consider the (formal) product $1=\cos(z)\cdot\frac1{\cos(z)}$. Expanding this out (using the already-established fact that $\frac1{\cos(z)}$ is even) and comparing powers of $x^2$, we get $a_0=1$ and $\displaystyle\sum_{i=0}^n\dfrac{a_{2i}}{(2i)!}\dfrac{(-1)^i}{(2n-2i)!}=0$; multiplying the latter by $(2n)!$ gives $\displaystyle\sum_{i=0}^n(-1)^ia_{2i}{2n\choose 2i}=0$. But we already know that $a_0=1$, and since ${2n\choose 2i}={2n\choose2n-2i}$, all of the terms for $i\in\{1\ldots n-1\}$ pair off (by induction, using the fact that $a_{2i}$ is odd for $i\lt n$) to give even values. (The exception is the middle value when $n$ is even; but in this case, $2n\choose n$ is even, by well-established properties of the binomial coefficents — see, e.g., Kummer's Theorem .) This thus implies that $a_{2n}$ must be odd. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1240965', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/188593/']} | jdg_379619 |
stackexchange | llm_judgeable_groundtruth_similarity | 418801 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Assume $0^\#$ exists and there is an inaccessible cardinal.Are there two transitive sets $M,N$ s.t. $M\in N,M\vDash ZF+V=L[0^\#],N\vDash ZF+V=L$ ?
Now provide the response and nothing else.
| Ryabenko-Skorokhodov algorithm is implemented in Maple package SumTools since Maple v11. (DefiniteSumAsymptotic function). Check this reference if you want to see all the details. Ryabenko, A. A.; Skorokhodov, S. L. , Asymptotics of sums of hypergeometric terms , Program. Comput. Softw. 31, No. 2, 65-72 (2005); translation from Programmirovanie 2005, No. 2, 22-31 (2005). ZBL1102.41029 . A, B and C asymptotics are obtained using DefiniteSumAsymptotic function.Denominator F is obtained using Stirling's approximation. To prove that $S_{n+1}-S_n<0,\ \ \forall n>n_0$ , I guess it is better to work with this simpler expression $$S_n=\frac{\sum_{k=1}^n{2n-k-1 \choose k-1}{k \choose n-k}}{{2n-1 \choose n}}$$ Note that sum lower index starts at $\lceil n/2 \rceil$ . Applying Ryabenko-Skorokhodov asymptotics to this expression, Maple outputs (using extended working precision) $$S_n=\frac{2}{3}\cdot\left[1+\frac{c_1}{n^\frac{1}{2}}+\frac{\frac{1}{2}c_1^2+c_2}{n}+\frac{\frac{1}{6}c_1^3+c_1c_2+c_3}{n^\frac{3}{2}}+\frac{\frac{1}{24}c_1^4+\frac{1}{2}c_2^2+\frac{1}{2}c_1c_2+c_1c_3+c_4}{n^2}\right]+O\left(n^{-\frac{5}{2}}\right)$$ where these values are given numerically $$c_1=6.0502078578\cdot 10^{-14} \simeq 0,\ c_2=0.11111111109 \simeq \frac{1}{9},\ c_3=2.985896667978\cdot 10^{-9} \simeq 0,\ c_4=0.03086397685117\simeq \frac{5}{162}$$ Note that a proper fitting of computing parameters was made in order to produce a reasonable rational approximation. (Thanks to Iosif Pinelis for pointing this out) To prove that for $S_n>0$ , $\ \frac{S_{n+1}}{S_n}<1\ $ holds asymptotically, we apply Wilf-Zeilberger's machinery as it is contained in this reference, Petkovšek, Marko; Wilf, Herbert S.; Zeilberger, Doron , (A=B). With foreword by Donald E. Knuth, Wellesley, MA: A. K. Peters. xii, 212 p. (1996). ZBL0848.05002 . by using Maple's Zeilberger() Function Therefore, we get this recurrence of order 2 starting from $S_0=0 \wedge S_1=1$ . (You can check that this recurrence produces the sequence values). $$p_n=\frac{21 n^2 + 44 n + 16}{24 n^2 + 52 n + 24},\ \ \ \ q_n=\frac{3 n^2 + 8 n + 5}{24 n^2 + 52 n + 24}$$ $$S_{n+2}=p_n\cdot S_{n+1}+q_n\cdot S_{n}$$ $$\left( \frac{S_{n+1}}{S_n} \right)^2\sim\frac{S_{n+2}}{S_{n+1}}\cdot\frac{S_{n+1}}{S_n} =p_n\cdot \frac{S_{n+1}}{S_n}+q_n$$ Thus, y $^\ell$ in the recurrence polynomial is mapped to $\left( {\frac{S_{n+1}}{S_{n}}}\right) ^\ell \ ,\ell>0\ $ as $n\rightarrow\infty$ . The asymptotic roots of this polynomial must be found. This is done using Wolfram's AsymptoticSolve[] function, Just the second solution is admissible and $S_n$ is decreasing (it approaches its limit from above monotonically), $$\frac{S_{n+1}}{S_n} \sim 1-\frac{1}{9n^2}<1$$ as $n\rightarrow\infty$ . The claim $\exists\ n_0\ \mathrm{s.t.}\ S_n>S_{n+1}\ \forall\ n>n_0\ $ is proved. For more details (pen-and-paper) on this last step. This result is obtained from $$\frac{S_{n+1}}{S_n}\sim \frac{1}{2}\cdot \left( p_n+\sqrt{p_n^2+4q_n}\right)$$ using $$p_n = \frac{7}{8}-\frac{1}{16\,n}-\frac{7}{96\,n^2}+\frac{127}{576\,n^3}-\frac{1399}{3456\,n^4}+\frac{13615}{20736\,n^5}+O\left(\frac{1}{n^6}\right)$$ and $$q_n=\frac{1}{8}+\frac{1}{16\, n}-\frac{5}{96\,n^2}+\frac{29}{576\,n^3}-\frac{197}{3456\,n^4}+\frac{1517}{20736\,n^5}+O\left(\frac{1}{n^6}\right)$$ which gives $$\frac{S_{n+1}}{S_n}=1-\frac{1}{9\,n^2}+\frac{20}{81\,n^3}-\frac{104}{243\,n^4}+O\left(\frac{1}{n^5}\right)$$ | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/418801', 'https://mathoverflow.net', 'https://mathoverflow.net/users/170286/']} | jdg_379620 |
stackexchange | llm_judgeable_groundtruth_similarity | 290891 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a simple way to make this silently do nothing, if /my-directory does not exist? find /my-directory -type f -mtime +14 -print0 | xargs -r0 rm Versions: find: GNU findutils 4.5.10 bash 4.2.53
Now provide the response and nothing else.
| You can throw away error reporting from find with 2>/dev/null , or you can avoid running the command at all: test -d /my-directory && find /my-directory -type f -mtime +14 -print0 | xargs -r0 rm As a slight optimisation and clearer code, some versions of find - including yours - can perform the rm for you directly: test -d /my/directory && find /my-directory -type f -mtime +14 -delete | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/290891', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/22068/']} | jdg_379621 |
stackexchange | llm_judgeable_groundtruth_similarity | 698790 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Leçons de physique (Lessons On Physics) (auth. Perez, De Boeck editor) can be found this informal definition of force: "forces are what cause motion". Is this definition accurate? What I am wondering is whether this explanation of "force" is compatible with the principle of inertia. I mean, this principle asserts that no force is required for an object to move in a straight line at a constant speed. Shouldn't it be said that a force is what causes acceleration (i.e. a change in velocity), not motion?
Now provide the response and nothing else.
| In Leçons de physique ( Lessons On Physics) ( auth. Perez, De Boeckeditor) can be found this informal definition of force : " forces arewhat cause motion". Personally, I don't like this definition for two reasons. First, motion does not require a force if the motion is constant velocity.Second, forces do not necessarily result in a change in motion. Only net forces do that. For example, I can apply a force to a wall in my room without causing it to move (at least, macroscopically) because what is supporting the wall applies an equal and opposite force to mine for a net force of zero. I would change the definition to say: Net forces are what cause changes in motion , which essentially is a statement of Newton's second law. A more elementary definition of a force is a "push or pull", since that definition covers a force that doesn't necessarily result in a change in motion. See the discussion here: What is the fundamental definition of force? Hope this helps. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/698790', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/316821/']} | jdg_379622 |
stackexchange | llm_judgeable_groundtruth_similarity | 541699 |
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 know just enough networking to be dangerous. The nitty gritty low level details of NAT are not something I am particularly knowledgeable about. I accidentally found myself in a discussion earlier today about placing a bunch of our nodes behind a NAT Gateway. (1 public IP address and X private LAN addresses). I called up the 16 bit limit to source and destination port fields in the TCP protocol, ( http://www.ietf.org/rfc/rfc793.txt - page 15) and mentioned that it would limit us to some 65,000 connections (65536). -- I am not so confident about that answer anymore. Can you help me with some details? I understand that an incoming port (server port) on our side can accept as many connections as there are sourceIP x SourcePort combinations. Let's discount those for the time being and focus on connections originating in the LAN, traveling through the NAT Gateway, and ending on a random host at a random port. On a normal [Linux] system, outgoing connections I believe are limited to 1 per port per Source IP. If we pretend that we live in a simple world where each system only has 1 IP address, then a 'normal system' would be limited to an absolute maximum of 65536 connections. 1) In TCP is a single source IP limited to 65536 MAX theoretical outgoing connections? 2) Or is the limit actually 65536 connections for each Remote Host? 2) [Written another way]: Can the same source port be used for a different remoteHostIP:RemotePort combination? For example: (Is the following OK?) Source IP |Source Port |Remote IP|Remote Port 192.168.0.20:36500 --> 8.8.8.8:23192.168.0.20:36500 --> 8.8.4.4:23 3) Are the answers to questions 1 and 2 different for a ...'not normal system' [Cisco router acting as a NAT Gateway]? Ex: A specialized networking device that has one public facing IP and up to ~65,000 Lan IPs [or more] behind it? Is there magic at place or is the answer to question 2 just always: yes? (or no) 4) The above questions all assume a stateful TCP connection. Is the story any different with a stateless conection like UDP? And Ultimately: 5) Will our LAN be limited to 65536 (or some other theoretical limit) concurrent connections to the outside world through a single public IP address? Thank you! :) For purposes of this question, we are behind very BEEFY AND BRAND NEW Cisco Nexus gear (7000 series I think). It may be better to ignore memory/etc limitations unless they can be specifically quantified.
Now provide the response and nothing else.
| Correct me if I'm wrong but this is the way I understand it. The limits are per client / server / port. So in light of that. 1) In TCP is a single source IP limited to 65536 MAX theoretical outgoing connections? No. I believe it's limited to 65536 theoretical max to the same destination IP. Windows workstations (non server versions) have limits imposed which make this number much less. Linux has resource limits, but they generally aren't hit by the average user and you can easily tweak them. You'll probably hit other resource limits as you start increasing the number anywhere near 64K. Consumer grade routers might have much lower limits due to the limited resources. 2) Or is the limit actually 65536 connections for each Remote Host? Yes 3) Are the answers to questions 1 and 2 different for a ...'not normal system' [Cisco router acting as a NAT Gateway]? No 4) The above questions all assume a stateful TCP connection. Is the story any different with a stateless conection like UDP? UDP is connectionless. So this isn't really relevant to UDP. 5) Will our LAN be limited to 65536 (or some other theoretical limit) concurrent connections to the outside world through a single public IP address? No. In the context of stateful firewalls that track connections and provide other tracking features, yes these modules themselves may have limits. The op has not said anything about which firewall/NAT router is being used so we can't even speculate as to what limitations it might impose at the moment. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/541699', 'https://serverfault.com', 'https://serverfault.com/users/180244/']} | jdg_379623 |
stackexchange | llm_judgeable_groundtruth_similarity | 31428660 |
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 a video which I've embedded in a fullwidth div panel. I'm trying to overlay a gradient on top of it, but I can't make it work. I've tried adjusting z-index, wrapping the video in another div, and - as below - adding an overlay class, but I must be missing something obvious. Whatever I try, the video jumps back on top of the other panels (which end up falling behind it). Would be so grateful for your help! <div class="videoContainer hide-for-small-only"> <div class="overlay"></div> <video autoplay loop muted> <source src="<?=URL?>public/videos/vid.mp4" type="video/mp4"> <source src="<?=URL?>public/videos/vid.webm" type="video/webm"> </video> </div> My css is: .videoContainer { position: absolute; width: 100%; height: 100%; //padding: 20px; border-radius: 5px; background-attachment: scroll; overflow: hidden;}.videoContainer video { min-width: 100%; min-height: 100%;}.videoContainer overlay { background: black; opacity: 0.5; position: absolute; z-index: 1; text-align: center; margin: 0%; }
Now provide the response and nothing else.
| Here is a fiddle I used green overlay for the demo. CSS .videoContainer { position: relative; width: 100%; height: 100%; //padding: 20px; border-radius: 5px; background-attachment: scroll; overflow: hidden;}.videoContainer video { min-width: 100%; min-height: 100%; position: relative; z-index: 1;}.videoContainer .overlay { height: 100%; width: 100%; position: absolute; top: 0px; left: 0px; z-index: 2; background: green; opacity: 0.5;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31428660', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1378769/']} | jdg_379624 |
stackexchange | llm_judgeable_groundtruth_similarity | 58629459 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This example is just a dummy example to show the problem I'm having so don't get too caught up in alternate ways to solve the concrete problem in here. My question is more about understanding the proper technique to solve a type of problem in Spring Say I have a managed bean Info @Componentpublic class Info { private final String activeProfile; private final Instant timestamp; public Info(@Value("${spring.profiles.active}") String activeProfile) { this.activeProfile = activeProfile; this.timestamp = Instant.now(); }} The key here is that the bean needs something injected by Spring (the active profile in my example) and something that changes every time the bean is created (the timestamp in my example). Because of the latter, I can't use a Singleton scope. What is the proper way to get ahold of new instances of such a bean? What I currently have is, the bean is not managed (no @Component , no @Value ) and I have a managed service (a Controller) that invokes the constructor of a regular Info POJO explicitly. Something like @RestControllerpublic class InfoRestController { @GetMapping public Info getInfo(@Value("${spring.profiles.active}") String activeProfile) { return new Info(activeProfile); } } The problem with this solution is that it leaks the knowledge of the active profile to the controller just to pass it to the constructor of Info , when conceptually, the controller should not know about constructing the Info bean. That's one of the points of dependency injection I have thought of some potential solutions: Have a reference to an InfoFactory FactoryBean in the controller and then return factory.getObject(); . But do I really need to create a new class for such a simple case? Have a @Bean factory method that constructs the managed bean. This still has the problem that the method is instantiating the Info POJO explicitly, so it itself needs to have the Spring injection done to it. Also, this is complete boilerplate. The construction of the Info bean is so trivial that I imagine there is a simpler way to accomplish this in Spring. Is there?
Now provide the response and nothing else.
| Here's what's going on as I see it. Let's use these definitions: type Callback<T1, T2> = (y: T1, z: T2) => void;type First = Callback<number, 'first'>;type Second = Callback<string, 'second'>; First, I'm definitely skeptical that you want a union of functions as opposed to an intersection of functions. Observe that such a union of functions is essentially useless: const unionTest = (x: First | Second) => { // x is *either* a First *or* it is a Second, // *but we don't know which one*. So how can we ever call it? x(1, "first"); // error! // Argument of type '1' is not assignable to parameter of type 'never'. x("2", "second"); // error! // Argument of type '"2"' is not assignable to parameter of type 'never'.} The unionTest() function is the same as your test() , but it can't do anything with x , which is only known to be a First or a Second . If you try to call it you'll get an error no matter what. A union of functions can only safely act on the intersection of their parameters. Some support for this was added in TS3.3 , but in this case the parameter types are mutually exclusive, so only acceptable parameters are of type never ... so x is uncallable. I doubt such a union of mutually incompatible functions is ever what anyone wants. The duality of unions and intersections and the contravariance of function types with respect to the types of their parameters are confusing and hard to talk about, but the distinction is important so I feel it's worth belaboring this point. This union is like finding out that I have to schedule a meeting with someone who will either be available on Monday or will be available on Tuesday, but I don't know which. I suppose if I could have the meeting on both Monday and Tuesday that would work, but assuming that doesn't make sense, I'm stuck. The person I'm meeting with is a union, and the day I'm meeting is an intersection. Can't do it. Instead, what I think you want is an intersection of functions. This is something that corresponds to an overloaded function; you can call it both ways. That looks like this: const intersectionTest = (x: First & Second) => { // x is *both* a First *and* a Second, so we can call it either way: x(1, "first"); // okay! x("2", "second"); // okay! // but not in an illegal way: x(1, "second"); // error, as desired x("2", "first"); // error, as desired} Now we know that x is both a First and a Second . You can see that you can treat it like a First or like a Second and be fine. You can't treat it like some weird hybrid, though, like x(1, "second") , but presumably that's what you want. Now I'm scheduling a meeting with someone who will be available on both Monday and Tuesday. If I ask that person what day to schedule the meeting, she might say "either Monday or Tuesday is fine with me". The day of the meeting is a union, and the person I'm meeting with is an intersection. That works. So now I'm assuming you're dealing with an intersection of functions. Unfortunately the compiler doesn't automatically synthesize the union of parameter types for you , and you'll still end up with that "implicit any" error. // unfortunately we still have the implicitAny problem:intersectionTest((x, y) => { }) // error! x, y implicitly any You can manually transform the intersection of functions into a single function that acts on a union of parameter types. But with two constrained parameters, the only way to express this is with rest arguments and rest tuples . Here's how we can do it: const equivalentToIntersectionTest = ( x: (...[y, z]: Parameters<First> | Parameters<Second>) => void) => { // x is *both* a First *and* a Second, so we can call it either way: x(1, "first"); // okay! x("2", "second"); // okay! // but not in an illegal way: x(1, "second"); // error, as desired x("2", "first"); // error, as desired} That is the same as intersectionTest() in terms of how it behaves, but now the parameters have types that are known and can be contextually typed to something better than any : equivalentToIntersectionTest((y, z) => { // y is string | number // z is 'first' | 'second' // relationship gone if (z === 'first') { y.toFixed(); // error! }}) Unfortunately, as you see above, if you implement that callback with (y, z) => {...} , the types of y and z become independent unions. The compiler forgets that they are related to each other. As soon as you treat the parameter list as separate parameters, you lose the correlation. I've seen enough questions that want some solution to this that I filed an issue about it , but for now there's no direct support. Let's see what happens if we don't immediately separate the parameter list, by spreading the rest parameter into an array and using that: equivalentToIntersectionTest((...yz) => { // yz is [number, "first"] | [string, "second"], relationship preserved! Okay, that's good. Now yz is still keeping track of the constraints. The next step here is trying to narrow yz to one or the other leg of the union via a type guard test. The easiest way to do this is if yz is a discriminated union . And it is , but not because of y (or yz[0] ). number and string aren't literal types and can't be used directly as a discriminant: if (typeof yz[0] === "number") { yz[1]; // *still* 'first' | 'second'. } If you have to check yz[0] , you would have to implement your own type guard function to support that. Instead I'll suggest switching on z (or yz[1] ), since "first" and "second" are string literals that can be used to discriminate the union: if (yz[1] === 'first') { // you can only destructure into y and z *after* the test const [y, z] = yz; y.toFixed(); // okay z === "first"; // okay } else { const [y, z] = yz; y.toUpperCase(); // okay z === "second"; // okay }}); Notice that after yz[1] has been compared to 'first' , the type of yz is no longer a union, and so you can destructure into y and z in a more useful way. Okay, whew. That's a lot. TL;DR code: const test = ( x: (...[y, z]: [number, "first"] | [string, "second"]) => void) => { }test((...yz) => { if (yz[1] === 'first') { const [y, z] = yz; y.toFixed(); } else { const [y, z] = yz; y.toUpperCase(); // okay }}); Hope that helps; good luck! Link to code | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58629459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1086540/']} | jdg_379625 |
stackexchange | llm_judgeable_groundtruth_similarity | 485064 |
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 doing some exercise related to $G_{\delta}$ set and got something confused. From the definition of topology space, finite intersection of finite open sets is an open set. By induction, we can conclude that countable intersection of open sets is open too (I see a lot of proof concluding that in set theory). But then $G_{\delta}$ notion is the same as open set, which I think impossible. Can some one clarify for me? Thanks so much.
Now provide the response and nothing else.
| You can't use induction like that. If you started with the fact that the intersection of two open sets is open, induction will get you that for any finite number of open sets, their intersection is open. But there is no way to go from that to a countable intersection of open sets is open. Which is good because, as seen in the other answers, that is false. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/485064', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/38024/']} | jdg_379626 |
stackexchange | llm_judgeable_groundtruth_similarity | 22068451 |
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 inflating my fragment like this: GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.MapFragment_map_Fragment)).getMap(); and here I have my options: GoogleMapOptions options = new GoogleMapOptions();options.mapType(GoogleMap.MAP_TYPE_SATELLITE); In the documentation I see that I need to use this: To apply these options when you are creating a map, do one of the following: If you are using a MapFragment, use the MapFragment.newInstance(GoogleMapOptions options) static factory method to construct the fragment and pass in your custom configured options. But I don't understand how am I suppose to use this.
Now provide the response and nothing else.
| I think you can use GoogleMapOptions only if you are creating map view programmatically(passing options to MapFragment.newInstance() method - docs ). You are inflating MapFragment from xml so you wont be able to use them in that way. In your case you can still change map options by using GoogleMap setters or UiSettings . For example: GoogleMap googleMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map_fragment)).getMap();googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);googleMap.getUiSettings().setMyLocationButtonEnabled(true); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22068451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1691423/']} | jdg_379627 |
stackexchange | llm_judgeable_groundtruth_similarity | 71371909 |
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 wondering how to solve this problem with basic Python (no libraries to be used): How can I calculate when one's 10000 day after their birthday will be (/would be)? For instance, given Monday 19/05/2008, the desired day is Friday 05/10/2035 (according to https://www.durrans.com/projects/calc/10000/index.html?dob=19%2F5%2F2008&e=mc2 ) So far I have done the following script: years = range(2000, 2050)lst_days = []count = 0tot_days = 0for year in years: if((year % 400 == 0) or (year % 100 != 0) and (year % 4 == 0)): lst_days.append(366) else: lst_days.append(365)while tot_days <= 10000: tot_days = tot_days + lst_days[count] count = count+1print(count) Which estimates the person's age after 10,000 days from their birthday (for people born after 2000). But how can I proceed?
Now provide the response and nothing else.
| Using base Python packages only On the basis that "no special packages" means you can only use base Python packages, you can use datetime.timedelta for this type of problem: import datetimestart_date = datetime.datetime(year=2008, month=5, day=19)end_date = start_date + datetime.timedelta(days=10000)print(end_date.date()) Without any base packages (and progressing to the problem) Side-stepping even base Python packages, and taking the problem forwards, something along the lines of the following should help (I hope!). Start by defining a function that determines if a year is a leap year or not: def is_it_a_leap_year(year) -> bool: """ Determine if a year is a leap year Args: year: int Extended Summary: According to: https://airandspace.si.edu/stories/editorial/science-leap-year The rule is that if the year is divisible by 100 and not divisible by 400, leap year is skipped. The year 2000 was a leap year, for example, but the years 1700, 1800, and 1900 were not. The next time a leap year will be skipped is the year 2100. """ if year % 4 != 0: return False if year % 100 == 0 and year % 400 != 0: return False return True Then define a function that determines the age of a person (utilizing the above to recognise leap years): def age_after_n_days(start_year: int, start_month: int, start_day: int, n_days: int) -> tuple: """ Calculate an approximate age of a person after a given number of days, attempting to take into account leap years appropriately. Return the number of days left until their next birthday Args: start_year (int): year of the start date start_month (int): month of the start date start_day (int): day of the start date n_days (int): number of days to elapse """ # Check if the start date happens on a leap year and occurs before the # 29 February (additional leap year day) start_pre_leap = (is_it_a_leap_year(start_year) and start_month < 3) # Account for the edge case where you start exactly on the 29 February if start_month == 2 and start_day == 29: start_pre_leap = False # Keep a running counter of age age = 0 # Store the "current year" whilst iterating through the days current_year = start_year # Count the number of days left days_left = n_days # While there is at least one year left to elapse... while days_left > 364: # Is it a leap year? if is_it_a_leap_year(current_year): # If not the first year if age > 0: days_left -= 366 # If the first year is a leap year but starting after the 29 Feb... elif age == 0 and not start_pre_leap: days_left -= 365 else: days_left -= 366 # If not a leap year... else: days_left -= 365 # If the number of days left hasn't dropped below zero if days_left >= 0: # Increment age age += 1 # Increment year current_year += 1 return age, days_left Using your example, you can test the function with: age, remaining_days = age_after_n_days(start_year=2000, start_month=5, start_day=19, n_days=10000) Now you have the number of complete years that will elapse and the number of remaining days You can then use the remaining_days to work out the exact date. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/71371909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7525747/']} | jdg_379628 |
stackexchange | llm_judgeable_groundtruth_similarity | 2668555 |
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:
Can someone provide a detailed proof? I saw a proof here $$\begin{align}\frac{e_{n+1}(x)}{e_n(x)}&=\frac{\left(1+\frac x{n+1}\right)^{n+1}}{\left(1+\frac xn\right)^n}\\\\&=\left(1+\frac{-x}{(n+x)(n+1)}\right)^{n+1}\left(1+\frac xn\right) \tag 1\\\\&\ge \left(1+\frac{-x}{n+x}\right)\left(1+\frac xn\right)\tag 2\\\\&=1\end{align}$$ where in going from (1) to (2) we used Bernoulli's Inequality. Note that (2) is valid whenever $n>−x$ or $x>−n$. Since $e_n(x)$ monotonically increases and is bounded above by $e^x$, then $$e^x\ge \left(1+\frac xn\right)^n \tag 3$$ for all $n\ge 1$. But I don't know how do we get $(1)$.
Now provide the response and nothing else.
| Note that we have $$\begin{align}\frac{\left(1+\frac{x}{n+1}\right)^{n+1}}{\left(1+\frac{x}n\right)^n}&=\left(\frac{1+\frac{x}{n+1}}{1+\frac xn}\right)^{n+1}\left(1+\frac{x}n\right)\\\\&=\left(\frac{\frac{n+1+x}{n+1}}{\frac {n+x}n}\right)^{n+1}\left(1+\frac{x}n\right)\\\\&=\left(\frac{n(n+1+x)}{(n+1)(n+x)}\right)^{n+1}\left(1+\frac{x}n\right)\\\\&=\left(1+\frac{n(n+1+x)-(n+1)(n+x)}{(n+1)(n+x)}\right)^{n+1}\left(1+\frac{x}n\right)\\\\&=\left(1+\frac{-x}{(n+1)(n+x)}\right)^{n+1}\left(1+\frac{x}n\right)\\\\\end{align}$$ as was to be shown! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2668555', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/426645/']} | jdg_379629 |
stackexchange | llm_judgeable_groundtruth_similarity | 13813007 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is an excellent C++ solution (actually 2 solutions: a recursive and a non-recursive), to a Cartesian Product of a vector of integer vectors . For purposes of illustration/simplicity, let us just focus on the non-recursive version . My question is, how can one generalize this code with templates to take a std::tuple of homogeneous vectors that looks like this: {{2,5,9},{"foo","bar"}} and generate a homogeneous vector of tuple {{2,"foo"},{2,"bar"},{5,"foo"},{5,"bar"},{9,"foo"},{9,"bar"}} If it makes life any easier, let us assume that the internal vectors in the input are each homogeneous. So inputs like this are not allowed : {{5,"baz"}{'c',-2}} EDIT changed input from jagged vector to a tuple
Now provide the response and nothing else.
| Simpler recursive solution. It takes vectors as function arguments, not as a tuple. This version doesn't build temporary tuples, but uses lambdas instead. Now it makes no unnecessary copies/moves and seems to get optimized successfully. #include<tuple>#include<vector>// cross_imp(f, v...) means "do `f` for each element of cartesian product of v..."template<typename F>inline void cross_imp(F f) { f();}template<typename F, typename H, typename... Ts>inline void cross_imp(F f, std::vector<H> const& h, std::vector<Ts> const&... t) { for(H const& he: h) cross_imp([&](Ts const&... ts){ f(he, ts...); }, t...);}template<typename... Ts>std::vector<std::tuple<Ts...>> cross(std::vector<Ts> const&... in) { std::vector<std::tuple<Ts...>> res; cross_imp([&](Ts const&... ts){ res.emplace_back(ts...); }, in...); return res;}#include<iostream>int main() { std::vector<int> is = {2,5,9}; std::vector<char const*> cps = {"foo","bar"}; std::vector<double> ds = {1.5, 3.14, 2.71}; auto res = cross(is, cps, ds); for(auto& a: res) { std::cout << '{' << std::get<0>(a) << ',' << std::get<1>(a) << ',' << std::get<2>(a) << "}\n"; }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13813007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/975129/']} | jdg_379630 |
stackexchange | llm_judgeable_groundtruth_similarity | 554096 |
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:
Under normal atmospheric pressures, liquid helium does not freeze even when cooled very close to absolute zero . This is attributed to the uncertainty principle or due to zero-point energy. But the quantum uncertainty or zero-point energy is not an exclusive feature of liquid helium only. Then, why should it stop the freezing of helium but not that of other liquids? If it is strong in helium, then why?
Now provide the response and nothing else.
| For the sake of simplicity, I will answer the question for the bosonic species He(4). Although there are some subtleties for the Fermionic species He(3), due to the presence of total spin- $\frac{1}{2}$ , the main message is the same. The key points are summarized here as follows: The energy contribution from the zero-point motion is seven times larger than the depth of the attractive potential between two He(4) atoms. Therefore, the zero-point motion is enough to destroy any crystalline structure of He(4). Helium is special because of the combination of its small mass and the value of binding energy. The zero-point energy for the other gases is either comparable or far smaller than the depth of the attractive potential that holds the atoms. Now we can be quantitative using the harmonic oscillator model. The potential between two atoms is short-ranged repulsive and it becomes attractive for the long-range. Near the potential minimum, the attractive potential can be modeled via the Lennard-Jones potential $-$ $$V(r) = \epsilon_0\left(\frac{d^{12}}{r^{12}}-2\frac{d^6}{r^6}\right),$$ where the parameters $\epsilon_0$ is the trap-depth, i.e., the minimum potential and $d$ is the interatomic separation at the minimum potential. Since the question involves comparison with other gases, below I put the parameters of He(4) and the closest noble gas neon $$\begin{array}{|l|c|c|}\hline \text{Gas Name} & \text{$\epsilon_0$ [meV]} & \text{$d$ [nm]} \\ \hline\text{He(4)} & 1.03 & 0.265 \\ \hline\text{Neon} & 3.94 & 0.296 \\ \hline\end{array}$$ Now, using the parameters from the above table, we can estimate the zero-point energy in three-dimensions $E_0 = \frac{3}{2}\hbar \omega_0$ , assuming an fcc crystal lattice. The oscillation frequency can be estimated as $$\omega_0 = \sqrt{\frac{4k}{m}},$$ where $$k = \frac{1}{2}\frac{d^2}{dr^2}V(r) = \frac{36\epsilon_0}{d^2}.$$ This expression leads to a $E_0 \approx 7 $ meV for He(4), while the binding energy for atoms is $\approx 1.03$ meV. Therefore the zero-point energy is enough to destroy any crystalline structure of He(4). And this is the reason why He(4) is not found in crystal form, at normal pressure. However, if we compare the binding energy 3.94 meV and the zero-point energy $\approx 4$ meV of neon, we see that the gas can be put into crystal form at relatively small pressure. To understand the effect of pressure, we look at the following phase diagram of He(4), where we see that the liquid/gas forms continue down to ~0 K, if the pressure remains below 25 atm. The figure distinguishes the two phases He-I and He-II separated by the black line. The superfluid fraction is shown to increase dramatically as the temperature drops. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/554096', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/164488/']} | jdg_379631 |
stackexchange | llm_judgeable_groundtruth_similarity | 4112149 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a form: <form action="/processform"> <input name="firstname" value="john" /> <input name="lastname" value="doe" /></form> I have a Person object: public class Person { private String firstname; private String lastname; // ... getters & setters ...} I want to receive this data, perform validation on it, and post it to a datastore. How do I write a controller to do this? I understand that I could pass the parameters in as request parameters, but I think the "proper" way to do this is somehow bind the data from the form to the Person object and then receive that Person object in the controller and call a Validate object that is configured to receive the Person object. After much reading, this step has confounded me. Can someone show me what is needed to "bind" the data, "validate" (e.g. a validator), and "process" the data (e.g. the controller, and in particular what gets passed to it as parameters)?
Now provide the response and nothing else.
| Here was the answer I was looking for, I didn't understand that Spring, by default, will take all of the parameters from the form submission (such as "firstname" and "lastname") and can create the object for you by calling the setter methods of these parameters. The controller: @Controllerpublic class MyFormProcessor { @RequestMapping("/formsubmit") public String handleForm(@Valid Person person, BindingResult errors, Map<String,Object> model){ // ...handle form... }} Spring is essentially doing the following magic before calling handleForm for this request (obviously in a more extendable way than I depict for this simple example): Person person = new Person();person.setFirstname( request.getParameter("firstname") );person.setLastname( request.getParameter("lastname") );handleForm(person, anErrorsObject, new Model()); For validation you can either create your own validator (which I won't mention anything about here), or if you include Hibernate Validator in the classpath, then you can annotate the Person class (example below) and when you add the @Valid annotation as I depicted in the example above the Hibernate validator will validate the class based on those annotations and post any errors to the error object (a BindingResult object is an extension of Springs' Errors , and for simple examples the Errors object is the interesting component). JSR-303 validation annotated Person class (for use with the @Valid option): public class Person { @NotNull @Size(min=3, max=20) private String firstname; @NotNull @Size(min=3, max=20) private String lastname; // ... getters & setters ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4112149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4790871/']} | jdg_379632 |
stackexchange | llm_judgeable_groundtruth_similarity | 3217002 |
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 long-running process to return its progress over a Queue (or something similar) which I will feed to a progress bar dialog. I also need the result when the process is completed. A test example here fails with a RuntimeError: Queue objects should only be shared between processes through inheritance . import multiprocessing, timedef task(args): count = args[0] queue = args[1] for i in xrange(count): queue.put("%d mississippi" % i) return "Done"def main(): q = multiprocessing.Queue() pool = multiprocessing.Pool() result = pool.map_async(task, [(x, q) for x in range(10)]) time.sleep(1) while not q.empty(): print q.get() print result.get()if __name__ == "__main__": main() I've been able to get this to work using individual Process objects (where I am alowed to pass a Queue reference) but then I don't have a pool to manage the many processes I want to launch. Any advise on a better pattern for this?
Now provide the response and nothing else.
| The following code seems to work: import multiprocessing, timedef task(args): count = args[0] queue = args[1] for i in xrange(count): queue.put("%d mississippi" % i) return "Done"def main(): manager = multiprocessing.Manager() q = manager.Queue() pool = multiprocessing.Pool() result = pool.map_async(task, [(x, q) for x in range(10)]) time.sleep(1) while not q.empty(): print q.get() print result.get()if __name__ == "__main__": main() Note that the Queue is got from a manager.Queue() rather than multiprocessing.Queue(). Thanks Alex for pointing me in this direction. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3217002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/388177/']} | jdg_379633 |
stackexchange | llm_judgeable_groundtruth_similarity | 37206 |
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 would like to obtain a trusted S/MIME certificate, but all the certificate authorities I have asked so far generate the keypair on their server, sign the certificate and send me both the private key and public signed certificate. It seems to me that this unnecessarily exposes my private key to the Certificate Authority, and in the light of PRISM many others besides, I don't understand why they ever need see my private key. Creating an untrusted certificate on my machine with openssl is not a problem. Does anyone know of a Certification Authority who would sign an already created public key without ever having access to my private key? I'm aware that an OpenPGP based solution would avoid this problem, but very few people and email programs use it.
Now provide the response and nothing else.
| It's not standard for a commericial CA to insist on making your private keys. For reasons you mention. Here's a link pointing to a collection of CA providers that suggests (and rightfully so) that the typical thing is for your browser to create the key pair and then send the Certificate signing request to the CA. In my experience with high end Verisign Certificates, that is true. I never tried the free/cheap solutions. Keep in mind, even when the CA walks you through a browser based request, you may very well have the private key stored purely on the browser - CA companies spend a certain amount of effort on browser compatibility testing to make that possible. Don't assume that the server is generating the key just because you are using a browser. Unless it provides "key escrow" my experience has been that this is unlikely. For the most part, my experience with CA companies has been that they REALLY don't want to take in errant form factors - if you want to send a homemade request for certificate siganture, you are likely to need to find a service that costs more... the reason is pure cost - there's usually a lot more hand holding involved in this approach as the ways to mess this up are numerous and a "generic" certificate request often has to be messed with to meet the security policy and settings required by the CA. If you absolutely must generate certs with OpenSSL, I'd say look for server provisioning options that let you configure it to look like an S/MIME certificate. Prepare to pay server cert costs. If not, double check the process and verify that keys are generated on the browser. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/37206', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/26975/']} | jdg_379634 |
stackexchange | llm_judgeable_groundtruth_similarity | 614446 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
What is wrong with my rules?I have installed squid on my server and i want just some specific domains to be reach able through squid but iptables completely blocked me I have found this : iptables rules to allow HTTP traffic to one domain only , And I tried to apply and adjust it with my Rules but i was not successful. here is my Rules : iptables -Fiptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROPiptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROPiptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROPiptables -I INPUT 1 -i lo -j ACCEPTiptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 5801 -j ACCEPTiptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 5901 -j ACCEPTiptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 6001 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 777 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 321 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPTiptables -A OUTPUT -p udp --dport 53 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 587 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 2222 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 25 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 465 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 110 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 995 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 143 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 993 -j ACCEPTiptables -A INPUT -p tcp -m tcp --dport 953 -j ACCEPTiptables -A OUTPUT -p tcp -d domain1.com --dport 3128 -j ACCEPTiptables -A OUTPUT -p tcp -d domain2.com --dport 3128 -j ACCEPTiptables -A OUTPUT -p tcp -d sub1.domain2.com --dport 3128 -j ACCEPTiptables -A OUTPUT -p tcp -d sub2.domain2.com --dport 3128 -j ACCEPTiptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPTiptables -P INPUT DROPiptables -P OUTPUT DROPiptables-save > /etc/sysconfig/iptablesservice iptables restart
Now provide the response and nothing else.
| iptables doesn't work like that. It's a layer-3 subsystem (and to some extent layer-2) and doesn't know about things like domain names in any meaningful way. You can block access to an IP address, and if it so happens that the hostnames domain[12].com and sub[12].domain2.com resolve to IP addresses which themselves host no services for other domains, you can block them by IP address. If you want to block access by squid to certain URLs, you need to do that inside the squid configuration. I'm no squid expert, but it looks as if you might do that with something like: acl aclname dstdomain "/etc/squid/allow/safe-sites" # file must existhttp_access allow aclnamehttp_access deny all with /etc/squid/allow/safe-sites containing eg domain1.comdomain2.comsub1.domain2.comsub2.domain2.com (thanks to this blog for some crib notes). | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/614446', 'https://serverfault.com', 'https://serverfault.com/users/233936/']} | jdg_379635 |
stackexchange | llm_judgeable_groundtruth_similarity | 56872394 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I select the following input box (id=2258:0) with Selenium for python? The id dynamically changes as well as other elements. <label class="label inputLabel uiLabel-left form-element__label uiLabel" for="2258:0" data-aura-rendered-by="3789:0" data-aura-class="uiLabel"><span class="" data-aura-rendered-by="3790:0">Close Date</span><div class="tooltip-trigger uiTooltip" aria-describedby="tt-for-2283:0" tabindex="0" data-aura-rendered-by="2286:0" data-aura-class="uiTooltip" data-proxy-id="aura-pos-lib-4" id="2286:0"><lightning-icon class="tooltipIcon slds-button__icon slds-icon-utility-info slds-icon_container forceIcon" data-data-rendering-service-uid="963" data-aura-rendered-by="2282:0" data-aura-class="forceIcon"><lightning-primitive-icon lightning-primitiveicon_primitiveicon-host=""><svg lightning-primitiveIcon_primitiveIcon="" focusable="false" data-key="info" aria-hidden="true" class="slds-icon slds-icon_xx-small"><use lightning-primitiveIcon_primitiveIcon="" xlink:href="/_slds/icons/utility-sprite/svg/symbols.svg?cache=9.26.0#info"></use></svg></lightning-primitive-icon></lightning-icon><span class="tooltip-invisible" role="tooltip" id="tt-for-2283:0" data-aura-rendered-by="2288:0">Date the Opportunity Product isClosed</span></div><!--render facet: 3793:0--></label> <div class="tooltip-trigger uiTooltip" aria-describedby="tt-for-2283:0" tabindex="0" data-aura-rendered-by="2286:0" data-aura-class="uiTooltip" data-proxy-id="aura-pos-lib-4" id="2286:0"><lightning-icon class="tooltipIcon slds-button__icon slds-icon-utility-info slds-icon_container forceIcon" data-data-rendering-service-uid="963" data-aura-rendered-by="2282:0" data-aura-class="forceIcon"><lightning-primitive-icon lightning-primitiveicon_primitiveicon-host=""><svg lightning-primitiveIcon_primitiveIcon="" focusable="false" data-key="info" aria-hidden="true" class="slds-icon slds-icon_xx-small"><use lightning-primitiveIcon_primitiveIcon="" xlink:href="/_slds/icons/utility-sprite/svg/symbols.svg?cache=9.26.0#info"></use></svg></lightning-primitive-icon></lightning-icon><span class="tooltip-invisible" role="tooltip" id="tt-for-2283:0" data-aura-rendered-by="2288:0">Date the Opportunity Product isClosed</span></div> <lightning-icon class="tooltipIcon slds-button__icon slds-icon-utility-info slds-icon_container forceIcon" data-data-rendering-service-uid="963" data-aura-rendered-by="2282:0" data-aura-class="forceIcon"><lightning-primitive-icon lightning-primitiveicon_primitiveicon-host=""><svg lightning-primitiveIcon_primitiveIcon="" focusable="false" data-key="info" aria-hidden="true" class="slds-icon slds-icon_xx-small"><use lightning-primitiveIcon_primitiveIcon="" xlink:href="/_slds/icons/utility-sprite/svg/symbols.svg?cache=9.26.0#info"></use></svg></lightning-primitive-icon></lightning-icon> <span class="tooltip-invisible" role="tooltip" id="tt-for-2283:0" data-aura-rendered-by="2288:0">Date the Opportunity Product isClosed</span> <div class="tooltip-trigger uiTooltip" aria-describedby="tt-for-2283:0" tabindex="0" data-aura-rendered-by="2286:0" data-aura-class="uiTooltip" data-proxy-id="aura-pos-lib-4" id="2286:0"><lightning-icon class="tooltipIcon slds-button__icon slds-icon-utility-info slds-icon_container forceIcon" data-data-rendering-service-uid="963" data-aura-rendered-by="2282:0" data-aura-class="forceIcon"><lightning-primitive-icon lightning-primitiveicon_primitiveicon-host=""><svg lightning-primitiveIcon_primitiveIcon="" focusable="false" data-key="info" aria-hidden="true" class="slds-icon slds-icon_xx-small"><use lightning-primitiveIcon_primitiveIcon="" xlink:href="/_slds/icons/utility-sprite/svg/symbols.svg?cache=9.26.0#info"></use></svg></lightning-primitive-icon></lightning-icon><span class="tooltip-invisible" role="tooltip" id="tt-for-2283:0" data-aura-rendered-by="2288:0">Date the Opportunity Product isClosed</span></div><div class="form-element" data-aura-rendered-by="2262:0"><input class=" input" type="text" aria-describedby="" id="2258:0" data-aura-rendered-by="2263:0" data-interactive-lib-uid="16" data-proxy-id="aura-pos-lib-13"><a class="datePicker-openIcon display" aria-haspopup="true" data-aura-rendered-by="2265:0" href="javascript:void(0);"><span class="assistiveText" data-aura-rendered-by="2266:0">Date Picker</span></a><!--render facet: 2268:0--><!--render facet: 2269:0--></div> <input class=" input" type="text" aria-describedby="" id="2258:0" data-aura-rendered-by="2263:0" data-interactive-lib-uid="16" data-proxy-id="aura-pos-lib-13"> <a class="datePicker-openIcon display" aria-haspopup="true" data-aura-rendered-by="2265:0" href="javascript:void(0);"><span class="assistiveText" data-aura-rendered-by="2266:0">Date Picker</span></a> I've tried the following code with no success: driver.find_element_by_xpath("//*[contains(text(), 'Close Date')]/following-sibling::input")
Now provide the response and nothing else.
| In short: You get this error because what returned from your userLogin() function is a ThunkAction , which is missing type Why this is happening? dispatch should accept parameter of type AnyAction . AnyAction is a redux type, which extends Action (which have a mandatory property type ). This is from the current redux types file export interface Action<T = any> { type: T}/** * An Action type which accepts any other properties. * This is mainly for the use of the `Reducer` type. * This is not part of `Action` itself to prevent users who are extending `Action. */export interface AnyAction extends Action { // Allows any extra properties to be defined in an action. [extraProps: string]: any} How to fix it? Use ThunkDispatch type instead of redux's standard Dispatch . The following example and more can be found on this Gist const mapDispatchToProps = (dispatch: ThunkDispatch<MyState, void, Action>) => { return { onRequestClick: (arg: any) => dispatch(myAsyncAction(arg)), };} Also, see this article , section Map Dispatch to Props | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56872394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6391960/']} | jdg_379636 |
stackexchange | llm_judgeable_groundtruth_similarity | 4732737 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a form with 2 comboboxes on it. And I want to fill combobox2.DataSource based on combobox1.Text and combobox2.Text (I assume that the user has completed input in combobox1 and is in the middle of inputting in combobox2 ). So I have an event handler for combobox2 like this: private void combobox2_TextChanged(object sender, EventArgs e){ if (cmbDataSourceExtractor.IsBusy) cmbDataSourceExtractor.CancelAsync(); var filledComboboxValues = new FilledComboboxValues{ V1 = combobox1.Text, V2 = combobox2.Text}; cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues );} As far as building DataSource is time-consuming process (it creates a request to database and executes it) I decided that it's better to perform it in another process using BackgroundWorker. So there's a scenario when cmbDataSourceExtractor hasn't completed its work and the user types one more symbol. In this case I get an exception on this line cmbDataSourceExtractor.RunWorkerAsync(filledComboboxValues ); about that BackgroundWorker is busy and cannot perform several actions in the same time. How to get rid of this exception? Thanks in advance!
Now provide the response and nothing else.
| CancelAsync doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker.CancellationPending . Your DoWork delegate that is being run in the background must periodically check this property and handle the cancellation itself. The tricky part is that your DoWork delegate is probably blocking, meaning that the work you do on your DataSource must complete before you can do anything else (like check for CancellationPending). You may need to move your actual work to yet another async delegate (or maybe better yet, submit the work to the ThreadPool ), and have your main worker thread poll until this inner worker thread triggers a wait state, OR it detects CancellationPending. http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync.aspx http://www.codeproject.com/KB/cpp/BackgroundWorker_Threads.aspx | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4732737', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/219976/']} | jdg_379637 |
stackexchange | llm_judgeable_groundtruth_similarity | 9004303 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
File1.groovy def method() { println "test"} File2.groovy method() I want to load/include the functions/methods from File1.groovy during runtime, equals to rubys/rake's load. They are in two different directories.
Now provide the response and nothing else.
| If you don't mind the code in file2 being in a with block, you can do: new GroovyShell().parse( new File( 'file1.groovy' ) ).with { method()} Another possible method would be to change file1.groovy to: class File1 { def method() { println "test" }} And then in file2.groovy you can use mixin to add the methods from file1 def script = new GroovyScriptEngine( '.' ).with { loadScriptByName( 'file1.groovy' )} this.metaClass.mixin scriptmethod() | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9004303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/540992/']} | jdg_379638 |
stackexchange | llm_judgeable_groundtruth_similarity | 17152719 |
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 csv file named data.csv such as TS;val10:00;0.110:05;0.210:10;0.310:15;0.4 I read this csv file using this script #!/usr/bin/env pythonimport pandas as pdif __name__ == "__main__": yyyy = 2013 mm = 2 dd = 1 df = pd.read_csv('data.csv', sep=';', parse_dates=[0], index_col=0) print(df) I get this valTS 2013-06-17 10:00:00 0.12013-06-17 10:05:00 0.22013-06-17 10:10:00 0.32013-06-17 10:15:00 0.4 I would like to change date of every DateTimeIndex to 2013-02-01 valTS 2013-02-01 10:00:00 0.12013-02-01 10:05:00 0.22013-02-01 10:10:00 0.32013-02-01 10:15:00 0.4 What is the easier way to do this ?
Now provide the response and nothing else.
| Timestamps have a replace method (just like datetimes): In [11]: df.index.map(lambda t: t.replace(year=2013, month=2, day=1))Out[11]:array([Timestamp('2013-02-01 10:00:00', tz=None), Timestamp('2013-02-01 10:05:00', tz=None), Timestamp('2013-02-01 10:10:00', tz=None), Timestamp('2013-02-01 10:15:00', tz=None)], dtype=object) So set your index to this: In [12]: df.index = df.index.map(lambda t: t.replace(year=2013, month=2, day=1)) Worth mentioning that you can pass in a date_parser function to read_csv , which might make more sense for you: In [21]: df = pd.read_csv(file_name, sep=';', parse_dates=[0], index_col=0, date_parser=lambda time: pd.Timestamp('2013/02/01 %s' % time))In [22]: dfOut[22]: valTS2013-02-01 10:00:00 0.12013-02-01 10:05:00 0.22013-02-01 10:10:00 0.32013-02-01 10:15:00 0.4 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17152719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1609077/']} | jdg_379639 |
stackexchange | llm_judgeable_groundtruth_similarity | 289011 |
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:
What "General dispersion relation", has to do with Dispersion relation , in general?And what is the use of it in cosmology?
Now provide the response and nothing else.
| Dispersion relations are the equations relating frequency to wavelength or wavenumber, or either one to the speed of any waves. For light in vacuum $\omega$ (w 2pi*frequency) and k (2pi/wavelength) are proportional with c as the proportionality factor. If that's not true, as in a prism, where different wavelengths or freqs have different indices of refraction and the different colors separate. It's used for any wave phenomena. In cosmology it has been used for the density perturbations of matter, and including the spatial variations in mass density, I.e, it's about the formation of structure (such as galaxies, stars) due to gravitational attraction in the expanding universe. So the waves are then waves of the metric perturbation due to matter density perturbation, in an expanding universe. Since they arise from density perturbations they are sometimes called acoustic perturbations An example is at https://arxiv.org/pdf/1308.5708v2.pdf where it is used to get the growth of perturbations due to inflation very early in the universe. This is called the trans-Planckian problem, because the start of inflation is at about Planckian times and sizes, in the early part of inflation. Different posited quantum gravity models lead to different dispersion relations during those times, with $\omega$ and k not proportional, i.e., the speed of the density perturbations varying with the size of the perturbations. Another example of its use is at https://arxiv.org/abs/1609.06891 . Note that these primordial perturbations later grew into the density inhomogeneities and anisotropy we see due to the formation of higher density regions like galaxies and stars, and cluster/superclusters. Those are also reflected, as the perturbations were read at about 380,000 years after the Big Bang, in the CMB. For the CMB see http://www.weizmann.ac.il/particle/waxman/Cosmo/linearpert_CMB.pdf , where they treat the acoustic perturbations, i.e. The density fluctuations that gave rise to the anisotropy of the CMB, and now measured. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/289011', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/133041/']} | jdg_379640 |
Subsets and Splits