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
6377231
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just upgraded to Django 1.3. My test suite is now showing a bunch of useless warnings like this every time I check that a given URL is 404. It didn't do that under Django 1.2. For example, let's say we have views and URLs wired up such that this test passes: def test_foo(self): response = self.client.get('/foo/bar/') self.assertEqual(response.status_code, 200) response = self.client.get('/foo/bar2/') self.assertEqual(response.status_code, 404) Although the test passes, the 404 (which we expect) triggers a warning to the console: .WARNING Not Found: /foo/bar2/ This is just useless noise; I have about 30 of them in one of my current test suites. Is there a way to silence those just during tests ? I'd like to leave them on during normal operation. And I don't think I want to filter out all warnings from the 'django.request' logger. Now provide the response and nothing else.
The warning is coming from here: http://code.djangoproject.com/svn/django/trunk/django/core/handlers/base.py What you want to do is set the logging threshold of the 'django.request' module to something above WARNING (e.g. ERROR) at the beginning of the test, and then set it back afterward. Try something like this: import logging#before testslogger = logging.getLogger('django.request')previous_level = logger.getEffectiveLevel()logger.setLevel(logging.ERROR)#after testslogger.setLevel(previous_level)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6377231', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/137635/']}
jdg_76441
stackexchange
llm_judgeable_groundtruth_similarity
39511088
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am facing a weird bug, that happens only on iOS 10. I have a application with several screens, and each screen colors the navigationBar in viewWillAppear . So when you go to the next screen, it will be properly colored. However, when testing on iOS 10 I suddenly see the following behaviour when going back to a previous screen:When the previous screen appears the navigationBar still has the color of the previous screen and then flashes to the proper color.It almost looks like viewWillAppear somehow behaves as viewDidAppear . Relevant code: ViewController: - (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; [ViewControllerPainter paint:self withBackground:[UIColor whiteColor] andForeground:[UIColor blackColor] andIsLight:true];} Painter: + (void)paint:(UIViewController *)controller withBackground:(UIColor *)backgroundColor andForeground:(UIColor *)foregroundColor andIsLight:(bool)isLight{ controller.navigationController.navigationBar.opaque = true; controller.navigationController.navigationBar.translucent = false; controller.navigationController.navigationBar.tintColor = foregroundColor; controller.navigationController.navigationBar.barTintColor = backgroundColor; controller.navigationController.navigationBar.backgroundColor = backgroundColor; controller.navigationController.navigationBar.barStyle = isLight ? UIBarStyleDefault : UIBarStyleBlack; controller.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: foregroundColor};} Is this a bug? Is there something I can do about to fix this? It's very frustrating. Now provide the response and nothing else.
Here's what changed according to the iOS 10 SDK Release Notes : In iOS 10, UIKit has updated and unified background management for UINavigationBar, UITabBar, and UIToolbar. In particular, changes to background properties of these views (such as background or shadow images, or setting the bar style) may kick off a layout pass for the bar to resolve the new background appearance. In particular, this means that attempts to change the background appearance of these bars inside of -[UIView layoutSubviews], -[UIView updateConstraints], -[UIViewController willLayoutSubviews], -[UIViewController didLayoutSubviews], - [UIViewController updateViewConstraints], or any other method that is called in response to layout may result in a layout loop. So the problem seems to be that viewWillAppear is triggering the mentioned layout loop, since it's called as a result of a layout change: The quick fix for me was overriding popViewControllerAnimated and pushViewController and updating the navigationBar background on my subclass of UINavigationController . Here's how it looks like: override func popViewControllerAnimated(animated: Bool) -> UIViewController? { let poppedViewController = super.popViewControllerAnimated(animated) // Updates the navigation bar appearance updateAppearanceForViewController(nextViewController) return poppedViewController}override func pushViewController(viewController: UIViewController, animated: Bool) { super.pushViewController(viewController, animated: animated) // Updates the navigation bar appearance updateAppearanceForViewController(viewController)} My guess is that it works because popViewControllerAnimated and pushViewController are not called by the OS as a result of a layout change, but by a touch event. So keep that in mind if you want to find another place to update your navigationBar background.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39511088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107029/']}
jdg_76442
stackexchange
llm_judgeable_groundtruth_similarity
268764
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: In a set of if/elif/else/fi statements, I have made 'else' present the user with an error message, but I also want it to take the user back to the question which was asked before the if/else statements so that they can try to answer it again. How do I take the user back to a previous line of code? Or, if this is not possible, is there another way to do this? Now provide the response and nothing else.
I think the easiest way would be to wrap the prompting code into a function, and then drop it into an until loop. Since all you need really is to call the function until it succeeds, you can put the noop command " : " in the until loop. Something like this: #!/bin/bashgetgender() { read -p "What is the gender of the user? (male/female): " gender case "$gender" in m|M) grouptoaddto="boys" return 0 ;; f|F) grouptoaddto="girls" return 0 ;; *) printf %s\\n "Please enter 'M' or 'F'" return 1 ;; esac}until getgender; do : ; donesudo usermod -a -G "$grouptoaddto" "$username" The point here is the function called with until , so it is repeatedly called until it succeeds. The case switch within the function is just an example. Simpler example, without using a function: while [ -z "$groupname" ]; do read -p "What gender is the user?" answer case "$answer" in [MmBb]|[Mm]ale|[Bb]oy) groupname="boys" ;; [FfGg]|[Ff]emale|[Gg]irl) groupname="girls" ;; *) echo "Please choose male/female (or boy/girl)" ;; esacdonesudo usermod -a -G "$groupname" "$username" In this last example, I'm using the -z switch to the [ (test) command, to continue the loop as long as the "groupname" variable has zero length. The keynote is the use of while or until . To translate this last example into human readable pseudocode: While groupname is empty, ask user for gender. If he answers with one letter "m" or "B", or the word "Male" or "boy", set the groupname as "boys". If she answers with one letter "F" or "g", or the word "female" or "Girl", set the groupname as "girls". If he/she answers anything else, complain.(And then repeat, since groupname is still empty.)Once you have groupname populated, add the user to that group. Yet another example, without the groupname variable: while true; do read -p "What gender is the user?" answer case "$answer" in [MmBb]|[Mm]ale|[Bb]oy) sudo usermod -a -G boys "$username" break ;; [FfGg]|[Ff]emale|[Gg]irl) sudo usermod -a -G girls "$username" break ;; *) echo "Please choose male/female (or boy/girl)" ;; esacdone
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/268764', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/142920/']}
jdg_76443
stackexchange
llm_judgeable_groundtruth_similarity
2987605
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For example, input is Array 1 = [2, 3, 4, 5]Array 2 = [3, 2, 5, 4] Minimum number of swaps needed are 2 . The swaps need not be with adjacent cells, any two elements can be swapped. https://www.spoj.com/problems/YODANESS/ Now provide the response and nothing else.
As @IVlad noted in the comment to your question Yodaness problem asks you to count number of inversions and not minimal number of swaps. For example: L1 = [2,3,4,5]L2 = [2,5,4,3] The minimal number of swaps is one (swap 5 and 3 in L2 to get L1 ), but number of inversions is three : (5 4), (5 3), and (4 3) pairs are in the wrong order. The simplest way to count number of inversions follows from the definition : A pair of elements (p i ,p j ) is called an inversion in a permutation p if i < j and p i > p j . In Python: def count_inversions_brute_force(permutation): """Count number of inversions in the permutation in O(N**2).""" return sum(pi > permutation[j] for i, pi in enumerate(permutation) for j in xrange(i+1, len(permutation))) You could count inversion in O(N*log(N)) using divide & conquer strategy (similar to how a merge sort algorithm works). Here's pseudo-code from Counting Inversions translated to Python code: def merge_and_count(a, b): assert a == sorted(a) and b == sorted(b) c = [] count = 0 i, j = 0, 0 while i < len(a) and j < len(b): c.append(min(b[j], a[i])) if b[j] < a[i]: count += len(a) - i # number of elements remaining in `a` j+=1 else: i+=1 # now we reached the end of one the lists c += a[i:] + b[j:] # append the remainder of the list to C return count, cdef sort_and_count(L): if len(L) == 1: return 0, L n = len(L) // 2 a, b = L[:n], L[n:] ra, a = sort_and_count(a) rb, b = sort_and_count(b) r, L = merge_and_count(a, b) return ra+rb+r, L Example: >>> sort_and_count([5, 4, 2, 3])(5, [2, 3, 4, 5]) Here's solution in Python for the example from the problem : yoda_words = "in the force strong you are".split()normal_words = "you are strong in the force".split()perm = get_permutation(normal_words, yoda_words)print "number of inversions:", sort_and_count(perm)[0]print "number of swaps:", number_of_swaps(perm) Output: number of inversions: 11number of swaps: 5 Definitions of get_permutation() and number_of_swaps() are: def get_permutation(L1, L2): """Find permutation that converts L1 into L2. See http://en.wikipedia.org/wiki/Cycle_representation#Notation """ if sorted(L1) != sorted(L2): raise ValueError("L2 must be permutation of L1 (%s, %s)" % (L1,L2)) permutation = map(dict((v, i) for i, v in enumerate(L1)).get, L2) assert [L1[p] for p in permutation] == L2 return permutationdef number_of_swaps(permutation): """Find number of swaps required to convert the permutation into identity one. """ # decompose the permutation into disjoint cycles nswaps = 0 seen = set() for i in xrange(len(permutation)): if i not in seen: j = i # begin new cycle that starts with `i` while permutation[j] != i: # (i σ(i) σ(σ(i)) ...) j = permutation[j] seen.add(j) nswaps += 1 return nswaps
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2987605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/320615/']}
jdg_76444
stackexchange
llm_judgeable_groundtruth_similarity
50299548
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's going on here? Why are %a{3} and %a{3}.Array different if %a has Array values and %a{3} is an Array ? > my Array %a{}> %a{3}.push("foo")[foo]> %a{3}.push("bar")[foo bar]> %a{3}.push("baz")[foo bar baz]> .say for %a{3}[foo bar baz]> %a{3}.WHAT(Array)> .say for %a{3}.Arrayfoobarbaz Now provide the response and nothing else.
The difference being observed here is the same as with: my $a = [1,2,3];.say for $a; # [1 2 3].say for $a.Array; # 1\n2\n3\n The $ sigil can be thought of as meaning "a single item". Thus, when given to for , it will see that and say "aha, a single item" and run the loop once. This behavior is consistent across for and operators and routines . For example, here's the zip operator given arrays and them itemized arrays: say [1, 2, 3] Z [4, 5, 6]; # ((1 4) (2 5) (3 6))say $[1, 2, 3] Z $[4, 5, 6]; # (([1 2 3] [4 5 6])) By contrast, method calls and indexing operations will always be called on what is inside of the Scalar container. The call to .Array is actually a no-op since it's being called on an Array already, and its interesting work is actually in the act of the method call itself, which is unwrapping the Scalar container. The .WHAT is like a method call, and is telling you about what's inside of any Scalar container. The values of an array and a hash are - by default - Scalar containers which in turn hold the value. However, the .WHAT used to look at the value was hiding that, since it is about what's inside the Scalar . By contrast, .perl [1] makes it clear that there's a single item: my Array %a;%a{3}.push("foo");%a{3}.push("bar");say %a{3}.perl; $["foo", "bar"] There are various ways to remove the itemization: %a{3}.Array # Identity minus the container%a{3}.list # Also identity minus the container for Array@(%a{3}) # Short for %a{3}.cache, which is same as .list for Array%a{3}<> # The most explicit solution, using the de-itemize op|%a{3} # Short for `%a{3}.Slip`; actually makes a Slip I'd probably use for %a{3}<> { } in this case; it's both shorter than the method calls and makes clear that we're doing this purely to remove the itemization rather than a coercion. While for |%a{3} { } also works fine and is visually nice, it is the only one that doesn't optimize down to simply removing something from its Scalar container, and instead makes an intermediate Slip object, which is liable to slow the iteration down a bit (though depending on how much work is being done by the loop, that could well be noise). [1] Based on what I wrote, one may wonder why .perl can recover the fact that something was itemized. A method call $foo.bar is really doing something like $foo<>.^find_method('bar')($foo) . Then, in a method bar() { self } , the self is bound to the thing the method was invoked on, removed from its container. However, it's possible to write method bar(\raw-self:) { } to recover it exactly as it was provided.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50299548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7730888/']}
jdg_76445
stackexchange
llm_judgeable_groundtruth_similarity
1940841
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently building an app that will parse all of the Audit entries in a site collection and send out a pretty email to users. My problem is that the emails should be based on a particular web (essentially an email summarizing the changes that happened to each subsite). Apparently, there is no information in the SPAuditEntry object about the web it came from except for the DocLocation property. This means I can get any of the following DocLocations (ItemType = Document, Event = Update): sites/MySiteCollection/Documents/This is a test.doc sites/MySiteCollection/Reporting Templates/audit.xml sites/MySiteCollection/Lists/Reporting Metadata/1_.000 sites/MySiteCollection/MySubSite1/Lists/Announcements/2_.000 sites/MySiteCollection/MySubSite1/Template Documents/SampleTestEmail.doc I'm thinking I can probably figure out the web from the URL by using SPSite.AllWebs.Names if I have to. Q: How do I figure out which SPWeb a particular SPAuditEntry comes from? Now provide the response and nothing else.
Here's one example of drawing a line directly into a matrix. First, we'll create a matrix of zeros for an empty image: mat = zeros(250, 250, 'uint8'); % A 250-by-250 matrix of type uint8 Then, let's say we want to draw a line running from (30, 35) to (200, 60) . We'll first compute how many pixels long the line will have to be: x = [30 200]; % x coordinates (running along matrix columns)y = [35 60]; % y coordinates (running along matrix rows)nPoints = max(abs(diff(x)), abs(diff(y)))+1; % Number of points in line Next, we compute row and column indices for the line pixels using linspace , convert them from subscripted indices to linear indices using sub2ind , then use them to modify mat : rIndex = round(linspace(y(1), y(2), nPoints)); % Row indicescIndex = round(linspace(x(1), x(2), nPoints)); % Column indicesindex = sub2ind(size(mat), rIndex, cIndex); % Linear indicesmat(index) = 255; % Set the line pixels to the max value of 255 for uint8 types You can then visualize the line and the filtered version with the following: subplot(1, 2, 1);image(mat); % Show original line imagecolormap(gray); % Change colormaptitle('Line');subplot(1, 2, 2);h = fspecial('gaussian', 20, 10); % Create filterfilteredImg = imfilter(mat, h); % Filter imageimage(filteredImg); % Show filtered line imagetitle('Filtered line');
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1940841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/98933/']}
jdg_76446
stackexchange
llm_judgeable_groundtruth_similarity
49873174
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 below snippets? var a = 0;function b(){ a = 10; return function a(){};}b();console.log(a); // => 10 and var a = 0;function b(){ a = 10; return function a(){};}b();console.log(a); // => 0 It has something to do with JavaScript hoisting, but my understanding of the concept gives exactly the opposite output. Now provide the response and nothing else.
return function a(){}; Here function ... is an expression. A named function expression to be precise. The a here doesn't matter much, it just gives the anonymous function a .name , but it's still just a function expression that you're returning. return function a(){}; This here is equivalent to: return;function a(){}; Here function a is a declaration, not an expression. It is hoisted, creating a local name a in the scope, shadowing the outer a . I.e. it is equivalent to: function b(){ var a = function () {}; a = 10; return;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/49873174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3243267/']}
jdg_76447
stackexchange
llm_judgeable_groundtruth_similarity
23967390
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Long story short, I have a button. On clicking it, I want an ajax request to be triggered which gets flash[:notice] and displays it in a div in$ Here is my shortened view: <input type="button" id="search" value="display"/> <div id="notice"> </div> My ajax request in the view: $("#search").submit(function(){ $.ajax({ type: "POST", url: //url to my show action success: function(data){ /*$("#notice").html("<%= flash[:notice] %>"); $("#content").html(data);*/ } }); return false; }); My controller: def HomeController < ActionController::Base def index end def show respond_to do |format| format.js { flash[:notice] = "" + count.to_s + " results found for " + params[:query][:search_key] + "" } end #render :partial => 'search' endend My show.js.erb #app/views/dashboard_home/show.js.erb$("#notice").html("<%=j flash[:notice] %>");$("#content").html("<%=j render partial: "search" %>"); The problem is when I click on button, the notice is displayed fine. But the same notice persists on the next clicks too. The search partial contains the table Please help! Now provide the response and nothing else.
Sessions the same notice persists on the next clicks too This is caused by the flash being stored in the session variable of Rails : The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc. The problem you have is that since I don't think ajax counts as a new request (need reference for this), the data will persist into the next time you request via HTTP. -- Fix I would initially try this: def show respond_to do |format| format.js { flash[:notice] = "my secret number "+rand(0,5)+" !" } endend The main problem you have is you're processing the flash variable in your JS using the ERB preprocessor. This is an issue as it means you won't be able to use asset precompile to help it work. After looking at this question , why not try using the after_filter callback , like this: #app/controllers/home_controller.rbClass Home < ActionController::Base after_filter { flash.discard if request.xhr? }, only: :show def show respond_to do |format| format.js { flash[:notice] = "my secret number "+rand(0,5)+" !" } end endend -- Update You should include the success functionality in your show.js.erb : #app/views/home/show.js.erb$("#notice").html("<%= flash[:notice] %>"); This means you can remove the whole ajax call from the application.js , and replace with the remote: true for your search form: #app/views/search/index.html.erb<%= form_tag home_show_path, remote: true %> The reason this works is because when you use the format.js respond block, Rails will load the [action].js.erb file in your views. Considering this only happens after the action has been completed, it's equivalent to the success function of your ajax. By doing this, you'll be able to remove the entire ajax function from your application.js , and replace with the UJS version, as described above
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23967390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2958963/']}
jdg_76448
stackexchange
llm_judgeable_groundtruth_similarity
31993377
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Question How is it that for a scanner object the hasNextLine() method returns true while the hasNext() method returns false? Note: Based on the input file, the hasNext() method is returning the result as expected; the hasNextLine() does not seem to be returning the correct result. Code Here's the code I'm running that's creating the results below: public void ScannerTest(Reader fileReaderObject){ Scanner scannerObj = new Scanner(fileReaderObject); for(int i = 1; scannerObj.hasNext(); i++){ System.out.println(i + ": " + scannerObj.next()); System.out.println("Has next line: " + scannerObj.hasNextLine()); System.out.println("Has next: " + scannerObj.hasNext()); } System.out.println(); scannerObj.close();} Input File The following is the actual content of the file that I'm passing to this scanner: a 3 9b 3 6c 3 3d 2 8e 2 5f 2 2g 1 7h 1 4i 1 1 Result The following is the end of what's printed in the console when I run my code, and includes the portion I can't make sense of: 25: iHas next line: trueHas next: true26: 1Has next line: trueHas next: true27: 1Has next line: trueHas next: false Now provide the response and nothing else.
You have a single extra newline at the end of your file. hasNextLine() checks to see if there is another linePattern in the buffer. hasNext() checks to see if there is a parseable token in the buffer, as separated by the scanner's delimiter. Since the scanner's delimiter is whitespace, and the linePattern is also white space, it is possible for there to be a linePattern in the buffer but no parseable tokens. Typically, the most common way to deal with this issue by always calling nextLine() after parsing all the tokens (e.g. numbers) in each line of your text. You need to do this when using Scanner when reading a user's input too from System.in . To advance the scanner past this whitespace delimiter, you must use scanner.nextLine() to clear the line delimiter. See: Using scanner.nextLine() Appendix: LinePattern is defined to be a Pattern that matches this: private static final String LINE_SEPARATOR_PATTERN = "\r\n|[\n\r\u2028\u2029\u0085]";private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$"; The default token delimiter is this Pattern : private static Pattern WHITESPACE_PATTERN = Pattern.compile( "\\p{javaWhitespace}+");
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31993377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5219813/']}
jdg_76449
stackexchange
llm_judgeable_groundtruth_similarity
203355
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'm trying to understand why one would add a batterypack to a raid card. It seems to me like if power goes down, running just the raid card is going to do little good: without power for HDs and motherboard, writing in-memory data isn't going to work anyway, right? In addition, doesn't having a UPS facilitate this? Now provide the response and nothing else.
It allows the raid card to remember what is in its buffers ( that hasnt been sync'd to disk ) Its very important for people who need high data integrity.. Or to save your DB from certain types of corruption.. (Basically whats on disk, is on disk - so thats safe.. The problem is when the OS thinks its on disk but its actually not and in a RAID card buffer) When the server starts up again, obviously those buffers get flushed to the disks.. So you have a point in time correlation with your disks and OS.. ( otherwise you will just loose information - like a few database records, which you will never know. ) A UPS help sure..but its not safe enough.. ever decent RAID card should have a BBU (Battery Backed Unit)
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/203355', 'https://serverfault.com', 'https://serverfault.com/users/-1/']}
jdg_76450
stackexchange
llm_judgeable_groundtruth_similarity
3623
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: Note: One, I am not sure if synthetic queries is right word for the risk I am talking about. Second, though I am considering 3-tier model of web-applications general answers are welcome in client-server situations where server side validation is not possible. Currently I have a page where you do certain computations using what is called as DHTML, This computation generates a string which has no particular pattern as such. This string is sent to a server side script using AJAX. Anyone with basic training in these technologies can read the code and realize that the query is sent is something like this: http://domain.com/script.php?var=theStringSoGenerated Hoping to exploit a possible flaw, a hacker types in his browser: http://domain.com/script.php?var=aCompletelyRandomString He does this a few times and sees no evident benefit and quits, but in the middle tier, the PHP script, completely helpless without a possible validation, updates and inserts the random string into the database impacting its integrity and leading to wastage of resources. Question: How can I protect my application against such attacks? Now provide the response and nothing else.
Why can't we escape all user input using "magic"? At the time the magic is applied, it is unknown where the data will end up. So magic quotes are destroying data that, unless it is written unescaped to a database. It may just be used in the HTML response sent back to the client. Think of a form that has not beem filled in completely and is therefore shown again to the user. With magic quotes, the data entered on the first attempt will now be SQL escaped, which is meaningless on an HTML page. Even worse: on the second submission the data is SQL escaped again. Why wasn't addslashes "good enough"? It has issues with multibyte characters: ' 27\ 5c뼧 bf 5c Those are two bytes, but only one Unicode character. Since addslashes does not know anything about Unicode, it converts the input bf 27 to bf 5c 27 . If this is read by a Unicode-aware program, it is seen as 뼧'. Boom. There is a good explanation of this issue at http://shiflett.org/blog/2006/jan/addslashes-versus-mysql-real-escape-string Whats wrong with using DB-specific escape functions, and why was it better than addslashes? They are better because they ensure that the escaping interprets the data in the same way the database does (see the last question). From a security point of view, they are okay if you use them for every single database input. But they have the risk that you may forget either of them somewhere. Edit : As getahobby added: Or that you use xxx_escape_strings for numbers without adding quotation marks around them in the SQL statement and without ensuring that they are actual numbers by casting or converting the input to the appropriate data type /Edit From a software development perspective they are bad because they make it a lot harder to add support for other SQL database server software. Why are prepared statements with frameworks and PDO being hailed as the gold standard of SQL? Why are they better? PDO is mostly a good thing for software design reasons. It makes it a lot easier to support other database server software. It has an object orientated interface which abstracts many of the little database specific incompatibilities. Why can't I do an SQL injection with these [prepared statements], where as I COULD have with the previously mentioned means? The " constant query with variable parameters " part of prepared statements is what is important here. The database driver will escape all the parameters automatically without the developer having to think about it. Parametrized queries are often easier to read that normal queries with escaped parameters for syntactic reasons. Depending on the environment, they may be a little faster. Always using prepared statements with parameters is something that can be validated by static code analysis tools . A missing call to xxx_escape_string is not spotted that easily and reliably. Can a programmer not somehow manage to still screw this up? What should they look out for? "Prepared statements" imply that the are constant . Dynamically generating prepared statements - especially with user input - still have all the injection issues.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/3623', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/2137/']}
jdg_76451
stackexchange
llm_judgeable_groundtruth_similarity
45394
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have heard that a moon in our solar system orbiting Saturn possesses geographical features that essentially spit out water and moisture from 'volcanoes' on its surface. The volume of water outputted thus far is such that it comprises a faint ring of Saturn Would it be possible for a rocky planet orbiting their Sun/gas giant to have the right combination of volcanic activity and low-gravity such that magma thrown up by the volcanoes ends up in orbit of the small planet, cooling over time to form rings? It seems to have happened with that specific moon of Saturn, with water, and rings formed around Saturn instead of the moon itself? Can it be possible with cooled-down lava? Now provide the response and nothing else.
This doesn't seem to occur in our solar system. The most volcanic body, Io, does create a trail of gas around its orbit of Jupiter, but has no ringlike structure of its own. As uhoh notes, orbital dynamics means that if an object is projected from the surface of a planet or moon it will either exceed escape velocity (in which case it goes out into space) or it will travel on an ellipse that must intersect with the starting position (at the surface). It is more or less impossible to put something into orbit with a single push from the surface. Rockets need an initial push up and then a push along to achieve orbit, though these phases are normally merged. However as uhoh also notes, in principle matter on an escape velocity could interact with other orbiting matter, lose some energy and so enter orbit as a ring. Perhaps a possible scenario is that matter is ejected into a torus of dust around the planet, which is then gathered by the moon into a ring. However this hasn't occurred in our solar system.
{}
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/45394', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/38081/']}
jdg_76452
stackexchange
llm_judgeable_groundtruth_similarity
4085529
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Having problems deserializing some xml into an object in C#. The error that I receive is... xmlns=''> was not expected. The XSD that I received to generate my class is as follows... <?xml version="1.0" encoding="UTF-8"?><xs:schema targetNamespace="xml.AAAAAAA.com/commerce/apres-vente_technique/assistance" xmlns:pgp="xml.AAAAAAA.com/commerce/apres-vente_technique/assistance" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified"> <xs:element name="ListeAvisRemboursements"> <xs:annotation> <xs:documentation>Liste des avis de remboursements</xs:documentation> </xs:annotation> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="AvisRemboursement" type="pgp:AvisRemboursementType"/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name="AvisRemboursementType"> <xs:annotation> <xs:documentation>Avis de remboursement lié à une DC</xs:documentation> </xs:annotation> <xs:sequence> (snipped) The file that I am attempting to import is as follows: <?xml version="1.0" encoding="UTF-8"?><ListeAvisRemboursements xmlns:ast="xml.AAAAAAA.com/commerce/apres-vente_technique/assistance"> <ast:AvisRemboursement NumeroDT="3826961" CodeRA="020545G01" NumeroDC="1"> <ast:DateTraitement>2010-06-22</ast:DateTraitement> <ast:MontantDC>25.0</ast:MontantDC> <ast:MontantMO>0.0</ast:MontantMO> <ast:SommeAD>25.0</ast:SommeAD> <ast:MontantPR>0.0</ast:MontantPR> <ast:SommePR>0.0</ast:SommePR> <ast:FraisGestion>0.0</ast:FraisGestion> <ast:NombreHeuresTotalRemboursees>0</ast:NombreHeuresTotalRemboursees> <ast:Etat>C</ast:Etat> <ast:NoteCredit>319984</ast:NoteCredit> <ast:Imputation>030</ast:Imputation> <ast:ListInterventionsPR/> <ast:ListInterventionsMO/> </ast:AvisRemboursement> (snipped) I think what is happening is that when .Net attempts to derserialize the xml, it hits the first line which contains the "xmlns:ast" and complaints about it. As I understand it, .Net will try to map attributes to a public property in the target class (and it wont find one called xmlns. Or there is something wrong with how I am handling the name spaces. My deserialization code looks as follows: XmlDocument _Doc = new XmlDocument(); _Doc.Load(@"C:\inputfile.xml"); XmlSerializer _XMLSer = new XmlSerializer(typeof(ListeAvisRemboursements)); ListeAvisRemboursements _X = (ListeAvisRemboursements)_XMLSer.Deserialize(new StringReader(_Doc.OuterXml)); I have also tried various combinations of adding a namespace manager to the XML document.. XmlNamespaceManager _Ns = new XmlNamespaceManager(_Doc.NameTable);_Ns.AddNamespace("ast", "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance"); I understand there is a way I can use this to tell .Net what namespaces to accept. Would be greatful for some help iwth this problem. --- Updated at request with class snippet (sorry should have included before) this was created with xsd.exe --- /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance", IsNullable = false)] public partial class ListeAvisRemboursements { private AvisRemboursementType[] avisRemboursementField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("AvisRemboursement")] public AvisRemboursementType[] AvisRemboursement { get { return this.avisRemboursementField; } set { this.avisRemboursementField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance")] public partial class AvisRemboursementType { private System.DateTime dateTraitementField; private double montantDCField; private double montantMOField; private double sommeADField; private double montantPRField; Now provide the response and nothing else.
Without a full xsd / xml, or (alternatively) your C# classes, we can't reproduce. But working from the xml upwards, this works fine for me; meaning: the error is not (as far as I can see) in the code/data you posted. Can you post a more complete (reproducible) example? public class ListeAvisRemboursements{ private readonly List<AvisRemboursement> items = new List<AvisRemboursement>(); [XmlElement("AvisRemboursement", Namespace = "xml.AAAAAAA.com/commerce/apres-vente_technique/assistance")] public List<AvisRemboursement> Items { get { return items; } }}public class AvisRemboursement{ [XmlAttribute] public string NumeroDT {get;set;} [XmlAttribute] public string CodeRA {get;set;} [XmlAttribute] public string NumeroDC {get;set;} public DateTime DateTraitement { get; set; } public decimal MontantDC { get; set; } public decimal MontantMO { get; set; } public decimal SommeAD { get; set; } public decimal MontantPR { get; set; } public decimal SommePR { get; set; } public decimal FraisGestion { get; set; } public int NombreHeuresTotalRemboursees { get; set; } public string Etat { get; set; } public string NoteCredit { get; set; } public string Imputation { get; set; }}static void Main(){ var ser = new XmlSerializer(typeof(ListeAvisRemboursements)); var wrapper = (ListeAvisRemboursements)ser.Deserialize(new StringReader(xml)); // inspect wrapper.Items etc} also works fine with: var ser = new XmlSerializer(typeof(ListeAvisRemboursements));using (var reader = XmlReader.Create("inputfile.xml")){ var wrapper = (ListeAvisRemboursements)ser.Deserialize(reader);} and: XmlDocument _Doc = new XmlDocument();_Doc.Load("inputfile.xml");var ser = new XmlSerializer(typeof(ListeAvisRemboursements));var wrapper = (ListeAvisRemboursements)ser.Deserialize(new StringReader(_Doc.OuterXml)); and XmlDocument _Doc = new XmlDocument();_Doc.Load("inputfile.xml");var ser = new XmlSerializer(typeof(ListeAvisRemboursements));var wrapper = (ListeAvisRemboursements)ser.Deserialize(new XmlNodeReader(_Doc.DocumentElement));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4085529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/169640/']}
jdg_76453
stackexchange
llm_judgeable_groundtruth_similarity
31096035
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 the select I'm doing: $query = "SELECT gestiondoc_publicados_tags.tag FROM gestiondoc_publicados_tags, gestionDoc_publicados_permisos WHERE gestionDoc_publicados_permisos.id_publicado = gestiondoc_publicados_tags.id_publicado AND gestionDoc_publicados_permisos.cargo = :cargo"; The table gestiondoc_publicados_tags is like: | id | tag | id_publicado || 1 | tag1| 1 || 2 | tag2| 1 | The table gestiondoc_publicados_permisos is like: | id | cargo | id_publicado || 1 | cargo1 | 1 || 2 | cargo2 | 1 | I want to get every tag where the id_publicado is equal to the id_publicado where cargo is equal to cargo1, but I'm only getting tag1 as the result, how can I do the query properly? Now provide the response and nothing else.
There are 5 options that could be considered as implementations of «Hash notation» (the last two are kinda hash- ish ): With Ruby on Rails 5 you are able to do the following chaining using ActiveRecord::Relation#or method: Person.where(name: 'Neil').or(Person.where(age: 27)) Use where_values together with reduce . The unscoped method is necessary only for Rails 4.1+ to ensure default_scope is not included in the where_values . Otherwise predicates from both default_scope and where would be chained with the or operator: Person.where( Person.unscoped.where(name: ['Neil'], age: [27]).where_values.reduce(:or) ) Install third-party plugins that implement these or similar features, for example: Where Or (backport of the Ruby on Rails 5 .or feature mentioned above) Squeel Person.where{(name == 'Neil') | (age == 27)} RailsOr Person.where(name: 'Neil').or(age: 27) ActiverecordAnyOf Person.where.anyof(name: 'Neil', age: 27) SmartTuple Person.where( (SmartTuple.new(' or ') << {name: 'Neil', age: 27}).compile) Use Arel : Person.where( Person.arel_table[:name].eq('Neil').or( Person.arel_table[:age].eq(27) ) ) Use prepared statements with named parameters: Person.where('name = :name or age = :age', name: 'Neil', age: 27)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/31096035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5029943/']}
jdg_76454
stackexchange
llm_judgeable_groundtruth_similarity
22787139
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a cron php script which will run once a day. Because it runs this way, the output from the file can't be seen. I could literally write all the messages I want into a variable, appending constantly information I want to be written to file, but this would be very tedious and I have a hunch not necessary. Is there a PHP command to tell the write buffer to write to a log file somewhere? Is there a way to get access to what has been sent to the buffer already so that I can see the messages my script makes. For example lets say the script says PHP: <? echo 'hello there'; echo 'hello world';?> It should output to a file saying: 'hello therehello world'; Any ideas? Is this possible? I'm already aware of file_put_contents('log.txt', 'some data', FILE_APPEND); This is dependent upon 'some data', when I don't know what 'some data' is unless I put it in a variable. I'm trying to catch the results of whatever PHP has outputted. Now provide the response and nothing else.
You may want to redirect your output in crontab : php /path/to/php/file.php >> log.txt Or use PHP with, for example, file_put_contents() : file_put_contents('log.txt', 'some data', FILE_APPEND); If you want to capture all PHP output, then use ob_ function, like: ob_start();/*We're doing stuff..stuff...and again*/$content = ob_get_contents();ob_end_clean(); //here, output is cleaned. You may want to flush it with ob_end_flush()file_put_contents('log.txt', $content, FILE_APPEND);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22787139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1606689/']}
jdg_76455
stackexchange
llm_judgeable_groundtruth_similarity
6366054
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 use git and I have many computers. I usually work on my desktop, but sometimes use laptops. How do you sync source code on git when you go home from work and you didn't finish working on the code? Do you send a patch file through email or just commit to git the incomplete codes? I agree the latter is more convenient, but I think it makes the git changelog dirty. Now provide the response and nothing else.
Commit your work in progress and push it to a remote branch. When you're ready to merge it into your main branch you can use an interactive rebase to rewrite your history and eliminate "work in progress" commits.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6366054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342355/']}
jdg_76456
stackexchange
llm_judgeable_groundtruth_similarity
18862214
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two separate node applications. I'd like one of them to be able to start the other one at some point in the code. How would I go about doing this? Now provide the response and nothing else.
Use child_process.fork() . It is similar to spawn() , but is used to create entire new instances of V8. Therefore it is specially used for running new instances of Node. If you are just executing a command, then use spawn() or exec() . var fork = require('child_process').fork;var child = fork('./script'); Note that when using fork() , by default, the stdio streams are associated with the parent. This means all output and errors will be shown in the parent process. If you don't want the streams shared with the parent, you can define the stdio property in the options: var child = fork('./script', [], { stdio: 'pipe'}); Then you can handle the process separately from the master process' streams. child.stdin.on('data', function(data) { // output from the child process}); Also do note that the process does not exit automatically. You must call process.exit() from within the spawned Node process for it to exit.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18862214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2789699/']}
jdg_76457
stackexchange
llm_judgeable_groundtruth_similarity
47090574
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 several components which have the following CSS/component structure About/style.css .AboutContainer { # Some style}p > code { # Some style} And I import the CSS in the componet as follows About/index.js import './style.css';export default class About extends Component { render() { # Return some component }} However, the CSS is imported in the <header> section and stays global-scope. I was expecting CSS to be: Component-scoped in a way that the style is only applied to things that are only rendered within this component. Style for this component would disappear if the component is unmounted. However, when inspecting from the browser, the styles are specified at the <header> section and gets applied to all the components <header> // Stuff <style type="text/css">style for component About</style> <style type="text/css">style for component B</style> <style type="text/css">style for component C</style> // Stuff</header> How do I import CSS to be component-scoped? It seems like I'm understanding CSS import in React ES6 incorrectly. I was following this tutorial Edit Answer by Brett is correct. However, my problem turns out to be somewhere else. I created my app using create-react-app which basically simplifies setups required to do React. It include WebPack, Babel and other things to get started. The default WebPack config that it uses did not set module option for the css-loader so it defaulted to false , and as a result the local-scoping was not enabled. Just for additional info, it seems like create-react-app does not have straightforward way to customize WebPack config, but there seem to be numerous how-to workarounds on the web. Now provide the response and nothing else.
It sounds like CSS Modules , or many of the other CSS-in-JS packages, does what you want. Others include Emotion (my current favorite), Styled Components , or many of the packages here . A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. All URLs (url(...)) and @imports are in module request format (./xxx and ../xxx means relative, xxx and xxx/yyy means in modules folder, i. e. in node_modules). Here's a quick example: Let's say we have a React component like: import React from 'react';import styles from './styles/button.css';class Button extends React.Component { render() { return ( <button className={styles.button}> Click Me </button> ); }}export default Button; and some CSS in ./styles/button.css of: .button { border-radius: 3px; background-color: green; color: white;} After CSS Modules performs it's magic the generated CSS will be something like: .button_3GjDE { border-radius: 3px; background-color: green; color: white;} where the _3DjDE is a randomly generated hash - giving the CSS class a unique name. An Alternative A simpler alternative would be to avoid using generic selectors (like p , code , etc) and adopt a class-based naming convention for components and elements. Even a convention like BEM would help in preventing the conflicts you're encountering. Applying this to your example, you might go with: .aboutContainer { # Some style}.aboutContainer__code { # Some style} Essentially all elements you need to style would receive a unique classname.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/47090574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/633565/']}
jdg_76458
stackexchange
llm_judgeable_groundtruth_similarity
45124673
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem on my app and I want to report this bug. I develope the app which can crawls notifications using NotificationListenerService. It works well. But NotificationListenerService class has the problem I think. Because, If the app is crashed, app can't crawl the notification at all, UNTIL the phone reboots. Is anyone who can solve this problem?? Please help me. The bug is very clear!! But It is not easy to find the solution .... Now provide the response and nothing else.
If do you have already permissions then: In your service class or another service/activity you can switch the "component hability" to listen notifications : public void tryReconnectService() { toggleNotificationListenerService(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { ComponentName componentName = new ComponentName(getApplicationContext(), NotificationReaderV2Service.class); //It say to Notification Manager RE-BIND your service to listen notifications again inmediatelly! requestRebind(componentName); } }/*** Try deactivate/activate your component service*/ private void toggleNotificationListenerService() { PackageManager pm = getPackageManager(); pm.setComponentEnabledSetting(new ComponentName(this, NotificationReaderV2Service.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); pm.setComponentEnabledSetting(new ComponentName(this, NotificationReaderV2Service.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); } Your notification listener, is a SERVICE, it can be killed by System , you can do your service as FOREGROUND to drastically decrease the probability that the system will kill your service. @Override public void onListenerConnected() { super.onListenerConnected(); Log.d(TAG, "Service Reader Connected"); Notification not = createNotification(); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (mNotificationManager != null) { mNotificationManager.notify(NOTIFICATION_ID, not); } startForeground(NOTIFICATION_ID, not); //Alarm to auto - send Intents to Service to reconnect, you can ommit next line. alarmIt();} If do you like so more "safe", you can to programming not-friendly battery alarms, try to use inexact alarms please, the user's battery will be happy: private void alarmIt() { Log.d(TAG, "ALARM PROGRAMMATED at"+HotUtils.formatDate(new Date())); Calendar now = Calendar.getInstance(); now.setTimeInMillis(System.currentTimeMillis()); now.set(Calendar.MINUTE, now.get(Calendar.MINUTE) + 1); Intent intent = new Intent(this, NotificationReaderV2Service.class); intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); intent.setAction(REBIND_ACTION); PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0); AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); //The alarms that are repeated are inaccurate by default, use RTC_WAKE_UP at your convenience. //Alarm will fire every minute, CHANGE THIS iF DO YOU CAN, you can't use less than 1 minute to repeating alarms. manager.setRepeating(AlarmManager.RTC_WAKEUP, now.getTimeInMillis(), 1000 * 60 * 1, pendingIntent);} and next read the Intent to reconnect service binding: @Overridepublic int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "Notification service onStartCommandCalled"); if (intent!=null && !HotUtils.isNullOrEmpty(intent.getAction()) && intent.getAction().equals(REBIND_ACTION)){ Log.d(TAG, "TRYING REBIND SERVICE at "+HotUtils.formatDate(new Date())); tryReconnectService();//switch on/off component and rebind } //START_STICKY to order the system to restart your service as soon as possible when it was killed. return START_STICKY;} Keep in mind that doing all these steps you can sure that your service will be killed anyway by the system but this code will restart the service and make it harder to kill it. Maybe, you should consider using PARTIAL_WAKE_LOCK with your service and execute it in a process independently (:remote) if you want even more certainty (Maybe this is useless) I would like to add a common error that is often followed, NEVER override the onBind and onUnbind method or overwrite the INTENT ACTION. This will cause your service to not be connected and never run onListenerConnected Keep the Intent as it is, in most cases you do not need to edit it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45124673', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8282818/']}
jdg_76459
stackexchange
llm_judgeable_groundtruth_similarity
18876017
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I'm clicking a button, that is indeed inside an LinearLayout, I get this error on this line: LinearLayout ll = (LinearLayout) view; My method looks like this: public void adjDoa(final View view) { final CharSequence[] items = {"Get on with it!", "Doable!", "Maybe, maybe not.", "Unlikely!", "When pigs fly!"}; AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(GetItActivity.this); dialogBuilder.setTitle("Choose doability!"); dialogBuilder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { LinearLayout ll = (LinearLayout) view; TextView text = (TextView)ll.findViewById(R.id.tViewChDoa); text.setText(items[which]); } }); dialogBuilder.create().show();} What does it mean? Now provide the response and nothing else.
Although it can be as easy as sockeqwe's answer . Sometimes this error can happen if you have copied/pasted/moved a part of your layout XML to another part of the XML. If that is the case, cleaning the project through Project -> Clean will resolve that problem. In this particular case it seems like you want the parent of the button, in which case you need to call view.getParent(); like this: (Here I am typecasting to ViewGroup instead of LinearLayout because it really doesn't matter which kind of layout the parent is) ViewGroup ll = (ViewGroup) view.getParent(); If you only have one view with the id tViewChDoa , you don't need to get the LinearLayout before you get that view, if you have this code in your activity then this will work: TextView text = (TextView) findViewById(R.id.tViewChDoa);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18876017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2691489/']}
jdg_76460
stackexchange
llm_judgeable_groundtruth_similarity
53800184
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 3 php files and one webpage. When I click on a navbar link, how can I change from ?php include 'sample1.php'; ? to ?php include 'sample2.php'; ? using the same template. Instead of making multiple templates. Is this possible? - thanks Example:On the template the active is ?php include 'sample1.php'; ---- when I click sample2 link on the navbar... the template stays the same but sample2.php will be placed and sample1.php is removed -thanks Navbar - Home - Sample1 Sample2 Sample1 is active and it is on the webpage<?php include 'sample1.php'; ?> when I click Sample2 in the navbar, sample one should be replace by <?php include 'sample2.php'; ?>and replace sample1.php on the same webpage Now provide the response and nothing else.
Use URLSearchParams.get() as described on MDN : // Get the location object that is implicitly passed as props // for every page in the `pages` folderconst Index = ({ location }) => { console.log(location); // inspect location for yourself // the parameter to return for URL. Example: // https://localhost:8000/?parameter1=firstParam&parameter2=secondParam const params = new URLSearchParams(location.search); const parameter1 = params.get("parameter1"); const parameter2 = params.get("parameter2"); console.log(parameter1); // -> "firstParam" console.log(parameter2); // -> "secondParam" // ... Alternative: package query-string yarn add query-string or npm i --save query-string import * as queryString from "query-string";// Get the location object that is implicitly passed as props // for every page in the `pages` folderconst Index = ({ location }) => { console.log(location); // inspect location for yourself // query-string parses the parameters that are contained in the location object const { parameter1, parameter2 } = queryString.parse(location.search); console.log(parameter1); console.log(parameter2); // ...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53800184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10750883/']}
jdg_76461
stackexchange
llm_judgeable_groundtruth_similarity
17878362
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Example self.accessibilityTraits |= UIAccessibilityTraitAdjustable; adds the UIAccessibilityTraitAdjustable option. But how to remove an option from the mask like this, without having to set everything? Now provide the response and nothing else.
And it with the complement of the flag: self.accessibilityTraits &= ~UIAccessibilityTraitAdjustable; If self.accessibilityTraits was: 000110 and UIAccessibilityTraitAdjustable is: 000100 ( these values are examples; I haven't looked-up the real values ) then self.accessibilityTraits &= ~UIAccessibilityTraitAdjustable; is: 000110& 111011= 000010
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17878362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221023/']}
jdg_76462
stackexchange
llm_judgeable_groundtruth_similarity
4925511
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to know what is the differecnce between Integer 16, Integer 32 and Integer 64, and the difference between a signed integer and an unsigned integer(NSInteger and NSUInteger) Now provide the response and nothing else.
I'm not sure exactly what types you mean by "Integer 16", "Integer 32", and "Integer 64", but normally, those numbers refer to the size in bits of the integer type. The difference between a signed and an unsigned integer is the range of values it can represent. For example, a two's-complement signed 16-bit integer can represent numbers between -32,768 and 32,767. An unsigned 16-bit integer can represent values between 0 and 65,535. For most computers in use today, a signed integer of width n can represent the values [-2 n -1 ,2 n -1 ) and an unsigned integer of width n can represent values [0,2 n ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4925511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/595146/']}
jdg_76463
stackexchange
llm_judgeable_groundtruth_similarity
8375755
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 a newbie question I have the following code: var total = 0Ldocs.foreach(total += _.length) in docs I have a collection of objects with the .length property I'd like something like: val total = docs.[someScalaMethod](0, (element, acum) => acum + element.length ) I mean, a method that iterates each element passing an accumulator variable... The first zero I pass should be the initial value of the accumulator var.. How can it be achieved? Now provide the response and nothing else.
This called a fold. It's almost exactly what you stated: docs.foldLeft(0)((accum, element) => accum + element.length) for the version that traverses the collection from left to right (usually preferable; right to left is foldRight , and 2.9 has a fold that can start anywhere, but has limitations on how it can transform the type). Once you get used to this, there is a short-hand version of fold left, where the accumulator goes on the left (think of it being pushed from left to right through the list), and you use placeholders for the variable names since you only use them once each: (0 /: docs)(_ + _.length)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8375755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47633/']}
jdg_76464
stackexchange
llm_judgeable_groundtruth_similarity
38036943
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 the Windows version of my current personal project, I'm looking to support extended length filepaths . As a result, I'm a little confused with how to use the GetFullPathNameW API to resolve the full name of a long filepath. According to the MSDN (with regards to the lpFileName parameter): In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\?\" to the path. For more information, see Naming a File. If I'm understanding this correctly, in order to use an extended length filepath with GetFullPathNameW , I need to specify a path with the \\?\ prefix attached. Since the \\?\ prefix is only valid before volume letters or UNC paths, this would mean that the API is unusable for resolving the full name of a path relative to the current directory. If that's the case, is there another API I can use to resolve the full name of a filepath like ..\somedir\somefile.txt if the resulting name's length exceeds MAX_PATH ? If not, would I be able to combine GetCurrentDirectory with the relative filepath ( \\?\C:\my\cwd\..\somedir\somefile.txt ) and use it with GetFullPathNameW , or would I need to handle all of the filepath resolution on my own? Now provide the response and nothing else.
GetFullPathNameA is limited to MAX_PATH characters, because it converts the ANSI name to a UNICODE name beforehand using a hardcoded MAX_PATH -sized (in chars) UNICODE buffer. If the conversion doesn't fail due to the length restrictions, then GetFullPathNameW (or direct GetFullPathName_U[Ex] ) is called and the resulting UNICODE name is converted to ANSI. GetFullPathNameW is a very thin shell over GetFullPathName_U . It is limited to MAXSHORT (0x7fff) length in WCHARs, independent of the \\?\ file prefix. Even without \\?\ , it will be work for long (> MAX_PATH ) relative names. However, if the lpFileName parameter does not begin with the \\?\ prefix, the result name in the lpBuffer parameter will not begin with \\?\ either. if you will be use lpBuffer with functions like CreateFileW - this function internally convert Win32Name to NtName . and result will be depended from nape type ( RTL_PATH_TYPE ). if the name does not begin with \\?\ prefix, the conversion fails because RtlDosPathNameToRelativeNtPathName_U[_WithStatus] fails (because if the path not begin with \\?\ it will be internally call GetFullPathName_U (same function called by GetFullPathNameW ) with nBufferLength hardcoded to MAX_PATH (exactly 2*MAX_PATH in bytes – NTDLL functions use buffer size in bytes, not in WCHAR s). If name begin with \\?\ prefix, another case in RtlDosPathNameToRelativeNtPathName_U[_WithStatus] is executed – RtlpWin32NtNameToNtPathName , which replaces \\?\ with \??\ and has no MAX_PATH limitation So the solution may look like this: if(ULONG len = GetFullPathNameW(FileName, 0, 0, 0)){ PWSTR buf = (PWSTR)_alloca((4 + len) * sizeof(WCHAR)); buf[0] = L'\\', buf[1] = L'\\', buf[2] = L'?', buf[3] = L'\\'; if (len - 1 == GetFullPathName(FileName, len, buf + 4, &c)) { CreateFile(buf, ...); }} So we need to specify a path with the \\?\ prefix attached, but not before GetFullPathName - after! For more info, read this - The Definitive Guide on Win32 to NT Path Conversion
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38036943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1017636/']}
jdg_76465
stackexchange
llm_judgeable_groundtruth_similarity
41467146
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: as the link https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute It then only gives an example of using the component immediately. I'm trying to find out how i would use this function to access the component immediately, and save the component for future use, as it says we are able to do. Now provide the response and nothing else.
The difference is using ref={callback} react passes the responsibility of managing the reference storage back to you. When you use ref="sometext", under the covers react has to create a refs property on your class and then add all the ref="sometext" statements to it. While its nice to have a simple this.refs.sometext access to components its difficult and error prone on the react side to clean up this refs property when the component is destroyed. It's much easier for react to pass you the component and let you handle storing it or not. According to the react docs React will call the ref callback with the DOM element when thecomponent mounts, and call it with null when it unmounts. This is actually a pretty slick idea, by passing null on unmount and calling your callback again you automatically clean up references. To actually use it all you have to do is access it from any function like so: class CustomTextInput extends React.Component { constructor(props) { super(props); this.focus = this.focus.bind(this); } focus() { // Explicitly focus the text input using the raw DOM API this.textInput.focus(); } render() { // Use the `ref` callback to store a reference to the text input DOM // element in this.textInput. return ( <div> <input type="text" ref={(input) => { this.textInput = input; }} /> <input type="button" value="Focus the text input" onClick={this.focus} /> </div> ); }} The callback you set on ref will receive the component as the first parameter, the 'this' word will be the current class 'CustomTextInput' in this example. Setting this.textInput in your callback will make textInput available to all other functions like focus() Concrete Example Tweet from Dan Abermov showing a case where ref callbacks work better Update Per Facebook Docs using strings for refs is consider legacy and they "recommend using either the callback pattern or the createRef API instead."
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41467146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7166494/']}
jdg_76466
stackexchange
llm_judgeable_groundtruth_similarity
29415522
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 RxJava I have a Subscriber object wich I subscribe on a Observable . Later on (some time after onComplete() has been invoked) I create a new Observable and subscribe with the same Subscriber instance used before. However, that seems not work. Is a subscriber not reusable? Example: class Loader extends Subscriber<T> { public void load(){ Observable.just("Foo").subscribe(this); } public void onComplete(){ // update UI }} In my code I would like to instantiate a Loader once, and call load() multiple time, for instance after the user clicks on a refresh button ... Now provide the response and nothing else.
You cannot reuse Subscriber , because it implements Subscription , which has an isUnsubscribed field which, once set to true , will never become false again, so Subscription is not reusable. Observer , on the other hand, does not contain any information about the subscription status, so you can reuse it. Each time you subscribe an Observer to an Observable , the RxJava implementation will wrap it inside a new Subscriber for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29415522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/997851/']}
jdg_76467
stackexchange
llm_judgeable_groundtruth_similarity
25140730
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the following command to get a list of pipes: lsof | grep PIPE I want to know what the values of the FD column mean (the 5th one http://i.imgur.com/KHczptf.png ). I think that r and w mean read and write , respectively, but what does the number which follows each of these chars means? I know that FD means File Descriptor, what I want to figure out is what means the values shown in the column, like the 3r, 16w, 20r, etc. Now provide the response and nothing else.
Files are not only opened as streams. Some of those are listed in lsof 's manual: FD is the File Descriptor number of the file or: cwd current working directory; Lnn library references (AIX); err FD information error (see NAME column); jld jail directory (FreeBSD); ltx shared library text (code and data); Mxx hex memory-mapped type number xx. m86 DOS Merge mapped file; mem memory-mapped file; mmap memory-mapped device; pd parent directory; rtd root directory; tr kernel trace file (OpenBSD); txt program text (code and data); v86 VP/ix mapped file; FD is followed by one of these characters, describing the mode under which the file is open: r for read access; w for write access; u for read and write access; space if mode unknown and no lock character follows; '-' if mode unknown and lock character follows. The mode character is followed by one of these lock charac- ters, describing the type of lock applied to the file: N for a Solaris NFS lock of unknown type; r for read lock on part of the file; R for a read lock on the entire file; w for a write lock on part of the file; W for a write lock on the entire file; u for a read and write lock of any length; U for a lock of unknown type; x for an SCO OpenServer Xenix lock on part of the file; X for an SCO OpenServer Xenix lock on the entire file; space if there is no lock. See the LOCKS section for more information on the lock information character. The FD column contents constitutes a single field for pars- ing in post-processing scripts.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25140730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3884697/']}
jdg_76468
stackexchange
llm_judgeable_groundtruth_similarity
14824524
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why does this work print (True, True, True, True, True, True, True, True, True, True, True, True, True, True, True) while this does not print (True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True) Now provide the response and nothing else.
Because there is Show instance for 15-tuple: Prelude> :i (,,,,,,,,,,,,,,)data (,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o = (,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o -- Defined in `GHC.Tuple'<<skip>>instance (Read a, Read b, Read c, Read d, Read e, Read f, Read g, Read h, Read i, Read j, Read k, Read l, Read m, Read n, Read o) => Read (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) -- Defined in `GHC.Read'instance (Show a, Show b, Show c, Show d, Show e, Show f, Show g, Show h, Show i, Show j, Show k, Show l, Show m, Show n, Show o) => Show (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) -- Defined in `GHC.Show' And there are no for 16-tuple: Prelude> :i (,,,,,,,,,,,,,,,)data (,,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o p = (,,,,,,,,,,,,,,,) a b c d e f g h i j k l m n o p -- Defined in `GHC.Tuple' See docs AFAIK instances are hand-written somethere in ghc internal libraries, and it is unlikely anybody will need to show 16-tuple.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14824524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/903414/']}
jdg_76469
stackexchange
llm_judgeable_groundtruth_similarity
138582
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: $B = \pm \sqrt {(1 + 3 x^2) (1 + 3 y^2)}$ I tried to use a data command to generated $B$ values at different Value of x and y, and then plot it as the graph in (3 D) dimension, however, I did not succeed. Could any one help me? B = Sqrt[(1 + 3 i^2)*(1 + 3 j^2)];data = Table[{B, -B}, {i, 0, 100}, {j, 0, 100}];Length[data];ListPlot3D[data] Now provide the response and nothing else.
You could make your mark thing work like this: evalmark = Function[Null, Unevaluated[#] /. mark[x_] :> RuleCondition[x], HoldFirst];evalmark[ test1[f_] := mark[5 + x - x] D[f, x]; test2[f_] := mark[x + x] f^2; ]?test1?test2 test[f_] := 5 D[f,x] test2[f_] := (2 x) f^2
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/138582', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/46684/']}
jdg_76470
stackexchange
llm_judgeable_groundtruth_similarity
7627
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 want to graph an equilateral triangle. It would be ideal if I had a set of three points: $(x_1, y_1), (x_2, y_2), (x_3, y_3)$ with $x_i, y_i \in \mathbb{Z}$ as the vertices. However, this is impossible. I am willing to "settle" for a triangle that is off by the width of a pencil lead. (That is, if we draw circles of radius $\delta$ around all of the lattice points, the true location of the vertices of the equilateral triangle are inside of these error circles.) For a given $\delta$ what is the smallest such triangle? My instinct is to let the computer guess, is there a more elegant way? Now provide the response and nothing else.
Great question! Here is an upper bound: let $\frac{p_n}{q_n}$ be the sequence of convergents to the continued fraction of $\sqrt{3}$. It is known that $| \sqrt{3} - \frac{p_n}{q_n} | < \frac{1}{q_n q_{n+1}}$. Then the vertices $$(0, 0), (2q_n, 0), (q_n, p_n)$$ are within $|\sqrt{3} q_n - p_n| < \frac{1}{q_{n+1}}$ of an equilateral triangle. Asymptotically I believe that $q_n \sim C \cdot \sqrt{3}^n$ for some constant $C$, which means that for small $\delta$ we can always find a triangle with side length something like $\frac{2}{\delta}$. Here is a way to get a lower bound: suppose $(x_i, y_i)$ is a collection of points which are $\delta$-close to an equilateral triangle, and suppose WLOG that $(x_1, y_1) = (0, 0)$. Then $\frac{x_3 + iy_3}{x_2 + iy_2}$ is a rational approximation to $\frac{1}{2} + \frac{\sqrt{3}}{2} i$, hence taking imaginary parts, $2 \frac{x_2 y_3 - x_3 y_2}{x_2^2 + y_2^2}$ is a rational approximation to $\sqrt{3}$. It is known that the convergents $\frac{p_n}{q_n}$ give the best rational approximations to $\sqrt{3}$ (in the sense that better ones must have larger denominators), so one should be able to write down how good this approximation is in terms of $\delta$ and use this to give a lower bound on how large $x_2^2 + y_2^2$ must be. But the details look messy. In any case, I would be very surprised if one didn't end up with a lower bound of the form $\frac{C}{\delta}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/7627', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2563/']}
jdg_76471
stackexchange
llm_judgeable_groundtruth_similarity
125521
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a data set shown as box-whisker graphs after disaggregating. See below. I am wondering why Tableau (the product I am using) automatically plots a whole bunch of values outside the box-whisker.I thought the whiskers of the box are minimums and maximums. It says that the values above the maximum whisker are outliers but I don't see the need to show it and second not sure what logic it uses to calculate it. So just wondering whether anyone knows why someone would want to look at a box-whisker graph which has outliers shown as well rather than them being contained within the box-whisker? (I.e. is this common statistical practice?) Now provide the response and nothing else.
The usual (and original) definition of a box and whisker plot does include outliers (indeed, Tukey had two kinds of outlying points , which these days are often not distinguished). Specifically, the ends of the whiskers in the Tukey boxplot go at the nearest observations inside the inner fences, which are generally at the upper hinge + 1.5 H-spreads and lower hinge - 1.5 H-spreads (basically, UQ + 1.5 IQR and LQ - 1.5 IQR). What's outside those is marked as outliers. That's what R does, for example: There are many variations on the box plot, and some packages implement other things than the Tukey boxplot, but it's the most common one. Indeed, Wickham & Stryjewski's " 40 years of boxplots " mentions numerous variations (and that's only a fraction of what can be found out there). See Wikipedia's article on the box plot for some basic details. Incidentally, Tableau isn't just showing outliers - it's showing all the data there. You can see it's marking points between the ends of the whiskers, and even points inside the boxes, not just the ones outside the inner fences. Tableau describes its boxplots here ; as you see the description broadly matches what I describe for Tukey boxplots above. Edit: This is just to add a drawing of what the boxplot elements look like in the Schmid and Crowe references mentioned in comments so people don't have to chase them down to see what was being discussed: (the Crowe version is slightly tweaked here in a couple of ways, one of which makes it seem a bit more boxplot-like; I may do a more faithful version later)
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/125521', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/61504/']}
jdg_76472
stackexchange
llm_judgeable_groundtruth_similarity
13414791
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 do not understand this MySQL behaviour : if I want to display a\b, I can just select "a\\b" which work without problem : mysql> select "a\\b";+-----+| a\b |+-----+| a\b |+-----+1 row in set (0.05 sec) But if I wnat to search a string containing a \ in a table using LIKE, I need to double-escape my "\". Why ? Here is an example. We prepare a small table. create table test ( test varchar(255) );insert into test values ( "a\\b" ) , ( "a\\b\\c" ) , ( "abcd" );mysql> select * from test;+-------+| test |+-------+| a\b || a\b\c || abcd |+-------+3 rows in set (0.05 sec) We try to get entries beginning by "a\b" ... mysql> select * from test where test LIKE "a\\b%";+------+| test |+------+| abcd |+------+1 row in set (0.05 sec) Why \\ is just ignored there? Why I need to double-escape basckslash to get my expected result? mysql> select * from test where test LIKE "a\\\\b%";+-------+| test |+-------+| a\b || a\b\c |+-------+2 rows in set (0.04 sec) Now provide the response and nothing else.
You escape first for the string syntax, then for LIKE syntax. In LIKE characters % and _ have special meaning, so if you want to search for literal % , you need to use \% , and if you want to search for literal \% you need to escape the backslash as in \\% . In string syntax " obviously has special meaning, so if you want to include quote in the string you need to escape it as \" , and to include literal \" in the string you have to escape the backslash as in \\" . So in both syntaxes you have to escape \ . If you don't want to use \ to escape the LIKE pattern , you can use ESCAPE keyword. For example: ... where test LIKE "a\\b%" ESCAPE '|'; This way, you'll need to write |% , |_ or || to escape these special chars.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13414791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/731138/']}
jdg_76473
stackexchange
llm_judgeable_groundtruth_similarity
217777
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: The paper The Dirac quantum automaton: a short review ( pdf ) starts off by stating: The starting point for the construction of space–time and the physical laws therein is an unstructured, countably infinite set, $G$, of local Fermionic modes . I have seen in other papers mention of bosonic modes as well. Searching google doesn't give any definition. I understand fermions are quark/electrons/etc., and bosons are photons and such. However, I only have basic undergraduate physics experience. So my only sense after a bit of digging is that the word "mode" is sort of casually used when talking about the different types of wave functions that can occur, but I am not sure. What is meant by the word "mode" in "fermionic modes" and "bosonic modes"? Is there a standard definition? Now provide the response and nothing else.
The terminology of a mode of a free quantum field $\phi(x)$ comes from writing it as a Fourier transform, often also called mode expansion :$$ \phi(\vec x) = \int \frac{\mathrm{d}^3 p}{(2\pi)^3}\frac{1}{\sqrt{2\omega_p}}\left(a(\vec p)\mathrm{e}^{\mathrm{i}\vec x\cdot\vec p} + b(\vec p)^\dagger\mathrm{e}^{-\mathrm{i}\vec x\cdot\vec p}\right)$$where for a spinor or vector field there are additional factors in there that don't play a role here. The crucial question is whether the objects $a$ and $a^\dagger$ (and likewise $b$ and $b^\dagger$) commute or anticommute, since they are the creation and annihilation operators for the particle (resp. antiparticle in the case of $b$) associated to the field. If they commute, the corresponding particle is a boson - you can pile up arbitrarily many particles into the same state just by applying the creation operator many times. Then, the operators are bosonic modes . If they anticommute, the corresponding particle is a fermion - applying the creation operator twice just gives zero, so you can't ever have more than one particle in the same state. Here, the operators are fermionic modes . They are "modes" because the Fourier transform splits up a classical oscillation into its pure-frequency modes, so by analogy, we also call the objects it produces when applied to a quanutm field "modes". In a slight generalization, one calls any collection of creation/annihilation operators bosonic or fermionic modes according to their commutation relations, regardless of whether they arose from a quantum field or were just given in some other way.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/217777', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/16731/']}
jdg_76474
stackexchange
llm_judgeable_groundtruth_similarity
4770506
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As per C precedence tables, the ternary conditional operator has right-to-left associativity. So, is it directly convertible to the equivalent if-else ladder? For example, can: x?y?z:u:v; be interpreted as: if(x){ if(y) { z; } else { u; }}else{ v; } by matching an else ( : ) with the closest unpaired if ( ? )? Or does right-to-left associativity imply some other arrangement? Now provide the response and nothing else.
The example you gave could only be interpreted in one way (like the if statements you gave), whether the ternary operator had right-to-left or left-to-right associativity. Where the right-to-left associativity matters is when you have: x = a ? b : c ? d : e; Which is interpreted as: x = a ? b : (c ? d : e) , not as x = (a ? b : c) ? d : e . To give a more realistic example: int getSign(int x) { return x < 0 ? -1 : x > 0 ? 1 : 0;} This is identical to the (probably more readable) if / else-if statements: int getSign(int x) { if (x < 0) return -1; else if (x > 0) return 1; else return 0;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4770506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_76475
stackexchange
llm_judgeable_groundtruth_similarity
3560707
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 looking to apply SQL column level encryption using symmetric keys. The initial steps needed to create the Database Master Key, Certificates and Symmetric Keys seems straight forward and I have tested encrypting/decrypting data using Symmetric Keys successfully. However, once the data is encrypted I don't know how best to query it. E.g. SELECT PlainTextA, PlainTextB, PlainTextC WHERE CONVERT(varchar, DECRYPTBYKEY(EncyptedColumn)) = @SearchTerm would surely result in a full table scan? Another option I thought might work is encrypting the search criteria first e.g. SELECT PlainTextA, PlainTextB, PlainTextC WHERE EncyptedColumn = ENCRYPTBYKEY(KEY_GUID('KeyName'), @SearchTerm) but this doesn't work as the encrypted value generated is always different. Any suggestions would be greatly appreciated. Now provide the response and nothing else.
The typical way is to store both the encrypted value and a one-way hash of the value. When you seek a specific value, you would seek the hash. This way you can query efficiently, w/o having to decrypt every row in order to find the value you're interested: create table Table (EncryptedColumn varbinary(max),HashValue binary(20),PlainA int,PlainB varchar(256),PlainC Datetime);create index ndxTableHash on Table(HashValue);select PlainA, plainB, PlainCfrom tablewhere HashValue = HashBytes('SHA1', @searchTerm); In theory, you can have a hash conflict once in a blue moon, to be paranoid-safe you add a double check on the decrypted column: select PlainA, plainB, PlainCfrom tablewhere HashValue = HashBytes('SHA1', @searchTerm)and DecryptByKey(..., EncryptedColumn) = @searchTerm; Also see Indexing encrypted data and SQL Server 2005: searching encrypted data .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3560707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23429/']}
jdg_76476
stackexchange
llm_judgeable_groundtruth_similarity
8960550
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've created a map of vectors that looks like this: map<string, vector<char> > myMap;string key = "myKey";vector<char> myVector;myMap[key] = myVector; I want to be able to append 'char's' to the vector in the map but I can't figure out how to access said vector to append once the particular key/value(vector) has been created. Any suggestions? I'm iterating over char's and might be adding a lot to the vector as I go so it would be nice to have a simple way to do it. Thanks. I would like the vector in map to be appended as I go. I don't need the original vector...I just need to return the map of key/vector's that I've created (after apending) so that I can pass it to another function. What does the * in map* > do? Is that refrencing a pointer? (I haven't gotten there in lecture yet) Also, do I need: myMap[key]->push_back('s');or myMap[key].push_back('s');?? Now provide the response and nothing else.
To append: myMap[key].push_back('c'); Or use myMap.find , but then you have to check whether you get an end iterator. operator[] returns a reference to the vector . But this modifies the vector stored in the map , not the original one, since you've stored a copy in the map with myMap[key] = myVector; . If that's not what you want, you should rethink your design and maybe store (smart) pointers to vectors in your map.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8960550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1130069/']}
jdg_76477
stackexchange
llm_judgeable_groundtruth_similarity
5820977
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hello I am trying to make a navigation constructed from DIV's which uses jQuery AJAX function to load pages. The thing I want to is is when user clicks say on Pages then Dashboard or what ever active page they are on has class called active removed and added to the new clicked one <div class="dijit active" id="dijit_dashboard">Dashboard</div> <div class="dijit" id="dijit_pages">Pages</div> jQuery code which doesn't quite do the work. $("#dijit_pages").click(function() { $("#dijit_utm").load('index.html'); $(this).addClass("active");}); but I am not sure how to remove class active from all others. Now provide the response and nothing else.
$(function() { $(".dijit").live("click", function() { $(".dijit").removeClass("active"); // remove active class from all $(this).addClass("active"); // add active class to clicked element $("#dijit_utm").load('index.html'); });}); Using this method will mean the same page is loaded for each link. If you need to load a page per item, then the following code will be more apt: <div class="dijit active" id="dijit_dashboard"><a href="dashboard.html">Dashboard</a></div> <div class="dijit" id="dijit_pages"><a href="pages.html">Pages</a></div> $(function() { $(".dijit").live("click", function(e) { e.preventDefault(); $(".dijit").removeClass("active"); // remove active class from all $(this).addClass("active"); // add active class to clicked element var href = $(this).find("A").attr("href"); $("#dijit_utm").load(href); });}); UPDATE This old answer still seems to get quite steady views, so here's an updated answer using the latest jQuery methods as live() has been deprecated since version 1.7: $(document).on('click', '.dijit', function(e) { e.preventDefault(); var $el = $(this); $el.addClass("active").siblings().removeClass('active'); $("#dijit_utm").load($el.find('a').attr('href'));});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5820977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/692114/']}
jdg_76478
stackexchange
llm_judgeable_groundtruth_similarity
54468680
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 question: As I know I can declare a const pointer to some datatype or a pointer to constant datatype but I can only declare a reference to a constant datatype only and no constant reference to a datatype; the fact that a reference is already constant because it cannot be rebound to another object. So when I try to create a const ref to someDataType I get compile-time error. But the thing that matters me is when used with type alias using typedef or using . e.g: #include <iostream>int main() { int i{ 10 }; // int& const r1{ i }; // error: ‘const’ qualifiers cannot be applied to ‘int&’. Ok here. using rInt = int&; // or typedef int& rInt; const rInt r2{ i }; // why const is allowed here? ++r2; // this proves that the const is applied to the reference not to the object referred to. std::cout << r2 << std::endl; // 11} As you can see above I can add const to the reference which I think is Redundant in that context. But why C++ allows this with type-aliases but not directly? Now provide the response and nothing else.
Because the standard say so: [dcl.ref] ... Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a typedef-name ([dcl.typedef], [temp.param]) or decltype-specifier ([dcl.type.simple]), in which case the cv-qualifiers are ignored This is similar to how you cannot declare a reference reference, while it is possible through a typedef (where the references collapse into one): int i;int& iref = i;//int& & irefref = iref; // not OKusing Iref = int&;Iref& iretypedef = iref; // OK; collapses into int& The CV-collapsing rules, just like reference collapsing rules are essential to make templates and type deductions usable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54468680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9154738/']}
jdg_76479
stackexchange
llm_judgeable_groundtruth_similarity
19814673
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 trying to submit a form with missing required fields, my browser (Chrome), displays a message mentionning there is a field missing, and if it's out of my screen, it scrolls up to it. My problem is that I have a 50px fixed header in my webpage, and as a result, the input field is hidden, and the message seems to come out of nowhere: Instead of Is there a way around this? I tried both applying the 50px margin to <html> and to <body> Cheers EDIT Here's a fiddle of the problem: http://jsfiddle.net/LL5S6/1/ Now provide the response and nothing else.
The only way I found is adding an 'override' to the invalid handler.To implement this for every input in your form you can do something like this. var elements = document.querySelectorAll('input,select,textarea');var invalidListener = function(){ this.scrollIntoView(false); };for(var i = elements.length; i--;) elements[i].addEventListener('invalid', invalidListener); This requires HTML5 and this is tested on IE11, Chrome and Firefox. Credits to @HenryW for finding that scrollIntoView works like expected. Note that the false parameter for scrollIntoView aligns the input with the bottom, so if you have a large form it may be aligned with the bottom of the page. jsfiddle
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19814673', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620081/']}
jdg_76480
stackexchange
llm_judgeable_groundtruth_similarity
24309323
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It seems it does not and we are planning to use it (Logging, Exception, etc..) for future projects. Is it still supported? I do not see a lot of activity around this tool as there used to be. We already have NewRelic so also be helpful to know if NewRelic can do logging/Exception handling already. For example, can I create custom logs or exceptions and see them in the new relic dashboard? Now provide the response and nothing else.
It does. You may add Enterprise Library 6 into your project via Nuget Here is the sample application. using System;using System.Diagnostics;using Microsoft.Practices.EnterpriseLibrary.Logging;using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;namespace Practice.Logging{ internal class Program { public static void Main(string[] args) { LoggingConfiguration loggingConfiguration = BuildProgrammaticConfig(); var defaultWriter = new LogWriter(loggingConfiguration); // Check if logging is enabled before creating log entries. if (defaultWriter.IsLoggingEnabled()) { defaultWriter.Write("Log entry created using the simplest overload."); defaultWriter.Write("Log entry with a single category.", "General"); defaultWriter.Write("Log entry with a category, priority, and event ID.", "General", 6, 9001); defaultWriter.Write("Log entry with a category, priority, event ID, " + "and severity.", "General", 5, 9002, TraceEventType.Warning); defaultWriter.Write("Log entry with a category, priority, event ID, " + "severity, and title.", "General", 8, 9003, TraceEventType.Warning, "Logging Block Examples"); } else { Console.WriteLine("Logging is disabled in the configuration."); } } private static LoggingConfiguration BuildProgrammaticConfig() { // Formatter var formatter = new TextFormatter(); // Trace Listeners var eventLog = new EventLog("Application", ".", "StackOverflow #24309323"); var eventLogTraceListener = new FormattedEventLogTraceListener(eventLog, formatter); // Build Configuration var config = new LoggingConfiguration(); config.AddLogSource("General", SourceLevels.All, true) .AddTraceListener(eventLogTraceListener); config.IsTracingEnabled = true; return config; } }} You may find more details in Logging Application Block To use Enterprise Library Configuration Console Extension To install the extension into the Visual Studio 2013 you may follow the workaround steps below. download Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix from the link A VSIX file is a zip file that uses the Open Packaging Convention. You can rename the .VSIX extension to .ZIP and use any zip browser (including the Windows File Explorer) to browse its contents. extract the file into a folder locate the file called extension.vsixmanifest in the folder open the file with notepad.exe locate <SupportedProducts> <VisualStudio Version="11.0"> <Edition>Ultimate</Edition> <Edition>Premium</Edition> <Edition>Pro</Edition> </VisualStudio></SupportedProducts> and replace it with the part below <SupportedProducts> <VisualStudio Version="11.0"> <Edition>Ultimate</Edition> <Edition>Premium</Edition> <Edition>Pro</Edition> </VisualStudio> <VisualStudio Version="12.0"> <!-- VS2013 --> <Edition>Ultimate</Edition> <Edition>Premium</Edition> <Edition>Pro</Edition> </VisualStudio> <VisualStudio Version="14.0"> <!-- VS2015 --> <Edition>Ultimate</Edition> <Edition>Premium</Edition> <Edition>Pro</Edition> </VisualStudio></SupportedProducts> save the file and exit compress folder as a ZIP file again rename the extension to VSIX double click on it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24309323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193189/']}
jdg_76481
stackexchange
llm_judgeable_groundtruth_similarity
33749759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Initial state in a Redux app can be set in two ways: pass it as the second argument to createStore ( docs link ) pass it as the first argument to your (sub-)reducers ( docs link ) If you pass initial state to your store, how do you read that state from the store and make it the first argument in your reducers? Now provide the response and nothing else.
TL;DR Without combineReducers() or similar manual code, initialState always wins over state = ... in the reducer because the state passed to the reducer is initialState and is not undefined , so the ES6 argument syntax doesn't get applied in this case. With combineReducers() the behavior is more nuanced. Those reducers whose state is specified in initialState will receive that state . Other reducers will receive undefined and because of that will fall back to the state = ... default argument they specify. In general, initialState wins over the state specified by the reducer. This lets reducers specify initial data that makes sense to them as default arguments, but also allows loading existing data (fully or partially) when you're hydrating the store from some persistent storage or the server. First let's consider a case where you have a single reducer. Say you don't use combineReducers() . Then your reducer might look like this: function counter(state = 0, action) { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; }} Now let's say you create a store with it. import { createStore } from 'redux';let store = createStore(counter);console.log(store.getState()); // 0 The initial state is zero. Why? Because the second argument to createStore was undefined . This is the state passed to your reducer the first time. When Redux initializes it dispatches a “dummy” action to fill the state. So your counter reducer was called with state equal to undefined . This is exactly the case that “activates” the default argument. Therefore, state is now 0 as per the default state value ( state = 0 ). This state ( 0 ) will be returned. Let's consider a different scenario: import { createStore } from 'redux';let store = createStore(counter, 42);console.log(store.getState()); // 42 Why is it 42 , and not 0 , this time? Because createStore was called with 42 as the second argument. This argument becomes the state passed to your reducer along with the dummy action. This time, state is not undefined (it's 42 !), so ES6 default argument syntax has no effect. The state is 42 , and 42 is returned from the reducer. Now let's consider a case where you use combineReducers() . You have two reducers: function a(state = 'lol', action) { return state;}function b(state = 'wat', action) { return state;} The reducer generated by combineReducers({ a, b }) looks like this: // const combined = combineReducers({ a, b })function combined(state = {}, action) { return { a: a(state.a, action), b: b(state.b, action) };} If we call createStore without the initialState , it's going to initialize the state to {} . Therefore, state.a and state.b will be undefined by the time it calls a and b reducers. Both a and b reducers will receive undefined as their state arguments, and if they specify default state values, those will be returned. This is how the combined reducer returns a { a: 'lol', b: 'wat' } state object on the first invocation. import { createStore } from 'redux';let store = createStore(combined);console.log(store.getState()); // { a: 'lol', b: 'wat' } Let's consider a different scenario: import { createStore } from 'redux';let store = createStore(combined, { a: 'horse' });console.log(store.getState()); // { a: 'horse', b: 'wat' } Now I specified the initialState as the argument to createStore() . The state returned from the combined reducer combines the initial state I specified for the a reducer with the 'wat' default argument specified that b reducer chose itself. Let's recall what the combined reducer does: // const combined = combineReducers({ a, b })function combined(state = {}, action) { return { a: a(state.a, action), b: b(state.b, action) };} In this case, state was specified so it didn't fall back to {} . It was an object with a field equal to 'horse' , but without the b field. This is why the a reducer received 'horse' as its state and gladly returned it, but the b reducer received undefined as its state and thus returned its idea of the default state (in our example, 'wat' ). This is how we get { a: 'horse', b: 'wat' } in return. To sum this up, if you stick to Redux conventions and return the initial state from reducers when they're called with undefined as the state argument (the easiest way to implement this is to specify the state ES6 default argument value), you're going to have a nice useful behavior for combined reducers. They will prefer the corresponding value in the initialState object you pass to the createStore() function, but if you didn't pass any, or if the corresponding field is not set, the default state argument specified by the reducer is chosen instead. This approach works well because it provides both initialization and hydration of existing data, but lets individual reducers reset their state if their data was not preserved. Of course you can apply this pattern recursively, as you can use combineReducers() on many levels, or even compose reducers manually by calling reducers and giving them the relevant part of the state tree.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/33749759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/723007/']}
jdg_76482
stackexchange
llm_judgeable_groundtruth_similarity
18638900
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a modern JavaScript implementation of CRC32. This implementation , which may have originated from here , and is now here, there and everywhere , is unacceptable because it's slow (500ms/MB), and depends on over 2KB of space delimited table, accessed using substr. Yuck! There appears to be a few variations of CRC32, so I need to match this output: mysql> SELECT CRC32('abcde');> 2240272485 Function doesn't actually need to accept a string however, since I'm working with byte arrays. Now provide the response and nothing else.
Update I added a helper function to create the CRCTable instead of having this enormous literal in the code. It could also be used to create the table once and save it in an object or variable and have the crc32 function use that (or as W3C's example, check for the existence and create if necessary). I also updated the jsPerf to compare using a CRCtable with the literal string, literal array, saved window variable and dynamic pointer (the example shown here). var makeCRCTable = function(){ var c; var crcTable = []; for(var n =0; n < 256; n++){ c = n; for(var k =0; k < 8; k++){ c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } crcTable[n] = c; } return crcTable;}var crc32 = function(str) { var crcTable = window.crcTable || (window.crcTable = makeCRCTable()); var crc = 0 ^ (-1); for (var i = 0; i < str.length; i++ ) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; } return (crc ^ (-1)) >>> 0;}; Here's a link to the performance difference: http://jsperf.com/js-crc32 Well here's my ameatur shot at this. I figured reading off an array is faster than substringing it. Warning though, I forwent the use of the Utf8Encode function in these examples to simplify the tests. After all, these are just examples and pretty rough ones at that.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18638900', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1090770/']}
jdg_76483
stackexchange
llm_judgeable_groundtruth_similarity
2164007
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I find $x,y$ for: $$\sin x + \sin y = 0 \\ \sin 2x + \sin 2y = 0$$ I've tried to utilize the identity $\sin 2x = 2\sin x\cos x$ but wasn't able to reach the solution. Now provide the response and nothing else.
You've used the correct identity, just go on: $$\sin \, x = - \sin \,y$$ hence the second equations is equivalent to $$\sin y (\cos \,y - \cos \, x) = 0$$ and now you just split the solution into $$\sin \,y = 0\ \text{ OR }\ (\cos \,y - \cos \, x) = 0.$$ In the first case, when $\sin \,y = 0$, then $\sin \,x = 0$ as well, so $(x,y) = (k;n)\pi$ for $k,n \in \mathbb{N}$. In the second case one has to consider both conditions, i.e. $\cos \,y = \cos \, x$ implies $x$ and $y$ must be either equal or $x=-y$ (symmetrical along horizontal axis + consider the period) from which the condition $\sin \, x = - \sin \,y$ chooses the latter.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2164007', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/399795/']}
jdg_76484
stackexchange
llm_judgeable_groundtruth_similarity
33833
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: According to BBC , Marine Le Pen was ordered by a French court to undergo psychiatric testing: A French court has ordered far-right leader Marine Le Pen to undergo psychiatric tests as part of an inquiry into her sharing images of Islamic State group atrocities. I assume that undergoing psychiatric testing alone (not mentioning a positive result of some mental illness) can have a serious political impact and I am wondering why is she not simply fined? Question: Why is Marine Le Pen ordered to undergo psychiatric testing instead of just being fined? Now provide the response and nothing else.
As stated in the Le Parisien article mentioned in the BBC article you linked, a medical exam is simply something that a prosecutor must order as part of an investigation for the type of offense that Le Pen is being investigated for. However, since the point of the medical exam is to provide proper prison care in the event of a conviction I'm sure there are few penalties(if any) for ignoring the order, and that challenging the order wouldn't be too difficult. The section of the French legal code that requires this sort of order is Article 706-47-1 . Translated from the original French: Persons prosecuted for one of the offenses mentioned in article 706-47 must be subjected, before any judgment on the merits, to a medical report. The expert is questioned about the desirability of an order of care in the framework of a socio-judicial follow-up. This expertise can be ordered at the stage of the investigation by the public prosecutor. This expertise is communicated to the prison administration in the event of condemnation to a custodial sentence, in order to facilitate the medical and psychological monitoring in detention provided for by article 717-1. Article 706-47 contains the various crimes that allow the above medical exam to be ordered, the relevant one for Le Pen being potentially sharing particularly violent content to minors: Crimes of manufacture, transport, distribution or trade of violent or pornographic message likely to be seen or perceived by a minor In this case, Le Pen posted various images of tortures/killings by ISIS which could easily have been seen by minors.
{}
{'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/33833', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/11278/']}
jdg_76485
stackexchange
llm_judgeable_groundtruth_similarity
17084139
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I have an array like this : string[] mobile_numbers = plst.Where(r => !string.IsNullOrEmpty(r.Mobile)) .Select(r => r.Mobile.ToString()) .ToArray(); I want to paging this array and loop according to those pages . Say the array count is 400 and i wanna to take the first 20 then the second 20 and so on until the end of array to process each 20 item . How to do this with linq ? . Now provide the response and nothing else.
Use Skip and Take methods for paging (but keep in mind that it will iterate collection for each page you are going to take): int pageSize = 20;int pageNumber = 2;var result = mobile_numbers.Skip(pageNumber * pageSize).Take(pageSize); If you need just split array on 'pages' then consider to use MoreLinq (available from NuGet) Batch method: var pages = mobile_numbers.Batch(pageSize); If you don't want to use whole library, then take a look on Batch method implementation . Or use this extension method: public static IEnumerable<IEnumerable<T>> Batch<T>( this IEnumerable<T> source, int size){ T[] bucket = null; var count = 0; foreach (var item in source) { if (bucket == null) bucket = new T[size]; bucket[count++] = item; if (count != size) continue; yield return bucket; bucket = null; count = 0; } if (bucket != null && count > 0) yield return bucket.Take(count).ToArray();} Usage: int pageSize = 20;foreach(var page in mobile_numbers.Batch(pageSize)){ foreach(var item in page) // use items}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17084139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/418343/']}
jdg_76486
stackexchange
llm_judgeable_groundtruth_similarity
202987
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 stops someone from MITM-attacking the request to the certificate authority to verify the certificate? Does the browser come pre-loaded with the public keys of the trusted certificate authorities (thereby providing authentication)? Whenever I think about MITM attacks, I think that any defence requires a "safe" connection to be established for authentication, and that the initial establishment of any "safe" connection always seems to be subject to a MITM attack itself. So for example, if the public keys of the trusted certificate authorities above are indeed distributed with the browser, the distribution of the browser would be subject to MITM attacks. As I understand it, even if you physically handed someone a public key / certificate / anything on a piece of paper, you had better know them from elsewhere otherwise they could be a MITM. Do I understand this correctly? Thanks! Now provide the response and nothing else.
What stops someone from MITM-attacking the request to the certificate authority to verify the certificate? When a browser is presented with a certificate by , it doesn't connect to the issuing certificate authority (CA) to verify the certificate; it must already trust the CA, a priori. Depending on the certificate, the CA, and the browser, it may connect to a URL contained in the CA Certificate to check if the cert presented by the site has been revoked (a revocation list), but that connection is secured by the CA cert and not the cert presented by the site. As far as I am aware, most browsers don't actually do this, although most can be configured to. If a CA cert is compromised, then the CA cert will need to either be manually removed, or removed by a patch or new version of the browser code. Does the browser come pre-loaded with the public keys of the trusted certificate authorities (thereby providing authentication)? Yes. More than just public keys though, it is actually self-signed certificates from the CAs, which contain public keys, should contain URLs for verifying the Cert itself in addition to Revocation Lists, and potentially much more. Basically, every browser maker has to decide which CAs to pre-install and which ones to leave out, and this is a topic of much discussion and big business. Most CAs generate a lot of money selling certificates, and it benefits them to be pre-installed in every browser, so they push hard on browser makers to install them. But the trustworthiness of the CAs is a topic which can cause much debate among security folks. Whenever I think about MITM attacks, I think that any defence requires a "safe" connection to be established for authentication, and that the initial establishment of any "safe" connection always seems to be subject to a MITM attack itself. So for example, if the public keys of the trusted certificate authorities above are indeed distributed with the browser, the distribution of the browser would be subject to MITM attacks. While true, this is a significantly more difficult attack vector than other approaches, and you can combat it by verifying the distribution file of the browser prior to installing it (i.e. verify the SHA1 hash of the installation file based on the published hash of the website). At that point, an attacker would have to infiltrate either the browser manufacturer or the Certificate Authority, which again are more difficult attack vectors (although certainly not unheard of). As I understand it, even if you physically handed someone a public key / certificate / anything on a piece of paper, you had better know them from elsewhere otherwise they could be a MITM. Well, giving someone else your public key (or a certificate containing a public key) is harmless. All it means is that they can verify that stuff you signed with said certificate actually came from you (and they could encrypt things that only you can decrypt). But fundamentally, you are right. At some point, you have to trust someone. That is an important thing to remember about security, networking, business, and life. Of course, you need to temper this with a healthy dose of skepticism, and continually reevaluate your trust relationships. And of course, you should also keep in mind some sage advice from the Gipper: " Trust, but Verify " (or, if you prefer: follow the sound advice of the old Russian proverb: ""doveryai, no proveryai" [Russian: Доверяй, но проверяй]"). To really secure your computer, you will need to power it off, take it apart, destroy the components, then destroy the remains. As far as establishing a trust relationship with someone else goes, it helps to have a mutual friend that already trusts them. That is the whole point behind the "ring-of-trust"At some point you have to have a little faith. How do you know that the person that issued you your driver's license is REALLY an employee of the state. Of course, you could generate your public key, memorize the fingerprint, and install the pub key on the target system Do I understand this correctly? I'm not sure, but I suspect so. Please repeat it all back to me, paraphrased into your own words and I'll let you know. EDIT: And really, as GregD points out, all this is academic, because most people click the "Proceed anyway" button when their browser warns them that it doesn't trust the cert, and then it is game over. Of course if you work in an enterprise, and control the system that the users are issued, you can probably configure it so it doesn't present them that button, but you will have to deal with the fall-out. The only time it is ever acceptable to click that button is when you are not connected to a network and have single wire between you and the system presenting the untrusted certificate (and even then, it is arguable).
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/202987', 'https://serverfault.com', 'https://serverfault.com/users/60584/']}
jdg_76487
stackexchange
llm_judgeable_groundtruth_similarity
1728376
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 writing a script that will try encoding bytes into many different encodings in Python 2.6. Is there some way to get a list of available encodings that I can iterate over? The reason I'm trying to do this is because a user has some text that is not encoded correctly. There are funny characters. I know the unicode character that's messing it up. I want to be able to give them an answer like "Your text editor is interpreting that string as X encoding, not Y encoding". I thought I would try to encode that character using one encoding, then decode it again using another encoding, and see if we get the same character sequence. i.e. something like this: for encoding1, encoding2 in itertools.permutation(encodinglist(), 2): try: unicode_string = my_unicode_character.encode(encoding1).decode(encoding2) except: pass Now provide the response and nothing else.
Other answers here seem to indicate that constructing this list programmatically is difficult and fraught with traps. However, doing so is probably unnecessary since the documentation contains a complete list of the standard encodings Python supports, and has done since Python 2.3. You can find these lists (for each stable version of the language so far released) at: https://docs.python.org/2.3/lib/node130.html https://docs.python.org/2.4/lib/standard-encodings.html https://docs.python.org/2.5/lib/standard-encodings.html https://docs.python.org/2.6/library/codecs.html#standard-encodings https://docs.python.org/2.7/library/codecs.html#standard-encodings https://docs.python.org/3.0/library/codecs.html#standard-encodings https://docs.python.org/3.1/library/codecs.html#standard-encodings https://docs.python.org/3.2/library/codecs.html#standard-encodings https://docs.python.org/3.3/library/codecs.html#standard-encodings https://docs.python.org/3.4/library/codecs.html#standard-encodings https://docs.python.org/3.5/library/codecs.html#standard-encodings https://docs.python.org/3.6/library/codecs.html#standard-encodings https://docs.python.org/3.7/library/codecs.html#standard-encodings https://docs.python.org/3.8/library/codecs.html#standard-encodings https://docs.python.org/3.9/library/codecs.html#standard-encodings https://docs.python.org/3.10/library/codecs.html#standard-encodings https://docs.python.org/3.11/library/codecs.html#standard-encodings Below are the lists for each documented version of Python. Note that if you want backwards-compatibility rather than just supporting a particular version of Python, you can just copy the list from the latest Python version and check whether each encoding exists in the Python running your program before trying to use it. Python 2.3 (59 encodings) ['ascii', 'cp037', 'cp424', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp869', 'cp874', 'cp875', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8'] Python 2.4 (85 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8'] Python 2.5 (86 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 2.6 (90 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 2.7 (93 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_11', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 3.0 (89 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 3.1 (90 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 3.2 (92 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 3.3 (93 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'cp65001', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 3.4 (96 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp273', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1125', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'cp65001', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_11', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_u', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 3.5 (98 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp273', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1125', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'cp65001', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_11', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 3.6 (98 encodings) Same as previous version. Python 3.7 (98 encodings) Same as previous version. Python 3.8 (97 encodings) ['ascii', 'big5', 'big5hkscs', 'cp037', 'cp273', 'cp424', 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp864', 'cp865', 'cp866', 'cp869', 'cp874', 'cp875', 'cp932', 'cp949', 'cp950', 'cp1006', 'cp1026', 'cp1125', 'cp1140', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'euc_jp', 'euc_jis_2004', 'euc_jisx0213', 'euc_kr', 'gb2312', 'gbk', 'gb18030', 'hz', 'iso2022_jp', 'iso2022_jp_1', 'iso2022_jp_2', 'iso2022_jp_2004', 'iso2022_jp_3', 'iso2022_jp_ext', 'iso2022_kr', 'latin_1', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_8', 'iso8859_9', 'iso8859_10', 'iso8859_11', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_16', 'johab', 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'mac_cyrillic', 'mac_greek', 'mac_iceland', 'mac_latin2', 'mac_roman', 'mac_turkish', 'ptcp154', 'shift_jis', 'shift_jis_2004', 'shift_jisx0213', 'utf_32', 'utf_32_be', 'utf_32_le', 'utf_16', 'utf_16_be', 'utf_16_le', 'utf_7', 'utf_8', 'utf_8_sig'] Python 3.9 (97 encodings) Same as previous version. Python 3.10 (97 encodings) Same as previous version. Python 3.11 (97 encodings) Same as previous version. In case they're relevant to anyone's use case, note that the docs also list some Python-specific encodings , many of which seem to be primarily for use by Python's internals or are otherwise weird in some way, like the 'undefined' encoding which always throws an exception if you try to use it. You probably want to ignore these completely if, like the question-asker here, you're trying to figure out what encoding was used for some text you've come across in the real world. As of Python 3.7, the list is as follows: ["idna", "mbcs", "oem", "palmos", "punycode", "raw_unicode_escape", "rot_13", "undefined", "unicode_escape", "unicode_internal", "base64_codec", "bz2_codec", "hex_codec", "quopri_codec", "uu_codec", "zlib_codec"] Some older Python versions had a string_escape special encoding that I've not included in the above list because it's been removed from the language. Finally, in case you'd like to update my tables above for a newer version of Python, here's the (crude, not very robust) script I used to generate them: import reimport requestsimport lxml.htmlimport pprintprevious = Nonefor version, url in [ ('2.3', 'https://docs.python.org/2.3/lib/node130.html'), ('2.4', 'https://docs.python.org/2.4/lib/standard-encodings.html'), ('2.5', 'https://docs.python.org/2.5/lib/standard-encodings.html'), ('2.6', 'https://docs.python.org/2.6/library/codecs.html#standard-encodings'), ('2.7', 'https://docs.python.org/2.7/library/codecs.html#standard-encodings'), ('3.0', 'https://docs.python.org/3.0/library/codecs.html#standard-encodings'), ('3.1', 'https://docs.python.org/3.1/library/codecs.html#standard-encodings'), ('3.2', 'https://docs.python.org/3.2/library/codecs.html#standard-encodings'), ('3.3', 'https://docs.python.org/3.3/library/codecs.html#standard-encodings'), ('3.4', 'https://docs.python.org/3.4/library/codecs.html#standard-encodings'), ('3.5', 'https://docs.python.org/3.5/library/codecs.html#standard-encodings'), ('3.6', 'https://docs.python.org/3.6/library/codecs.html#standard-encodings'), ('3.7', 'https://docs.python.org/3.7/library/codecs.html#standard-encodings'), ('3.8', 'https://docs.python.org/3.8/library/codecs.html#standard-encodings'), ('3.9', 'https://docs.python.org/3.9/library/codecs.html#standard-encodings'), ('3.10', 'https://docs.python.org/3.10/library/codecs.html#standard-encodings'), ('3.11', 'https://docs.python.org/3.11/library/codecs.html#standard-encodings'),]: html = requests.get(url).text # Work-around for weird HTML markup in recent versions of Python documentation: html = re.sub('<[/]?p>', '', html) doc = lxml.html.fromstring(html) standard_encodings_table = doc.xpath( '//table[preceding::h2[.//text()[contains(., "Standard Encodings")]]][//th/text()="Codec"]' )[0] codecs = standard_encodings_table.xpath('.//td[1]/text()') print("## Python %s (%i encodings)\n" % (version, len(codecs))) if codecs == previous: print('_Same as previous version._\n') else: print('```python\n' + pprint.pformat(codecs) + '\n```\n') previous = codecs
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1728376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/161922/']}
jdg_76488
stackexchange
llm_judgeable_groundtruth_similarity
26367862
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The current best solution: https://stackoverflow.com/a/21888830/1786820 I am trying to do one better, by opening the Instagram app with a preselected video file from the PhotoRoll, and a preloaded caption. In the Flipagram app, they do just this. When you hit share on a video, they save it your camera roll, suggest a caption, then direct to the Instagram app photo selection screen, with the video preselected. Even if the video is not the latest media in the PhotoRoll, it correctly highlights the correct video, along the caption prepared in the Flipagram app. Is this possibly an undocumented iPhone hook? Any help is appreciated. Now provide the response and nothing else.
I came up with the idea to allow my app to accept the instagram:// URL schema. The hook from Flipagram opened up in my app as the following: instagram://library?AssetPath=assets-library%3A%2F%2Fasset%2Fasset.mp4%3Fid%3D8864C466-A45C-4C48-B76F-E3C421711E9D%26ext%3Dmp4&InstagramCaption=Some%20Preloaded%20Caption The undocumented iPhone hook that allows you to automatically select assets from the iPhones photo roll, and preload a caption for the video. This should give you the same user experience that Flipagrams app has with sharing a video to Instagram. NSURL *videoFilePath = ...; // Your local path to the videoNSString *caption = @"Some Preloaded Caption";ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];[library writeVideoAtPathToSavedPhotosAlbum:[NSURL URLWithString:videoFilePath] completionBlock:^(NSURL *assetURL, NSError *error) { NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@",[assetURL absoluteString].percentEscape,caption.percentEscape]]; if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) { [[UIApplication sharedApplication] openURL:instagramURL]; }}]; Works great! Update: Instagram has removed the ability to pass the caption to their app. The best solution now it to just copy the desired caption to the paste board.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26367862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1786820/']}
jdg_76489
stackexchange
llm_judgeable_groundtruth_similarity
156883
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Strassen's algorithm, we calculate the time complexity based on n being the number of rows of the square matrix. Why don't we take n to be the total number of entries in the matrices (so if we were multiplying two 2x2 matrices, we would have n = 8 for the four entries in each matrix)?Then, using the naïve method of multiplying matrices, we would end up with only n multiplications and n/2 additions.For instance, multiplying [1 2, 3 4] by [5 6, 7 8] yields [1*5+2*7 1*6+2*8, 3*5+4*7 3*6+4*8]. Here, n = 8 and we are doing n = 8 multiplications and n/2 = 4 additions.So even a naïve multiplication algorithm would yield a time complexity of O(n). Of course, this reasoning is wrong because the time complexity cannot be linear but I don't understand why.I would appreciate any input. Thank you! Now provide the response and nothing else.
Here, n = 8 and we are doing n = 8 multiplications and n/2 = 4 additions. So even a naïve multiplication algorithm would yield a time complexity of O(n). That is wrong. It might work for a small example like $n = 8$ , but for bigger ones it doesn't.E.g. if you have two square matrices with a total of $n = 200$ elements (two $10 \times 10$ matrices) you have already 1,000 multiplications, for $n=20\,000$ you have $1\,000\,000$ . Now to the actual question. It is possible to give the number time complexity in terms of the number of matrix elements, but it is not very practical. One problem is, that the complexity differs a lot depending on the shape of the matrix: A multiplication of a $1 \times N$ matrix with a $N \times 1$ matrix has time complexity $O(N)$ (linear in the number of matrix elements). But a multiplication of a $N \times 1$ matrix with a $1 \times N$ matrix takes $O(N^2)$ (quadratic in the number of elements). So it's a lot harder to argue about time complexities when you only know the number of elements. And it's also easier to talk about the matrices in general.It feels more natural.E.g. saying "I've doubled the number of rows of the first matrix" makes sense to everybody (and you immediately know that the algorithm will run about twice as slow, "I've doubled the both dimensions of both matrices" makes sense.But saying "I've double the number of elements" will confuse anybody, how does the matrix look like afterwards. Did you increase both dimensions by a factor of 1.41? Did the matrix change shape? Or what happen? And what impact does it have on the runtime...
{}
{'log_upvote_score': 5, 'links': ['https://cs.stackexchange.com/questions/156883', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/156891/']}
jdg_76490
stackexchange
llm_judgeable_groundtruth_similarity
1164192
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 migrate a bunch of tests from SimpleTest to PHPUnit and I was wondering if there is an equivalent for SimpleTest's partial mocks . I can't seem to find anything in the documentation which suggests that this feature is available, but it occurred to me that I could just use a subclass. Is this a good or bad idea? class StuffDoer { protected function doesLongRunningThing() { sleep(10); return "stuff"; } public function doStuff() { return $this->doesLongRunningThing(); }}class StuffDoerTest { protected function doesLongRunningThing() { return "test stuff"; }}class StuffDoerTestCase extends PHPUnit_Framework_TestCase { public function testStuffDoer() { $sd = new StuffDoerTest(); $result = $sd->doStuff(); $this->assertEquals($result, "test stuff"); }} Now provide the response and nothing else.
From reading the linked page, a SimpleTest partial mock seems to be a mock where only some of the methods are overridden. If this is correct, that functionality is handled by a normal PHPUnit mock. Inside a PHPUnit_Framework_TestCase , you create a mock with $mock = $this->getMock('Class_To_Mock'); Which creates an mock instance where all methods do nothing and return null. If you want to only override some of the methods, the second parameter to getMock is an array of methods to override. $mock = $this->getMock('Class_To_Mock', array('insert', 'update')); will create an mock instance of Class_To_Mock with the insert and update functions removed, ready for their return values to be specified. This information is in the phpunit docs . Note , this answer shows more up to date code examples, for PHPUnit versions starting 5.4
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1164192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15004/']}
jdg_76491
stackexchange
llm_judgeable_groundtruth_similarity
56591683
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 have nginx serve static content while reverse proxying everything else to a rails server. All that works, except for the home page. If I go to example.com I get a 403 error and the error log shows 2019/06/14 04:32:59 [error] 9746#9746: *1 directory index of "/var/www/html/" is forbidden I want the request to be sent to the rails server as example.com/ instead of trying (and failing) to get a directory listing. The rails server should display a homepage instead. (side note: if I turn autoindex on I will get a directory listing) Configuration is here: server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; server_name example.com; index index.html; location / { autoindex off; root /var/www/html; try_files $uri $uri/ @rails; expires max; access_log off; } location @rails { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header Host $host; proxy_pass http://127.0.0.1:3000; }} Now provide the response and nothing else.
Dark mode is half working in previews, it just forgets to draw the background. The following workaround allows you to add .darkModeFix() to your ContentView() in your preview function. You can optionally add false as a parameter to switch off dark mode. struct ContentView_Previews : PreviewProvider { static var previews: some View { Group { ContentView() .darkModeFix() } }} Just add the following somewhere in your project: public struct DarkView<Content> : View where Content : View { var darkContent: Content var on: Bool public init(_ on: Bool, @ViewBuilder content: () -> Content) { self.darkContent = content() self.on = on } public var body: some View { ZStack { if on { Spacer() .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) .background(Color.black) .edgesIgnoringSafeArea(.all) darkContent.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.black).colorScheme(.dark) } else { darkContent } } }}extension View { public func darkModeFix(_ on: Bool = true) -> DarkView<Self> { DarkView(on) { self } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56591683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275780/']}
jdg_76492
stackexchange
llm_judgeable_groundtruth_similarity
2849423
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 the scenario: I put a break point at the beginning of a method that I want to debug... at first lets say there is Part1 in this method that I want to step into/over some of the codes... good... after that there is a While loop that I am NOT interested to step into/over it, I just want to tell the debugger that Hey you yourself run this loop for 10 times and just let me move to Part2 of my code which starts after this While loop , is it possible to do this with debugging options? so something like this : BreakPoint : MyMethod{Part One of the code : Ok, lets debug itWhile Loop : I do not care, Do not want to debug itPart Two of the code: Yes, I want to debug it too } Now provide the response and nothing else.
Right-click on the line of code you want to run to, and click "Run To Cursor", or you can set a second breakpoint after the loop and just run. Edit: You kind of asked two questions here. The method above will let you step over the whole loop, regardless of how many iterations it goes through. If you want to only go through the loop body 10 times, add a breakpoint on the last statement of the loop, right-click that line, click "Breakpoint", then "Hit count", then "break when hit count is equal to" and put 10 in the box that appears. This will pause the program after the loop executes 10 times (you will manually have to reposition the current statement), but will NOT break if the loop executes less than 10 times (add an additional breakpoint after the loop as I suggested above).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2849423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/320724/']}
jdg_76493
stackexchange
llm_judgeable_groundtruth_similarity
691304
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 would like to SSH into a computer behind a firewall that blocks SSH connections (incoming and outgoing). Amusingly, I can still access the computer using the remote-desktop software TeamViewer. I assumed that TeamViewer is allowed in because it uses a different port than SSH's default port 22, so I added the following ports to /etc/ssh/sshd_config: Port 22Port 443Port 80Port 5938Port 10000 and then tried to connect to each of them in turn using (e.g.) ssh [email protected] -p 5938 None of the ports work: I still get a Connection timed out error. Why can TeamViewer connect to the remote computer while SSH can't? How can I SSH into (or out of) the remote computer? Now provide the response and nothing else.
If you want to connect via SSH to a computer behind the firewall, then you will need to add a port forward (DNAT) rule to the firewall mapping port 22 (or whatever port you decide to use) to the SSH port on the internal server. TeamViewer is able to get through by using techniques such as NAT Traversal and UDP hole punching to establish a connection through the router to the PC. While TeamViewer connections are peer-to-peer (client connects directly to host) the initial connection is established with the help of TeamViewer's servers which tells the host that a client is trying to connect and then helps facilitate the NAT traversal by having the server and client try to open connections which will then put the firewall in a state where it will allow the TeamViewer connection to pass through to the host. Traffic for the TeamViewer connection to the host computer passes through the router much like the traffic from visiting a webpage would when the browser on the PC goes through the firewall to request a webpage and then have the response delivered back to it. The main difference is that "tricks" are used to open the appropriate ports on the client firewall/router and allow the connection through from the remote TeamViewer client.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/691304', 'https://serverfault.com', 'https://serverfault.com/users/216250/']}
jdg_76494
stackexchange
llm_judgeable_groundtruth_similarity
144846
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a config file with following structure. ValueOne = 1ValueTwo = 2ValueThree = 3 I want a one liner bash script to find ValueTwo and change the value to 22222. Any idea? Not School Thing Now provide the response and nothing else.
I bet there'll be better ones but here's my go: If the config file has parameters on their own line sed -i '/ValueTwo/s/= .*/= 22222/' config_file /ValueTwo/ : Search for the string ValueTwo to find which line to operate on ( Addresses ) s/= .*/= 22222/ : On the lines that match the search above, substitute = .* for = 22222 ( Substitute ) = .* : Search for the = character followed by a space ( ) character followed by 0 or more of any character ( .* ) ( Regex example ) = 22222 : Replace what's found with the literal string = 22222 This will replace the contents of config_file in-place. To create a new file with the parameter changed, remove -i and place > new_file at the end of the line. If your config file has parameters on the same line (like the unedited question): sed -i 's/ValueTwo = [^ ]*/ValueTwo = 22222/' config_file This will replace the contents of config_file in-place as well. It will work as long as there are no spaces in the parameter for ValueTwo. This will also work in the case where parameters are on their own line, but the former method is perhaps more robust in that case.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/144846', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/77722/']}
jdg_76495
stackexchange
llm_judgeable_groundtruth_similarity
4193520
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am getting following exception when I tried to deploy liferay war file into Virgo server. Can any one help me please? [2010-11-10 06:24:16.647] start-signalling-3 System.out Loading jar:file:/D:/VGP/Servers/Spike-liferay inside virgo/virgo-web-server-2.1.0.RELEASE/virgo-web-server-2.1.0.RELEASE/work/osgi/configuration/org.eclipse.osgi/bundles/36/data/store/org.eclipse.osgi/bundles/63/1/bundlefile/WEB-INF/lib/portal-impl.jar!/portal.properties [2010-11-10 06:28:21.647] start-signalling-3 System.out 06:28:21,553 ERROR [ContextLoader:220] Context initialization failed [2010-11-10 06:28:21.662] start-signalling-3 System.out org.eclipse.virgo.util.osgi.manifest.parse.BundleManifestParseException: Error parsing bundle manifest header [JSR 286] [2010-11-10 06:28:21.662] start-signalling-3 System.out HP005W:[col 3]: Unexpected space found [2010-11-10 06:28:21.662] start-signalling-3 System.out HP013E:[col 4]: Expected a semicolon but found '286' [2010-11-10 06:28:21.662] start-signalling-3 System.out[2010-11-10 06:28:21.662] start-signalling-3 System.out at org.eclipse.virgo.util.osgi.manifest.parse.standard.StandardHeaderParser.parseBundleSymbolicName(StandardHeaderParser.java:96) [2010-11-10 06:28:21.662] start-signalling-3 System.out at org.eclipse.virgo.util.osgi.manifest.internal.StandardBundleSymbolicName.parse(StandardBundleSymbolicName.java:33) [2010-11-10 06:28:21.662] start-signalling-3 System.out at org.eclipse.virgo.util.osgi.manifest.internal.BaseParameterised.resetFromParseString(BaseParameterised.java:42) [2010-11-10 06:28:21.662] start-signalling-3 System.out at org.eclipse.virgo.util.osgi.manifest.internal.StandardBundleManifest.initializeHeaders(StandardBundleManifest.java:118) ........... Now provide the response and nothing else.
You cannot know until the assembly is loaded. The assembly resolution algorithm is complicated and you can't reliably guess up front what it will do. Calling the Assembly.Load(AssemblyName) override will get you a reference to the assembly, and its Location property tells you what you need. However, you really don't want to load assemblies up front, before the JIT compiler does it. It is inefficient and the likelihood of problems is not zero. You could for example fire an AppDomain.AssemblyResolve event before the program is ready to respond to it. Avoid asking this question.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4193520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/366504/']}
jdg_76496
stackexchange
llm_judgeable_groundtruth_similarity
14710
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This question may or may not be specific to the General American accent. In words such as thin, thick, and throw, the initial /θ/ doesn't sound the same as the /θ/ in words such as math and wrath. I understand that phonemically they are both (voiceless) dental fricatives, but the initial ⟨th⟩ sounds like a plosive or aspirated dental fricative or stop. What is phonetic realization of initial ⟨th⟩ in the English language? Now provide the response and nothing else.
You are comparing consonants at the beginning of a syllable with consonants at the end. Consonants at the beginning are fortis, while those at the end are lenis. This is a very general difference in English and in some other languages. Saussure called syllable onset, fortis, consonants explosive , and he called syllable offset, lenis consonants, implosive (in Course in General Linguistics ). Fortis consonants use more muscular effort, and consequently for the dental fricatives, the tongue is pressed more forcefully against the upper teeth. This makes the obstruction to the stream of air through the mouth smaller and makes it last longer. More air pressure will build up in the mouth, behind the obstruction, and when the consonant is released, there will be a larger explosion of air than for the corresponding lenis consonant in the offset of a syllable. Lenis consonsonants are more subject to lenitive changes, such as assimilation, than fortis consonants. In English "tenth", the final "th" can assimilate to the preceding (nasal) stop to become a dental stop.
{}
{'log_upvote_score': 4, 'links': ['https://linguistics.stackexchange.com/questions/14710', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/10694/']}
jdg_76497
stackexchange
llm_judgeable_groundtruth_similarity
10274679
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 see how can I invoke a js function after the client gets a result from a Meteor method call. The only thing I was able to get is to invoke the function myFunc only on the client that made the actual method call.Any thoughts how i can invoke the function on all the currently subscribed clients? here is the code: function myFunc(error, result) { alert(result);}if (Meteor.is_client) { Template.container.events = { 'click input' : function () { Meteor.call('someMethod',myFunc); if (typeof console !== 'undefined') console.log("You pressed the button"); } };}if (Meteor.is_server) { Meteor.startup(function () { // code to run on server at startup });}Meteor.methods({ someMethod: function() { //console.log(!this.is_simulation); return "something"; }}) Thanks Now provide the response and nothing else.
Currently you can't broadcast a method call to all clients directly. At least as far as I can tell. But a work around would be to create a collection called Alerts and monitor it for changes. Then when you want to send a message to all your users you can change the document in Alerts: Client: Alerts = new Meteor.Collection("alerts")Meteor.autosubscribe(function() { Alerts.find().observe({ added: function(item){ alert(item.message); } });}); Server: Alerts = new Meteor.Collection("alerts")Meteor.publish("alerts", function(){ Alerts.find();});Alerts.remove({}); // remove allAlerts.insert({message: "Some message to show on every client."});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10274679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1329668/']}
jdg_76498
stackexchange
llm_judgeable_groundtruth_similarity
22710272
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 stumbled upon a difference in the way floating point arithmetics are done between MS VS 2010 builds for x86 and x64 (both executed on the same 64 bit machine). This is a reduced code sample: float a = 50.0f;float b = 65.0f;float c = 1.3f;float d = a*c;bool bLarger1 = d<b;bool bLarger2 = (a*c)<b; The boolean bLarger1 is always false (d is set to 65.0 in both builds).Variable bLarger2 is false for x64 but true for x86! I am well aware of floating point arithmetics and the rounding effects taking place. I also know that 32 bit sometimes uses different instructions for floating operations than 64 bit builds. But in this case I am missing some information. Why is there a discrepency between bLarger1 and bLarger2 on the first place? Why is it only present on the 32 bit build? Now provide the response and nothing else.
The issue hinges on this expression: bool bLarger2 = (a*c)<b; I looked at the code generated under VS2008, not having VS2010 to hand. For 64 bit the code is: 000000013FD51100 movss xmm1,dword ptr [a] 000000013FD51106 mulss xmm1,dword ptr [c] 000000013FD5110C movss xmm0,dword ptr [b] 000000013FD51112 comiss xmm0,xmm1 For 32 bit the code is: 00FC14DC fld dword ptr [a] 00FC14DF fmul dword ptr [c] 00FC14E2 fld dword ptr [b] 00FC14E5 fcompp So under 32 bit the calculation is performed in the x87 unit, and under 64 bit it is performed by the x64 unit. And the difference here is that the x87 operations are all performed to higher than single precision. By default the calculations are performed to double precision. On the other hand the SSE unit operations are pure single precision calculations. You can persuade the 32 bit unit to perform all calculations to single precision accuracy like this: _controlfp(_PC_24, _MCW_PC); When you add that to your 32 bit program you will find that the booleans are both set to false. There is a fundamental difference in the way that the x87 and SSE floating point units work. The x87 unit uses the same instructions for both single and double precision types. Data is loaded into registers in the x87 FPU stack, and those registers are always 10 byte Intel extended. You can control the precision using the floating point control word. But the instructions that the compiler writes are ignorant of that state. On the other hand, the SSE unit uses different instructions for operations on single and double precision. Which means that the compiler can emit code that is in full control of the precision of the calculation. So, the x87 unit is the bad guy here. You can maybe try to persuade your compiler to emit SSE instructions even for 32 bit targets. And certainly when I compiled your code under VS2013 I found that both 32 and 64 bit targets emitted SSE instructions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22710272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/344159/']}
jdg_76499
stackexchange
llm_judgeable_groundtruth_similarity
23471
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 $\Delta(G) + \delta(G) \geq n-1$. Can we conclude that $G$ is connected? Now provide the response and nothing else.
Yes. Suppose that $V(G)$ can be split into two sets $A$ and $B$ of respective sizes $a \geq b \geq 1$, and no edges between the two sets. Since vertices in $A$ (resp. $B$) have degree at most $a-1$ (resp. $b-1$), we see that $\Delta(G) \leq a-1$ and $\delta(G) \leq b-1$. So $\Delta(G) + \delta(G) \leq a+b-2 = n-2$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/23471', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5764/']}
jdg_76500
stackexchange
llm_judgeable_groundtruth_similarity
33706191
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 new to REST and just started reading some tutorials. One thing that really confuses me is: what comes in txt/xml/json form: the resources or the resource representations? Must be the latter, right? Since resources can be a video, audio or other MIME types. Take the example below. Let's say I am given a description like 'a RESTful service where User is a resource which is represented using the following XML format': <user> <id>1</id> <name>Mahesh</name> <profession>Teacher</profession></user> or JSON format: { "id":1, "name":"Mahesh", "profession":"Teacher"} Then, when I use HTTP GET to access the resource, what data do I actually get back? Do I get '1, Mahesh, Teacher' since this is the real data excluding the format, or do I get the whole xml or json 'object' that contains both the data and the data representation? What if User has an image property? What kind of 'package' and in which form will HTTP deliver it to me: the image itself or a link to the image? EDIT Another example here: http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false Here should I understand that the returned resource itself is an XML file, or the resource is NOT an XML file, but some data that's embedded in XML resource representation is? And what if the resource I want contains images, videos, etc.? Those are not text data that can be embedded in XML or JSON format--in that case, what do I get? Now provide the response and nothing else.
Resource The concept of a REST resource is abstract and you can understand it as something that is identified by a URL provided by the server . The resource can be a user, a list of users, a customer, a file or any entity of the application. For example, consider a user as your resource with the following attributes and values: ID: 1 First name: John Last name: Doe e-mail: [email protected] URL The URL ( Uniform Resource Locator ) just identifies the resource, that is, where the resource is located in the server. For example, while the URL /app/users/1 locates the user with the ID 1 , the URL /app/users locate all the users in the application. HTTP methods REST is protocol independent, but, if you are using HTTP, you can perform actions on the resource accessing the URL with HTTP methods, such as GET , POST , PUT and DELETE . For example, when you perform a GET to the URL /app/users/1 , you'll obtain a representation for the user with the ID 1 . Resource representation A resource can be represented in multiple formats, such as JSON, XML, YAML, etc. In JSON, the representation would be: { "id": 1, "firstName": "John", "lastName": "Doe", "email": "[email protected]"} In XML, the representation would be the following: <user> <id>1</id> <firstName>John</firstName> <lastName>Doe</lastName> <email>[email protected]</email></user> Example 1 Consider you are developing an application in JavaScript and the server can provide a representation of the resources as JSON and XML. It's easier to deal with JSON rather than XML in JavaScript applications. So, you want the resources represented as JSON. To do it, when performing a GET to the URL /app/users/1 , you'll add the HTTP header Accept with the application/json value to tell the server the representation the client accepts. Consequently, the server will return the resource represented as JSON. The response will contain the Content-Type header with the application/json value, indicating the content of the response is a JSON. Example 2 Besides JSON and XML, for example, the resources can be represented as images or videos. Consider a URL which locates the profile picture of a user: /app/users/1/profile-picture . Depending the image type, the Content-Type of the response will be image/jpeg , image/png , image/gif , etc. This answer may also be insightful.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33706191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1559625/']}
jdg_76501
stackexchange
llm_judgeable_groundtruth_similarity
22873550
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 application is made using QML+JS and I am looking to create a circular progress bar widget. I can create the circle using a QML Rectangle and settings its radius equal to its width/2 to make it into a circle. How do I create a progress bar out of it? I am planning to implement the following mockup. Now provide the response and nothing else.
I've implemented a basic circular progress using a Canvas. import QtQml 2.2import QtQuick 2.0// draws two arcs (portion of a circle)// fills the circle with a lighter secondary color// when pressedCanvas { id: canvas width: 240 height: 240 antialiasing: true property color primaryColor: "orange" property color secondaryColor: "lightblue" property real centerWidth: width / 2 property real centerHeight: height / 2 property real radius: Math.min(canvas.width, canvas.height) / 2 property real minimumValue: 0 property real maximumValue: 100 property real currentValue: 33 // this is the angle that splits the circle in two arcs // first arc is drawn from 0 radians to angle radians // second arc is angle radians to 2*PI radians property real angle: (currentValue - minimumValue) / (maximumValue - minimumValue) * 2 * Math.PI // we want both circle to start / end at 12 o'clock // without this offset we would start / end at 9 o'clock property real angleOffset: -Math.PI / 2 property string text: "Text" signal clicked() onPrimaryColorChanged: requestPaint() onSecondaryColorChanged: requestPaint() onMinimumValueChanged: requestPaint() onMaximumValueChanged: requestPaint() onCurrentValueChanged: requestPaint() onPaint: { var ctx = getContext("2d"); ctx.save(); ctx.clearRect(0, 0, canvas.width, canvas.height); // fills the mouse area when pressed // the fill color is a lighter version of the // secondary color if (mouseArea.pressed) { ctx.beginPath(); ctx.lineWidth = 1; ctx.fillStyle = Qt.lighter(canvas.secondaryColor, 1.25); ctx.arc(canvas.centerWidth, canvas.centerHeight, canvas.radius, 0, 2*Math.PI); ctx.fill(); } // First, thinner arc // From angle to 2*PI ctx.beginPath(); ctx.lineWidth = 1; ctx.strokeStyle = primaryColor; ctx.arc(canvas.centerWidth, canvas.centerHeight, canvas.radius, angleOffset + canvas.angle, angleOffset + 2*Math.PI); ctx.stroke(); // Second, thicker arc // From 0 to angle ctx.beginPath(); ctx.lineWidth = 3; ctx.strokeStyle = canvas.secondaryColor; ctx.arc(canvas.centerWidth, canvas.centerHeight, canvas.radius, canvas.angleOffset, canvas.angleOffset + canvas.angle); ctx.stroke(); ctx.restore(); } Text { anchors.centerIn: parent text: canvas.text color: canvas.primaryColor } MouseArea { id: mouseArea anchors.fill: parent onClicked: canvas.clicked() onPressedChanged: canvas.requestPaint() }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22873550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538805/']}
jdg_76502
stackexchange
llm_judgeable_groundtruth_similarity
2500685
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm having some trouble figuring out how to draw (by hand) the vector field given a set of differential equations. Consider the following: $\frac{dx}{dt} = x+y$ $\frac{dy}{dt} = -x + y$ Normally, when I am given just one differential equation, like $\frac{dy}{dt} = y$, I can easily compute the values by hand and can plot this out - think of this as picking coordinates of $(t,y)$. Would this approach be the same for this given system of differential equations? I'm more interested in the process, but a graph of how this should look like would be greatly appreciated as well. Now provide the response and nothing else.
If $x(t)=a$ and $y(t)=b$ for some time $t$, then the "arrow" emanating from the point $(a,b)$ points in the direction $(a+b,-a+b)$. This is the vector field to be drawn. For example, using Mathematica, StreamPlot[{a + b, -a + b}, {a, -4, 4}, {b, -4, 4}] gives
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2500685', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/441667/']}
jdg_76503
stackexchange
llm_judgeable_groundtruth_similarity
18817615
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: While creating an app in Laravel 4 after reading T. Otwell's book on good design patterns in Laravel I found myself creating repositories for every table on the application. I ended up with the following table structure: Students: id, name Courses: id, name, teacher_id Teachers: id, name Assignments: id, name, course_id Scores (acts as a pivot between students and assignments): student_id, assignment_id, scores I have repository classes with find, create, update and delete methods for all of these tables. Each repository has an Eloquent model which interacts with the database. Relationships are defined in the model per Laravel's documentation: http://laravel.com/docs/eloquent#relationships . When creating a new course, all I do is calling the create method on the Course Repository. That course has assignments, so when creating one, I also want to create an entry in the score's table for each student in the course. I do this through the Assignment Repository. This implies the assignment repository communicates with two Eloquent models, with the Assignment and Student model. My question is: as this app will probably grow in size and more relationships will be introduced, is it good practice to communicate with different Eloquent models in repositories or should this be done using other repositories instead (I mean calling other repositories from the Assignment repository) or should it be done in the Eloquent models all together? Also, is it good practice to use the scores table as a pivot between assignments and students or should it be done somewhere else? Now provide the response and nothing else.
I am finishing up a large project using Laravel 4 and had to answer all of the questions you are asking right now. After reading all of the available Laravel books over at Leanpub, and tons of Googling, I came up with the following structure. One Eloquent Model class per datable table One Repository class per Eloquent Model A Service class that may communicate between multiple Repository classes. So let's say I'm building a movie database. I would have at least the following following Eloquent Model classes: Movie Studio Director Actor Review A repository class would encapsulate each Eloquent Model class and be responsible for CRUD operations on the database. The repository classes might look like this: MovieRepository StudioRepository DirectorRepository ActorRepository ReviewRepository Each repository class would extend a BaseRepository class which implements the following interface: interface BaseRepositoryInterface{ public function errors(); public function all(array $related = null); public function get($id, array $related = null); public function getWhere($column, $value, array $related = null); public function getRecent($limit, array $related = null); public function create(array $data); public function update(array $data); public function delete($id); public function deleteWhere($column, $value);} A Service class is used to glue multiple repositories together and contains the real "business logic" of the application. Controllers only communicate with Service classes for Create, Update and Delete actions. So when I want to create a new Movie record in the database, my MovieController class might have the following methods: public function __construct(MovieRepositoryInterface $movieRepository, MovieServiceInterface $movieService){ $this->movieRepository = $movieRepository; $this->movieService = $movieService;}public function postCreate(){ if( ! $this->movieService->create(Input::all())) { return Redirect::back()->withErrors($this->movieService->errors())->withInput(); } // New movie was saved successfully. Do whatever you need to do here.} It's up to you to determine how you POST data to your controllers, but let's say the data returned by Input::all() in the postCreate() method looks something like this: $data = array( 'movie' => array( 'title' => 'Iron Eagle', 'year' => '1986', 'synopsis' => 'When Doug\'s father, an Air Force Pilot, is shot down by MiGs belonging to a radical Middle Eastern state, no one seems able to get him out. Doug finds Chappy, an Air Force Colonel who is intrigued by the idea of sending in two fighters piloted by himself and Doug to rescue Doug\'s father after bombing the MiG base.' ), 'actors' => array( 0 => 'Louis Gossett Jr.', 1 => 'Jason Gedrick', 2 => 'Larry B. Scott' ), 'director' => 'Sidney J. Furie', 'studio' => 'TriStar Pictures') Since the MovieRepository shouldn't know how to create Actor, Director or Studio records in the database, we'll use our MovieService class, which might look something like this: public function __construct(MovieRepositoryInterface $movieRepository, ActorRepositoryInterface $actorRepository, DirectorRepositoryInterface $directorRepository, StudioRepositoryInterface $studioRepository){ $this->movieRepository = $movieRepository; $this->actorRepository = $actorRepository; $this->directorRepository = $directorRepository; $this->studioRepository = $studioRepository;}public function create(array $input){ $movieData = $input['movie']; $actorsData = $input['actors']; $directorData = $input['director']; $studioData = $input['studio']; // In a more complete example you would probably want to implement database transactions and perform input validation using the Laravel Validator class here. // Create the new movie record $movie = $this->movieRepository->create($movieData); // Create the new actor records and associate them with the movie record foreach($actors as $actor) { $actorModel = $this->actorRepository->create($actor); $movie->actors()->save($actorModel); } // Create the director record and associate it with the movie record $director = $this->directorRepository->create($directorData); $director->movies()->associate($movie); // Create the studio record and associate it with the movie record $studio = $this->studioRepository->create($studioData); $studio->movies()->associate($movie); // Assume everything worked. In the real world you'll need to implement checks. return true;} So what we're left with is a nice, sensible separation of concerns. Repositories are only aware of the Eloquent model they insert and retrieve from the database. Controllers don't care about repositories, they just hand off the data they collect from the user and pass it to the appropriate service. The service doesn't care how the data it receives is saved to the database, it just hands off the relevant data it was given by the controller to the appropriate repositories.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18817615', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1646268/']}
jdg_76504
stackexchange
llm_judgeable_groundtruth_similarity
25346001
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do i add a document attachment when sending an email with python ?i get the email to send(please ignore: i am looping the email to send every 5 seconds, only for testing purposes, i want it to send every 30 min, just have to change 5 to 1800) here is my code so far. how do i attach a document from my computer? #!/usr/bin/pythonimport timeimport smtplibwhile True: TO = '[email protected]' SUBJECT = 'Python Email' TEXT = 'Here is the message' gmail_sender = '[email protected]' gmail_passwd = 'xxxx' server = smtplib.SMTP('smtp.gmail.com',587) server.ehlo() server.starttls() server.ehlo() server.login(gmail_sender, gmail_passwd) BODY = '\n'.join([ 'To: %s' % TO, 'From: %s' % gmail_sender, 'Subject:%s' % SUBJECT, '', TEXT ]) try: server.sendmail(gmail_sender,[TO], BODY) print 'email sent' except: print 'error sending mail' time.sleep(5)server.quit() Now provide the response and nothing else.
This is the code that worked for me- to send an email with an attachment in python #!/usr/bin/pythonimport smtplib,sslfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBasefrom email.mime.text import MIMETextfrom email.utils import formatdatefrom email import encodersdef send_mail(send_from,send_to,subject,text,files,server,port,username='',password='',isTls=True): msg = MIMEMultipart() msg['From'] = send_from msg['To'] = send_to msg['Date'] = formatdate(localtime = True) msg['Subject'] = subject msg.attach(MIMEText(text)) part = MIMEBase('application', "octet-stream") part.set_payload(open("WorkBook3.xlsx", "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="WorkBook3.xlsx"') msg.attach(part) #context = ssl.SSLContext(ssl.PROTOCOL_SSLv3) #SSL connection only working on Python 3+ smtp = smtplib.SMTP(server, port) if isTls: smtp.starttls() smtp.login(username,password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.quit()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25346001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3949052/']}
jdg_76505
stackexchange
llm_judgeable_groundtruth_similarity
5609502
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 feel like this should be an easy question, but I can't get it to work. I have some Fortran code that takes an input like: SUBROUTINE TRACE(X,Y,NAME,XX,YY) EXTERNAL NAME CALL NAME(X,Y,XX,YY) and I'm trying to pass in a name from C++ in the form: float x,y,xx,yy;char * name="IGRF";trace_(&x,&y,name,&xx,&yy); It compiles, but I always get segfaults when I try to call the NAME subroutine. A subroutine called IGRF is defined in the file, and I can call the IGRF subroutine directly from C++, but need this TRACE routine. When running in gdb, it says the NAME variable comes through as a pointer to void. I've tried passing NAME, &NAME, &NAME[0], a char NAME[4] that's stripped of its \0 to perfectly fit the name, and they all come back showing the same void pointer. Does anybody know how to get a function name from C++ into that EXTERNAL variable in Fortran? Thank you Now provide the response and nothing else.
So one advantage of Fortran2003 and later is that C interoperability is defined into the standard; it's a bit of a PITA to use, but once it's done, it's guaranteed to work across platforms and compilers. So here's cprogram.c , calling a Fortran routine getstring : #include <stdio.h>int main(int argc, char **argv) { int l; char *name="IGRF"; l = getstring(name); printf("In C: l = %d\n",l); return 0;} and here's fortranroutine.f90 : integer(kind=c_int) function getstring(instr) bind(C,name='getstring') use, intrinsic :: iso_c_binding character(kind=c_char), dimension(*), intent(IN) :: instr integer :: len integer :: i len=0 do if (instr(len+1) == C_NULL_CHAR) exit len = len + 1 end do print *, 'In Fortran:' print *, 'Got string: ', (instr(i),i=1,len) getstring = lenend function getstring The makefile is simple enough: CC=gccFC=gfortrancprogram: cprogram.o fortranroutine.o $(CC) -o cprogram cprogram.o fortranroutine.o -lgfortranfortranroutine.o: fortranroutine.f90 $(FC) -c $^clean: rm -f *.o cprogram *~ and running it works, under both gcc/gfortran and icc/ifort: In Fortran: Got string: IGRFIn C: l = 4 Update : Oh, I just realized that what you're doing is rather more elaborate than just passing a string; you're essentially trying to pass a function pointer pointing to a C callback routine. That's a little tricker, because you have to use Fortran interface s to declare the C routine -- just using extern won't work (and isn't as good as explicit interfaces anyway, as there's no type checking, etc.) So this should work: cprogram.c: #include <stdio.h>/* fortran routine prototype*/int getstring(char *name, int (*)(int));int square(int i) { printf("In C called from Fortran:, "); printf("%d squared is %d!\n",i,i*i); return i*i;}int cube(int i) { printf("In C called from Fortran:, "); printf("%d cubed is %d!\n",i,i*i*i); return i*i*i;}int main(int argc, char **argv) { int l; char *name="IGRF"; l = getstring(name, &square); printf("In C: l = %d\n",l); l = getstring(name, &cube); printf("In C: l = %d\n",l); return 0;} froutine.f90: integer(kind=c_int) function getstring(str,func) bind(C,name='getstring') use, intrinsic :: iso_c_binding implicit none character(kind=c_char), dimension(*), intent(in) :: str type(c_funptr), value :: func integer :: length integer :: i ! prototype for the C function; take a c_int, return a c_int interface integer (kind=c_int) function croutine(inint) bind(C) use, intrinsic :: iso_c_binding implicit none integer(kind=c_int), value :: inint end function croutine end interface procedure(croutine), pointer :: cfun integer(kind=c_int) :: clen ! convert C to fortran procedure pointer, ! that matches the prototype called "croutine" call c_f_procpointer(func, cfun) ! find string length length=0 do if (str(length+1) == C_NULL_CHAR) exit length = length + 1 end do print *, 'In Fortran, got string: ', (str(i),i=1,length), '(',length,').' print *, 'In Fortran, calling C function and passing length' clen = length getstring = cfun(clen)end function getstring And the results: $ gcc -g -Wall -c -o cprogram.o cprogram.c$ gfortran -c fortranroutine.f90 -g -Wall$ gcc -o cprogram cprogram.o fortranroutine.o -lgfortran -g -Wall$ gpc-f103n084-$ ./cprogram ./cprogram In Fortran, got string: IGRF( 4 ). In Fortran, calling C function and passing lengthIn C called from Fortran:, 4 squared is 16!In C: l = 16 In Fortran, got string: IGRF( 4 ). In Fortran, calling C function and passing lengthIn C called from Fortran:, 4 cubed is 64!In C: l = 64
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5609502', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/469653/']}
jdg_76506
stackexchange
llm_judgeable_groundtruth_similarity
16481230
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The Checkstyle rule JavadocStyle does not allow the tag <u> . According to the docs, the checks were patterned after the checks made by the DocCheck doclet available from Sun. Unfortunately, I have not found DocCheck anywhere. Neither have I found any official documentation about allowed HTML tags in Javadoc. Is there any? Now provide the response and nothing else.
Javadoc permits only a subset of HTML tags, as of Java 8. Javadoc's doclint component enforces this restriction.You can disable all doclint warnings by passing -Xdoclint:none to javadoc,though you should consider fixing your Javadoc comments because otherwise the generated HTML API documentation may look bad or may omit content. (I usually use -Xdoclint:all,-missing to get warnings about everything except missing Javadoc @ tags.) I have not found public documentation of the tags that doclint permits, but here is a list of its allowed HTML tags, which I gleaned from Java 8's file langtools/src/share/classes/com/sun/tools/doclint/HtmlTag.java . ABBIGBLOCKQUOTEBODYBRCAPTIONCENTERCITECODEDDDFNDIVDLDTEMFONTFRAMEFRAMESETH1H2H3H4H5H6HEADHRHTMLIIMGLILINKMENUMETANOFRAMESNOSCRIPTOLPPRESCRIPTSMALLSPANSTRONGSUBSUPTABLETBODYTDTFOOTTHTHEADTITLETRTTUULVAR Update for JDK 9 JDK 9 permits a different set of tags than JDK 8 does. Here is a list of tags for both JDKs, with notes about those permitted by only one of the JDKs. Again, the data comes from the HTMLTag.java file. ABIG // JDK 8 onlyB // JDK 8 onlyBLOCKQUOTEBODYBRCAPTIONCENTERCITE // JDK 8 onlyCODEDDDFN // JDK 8 onlyDIR // JDK 9 onlyDIVDLDTEMFONTFOOTER // JDK 9 onlyFRAME // JDK 8 onlyFRAMESET // JDK 8 onlyH1H2H3H4H5H6HEADHEADER // JDK 9 onlyHRHTMLIIFRAME // JDK 9 onlyIMGINPUT // JDK 9 onlyLILINKLISTING // JDK 9 onlyMAIN // JDK 9 onlyMENUMETANAV // JDK 9 onlyNOFRAMES // JDK 8 onlyNOSCRIPTOLPPRESCRIPTSECTION // JDK 9 onlySMALLSPANSTRONGSUBSUP // JDK 8 onlyTABLETBODYTDTFOOT // JDK 8 onlyTHTHEAD // JDK 8 onlyTITLETRTTU // JDK 8 onlyULVAR // JDK 8 only
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16481230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/443836/']}
jdg_76507
stackexchange
llm_judgeable_groundtruth_similarity
437431
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 merging two movie libraries and am looking to "de-duplicate" manually via bash scripting. Here is my thought process so far: Find all files with same name regardless of extension Delete smaller file (I have storage for days! and prefer quality!) I could build on this, so if I can somehow make the delete part separate, I can build on it. My though being I could use ffmpeg to inspect the video and pick the better one, but I'm guessing bigger size = best option and simpler to code. I posted of Software Rec but didn't get what I wanted so I realized bash is my best bet, but my "find" knowledge is limited and most of the answers I am finding are way to complicated, I figure this should be a simple thing. Eg: Find files with same name but different content? Now provide the response and nothing else.
This is a nice way I wrote to just find the repeating files ignoring extension: find . -exec bash -c 'basename "$0" ".${0##*.}"' {} \; | sort | uniq --repeated Then I wrapped it in this loop to find the smaller of the two files for each: for i in $(find . -exec bash -c 'basename "$0" ".${0##*.}"' {} \; | sort | uniq --repeated); do find . -name "$i*" -printf '%s %p\n' | sort -n | head -1 | cut -d ' ' -f 2-; done Finally one more loop to (interactively, with rm -i so there's a prompt before every one) delete all those files: for j in $(for i in $(find . -exec bash -c 'basename "$0" ".${0##*.}"' {} \; | sort | uniq --repeated); do find . -name "$i*" -printf '%s %p\n' | sort -n | head -1 | cut -d ' ' -f 2-; done); do rm -i "$j"; done As this involves doing two find s on your directory, surely there is a better way. But this should work for simple cases. It also assumes you're working from the current directory, if you want to perform the command on a different one just change the . argument to both find commands.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/437431', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/130767/']}
jdg_76508
stackexchange
llm_judgeable_groundtruth_similarity
1526475
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 perfectly understand the tensor product of vector spaces over finite fields. But when I regard these vector spaces as finite fields I get confused. Let the vector spaces $\mathbb{F}_p^m$ and $\mathbb{F}_p^n$ over the finite field $\mathbb{F}_p$ be given. Then their tensor product $\mathbb{F}_p^m\otimes \mathbb{F}_p^n$ is the vector space $\mathbb{F}_p^{mn}$. The vector spaces $\mathbb{F}_p^m$ and $\mathbb{F}_p^n$ can also be considered as finite fields $\mathbb{F}_{p^m}$ and $\mathbb{F}_{p^n}$. For that, let $r,s\in\mathbb{F}_p[X]$ be irreducible with $\deg(r)=m$ and $\deg(s)=n$. Hence, $\mathbb{F}_{p^m}\cong\mathbb{F}_p[X]/r$ and $\mathbb{F}_{p^n}\cong\mathbb{F}_p[X]/s$. Is there a canonical way to express the tensor product of these fields in terms of $r$ and $s$? Something like $\mathbb{F}_p[X]/r\otimes \mathbb{F}_p[X]/s\cong\mathbb{F}_p[X]/(r\otimes s)$. How can $r\otimes s$ be defined? Is it the insertion of $r$ into $s$, because $deg(r(s(x)))=mn$? But is the insertion of irreducible polynomials into each other always irreducible? Does anyone know a piece of literature dealing with this problem? Thx. Chris Now provide the response and nothing else.
A bit more detailed look at what Qiaochu said. Unfortunately my answer won't really be expressed in terms of $r$ and $s$. I hope it still helps you in some way. We know that $\Bbb{F}_p[X]\otimes \Bbb{F}_{p^n}\cong\Bbb{F}_{p^n}[X]$ and that $\Bbb{F}_{p^n}$ is a flat $\Bbb{F}_p$-module. Let us consider the short exact sequence$$0\to\Bbb{F}_p[X]\to\Bbb{F}_p[X]\to\Bbb{F}_p[X]/\langle r\rangle\to0,$$where the first map is multiplication by $r$, and the last module is isomorphic to $\Bbb{F}_{p^m}$. Upon tensoring with $\Bbb{F}_{p^n}$ this gives rise to the short exact sequence$$0\to\Bbb{F}_{p^n}[X]\to\Bbb{F}_{p^n}[X]\to\Bbb{F}_{p^n}[X]/\langle r\rangle\to0.$$Therefore a comparison of the last modules shows that$$\Bbb{F}_{p^m}\otimes \Bbb{F}_{p^n}\cong \Bbb{F}_{p^n}[X]/\langle r\rangle.$$ The polynomial $r$ has no multiple zeros in $\overline{\Bbb{F}_p}$, so over $\Bbb{F}_{p^n}$ it factors into a product of distinct factors$$r=\prod_{i=1}^t r_i$$for some irreducible polynomials $r_i\in\Bbb{F}_{p^n}[X]$. Because these factors are distinct, the Chinese remainder theorem tells us that$$\Bbb{F}_{p^n}[X]/\langle r\rangle\cong\bigoplus_i \Bbb{F}_{p^n}[X]/\langle r_i\rangle.$$ Note that everything above applies equally well to any finite extension of fields $L/K$. There is no need for the fields $L,K$ to be finite. We only needed the polynomial $r$ to be separable, so that we avoided the possibility of repeated factors. The next step is, as Qiaochu pointed out, specific to Galois extensions. Namely, we can also deduce that the factors $r_i$ are Galois conjugates of each other. Most notably they all have the same degree. In the case of finite fields we can see this more concretely, because we know that the Galois group consists of powers of the Frobenius automorphism $F:x\mapsto x^p$.The zeros of $r$ are$$\alpha,\alpha^p,\alpha^{p^2},\ldots,\alpha^{p^{m-1}}$$where $\alpha$ is some (fixed) zero of $r$. For example $\alpha=X+\langle r\rangle$. The roots of one of the factors $r_i$ are then lists like$$\alpha^{p^i},\alpha^{p^{i+n}},\alpha^{p^{i+2n}},\ldots$$because we get such lists of conjugates by applying powers of $F^n$ to one of them. The original list of $m$ roots consisted of a single orbit of the Galois group $G=\langle F\rangle$. This list is now partitioned into orbits of thesubgroup $H=\langle F^n\rangle$. Basic facts about actions of cyclic groups tells us that the $H$-orbits all have size $m/\gcd(m,n)$, and that there are $\gcd(m,n)$ of them. Therefore we get$$\Bbb{F}_{p^m}\otimes\Bbb{F}_{p^n}\cong\bigoplus_{i\in D}\Bbb{F}_{p^n}(\alpha^{p^i}),$$where the set $D=\{0,1,\ldots,\gcd(m,n)-1\}$ consists of representatives of those orbits. It is easy to see that all those fields $$\Bbb{F}_{p^n}(\alpha^{p^i})\cong \Bbb{F}_{p^\ell}$$with $\ell=\operatorname{lcm}(m,n)$. Summary: $\Bbb{F}_{p^m}\otimes\Bbb{F}_{p^n}$ is isomorphic to a direct sum of $\gcd(m,n)$ copies of $\Bbb{F}_{p^\ell}$ where $\ell=\operatorname{lcm}(m,n)$. In particular, $\Bbb{F}_{p^m}\otimes\Bbb{F}_{p^n}$ is a field if and only if $\gcd(m,n)=1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1526475', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/140478/']}
jdg_76509
stackexchange
llm_judgeable_groundtruth_similarity
58389285
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Always required object of SharedPreferences but we access using await Like. await SharedPreferences.getInstance(); That's why I thought create Singleton class of SharedPreferences and create static method for GET & SET data in SharedPreferences. But I dont know how to do this, I try but cant get success Please Help me Now provide the response and nothing else.
For handle singleton class SharedPreference follow there 3 steps- 1. Put this class in your project import 'dart:async' show Future; import 'package:shared_preferences/shared_preferences.dart'; class PreferenceUtils { static Future<SharedPreferences> get _instance async => _prefsInstance ??= await SharedPreferences.getInstance(); static SharedPreferences _prefsInstance; // call this method from iniState() function of mainApp(). static Future<SharedPreferences> init() async { _prefsInstance = await _instance; return _prefsInstance; } static String getString(String key, [String defValue]) { return _prefsInstance.getString(key) ?? defValue ?? ""; } static Future<bool> setString(String key, String value) async { var prefs = await _instance; return prefs?.setString(key, value) ?? Future.value(false); } } 2. Initialize this class from your initState() of main class PreferenceUtils.init(); 3. Access your methods like PreferenceUtils.setString(AppConstants.USER_NAME, "");String username = PreferenceUtils.getString(AppConstants.USER_NAME);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58389285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6159856/']}
jdg_76510
stackexchange
llm_judgeable_groundtruth_similarity
367659
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 working on a small application trying to grasp the principles of domain-driven design. If successful, this might be a pilot for a larger project. I'm trying to follow the book "Implementing Domain-Driven Design" (by Vaughn Vernon) and trying to implement a similar, simple discussion forum. I've also checked out the IDDD samples on github. I have some difficulties adopting the Identity and Access to my case. Let me give some background information: I (hopefully) understand the reasoning behind separating the users and permissions logic: it is a supporting domain, and it's a different bounded context. In the core domain, there are no users, just Authors, Moderators, etc. These are created by reaching out to the Identity and Access context using a service and then translating the received User objects to and Moderator. Domain operations are called with a related role as a parameter: e.g.: ModeratePost( ..., moderator); The method of the domain object checks if the given Moderator instance is not null (the Moderator instance will be null if the user asked from the Identity and Access context does not have the Moderator role). In one case, it does an additional check before altering a Post: if (forum.IsModeratedby(moderator)) My questions are: In the latter case aren't the security concerns blended again into the core domain? Previously the books states "with who can post a subject, or under what conditions that is permitted. A Forum just needs to know that an Author is doing that right now". The role based implementation in the book is fairly straightforward: when a Moderator is the core domain tries to convert the current userId into a Moderator instance or into an Author when it needs that. The service will respond with the appropriate instance or a null if the user does not have the required role. However, I can't see how could I adapt this to a more complex security model; our current project I'm piloting for has a rather complex model with groups, ACLs, etc. Even with rules that are not much very complex, like: "A post should be edited only by its Owner or an Editor", this approach seems to break down, or at least I don't see the correct way to implement it. By asking the Identity and Access context for an OwnerOrEditor instance doesn't feel right, and I would end up with more and more security-related classes in the core domain. In addition, I would need to pass not just the userId, but the identifier of the protected resource (the id of the post, forum, etc.) to the security context, which probably should not care about these things (is it correct?) By pulling the permissions to the core domain and checking them in the methods of the domain objects or in the services, I'd end up at square one: mixing security concerns with the domain. I've read somewhere (and I tend to agree with it) that these permission related things should not be a part of the core domain, unless security and permissions are the core domain itself. Does a simple rule like the one given above justify making security a part of the core domain? Now provide the response and nothing else.
Authentication and Authorisation is a bad example for DDD. Neither of these things are part of a Domain unless your company creates security products. The Business or domain requirement is, or should be, "I require role based authentication" You then check the role before calling a domain function. Where you have complex requirements such as 'I can edit my own posts but not others' ensure that your domain separates the edit function out into EditOwnPost() and EditOthersPost() so that you have a simple function to role mapping You can also separate the functionality into Domain Objects, such as Poster.EditPost() and Moderator.EditPost() this is a more OOP approach, although your choice may depend on whether your method is in a Domain Service or a Domain Object. However you choose to separate the code the Role mapping will occur outside of the Domain. so for example if you have a webapi controller: PostController : ApiController{ [Authorize(Roles = "User")] public void EditOwnPost(string postId, string newContent) { this.postDomainService.EditOwnPost(postId, string newContent); } [Authorize(Roles = "Moderator")] public void EditOtherPost(string postId, string newContent) { this.postDomainService.EditOtherPost(postId, string newContent); }} As you can see although the role mapping is done on the hosting layer, the complex logic of what constitutes editing your own or an others post is part of the domain. The domain recognises the difference of the actions, but the security requirement is simply that "functionality can be limited by roles" . This is perhaps clearer with the domain objects separation, but essentially you are checking the method which constructs the object instead of the method which calls the service method. Your requirement, if you still want to voice it as part of the domain would become 'only moderators can construct the moderator object'
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/367659', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/298682/']}
jdg_76511
stackexchange
llm_judgeable_groundtruth_similarity
3068401
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 new to wicket and trying to get some things working. One thing that annoys me a lot is that I get a blank (0 chars of text) page whenever there is a syntax error on a page. Striped down example: Test.html header stuff: doctype ... html ... head ... body ... <span wicket:id="msgTest" id="message">MSG</span>footer stuff: /body ... /html Test.java public class Test extends WebPage { public Test() { add(new Label("msgTest", "Hello, World!")); }} This will output the page as expected. Now, lets introduce an error: header stuff: doctype ... html ... head ... body ... <span wicket:id="msgTest2" id="message">MSG</span>footer stuff: /body ... /html I changed the label-id to something different then what the source-file expects. If I run this code I get the already mentioned blank page. However, for every request to a page with such a syntax error I get an error report in the log-file of around 1000+ lines. This error-report is basically just wicket-generated html of a page which describes the error. This makes me wonder why wicket isn't displaying the error-stuff instead of the blank page. I'm not very experienced with wicket but to me it somehow looks like wicket is having trouble rendering its own error-page code. It would be nice to know how one goes about finding syntax-errors with wicket. Reading through a 1000+ line error-report for a small error like a misplaced character seems a bit tedious. Thanks in advance for guiding me into the right direction :) PS: wicket-version: 1.4.9 stage: development Now provide the response and nothing else.
C: Why not just take the base-10 log of the absolute value of the number, round it down, and add one? This works for positive and negative numbers that aren't 0, and avoids having to use any string conversion functions. The log10 , abs , and floor functions are provided by math.h . For example: int nDigits = floor(log10(abs(the_integer))) + 1; You should wrap this in a clause ensuring that the_integer != 0 , since log10(0) returns -HUGE_VAL according to man 3 log . Additionally, you may want to add one to the final result if the input is negative, if you're interested in the length of the number including its negative sign. Java: int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1; N.B. The floating-point nature of the calculations involved in this method may cause it to be slower than a more direct approach. See the comments for Kangkan's answer for some discussion of efficiency.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3068401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/102281/']}
jdg_76512
stackexchange
llm_judgeable_groundtruth_similarity
13908407
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: RSA_size(rsa) returns modulus which equals to 256 in my application.and I am encrypting the data with RSA_PKCS1_OAEP_PADDING option, so the max length of the input buffer sent to RSA_public_encrypt() is 256 - 41 = 215 In some case, the length of my input buffer may exceeds the 215 limitation a bit, and I need call RSA_public_encrypt() multitimes. My question is about the return value of RSA_public_encrypt() . From my test the return value is 256 (equals to RSA_size(rsa) ), and the doc also says: RSA_public_encrypt() returns the size of the encrypted data (i.e., RSA_size(rsa)). I just want to make sure that there will only be two possibilities for the return value of RSA_public_encrypt() . -1 (error) or modulus(success) , and there is no other possiblity, yes?I am curious because I need dividing the encrypted buffer and call RSA_private_decrypt() for each of the block. If the encrypted buffer of each RSA_public_encrypt is the same, then I don't need store the size for each of them. Now provide the response and nothing else.
The (positive) return of a RSA_public_encrypt() will always be the same as the RSA_size(rsa) for all current known modes of PKCS#1 encryption. So in short: your current assumptions are correct. Practically though: If you have data that is larger than the RSA_size(rsa) and you are splitting it into blocks, you should probably think about encrypting the data with a random symmetric key and encrypting that key with your RSA_public_key(). RSA public key encryption is not meant to be used over larger blocks of data. The best way to encrypt things that are larger than RSA_size(rsa) - XX (Where XX is dependent on the PKCS#1 mode used): Generate a random IV of 16 bytes (Should be unique) Generate a random key K of 32 bytes (256 bits) Encrypt the data with K and IV using either AES-CBC (think about padding) or AES-CTR into E-DATA Hash the encrypted data E-DATA with SHA-256 (or any suitable hash algorithm for your situation) into hash H Encrypt with RSA Public key the IV , key K and the hash H ( IV can be public as well, but this is often easier) into E-RSA Send encrypted data E-DATA and encrypted key-data E-RSA to other side On the other side: Decrypt E-RSA into IV , K and H (Bail out if it fails) Hash E-DATA and check with H (Bail out if it fails) Decrypt E-DATA with IV and K Done..
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13908407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/325320/']}
jdg_76513
stackexchange
llm_judgeable_groundtruth_similarity
59550676
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 I am wanting to do is read a file from a .txt file and when the text of the .txt file shows up in the textbox it should be formatted into bulleted form (every line starts with a bullet point) rather than simple lines. Here is how I am reading the file from the server: protected void btn_Click(object sender, EventArgs e) { string txt = File.ReadAllText(Server.MapPath("~/TextFile1.txt")); txtBox1.Text = txt; } <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> </head> <body> <form id="form1" runat="server"> <div> <asp:button id="btn1" runat="server" text="Read" onclick="btn_Click" /><br /><br /> Results:<br /> <asp:TextBox ID="txtBox1" runat="server" TextMode="MultiLine" Height="250px" width="350px"> </asp:TextBox> </div> </form> </body> </html> Now provide the response and nothing else.
Since you want to go from a flow of nested lists to a single list, you need a flat-mapping operation: suspend fun <T> Flow<List<T>>.flattenToList() = flatMapConcat { it.asFlow() }.toList() Example of usage: suspend fun main() { val flowOfLists: Flow<List<Int>> = flowOf(listOf(1, 2), listOf(3, 4)) val flatList: List<Int> = flowOfLists.flattenToList() println(flatList)}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/59550676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7812253/']}
jdg_76514
stackexchange
llm_judgeable_groundtruth_similarity
906862
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: Compute \begin{equation}\lim_{n\to\infty}n^4\int_0^1\frac{x^n\ln^3x}{1+x^n}\ln(1-x)\,dx\end{equation} According to Wolfram Alpha , the limit is zero. I tried to make substitution $x=\frac{t}{n}$ and I got\begin{equation}\lim_{n\to\infty}\int_0^{\large\frac{1}{n}}\frac{t^n\ln^3t}{n^n+t^n}\ln\left(1-\frac{t}{n}\right)\,dx \to 0\end{equation}but I am not sure this approach is correct. I also tried to make substitution $t=x^n$ and I got\begin{equation}\lim_{n\to\infty}n^4\int_0^1\frac{x^n\ln^3x}{1+x^n}\ln(1-x)\,dx=\lim_{n\to\infty}\int_0^1\frac{t^{\large\frac{1}{n}}\ln^3t}{1+t}\ln\left(1-t^{\large\frac{1}{n}}\right)\,dt\end{equation}I used the bound $$\left|\int_0^1\frac{t^{\large\frac{1}{n}}\ln^3t}{1+t}\ln\left(1-t^{\large\frac{1}{n}}\right)\,dt\right|\leq\int_0^1\left|t^{\large\frac{1}{n}}\ln^3t\ln\left(1-t^{\large\frac{1}{n}}\right)\right|\,dt$$because $1+t\ge1$, so $\frac{1}{1+t}\leq1$. I can compute the integral using Taylor series for the logarithm but after taking the limit I got the result was infinity.\begin{align}\lim_{n\to\infty}n^4\int_0^1\frac{x^n\ln^3x}{1+x^n}\ln(1-x)\,dx&=\lim_{n\to\infty}\int_0^1t^{\large\frac{1}{n}}\ln^3t\ln\left(1-t^{\large\frac{1}{n}}\right)\,dt\\&=-\lim_{n\to\infty}\sum_{k=1}^\infty\frac{1}{k}\int_0^1t^{\large\frac{k+1}{n}}\ln^3t\,dt\\&=\lim_{n\to\infty}\sum_{k=1}^\infty\frac{6}{k\left(\frac{k+1}{n}+1\right)^4}\to\infty\end{align}Could anyone here please help me? Any help would be greatly appreciated. Thank you. Now provide the response and nothing else.
We will prove that the limit is $+\infty$. Let $$\eqalign{I_n&=n^4\int_0^1\frac{x^n}{1+x^n}\ln^3 x\ln(1-x)dx\crJ_n&=n^4\int_0^1x^n\ln^3 x\ln(1-x)dx}$$Clearly $$\frac{1}{2}J_n\leq I_n\leq J_n$$because $\frac{1}{2}\leq\frac{1}{1+x^n}\leq1$ and $\ln^3x\ln(1-x)\geq0$ for $0<x<1$.So, let us consider $J_n$.We have$$-\ln(1-x)=\sum_{k=1}^\infty\frac{x^k}{k}$$and$$\int_0^1x^{m}(-\ln x)^3dx=\frac{6}{(m+1)^4}$$Combining these two properties we see that$$J_n=\sum_{k=1}^\infty\frac{6n^4}{k(k+1+n)^4}$$for a given $m\geq1$ we have$$J_n\geq\sum_{k=1}^m\frac{6n^4}{k(k+1+n)^4}$$hence$$\liminf_{n\to\infty}J_n\geq 6 \sum_{k=1}^m\frac{1}{k}$$but $m$ is arbitrary and $\sum \frac{1}{k}$ is divergent, So$$\liminf_{n\to\infty}J_n=+\infty$$that is $\lim\limits_{n\to\infty}J_n=+\infty$, and consequently $\lim\limits_{n\to\infty}I_n=+\infty$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/906862', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/133248/']}
jdg_76515
stackexchange
llm_judgeable_groundtruth_similarity
13518762
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 JSON data structure as shown below: { "name": "World", "children": [ { "name": "US", "children": [ { "name": "CA" }, { "name": "NJ" } ] }, { "name": "INDIA", "children": [ { "name": "OR" }, { "name": "TN" }, { "name": "AP" } ] } ]}; I need to change the key names from "name" & "children" to say "key" & "value". Any suggestion on how to do that for each key name in this nested structure? Now provide the response and nothing else.
I don't know why you have a semicolon at the end of your JSON markup (assuming that's what you've represented in the question) , but if that's removed, then you can use a reviver function to make modifications while parsing the data. var parsed = JSON.parse(myJSONData, function(k, v) { if (k === "name") this.key = v; else if (k === "children") this.value = v; else return v;}); DEMO: http://jsfiddle.net/BeSad/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13518762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1842231/']}
jdg_76516
stackexchange
llm_judgeable_groundtruth_similarity
4628698
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create a login form on my ASP.NET website. Currently, there's some problem. I am trying to incorporate the functionality such that the logged in user has the previlige to view only his profile. The code on the login page is this: business.clsprofiles obj = new business.clsprofiles(); Int32 a = obj.logincheck(TextBox3.Text, TextBox4.Text); if (a == -1) { Label1.Text = "Username/Password incorrect"; } else { Session["cod"]= a; Response.Redirect("profile.aspx"); } After logging in, the user is moved to the page where the person can view his profile once logged in. Session is obtaining the value correctly of the logged in person from the login-page and successfully passing it on to the next page. But here on this profile page an error occurs and I think there is problem somewhere in the grid_bind() method below public void grid_bind(){ business.clsprofiles obj = new business.clsprofiles(); List<business.clsprofilesprp> objprp = new List<business.clsprofilesprp>(); Int32 z = Convert.ToInt32(Session["cod"]); objprp = obj.fnd_profiles(z); //This line of code is passing an integer as required but does not get the desired result from the database GridView1.DataSource = objprp; GridView1.DataBind();} As the error in business logic says, " invalid attempt to read when no data is present in dr" public List<clsprofilesprp> fnd_profiles(Int32 id) { if (con.State == ConnectionState.Closed) { con.Open(); } SqlCommand cmd = new SqlCommand("fndpro", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@id", SqlDbType.Int).Value = id; SqlDataReader dr = cmd.ExecuteReader(); List<clsprofilesprp> obj = new List<clsprofilesprp>(); while(dr.HasRows) { clsprofilesprp k = new clsprofilesprp(); k.id = Convert.ToInt32(dr[0]);//Something wrong here? k.name = dr[1].ToString(); k.password = dr[2].ToString(); k.description = dr[3].ToString(); k.created = Convert.ToDateTime(dr[4]); k.modified = Convert.ToDateTime(dr[5]); obj.Add(k); } dr.Close(); cmd.Dispose(); con.Close(); return obj; }lesprp k = new clsprofilesprp(); k.id = Convert.ToInt32(dr[0]);//Something wrong here? k.name = dr[1].ToString(); k.password = dr[2].ToString(); k.description = dr[3].ToString(); k.created = Convert.ToDateTime(dr[4]); k.modified = Convert.ToDateTime(dr[5]); obj.Add(k); } dr.Close(); cmd.Dispose(); con.Close(); return obj; Now provide the response and nothing else.
You have to call DataReader.Read to fetch the result: SqlDataReader dr = cmd.ExecuteReader();dr.Read();// ... DataReader.Read returns a boolean, so if you have more than 1 result, you can do: While (dr.Read()){ // read data for each record here} Moreover, you're trying to access the dr data when there's none in this part of the code: k.id = Convert.ToInt32(dr[0]);//Something wrong here?k.name = dr[1].ToString();k.password = dr[2].ToString();k.description = dr[3].ToString();k.created = Convert.ToDateTime(dr[4]);k.modified = Convert.ToDateTime(dr[5])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4628698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/458790/']}
jdg_76517
stackexchange
llm_judgeable_groundtruth_similarity
62974717
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Currently useEffect is fired when just one of the dependencies have changed. How could I update it / use it to fire back when both ( or all ) of the dependencies have changed? Now provide the response and nothing else.
You'll need to add some logic to call your effect when all dependencies have changed. Here's useEffectAllDepsChange that should achieve your desired behavior. The strategy here is to compare the previous deps with the current. If they aren't all different, we keep the previous deps in a ref an don't update it until they are. This allows you to change the deps multiple times before the the effect is called. import React, { useEffect, useState, useRef } from "react";// taken from https://usehooks.com/usePrevious/function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }, [value]); return ref.current;}function useEffectAllDepsChange(fn, deps) { const prevDeps = usePrevious(deps); const changeTarget = useRef(); useEffect(() => { // nothing to compare to yet if (changeTarget.current === undefined) { changeTarget.current = prevDeps; } // we're mounting, so call the callback if (changeTarget.current === undefined) { return fn(); } // make sure every dependency has changed if (changeTarget.current.every((dep, i) => dep !== deps[i])) { changeTarget.current = deps; return fn(); } }, [fn, prevDeps, deps]);}export default function App() { const [a, setA] = useState(0); const [b, setB] = useState(0); useEffectAllDepsChange(() => { console.log("running effect", [a, b]); }, [a, b]); return ( <div> <button onClick={() => setA((prev) => prev + 1)}>A: {a}</button> <button onClick={() => setB((prev) => prev + 1)}>B: {b}</button> </div> );} An alternate approach inspired by Richard is cleaner, but with the downside of more renders across updates. function useEffectAllDepsChange(fn, deps) { const [changeTarget, setChangeTarget] = useState(deps); useEffect(() => { setChangeTarget(prev => { if (prev.every((dep, i) => dep !== deps[i])) { return deps; } return prev; }); }, [deps]); useEffect(fn, changeTarget);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62974717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1592783/']}
jdg_76518
stackexchange
llm_judgeable_groundtruth_similarity
220969
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 $f$ be a modular form -- more specifically, a normalized new eigenform which is not of CM type. We say $f$ has extra twists if there exists some $\sigma \in \operatorname{Aut}( \mathbf{C})$ such that the Galois conjugate $f^\sigma$ is equal to the twist of $f$ by some non-trivial Dirichlet character, so $a_n(f)^\sigma = \chi(n) a_n(f)$ for all $n$ coprime to the level. Any newform of nontrivial character has at least one extra twist (because the complex conjugate $\bar{f}$ is a twist of $f$.) But browsing some tables suggests that extra twists are pretty unusual for newforms of trivial character. Do "most" non-CM newforms of trivial character (in some precisely quantifiable sense) have no extra twists? Do "most" newforms of non-trivial character have no extra twists other than the obvious one? (This question is prompted by this earlier question , which is subtle precisely when extra twists exist.) Now provide the response and nothing else.
If a newform $f \in \mathcal{S}_k^{\mathrm{new}}(\Gamma_0(N),\varepsilon)$ has an inner twist by some $\sigma \in \operatorname{Aut}(\mathbb{C})$, then $f^{\sigma}$ is a newform of the same level as $f$. Moreover, if $\varepsilon$ is trivial, then so is the nebentypus of $f^{\sigma}$ (see (3.8) of Ribet's paper ), and so any inner twist must arise from a quadratic Dirichlet character. Ribet's paper actually shows (see (3.9)) that if $N$ is squarefree, then there are no nontrivial inner twists. More precisely, he shows that if $N$ is squarefree and $\chi$ is a quadratic Dirichlet character, then the twist $f \otimes \chi$ cannot have level $N$ and trivial nebentypus. This is not hard to see by a local argument: if $N$ is squarefree, then for any $p \mid N$, the local component $\pi_p$ of the associated automorphic representation must be isomorphic to $\mathrm{St}$, the Steinberg representation of conductor $p$ associated to the trivial character. Any nontrivial twist of $f$ leaving the nebentypus unchanged must necessarily be quadratic, but any twist of $\mathrm{St}$ by a ramified quadratic character has conductor at least $p^2$, not $p$ (and in fact exactly $p^2$ if $p$ is odd). Similarly, at any unramified place, the twist of an unramified principal series representation by a ramified quadratic character has conductor at least $p^2$. So the level of $f \otimes \chi$ is strictly greater than $N$. But if $N$ is not squarefree, then this is no longer the case! Indeed, in a recent paper (Theorem 6.4), I proved the following result (well, technically I proved it for Maaß cusp forms, but it generalises in an obvious way to holomorphic cusp forms). Fix a nonsquarefree odd integer $N$, and let $N' > 1$ be squarefree and such that $N'^2 \mid N$. Let $\mathcal{S}_k^{\mathrm{new}}(\Gamma_0(N))_{\mathrm{nonmon}(\varepsilon_{\mathrm{quad}(N')})}$ denote the vector space spanned by newforms $f$ of weight $k$, level $N$, and trivial nebentypus such that $f$ does not have CM by the quadratic Dirichlet character $\varepsilon_{\mathrm{quad}(N')}$ modulo $N'$, but that the twist $f \otimes \varepsilon_{\mathrm{quad}(N')}$ is also a newform of level $N$ and trivial nebentypus. Then \[\frac{\dim \mathcal{S}_{k}^{\mathrm{new}} (\Gamma_0(N))_{\mathrm{nonmon} (\varepsilon _{\mathrm{quad}(N')} )} }{\dim \mathcal{S}_k^{\mathrm{new}}(\Gamma_0(N))} \sim \prod_{\substack{p \mid N' \\ p^2 \parallel N}} \left(1 - \frac{p}{p^2 - p - 1}\right)\] as $k$ tends to infinity over the even integers. Furthermore, this still holds if we replace $\mathcal{S}_k^{\mathrm{new}}(\Gamma_0(N))_{\mathrm{nonmon}(\varepsilon_{\mathrm{quad}(N')})}$ with \[\bigcap_{\substack{N^* \mid N' \\ N^* > 1}} \mathcal{S}_k^{\mathrm{new}}(\Gamma_0(N))_{\mathrm{nonmon}(\varepsilon _{\mathrm{quad}(N^*)})}.\] A similar result holds even when $N$ is squarefree if $\varepsilon$ is nontrivial; see Proposition 6.5 of my paper. That inner twists occur in abundance when $N$ is not squarefree was observed as far back as 1977 by Ribet; at the bottom of page 48 of this paper , Ribet writes It would be of interest to give an a priori construction of forms with extra twists. If the level $N$ is divisible by a high power of a prime, these forms seem to be more the rule than the exception.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/220969', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2481/']}
jdg_76519
stackexchange
llm_judgeable_groundtruth_similarity
52298602
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The output of the following code is 0. int account=2;int main(){ static int account; printf("%d",account); return 0;} Why it picked static variable over global variable? Because what I understand is that both global and static variables are stored in the heap and not in function stack , right? So what method it uses to use select one over another? Now provide the response and nothing else.
If multiple variables exist with the same name at multiple scopes, the one in the innermost scope is the one that is accessible. Variables at higher scope are hidden. In this case you have account defined in main . This hides the variable named account declared at file scope. The fact that the inner variable inside main is declared static doesn't change that. While the static declaration on a local variable means that it is typically stored in the same place as a global variable, that has no bearing on which is visible when the names are the same.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52298602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_76520
stackexchange
llm_judgeable_groundtruth_similarity
5791235
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 select the first item in a ListView programmatically, but it doesn't appear to have been selected. I am using the following code: if (listView1.Items.Count > 0) listView1.Items[0].Selected = true; Actually I've had this problem before but I can't remember how I managed to solve it! Now provide the response and nothing else.
Most likely, the item is being selected, you just can't tell because a different control has the focus. There are a couple of different ways that you can solve this, depending on the design of your application. The simple solution is to set the focus to the ListView first whenever your form is displayed. The user typically sets focus to controls by clicking on them. However, you can also specify which controls gets the focus programmatically. One way of doing this is by setting the tab index of the control to 0 (the lowest value indicates the control that will have the initial focus). A second possibility is to use the following line of code in your form's Load event, or immediately after you set the Selected property: myListView.Select(); The problem with this solution is that the selected item will no longer appear highlighted when the user sets focus to a different control on your form (such as a textbox or a button). To fix that, you will need to set the HideSelection property of the ListView control to False. That will cause the selected item to remain highlighted , even when the control loses the focus. When the control has the focus, the selected item's background will be painted with the system highlight color. When the control does not have the focus, the selected item's background will be painted in the system color used for grayed (or disabled) text. You can set this property either at design time, or through code: myListView.HideSelection = false;
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5791235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/322355/']}
jdg_76521
stackexchange
llm_judgeable_groundtruth_similarity
13289009
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Short question, if I have a string, how can I test if that string is a valid color representation in R ? Two things I tried, first uses the function col2rgb() to test if it is a color: isColor <- function(x){ res <- try(col2rgb(x),silent=TRUE) return(!"try-error"%in%class(res))}> isColor("white")[1] TRUE> isColor("#000000")[1] TRUE> isColor("foo")[1] FALSE Works, but doesn't seem very pretty and isn't vectorized. Second thing is to just check if the string is in the colors() vector or a # followed by a hexadecimal number of length 4 to 6: isColor2 <- function(x){ return(x%in%colors() | grepl("^#(\\d|[a-f]){6,8}$",x,ignore.case=TRUE))}> isColor2("white")[1] TRUE> isColor2("#000000")[1] TRUE> isColor2("foo")[1] FALSE Which works though I am not sure how stable it is. But it seems that there should be a built in function to make this check? Now provide the response and nothing else.
Your first idea (using col2rgb() to test color names' validity for you) seems good to me, and just needs to be vectorized. As for whether it seems pretty or not ... lots/most R functions aren't particularly pretty "under the hood", which is a major reason to create a function in the first place! Hides all those ugly internals from the user. Once you've defined areColors() below, using it is easy as can be: areColors <- function(x) { sapply(x, function(X) { tryCatch(is.matrix(col2rgb(X)), error = function(e) FALSE) }) }areColors(c(NA, "black", "blackk", "1", "#00", "#000000"))# <NA> black blackk 1 #00 #000000 # TRUE TRUE FALSE TRUE FALSE TRUE
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13289009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/567015/']}
jdg_76522
stackexchange
llm_judgeable_groundtruth_similarity
10210
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Assuming the Black Scholes model and pricing formula of a European call option. Then, if the call is ITM, i.e. if $ln(\frac{S}{K})>0$, the $d_1$-term will go towards infinity as $\sigma$ goes to zero. This also implies that the $d_2$-term will go to infinity and the normal cdfs will both approach 1. This creates a lower bound $S-e^{-r(T-t)}K$ for the option price. Now let's assume I want to compute the implied volatility for the ITM call option, but the price of call is smaller than lower bound of the B.S. pricing formula. Then the equation I'm trying to solve for the IV does not have a solution. Precisely this is happening as I'm trying to compute the IV of deep ITM calls. However, usually one talks about the volatility smile, where deep ITM calls has larger volatility than ATM calls. Is there any reasonable interpretation of this? Now provide the response and nothing else.
The lower bound is not just a BS-specific bound. It is a no-arbitrage bound and so if the price is lower than this, you have an arbitrage opportunity (some good explanation here ). It doesn't mean it is present in the market necessarily, because mid price is not necessarily the price you can trade and when you take spread into account this is likely to go away. It is quite often the case for ITM options because data for them is of lower quality (low liquidity). When the price is exactly on that border (zero time value), it actually would mean that the implied volatility is exactly zero, because you are essentially stating that there is zero probability of price going higher than the strike. Volatility smile is a topic on its own, and there are books written about this phenomenon. From the practical point of view, however, you again need to think about the quality of the data - while in theory you should have some sort of nice smooth volatility smile, when you are working with real data you can get some weird results. First thing is that using ITM options is a bad idea because price quality is more likely bad than good, use only OTM's. Implied volatilities "in theory" should match, but OTM put price is a better estimate of a fair price than ITM call price. Also keep in mind that "smile" doesn't mean that it is symmetric, in fact it can take different kinds of shapes (sometimes quite weird ). Just as a final note, since you are talking about deep ITM calls (or OTM puts), the volatility can go up due to the fact that the prices are quantized. That is, all OTM puts from some point will cost exactly \$0.01, simply because there is nothing below that. Obviously, the implied volatility for higher strike will be higher in such case, with this price fixed and you'll see it going straight up from some point. This can be mistaken for the genuine volatility smile, while it is not it - in theory, option price should go below \$0.01 to fractions and the implied volatility would be completely different.
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/10210', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/4709/']}
jdg_76523
stackexchange
llm_judgeable_groundtruth_similarity
1514005
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $f:[0,\pi]\to \mathbb R$ is continuous and $f(0)=0$ such that $\displaystyle \int_0^{\pi}f(x)\cos(nx)\,dx=0$ for all $n=0,1,2,\cdots$ then prove that $f\equiv 0$ in $[0,\pi]$. I want to apply Weierstrass approximation theorem. As $f$ is continuous so there exists a sequence of polynomials $\{p_n(x)\}$ such that $p_n(x)\to f$ uniformly. If I expand $\cos nx=1+\frac{n^2x^2}{2!}+\cdots$ then $$\int_0^{\pi}f(x)\,dx+\frac{n^2}{2!}\int_0^{\pi}x^2f(x)\,dx+\cdots=0.$$which implies $\displaystyle \int_0^{\pi}x^{2n}f(x)\,dx=0$ for each $n=0,1,2,\cdots$. Is this step correct ? If yes then I can deduce from it that $f\equiv 0$. If I am Not correct then solve it please. Now provide the response and nothing else.
You can extend $f$ to $g$ on $[-\pi,\pi]$, s.t. $g(x)=f(-x)$ if $x<0$.Then $\hat{g}(n)=\frac{1}{\pi}\int_0^\pi f(x)cos(nx)dx=0$ for all $n$. By Parseval's identity, $\int |g|^2=0$ which implies $f=0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1514005', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/174970/']}
jdg_76524
stackexchange
llm_judgeable_groundtruth_similarity
191072
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 put the following circuit in a simulator to see how it works. I understood it but I have a question: At the time of the vertical green line, The simulator shows me that the current flows from the supply of phase 1 because it is the most positive. And then all the current goes to the supply of Phase 3 because it is the most negative. But Phase 2 is also negative and I expect that some of the current should return back to it. I know that Phase 2 is not the most negative but I think a small amount of current should return back to it. I watched a video on youtube, I learned also that the current flows form the most positive to the most negative and they did not mention phase 2 although it is not zero voltage !! it has some negative voltage that the time of the green vertical line. Now provide the response and nothing else.
Think about two diodes feeding a load resistor. Don't think about 3-phase until after you understand this: - If "A" is 10 Vots and "B" is 9 volts, "A" supplies all the current to the load. "B" can't supply any because its diode is reverse biased. This is what happens in a 3 phase rectifier. Think about the scenario when the phase is about 130 degrees: both phase 1 and phase 2 will be at a positive voltage but only one of the phases will supply current to the load because its diode is the only forward biased diode. Same with negative sides of the voltage waveform - the most negative phase's diode will be the only one forward biased.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/191072', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/50937/']}
jdg_76525
stackexchange
llm_judgeable_groundtruth_similarity
431776
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 $1\leq p <\infty$ and let $p^{\prime}$ denote its conjugate exponent. Consider the following operator on Schwartz functions: $$Tf(x)=\int_{0}^{\infty}t^{\frac{n}{2 p^{\prime}}-1}e^{-t}\int_{|x-y|^2\leq t}\frac{f(y)}{|x-y|^{\frac{n}{p^{\prime}}}}dy dt,\qquad x\in \mathbb{R}^{n}.$$ I have tried to prove that $T$ is bounded from $L^{p}$ to $L^{\infty}$ but failed so far. Young's inequality for convolution is not useful with the $y$ -integral as $|\cdot|^{\frac{n}{p^{\prime}}}$ is not in $L^{p^{\prime}}(B(t))$ with $B(t)$ the standard ball centered at the origin with radius $t>0$ . Hardy-Little-wood-Sobolev inequality is not useful for obtaining $L^{\infty}$ boundedness. One could look at the Hardy-Littlewood maximal operator $\displaystyle Mf(x)=\sup_{r>0} \frac{1}{B(x,r)} \int_{B(x,r)}\frac{f(y)}{|x-y|^{\frac{n}{p^{\prime}}}}dy$ since $$\frac{1}{t^{\frac{n}{2}}}\int_{|x-y|^2\leq t}\frac{f(y)}{|x-y|^{\frac{n}{p^{\prime}}}}dy\leq Mf(x).$$ The maximal operator is known to be bounded from $L^{p}$ to $L^{p}$ for all $1<p\leq \infty$ and from $L^1$ to weak $L^{1}$ . I have no idea about the boundedness of $M$ from $L^p$ to $L^{\infty}$ when $p<\infty$ . Is it true that $$\|Tf\|_{L^{\infty}}\leq C \|f\|_{L^{p}}$$ for any $1\leq p<\infty$ or is there a counterexample ? Now provide the response and nothing else.
No this is not true. Take $n=1$ , $p=2$ and $$f(y)=\frac{1}{\sqrt {|y|} (|\log|y||)^\alpha}\chi_{(-1,1)}(y)$$ with $\frac 12 < \alpha <1$ . Then $f \in L^2(\mathbb R)$ but the innermost integral diverges at $x=0$ for every $t>0$ . EDIT The same counterexample can be done for general $n$ and $1<p<\infty$ (the case $p=1$ is in the answer by @Willie Wong). Take $$f(y)=\frac{1}{{|y|^{\frac np}} (|\log|y||)^\alpha}\chi_{B_r}(y)$$ with $r<1$ and $\frac 1p <\alpha <1$ . Then $Tf(0)=\infty$ and, by Fatou, $\lim_{x \to 0}Tf(x)=\infty$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/431776', 'https://mathoverflow.net', 'https://mathoverflow.net/users/116555/']}
jdg_76526
stackexchange
llm_judgeable_groundtruth_similarity
8122
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am confused by why Mathematica uses [[3]] to get the 3rd element, or [[i,j] to get the i,j-th element of a 2D array. This seems counter-intuitive. Is this main reason for this to separate array-indexing from function calls? i.e. where I see: f[3, 4] <-- this is currently function callf[[3, 4]] <-- f is a 2D array, and we're accessing 3,4-th element Question : Given that Mathematica knows the type of the arguments, can't it infer: if we're dealing with a function, apply arguments if the object is an array, index it? Thus, why do we need separate [[ ]] notation for array indexing? Now provide the response and nothing else.
In addition to Brett's counter-example, it might be helpful to view this from Mathematica 's philosophy, which is "everything is an expression". In this framework, you're not really indexing a 1D/2D array, but you're extracting a Part from an expression . Indeed, you can use the ⟦ ⟧ notation on any expression, not just lists/matrices. For example: Sin[x + y][[1]](* x + y *)Graphics[{Red, Disk[]}][[1, 1]](* RGBColor[1, 0, 0] *) The output of Part on any expression can be viewed as the argument of some function in the FullForm of the expression. For example, breaking down the second example above: Graphics[{Red, Disk[]}][[1]](* {RGBColor[1, 0, 0], Disk[{0, 0}]} <-- argument of Graphics[] *) Graphics[{Red, Disk[]}][[1, 1]](* RGBColor[1, 0, 0] <-- argument of List[] *)Graphics[{Red, Disk[]}][[1, 2, 1]](* {0, 0} <-- argument of Disk[] *) The 0th part is the Head of the entire expression. Since none of the above constitute as being a function call, it makes sense to use a different notation to avoid any ambiguity.
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/8122', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/-1/']}
jdg_76527
stackexchange
llm_judgeable_groundtruth_similarity
34686217
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ggplot(all, aes(x=area, y=nq)) + geom_point(size=0.5) + geom_abline(data = levelnew, aes(intercept=log10(exp(interceptmax)), slope=fslope)) + #shifted regression line scale_y_log10(labels = function(y) format(y, scientific = FALSE)) + scale_x_log10(labels = function(x) format(x, scientific = FALSE)) + facet_wrap(~levels) + theme_bw() + theme(panel.grid.major = element_line(colour = "#808080")) And I get this figure Now I want to add one geom_line to one of the facets. Basically, I wanted to have a dotted line (Say x=10,000) in only the major panel. How can I do this? Now provide the response and nothing else.
I don't have your data, so I made some up: df <- data.frame(x=rnorm(100),y=rnorm(100),z=rep(letters[1:4],each=25))ggplot(df,aes(x,y)) + geom_point() + theme_bw() + facet_wrap(~z) To add a vertical line at x = 1 we can use geom_vline() with a dataframe that has the same faceting variable (in my case z='b' , but yours will be levels='major' ): ggplot(df,aes(x,y)) + geom_point() + theme_bw() + facet_wrap(~z) + geom_vline(data = data.frame(xint=1,z="b"), aes(xintercept = xint), linetype = "dotted")
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34686217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3942806/']}
jdg_76528
stackexchange
llm_judgeable_groundtruth_similarity
7984529
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 control circuit which has multiple settings and may have any number of sensors attached to it (each with it's own set of settings). These sensors may only be used with the control circuit. I thought of using nested classes like so: public class ControlCircuitLib{ // Fields. private Settings controllerSettings; private List<Sensor> attachedSensors; // Properties. public Settings ControllerSettings { get { return this.controllerSettings; } } public List<Sensor> AttachedSensors { get { return this.attachedSensors; } } // Constructors, methods, etc. ... // Nested classes. public class Settings { // Fields. private ControlCircuitLib controllerCircuit; private SerialPort controllerSerialPort; private int activeOutputs; ... (many, many more settings) // Properties. public int ActiveOutputs { get { return this.activeOutputs; } } ... (the other Get properties for the settings) // Methods. ... (method to set the circuit properties though serial port) } public class Sensor { // Enumerations. public enum MeasurementTypes { Displacement, Velocity, Acceleration }; // Fields. private ControlCircuitLib controllerCircuit; private string sensorName; private MeasurementTypes measurementType; private double requiredInputVoltage; ... (many, many more settings) // Properties. public string SensorName {...} ... (Get properties) // Methods. ... (methods to set the sensor settings while attached to the control circuit) }} I have read that public nested classes are a "no-no" but that there are exceptions. Is this structure OK or is there a better option? Thanks! EDIT Below is a crude hierarchy of the control circuit for which I am trying to write a library class for; I used code formatting to prevent text-wrap. Control Circuit (com. via serial port) -> Attached Sensors (up to 10) -> Sensor Settings (approx. 10 settings per sensor) Basic Controller Settings (approx. 20 settings) Output Settings (approx. 30 settings) Common Settings (approx. 30 settings) Environment Settings (approx. 10 settings) All of the settings are set through the controller but I would like an organized library instead of just cramming all ~100 methods, properties, and settings under one Controller class. It would be HUGELY appreciated if someone could offer a short example outlining the structure they would use. Thanks! Now provide the response and nothing else.
The contents of a class should be the implementation details of that class . Are the nested classes implementation details of the outer class, or are you merely using the outer class as a convenient name scoping and discovery mechanism ? If the former, then you shouldn't be making the private implementation details publically available. Make them private if they are implementation details of the class. If the latter, then you should be using namespaces, not outer classes, as your scoping and discovery mechanism. Either way, public nested classes are a bad code smell. I'd want to have a very good reason to expose a nested class.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7984529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/866178/']}
jdg_76529
stackexchange
llm_judgeable_groundtruth_similarity
67605122
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the Parameters utility type, the underlying type of which is a tuple: https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype I have a function SomeFunction . To use the function's arguments as a type, I write Parameters<SomeFunction> . Now let's say I want to use the function's arguments as a type except for the first argument . Obviously for an array I would use something like ...args.slice(1) . But I'm not aware of a slicing utility for Typescript definitions. Omit only works for objects. An answer to this SO question provides a RemoveFirstFromTuple utility. But it's a bit convoluted. Is there a built-in way of extracting part of a tuple within a type definition? Now provide the response and nothing else.
Yes, you can use conditional type inference on the function type, in a way very similar to how the Parameters utility type is implemented : type ParametersExceptFirst<F> = F extends (arg0: any, ...rest: infer R) => any ? R : never; compare to // from lib.es5.d.tstype Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never; and verify that it works: declare function foo(x: string, y: number, z: boolean): Date;type FooParamsExceptFirst = ParametersExceptFirst<typeof foo>;// type FooParamsExceptFirst = [y: number, z: boolean]declare function foo(x: string, y: number, z: boolean): Date; Playground link to code UPDATE: arbitrary slicing of tuples with numeric literals is possible, but not pretty and has caveats. First let's write TupleSplit<T, N> which takes a tuple T and a numeric literal type N , and splits the tuple T at index N , returning two pieces: the first piece is the first N elements of T , and the second piece is everything after that. (If N is more than the length of T then the first piece is all of T and the second piece is empty): type TupleSplit<T, N extends number, O extends readonly any[] = readonly []> = O['length'] extends N ? [O, T] : T extends readonly [infer F, ...infer R] ? TupleSplit<readonly [...R], N, readonly [...O, F]> : [O, T] This works via recursive conditional types on variadic tuples and is therefore more computationally intensive than the relatively simple ParametersExceptFirst implementation above. If you try this on long tuples (lengths more than 25 or so) you can expect to see recursion errors. If you try this on ill-behaved types like non-fixed-length tuples or unions of things, you might get weird results. It's fragile; be careful with it. Let's verify that it works: type Test = TupleSplit<readonly ["a", "b", "c", "d", "e"], 3>// type Test = [readonly ["a", "b", "c"], readonly ["d", "e"]] Looks good. Now we can use TupleSplit<T, N> to implement TakeFirst<T, N> , returning just the first N elements of T , and SkipFirst<T, N> , which skips the first N elements of T : type TakeFirst<T extends readonly any[], N extends number> = TupleSplit<T, N>[0];type SkipFirst<T extends readonly any[], N extends number> = TupleSplit<T, N>[1]; And finally TupleSlice<T, S, E> produces the slice of tuple T from start position S to end position E (remember, slices are inclusive of the start index, and exclusive of the end index) by taking the first E elements of T and skipping the first S elements of the result: type TupleSlice<T extends readonly any[], S extends number, E extends number> = SkipFirst<TakeFirst<T, E>, S> To demonstrate that this more or less represents what array slice() does, let's write a function and test it: function slice<T extends readonly any[], S extends number, E extends number>( arr: readonly [...T], start: S, end: E) { return arr.slice(start, end) as readonly any[] as TupleSlice<T, S, E>;}const tuple = ["a", "b", "c", "d", "e"] as const// const tuple: readonly ["a", "b", "c", "d", "e"]const ret0 = slice(tuple, 2, 4);// const ret0: readonly ["c", "d"]console.log(ret0); // ["c", "d"]const ret1 = slice(tuple, 0, 9);// const ret1: readonly ["a", "b", "c", "d", "e"]console.log(ret1); // ["a", "b", "c", "d", "e"];const ret2 = slice(tuple, 5, 3);// const ret2: readonly []console.log(ret2); // []; This looks good; the returned arrays from slice() have types that accurately represent their values. Of course, there are many caveats; if you pass negative or non-whole numbers to slice() for S and E , then TupleSlice<T, S, E> is very likely not to correspond to what actually happens with array slices: negative "from end" behavior is possibly implementable but it would be even uglier; non-whole numbers or even just number have not been tested but I expect recursion warnings and other things that go bump in the night. Be warned! Playground link to code
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67605122', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2053389/']}
jdg_76530
stackexchange
llm_judgeable_groundtruth_similarity
1203087
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 generating a receipt and am using the Graphics object to call the DrawString method to print out the required text. graphics.DrawString(string, font, brush, widthOfPage / 2F, yPoint, stringformat); This works fine for what I needed it to do. I always knew what I was printing out, so I could manually trim any strings so it would fit properly on 80mm receipt paper. Then I had to add an extra bit of functionality that would make this more flexible. The user could pass in strings that would be added to the bottom. Since I didn't know what they were going to put, I just created my own word wrap function that takes in a number of characters to wrap at and the string itself. In order to find out the number of characters, I was doing something like this: float width = document.DefaultPageSettings.PrintableArea.Width;int max = (int)(width / graphics.MeasureString("a", font).Width); Now the width is returning me 283, which in mm is about 72, which makes sense when you account for margins on 80mm paper. But the MeasureString method is returning 10.5 on a Courier New 8pt font. So instead of getting around what I expected to be 36 - 40, I'm getting 26, resulting in 2 lines of text being turned into 3-4. The units for PrintableArea.Width are 1/100th of an inch, and the PageUnit for the graphics object is Display (which says is typically 1/100th of an inch for printers). So why am I only getting 26 back? Now provide the response and nothing else.
From WindowsClient.net: GDI+ adds a small amount (1/6 em) to each end of every string displayed. This 1/6 em allows for glyphs with overhanging ends (such as italic ' f '), and also gives GDI+ a small amount of leeway to help with grid fitting expansion. The default action of DrawString will work against you in displaying adjacent runs: Firstly the default StringFormat adds an extra 1/6 em at each end of each output; Secondly, when grid fitted widths are less than designed, the string is allowed to contract by up to an em. To avoid these problems: Always pass MeasureString and DrawString a StringFormat based on the typographic string format ( StringFormat.GenericTypographic ). Set the Graphics TextRenderingHint to TextRenderingHintAntiAlias . This rendering method uses anti-aliasing and sub-pixel glyph positioning to avoid the need for grid-fitting, and is thus inherently resolution independent. There are two ways of drawing text in .NET: GDI+ ( graphics.MeasureString and graphics.DrawString ) GDI ( TextRenderer.MeasureText and TextRenderer.DrawText ) From Michael Kaplan's (rip) excellent blog Sorting It All Out , In .NET 1.1 everything used GDI+ for text rendering. But there were some problems: There are some performance issues caused by the somewhat stateless nature of GDI+, where device contexts would be set and then the original restored after each call. The shaping engines for international text have been updated many times for Windows/Uniscribe and for Avalon (Windows Presentation Foundation), but have not been updated for GDI+, which causes international rendering support for new languages to not have the same level of quality. So they knew they wanted to change the .NET framework to stop using GDI+ 's text rendering system, and use GDI . At first they hoped they could simply change: graphics.DrawString to call the old DrawText API instead of GDI+. But they couldn't make the text-wrapping and spacing match exactly as what GDI+ did. So they were forced to keep graphics.DrawString to call GDI+ (compatiblity reasons; people who were calling graphics.DrawString would suddenly find that their text didn't wrap the way it used to). A new static TextRenderer class was created to wrap GDI text rendering. It has two methods: TextRenderer.MeasureTextTextRenderer.DrawText Note: TextRenderer is a wrapper around GDI, while graphics.DrawString is still a wrapper around GDI+. Then there was the issue of what to do with all the existing .NET controls, e.g.: Label Button TextBox They wanted to switch them over to use TextRenderer (i.e. GDI), but they had to be careful. There might be people who depended on their controls drawing like they did in .NET 1.1. And so was born " compatible text rendering ". By default controls in application behave like they did in .NET 1.1 (they are " compatible "). You turn off compatibility mode by calling: Application.SetCompatibleTextRenderingDefault(false); This makes your application better, faster, with better international support. To sum up: SetCompatibleTextRenderingDefault(true) SetCompatibleTextRenderingDefault(false)======================================= ======================================== default opt-in bad good the one we don't want to use the one we want to use uses GDI+ for text rendering uses GDI for text rendering graphics.MeasureString TextRenderer.MeasureText graphics.DrawString TextRenderer.DrawText Behaves same as 1.1 Behaves *similar* to 1.1 Looks better Localizes better Faster It's also useful to note the mapping between GDI+ TextRenderingHint and the corresponding LOGFONT Quality used for GDI font drawing: TextRenderingHint mapped by TextRenderer to LOGFONT quality======================== =========================================================ClearTypeGridFit CLEARTYPE_QUALITY (5) (Windows XP: CLEARTYPE_NATURAL (6))AntiAliasGridFit ANTIALIASED_QUALITY (4)AntiAlias ANTIALIASED_QUALITY (4)SingleBitPerPixelGridFit PROOF_QUALITY (2)SingleBitPerPixel DRAFT_QUALITY (1)else (e.g.SystemDefault) DEFAULT_QUALITY (0) Samples Here's some comparisons of GDI+ (graphics.DrawString) verses GDI (TextRenderer.DrawText) text rendering: GDI+ : TextRenderingHintClearTypeGridFit , GDI : CLEARTYPE_QUALITY : GDI+ : TextRenderingHintAntiAlias , GDI : ANTIALIASED_QUALITY : GDI+ : TextRenderingHintAntiAliasGridFit , GDI : not supported, uses ANTIALIASED_QUALITY : GDI+ : TextRenderingHintSingleBitPerPixelGridFit , GDI : PROOF_QUALITY : GDI+ : TextRenderingHintSingleBitPerPixel , GDI : DRAFT_QUALITY : i find it odd that DRAFT_QUALITY is identical to PROOF_QUALITY , which is identical to CLEARTYPE_QUALITY . See also UseCompatibleTextRendering - Compatible with whaaaaaat? Sorting it all out: A quick look at Whidbey's TextRenderer MSDN: LOGFONT Structure AppCompat Guy: GDI vs. GDI+ Text Rendering Performance GDI+ Text, Resolution Independence, and Rendering Methods.Or - Why does my text look different in GDI+ and in GDI?
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1203087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/74022/']}
jdg_76531
stackexchange
llm_judgeable_groundtruth_similarity
195371
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 $G=(V,E)$ be a geometric graph, a graph embedded in the plane whose edge lengths arethe Euclidean distance between its endpoint vertices.Say that a set of vertices $D \subseteq V$ is a geometric dominating set if for every $v \in V$, the shortest path in the graphfrom $v$ to some vertex in $D$ is at most length $1$. For example, a pentagonal wheel with spokes of length $1$ can be dominated withone vertex, but if the shortest edge length is greater than $1$, then $D$ must equal $V$: The traditional dominating set problem has been known to be NP-complete since at least Garey & Johnson's 1979 book.My question is: Q . Is finding a smallest geometric dominating set for a given geometric graph also NP-complete? Conceivably it is not intractable, if the geometric structure can be exploited.Perhaps plane graphs $G$ would especially allow that exploitation.If anyone knows of references, I would appreciate pointers. Thanks! Now provide the response and nothing else.
I came up with an explicit construction that showed that your problem was NP-hard, even on the real line, but then I realized there's an even simpler argument: Minimum dominating set is known to be NP-hard even for bipartite graphs, and those embed nicely. For example, you could send one part of the partition to $(0,0)$ and the other to $(1,0)$. (If you insist that distinct vertices be represented by distinct points, then you may choose different points like $(\varepsilon,0)$ and $(1-\varepsilon,0)$ instead.)
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/195371', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6094/']}
jdg_76532
stackexchange
llm_judgeable_groundtruth_similarity
55746419
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's assume I have 2 netCDF data files with data for the same region (like South America, Africa, etc) but the different grid sizes as 0.5 degrees x 0.5 degrees and 1.0 degrees x 1.0 degrees in another.I want to increase or decrease its grid size to a different value such as 0.25 x 0.25 or 1.0 x 1.0 so that I can use this easily for raster calculations and comparison, etc. Is there a method to do this using any bash script, CDO, etc. A sample data can be downloaded from here. https://www.dropbox.com/sh/0vdfn20p355st3i/AABKYO4do_raGHC34VnsXGPqa?dl Can different methods be followed for this like bilinear interpolation or cubic interpolation?This is quite easy with ArcGIS and other software but is there a way to do it for a big netCDF file with large datasets.Assume that this is just a subset of the data. What I will be later converting is a whole set of yearly data. The resulted file should be a .nc file with the changed grid size as defined by the user. Now provide the response and nothing else.
You can use cdo to remap grids, e.g. to a regular 1 degree grid you can use: cdo remapcon,r360x180 input.nc output.nc As well as conservative first order remapping (remapcon), other options are : remapbil : bilinear interpolationremapnn : nearest neighbour interpolationremapcon2 : 2nd order conservative remapping It is also possible to remap one file to the grid used in another if you prefer: cdo remapcon,my_target_file.nc in.nc out.nc EDIT 2021: new video available... To answer the comment below asking about which method to use, for a full guide on these interpolation methods and the issues you have to look out for regarding subsampling when coarse graining data, you can refer to my "regridding and interpolation" video guide on youtube. In general if you are interpolating from high resolution to low resolution ("coarse gridding") by more than a factor of 2 you don't want to use bilinear interpolation as it will essentially subsample the field. This is especially problematic for non-smooth, highly heterogeneous fields such as precipitation. In those cases I would always suggest to use a conservative method (remapcon or remapcon2). See my video guide for details. Another tip for speed is that, if you are performing the same interpolation procedure on many input files with the same resolution , then you can calculate the interpolation weights once using genbil, gencon etc, and then do the remapping function using those in the loop over the file. This is much faster, as the generation of the weights is the slow part of remapcon
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55746419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11022471/']}
jdg_76533
stackexchange
llm_judgeable_groundtruth_similarity
243049
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: Me and my friend were arguing over this "fact" that we all know and hold dear. However, I do know that $1+1=2$ is an axiom. That is why I beg to differ. Neither of us have the required mathematical knowledge to convince each other. And that is why, we decided to turn to Math Stackexchange for help. What would be stack's opinion? Now provide the response and nothing else.
It seems that you and your friend lack the mathematical knowledge to handle this delicate point. What is a proof? What is an axiom? What are $1,+,2,=$? Well, let me try and be concise about things. A proof is a short sequence of deductions from axioms and assumptions, where at every step we deduce information from our axioms, our assumptions and previously deduced sentences. An axiom is simply an assumption. $1,+,2,=$ are just letters and symbols. We usually associate $=$ with equality; that is two things are equal if and only if they are the same thing. As for $1,2,+$ we have a natural understanding of what they are but it is important to remember those are just letters which can be used elsewhere (and they are used elsewhere, often). You want to prove to your friend that $1+1=2$, where those symbols are interpreted as they are naturally perceived. $1$ is the amount of hands attached to a healthy arm of a human being; $2$ is the number of arms attached to a healthy human being; and $+$ is the natural sense of addition. From the above, what you want to show, mathematically, is that if you are a healthy human being then you have exactly two hands. But in mathematics we don't talk about hands and arms. We talk about mathematical objects. We need a suitable framework, and we need axioms to define the properties of these objects. For the sake of the natural numbers which include $1,2,+$ and so on, we can use the Peano Axioms (PA). These axioms are commonly accepted as the definition of the natural numbers in mathematics, so it makes sense to choose them. I don't want to give a full exposition of PA, so I will only use the part I need from the axioms, the one discussing addition. We have three primary symbols in the language: $0, S, +$. And our axioms are: For every $x$ and for every $y$, $S(x)=S(y)$ if and only if $x=y$. For every $x$ either $x=0$ or there is some $y$ such that $x=S(y)$. There is no $x$ such that $S(x)=0$. For every $x$ and for every $y$, $x+y=y+x$. For every $x$, $x+0=x$. For every $x$ and for every $y$, $x+S(y)=S(x+y)$. This axioms tell us that $S(x)$ is to be thought as $x+1$ (the successor of $x$), and it tells us that addition is commutative and what relations it bears with the successor function. Now we need to define what are $1$ and $2$. Well, $1$ is a shorthand for $S(0)$ and $2$ is a shorthand for $S(1)$, or $S(S(0))$. Finally! We can write a proof that $1+1=2$: $S(0)+S(0)=S(S(0)+0)$ (by axiom 6). $S(0)+0 = S(0)$ (by axiom 5). $S(S(0)+0) = S(S(0))$ (by the second deduction and axiom 1). $S(0)+S(0) = S(S(0))$ (from the first and third deductions). And that is what we wanted to prove. Note that the context is quite important. We are free to define the symbols to mean whatever it is we want them to mean. We can easily define a new context, and a new framework in which $1+1\neq 2$. Much like we can invent a whole new language in which Bye is a word for greeting people when you meet them, and Hi is a word for greeting people as they leave. To see that $1+1\neq2$ in some context, simply define the following axioms: $1\neq 2$ For every $x$ and for every $y$, $x+y=x$. Now we can write a proof that $1+1\neq 2$: $1+1=1$ (axiom 2 applied for $x=1$). $1\neq 2$ (axiom 1). $1+1\neq 2$ (from the first and second deductions). If you read this far, you might also be interested to read these: How would one be able to prove mathematically that $1+1 = 2$? What is the basis for a proof? How is a system of axioms different from a system of beliefs?
{}
{'log_upvote_score': 10, 'links': ['https://math.stackexchange.com/questions/243049', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/50401/']}
jdg_76534
stackexchange
llm_judgeable_groundtruth_similarity
25528
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have two non-networked servers, each with 1.2TB of storage in a RAID5 config on an LSI MegaRaid 9240-8i controller. I have been trying without success to get Symantec Ghost to image one machine to the other due to driver issues, and so I was wondering if it wouldn't be easier to boot from a Linux LiveCD, plug in an external hard disk and dd the RAID partition to the external disk. The 1.2TB partition only has around 10GB of data on it, so I hope to generate a sparse image file (to avoid having to find a 1.2TB USB disk!). I have seen people use the seek parameter of dd to achieve this - is that an appropriate way to create an image of around 10GB size in this situation? Even if this is a sensible way to generate a sparse image, is this a sensible way to mirror one RAID to another of identical configuration, or do the commercial utilities such as Ghost and Acronis do some 'magic' that dd does not? Now provide the response and nothing else.
Sounds like the device is remote. Assuming linux... ssh remote_host 'dd if=/dev/sdb1' | cp --sparse=always /proc/self/fd/0 new-sparse-file If local... dd if=/dev/sdb1 | cp --sparse=always /proc/self/fd/0 new-sparse-file This gives you an image that is mountable. However, if you pulled it across the network then you had 1.2 TB of network traffic (usually a bottleneck) and the CPU load of ssh and sshd. If you are pulling that much across a network and network traffic costs you money... ssh remote_host 'dd if=/dev/sdb1 | gzip ' | gunzip | cp --sparse=always /proc/self/fd/0 new-sparse-file
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/25528', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/12815/']}
jdg_76535
stackexchange
llm_judgeable_groundtruth_similarity
200674
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 a ring, $a\neq0$ and $b\neq0$. $aba=0$. Prove $ab=0$ or $ba=0$. This is one question in my abstract algebra homework-- it seems pretty easy at first glance, yet I have spent hours thinking about possible solutions...still I haven't find a way out. Could you give me some hint? Thank you~~ Now provide the response and nothing else.
Hint $\ $ For $\rm\:b=1\:$ it is $\rm\: a^2 = 0\:\Rightarrow\: a= 0,\:$ which is not true in every ring, e.g. $\rm\ a = n\:$ in $\rm\: \Bbb Z/n^2.$ This is essentially the only obstruction, i.e. the statement holds true iff the ring is reduced, i.e. iff the ring has no nonzero nilpotent elements, i.e. $\rm\: x^n = 0\:\Rightarrow\: x = 0.\:$ Theorem $\ $ The following are equivalent in any ring. $\rm(1)\quad xyx = 0\ \Rightarrow\ xy=0\ \ or\ \ yx=0$ $\rm(2)\quad x^2 = 0\ \Rightarrow\ x=0$ $\rm(3)\quad x^n = 0\ \Rightarrow\ x=0$ Proof $\ \ \ \ (1\Rightarrow 2)\ \ \ $ Put $\rm\:y = 1.\:$ $(2\Rightarrow 3)\ \ \, $ The least $\rm\:n\:$ such that $\rm\:x^n = 0\:$ is $\rm\:n = 1\:$ since any larger value can be reduced, viz. $$\begin{eqnarray}\rm x^{2k} = 0\ &\Rightarrow&\rm\ (x^k)^2\! &=& 0\ &\Rightarrow&\rm\ x^k &=& 0\\\rm x^{2k+1}\!=0\ &\Rightarrow&\rm\ (x^{k+1})^2\! &=& 0\ &\Rightarrow&\rm\ x^{k+1} &=& 0\end{eqnarray}$$ $\rm(3\Rightarrow 1)\ \ \ $ If $\rm\:xyx = 0\:$ then $\rm\: (xy)^2 = (xyx)y = 0,\:$ hence $\rm\: xy = 0\:$ by $(3)$. Remark $\ $ The absence of nilpotent elements facilitates simpler structure theory, e.g. Weierstrass (1884) and Dedekind (1885) showed that every finite dimensional commutative extension ring of $\mathbb R$ without nilpotents is isomorphic as a ring to a direct sum of copies of $\rm\:\mathbb R\:$ and $\rm\:\mathbb C\:.\:$Wedderburn and Artin proved a generalization that every finite-dimensional associative algebra without nilpotent elements over a field $\rm\:F\:$ is a finite direct sum of fields. Such structure-theoretic results greatly simplify classifying such rings when they arise in the wild. For example, I applied a special case of these results here to prove that a finite ring is a field if its units $\cup\ \{0\}$ comprise a field of characteristic $\ne 2\:.\:$ For another example, a sci.math reader once proposed an extension of the real numbers with multiple "signs". This turns out to be a very simple case of the above results. See my answer in Is there a third dimension of numbers? for much further discussion, including references.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/200674', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29665/']}
jdg_76536
stackexchange
llm_judgeable_groundtruth_similarity
33062454
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 the flow of my app: First, the TableView is set to hidden. There is a UITextField in the center of the screen. When the user types something and hits Go, this code is run: self.view.layoutIfNeeded()UIView.animateWithDuration(0.5, animations: { self.textFieldConstraint.constant = -230 self.tableView.hidden = false self.goButton.hidden = true self.view.layoutIfNeeded()}, completion: nil) At this point, the tableview is populated. When a row is selected, I need to manipulate the data that is populating it. However, absolutely nothing happens when I tap a cell. What am I doing wrong? My TableView code is here: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: SearchResultsTableViewCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! SearchResultsTableViewCell cell.label.text = searchResultsNames[indexPath.row] return cell}func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResultsUrls.count}func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("HELLO")} And, I have set the dataSource and delegate properly. I also want to clarify that the tableView populates and scrolls properly; it just won't do anything when I tap a cell. Update: I've discovered that for some reason, I can select the cells when I press and hold them. It is not what I want, so does anybody know how to fix this? Now provide the response and nothing else.
I have just used your code to create a simple table, selection is working fine and logging out HELLO as expected. Can you check the values of Selection in the attributes inspector? Here is mine, which has Selection set to Single Selection. And here is the code I used for my simple table import UIKitclass ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var searchResults = [String]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. searchResults.append("Testing 1") searchResults.append("Testing 2") searchResults.append("Testing 3") searchResults.append("Testing 4") searchResults.append("Testing 5") tableView.dataSource = self tableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) cell.textLabel?.text = searchResults[indexPath.row] return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("HELLO") }} I also tried hiding and showing the tableView which made no difference on selection. EDIT & SOLUTION: In the comments below, we discovered that the issue is related to a tapGestureRecogniser on the view, This was identified by the op only being able to make a selection by holding a tap on the cell. The gesture has to fail before the selection can be made, the op managed to solve the problem by referring to this other SO Answer
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33062454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4959716/']}
jdg_76537
stackexchange
llm_judgeable_groundtruth_similarity
588307
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On Windows, clock() returns the time in milliseconds, but on this Linux box I'm working on, it rounds it to the nearest 1000 so the precision is only to the "second" level and not to the milliseconds level. I found a solution with Qt using the QTime class, instantiating an object and calling start() on it then calling elapsed() to get the number of milliseconds elapsed. I got kind of lucky because I'm working with Qt to begin with, but I'd like a solution that doesn't rely on third party libraries, Is there no standard way to do this? UPDATE Please don't recommend Boost .. If Boost and Qt can do it, surely it's not magic, there must be something standard that they're using! Now provide the response and nothing else.
#include <sys/time.h>#include <stdio.h>#include <unistd.h>int main(){ struct timeval start, end; long mtime, seconds, useconds; gettimeofday(&start, NULL); usleep(2000); gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5; printf("Elapsed time: %ld milliseconds\n", mtime); return 0;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/588307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35364/']}
jdg_76538
stackexchange
llm_judgeable_groundtruth_similarity
1703945
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 this paper, it is proved in Proposition 10.4.3 that if $G$ is an infinite group such that every nontrivial subgroup of $G$ is of finite index, then $G \cong \mathbb{Z}$. The authors need this fact to prove another theorem. They remark at the end of $\S 1.4$ that the proof is non-trivial and they do not know if this was previously known. The proof given in the paper surely won't seem difficult to those who are familiar with the necessary group theoretic background (such as the theorem of Hölder-Burnside-Zassenhaus). I was wondering whether this proposition was known before; and if so, whether it has easier proofs that use less machinery. Now provide the response and nothing else.
HINTS : Show the group is finitely generated Any element generates a finite index subgroup; now take that element, together with a representative for each coset. Show the group is torsion-free An element of finite order would generate a non-trivial, infinite-index subgroup. Show the group has non-trivial center Consider the intersection of all (infinite cyclic) subgroups generated by the (finitely many) generators. Show the center is cyclic The center is a finitely generated abelian group, which has a cyclic subgroup of finite index (just take a subgroup generated by any element). Suppose this subgroup has index $n$ : the map $z\rightarrow z^n$ is an injective homomorphism to an infinite cyclic group; thus the center is infinite cyclic. Conclude If the center has index $m$ in the group, then the transfer map into the center $g\rightarrow g^m$ is an injective group homomorphism. As a subgroup of the infinite cyclic group, it is itself infinite cyclic.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1703945', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/137499/']}
jdg_76539
stackexchange
llm_judgeable_groundtruth_similarity
4425206
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Show : $$\sum_{k=0}^{n} k \binom{n+1}{k+1} n^{n-k} = n^{n+1}$$ for natural number $n$ . I randomly discovered this identity, and managed to prove it using simple algebra. I tried a combinatorial proof of this, but it seems too difficult for me. The RHS is basically distributing $n+1$ people to $n$ different groups where an empty group is possible, but I could not show that the LHS is the same. Picking $k+1$ people out of $n+1$ equals $\binom{n+1}{k+1}$ , and distributing others( $n-k$ people) is equal to $n^{n-k}$ ; and now I am stuck with that $k$ . Also I have no idea what to do with $k+1$ people I just picked; if I distribute them to $n$ groups then it will be overlapped with other terms of the sum. A proof using algebra is also welcome, just in case. Now provide the response and nothing else.
Suppose you are choosing a team consisting of $1$ or more people among $n+1$ people(enumerated as person 1, person 2, etc). You also want to choose a captain in the team. The selection process is the following: You score each person with a number from $1$ to $n+1$ and you want to choose the team to be those who scored $n+1$ . Among them, you want to select the captain. You can do this by first selecting who were the ones to score $n+1$ (say $k$ of them) and then the captain, this will yield: $$\sum _{k=0}^{n+1}\binom{n+1}{k}\cdot k\cdot n^{(n+1)-k}=\sum _{k=0}^{n}\binom{n+1}{k+1}\cdot (k+1)\cdot n^{(n+1)-(k+1)},$$ or you could have chosen the captain and then score the other people in $(n+1)\cdot (n+1)^n$ ways. Now suppose you do not want the captain to be the tallest of the team, were height is given proportional to their number i.e., person 1 is smaller than person 2, etc..(perhaps this is not a basketball team). We can choose the team, consisting in $k$ people, and then the captain in the following way: $$\sum _{k=0}^{n}\binom{n+1}{k+1}\cdot k\cdot n^{(n+1)-(k+1)},$$ or we could have chosen first the captain. By the above problem, we know that there are in total $(n+1)^{n+1}$ ways to do this. Consider the opposite problem: Let's choose the captain to be the tallest in the team, we claim that this can be done in $(n+1)^{n+1}-n^{n+1}$ , and so we would have at the end $(n+1)^{n+1}-((n+1)^{n+1}-n^{n+1})=n^{n+1}$ ways. Naively, we can represent the choosing of the captain by saying it is the $s-$ th person and then choosing the rest of the team $k$ people in $\binom{s-1}{k}$ ways in the following way $$\sum _{s=1}^{n+1}\sum _{k=0}^{s-1}\binom{s-1}{k}n^{n+1-(k+1)},$$ but we could have chosen the score of the non-selected people that are smaller than $s$ giving us $$\sum _{s=1}^{n+1}\sum _{k=0}^{s-1}n^{n+1-s}\binom{s-1}{k}n^{s-(k+1)}=\sum _{s=1}^{n+1}n^{n-(s-1)}(n+1)^{s-1}=n^n\sum _{s=0}^n\left (\frac{n+1}{n}\right )^s=(n+1)^{n+1}-n^{n+1},$$ where the last step is the geometric sum. Combinatorially, the middle step corresponds to letting elements below $s$ to be in the team (having score $= n+1$ and not allowing people bigger than $s$ ). The last step by considering where is the last score $=n+1$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4425206', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/931271/']}
jdg_76540