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 | 27769013 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi I am quite new to Rails and am just setting up comments for my Shop_Profile model. I am using the acts_as_commentable gem to allow for polymorphic comments. I am allowing comments on the profile Show page so am displaying the list of comments and the new comment form on the same page. My Show Action in the ShopProfilesController looks like this: def show @comments = @shop_profile.comments @comment = @shop_profile.comments.new end And I am rendering the comment form and comments in the show view with: <% if user_signed_in? %> <%= render 'comments/form' %><% end %><%= render @comments %> My Create action on my comment controller is: def create @comment = @user.comments.build(comment_params) @commentable = Comment.find_commentable(params[:comment][:commentable_type], params[:comment][:commentable_id]) if @comment.save redirect_to @commentable end end and my _comment partial is: <p> <strong>Title:</strong> <%= comment.title %></p><p> <strong>Comment:</strong> <%= comment.comment %></p><p> <small>By:</small> <%= comment.user.username %></p> The new @comment for the form keeps getting included in the @comments and is thus causing an error "undefined method `username' for nil:NilClass" because the new @commentn has no user_id .How can I display my @comments without including this new @comment for the form_for? Thanks for any help
Now provide the response and nothing else.
| Assuming you are starting your instance in a VPC public subnet (i.e. a subnet that has a routing table incl. a rule to send traffic to 0.0.0.0/0 to the Internet Gateway), just define AssociatePublicIpAddress property in the NetworkInterfaces group of your EC2 resource: "NetworkInterfaces" : [{ "AssociatePublicIpAddress" : "True", "DeleteOnTermination" : "True", "SubnetId" : { "Ref" : "PublicSubnet" }, "DeviceIndex" : "0", "GroupSet" : [ { "Ref" : "SecurityGroup" } ] }], See documentation at http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html If you are starting your instance in EC2 Classic networking (non VPC), it will receive a public IP address automatically. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27769013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3869486/']} | jdg_82141 |
stackexchange | llm_judgeable_groundtruth_similarity | 18646920 |
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 radio group, a button and a boolean value. When the button is clicked, if the boolean is true, check one radio button and if it false, check the other. Not sure how to set up binding for something like that. Edit The situation is a little more complicated it turns out. The flow goes like this: Presented with 2 buttons one to Buy Now one to Buy in Installments Presented with an upsell If you clicked buy now, add an "addon" sku to the order items hash If you clicked buy in installments add an "addon_plan" sku to the items hash So the different states of the hash look like: //base offer onlyorder.items = {base_offer: 1}//base offer with payment planorder.items = {base_offer_plan: 1}//accessory kit only if base_offer_plan was not selectedorder.items = {accessory_kit: 1}//accessory kit with plan if user first chose base_offer_planorder.items = {accessory_kit_plan: 1}
Now provide the response and nothing else.
| I ran into this problem, and it was quite confusing. The problem appears to be that calling a resource action doesn't actually return an http promise, but an empty reference (that is populated when the data returns from the server -see the return value section of the $resource docs ). I'm not sure why this results in .then(result) returning an array of unresolved promises, but to get each resource's promise, you need to use resource1.query().$promise . To re-write your example: $scope.init = function() { return $q.all([resource1.query().$promise, resource2.query().$promise, resource3.query().$promise]) .then( function(result) { $scope.data1 = result[0]; $scope.data2 = result[1]; $scope.data3 = result[2]; console.log($scope.data1); doSomething($scope.data1,$scope.data2); })} I hope that saves someone else some time. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18646920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234867/']} | jdg_82142 |
stackexchange | llm_judgeable_groundtruth_similarity | 478344 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the result of the next limit: $$ \lim_{n \to \infty} \frac{ \sum^n_{i=1} i^k}{n^{k+1}},\ k \in \mathbb{R} $$ Why (theorem)?
Now provide the response and nothing else.
| You can apply Lemma Stolz-Cesaro :$$ \lim_{n \to \infty} \frac{ \sum^n_{i=1} i^k}{n^{k+1}}= \lim_{n \to \infty} \frac{ (n+1)^k}{(n+1)^{k+1}-n^{k+1}}=\frac{1}{k+1}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/478344', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91781/']} | jdg_82143 |
stackexchange | llm_judgeable_groundtruth_similarity | 4437358 |
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 eclipse java ee to perform java programming. I had the following line of code in one of my functions: Long result = -1; I got the following error: Type mismatch: cannot convert from int to Long I can't quite understand why when i add a number to the variable it provides this error. How can this issue be resolved and why did it happen in the first place?
Now provide the response and nothing else.
| There is no conversion between the object Long and int so you need to make it from long . Adding a L makes the integer -1 into a long ( -1L ): Long result = -1L; However there is a conversion from int a long so this works: long result = -1; Therefore you can write like this aswell: Long result = (long) -1; Converting from a primitive ( int , long etc) to a Wrapper object ( Integer , Long etc) is called autoboxing, read more here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4437358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80932/']} | jdg_82144 |
stackexchange | llm_judgeable_groundtruth_similarity | 29898269 |
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 write a R data frame to Excel and want to add additional cells/columns that have Excel formulas and/or data validation values (e.g. using the Data/Validation menu in Excel to provide drop-down lists of allowable values for a cell) I've looked at the R packages: xlsx, XLConnect and openxlsx. These are great for writing cells but not formulas or data validation settings . I'm currently thinking that I have to resort to post-processing the xlsx files using either AppleScript (on Mac) or a VBA solution. I'd like to do it all in R if possible so the logic doesn't have to be split across programs. Of the two: writing the data validation settings for a cell (vs. writing Excel formulas) is more important. The use case is writing a R data frame to Excel and including empty columns for making corrections. For the empty columns, I want to have drop-down lists of the acceptable values (e.g. "Yes"/"No") for that column. Thanks in advance.
Now provide the response and nothing else.
| The example below shows how to add drop-down lists to Excel cells. # Librarieslibrary(openxlsx)# Create workbookwb = createWorkbook()# Add worksheet "Customers" to the workbookaddWorksheet(wb, "Customers")# Create Customers dataframecustomers_df = data.frame("Name" = c("Alex", "Kate", "Mary"), "Gender" = c("male", "female", "female"))# Add Customers dataframe to the sheet "Customers"writeData(wb, sheet = "Customers", x = customers_df, startCol = 1)# Add worksheet "Drop-down values" to the workbookaddWorksheet(wb, "Drop-down values")# Create drop-down values dataframegender_values_df = data.frame("Gender" = c("male", "female"))# Add drop-down values dataframe to the sheet "Drop-down values"writeData(wb, sheet = "Drop-down values", x = gender_values_df, startCol = 1)# Add drop-downs to the column Gender on the worksheet "Customers"dataValidation(wb, "Customers", col = 2, rows = 2:4, type = "list", value = "'Drop-down values'!$A$2:$A$3")# Save workbooksaveWorkbook(wb, "D:/Customers.xlsx", overwrite = TRUE) More information can be found here: dataValidation | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29898269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3420621/']} | jdg_82145 |
stackexchange | llm_judgeable_groundtruth_similarity | 197441 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a list, l1 = {{a, b, 3, c}, {e, f, 5, k}, {n, k, 12, m}, {s, t, 1, y}} and want to apply differences on the third parts and keep the parts right of the numerals collected. My result should be l2 = {{2, c, k}, {7, k, m}, {-11, m, y}} I tried Map and MapAt, but I could not get anywhere. I could work around split things up and connect again. But is there a better way to do it?
Now provide the response and nothing else.
| Perhaps this?: l1 = {{a, b, 3, c}, {e, f, 5, k}, {n, k, 12, m}, {s, t, 1, y}};l2 = Differences[l1[[All, 3 ;;]]] /. b_ - a_ :> Sequence[a, b](* {{2, c, k}, {7, k, m}, {-11, m, y}} *) It assumes the letter symbols are simple and not complicated expressions. This is more complicated, but more robust: Flatten /@ Transpose@ MapAt[Differences, Partition[Transpose@l1[[All, 3 ;;]], {1, 2}, {1, 1}], {1, All, 1}] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/197441', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/57467/']} | jdg_82146 |
stackexchange | llm_judgeable_groundtruth_similarity | 1786 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a hash function over sets H(.) and a relation R(.,.) such that if A is included in B then R(H(A), H(B)). Of course, R(.,.) must be easy to verify (constant time), and H(A) should be computed in linear time. One example of H and R is: $H(A) = \bigvee_{x\in A} 1 << (h(x) \mod k)$, where k is a fixed integer and h(x) a hash function over integers. R(H(A), H(B)) = ((H(A) & H(B)) == H(A)) Are there any other good examples? (good is hard to define but intuitively if R(H(A), H(B)) then whp A is included in B). Later edit : I'm looking for a family of hash functions. I have many sets; 3 - 8 elements in each set; 90% of them have 3 or 4 elements. The example hash function I gave is not very well distributed for this case. The number of bits of H(.) (in my example, k) which should be small (ie. H(.) must fit in an integer or long). One nice property of R is that if H(.) has k bits then R(.,.) is true for (3^k - 2^k) / 4^k pairs, ie. for very few pairs. Bloom filters are especially good for large sets. I tried using BF for this problem, but the optimum results were with only one function. (crosspost from stackoverflow , I didn't receive an answer good enough)
Now provide the response and nothing else.
| (This answer was originally in comments but I'm moving it to a separate answer at Suresh's suggestion.) For your application with very small sets you probably want the number of Bloom hash functions $k$ to be quite large to minimize the number of false positives. To save computation time I suggest the following variation of a Bloom filter. Assume you have three traditional hash functions $h_1$, $h_2$, $h_3$ for the elements that each produce $m$-bit strings. Hash each element to the bitwise and of these three hash functions. The resulting element hashes will be about $2^{-3}=1/8^{th}$ ones. Hash each set to the bitwise or of the hashes of its constituent elements. Because your sets have 3-8 elements the resulting hashes will be in the neighborhood of one-half ones, which is presumably what you want to best keep the false positive rate down. The difference between the above scheme are the traditional Bloom filter is analogous to the difference between the classic $G_{n,p}$ Erdos random graph model and random $d$-regular graphs. The above scheme has the effective number $k$ of Bloom hashes vary a bit around its mean of $m/8$ but $m/8$ is pretty large so this difference shouldn't matter. | {} | {'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/1786', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/10/']} | jdg_82147 |
stackexchange | llm_judgeable_groundtruth_similarity | 8287769 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Spatialite has a the ability to calculate the distance between 2 geometries with it's Distance() function. There are other functions that work on LINESTRINGs. However I can't find out what units it returns it in. Is it metres? If I have 2 points, how do I calculate the distance between them in a spatialite query? (For the record I'm using SRID 4326, i.e. WSG 86, i.e. the old traditional degrees of latitude and longitude).
Now provide the response and nothing else.
| the unit returned by ST_Distance(), ST_Length() and ST_Area() exactly is the one defined by the corresponding SRID. consequently, if you are using latitude and longitude (SRID=4326, WGS 84), any length will be measured in DEGREES, and any area in SQUARE DEGREES. if you are interested in giving a more conventionalunit (METERS, SQUARE METERS), you simply have to projectyour geometries into some appropriate 'planar' CRS (e.g. UTM)using ST_Transform() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8287769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/161922/']} | jdg_82148 |
stackexchange | llm_judgeable_groundtruth_similarity | 7447705 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using MVC 3 with Forms Authentication. On my controller or methods, I am doing the following: [Authorize (Roles = "developer")] In this situation, I want to check if the user is logged in and if not, return them to the login page. However, if the 'IsInRole' check for that user returns false, I want them to go to a different view that says something like 'Not authorized'. What is the best way to accomplish something like this? I was hoping to avoid creating a new Authorization attribute so I didn't have to refactor every Authorize attribute in my entire application, but if that is what is required, I will go that route.
Now provide the response and nothing else.
| A custom authorize attribute overriding the HandleUnauthorizedRequest method could do the job: public class MyAuthorizeAttribute : AuthorizeAttribute{ protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { // The user is not authenticated base.HandleUnauthorizedRequest(filterContext); } else if (!this.Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole)) { // The user is not in any of the listed roles => // show the unauthorized view filterContext.Result = new ViewResult { ViewName = "~/Views/Shared/Unauthorized.cshtml" }; } else { base.HandleUnauthorizedRequest(filterContext); } }} and then: [MyAuthorize(Roles = "developer")]public ActionResult Develop(){ ...} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7447705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/214048/']} | jdg_82149 |
stackexchange | llm_judgeable_groundtruth_similarity | 1768005 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to perform a circular left shift of a 64-bit integer in JavaScript. However: JavaScript numbers are doubles JavaScript converts them to 32-bit signed ints when you start with the << and the >> and the >>> and the ~ and all of the bit-twiddling business. And then it's back to doubles when you're done. I think. I don't want the sign. And I definitely don't want the decimal bits. But I definitely do want 64 bits. So, how do I perform a bitwise left rotation of a 64-bit value?
Now provide the response and nothing else.
| Keep your 64-bit number as separate high and low partitions. To rotate left N when N < 32: hi_rot = ((hi << N) | (lo >>> (32-N))) & (0xFFFFFFFF) lo_rot = ((lo << N) | (hi >>> (32-N))) & (0xFFFFFFFF) If N >= 32, then subtract 32 from N, swap hi and lo, and then do the above. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1768005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33775/']} | jdg_82150 |
stackexchange | llm_judgeable_groundtruth_similarity | 7537701 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to prevent a WebView from caching data in /data/data/???/cache/webViewCache? I've set the following on the WebSettings but the cache folder is still used: webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);webSettings.setAppCacheEnabled(false); I've noticed that the cache files are deleted on application exit or when the application goes into the background but I'd prefer for them not to be created at all. Furthermore I'd like to prevent the use of the webview.db & webviewCache.db found in /data/data/???/database. I currently delete the databases like so: context.deleteDatabase("webview.db");context.deleteDatabase("webviewCache.db"); This appears to have the desired effect and the files don't appear to be recreated again for use. Is it safe to assume this is the case?
Now provide the response and nothing else.
| The notes on this page lead me to believe they don't want you to have fine access to the cache: http://developer.android.com/reference/android/webkit/CacheManager.html As far as I can tell, there are (at least) two ways around keeping cache. I haven't written any of this in an app, so no guarantees: (1) Every time your WebView finishes a page, clear the cache. Something like this in your WebViewClient: @Overridepublic void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); view.clearCache(true);} (2) If you don't care too much what is stored, but just want the latest content, you might be able to achieve this by setting the right http headers on loadUrl (obviously you'd want to test this against your server). Also, this is only available for Android API 8+ Map<String, String> noCacheHeaders = new HashMap<String, String>(2); noCacheHeaders.put("Pragma", "no-cache"); noCacheHeaders.put("Cache-Control", "no-cache"); view.loadUrl(url, noCacheHeaders); Maybe you tried this, but maybe also set the WebView Cache size to something small. I'm not sure if 0 will work, so maybe 1: wv.getSettings().setAppCacheMaxSize(1); Good Luck! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7537701', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/406920/']} | jdg_82151 |
stackexchange | llm_judgeable_groundtruth_similarity | 103 |
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Assume that we have a set of elements E and a similarity ( not distance ) function sim(ei, ej) between two elements ei,ej ∈ E . How could we (efficiently) cluster the elements of E , using sim ? k -means, for example, requires a given k , Canopy Clustering requires two threshold values. What if we don't want such predefined parameters? Note, that sim is not neccessarily a metric (i.e. the triangle inequality may, or may not hold). Moreover, it doesn't matter if the clusters are disjoint (partitions of E ).
Now provide the response and nothing else.
| I think a number of clustering algorithms that normally use a metric, do not actually rely on the metric properties (other than commutativity, but I think you'd have that here). For example, DBSCAN uses epsilon-neighborhoods around a point; there is nothing in there that specifically says the triangle inequality matters. So you can probably use DBSCAN, although you may have to do some kind of nonstandard spatial index to do efficient lookups in your case. Your version of epsilon-neighborhood will likely be sim > 1/epsilon rather than the other way around. Same story with k-means and related algorithms. Can you construct a metric from your similarity? One possibility: dist(ei, ej) = min( sim(ei, ek) + sim(ek, ej) ) for all k ... Alternately, can you provide an upper bound such that sim(ei, ej) < sim(ei, ek) + sim(ek, ej) + d, for all k and some positive constant d? Intuitively, large sim values means closer together: is 1/sim metric-like? What about 1/(sim + constant)? What about min( 1/sim(ei, ek) + 1/sim(ek, ej) ) for all k? (that last is guaranteed to be a metric, btw) An alternate construction of a metric is to do an embedding. As a first step, you can try to map your points ei -> xi, such that xi minimize sum( abs( sim(ei, ej) - f( dist(xi, xj) ) ), for some suitable function f and metric dist. The function f converts distance in the embedding to a similarity-like value; you'd have to experiment a bit, but 1/dist or exp^-dist are good starting points. You'd also have to experiment on the best dimension for xi. From there, you can use conventional clustering on xi. The idea here is that you can almost (in a best fit sense) convert your distances in the embedding to similarity values, so they would cluster correctly. On the use of predefined parameters, all algorithms have some tuning. DBSCAN can find the number of clusters, but you still need to give it some parameters. In general, tuning requires multiple runs of the algorithm with different values for the tunable parameters, together with some function that evaluates goodness-of-clustering (either calculated separately, provided by the clustering algorithm itself, or just eyeballed :) If the character of your data doesn't change, you can tune once and then use those fixed parameters; if it changes then you have to tune for each run. You can find that out by tuning for each run and then comparing how well the parameters from one run work on another, compared to the parameters specifically tuned for that. | {} | {'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/103', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/113/']} | jdg_82152 |
stackexchange | llm_judgeable_groundtruth_similarity | 65538 |
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'm connecting a PIC18F46K22 (master) to a PIC18F4620 (slave) using I 2 C. The wire between the devices is ~30cm. I'm using 400kHz without slew rate control. Later on, I'll add another 18F4620 on ~5cm from the master (~35cm from the other slave). How do I calculate the pull-up resistance needed on both the SCL as the SDA line? Does it matter where I place the pull-up (near the master, near the slave, both, in the middle, ...)?
Now provide the response and nothing else.
| The pull-ups are generally located near the master device. This app note goes into some of the calculations. Essentially, the size of the pull-up will be defined by the total bus capacitance and the pull-down capabilities of the devices on the bus: \$ R_p \ge \dfrac{V_{dd}-V_{OL}}{I_{OL}}\$ and \$ R_p \le \dfrac{300ns}{0.847298 \times C_{bus}}\$ where \$V_{OL}\$ is the logic low voltage needed, \$I_{OL}\$ is the sinking current, and \$C_{bus}\$ is the bus capacitance. Of course, once your sample is built, the best thing to do is scope the waveforms and make whatever adjustments are needed. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/65538', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/-1/']} | jdg_82153 |
stackexchange | llm_judgeable_groundtruth_similarity | 425275 |
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 not sure if this is the correct forum to ask, but here goes... My employer decided to install a SAN. For various irrelevant reasons, this never actually happened. But I did some research to find out what a "SAN" is, and... I'm baffled. It looks like such an absurdly bad idea that I can only conclude that I've misunderstood how it works. As best as I can tell, SAN stands for Storage Area Network, and it basically means that you connect your servers to your disks using an ordinary IP network. I am utterly stunned that any sane person would think this is a good idea. So I have my server connected to its disks with an Ultra-320 SCSI link. That's 320 MB/s of bandwidth shared between all the disks on that server. And then I rip them off the SCSI link and plug them into a 100 Mbit/s Ethernet network with its piffling 12.5 MB/s of theoretical bandwidth. That's before you take into account any routing delays, IP overhead, and perhaps packet collisions. (The latter can usually be avoided.) 320 MB/s verses 12.5 MB/s. That's, let me see, roughly 25x slower. On paper. Before we add IP overhead. (Presumably SCSI has its own command overheads, but I'm guessing a SAN probably just tunnels SCSI commands over IP, rather than implementing a completely new disk protocol over IP.) Now, with each server having a dedicated SCSI link, that means every time I add another server, I'm adding more bandwidth (and more disks). But with a shared SAN, every time I add a server I'm taking bandwidth away from the existing servers. The thing now gets slower as I add more hardware, not faster . Additionally, SAN technology is apparently extremely expensive. And it seems reasonable to presume that setting up an entire IP network is vastly more complicated than just plugging a few drives into a cable. So, these are the drawbacks of using a SAN - massively increased cost, massively decreased performance, loss of scaling, increased complexity, and more possible points for the system to fail at. So what are the advantages? The one I keep hearing is that it makes it easier to add disks, or to move a disk from one server to another. Which sounds logical enough - presumably with a SAN you just gotta push a few buttons and the drive now belongs to a different server. That's a heck of a lot simpler than physically moving the drive (depending on exactly how your drives are connected). On the other hand, in 10 years of working here, I have needed to change disks... let me count... twice. So it's an event that happens roughly once every 5 years. So you're telling me that once every 5 years, the SAN is going to save me 5 minutes of work? And every second of every day it's going to make stuff 25x slower? And this is a good tradeoff? I guess if I was in charge of some huge datacenter with thousands of servers, keeping track of that much disk might be difficult, and having a SAN might make sense. Heck, if the servers are all virtualised, they'll all be as slow as hell anyway, so maybe the SAN won't even matter. However, this does not match my situation at all. I have two servers with three disks each. It's not as if managing all that stuff is "difficult". In short, no matter which way I look at this, it looks extremely stupid. In fact, it looks so obviously stupid that nobody would spend time on R&D making something so stupid. As I said above, this can only mean that I'm misunderstanding something somewhere - because nobody would do something this dumb. Can anyone explain to me what I'm not seeing here?
Now provide the response and nothing else.
| What you are not seeing here is, mainly, that while nobody with a sane mind would use 100 Mbit Ethernet to handle SAN traffic, there are lots of other options which are not only faster, but also a lot faster than direct-attached storage (like standard SCSI). Enterprise-grade SANs are usually connected to servers using Fibre Channel technology, whose speed range from 1 Gbit to 20 Gbit, with the most commonly used adapters being in the 4-8 Gbit range; this not only achieves some impressive bandwidth, but can also make use of Multipath I/O , allowing for bandwidth aggregation and failover between different adapters, FC switches and storage controllers, for maximum availability. Another way servers can access SAN storage is using iSCSI , which is an implementation of the SCSI protocol over IP transport; this is probably what you were referring to in your question. This is actually often considered a less-than-optimal solution (the optimal one being FC), but still nobody would run it over 100 Mbit Ethernet, and things change dramatically when running it over a gigabit (or 10 Gbit) Ethernet link. That said about speed, everything else you heard about SAN applies: you can create and resize volumes (called LUNs ) on demand, present them to different servers (even more than one at the same time, which is usually a requirement for clustering), and also have some nice added benefits like SAN-to-SAN replication and SAN-level backups, which can really change things when you have to handle high availability and disaster recovery for large (as in, many TBs) data sizes. As usual, you can start to dig further here: http://en.wikipedia.org/wiki/Storage_area_network . Of course, this usually makes sense for medium/large environments. There can be a case for a small SAN even in smaller ones. But in a place with two servers , any kind of SAN is much likely overkill. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/425275', 'https://serverfault.com', 'https://serverfault.com/users/125657/']} | jdg_82154 |
stackexchange | llm_judgeable_groundtruth_similarity | 4636191 |
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 question pertains specifically to shell scripts, but could be about any programming language. Is there any difference between using multiple if statements and using elif statements in shell scripts? And, a case statement would not work in my situation.
Now provide the response and nothing else.
| Yes, potentially. Consider this (C#, Java, whatever): int x = GetValueFromSomewhere();if (x == 0){ // Something x = 1;}else if (x == 1){ // Something else...} vs this: int x = GetValueFromSomewhere();if (x == 0){ // Something x = 1;}if (x == 1){ // Something else...} In the first case, only one of "Something" or "Something else..." will occur. In the second case, the side-effects of the first block make the condition in the second block true. Then for another example, the conditions may not be mutually exclusive to start with: int x = ...;if (x < 10){ ...} else if (x < 100){ ...}else if (x < 1000){ ...} If you get rid of the "else" here, then as soon as one condition has matched, the rest will too. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4636191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304725/']} | jdg_82155 |
stackexchange | llm_judgeable_groundtruth_similarity | 53637121 |
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 server of the application in which I work uses a certificate to allow requests.I have it installed, for example, in the desktop Chrome browser and it works fine. It´s a usual certificate with the extension .cer Now I have to make this certificate work also in my android application and, honestly, I have never done it and I'm a bit lost. To make the requests I am using okhttp2, as you can see in this example: public String makeServiceCall(String url, JSONObject data) { final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(45, TimeUnit.SECONDS); client.setReadTimeout(45, TimeUnit.SECONDS); client.setProtocols(Arrays.asList(Protocol.HTTP_1_1)); RequestBody body = RequestBody.create(JSON, data.toString()); Request request = new Request.Builder() .url(url) .header("Accept","application/json") .post(body) .build(); try { Response response = client.newCall(request).execute(); return response.body().string(); } catch (Exception e) { e.printStackTrace(); return null; } } So far everything works perfectly, but after searching and reading tutorials, examples, etc, (many of them from this page) I have not managed to make it work. Make it work with the certificate. Having never done this, and being a bit confused already, I would appreciate the following clarifications: The certificate in .cer format that I have, I suppose I should convert it to another format to be able to use it in android ...Is it correct? If it is correct, how should I do it? ok, I already have my certificate converted to BKS and hosted in the res / raw folder, but I'm still unable to apply it successfully to the request okhttp2 .. Once with a certificate in correct format,How is it implemented with the requests that I am already making in the code that I have set as an example? I have searched for information about doing it using okhttp3 but I have not been able to authorize the requests either. This article has been useful to me, but I am not using retrofit and adapting it to okhttp2 does not work either. I would appreciate an explanation of how to do it
Now provide the response and nothing else.
| Here is an implementation using official okhttp3 sample code . It is possible to create a trusted OkHttpClient using a custom certificate. I've put the .cer certificate in res/raw then read it in using the trustedCertificatesInputStream() method. CustomTrust customTrust = new CustomTrust(getApplicationContext());OkHttpClient client = customTrust.getClient(); CustomTrust.java import android.content.Context;import java.io.IOException;import java.io.InputStream;import java.security.GeneralSecurityException;import java.security.KeyStore;import java.security.cert.Certificate;import java.security.cert.CertificateFactory;import java.util.Arrays;import java.util.Collection;import javax.net.ssl.KeyManagerFactory;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import javax.net.ssl.TrustManagerFactory;import javax.net.ssl.X509TrustManager;import okhttp3.CertificatePinner;import okhttp3.OkHttpClient;public final class CustomTrust { private final OkHttpClient client; private final Context context; public CustomTrust(Context context) { this.context = context; X509TrustManager trustManager; SSLSocketFactory sslSocketFactory; try { trustManager = trustManagerForCertificates(trustedCertificatesInputStream()); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{trustManager}, null); sslSocketFactory = sslContext.getSocketFactory(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } client = new OkHttpClient.Builder() .sslSocketFactory(sslSocketFactory, trustManager) .connectTimeout(45, TimeUnit.SECONDS) .readTimeout(45, TimeUnit.SECONDS) .protocols(Arrays.asList(Protocol.HTTP_1_1)) .build(); } public OkHttpClient getClient() { return client; } /** * Returns an input stream containing one or more certificate PEM files. This implementation just * embeds the PEM files in Java strings; most applications will instead read this from a resource * file that gets bundled with the application. */ private InputStream trustedCertificatesInputStream() { return context.getResources().openRawResource(R.raw.certificate); } /** * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose * certificates have not been signed by these certificates will fail with a {@code * SSLHandshakeException}. * * <p>This can be used to replace the host platform's built-in trusted certificates with a custom * set. This is useful in development where certificate authority-trusted certificates aren't * available. Or in production, to avoid reliance on third-party certificate authorities. * * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using * the host platform's built-in trust store. * * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3> * * <p>Relying on your own trusted certificates limits your server team's ability to update their * TLS certificates. By installing a specific set of trusted certificates, you take on additional * operational complexity and limit your ability to migrate between certificate authorities. Do * not use custom trusted certificates in production without the blessing of your server's TLS * administrator. */ private X509TrustManager trustManagerForCertificates(InputStream in) throws GeneralSecurityException { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in); if (certificates.isEmpty()) { throw new IllegalArgumentException("expected non-empty set of trusted certificates"); } // Put the certificates a key store. char[] password = "password".toCharArray(); // Any password will work. KeyStore keyStore = newEmptyKeyStore(password); int index = 0; for (Certificate certificate : certificates) { String certificateAlias = Integer.toString(index++); keyStore.setCertificateEntry(certificateAlias, certificate); } // Use it to build an X509 trust manager. KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers)); } return (X509TrustManager) trustManagers[0]; } private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream in = null; // By convention, 'null' creates an empty key store. keyStore.load(in, password); return keyStore; } catch (IOException e) { throw new AssertionError(e); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53637121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1391483/']} | jdg_82156 |
stackexchange | llm_judgeable_groundtruth_similarity | 10676441 |
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 perl, at most places where hash is used a reference to python's dictionaries is given. A difference which I have noticed is that the hashes don't preserve the order of elements. I would like to know if there are some more concrete and fundamental differences between the two.
Now provide the response and nothing else.
| The most fundamental difference is that perl hashes don't throw errors if you access elements that aren't there. $ python -c 'd = {}; print("Truthy" if d["a"] else "Falsy")'Traceback (most recent call last): File "<string>", line 1, in <module>KeyError: 'a'$ perl -we 'use strict; my $d = {}; print $d->{"a"} ? "Truthy\n": "Falsy\n"'Falsy$ Perl hashes auto create elements too unlike python $ python -c 'd = dict(); d["a"]["b"]["c"]=1'Traceback (most recent call last): File "<string>", line 1, in <module>KeyError: 'a'$ perl -we 'use strict; my $d = {}; $d->{a}{b}{c}=1'$ If you are converting perl to python those are the main things that will catch you out. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10676441', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1406562/']} | jdg_82157 |
stackexchange | llm_judgeable_groundtruth_similarity | 8398102 |
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 faux dialog which uses this layout: <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="match_parent" android:layout_width="match_parent" android:id="@+id/containerPageConatiner"> <FrameLayout android:id="@+id/dialogHolder" android:layout_height="wrap_content" android:layout_width="wrap_content" android:padding="15dp" android:layout_gravity="center" android:background="@drawable/panel_picture_frame_bg_focus_blue"/> </FrameLayout> I place a fragment inside the <FrameLayout> depending on the dialog which is opening - The activity controlling the Dialog looks like this: <activity android:label="@string/app_name" android:name=".activity.DialogActivity" android:theme="@style/CustomTheme.Screen.Transparent" android:windowSoftInputMode="adjustResize"> Unfortunately when you click on an edit text inside of the dialog, no resizing takes place. The windowSoftInputMode literally makes no difference as the functionality is the same as pan mode. Documentation says "This of course only works for applications that have a resizeable area that can be reduced to make enough space" but doesn't tell you what it means by "a resizeable area" and makes me think that in some way I don't have a resizeable area? If anyone knows what's up can they help me out? EDIT Surrounding the dialog like so doesn't change anything: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/containerPageConatiner" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <View android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="1" /> <FrameLayout android:id="@+id/dialogHolder" android:layout_height="wrap_content" android:layout_width="wrap_content" android:padding="15dp" android:layout_gravity="center" android:background="@drawable/panel_picture_frame_bg_focus_blue"/> <View android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="1" /></LinearLayout> EDIT2 Scrollview as parent doesn't help either: <?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/containerPageConatiner" android:layout_width="match_parent" android:layout_height="match_parent" > <FrameLayout android:id="@+id/dialogHolder" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="15dp" /></ScrollView>
Now provide the response and nothing else.
| I created a new project in order to try and get the basic features working for window resizing and the slowly moved it towards the target peice of my project. Doing this I tracked the problem down to this: In my theme hierarchy I had this property: <item name="android:windowFullscreen">true</item> which was burried at the level of Theme.Black.NoTitleBar.FullScreen - An ancestor of my custom theme. The documentation suggests that this is a "Flag indicating whether this window should fill the entire screen". That sounds like a good thing to have if you have an app which takes up the whole screen... Except it still takes up the whole screen without the flag. In fact, once you've taken this out, there is absolutely no change in the app at all... apart from adjustResize now works perfectly. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8398102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/726954/']} | jdg_82158 |
stackexchange | llm_judgeable_groundtruth_similarity | 1882322 |
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 doing a mvn install I want to end up with 2 WAR files in my target directory. One will contain the production web.xml and the other will contain the test/uat web.xml . I've tried this: <build> <finalName>cas-server</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1-beta-1</version> <configuration> <webXml>src/main/config/prod/web.xml</webXml> <warName>cas-prod</warName> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1-beta-1</version> <configuration> <webXml>src/main/config/test/web.xml</webXml> <warName>cas-test</warName> </configuration> </plugin> </plugins></build> But I only end up with the test WAR.
Now provide the response and nothing else.
| I don't think you can do this in one step (actually, I'm surprised that Maven doesn't complain about your setup and wonder which one is applied) and I'd suggest to use profiles and maybe filtering to manage this use case. If your web.xml are really different, you could just put your maven-war-plugin configuration in two profiles. Or, better, you could merge them into something like this: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1-beta-1</version> <configuration> <webXml>src/main/config/${env}/web.xml</webXml> <warName>cas-test</warName> </configuration></plugin> And set the env property in two profiles to pick up the right web.xml at build time. <profiles> <profile> <id>uat</id> <properties> <env>test</env> </properties> </profile> <profile> <id>prod</id> <properties> <env>prod</env> </properties> </profile></profiles> If your web.xml are similar (i.e. if only values differ in them), you could define properties and their values in two profiles and use filtering to apply them. Something like this: <profiles> <profile> <id>env-uat</id> <activation> <property> <name>env</name> <value>uat</value> </property> </activation> <properties> <key1>uat_value_key_1</key1> <keyN>uat_value_key_n</keyN> </properties> </profile> <profile> <id>env-prod</id> <activation> <property> <name>env</name> <value>prod</value> </property> </activation> <properties> <key1>prod_value_key_1</key1> <keyN>prod_value_key_n</keyN> </properties> </profile></profiles> Then activate one profile or the other by passing the env property on the command line, e.g.: mvn -Denv=uat package Another option would be to put the values into specific filters and pick up the right one at build time (like in this post ). There are really many options but as I said, I don't think you can do this without runngin the build twice. More resources on profiles/filtering: Maven Book: Chapter 11. Build Profiles Maven Book: Chapter 15.3. Resource Filtering Introduction to Build Profiles Use an alternative Maven Profile during test phase maven profile filtering search on Google | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1882322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1126/']} | jdg_82159 |
stackexchange | llm_judgeable_groundtruth_similarity | 92014 |
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 may have an issue with conducted EMI through the ground connections between devices in a system. There is specifically a device which clearly creates noise on the measured signal from another circuit with a scope (noise is reduced when it's off). That scope has to be connected to both that noisy device and the measured circuit so I'm suspecting HF noise is conducted through the ground. I am thinking about putting ferrite beads on the ground connections for example on the ground connection from all the devices (especially the noisy one) to the scope, but that layout looks like odd to me. Does it make sense to have a ferrite for the ground lead of a coaxial cable? Is there any other way? Additionally, the scope is directly connected to the measured circuit, which is a resistor with one grounded lead (It's a current consumption measurement). Another approach I'm thinking about is a differential amplifier, does this approach looks better? Can even be necessary a combination of both?
Now provide the response and nothing else.
| Increasing the impedance of the system ground between various devices is a bad idea. Decouple the power supply feed points, filter signals between blocks as necessary, but keep the ground connections as solid as you can. If you do manage to decouple the ground, like by adding inductance in series, then the noise will be even larger on all the signals coming out of that block. By allowing the ground to float at high frequencies, you make everything common mode noise, so it will show up on all signals too. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/92014', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/18555/']} | jdg_82160 |
stackexchange | llm_judgeable_groundtruth_similarity | 2055667 |
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 C# how does one implement the ability to chain methods in one's custom classes so one can write something like this: myclass.DoSomething().DosomethingElse(x); etc... Thanks!
Now provide the response and nothing else.
| Chaining is a good solution to produce new instance from existing instances: public class MyInt{ private readonly int value; public MyInt(int value) { this.value = value; } public MyInt Add(int x) { return new MyInt(this.value + x); } public MyInt Subtract(int x) { return new MyInt(this.value - x); }} Usage: MyInt x = new MyInt(10).Add(5).Subtract(7); You can also use this pattern to modify an existing instance, but this is generally not recommended: public class MyInt{ private int value; public MyInt(int value) { this.value = value; } public MyInt Add(int x) { this.value += x; return this; } public MyInt Subtract(int x) { this.value -= x; return this; }} Usage: MyInt x = new MyInt(10).Add(5).Subtract(7); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2055667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174614/']} | jdg_82161 |
stackexchange | llm_judgeable_groundtruth_similarity | 1327469 |
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:
Quick question: Quite often, when doing stuff in Complex Analysis, I'm asked to put something of the form $f = u+iv$ into the form $f(z)$. I HATE this step, because it always amounts to me just looking at it, and trying to sorta guess half way, and work backwards from the guess. It's time-consuming, tedious and clumsy. This will not do. I'm now looking for appropriate theory (in the ideal case, an algorithm), or some other simple approach that will remove much of the guess work, remove stuff like the 'magically noticing' obscure trig identities, and just make the whole thing a bit more palatable. What are some good tactics? Thanks in advance.
Now provide the response and nothing else.
| Firstly I always check if it satisfies Cauchy-Riemann equations or not.If it satisfies you can write $f(x,y) = u(x,y)+iv(x,y)$ into the form $f(z)$. If it does not satisfy Cauchy-Riemann equations, you cannot write the $f(x,y) = u(x,y)+iv(x,y)$ into the form $f(z)$. I would like to show my strategy in some examples Example 1: ( you cannot convert the $f(x,y)$ into $f(z)$ in this example because it does not satisfy Cauchy-Riemann equations. Thus you do not need to struggle for converting into $f(z)$ because you cannot in any way) $$f(x,y)=x^2+y^2+i2xy$$$$u(x,y)=x^2+y^2$$$$v(x,y)=2xy$$ Cauchy-Riemann equations: $$\frac{\partial{u}}{\partial{x}}=\frac{\partial{v}}{\partial{y}}$$ $$\frac{\partial{u}}{\partial{y}}=-\frac{\partial{v}}{\partial{x}}$$ $$2x=2x$$$$2y \neq -2y$$ Thus you cannot do transform for example 1. Example 2: (The example you can convert the $f(x,y)$ as $f(z)$) $$f(x,y)=\frac{x}{x^2+y^2}-\frac{iy}{x^2+y^2}$$$$u(x,y)=\frac{x}{x^2+y^2}$$$$v(x,y)=-\frac{y}{x^2+y^2}$$ If you check, It satisfies Cauchy-Riemann equations thus you can convert into form of $f(z)$ Thus use the known relation for $z$ for convertion . We know $z=x+iy$ so $x=z-iy$ Put it into the equation and you will see that $y$ will disappear after operations because it satisfies Cauchy-Riemann equations $$f(z)=\frac{z-iy}{(z-iy)^2+y^2}-\frac{iy}{(z-iy)^2+y^2}$$$$f(z)=\frac{z-iy}{z^2-2izy}-\frac{iy}{z^2-2izy}$$$$f(z)=\frac{z-2iy}{z^2-2izy}=\frac{z-2iy}{z(z-2iy)}=\frac{1}{z}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1327469', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111167/']} | jdg_82162 |
stackexchange | llm_judgeable_groundtruth_similarity | 2917 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For $A\subset [n]$ denote by $a_i$ the $i^{th}$ smallest element of $A$ . For two $k$ -element sets, $A,B\subset [n]$ , we say that $A\le B$ if $a_i\le b_i$ for every $i$ . A $k$ -uniform hypergraph ${\mathcal H}\subset [n]$ is called a shift-chain if for any hyperedges, $A, B \in {\mathcal H}$ , we have $A\le B$ or $B\le A$ . (So a shift-chain has at most $k(n-k)+1$ hyperedges.) We say that a hypergraph ${\mathcal H}$ is two-colorable (or that it has Property B) if we can color its vertices with two colors such that no hyperedge is monochromatic. Is it true that shift-chains are two-colorable if $k$ is large enough? Remarks. I first posted this problem on mathoverflow , but nobody commented on it. The problem was investigated on the 1st Emlektabla Workshop for some partial results, see the booklet . The question is motivated by decomposition of multiple coverings of the plane by translates of convex shapes, there are many open questions in this area. (For more, see my PhD thesis .) For $k=2$ there is a trivial counterexample: (12),(13),(23). A very magical counterexample was given for $k=3$ by Radoslav Fulek with a computer program: (123),(124),(125),(135),(145),(245),(345),(346),(347),(357), (367),(467),(567),(568),(569),(579),(589),(689),(789). If we allow the hypergraph to be the union of two shift-chains (with the same order), then there is a counterexample for any $k$ . Update. I have recently managed to show that more restricted version of shift-chains are two-colorable in this preprint . Permanent bounty! I'm happy to award a 500 bounty for a solution anytime!
Now provide the response and nothing else.
| This is not an answer. What follows is a simple proof that the construction for k =3 is indeed a counterexample. I think that the asker knows this proof, but I will post it anyway because the proof is nice and this might be useful when people consider the case of larger k . It is easy to verify that it is a shift-chain. Let’s show that it does not have Property B. In fact, the subhypergraph {(123), (145), (245), (345), (346), (347), (357), (367), (467), (567), (568), (569), (789)} already fails to satisfy Property B. To see this, suppose that this hypergraph has a 2-coloring and let c i be the color of the vertex i . Look at three hyperedges (145), (245), (345). If c 4 = c 5 , then all of 1, 2 and 3 must be the opposite color to c 4 , but this would give a monochromatic hyperedge (123). Therefore, it must be the case that c 4 ≠ c 5 . Similarly, c 3 ≠ c 4 by comparing the three hyperedges (345), (346), (347) and noticing a hyperedge (567). c 6 ≠ c 7 by comparing the three hyperedges (367), (467), (567) and noticing a hyperedge (345). c 5 ≠ c 6 by comparing the three hyperedges (567), (568), (569) and noticing a hyperedge (789). Therefore, we have c 3 ≠ c 4 ≠ c 5 ≠ c 6 ≠ c 7 . But this implies c 3 = c 5 = c 7 , making the hyperedge (357) monochromatic. This contradicts the assumption of the 2-coloring. | {} | {'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/2917', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/419/']} | jdg_82163 |
stackexchange | llm_judgeable_groundtruth_similarity | 32828486 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a class with two methods where I don't care which is called... public class Foo { public String getProperty(String key) { return getProperty(key, null); } public String getProperty(String key, String defaultValue) { //... }} Both the below (from another class, still in my application) should pass my test: public void thisShouldPass(String key) { // ... String theValue = foo.getProperty(key, "blah"); // ...}public void thisShouldAlsoPass(String key) { // ... String theValue = foo.getProperty(key); if (theValue == null) { theValue = "blah"; } // ...} I don't care which was called, I just want one of the two variants to be called. In Mockito, I can generally do things like this: Mockito.verify(foo, atLeastOnce()).getProperty(anyString()); Or: Mockito.verify(foo, atLeastOnce()).getProperty(anyString(), anyString()); Is there a native way to say "verify either one or the other occurred at least once"? Or do I have to do something as crude as: try { Mockito.verify(foo, atLeastOnce()).getProperty(anyString());} catch (AssertionError e) { Mockito.verify(foo, atLeastOnce()).getProperty(anyString(), anyString());}
Now provide the response and nothing else.
| You could use atLeast(0) in combination with ArgumentCaptor : ArgumentCaptor<String> propertyKeyCaptor = ArgumentCaptor.forClass(String.class);Mockito.verify(foo, atLeast(0)).getProperty(propertyKeyCaptor.capture(), anyString());ArgumentCaptor<String> propertyKeyCaptor2 = ArgumentCaptor.forClass(String.class);Mockito.verify(foo, atLeast(0)).getProperty(propertyKeyCaptor2.capture());List<String> propertyKeyValues = propertyKeyCaptor.getAllValues();List<String> propertyKeyValues2 = propertyKeyCaptor2.getAllValues();assertTrue(!propertyKeyValues.isEmpty() || !propertyKeyValues2.isEmpty()); //JUnit assert -- modify for whatever testing framework you're using | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32828486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191761/']} | jdg_82164 |
stackexchange | llm_judgeable_groundtruth_similarity | 23049498 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Any ideas as to how I could resolve this error? I am using Spring JPA with Hibernate. Necessary details below. Entity class 1: @Entity@Table(name = "ways")@TypeDef(name = "hstore", typeClass = HstoreUserType.class)@Cacheablepublic class Way { /** * Primary key for the row in table. */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; /** * The ID to represent it across the system. * Used for preserving historical information. */ @Column(name = "way_id") private Long wayId; /** * The version of the way this Object represents. */ @Column(name = "version") private Integer version; /** * The {@link User} that edited this version. */ @OneToOne @PrimaryKeyJoinColumn(name = "user_id") private User user; /** * Timestamp when this version of the Way was edited. */ @Column(name = "tstamp") @Temporal(TemporalType.TIMESTAMP) private Date timestamp; /** * The changeset that this version of the way belongs to. */ @Column(name = "changeset_id") private Long changesetId; /** * All the tags this Way contains. */ @Type(type = "hstore") @Column(name = "tags", columnDefinition = "hstore") private Object2ObjectOpenHashMap<String, String> tags = new Object2ObjectOpenHashMap<String, String>(); @Column(name = "bbox") private Geometry bbox; @Column(name = "linestring") private Geometry linestring; @Column(name = "nodes") private Long[] nodes; // getters and setters} Entity class for User: @Entity@Table(name = "users")@Cacheablepublic class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "name", unique = true) private String name; // getters and setters} And the stacktrace : The stacktrace is quite huge. I am pasting the whole stacktrace below for reference and a quick TL;DR here: javax.persistence.PersistenceException: org.hibernate.type.SerializationException: could not deserializeCaused by: org.hibernate.type.SerializationException: could not deserializeCaused by: java.io.StreamCorruptedException: invalid stream header: 30313033 Full stacktrace follows: javax.persistence.PersistenceException: org.hibernate.type.SerializationException: could not deserialize at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1361) at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1289) at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:261) at org.hibernate.ejb.criteria.CriteriaQueryCompiler$3.getResultList(CriteriaQueryCompiler.java:260) at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll(SimpleJpaRepository.java:250) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFac at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySuppo at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeReava:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) at com.sun.proxy.$Proxy36.findAll(Unknown Source) at com.osmrecommend.persistence.service.WayPersistenceServiceImpl.getAllWays(WayPersistenceServiceImpl.java:32) at com.osmrecommend.dao.WayDAO.getAllWays(WayDAO.java:37) at com.osmrecommend.cbf.TFIDFModelBuilder.get(TFIDFModelBuilder.java:90) at com.osmrecommend.cbf.TFIDFModelBuilder.get(TFIDFModelBuilder.java:36) at org.grouplens.grapht.util.MemoizingProvider.get(MemoizingProvider.java:59) at org.grouplens.lenskit.inject.StaticInjector.instantiate(StaticInjector.java:130) at org.grouplens.lenskit.inject.StaticInjector.apply(StaticInjector.java:137) at org.grouplens.lenskit.inject.StaticInjector.apply(StaticInjector.java:47) at org.grouplens.lenskit.eval.traintest.ComponentCache$NodeInstantiator.call(ComponentCache.java:166) at com.google.common.cache.LocalCache$LocalManualCache$1.load(LocalCache.java:4792) at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3599) at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2379) at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2342) at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2257) at com.google.common.cache.LocalCache.get(LocalCache.java:4000) at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4789) at org.grouplens.lenskit.eval.traintest.ComponentCache$Instantiator.apply(ComponentCache.java:126) at org.grouplens.lenskit.eval.traintest.ComponentCache$Instantiator.apply(ComponentCache.java:104) at org.grouplens.lenskit.inject.RecommenderInstantiator$1.apply(RecommenderInstantiator.java:109) at org.grouplens.lenskit.inject.RecommenderInstantiator$1.apply(RecommenderInstantiator.java:99) at org.grouplens.lenskit.inject.RecommenderInstantiator.replaceShareableNodes(RecommenderInstantiator.java:188) at org.grouplens.lenskit.inject.RecommenderInstantiator.instantiate(RecommenderInstantiator.java:99) at org.grouplens.lenskit.eval.traintest.LenskitEvalJob.buildRecommender(LenskitEvalJob.java:74) at org.grouplens.lenskit.eval.traintest.TrainTestJob.runEvaluation(TrainTestJob.java:117) at org.grouplens.lenskit.eval.traintest.TrainTestJob.call(TrainTestJob.java:101) at org.grouplens.lenskit.eval.traintest.JobGraph$JobNode.call(JobGraph.java:116) at org.grouplens.lenskit.eval.traintest.JobGraph$JobNode.call(JobGraph.java:102) at org.grouplens.lenskit.util.parallel.SequentialTaskGraphExecutor.execute(SequentialTaskGraphExecutor.java:37) at org.grouplens.lenskit.eval.traintest.TrainTestEvalTask.runEvaluations(TrainTestEvalTask.java:468) at org.grouplens.lenskit.eval.traintest.TrainTestEvalTask.perform(TrainTestEvalTask.java:398) at org.grouplens.lenskit.eval.traintest.SimpleEvaluator.call(SimpleEvaluator.java:313) at com.osmrecommend.app.OSMRecommendEval.main(OSMRecommendEval.java:94)Caused by: org.hibernate.type.SerializationException: could not deserialize at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:262) at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306) at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:131) at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:117) at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:39) at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:67) at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:65) at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:269) at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:265) at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:238) at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:357) at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2695) at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1552) at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1484) at org.hibernate.loader.Loader.getRow(Loader.java:1384) at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:640) at org.hibernate.loader.Loader.doQuery(Loader.java:856) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289) at org.hibernate.loader.Loader.doList(Loader.java:2463) at org.hibernate.loader.Loader.doList(Loader.java:2449) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2279) at org.hibernate.loader.Loader.list(Loader.java:2274) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355) at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:196)2014-04-13 17:35:49 INFO persistence.service.WayPersistenceServiceImpl:37 - All ways fetched in 331s at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1115) at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101) at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:252) ... 51 moreCaused by: java.io.StreamCorruptedException: invalid stream header: 30313033 at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804) at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299) at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:328) at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:318) at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:237) ... 78 more UPDATE: I updated the Ways entity class to the following, but error still occurs : @Entity@Table(name = "ways")@Cacheablepublic class Way implements Serializable { /** * */ private static final long serialVersionUID = -7941769011539363185L; /** * Primary key for the row in table. */ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; /** * The ID to represent it across the system. * Used for preserving historical information. */ @Column(name = "way_id") private Long wayId; /** * The version of the way this Object represents. */ @Column(name = "version") private Integer version; /** * The {@link User} that edited this version. */ @OneToOne @PrimaryKeyJoinColumn(name = "user_id") private User user; /** * Timestamp when this version of the Way was edited. */ @Column(name = "tstamp") @Temporal(TemporalType.TIMESTAMP) private Date timestamp; /** * The changeset that this version of the way belongs to. */ @Column(name = "changeset_id") private Long changesetId; /** * All the tags this Way contains. */ @Column(name = "tags") private String tags; @Column(name = "bbox") private Geometry bbox; @Column(name = "linestring") private Geometry linestring; @Column(name = "nodes") @ElementCollection(targetClass=Long.class) private List<Long> nodes;
Now provide the response and nothing else.
| This issue is happening when something cannot be deserialized (thank you, Captain Obvious). In your entity mappings the following looks suspicious: @Type(type = "hstore")@Column(name = "tags", columnDefinition = "hstore")private Object2ObjectOpenHashMap<String, String> tags = new Object2ObjectOpenHashMap<String, String>(); @Column(name = "bbox")private Geometry bbox;@Column(name = "linestring")private Geometry linestring; My suggestion is either to take a look over Geometry and Object2ObjectHashMap classes - check whether they are serializable itself and all their fields either serializable too, or marked with transient keyword. Also if you post these classes here, this may help aswell. HstoreUserType class listing may also be helpful. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23049498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283143/']} | jdg_82165 |
stackexchange | llm_judgeable_groundtruth_similarity | 89211 |
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 trouble understanding the definition of cardinal exponentiation. Let's start with the definitions / claims I've been given: For any finite sets $A,B$, such that if $|A|=a$ and $|B|=b\neq 0$ then the number of functions from $A$ to $B$ is $b^a$. ( I'm guessing this is only used when both sets are finite ). For any sets $A,B$, $B^A$ is the set of functions from $A$ to $B$. For every set $A$, $|P(A)|=|\left \{ 0,1 \right \}^A|$ Now for the definition and why I don't understand it: Let $a,b$ be cardinal numbers. Let $A,B$ be sets such that $|A|=a, |B|=b$. Then $|B^A|=b^a$. How analagous to normal exponentiation is this and where does in differ when we introduce cardinals like $\aleph_0$ or $C$? Is $2^2=4$ and is $\frak c^2=c\cdot c=c\times c$?
Now provide the response and nothing else.
| When you say "normal exponentiation", you can think about natural numbers, real numbers, complex numbers, and so on. Assuming that you mean natural numbers, we want a coherent behavior from infinite sets to the laws we have figured out on finite sets. In particular, we want $|A^B| = |A|^{|B|}$. First let us review the basic laws of cardinal arithmetics: $|A|+|B| = |\{0\}\times A\cup\{1\}\times B|$, that is addition of cardinals is the disjoint union of representatives. $|A|\cdot|B| = |A\times B|$, that is multiplication is cardinality of the product. $|A|^{|B|} = |A^B|$. This is the nugget of gold in this question, and we'll discuss this through the rest of this answer. Of course we want these actions to behave in coherence with finitary actions. Multiplication is distributive over addition, exponentiation over multiplication, and so on and so forth. I will not get into that here. Why do we want that? Because if we denote $n=\{0,\ldots,n-1\}$ for every $n\in\mathbb N$, then $k^n$ is just the amount of functions from any set of $n$ elements to any set of $k$ elements. This means that if $|A|=|C|$ and $|B|=|D|$ then we would like that $|A^B|=|C^D|$. In other words, the cardinality is an equivalence relation and we want all the cardinal arithmetic to be independent of the choice of representatives (at least when finitely many sets are involved). However, infinite sets - and in particular $\aleph$ numbers - behave much differently than finite sets. For example $|\{0,\ldots,n-1\}\cup\{n\}|>n$ while $|\mathbb N\cup\{-1\}|=|\mathbb N|$. Even more so, $|\mathbb N\times\mathbb N|=|\mathbb N|$. This means that some things, while working "the same" are going to work differently. For your last question, we can notice that $\{f\colon\{1,2\}\to X\}$ would simply correspond to functions choosing two elements each time. This is just specifying ordered pairs in a very canonical way - $f(1)$ is the left coordinate and $f(2)$ is the right one. This means that $A^{\{0,\ldots,n-1\}}$ can be thought of as the set of $n$-tuples from $A$, or $\underbrace{A\times\ldots\times A}_{n\text{ times}}$. The laws of cardinal arithmetic tells us that $|A|\cdot|B| = |A\times B|$, so we have that $|A^{\{0,\ldots,n-1\}}|=|\underbrace{A\times\ldots\times A}_{n\text{ times}}|=\underbrace{|A|\cdot\ldots\cdot|A|}_{n\text{ times}}=|A|^n$. Of course, since we deal with infinite sets we are no longer guaranteed an actual increase of cardinality, but the laws work the same. What if $|A|$ and $|B|$ are infinite? Well, we already have the laws for how we wanted exponentiation to behave, now we just need to apply them. We can think of $A^B$ as $B$-tuples of $A$, that is every element of $B$ is an index of a sequence from $A$. These sequences need not be finite, nor countable - not even well ordered. And indeed, we see that if $A=\{0,1\}$ then the rule $|P(B)| = |\{0,1\}^B|=|\{0,1\}|^{|B|}=2^{|B|}$ holds as we wanted it to hold. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/89211', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9381/']} | jdg_82166 |
stackexchange | llm_judgeable_groundtruth_similarity | 658576 |
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 taking the limit as x approaches infinity from the left (-) of: $$ \sqrt{x^2+2x}- \sqrt{x^2-2x} $$ However I'm not sure how to go about this. I'm at: $$ \sqrt{ \frac{x^3+4x^2}{x+2x}}- \sqrt \frac{x^3-4x^2}{x-2x} $$ But I'm not sure if it's okay that I say: "Well, $x^3$ grows exponentially faster than the other factors so the first line gives us $ \sqrt{ \infty} - \sqrt { - \infty } $ so undefined??
Now provide the response and nothing else.
| Multiply numerator and denominator by $$\sqrt{x^2+2x}+ \sqrt{x^2-2x}$$That is, multiply by $1$:$$\dfrac{\sqrt{x^2+2x}- \sqrt{x^2-2x}}{1}\cdot \dfrac{\sqrt{x^2+2x}+ \sqrt{x^2-2x}}{\sqrt{x^2+2x}+ \sqrt{x^2-2x}} = \dfrac{4x}{\sqrt{x^2+2x}+ \sqrt{x^2-2x}}$$ Now, divide numerator and denominator by $x = \sqrt{x^2}$, since $x \to \infty $ implies $x>0$. ADDED: $$\dfrac{4x}{\sqrt{x^2+2x}+ \sqrt{x^2-2x}} = \dfrac {4x}{\sqrt{x^2\left(1 + \frac 2{x}\right)} + \sqrt{x^2\left(1 - \frac 2x\right)}} = \ldots$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/658576', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103867/']} | jdg_82167 |
stackexchange | llm_judgeable_groundtruth_similarity | 10132971 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created a spinner which is automatically updated with appliance names when a person adds an appliance using an array adapter. I created an OnItemSelected method with the spinner so when one of the names in the spinner is selected, a new window appears. However the OnItemSelected is automatically selecting the first item on the list when the activity starts and so the user does not have a chance to actually make a selection until the new window appears. Here is the code: public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub startActivity(new Intent("com.lukeorpin.theappliancekeeper.APPLIANCESELECTED")); }public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub Does anyone know a way in which the first item on the list wont be automatically selected? Here is the code for the rest of the spinner: ArrayAdapter<String> appliancenameadapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ApplianceNames); //Sets up an array adapter containing the values of the ApplianceNames string array applianceName = (Spinner) findViewById(R.id.spinner_name); //Gives the spinner in the xml layout a variable name applianceName.setAdapter(appliancenameadapter); //Adds the contents of the array adapter into the spinner applianceName.setOnItemSelectedListener(this);
Now provide the response and nothing else.
| If you are trying to avoid the initial call to your listener's onItemSelected() method, another option is to use post() to take advantage of the view's message queue. The first time the spinner checks for your listener it won't be set yet. // Set initial selectionspinner.setSelection(position);// Post to avoid initial invocationspinner.post(new Runnable() { @Override public void run() { spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // Only called when the user changes the selection } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10132971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1322398/']} | jdg_82168 |
stackexchange | llm_judgeable_groundtruth_similarity | 4860187 |
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 the following (simplified) code which I'd like to optimise for speed: long inputLen = 50000000; // 50 million DataTable dataTable = new DataTable();DataRow dataRow;object[] objectRow;while (inputLen--){ objectRow[0] = ... objectRow[1] = ... objectRow[2] = ... // Generate output for this input output = ... for (int i = 0; i < outputLen; i++) // outputLen can range from 1 to 20,000 { objectRow[3] = output[i]; dataRow = dataTable.NewRow(); dataRow.ItemArray = objectRow; dataTable.Rows.Add(dataRow); }}// Bulk copySqlBulkCopy bulkTask = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, null);bulkTask.DestinationTableName = "newTable";bulkTask.BatchSize = dataTable.Rows.Count;bulkTask.WriteToServer(dataTable);bulkTask.Close(); I'm already using SQLBulkCopy in an attempt to speed things up, but it appears assigning values to the DataTable itself proves to be slow. I don't know how DataTables work so I'm wondering if I'm creating unnecessary overhead by first creating a reusable array, then assigning it to a DataRow, then adding the DataRow to the DataTable? Or is using DataTable not optimal in the first place? The input comes from a database. I don't care much about LOC, just speed. Can anyone give some advice on this?
Now provide the response and nothing else.
| For such a big table, you should instead use the public void WriteToServer(IDataReader reader) method. It may mean you'll have to implement yourself a "fake" IDataReader interface with your code (if you' don't get the data from an existing IDataReader ), but this way, you'll get "streaming" from end to end, and will avoid a 200 million loop. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4860187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/405143/']} | jdg_82169 |
stackexchange | llm_judgeable_groundtruth_similarity | 816012 |
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 read somewhere that, there exist two numbers $x$ and $y$ such that $x! + y! = 10!$.But, the obvious calculations does not meet this criteria.So, is this equation even solvable :$x! + y! = 10!$
Now provide the response and nothing else.
| Surely the problem must be to find $x$ and $y$ such that the product of $x!$ and $y!$ is $10!$. Notice that the last few factors of $10!$ are $\ldots 8 \cdot 9 \cdot 10$, which factor into small primes. In particular, $8 \cdot 9 \cdot 10 = 720 = 6!$, so $10! = 7! \cdot 6!$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/816012', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29160/']} | jdg_82170 |
stackexchange | llm_judgeable_groundtruth_similarity | 59561391 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anyone explain in simple terms what is the difference between deploying Prometheus through Kubernetes operator and Prometheus helm chart or manifest file?The question is not just pertaining to Prometheus alone but in general
Now provide the response and nothing else.
| In general Helm is like a package manager for kubernetes whereas operator is a controller which manages the life cycle of particular kubernetes resource(s). Operator is a combination of "Custom Resource" and a "Controller" managing the custom resource. There are many native kubernetes resources like pods, deployments, statefulsets, services etc. Each of resources have a corresponding controller process running (currently inside the controller manager). When you create/modify instance of one of the native kubernetes resources using kubectl apply for example, the new/updated object will stored in etcd and api-server will notify the controller about change. The specification in etcd is called the desired state. The job of the controller is to identify the actual state of the cluster and to reconcile it with desired state. Similar to native kubernetes resources, kubernetes also allows you to create new types of resources using "Custom Resource Definitions". You can also write a controller whose job is to reconcile the your new custom resource. This is called an operator. Usually operators are written to manage the deployment, lifecycle of applications on kubernetes. So Prometheus guys have created a custom resource called Prometheus (using which you can express the desired state of a Prometheus cluster) and a controller which reconciles the desired state with actual state. This controller is called Prometheus operator. Helm is package manager for kubernetes resources which are generally declared as yaml based manifests. Helm allows you to template these yaml manifests so that you can substitute different values for these templated snippets when deploying the resources in an actual cluster. You can deploy various kubernetes resources including all native resources like pods, services, deployments etc. Operators also run as pods on kubernetes cluster, so helm can be used to deploy operators as well. You can read about custom resources and custom controllers here - https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/#custom-resources | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59561391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3009657/']} | jdg_82171 |
stackexchange | llm_judgeable_groundtruth_similarity | 18393498 |
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 added .DS_Store to the .gitignore file, but it seems that it is only ignoring .DS_Store in the root directory, not in every folder and subfolder. How do I fix this?
Now provide the response and nothing else.
| I think the problem you're having is that in some earlier commit, you've accidentally added .DS_Store files to the repository. Of course, once a file is tracked in your repository, it will continue to be tracked even if it matches an entry in an applicable .gitignore file. You have to manually remove the .DS_Store files that were added to your repository. You can use git rm --cached .DS_Store Once removed, git should ignore it. You should only need the following line in your root .gitignore file: .DS_Store . Don't forget the period! git rm --cached .DS_Store removes only .DS_Store from the current directory. You can use find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch to remove all .DS_Stores from the repository. Felt tip: Since you probably never want to include .DS_Store files, make a global rule. First, make a global .gitignore file somewhere, e.g. echo .DS_Store >> ~/.gitignore_global Now tell git to use it for all repositories: git config --global core.excludesfile ~/.gitignore_global This page helped me answer your question. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/18393498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2627407/']} | jdg_82172 |
stackexchange | llm_judgeable_groundtruth_similarity | 641252 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find the equilibrium solutions of the following differential equation: $$\dfrac{dy}{dt} = \dfrac{(t^2 - 1)(y^2 - 2)}{(y^2 -4)}$$ I'm not sure how to go about doing this since t appears explicitly on the right hand side. Would $y = \sqrt{2}$ or $-\sqrt{2}$ be solutions?
Now provide the response and nothing else.
| We are looking for where the derivative $\dfrac{dy}{dt} = 0$. This is satisfied when $y^2-2 = 0$ and you do not want $y^2 - 4 = 0$ (division by zero). This leads to the two equilibrium points, $y = \pm \sqrt{2}$. We can find a closed-form solution (ugly) for this DEQ: $$y(t)-\dfrac{\ln(\sqrt{2}-y(t))}{\sqrt{2}}+\dfrac{\ln(y(t)+\sqrt{2})}{\sqrt{2}} = c+\dfrac{t^3}{3}-t$$ A direction field plot shows (look at $y = \pm~ \sqrt{2}$): Additionally, if we look at $t = \pm 1$, on the following direction field plot, we can see the horizontal tangents as: | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/641252', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/51462/']} | jdg_82173 |
stackexchange | llm_judgeable_groundtruth_similarity | 3467279 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need a function which takes an arbitrary number of arguments (All of the same type), does something with them and afterwards gives a result back. A list of arguments is impracticable in my specific case. As I looked through the haskell libs, I saw that the function printf (from module Text.Printf ) uses a similar trick. Unfortunately, I couldn't understand that magic by looking at the source. Can somebody explain how to achieve this, or at least some webpage/paper/whatever where I could find a good description for this? Motivation: The reason I need this is really quite simple. For school (computer science class), we are required to write a module that is able to "record" a mathematical expression, express it as a string (Via writing an instance of Num/Real/etc for an own datatype), and perform various operations on it. This datatype contains a special constructor for a variable, which may be replaced by a value or whatever by a specified function. One of the goals is to write a function, which takes such an expression with some number of variables (pairs of type (Char,Rational) ) and calculates the result of the expression. We should look at how to express the goal of the function best. (My idea: The function returns another function which takes exactly as many arguments as vars that are defined in the function - seems to be impossible).
Now provide the response and nothing else.
| The key points of printf is the ability to either return a String or a function. Copied from http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/src/Text-Printf.html , printf :: (PrintfType r) => String -> rprintf fmts = spr fmts []class PrintfType t where spr :: String -> [UPrintf] -> tinstance (IsChar c) => PrintfType [c] where spr fmts args = map fromChar (uprintf fmts (reverse args))instance (PrintfArg a, PrintfType r) => PrintfType (a -> r) where spr fmts args = \a -> spr fmts (toUPrintf a : args) and the basic structure we can extract out is variadicFunction :: VariadicReturnClass r => RequiredArgs -> rvariadicFunction reqArgs = variadicImpl reqArgs memptyclass VariadicReturnClass r where variadicImpl :: RequiredArgs -> AccumulatingType -> rinstance VariadicReturnClass ActualReturnType where variadicImpl reqArgs acc = constructActualResult reqArgs accinstance (ArgClass a, VariadicReturnClass r) => VariadicReturnClass (a -> r) where variadicImpl reqArgs acc = \a -> variadicImpl reqArgs (specialize a `mappend` acc) For instance: class SumRes r where sumOf :: Integer -> rinstance SumRes Integer where sumOf = idinstance (Integral a, SumRes r) => SumRes (a -> r) where sumOf x = sumOf . (x +) . toInteger then we could use *Main> sumOf 1 :: Integer1*Main> sumOf 1 4 7 10 :: Integer22*Main> sumOf 1 4 7 10 0 0 :: Integer22*Main> sumOf 1 4 7 10 2 5 8 22 :: Integer59 | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3467279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/417501/']} | jdg_82174 |
stackexchange | llm_judgeable_groundtruth_similarity | 31909785 |
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 really running into a brick wall with this. How do you pass class values between tests in phpunit? Test 1 -> sets value, Test 2 -> reads value Here is my code: class JsonRpcBitcoinTest extends PHPUnit_Framework_TestCase{ public function setUp(){ global $configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort; $this->bitcoindConn = new JsonRpcBitcoin($configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort); $this->blockHash = ''; } /** * @depends testCanAuthenticateToBitcoindWithGoodCred */ public function testCmdGetBlockHash() { $result = (array)json_decode($this->bitcoindConn->getblockhash(20)); $this->blockHash = $result['result']; $this->assertNotNull($result['result']); } /** * @depends testCmdGetBlockHash */ public function testCmdGetBlock() { $result = (array)json_decode($this->bitcoindConn->getblock($this->blockHash)); $this->assertEquals($result['error'], $this->blockHash); }} testCmdGetBlock() is not getting the value of $this->blockHash that should be set in testCmdGetBlockHash() . Help in understanding what is wrong would be greatly appreciated.
Now provide the response and nothing else.
| The setUp() method is always called before tests, so even if you set up a dependency between two tests, any variables set in setUp() will be overwritten. The way PHPUnit data passing works is from the return value of one test to the parameter of the other: class JsonRpcBitcoinTest extends PHPUnit_Framework_TestCase{ public function setUp() { global $configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort; $this->bitcoindConn = new JsonRpcBitcoin($configRpcUser, $configRpcPass, $configRpcHost, $configRpcPort); $this->blockHash = ''; } public function testCmdGetBlockHash() { $result = (array)json_decode($this->bitcoindConn->getblockhash(20)); $this->assertNotNull($result['result']); return $result['result']; // the block hash } /** * @depends testCmdGetBlockHash */ public function testCmdGetBlock($blockHash) // return value from above method { $result = (array)json_decode($this->bitcoindConn->getblock($blockHash)); $this->assertEquals($result['error'], $blockHash); }} So if you need to save more state between tests, return more data in that method. I would guess that the reason PHPUnit makes this annoying is to discourage dependent tests. See the official documentation for details . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31909785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335583/']} | jdg_82175 |
stackexchange | llm_judgeable_groundtruth_similarity | 8397152 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to set android:layout_alignParentBottom="true" for a videoview, by code and not from xml?
Now provide the response and nothing else.
| I assume you are trying to add your VideoView to a RelativeLayout ? RelativeLayout relativeLayout = findViewById(R.id.your_relative_layout);mVideo = new VideoView(this); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // or wrap_contentlayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);relativeLayout.addView(mVideo , layoutParams); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8397152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/784766/']} | jdg_82176 |
stackexchange | llm_judgeable_groundtruth_similarity | 39431390 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi I followed a course by Jared Davidson to create a custom camera view and save pictures using AVFoundation. https://www.youtube.com/watch?v=w0O3ZGUS3pk However I would like to record and save videos instead of images. Can someone help me here? I'm sure its simple but apple's Documentation is written in Objective-C and I cant decipher it. This is my code. Thanks. import UIKitimport AVFoundationclass ViewController: UIViewController { var captureSession = AVCaptureSession() var sessionOutput = AVCaptureStillImageOutput() var previewLayer = AVCaptureVideoPreviewLayer() @IBOutlet var cameraView: UIView! override func viewWillAppear(animated: Bool) { let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in devices { if device.position == AVCaptureDevicePosition.Front{ do{ let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice) if captureSession.canAddInput(input){ captureSession.addInput(input) sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if captureSession.canAddOutput(sessionOutput){ captureSession.addOutput(sessionOutput) captureSession.startRunning() previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait cameraView.layer.addSublayer(previewLayer) previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2) previewLayer.bounds = cameraView.frame } } } catch{ print("Error") } } } } @IBAction func TakePhoto(sender: AnyObject) { if let videoConnection = sessionOutput.connectionWithMediaType(AVMediaTypeVideo){ sessionOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { buffer, error in let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData)!, nil, nil, nil) }) } }}
Now provide the response and nothing else.
| You can save record your video to file by creating and adding an AVCaptureMovieFileOutput to your capture session, and making your ViewController conform to the AVCaptureFileOutputRecordingDelegate . This example records 5 seconds of video to a file called "output.mov" in the app's Documents directory. class ViewController: UIViewController, AVCaptureFileOutputRecordingDelegate { var captureSession = AVCaptureSession() var sessionOutput = AVCaptureStillImageOutput() var movieOutput = AVCaptureMovieFileOutput() var previewLayer = AVCaptureVideoPreviewLayer() @IBOutlet var cameraView: UIView! override func viewWillAppear(animated: Bool) { self.cameraView = self.view let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) for device in devices { if device.position == AVCaptureDevicePosition.Front{ do{ let input = try AVCaptureDeviceInput(device: device as! AVCaptureDevice) if captureSession.canAddInput(input){ captureSession.addInput(input) sessionOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if captureSession.canAddOutput(sessionOutput){ captureSession.addOutput(sessionOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait cameraView.layer.addSublayer(previewLayer) previewLayer.position = CGPoint(x: self.cameraView.frame.width / 2, y: self.cameraView.frame.height / 2) previewLayer.bounds = cameraView.frame } captureSession.addOutput(movieOutput) captureSession.startRunning() let paths = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let fileUrl = paths[0].URLByAppendingPathComponent("output.mov") try? NSFileManager.defaultManager().removeItemAtURL(fileUrl) movieOutput.startRecordingToOutputFileURL(fileUrl, recordingDelegate: self) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { print("stopping") self.movieOutput.stopRecording() } } } catch{ print("Error") } } } } func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) { print("FINISHED \(error)") // save video to camera roll if error == nil { UISaveVideoAtPathToSavedPhotosAlbum(outputFileURL.path!, nil, nil, nil) } }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39431390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6733338/']} | jdg_82177 |
stackexchange | llm_judgeable_groundtruth_similarity | 40513101 |
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 learning about Firebase auth and storage in a web app. My idea asks users to login via Firebase and then upload an image. I can see that this is possible from Firebase auth and storage. However, I would like to put limits on the file count and file-size they can upload. Is it possible to control uploads within the Firebase console (or somewhere else)? After reviewing the JavaScript examples, I see how I can put files in, and I can imagine writing code which would query Firebase for a user's upload count, and then limit on the client side, but of course, this is a completely insecure method. If I hosted this as a single page app on, say, GitHub pages, I am wondering if I could set these limits without involving a server. Or, do I need to proxy my uploads through a server to make sure I never allow users to upload more than I intend them to?
Now provide the response and nothing else.
| You can limit what a user can upload through Firebase Storage's security rules . For example this (from the linked docs) is a way to limit the size of uploaded files: service firebase.storage { match /b/<your-firebase-storage-bucket>/o { match /images/{imageId} { // Only allow uploads of any image file that's less than 5MB allow write: if request.resource.size < 5 * 1024 * 1024 && request.resource.contentType.matches('image/.*'); } }} But there is currently no way in these rules to limit the number of files a user can upload. One approach that comes to mind would be to use fixed file names for that. For example, if you limit the allowed file names to be numbered 1..5, the user can only ever have five files in storage: match /public/{userId}/{imageId} { allow write: if imageId.matches("[1-5]\.txt");} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40513101', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105589/']} | jdg_82178 |
stackexchange | llm_judgeable_groundtruth_similarity | 86353 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am studying the derivation of the black hole temperature by means of the Euclidean approach, i.e. by Wick rotating, compactifying the Euclidean time and identifying the period with the inverse temperature. Consider the Schwarzschild case as an example. The Euclidean Schwarzschild metric is of course $ds^2=\left(1-\frac{2M}{r}\right)d\tau^2+\left(1-\frac{2M}{r}\right)^{-1}dr^2$ where $\tau=it$ the Euclidean time. Here $\tau\in[0,\beta]$ with $\beta=T^{-1}$ the inverse temperature, where the points $\tau=0$ and $\tau=\beta$ are equivalent. (I ignore the 2-sphere part of the metric.) Outside but close to the event horizon $r=2M$, we can (after simple some steps) write this as $ds^2=\frac{\sigma^2}{16M^2}d\tau^2+d\sigma^2$. Here $\sigma^2 \equiv 8M(r-2M) $, though this is not really relevant for my question. Now the next step in all the literature is to require that $\tau/4M$ is periodic with period $2\pi$ to prevent conical singularities. I have trouble understanding this. A conical singularity basically means that the point at $\sigma=0$ looks like the tip of a cone, right? So we have a singularity at $\sigma=0$. But don't we still have a singularity there for polar coordinates $(r,\theta)$, since the coordinate chart $\theta$ is not continuous there? If so, removing the point $\sigma=0$ would erase the conical singularity, right? Then why do we want to get rid of the conical singularity, why is it any worse than the polar coordinate singularity? Of course polar coordinates just describe flat space without the origin, is this not the case for the conical coordinates? Clearly I have not understood the concept of a conical singularity... Last question: suppose I did understand it, and continued the derivation to get the temperature $T=1/8\pi M$. Apparently this is the temperature as measured by an observer at infinity, how can I see this? I know the temperature gets redshifted, like frequency, but I don't see where the derivation identifies $T$ with the one measured at infinity.
Now provide the response and nothing else.
| Well, the singularity does not concern the differentiable structure: Even around the tip of a cone (including the tip) you can define a smooth differentiable structure (obviously this smooth structure cannot be induced by the natural one in $R^3$ when the cone is viewed as embedded in $R^3$).Here the singularity is metrical however! Consider a $2D$ smooth manifold an a point $p$, suppose that a smooth metric can be defined in a neighborhood of $p$, including $p$ itself. Next consider a curve $\gamma_r$ surrounding $p$ defined as the set of points with constant geodesic distance $r$ from $p$. Let $L(r)$ be the (metric) length of that curve. It is possible to prove that: $$L(r)/(2\pi r) \to 1\quad \mbox{ as $r \to 0$.}\qquad (1)$$ Actually it is quite evident that this result holds. We say that a $2D$ manifold, equipped with a smooth metric in a neighborhood $A-\{p\}$, of $p$ (notice that now $p$ does not belong to the set where the metric is defined), has a conical singularity in $p$ if:$$L(r)/(2\pi r) \to a\quad \mbox{ as $r \to 0$,}$$ with $0<a<1$. Notice that the class of curves $\gamma_r$ can be defined anyway, even if the metric at $p$ is not defined, since the length of curves and geodesics is however defined (as a limit when an endpoint terminates at $p$). Obviously, if there is a conical singularity in $p$, it is not possible to extend the metric of $A-\{p\}$ to $p$, otherwise (1) would hold true and we know that it is false. As you can understand, all that is independent from the choice of the coordinates you fix around $p$. Nonetheless, polar coordinates are very convenient to perform computations: The fact that they are not defined exactly at $p$ is irrelevant since we are only interested in what happens around $p$ in computing the limits as above. Yes, removing the point one would get rid of the singularity, but the fact remains that it is impossible to extend the manifold in order to have a metric defined also in the limit point $p$: the metric on the rest of the manifold remembers of the existence of the conical singularity! The fact that the Lorentzian manifold has no singularities in the Euclidean section and it is periodic in the Euclidean time coordinate has the following physical interpretation in a manifold with a bifurcate Killing horizon generated by a Killig vecotr field $K$. As soon as you introduce a field theory in the Lorentzian section, the smoothness of the manifold and the periodicity in the Euclidean time, implies that the two-point function of the field, computed with respect to the unique Gaussian state invariant under the Killing time and verifying the so called Hadamard condition (that analytically continued into the Euclidean time to get the Euclidean section) verifies a certain condition said the KMS condition with periodicity $\beta = 8\pi M$. That condition means that the state is thermal and the period of the imaginary time is the constant $\beta$ of the canonical ensemble described by that state (where also the thermodynamical limit has been taken). So that, the associated "statistical mechanics" temperature is: $$T = 1/\beta = 1/8\pi M\:.$$ However the "thermodynamical temperature" $T(x)$ measured at the event $x$ by a thermometer "at rest with" (i.e. whose world line is tangent to) the Killing time in the Lorentzian section has to be corrected by the known Tolman's factor . It takes into account the fact that the perceived temperature is measured with respect to the proper time of the thermometer, whereas the state of the field is in equilibrium with respect to the Killing time . The ratio of the notions of temperatures is the same as the inverse ratio of the two notions of time, and it is encapsulated in the (square root of the magnitude of the) component $g_{00}$ of the metric $$\frac{T}{T(x)}=\frac{dt_{proper}(x)}{dt_{Killing}(x)} = \sqrt{-g_{00}(x)}\:.$$ In an asymptotically flat spacetime , for $r \to +\infty$, it holds $g_{00} \to -1$ so that the "statistical mechanics" temperature $T$ coincides to that measured by the thermometer $T(r=\infty)$ far away from the black hole horizon. This is an answer to your last question. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/86353', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/23325/']} | jdg_82179 |
stackexchange | llm_judgeable_groundtruth_similarity | 33706215 |
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 analyzed these two regexes using regex101 . I think the backtrack of /\S+:/ is right. But I can't understand that difference. Am I wrong?
Now provide the response and nothing else.
| While this appears to be implementation specific (RegexBuddy doesn't show this behavior), it can be explained as follows: \w can't match : , but \S can. Therefore, \S+: needs to check more variations of the input string before making sure that get can't match it. More optimized regex engines will exclude impossible matches faster (e. g., when the regex contains a literal character that isn't present in the current part of the match), but apparently the engine that regex101 is using isn't doing that. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33706215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5467750/']} | jdg_82180 |
stackexchange | llm_judgeable_groundtruth_similarity | 47865646 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to open UIDocumentPickerViewController and It should allow user to select all type of files. ie.(.pdf,.doc)files I used UIDocumentPickerViewController method. my Code: UIDocumentPickerDelegate, UIDocumentMenuDelegate in my class declaration //upload file func OpenFile(){ let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePNG),String(kUTTypeImage)], in: .import) importMenu.delegate = self importMenu.modalPresentationStyle = .fullScreen self.present(importMenu, animated: true, completion: nil)}@available(iOS 8.0, *)public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { let cico = url as URL print("The Url is : \(cico)") do { let weatherData = try NSData(contentsOf: cico, options: NSData.ReadingOptions()) print(weatherData) let activityItems = [weatherData] let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) if UI_USER_INTERFACE_IDIOM() == .phone { self.present(activityController, animated: true, completion: { _ in }) } else { let popup = UIPopoverController(contentViewController: activityController) popup.present(from: CGRect(x: CGFloat(self.view.frame.size.width / 2), y: CGFloat(self.view.frame.size.height / 4), width: CGFloat(0), height: CGFloat(0)), in: self.view, permittedArrowDirections: .any, animated: true) } } catch { print(error) } //optional, case PDF -> render //displayPDFweb.loadRequest(NSURLRequest(url: cico) as URLRequest) }@available(iOS 8.0, *)public func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) { documentPicker.delegate = self present(documentPicker, animated: true, completion: nil) } func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { print(" cancelled by user") dismiss(animated: true, completion: nil) } In this code the app will crash. the reason is Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'You cannot initialize a UIDocumentPickerViewController except by the initWithDocumentTypes:inMode: and initWithURL:inMode: initializers. I don't know how to initialise the initWithDocumentTypes:inMode. I'm new to iOS any one help me???can you please help me..
Now provide the response and nothing else.
| Swift 3*, 4*, To open document and select any document, you are using UIDocumentPickerViewController then all documents presented in your iCloud, Files and in Google Drive will be shown if Google Drive is connected in user device. Then selected document need to download in your app and from there you can show it in WKWebView , @IBAction func uploadNewResumeAction(_ sender: Any) { /* let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import) */ let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.text", "com.apple.iwork.pages.pages", "public.data"], in: .import) documentPicker.delegate = self present(documentPicker, animated: true, completion: nil)} extension YourViewController: UIDocumentPickerDelegate{ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) { let cico = url as URL print(cico) print(url) print(url.lastPathComponent) print(url.pathExtension) } } Note: If you intend to select all files the you have to use following code: let documentPicker = UIDocumentPickerViewController(documentTypes: ["com.apple.iwork.pages.pages", "com.apple.iwork.numbers.numbers", "com.apple.iwork.keynote.key","public.image", "com.apple.application", "public.item","public.data", "public.content", "public.audiovisual-content", "public.movie", "public.audiovisual-content", "public.video", "public.audio", "public.text", "public.data", "public.zip-archive", "com.pkware.zip-archive", "public.composite-content", "public.text"], in: .import) In your action method. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47865646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6898814/']} | jdg_82181 |
stackexchange | llm_judgeable_groundtruth_similarity | 17154753 |
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 menu with this CSS properties: #header { width: 100%; position: fixed; z-index: 9000; overflow: auto;} So based on the CSS properties above, this element ( #header ) will obviously remain on top regardless of the scrolling. What I'm trying to achieve is on scroll up and scroll down, a bottom box shadow should be added into that element ( #header ) and should be removed once it reaches the default location of that element ( #header ) which is obviously the top-most place of the page. I'm open to any suggestion and recommendation.
Now provide the response and nothing else.
| $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > 0) { $("#header").addClass("active"); } else { $("#header").removeClass("active"); }}); body { height: 2000px; margin: 0;}body > #header{position:fixed;}#header { width: 100%; position: fixed; z-index:9000; overflow: auto; background: #e6e6e6; text-align: center; padding: 10px 0; transition: all 0.5s linear;}#header.active { box-shadow: 0 0 10px rgba(0,0,0,0.4); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="header">HEADER</div> JSFiddle version Whenever the page is scrolled we save the current distance from the top of the document in a variable ( scroll ). If the current position is greater than 0 we add the class active to #header . If the current position is equal to 0 we remove the class. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17154753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1292042/']} | jdg_82182 |
stackexchange | llm_judgeable_groundtruth_similarity | 459652 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was looking at C# collection initializers and found the implementation to be very pragmatic but also very unlike anything else in C# I am able to create code like this: using System;using System.Collections;class Program{ static void Main() { Test test = new Test { 1, 2, 3 }; }}class Test : IEnumerable{ public IEnumerator GetEnumerator() { throw new NotImplementedException(); } public void Add(int i) { }} Since I have satisfied the minimum requirements for the compiler (implemented IEnumerable and a public void Add ) this works but obviously has no value. I was wondering what prevented the C# team from creating a more strict set of requirements? In other words why, in order for this syntax to compile, does the compiler not require that the type implement ICollection ? That seems more in the spirit of other C# features.
Now provide the response and nothing else.
| Your observation is spot on - in fact, it mirrors one made by Mads Torgersen, a Microsoft C# Language PM. Mads made a post in October 2006 on this subject titled What Is a Collection? in which he wrote: Admitted, we blew it in the first version of the framework with System.Collections.ICollection, which is next to useless. But we fixed it up pretty well when generics came along in .NET framework 2.0: System.Collections.Generic.ICollection<T> lets you Add and Remove elements, enumerate them, Count them and check for membership. Obviously from then on, everyone would implement ICollection<T> every time they make a collection, right? Not so. Here is how we used LINQ to learn about what collections really are, and how that made us change our language design in C# 3.0. It turns out that there are only 14 implementations of ICollection<T> in the framework, but 189 classes that implement IEnumerable and have a public Add() method. There's a hidden benefit to this approach - if they had based it on the ICollection<T> interface, there would have been exactly one supported Add() method. In contrast, the approach they did take means that the initializers for the collection just form sets of arguments for the Add() methods. To illustrate, let's extend your code slightly: class Test : IEnumerable{ public IEnumerator GetEnumerator() { throw new NotImplementedException(); } public void Add(int i) { } public void Add(int i, string s) { }} You can now write this: class Program{ static void Main() { Test test = new Test { 1, { 2, "two" }, 3 }; }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/459652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34211/']} | jdg_82183 |
stackexchange | llm_judgeable_groundtruth_similarity | 1076802 |
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 wrote this PHP code to implement the Flesch-Kincaid Readability Score as a function: function readability($text) { $total_sentences = 1; // one full stop = two sentences => start with 1 $punctuation_marks = array('.', '?', '!', ':'); foreach ($punctuation_marks as $punctuation_mark) { $total_sentences += substr_count($text, $punctuation_mark); } $total_words = str_word_count($text); $total_syllable = 3; // assuming this value since I don't know how to count them $score = 206.835-(1.015*$total_words/$total_sentences)-(84.6*$total_syllables/$total_words); return $score;} Do you have suggestions how to improve the code? Is it correct? Will it work? I hope you can help me. Thanks in advance!
Now provide the response and nothing else.
| The code looks fine as far as a heuristic goes. Here are some points to consider that make the items you need to calculate considerably difficult for a machine: What is a sentence? Seriously, what is a sentence? We have periods, but they can also be used for Ph.D., e.g., i.e., Y.M.C.A., and other non-sentence-final purposes. When you consider exclamation points, question marks, and ellipses, you're really doing yourself a disservice by assuming a period will do the trick. I've looked at this problem before, and if you really want a more reliable count of sentences in real text, you'll need to parse the text. This can be computationally intensive, time-consuming, and hard to find free resources for. In the end, you still have to worry about the error rate of the particular parser implementation. However, only full parsing will tell you what's a sentence and what's just a period's other many uses. Furthermore, if you're using text 'in the wild' -- such as, say, HTML -- you're going to also have to worry about sentences ending not with punctuation but with tag endings. For instance, many sites don't add punctuation to h1 and h2 tags, but they're clearly different sentences or phrases. Syllables aren't something we should be approximating This is a major hallmark of this readability heuristic, and it's one that makes it the most difficult to implement. Computational analysis of syllable count in a work requires the assumption that the assumed reader speaks in the same dialect as whatever your syllable count generator is being trained on. How sounds fall around a syllable is actual a major part of what makes accents accents. If you don't believe me, try visiting Jamaica sometime. What this means it that even if a human were to do the calculations for this by hand, it would still be a dialect-specific score. What is a word? Not to wax psycholingusitic in the slightest, but you will find that space-separated words and what are conceptualized as words to a speaker are quite different. This will make the concept of a computable readability score somewhat questionable. So in the end, I can answer your question of 'will it work'. If you're looking to take a piece of text and display this readability score among other metrics to offer some kind of conceivable added value, the discerning user will not bring up all of these questions. If you are trying to do something scientific, or even something pedagogical (as this score and those like it were ultimately intended), I wouldn't really bother. In fact, if you're going to use this to make any kind of suggestions to a user about content that they have generated, I would be extremely hesitant. A better way to measure reading difficulty of a text would more likely be something having to do with the ratio of low-frequency words to high-frequency words along with the number of hapax legomena in the text. But I wouldn't pursue actually coming up with a heuristic like this, because it would be very difficult to empirically test anything like it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1076802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89818/']} | jdg_82184 |
stackexchange | llm_judgeable_groundtruth_similarity | 3574 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Can one get drunk with Vodka vapour using a humidifier ? As it was shown in a Simpsons episode.
Now provide the response and nothing else.
| Edit: Wow, I hate to do this after being accepted, but I need to change my answer! Vartec made the fantastic point that I was considering one had to get the entire amount of alcohol in a shot into one's blood stream. He is correct that I completely goofed on the amounnt and should have focused on Blood Alcohol Content (BAC), not how much one usually has to ingest to get drunk. If we keep the rest constant below, assuming all alcohol inhaled is absorbed, we just need the point at which there are ~5mL of alcohol in the blood (assuming an average total blood volume of 5L). With this adjustment, this method becomes incredibly more possible. Again, my apologies for the whiplash. TL;DR: If one perfectly vaporized 750 mL of 80 proof liquor (40% alcohol), one could achieve a BAC of 0.1 after ~900 respirations (45-75min) in a small room assuming that no alcohol escapes. Here goes... Assume a room of 3m x 3m x 3m (27m 3 ) Nebulize a 750 mL bottle of vodka (assume immediate/complete/uniform dispersion) At 40% alcohol, this means there are 300 mL of alcohol vapor in the air A standard shot is 1.5 fluid ounces, or ~44 mL, and let's say that if one can breath in 2 shots (88 mL), inebriation will be experienced We'll also assume that all alcohol breathed will be absorbed by the lungs The volume of an average human breath size is 500 mL ( SOURCE ) 1 mL = 0.001 L = 10 -6 m 3 "Drunk" is a blood alcohol content of 0.1 (0.1% of the blood is alcohol) The average human blood volume is 5L; "drunk" is when the blood contains 5mL of alcohol So, now we'll use the size of a breath, and concentration of alcohol in the air to determine the amount of vodka absorbed over time. We'll assume that the room is essentially sealed such that no alcohol vapor is removed. I won't drag this out. I ran such breath iterations in an Excel formula like so: Alc (mL) Air (m^3) Alc in Air (%) Alc in breath (mL) Air in breath (mL)300.00 27.000 0.00111% 0.00556 499.99299.99 27.000 0.00111% 0.00556 499.99299.99 27.000 0.00111% 0.00556 499.99 It pretty much just keeps going like that (the volume of alcohol is so small that it barely changes anything through time). For the formulas: Alc (mL): Alcohol in the air. Each cell subtracts the alcohol breathed from the previous volume that was present. The second value, for example, is subtracting the breathed amount of 0.00556 mL from the initial contents of 300 mL Air (m^3): Just subtracts the current alcohol content from 27 m^3 total room volume Alc in Air (%): divides the alcohol by air in room to get a percent content value Alc in breath (mL): 500mL breath volume * current alcohol percent Air in breath (mL): 500mL breath volume * (1 - current alcohol percent) Since the amount of alcohol is fairly small, the change over time is also extremely small. Thus, we can estimate that each breath will bring in 0.00556mL of alcohol into the system. To achieve drunkenness, one would need to respirate 5mL / (0.00556mL / respiration) = ~900 times. This would take 45-75min based on 12-20 respirations per minute. To decrease time, one could reduce the size of the room, or atomize more alcohol. The content will scale linearly, so using two bottles of vodka will take only half the time. Final caveat: This has all been theoretical, and I'm not sure how efficient the lungs would be at absorbing alcohol. I can find sources that give a rate of 25% for oxygen extraction from air, so this would have to be figured in as well. If the rate were only 25% for alcohol, it would take 4x as long as above, or 3-5 hours. Using more bottles would reduce that proportionally. Typical rooms also aren't sealed, and thus alcohol is going to diffuse to the outside air and reduce the concentration. This rate will vary by the room, but may have a huge effect on how this works. Reducing the room volume or creating a tent of sorts will help this. My conclusion? I originally found this nearly impossible due to my faulty assumption that one needed to breath the same amount as one needed to drink. Complete credit goes to vartec for this correction which, very surprisingly , swung the answer completely in the other direction. It now appears quite possible. | {} | {'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/3574', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/1708/']} | jdg_82185 |
stackexchange | llm_judgeable_groundtruth_similarity | 18624296 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I want to set a for loop running but don't want to block the execution, obviously I can put the for loop in a function f and call go f and continue with my life, but I was curious if there is a way to call go for directly, something like: fmt.Println("We are doing something")//line below is my questiongo for i := 1; i < 10; i ++ { fmt.Println("stuff running in background")} // life goes onfmt.Println("c'est la vie")
Now provide the response and nothing else.
| If you want to run each loop in the background, nest the goroutine in the loop and use the sync.WaitGroup structure. import "sync"fmt.Println("We are doing something")//line below is my questionwg := sync.WaitGroup{}// Ensure all routines finish before returningdefer wg.Wait()for i := 1; i < 10; i ++ { wg.Add(1) go func() { defer wg.Done() fmt.Println("stuff running in background") }()}// life goes onfmt.Println("c'est la vie") | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18624296', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/487855/']} | jdg_82186 |
stackexchange | llm_judgeable_groundtruth_similarity | 29027295 |
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 map viewer project and used openlayers 2 before this. Now I have to use OpenLayers 3 and map viewer app should support many different projections because I have wms and wfs layers from different sources and projections. I've found examples that use openlayers2 and proj4js. But I couldn't find explicit example for using ol3 and proj4js. What is your suggestion?
Now provide the response and nothing else.
| It seems that sometimes, like when using OpenLayers 3 and proj4 in Angular 2 using webpack, one needs to explicitly tell OL3 where to find it: import * as proj4 from "proj4";import * as ol from "openlayers";...ol.proj.setProj4(proj4); When all is fine, then after defining a projection, ol.proj.get should return it: proj4.defs("EPSG:28992", "...");if (!ol.proj.get('EPSG:28992')) { console.error("Failed to register projection in OpenLayers"); ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29027295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2682134/']} | jdg_82187 |
stackexchange | llm_judgeable_groundtruth_similarity | 1642411 |
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:
For students in a first course in analysis or topology, proving that certain function are continuous can be very tricky. However, some proofs which are difficult for students to prove using the $\epsilon-\delta$ definition of continuity are much easier to prove using the topological definition that the pre-image of every open set be open. For example, it is much easier for students to prove that $f(x)=x^2$ is continuous using open sets rather than $\epsilon-\delta$. One particularly challenging proof is showing that multiplication $\cdot \colon \mathbb{R}\times \mathbb{R}\to \mathbb{R}$ is continuous. Is anyone aware of a slick way to prove multiplication is continuous using open sets? Any attempt I make seems to more or less be just as complex as the $\epsilon-\delta$ definition.
Now provide the response and nothing else.
| Not sure if you would be interested in this approach, but it is easy to prove with the sequence definition of continuity. Suppose $x_n \to x$ and $y_n \to y$, then$$x_ny_n = (x + (x_n-x))(y + (y_n-y)) = xy + x(y_n-y) + y(x_n-x) + (x_n-x)(y_n-y)$$so that by triangle inequality$$|x_ny_n - xy| \leq |x| |y_n-y| + |y||x_n-x| + |x_n-x||y_n-y|$$since $x_n \to x, y_n \to y$ all three terms on the right tend to zero. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1642411', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31653/']} | jdg_82188 |
stackexchange | llm_judgeable_groundtruth_similarity | 5698473 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some code that has the following format: function myfunc1 () { ... jquery.bind('click', myfunc2) ... }function myfunc2 () { ... }... Yes, the functions are global, but it's ok since I'm writing within a google chrome extension content script, so it's sandboxed. Now, I'm trying to minify and obfuscate the code. I've tried YUI Compressor and the Google Closure compiler. The problem is, I can't figure out how to minify/obfuscate the global function names. With YUI it doesn't minify the global variables in case they're called externally. With Closure in advanced mode, it seems like it can rename the global variables, however I'm having problem with the dead code removal. Most functions appear to be dead since they depend on DOM interaction and event handling and aren't called directly. So any idea on how to minify these global variables? Do I need to just write a script to do some regex replacement? I'm also open to refactoring my code if that would fit the minification pattern better (for example, adding to a closure or whatnot)
Now provide the response and nothing else.
| Minifiers won't munge public/global names since, for many scripts, that will destroy the availability and predictability of the public API. Since you don't need to maintain a public API, making them "private" by wrapping them in a closure function may be enough: (function () { function myfunc1 () { ... jquery.bind('click', myfunc2) ... } function myfunc2 () { ... ...})(); But, even then, no guarantees as it's very much at the discretion of the minifier's authors. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5698473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598093/']} | jdg_82189 |
stackexchange | llm_judgeable_groundtruth_similarity | 924431 |
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:
We define a module to be an abelian group $M$ together with a ring action $R \times M \to M$ that satisfies certain properties. Q: Why do we require that $M$ is abelian? I know that modules generalize vector spaces and abelian groups and, in a sense, representations. But why not take it further and relax the underlying group? I'm curious about whether this definition simply produces a more manageable collection of objects, et cetera. On a related note, what can be said when $M$ is not abelian?
Now provide the response and nothing else.
| Let $R$ be a ring with $1$. If $M$ is a group, written multiplicatively, equipped with an $R$-action, then, for any $x,y\in M$, $(xy)^2 = (1+1)\cdot (xy) = [(1+1)\cdot x][(1+1)\cdot y] = x^2 y^2$. So $yx=xy$, and $M$ is abelian. If $R$ doesn't have a $1$, then we conclude only that $rM$ is abelian for all $r\in R$. In this case, we might be able to define noncommutative modules, but they are likely to be very awkward. For example, let $R=\{0,\epsilon\}$ with $\epsilon+\epsilon=\epsilon^2=0$, which is the simplest non-unital ring. Then a noncommutative $R$-module can be described by a group $G$, a normal subgroup $N\lhd G$, and an abelian subgroup $A \leq N$ isomorphic to $G/N$ (the quotient $G\to G/N$ is the multiplication map $\epsilon\cdot: G\to \epsilon G$). Understanding the ways this can happen is very subtle, probably intractable, and certainly only tangentially related to the study of $R$. Another perspective: a module is just a quotient of a free module. So if we want noncommutative modules, then we want to consider, for example, $R * R$, the amalgamated product, to be a module over $R$. But $r(R*R)=(rR)*(rR)$ is never abelian unless $rR=0$, so this is only an $R$-module when $R$ has trivial multiplication. In short, addition should always be commutative. If I really wanted to think of a non-abelian group as a module over something, I would probably work over a semigroup $S$, and define an $S$-module to be a group $G$ and a semigroup homomorphism $S\to\operatorname{End}(G)$ (one way to define an $R$-module is an abelian group $M$ with a homomorphism of rings $R\to \operatorname{End}(M)$). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/924431', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/153841/']} | jdg_82190 |
stackexchange | llm_judgeable_groundtruth_similarity | 23328383 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
$query = "SELECT Subjects FROM instructors";$rows = mysqli_query($con,$query);{ if($rows) { $count = 0; while($row = mysqli_fetch_array($rows)) { $id = 'Name'.strval($count); // array_push($results,$row); $results[] = array($id => $row['Subjects']); $count = $count + 1; } echo json_encode($results); } else { echo "Something wrong"; }} This outputs [{"Name0":"lore"},{"Name1":"ipsum"}] Now in JS, I would like to get these names. $(document).ready(function(){$.ajax({ url: "get_subs.php", dataType :"JSON", success : function(data) { alert(data); } })}); But this only prints 0 => [object Object] I also tried alert(data.Name0); But that also alerts the same thing.What am I doing wrong?
Now provide the response and nothing else.
| You need to set up the PendingIntent which is used to build Notification , to start a fresh task, and provide the PendingIntent with a back stack to achieve the application's normal Up behavior. Intent resultIntent = new Intent(this, SecondActivity.class);TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);// All the parents of SecondActivity will be added to task stack.stackBuilder.addParentStack(SecondActivity.class);// Add a SecondActivity intent to the task stack.stackBuilder.addNextIntent(resultIntent);// Obtain a PendingIntent for launching the task constructed by this builder.PendingIntent pendingIntent = stackBuilder.getPendingIntent(REQUEST_CODE, PendingIntent.FLAG_UPDATE_CURRENT);NotificationManager manager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);Notification notification = new Notification.Builder(this) .setContentTitle("My Notification") .setContentText("Notification content") .setSmallIcon(android.R.drawable.ic_menu_view) .setContentIntent(pendingIntent) .build();manager.notify(NOTIFICATION_ID, notification); Please read the Android official documentation on Preserving Navigation when Starting an Activity . It recommends the above approach. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23328383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2643846/']} | jdg_82191 |
stackexchange | llm_judgeable_groundtruth_similarity | 2790828 |
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 pickle a big class and getting TypeError: can't pickle module objects despite looking around the web, I can't exactly figure out what this means. and I'm not sure which module object is causing the trouble. is there a way to find the culprit? the stack trace doesn't seem to indicate anything.
Now provide the response and nothing else.
| I can reproduce the error message this way: import cPickleclass Foo(object): def __init__(self): self.mod=cPicklefoo=Foo()with file('/tmp/test.out', 'w') as f: cPickle.dump(foo, f) # TypeError: can't pickle module objects Do you have a class attribute that references a module? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2790828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9871/']} | jdg_82192 |
stackexchange | llm_judgeable_groundtruth_similarity | 26557873 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible in Spark to implement '.combinations' function from scala collections? /** Iterates over combinations. * * @return An Iterator which traverses the possible n-element combinations of this $coll. * @example `"abbbc".combinations(2) = Iterator(ab, ac, bb, bc)` */ For example how can I get from RDD[X] to RDD[List[X]] or RDD[(X,X)] for combinations of size = 2. And lets assume that all values in RDD are unique.
Now provide the response and nothing else.
| Cartesian product and combinations are two different things, the cartesian product will create an RDD of size rdd.size() ^ 2 and combinations will create an RDD of size rdd.size() choose 2 val rdd = sc.parallelize(1 to 5)val combinations = rdd.cartesian(rdd).filter{ case (a,b) => a < b }`.combinations.collect() Note this will only work if an ordering is defined on the elements of the list, since we use < . This one only works for choosing two but can easily be extended by making sure the relationship a < b for all a and b in the sequence | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26557873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1177991/']} | jdg_82193 |
stackexchange | llm_judgeable_groundtruth_similarity | 42837447 |
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 classes in PS with WinSCP PowerShell Assembly. In one of the methods I'm using various types from WinSCP. This works fine as long as I already have the assembly added - however, because of the way PowerShell reads the script when using classes (I assume?), an error is thrown before the assembly could be loaded. In fact, even if I put a Write-Host at the top, it will not load. Is there any way of forcing something to run before the rest of the file is parsed? Transfer() { $this.Logger = [Logger]::new() try { Add-Type -Path $this.Paths.WinSCP $ConnectionType = $this.FtpSettings.Protocol.ToString() $SessionOptions = New-Object WinSCP.SessionOptions -Property @{ Protocol = [WinSCP.Protocol]::$ConnectionType HostName = $this.FtpSettings.Server UserName = $this.FtpSettings.Username Password = $this.FtpSettings.Password } Results in an error like this: Protocol = [WinSCP.Protocol]::$ConnectionTypeUnable to find type [WinSCP.Protocol]. But it doesn't matter where I load the assembly. Even if I put the Add-Type cmdlet on the topmost line with a direct path to WinSCPnet.dll , it won't load - it detects the missing types before running anything, it seems.
Now provide the response and nothing else.
| As you've discovered, PowerShell refuses to run scripts that contains class definitions that reference then-unavailable (not-yet-loaded) types - the script-parsing stage fails. As of PSv5.1, even a using assembly statement at the top of a script does not help in this case, because in your case the type is referenced in the context of a PS class definition - this may get fixed in PowerShell Core , however ; the required work, along with other class-related issues, is being tracked in GitHub issue #6652 . The proper solution is to create a script module ( *.psm1 ) whose associated manifest ( *.psd1 ) declares the assembly containing the referenced types a prerequisite , via the RequiredAssemblies key. See alternative solution at the bottom if using modules is not an option. Here's a simplified walk-through : Create test module tm as follows : Create module folder ./tm and manifest ( *.psd1 ) in it: # Create module folder (remove a preexisting ./tm folder if this fails). $null = New-Item -Type Directory -ErrorAction Stop ./tm # Create manifest file that declares the WinSCP assembly a prerequisite. # Modify the path to the assembly as needed; you may specify a relative path, but # note that the path must not contain variable references (e.g., $HOME). New-ModuleManifest ./tm/tm.psd1 -RootModule tm.psm1 ` -RequiredAssemblies C:\path\to\WinSCPnet.dll Create the script module file ( *.psm1 ) in the module folder: Create file ./tm/tm.psm1 with your class definition; e.g.: class Foo { # As a simple example, return the full name of the WinSCP type. [string] Bar() { return [WinSCP.Protocol].FullName } } Note: In the real world, modules are usually placed in one of the standard locations defined in $env:PSMODULEPATH , so that the module can be referenced by name only, without needing to specify a (relative) path. Use the module : PS> using module ./tm; [Foo]::new().Bar()WinSCP.Protocol The using module statement imports the module and - unlike Import-Module -also makes the class defined in the module available to the current session. Since importing the module implicitly loaded the WinSCP assembly thanks to the RequiredAssemblies key in the module manifest, instantiating class Foo , which references the assembly's types, succeeded. If you need to determine the path to the dependent assembly dynamically in order to load it or even to ad-hoc-compile one (in which case use of a RequiredAssemblies manifest entry isn't an option), you should be able to use the approach recommended in Justin Grote's helpful answer - i.e., to use a ScriptsToProcess manifest entry that points to a *.ps1 script that calls Add-Type to dynamically load dependent assemblies before the script module ( *.psm1 ) is loaded - but this doesn't actually work as of PowerShell 7.2.0-preview.9 : while the definition of the class in the *.psm1 file relying on the dependent assembly's types succeeds, the caller doesn't see the class until a script with a using module ./tm statement is executed a second time: Create a sample module: # Create module folder (remove a preexisting ./tm folder if this fails).$null = New-Item -Type Directory -ErrorAction Stop ./tm# Create a helper script that loads the dependent# assembly.# In this simple example, the assembly is created dynamically,# with a type [demo.FooHelper]@'Add-Type @"namespace demo { public class FooHelper { }}"@'@ > ./tm/loadAssemblies.ps1# Create the root script module.# Note how the [Foo] class definition references the# [demo.FooHelper] type created in the loadAssemblies.ps1 script.@'class Foo { # Simply return the full name of the dependent type. [string] Bar() { return [demo.FooHelper].FullName }}'@ > ./tm/tm.psm1# Create the manifest file, designating loadAssemblies.ps1# as the script to run (in the caller's scope) before the# root module is parsed.New-ModuleManifest ./tm/tm.psd1 -RootModule tm.psm1 -ScriptsToProcess loadAssemblies.ps1 Now, still as of PowerShell 7.2.0-preview.9, trying to use the module's [Foo] class inexplicably succeeds only after calling using module ./tm twice - which you cannot do in a single script, rendering this approach useless for now: # As of PowerShell 7.2.0-preview.9:# !! First attempt FAILS:PS> using module ./tm; [Foo]::new().Bar()InvalidOperation: Unable to find type [Foo]# Second attempt: OKPS> using module ./tm; [Foo]::new().Bar()demo.FooHelper The problem is a known one , as it turns out, and dates back to 2017 - see GitHub issue #2962 If your use case doesn't allow the use of modules : In a pinch, you can use Invoke-Expression , but note that it's generally better to avoid Invoke-Expression in the interest of robustness and so as to avoid security risks [1] . # Adjust this path as needed.Add-Type -LiteralPath C:\path\to\WinSCPnet.dll# By placing the class definition in a string that is invoked at *runtime*# via Invoke-Expression, *after* the WinSCP assembly has been loaded, the# class definition succeeds.Invoke-Expression @'class Foo { # Simply return the full name of the WinSCP type. [string] Bar() { return [WinSCP.Protocol].FullName }}'@[Foo]::new().Bar() Alternatively , use a two -script approach : A main script that loads the dependent assemblies, which then dot-sources a second script that contains the class definitions relying on the types from the dependent assemblies. This approach is demonstrated in Takophiliac's helpful answer . [1] It's not a concern in this case, but generally, given that Invoke-Expression can invoke any command stored in a string, applying it to strings not fully under your control can result in the execution of malicious commands - see this answer for more information.This caveat applies to other language analogously, such as to Bash's built-in eval command. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42837447', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1717380/']} | jdg_82194 |
stackexchange | llm_judgeable_groundtruth_similarity | 1574830 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $m$ be a positive integer and $n$ a nonnegative integer. Prove that $$(n!)\cdot(m!)^n|(mn)!$$ I can prove it using Legendre's Formula , but I have to use the lemma that $$ \dfrac{\displaystyle\left(\sum_{i=1}^na_i\right)!}{\displaystyle\prod_{i=1}^na_i!} \in \mathbb{N} $$ I believe that it can be proved using the lemma, since in this answer of Qiaochu Yuan he has mentioned so at the end of his answer. Any help will be appreciated. Thanks.
Now provide the response and nothing else.
| Consider you have $mn$ balls with $n$ different colors and $m$ balls of each color. The number of possible arrangements is $$(mn)!\over (m!)^n$$. However each arrangement has $n!$ "symmetric arrangements", that is, if we exchange color between whole groups we obtain a symmetric arrangement. I.E. for example if we have three color R,G,B, then $RGRBGB$ and $GRGBRB$ are symmetric arrangement by exchanging colors $R$ and $G$. Thus $(mn)!\over (m!)^n$ is a multiple of $n!$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1574830', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/130750/']} | jdg_82195 |
stackexchange | llm_judgeable_groundtruth_similarity | 274089 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm developing software that i want to license under the MIT License. My software uses libraries licensed under the GPL. I'm NOT recompiling, building, or modifying the Library but I am linking to it. Am i allowed to distribute the package under the MIT license or do i have to distribute the package under the GPL? The library is actually dual licensed under CDDL 1.1 and GPLv2 with Classpath Exception. Take a look here: https://jsonp.java.net/license.html
Now provide the response and nothing else.
| Does your library depend on the GPL libraries for its proper functioning? If it does, then you have created a derived work, and your license must also be GPL. If your library does not depend on the GPL libraries for its proper functioning, and losing the GPL libraries does not substantially impair your library from working properly, then you should be able to dual-license it. *I am not a lawyer, and I do not play one on TV. Void where prohibited. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/274089', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/168947/']} | jdg_82196 |
stackexchange | llm_judgeable_groundtruth_similarity | 10938 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Usually the filters for detecting edges have the sum of all the values in the filter matrix equal to 0.For example: [-1 -2 -1, 0 0 0, 1 2 1]. Why is it so ?
Now provide the response and nothing else.
| An edge detection filter is, by definition, a high-pass filter. It is looking for quick changes (i.e. high frequencies), not slow trends. Thus, a good edge detection filter will have a response of 0 at DC. A FIR filter whose taps sum to 0 has a response of 0 at DC. | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/10938', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/1115/']} | jdg_82197 |
stackexchange | llm_judgeable_groundtruth_similarity | 93659 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I suspect this has been asked here before, but I didn't find anything using Search. Why is Newton's second law only second-order in position? For instance, could there exist higher-order masses $m_i$ with $$F(x) = m\ddot{x} + \sum_{i=3}^{\infty} m_i x^{(i)}?$$ Are there theoretical reasons why $m_i$ must be exactly zero for $i>2$? If not, if these masses existed but were extremely small, would we be able to tell experimentally (e.g. by observing galactic motion)?
Now provide the response and nothing else.
| I think Newton's first law, linearity of motion, and the time-reversal symmetry strongly constrain the form of Newton's second law. Generically, the linear relation between the position and the force is given by $$F = \beta_0 x+ \beta_1 \frac{dx}{dt} + \beta_2 \frac{d^2x}{dt^2} + \beta_3 \frac{d^3x}{dt^3}+\cdots.$$ The time-reversal symmetry demands that all odd derivatives vanish, $\beta_{2k+1} = 0$ for $k = 0,1,2\cdots$. The spatial homogeneity demands $\beta_0 = 0$. Therefore, $$F = \beta_2 \frac{d^2x}{dt^2} + \beta_4 \frac{d^4x}{dt^4} + \cdots = \beta_2 a + \beta_4 \frac{d^2a}{dt^2}+\cdots.$$ Here $a$ is the acceleration. The first law demands that, when $F=0$, the only solution is the trivial solution $a=0$. We see that, if all higher coefficients $\beta_4, \beta_6, \cdots$ are not zero, there will be other solutions. Thus, the only possible form is $$F = \beta_2 \frac{d^2x}{dt^2}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/93659', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2617/']} | jdg_82198 |
stackexchange | llm_judgeable_groundtruth_similarity | 5366155 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can you select the most frequently occurring values in a MySQL database? Assuming I have a num field, with these rows: 1, 1, 3, 1, 1, 17, 12, 1, 3, 17, 3 If I wanted to find the three most frequently occurring values, 1, 3, and 17, how would I go about doing this (and getting a count)? Would the proper method be to SELECT UNIQUE and do a tally for each individual value? Is there a more efficient method? This seems like it'd fail for larger data sets. Thanks for the help! This is in PHP, with a MySQL database.
Now provide the response and nothing else.
| Something like this should work: SELECT num, COUNT(num) AS ctFROM yourtableGROUP BY numORDER BY ct DESC This tells MySQL to group the results by the num column. By also also selecting COUNT(num) as the number of rows found for each num value, we can then issue the ORDER BY which will order the results according to how many rows each value of num has. With these values in the table: 1, 1, 3, 1, 1, 17, 12, 1, 3, 17, 3 The results would be: num | ct============ 1 | 5 3 | 3 17 | 2 12 | 1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5366155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113419/']} | jdg_82199 |
stackexchange | llm_judgeable_groundtruth_similarity | 52603131 |
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 move data from a table in PostgreSQL table to a Hive table on HDFS. To do that, I came up with the following code: val conf = new SparkConf().setAppName("Spark-JDBC").set("spark.executor.heartbeatInterval","120s").set("spark.network.timeout","12000s").set("spark.sql.inMemoryColumnarStorage.compressed", "true").set("spark.sql.orc.filterPushdown","true").set("spark.serializer", "org.apache.spark.serializer.KryoSerializer").set("spark.kryoserializer.buffer.max","512m").set("spark.serializer", classOf[org.apache.spark.serializer.KryoSerializer].getName).set("spark.streaming.stopGracefullyOnShutdown","true").set("spark.yarn.driver.memoryOverhead","7168").set("spark.yarn.executor.memoryOverhead","7168").set("spark.sql.shuffle.partitions", "61").set("spark.default.parallelism", "60").set("spark.memory.storageFraction","0.5").set("spark.memory.fraction","0.6").set("spark.memory.offHeap.enabled","true").set("spark.memory.offHeap.size","16g").set("spark.dynamicAllocation.enabled", "false").set("spark.dynamicAllocation.enabled","true").set("spark.shuffle.service.enabled","true") val spark = SparkSession.builder().config(conf).master("yarn").enableHiveSupport().config("hive.exec.dynamic.partition", "true").config("hive.exec.dynamic.partition.mode", "nonstrict").getOrCreate() def prepareFinalDF(splitColumns:List[String], textList: ListBuffer[String], allColumns:String, dataMapper:Map[String, String], partition_columns:Array[String], spark:SparkSession): DataFrame = { val colList = allColumns.split(",").toList val (partCols, npartCols) = colList.partition(p => partition_columns.contains(p.takeWhile(x => x != ' '))) val queryCols = npartCols.mkString(",") + ", 0 as " + flagCol + "," + partCols.reverse.mkString(",") val execQuery = s"select ${allColumns}, 0 as ${flagCol} from schema.tablename where period_year='2017' and period_num='12'" val yearDF = spark.read.format("jdbc").option("url", connectionUrl).option("dbtable", s"(${execQuery}) as year2017") .option("user", devUserName).option("password", devPassword) .option("partitionColumn","cast_id") .option("lowerBound", 1).option("upperBound", 100000) .option("numPartitions",70).load() val totalCols:List[String] = splitColumns ++ textList val cdt = new ChangeDataTypes(totalCols, dataMapper) hiveDataTypes = cdt.gpDetails() val fc = prepareHiveTableSchema(hiveDataTypes, partition_columns) val allColsOrdered = yearDF.columns.diff(partition_columns) ++ partition_columns val allCols = allColsOrdered.map(colname => org.apache.spark.sql.functions.col(colname)) val resultDF = yearDF.select(allCols:_*) val stringColumns = resultDF.schema.fields.filter(x => x.dataType == StringType).map(s => s.name) val finalDF = stringColumns.foldLeft(resultDF) { (tempDF, colName) => tempDF.withColumn(colName, regexp_replace(regexp_replace(col(colName), "[\r\n]+", " "), "[\t]+"," ")) } finalDF } val dataDF = prepareFinalDF(splitColumns, textList, allColumns, dataMapper, partition_columns, spark) val dataDFPart = dataDF.repartition(30) dataDFPart.createOrReplaceTempView("preparedDF") spark.sql("set hive.exec.dynamic.partition.mode=nonstrict") spark.sql("set hive.exec.dynamic.partition=true") spark.sql(s"INSERT OVERWRITE TABLE schema.hivetable PARTITION(${prtn_String_columns}) select * from preparedDF") The data is inserted into the hive table dynamically partitioned based on prtn_String_columns: source_system_name, period_year, period_num Spark-submit used: SPARK_MAJOR_VERSION=2 spark-submit --conf spark.ui.port=4090 --driver-class-path /home/fdlhdpetl/jars/postgresql-42.1.4.jar --jars /home/fdlhdpetl/jars/postgresql-42.1.4.jar --num-executors 80 --executor-cores 5 --executor-memory 50G --driver-memory 20G --driver-cores 3 --class com.partition.source.YearPartition splinter_2.11-0.1.jar --master=yarn --deploy-mode=cluster --keytab /home/fdlhdpetl/fdlhdpetl.keytab --principal [email protected] --files /usr/hdp/current/spark2-client/conf/hive-site.xml,testconnection.properties --name Splinter --conf spark.executor.extraClassPath=/home/fdlhdpetl/jars/postgresql-42.1.4.jar The following error messages are generated in the executor logs: Container exited with a non-zero exit code 143.Killed by external signal18/10/03 15:37:24 ERROR SparkUncaughtExceptionHandler: Uncaught exception in thread Thread[SIGTERM handler,9,system]java.lang.OutOfMemoryError: Java heap space at java.util.zip.InflaterInputStream.<init>(InflaterInputStream.java:88) at java.util.zip.ZipFile$ZipFileInflaterInputStream.<init>(ZipFile.java:393) at java.util.zip.ZipFile.getInputStream(ZipFile.java:374) at java.util.jar.JarFile.getManifestFromReference(JarFile.java:199) at java.util.jar.JarFile.getManifest(JarFile.java:180) at sun.misc.URLClassPath$JarLoader$2.getManifest(URLClassPath.java:944) at java.net.URLClassLoader.defineClass(URLClassLoader.java:450) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at org.apache.spark.util.SignalUtils$ActionHandler.handle(SignalUtils.scala:99) at sun.misc.Signal$1.run(Signal.java:212) at java.lang.Thread.run(Thread.java:745) I see in the logs that the read is being executed properly with the given number of partitions as below: Scan JDBCRelation((select column_names from schema.tablename where period_year='2017' and period_num='12') as year2017) [numPartitions=50] Below is the state of executors in stages: The data is not being partitioned properly. One partition is smaller while the other one becomes huge. There is a skew problem here.While inserting the data into Hive table the job fails at the line: spark.sql(s"INSERT OVERWRITE TABLE schema.hivetable PARTITION(${prtn_String_columns}) select * from preparedDF") but I understand this is happening because of the data skew problem. I tried to increase number of executors, increasing the executor memory, driver memory, tried to just save as csv file instead of saving the dataframe into a Hive table but nothing affects the execution from giving the exception: java.lang.OutOfMemoryError: GC overhead limit exceeded Is there anything in the code that I need to correct ? Could anyone let me know how can I fix this problem ?
Now provide the response and nothing else.
| Determine how many partitions you need given the amount of input data and your cluster resources. As a rule of thumb it is better to keep partition input under 1GB unless strictly necessary. and strictly smaller than the block size limit. You've previously stated that you migrate 1TB of data values you use in different posts (5 - 70) are likely way to low to ensure smooth process. Try to use value which won't require further repartitioning . Know your data. Analyze the columns available in the the dataset to determine if there any columns with high cardinality and uniform distribution to be distributed among desired number of partitions. These are good candidates for an import process. Additionally you should determine an exact range of values. Aggregations with different centrality and skewness measure as well as histograms and basic counts-by-key are good exploration tools. For this part it is better to analyze data directly in the database, instead of fetching it to Spark. Depending on the RDBMS you might be able to use width_bucket (PostgreSQL, Oracle) or equivalent function to get a decent idea how data will be distributed in Spark after loading with partitionColumn , lowerBound , upperBound , numPartitons . s"""(SELECT width_bucket($partitionColum, $lowerBound, $upperBound, $numPartitons) AS bucket, COUNT(*)FROM tGROUP BY bucket) as tmp)""" If there are no columns which satisfy above criteria consider: Creating a custom one and exposing it via. a view. Hashes over multiple independent columns are usually good candidates. Please consult your database manual to determine functions that can be used here ( DBMS_CRYPTO in Oracle, pgcrypto in PostgreSQL)*. Using a set of independent columns which taken together provide high enough cardinality. Optionally, if you're going to write to a partitioned Hive table, you should consider including Hive partitioning columns. It might limit the number of files generated later. Prepare partitioning arguments If column selected or created in the previous steps is numeric ( or date / timestamp in Spark >= 2.4 ) provide it directly as the partitionColumn and use range values determined before to fill lowerBound and upperBound . If bound values don't reflect the properties of data ( min(col) for lowerBound , max(col) for upperBound ) it can result in a significant data skew so thread carefully. In the worst case scenario, when bounds don't cover the range of data, all records will be fetched by a single machine, making it no better than no partitioning at all. If column selected in the previous steps is categorical or is a set of columns generate a list of mutually exclusive predicates that fully cover the data, in a form that can be used in a SQL where clause. For example if you have a column A with values { a1 , a2 , a3 } and column B with values { b1 , b2 , b3 }: val predicates = for { a <- Seq("a1", "a2", "a3") b <- Seq("b1", "b2", "b3")} yield s"A = $a AND B = $b" Double check that conditions don't overlap and all combinations are covered. If these conditions are not satisfied you end up with duplicates or missing records respectively. Pass data as predicates argument to jdbc call. Note that the number of partitions will be equal exactly to the number of predicates. Put database in a read-only mode (any ongoing writes can cause data inconsistency. If possible you should lock database before you start the whole process, but if might be not possible, in your organization). If the number of partitions matches the desired output load data without repartition and dump directly to the sink, if not you can try to repartition following the same rules as in the step 1. If you still experience any problems make sure that you've properly configured Spark memory and GC options. If none of the above works: Consider dumping your data to a network / distributes storage using tools like COPY TO and read it directly from there. Note that or standard database utilities you will typically need a POSIX compliant file system, so HDFS usually won't do. The advantage of this approach is that you don't need to worry about the column properties, and there is no need for putting data in a read-only mode, to ensure consistency. Using dedicated bulk transfer tools, like Apache Sqoop, and reshaping data afterwards. * Don't use pseudocolumns - Pseudocolumn in Spark JDBC . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52603131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7119501/']} | jdg_82200 |
stackexchange | llm_judgeable_groundtruth_similarity | 24620393 |
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 connect Amazon's S3 files from my (localhost) Windows 8 machine running AppServ 2.5.10 (which includes Apache 2.2.8 , php 5.2.6 , mysql 5.0.51b and phpMyAdmin 2.10.3 ) using Amazon SDK for php. In order to be compatible with Amazon SDK's namespace feature, I replaced php with version 5.3.28 by downloading its zipped file and unzipped it. My php code works fine to access S3 file in Amazon EC2 but it failed in my Windows local host. However when I run the php srcipt to read Amazon S3 bucket file in Windows local host machine, I got SSL error as following: Fatal error: Uncaught exception 'Guzzle\Http\Exception\CurlException' with message '[curl] 60: SSL certificate problem: unable to get local issuer certificate [url] https://images-st.s3.amazonaws.com/us/123977_sale_red_car.png ' in C:\AppServ\www\ecity\vendor\guzzle\guzzle\src\Guzzle\Http\Curl\CurlMulti.php:342 Stack trace: #0 C:\AppServ\www\ecity\vendor\guzzle\guzzle\src\Guzzle\Http\Curl\CurlMulti.php(283): Guzzle\Http\Curl\CurlMulti->isCurlException(Object(Guzzle\Http\Message\Request), Object(Guzzle\Http\Curl\CurlHandle), Array) #1 C:\AppServ\www\ecity\vendor\guzzle\guzzle\src\Guzzle\Http\Curl\CurlMulti.php(248): Guzzle\Http\Curl\CurlMulti->processResponse(Object(Guzzle\Http\Message\Request), Object(Guzzle\Http\Curl\CurlHandle), Array) #2 C:\AppServ\www\ecity\vendor\guzzle\guzzle\src\Guzzle\Http\Curl\CurlMulti.php(231): Guzzle\Http\Curl\CurlMulti->processMessages() #3 C:\AppServ\www\ecity\vendor\guzzle\guzzle\src\Guzzle\Http\Curl\CurlMulti.php(215): Guzzle\Http\Curl\CurlMulti->executeHandles() #4 C:\AppServ\www\ecity\ven in C:\AppServ\www\ecity\vendor\aws\aws-sdk-php\src\Aws\Common\Client\AbstractClient.php on line 288 I download the certifate from http://curl.haxx.se/ca/cacert.pem and define it in php.ini as following: curl.cainfo = "C:\AppServ\cacert.pem" but I still got the same error. It seems php doesn't honor the curl.cainfo defined in php.ini . My php version is 5.3.28 according to localhost/phpinfo.php . I also checked the cainfo parameter to be correct as C:\AppServ\cacert.pem using echo ini_get( "curl.cainfo" ) ; in the php script. Php version higher than 5.3 shall support curl.cainfo in php.ini . In Windows' command line, I check curl behavior and it seems work fine. C:\Users\Jordan>curl https://s3-us-west-2.amazonaws.com/images-st/aaa.txt curl: (60) SSL certificate problem: unable to get local issuer certificate ......C:\Users\Jordan>curl --cacert C:\AppServ\cacert.crt https://s3-us-west-2.amazonaws.com/images-st/aaa.txt This is aaa.txt file. Stored in Amazon S3 bucket. Is it because I used Apache in Windows which doesn't match php 5.3.28 zip file I downloaded from http://windows.php.net/download/ VC9 x86 Thread Safe (2014-Jun-11 01:09:56) zip version. In my apache's httpd-ssl.conf file, I have the following setting even I use from local host in Windows 8. <VirtualHost _default_:443>DocumentRoot "C:/AppServ/www"ServerName localhost:443ServerAdmin [email protected] "C:/AppServ/Apache2.2/logs/error.log"TransferLog "C:/AppServ/Apache2.2/logs/access.log"SSLEngine onSSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULLSSLCertificateFile "C:/AppServ/Apache2.2/conf/mydomain.cert"SSLCertificateKeyFile "C:/AppServ/Apache2.2/conf/mydomain.key"<FilesMatch "\.(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars</FilesMatch><Directory "C:/Apache2.2/cgi-bin"> SSLOptions +StdEnvVars</Directory>BrowserMatch ".*MSIE.*" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0CustomLog "C:/AppServ/Apache2.2/logs/ssl_request.log" \ "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"</VirtualHost> Now I am wondering what is the problem and how to connect to Amazon S3 bucket files and RDS database without producing these curl cannot get local issuer certificate problems from my Windows 8 local host. Any advice?
Now provide the response and nothing else.
| As mentioned by Jeremy Lindblom in the comments, the solution for AWS SDK v2 is to set the ssl.certificate_authority option when instantiating the SDK: $aws = Aws\Common\Aws::factory(array( 'region' => 'us-west-2', 'ssl.certificate_authority' => '/path/to/updated/cacert.pem')); http://docs.aws.amazon.com/aws-sdk-php/guide/latest/faq.html#what-do-i-do-about-a-curl-ssl-certificate-error I'll add that this was changed in the AWS SDK v3 , here is the new method: $client = new DynamoDbClient([ 'region' => 'us-west-2', 'version' => 'latest', 'http' => [ 'verify' => '/path/to/my/cert.pem' ]]); http://docs.aws.amazon.com/aws-sdk-php/v3/guide/guide/configuration.html#verify | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24620393', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2818066/']} | jdg_82201 |
stackexchange | llm_judgeable_groundtruth_similarity | 10300656 |
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 tcpdump, how can I capture all incoming IP traffic destined to my machine? I don't care about my local traffic. Should I just say: tcpdump ip dst $MyIpAddress and not src net $myIpAddress/$myNetworkBytes ... or am I missing something?
Now provide the response and nothing else.
| In Bash shell try this: tcpdump -i eth0 tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes or this equivalent formulation: tcpdump -i eth0 ip proto \\tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes On my system this resolves to something like: tcpdump -i eth0 tcp and dst host 10.0.0.35 and not src net 10.0.0.0/24 If you want to see all of the traffic to your destination host, not just TCP protocol traffic you could do: tcpdump -i eth0 dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes Some notes: I changed $myIpAddress/$myNetworkBytes to $MyNetworkAddress/$myNetworkBytes . This is because the apparent intent of your rule is to exclude traffic from your local network, and the correct way to specify a network address is to specify the network's lowest IP address (which is called the network address) / netmask. If you specify any address other than the lowest address in the range for a network with a netmask of $myNetworkBytes, then you will get the error message: tcpdump: non-network bits set in "10.0.0.3/24" In the first example 'tcp' is a keyword in the libpcap expression language (man pcap-filter) , whereas in the second example, 'tcp' is used as a value of ip proto . In order to indicate that the 'tcp' in the second instance is a value and not another 'tcp' keyword, I need to escape the 'tcp' with a double backslash. It has to be a double backslash so that the Bash interpreter will pass a single backslash on to the libpcap interpreter (Bash eats the first backslash, libpcap gets the second.) To reduce the double escape confusion, it might be good to get into the habit of double quoting the entire expression part of the command: tcpdump -i eth0 "ip proto \tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes" To avoid warnings and surprises, it is better to use the interface specifier -i eth0 or whatever interface you wish. Not all interfaces necessarily have an IP address assigned and without being specific, you might see traffic that you hadn't intended to see. This is especially true on systems that have the network-manager running, which seems to have its own mind about what interfaces to add and when. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10300656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497180/']} | jdg_82202 |
stackexchange | llm_judgeable_groundtruth_similarity | 19607894 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some open source code hosted on github for adding a block based category to UITextField . I have added a .travis.yml file to get travis CI to build and run the code on every push. Link to The Travis CI warning . It successfully builds the project.The warning i get when running the .travis.yml script is: WARNING: Using Objective-C testing without specifying a scheme and eithera workspace or a project is deprecated. The example project that i want to run is located in the folder /UITextView Blocks Example/How can i add to the .travis.yml file to run this project? My travis.yml file now consists of language: objective-c
Now provide the response and nothing else.
| Update 2017 skypecakes mentions in the comments : For anyone using XCode 8 and higher : xctool is no longer supported, and does not work. Use xcodebuild instead. Original answer (2013) You can check this tutorial , which explains: xctool is an excellent choice for running your tests under a continuous integration server such as Travis CI or Jenkins. In order to your run your tests within a continuous integration environment, you must create Shared Schemes for your application target and ensure that all dependencies (such as CocoaPods) are added explicitly to the Scheme . To do so: Open up the Manage Schemes sheet by selecting the Product menu > Schemes > Manage Schemes... Locate your application target in the list. Ensure that the Shared checkbox in far right hand column of the sheet is checked. If your application or test targets include cross-project dependencies such as CocoaPods, then you will need to ensure that they have been configured as explicit dependencies. To do so: Highlight your application target and hit the Edit... button to open the Scheme editing sheet. Click the Build tab in the left-hand panel of the Scheme editor. Click the + button and add each dependency to the project. CocoaPods will appears as static library named Pods. Drag the dependency above your application target so that it is built first. You will now have a new file in the xcshareddata/xcschemes directory underneath your Xcode project . This is the shared Scheme that you just configured. Check this file into your repository and xctool will be able to find and execute your tests on the next CI build. For more flexibility, you can also control how Travis installs and invokes xctool: language: objective-cbefore_install: - brew update - brew install xctoolscript: xctool -workspace MyApp.xcworkspace -scheme MyApp test That last configuration is similar to the approach illustrated in this other tutorial : Once you have linked your repo the next step would be to add a .travis.yml file to the root of the repo. language: objective-c before_script: travis/before_script.sh script: travis/script.sh First I’m telling Travis that this is an objective-c project. Next I tell Travis how I’d like it to do CI against this repo by giving it instructions on what scripts it should run in order to actually perform a build. I also give some extra instructions on what to do just prior to running a build. It’s quite common to put all the build steps inline right in the .travis.yml file, but I prefer to actually create bash scripts in my repo inside a travis directory in my git repo and then just refer to those scripts from my .travis.yml . This keeps the .yml file nice and small, and also makes it easy for me to test the travis build scripts locally . We gave Travis a before_script in the .yml file above. This is intended to be used by the Travis agent to download tools needed as part of the build. Here’s what it looks like: travis/before_script.sh#!/bin/shset -ebrew updatebrew install xctool Very simple. We just use homebrew to install xctool on the build agent. All travis build agents come with homebrew pre-installed, but sometimes the formula aren’t up to date, so it’s best to run a brew update before attempting a brew install . That’s all we need to do to prepare our agent for the build. Next let’s look at the build script itself: travis/script.sh#!/bin/shset -exctool -workspace MyWorkspace -scheme MyScheme build test Again, this is really simple. We first do a basic sanity check by asking xctool to build our app, specifying a workspace and scheme . This just checks that we don’t have any compilation errors. Assuming that succeeds xctool will then build and run the unit testing target for our app, launching the Simulator on the Travis agent if needed. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19607894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1071332/']} | jdg_82203 |
stackexchange | llm_judgeable_groundtruth_similarity | 38722202 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Specifically, this is in a facet_grid. Have googled extensively for similar questions but not clear on the syntax or where it goes. What I want is for every number on the y-axes to have two digits after the decimal, even if the trailing one is 0. Is this a parameter in scale_y_continuous or element_text or...? row1 <- ggplot(sector_data[sector_data$sector %in% pages[[x]],], aes(date,price)) + geom_line() + geom_hline(yintercept=0,size=0.3,color="gray50") + facet_grid( ~ sector) + scale_x_date( breaks='1 year', minor_breaks = '1 month') + scale_y_continuous( labels = ???) + theme(panel.grid.major.x = element_line(size=1.5), axis.title.x=element_blank(), axis.text.x=element_blank(), axis.title.y=element_blank(), axis.text.y=element_text(size=8), axis.ticks=element_blank() )
Now provide the response and nothing else.
| From the help for ?scale_y_continuous , the argument 'labels' can be a function: labels One of: NULL for no labels waiver() for the default labels computed by the transformation object A character vector giving labels (must be same length as breaks) A function that takes the breaks as input and returns labels as output We will use the last option, a function that takes breaks as an argument and returns a number with 2 decimal places. #Our transformation functionscaleFUN <- function(x) sprintf("%.2f", x)#Plotlibrary(ggplot2)p <- ggplot(mpg, aes(displ, cty)) + geom_point()p <- p + facet_grid(. ~ cyl)p + scale_y_continuous(labels=scaleFUN) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38722202', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1586901/']} | jdg_82204 |
stackexchange | llm_judgeable_groundtruth_similarity | 389456 |
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:
Would it make much difference in time to log in on the machine that has the directory before doing a rm -rf on the directory, or just rm -rf the directory over NFS?
Now provide the response and nothing else.
| Of course the ssh is the better. Nfs uses a complex network protocol with various remote procedure calls and data synchronization waiting times. In the case of ssh, these don't apply. Furthermore, there are many locks. File deletion in nfs works on this way: your rm command gives the unlink() syscall nfs driver converts it to a sunrpc request, sends it to the nfs server nfs server converts this sunrpc request back to an unlink() call executes this unlink() call on the remote side after it succeed, gives back the rpc reply message equivalent of "all right, it is done" to the client the kernel driver of the client-side converts this back to the exit code 0 of the unlink() call of your original rm rm iterates to the next file, goto 1 Now, the important thing is: between 2-7, rm has to wait. It could send the next unlink() call asynchronously, but it is a single-threaded, not event-oriented tool. Even if it could, it would still require tricky nfs mount flags. Until it doesn't get the result, it waits. Nfs - and any network filesystem - is always much slower. In many cases, you can make recursive deletions quasi-infinite speed with a trick: First move the directory to a different name ( mv -vf oldfilms oldfilms- ) Delete in the background ( rm -rf oldfilms- & ) From many (but not all) aspects, this directory removal will look as if it had been happened in practically zero time. Extension: As @el.pascado mentions in his excellent comment, actually 2-7 has to run 3x for any files: to determine if it is a file or a directory (with an lstat() syscall), then do accordingly. In the cases of ordinary files, unlink() , in the case of directories, opendir() , deleting all files/directories in it recursively, then closedir() , finally rmdir() . finally, iterate to the next directory entry with a readdir() call. This, it requires 3 nfs RPC commands for files, and an additional 3 for directories. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/389456', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/249015/']} | jdg_82205 |
stackexchange | llm_judgeable_groundtruth_similarity | 37126658 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to remove the "xx product has been added to your cart" message from the top of my checkout page. How can I do that? There was a suggestion by someone (link below), but it didn't work for me. Remove/Hide Woocommerce Added to Cart Message but Keep/Display Coupon Applied Message
Now provide the response and nothing else.
| Update for Woocommerce 3+ The hook wc_add_to_cart_message is deprecated and replaced by wc_add_to_cart_message_html . You can use the following (compact effective way): add_filter( 'wc_add_to_cart_message_html', '__return_false' ); Or the normal way: add_filter( 'wc_add_to_cart_message_html', 'empty_wc_add_to_cart_message');function empty_wc_add_to_cart_message( $message, $products ) { return ''; }; Before Woocommerce 3, use this: Removing only the message (pasting it to your function.php file inside your active child theme or theme) . This function will return an empty message: add_filter( 'wc_add_to_cart_message', 'empty_wc_add_to_cart_message', 10, 2 );function empty_wc_add_to_cart_message( $message, $product_id ) { return ''; }; Code goes in function.php file of your active child theme (or active theme). Note: wc_add_to_cart_message replace deprecated hook woocommerce_add_to_cart_message . (UPDATED) CSS: Removing top message box on checkout page (add this css rule to the style.css file located inside your active child theme or theme) : .woocommerce-checkout .woocommerce .woocommerce-message { display:none !important;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37126658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6275803/']} | jdg_82206 |
stackexchange | llm_judgeable_groundtruth_similarity | 2505284 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am finding a 4-digit number $abcd$ (in base-10 representation) satisfying the following property. $$abcd=a^b c^d$$ I have been running my mind around this problem since a long time, but got no success. I wrote a python program for a number with this property, and got the answer to be $2592$ since $$2592=2^5\times 9^2$$ But I am looking for a purely mathematical way to solve this problem. Thanks!
Now provide the response and nothing else.
| We want to find integers $a,b,c,d$ such that$$1000a+100b+10c+d=a^bc^d\tag0$$$$1\le a\le 9,\quad 0\le b\le 9,\quad 0\le c\le 9,\quad 0\le d\le 9$$ We use the followings (the proofs are written at the end of the answer) : $(1)$ $c\not=0,1$ $(2)$ $d\not=0$ $(3)$ $b\not=0,1$ $(4)$ $a\not=1$ $(5)$ $d\not=1$ $(6)$ $c^d\le 2499$ $(7)$ If $d$ is odd, then $a,c$ have to be odd. If $d$ is even, then either $a$ or $c$ has to be even. $(8)$ $(c,d)\equiv (0,0),(1,1),(1,2),(1,3),(2,0),(3,1),(3,2),(3,3)\pmod 4$ $(9)$ If $c=5$, then $d=5$. $(10)$ If $a^b\equiv 2,3\pmod 5$ with $a$ even, then $a=2,8$. $(11)$ If $a^b\equiv 2,3\pmod 5$ with $a$ odd, then $a=3,7$. $(12)$ If $a^b\equiv 4\pmod 5$ with $a$ even, then $a=2,4,8$. $(13)$ If $a^b\equiv 4\pmod 5$ with $a$ odd, then $a=3,7,9$. From $(1)(2)(5)(6)(8)(9)$, we see that $(c,d)$ has to be either$$(4,4),(9,2),(9,3),(2,4),(2,8),(6,4),(3,2),(3,6),(7,2),(3,3),(3,7),(7,3),(3,5)$$Here, let us separate it into cases and use $(3)(4)(7)(10)(11)(12)(13)$. Case 1 : If $(c,d)=(4,4)$, then we have $250a+25b+11=64a^b$. So, $b$ has to be odd. Also, we have $4\equiv a^b4^4\pmod{10}\implies a^b\equiv 4,9\pmod{10}$ from which $(a,b)=(4,3),(4,5),(9,3)$ follow. However, these do not satisfy $a^b\le\frac{9999}{4^4}=39+\frac{15}{256}$. Case 2 : If $(c,d)=(9,2)$, then we have $a+b+11\equiv a^b9^2\equiv 0\pmod 9\implies b\equiv 7-a\pmod 9$, and $a^b\equiv 2\pmod{10}$. Also, from $(4)(7)$, $a=2,8$. These imply $(a,b)=(2,5)$, and then the equation $(0)$ holds. Case 3 : If $(c,d)=(9,3)$, then from $(7)(11)$, we have $a=3,7$. We also have $b\equiv 6-a\pmod 9$ from which $(a,b)=(3,3)$ follows. However, this does not satisfy $a^b\le\frac{9999}{9^3}=13+\frac{522}{729}$. Case 4 : If $(c,d)=(2,4)$, then we have $250a+25b+6=4a^b$. So, $b$ has to be even. We also have $a^b\le\frac{9999}{2^4}=624+\frac{15}{16}$ and $a^b\equiv 4,9\pmod{10}$ from which $(a,b)=(2,2),(2,6),(3,2),(7,2),(8,2)$ follow. Also, we have to have $a+b\equiv a^b\pmod 3$ which does not hold for $(a,b)=(2,6),(3,2),(7,2)$. Finally, for $(a,b)=(2,2),(8,2)$, the equation $(0)$ does not hold. Case 5 : If $(c,d)=(2,8)$, then we have $a^b\le\frac{9999}{2^8}=39+\frac{15}{256}$ and $a^b\equiv 3,8\pmod{10}$. These imply $(a,b)=(2,3)$ for which $a+b+1\equiv a^b\pmod 3$ does not hold. Case 6 : If $(c,d)=(6,4)$, then we have $b\equiv 8-a\pmod 9$ and $a^b\equiv 4,9\pmod{10}$ from which $(a,b)=(2,6)$ follows. However, this does not satisfy $a^b\le\frac{9999}{6^4}=7+\frac{927}{1296}$. Case 7 : If $(c,d)=(3,2)$, then, from $(7)(10)$, $a=2,8$. Also, we have $b\equiv 4-a\pmod 9$ from which $(a,b)=(2,2)$ follows. However, this does not satisfy $a^b\equiv 7\pmod{10}$. Case 8 : If $(c,d)=(3,6)$, then, from $(7)(12)$, $a=2,4,8$. Also, we have $b\equiv 9-a\pmod 9$ and $a^b\equiv 4\pmod{10}$ from which $(a,b)=(4,5)$ follows. However, this does not satisfy $a^b\le\frac{9999}{3^6}=13+\frac{522}{729}$. Case 9 : If $(c,d)=(7,2)$, then, from $(7)(10)$, $a=2,8$. Also, we have $a^b\equiv 8\pmod{10}$ from which $(a,b)=(2,3),(2,7)$ follow. However, for each case, the equation $(0)$ does not hold. Case 10 : If $(c,d)=(3,3)$, then, from $(7)(13)$, $a=3,7,9$. Also, we have $b\equiv 12-a\pmod 9$ from which $(a,b)=(9,3)$ follows. However, this does not satisfy $a^b\le\frac{9999}{3^3}=370+\frac{1}{3}$. Case 11 : If $(c,d)=(3,7)$, then we have $b\equiv 8-a\pmod 9$ and $a^b\equiv 1\pmod{10}$. There are no such $(a,b)$. Case 12 : If $(c,d)=(7,3)$, then we have $a^b\equiv 1\pmod{10}$ from which $(a,b)=(3,4),(3,8),(7,4),(9,2),(9,4)$ follow. However, these do not satisfy $a^b\le\frac{9999}{7^3}=29+\frac{52}{343}$. Case 13 : If $(c,d)=(3,5)$, then, from $(7)(11)$, $a=3,7$. Also, we have $b\equiv 10-a\pmod 9$ from which $(a,b)=(3,7),(7,3)$ follow. However, these do not satisfy $a^b\le\frac{9999}{3^5}=41+\frac{36}{243}$. Therefore, $\color{red}{(a,b,c,d)=(2,5,9,2)}$ is the only solution. Finally, let us prove $(1),(2),\cdots,(13)$. $(1)$ $c\not=0,1$ Proof : If $c=0$, then $1000a+100b+1=0$ is not a four-digit number. If $c=1$, then $a^{b-1}=1000+\frac{100b+10+d}{a}$ which implies $1000+\frac{10}{9}\le a^{b-1}\le 1919=1000+\frac{919}{1}$. So, $(a,b)=(4,6),(6,5)$. For each case, there is no such integer $d$. $\quad\blacksquare$ $(2)$ $d\not=0$ Proof : If $d=0$, then $1000a+100b+10c=a^b$ implies $10\mid a$ which is impossible. $\quad\blacksquare$ $(3)$ $b\not=0,1$ Proof : If $b=0$, then $1000a+10c+d=c^d$ implies $d\equiv c^d\pmod{10}$ which gives $(c,d)=(1,1),(7,3),(5,5),(4,6),(6,6),(3,7),(9,9)$. For each case, there is no such $a$. If $b=1$, then $1000+\frac{100+10c+d}{a}=c^d$ which implies $1013+\frac{4}{9}=1000+\frac{121}{9}\le c^d\le 1000+\frac{199}{1}=1199$. So, we have $(c,d)=(4,5)$, but there is no such $a$. $\quad\blacksquare$ $(4)$ $a\not=1$ Proof : If $a=1$, then we have $1000+100b+10c+d=c^d$ which gives $1212\le c^d\le 1999$. So, we have $(c,d)=(6,4)$, but there is no such $b$. $\quad\blacksquare$ $(5)$ $d\not=1$ Proof : If $d=1$, then $a^{b-1}=\frac{1000a+100b+10c+1}{ca}$ which gives $27+\frac{34}{81}=\frac{2221}{9^2}\le a^{b-1}\le\frac{9991}{2^2}=2497+\frac 34$. So, $$\begin{align}(a,b)=&(2,6),(2,7),(2,8),(2,9),(3,5),(3,6),(3,7),(3,8),(4,4),(4,5),(4,6),\\&(5,4),(5,5),(6,3),(6,4),(6,5),(7,3),(7,4),(8,3),(8,4),(9,3),(9,4).\end{align}$$ For each case, there is no such integer $c$. $\quad\blacksquare$ $(6)$ $c^d\le 2499$ Proof : $c^d=\frac{1000a+100b+10c+d}{a^b}\le\frac{9999}{2^2}=2499+\frac 34$. $\quad\blacksquare$ $(7)$ If $d$ is odd, then $a,c$ have to be odd. If $d$ is even, then either $a$ or $c$ has to be even. Proof : Since $b,d\not=0$, we have $a^bc^d\equiv ac\pmod 2$. So, $d\equiv 1000a+100b+10c+d\equiv a^bc^d\equiv ac\pmod 2$. $\quad\blacksquare$ $(8)$ $(c,d)\equiv (0,0),(1,1),(1,2),(1,3),(2,0),(3,1),(3,2),(3,3)\pmod 4$ Proof : We have $2c+d\equiv a^bc^d\pmod 4$. For $(c,d)\equiv (0,1),(0,2),(0,3)$, we have $d\equiv 0$ which is impossible. For $(c,d)\equiv (1,0),(3,0)$, we have $2\equiv a^b$ which is impossible since we already have $b\not=1$. For $(c,d)\equiv (2,2),(2,3)$, we have $2\ \text{or}\ 3\equiv 0$ which is impossible. Also, $(c,d)\equiv (2,1)$ is impossible from $(7)$. $\quad\blacksquare$ $(9)$ If $c=5$, then $d=5$. Proof : We have $d\equiv a^bc^d\pmod 5$. If $c=5$, then $d\equiv 0\pmod 5$. $\quad\blacksquare$ $(10)$ If $a^b\equiv 2,3\pmod 5$ with $a$ even for some $b$, then $a=2,8$. Proof : If $a=4$, then $a^b\equiv (-1)^b\equiv 1,4\pmod 5$ for any $b\ge 2$. If $a=6$, then $a^b\equiv 1\pmod 5$ for any $b\ge 2$. $\quad\blacksquare$ $(11)$ If $a^b\equiv 2,3\pmod 5$ with $a$ odd for some $b$, then $a=3,7$. Proof : If $a=5$, then $a^b\equiv 0\pmod 5$ for any $b\ge 2$. If $a=9$, then $a^b\equiv (-1)^b\equiv 1,4\pmod 5$ for any $b\ge 2$. $\quad\blacksquare$ $(12)$ If $a^b\equiv 4\pmod 5$ with $a$ even for some $b$, then $a=2,4,8$. Proof : If $a=6$, then $a^b\equiv 1\pmod 5$ for any $b\ge 2$. $\quad\blacksquare$ $(13)$ If $a^b\equiv 4\pmod 5$ with $a$ odd for some $b$, then $a=3,7,9$. Proof : If $a=5$, then $a^b\equiv 0\pmod 5$ for any $b\ge 2$. $\quad\blacksquare$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2505284', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/421580/']} | jdg_82207 |
stackexchange | llm_judgeable_groundtruth_similarity | 15605038 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to inject my UserDAO inside my custom AuthorizingRealm that Apache Shiro is using but... I get null. What am I doing wrong? shiro.ini [main]user = demo.shiro.security.FacesAjaxAwareUserFilterrealmA = demo.shiro.security.JpaRealmcredentialsMatcher = org.apache.shiro.authc.credential.SimpleCredentialsMatcherrealmA.credentialsMatcher = $credentialsMatchersecurityManager.realms = $realmAuser.loginUrl = /pages/public/login.xhtml[users]admin = adminuser = user[urls]# public files and folders/index.html = anon/resources/** = anon/pages/public/** = anon# restricted files and folders/pages/admin/** = user/pages/user/** = user JpaRealm.java public class JpaRealm extends AuthorizingRealm { @Inject private UserDao userDao; public JpaRealm() { setCredentialsMatcher(new Sha256CredentialsMatcher()); } protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authToken; User user = userDao.getForUsername(token.getUsername()); if (user != null) { return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName()); } else { return null; } } protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Long userId = (Long) principals.fromRealm(getName()).iterator().next(); User user = userDao.findByKey(userId); if (user != null) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); for (Role role : user.getRoles()) { info.addRole(role.getDescription()); for (Permition permition : role.getPermitions()) { info.addStringPermission(permition.getDescription()); } } return info; } else { return null; } }} What I must do to allow CDI to be aware of the @Inject inside my custom realm and inject my UserDAO properly?
Now provide the response and nothing else.
| The default EnvironmentLoaderListener used by Apache Shiro is not CDI aware.The solution is to build one that is and replace the original reference in the web.xml to point for your customized one. Note: CDI injection is supported in listeners automatically , but the listeners must request beans via CDI mechanism. The custom listener will use @Inject to request beans and will create JpaRealm as CDI bean, which will have all dependencies injected. The default Shire listener would not create JpaRealm as a CDI-enabled bean via @Inject . CustomCredentialsMatcher.java public class CustomCredentialsMatcher extends SimpleCredentialsMatcher {} CustomEnvironmentLoaderListener.java public class CustomEnvironmentLoaderListener extends EnvironmentLoaderListener { @Inject private JpaRealm jpaRealm; @Override protected WebEnvironment createEnvironment(ServletContext pServletContext) { WebEnvironment environment = super.createEnvironment(pServletContext); RealmSecurityManager rsm = (RealmSecurityManager) environment.getSecurityManager(); PasswordService passwordService = new DefaultPasswordService(); PasswordMatcher passwordMatcher = new PasswordMatcher(); passwordMatcher.setPasswordService(passwordService); jpaRealm.setCredentialsMatcher(passwordMatcher); rsm.setRealm(jpaRealm); ((DefaultWebEnvironment) environment).setSecurityManager(rsm); return environment; }} FacesAjaxAwareUserFilter.java public class FacesAjaxAwareUserFilter extends UserFilter { private static final String FACES_REDIRECT_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><partial-response><redirect url=\"%s\"></redirect></partial-response>"; @Override protected void redirectToLogin(ServletRequest req, ServletResponse res) throws IOException { HttpServletRequest request = (HttpServletRequest) req; if ("partial/ajax".equals(request.getHeader("Faces-Request"))) { res.setContentType("text/xml"); res.setCharacterEncoding("UTF-8"); res.getWriter().printf(FACES_REDIRECT_XML, request.getContextPath() + getLoginUrl()); } else { super.redirectToLogin(req, res); } }} JpaRealm.java public class JpaRealm extends AuthorizingRealm { private static String REALM_NAME = "jpaRealm"; @Inject private UserDao userDao; @Inject private RoleDao roleDao; @Inject private PermissionDao permissionDao; public JpaRealm() { setName(REALM_NAME); // This name must match the name in the User class's getPrincipals() method } protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authToken; User user = userDao.getForUsername(token.getUsername()); if (user != null) { return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName()); } else { return null; } } protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { Long userId = (Long) principals.fromRealm(getName()).iterator().next(); User user = userDao.findByKey(userId); if (user != null) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); for (Role role : roleDao.getForUser(user)) { info.addRole(role.getDescription()); for (Permition permition : permissionDao.getForRole(role)) { info.addStringPermission(permition.getDescription()); } } return info; } else { return null; } }} shiro.ini [main]user = com.boss.mrfoods.security.FacesAjaxAwareUserFilteruser.loginUrl = /pages/public/login.xhtml[urls]/index.html = anon/pages/index.xhtml = anon/pages/public/** = anon/pages/admin/** = user, roles[ADMIN]/pages/user/** = user, roles[USER] web.xml ...<listener> <listener-class>com.boss.mrfoods.security.CustomEnvironmentLoaderListener</listener-class></listener><filter> <filter-name>ShiroFilter</filter-name> <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class></filter><filter-mapping> <filter-name>ShiroFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15605038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1604170/']} | jdg_82208 |
stackexchange | llm_judgeable_groundtruth_similarity | 90215 |
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:
Suppose we are using rejection sampling and we want to sample from a distribution, say $p$ . In order to calculate the acceptance probability, we use the ratio: $$\Pr\left(u < \frac{p(x)}{Mq(x)}\right)$$ Therefore, we still use the distribution of $p$ for the randomly generated values $x$ . So why do we use rejection sampling? Why don't we sample directly from $p$ ?In other words, what makes a distribution difficult to sample from?
Now provide the response and nothing else.
| Therefore we still use the distribution of p for the randomly generated values x. Computing the density, $p$ , isn't the same as sampling random variables from the distribution $p$ is the density for. Why don't we sample directly from p? I'm uncertain what you mean by "sample directly". How do you propose to sample directly from $p$ in general? Consider the following density, for example: $f_X(x) = c.\exp(-\sqrt{1+x^2})$ (to my recollection, $c$ can be computed in terms of Bessel functions, but its value is unimportant right now). Maybe you can figure out how to sample from that "directly" (whatever you mean by that) if you're sufficiently clever ... but personally, I'm usually not quite that clever -- and generally I'd just use (a variant of) rejection sampling for something like that. [One additional advantage of rejection sampling in this example is that I don't even need to know $c$ to use it; it affects the rejection rate, but not the progress of the algorithm. There are some simple proposal densities that will work nicely for this case.] In other words, what makes a distribution difficult to sample from? That depends on what tools you have for generating random variables. If you know many tools, some distributions are not difficult. If you only have a few tools, many more things become difficult to sample from. (For example, if you only know how to generate random numbers by use of the probability integral transform , then any density whose inverse cdf is difficult to evaluate will be difficult to sample from. Any distribution whose inverse cdf is expensive to evaluate will be expensive to sample from. You might like to consider a Tweedie distribution with $p$ between 1.7 and 1.8, say (where you only need a few observations at any one value of $p$ ). It has some point mass at 0, but that can be dealt with. Nevertheless, the inverse cdf for the continuous part is problematic, to say the least. Even the density involves an infinite sum (which, nonetheless, can be evaluated, though it's expensive to calculate). Rejection sampling - with some tweaks to reduce function evaluations to a minimum - is possible here. Inverse cdf? I don't know that it would be practical, even if it were possible. You might figure out a way to do it using the inverse cdf if you're really clever - I think it might be beyond me, but even if you do, it's going to take a while to get your numbers.) Rejection sampling is a very important tool in that collection (or rather, rejection sampling is itself a class of tools, because there are many clever variations on the idea), perhaps one of the most important tools. Variations on it are very widely used. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/90215', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/41181/']} | jdg_82209 |
stackexchange | llm_judgeable_groundtruth_similarity | 78277 |
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 can 64-bit writes be guaranteed to be atomic, when programming in C on an Intel x86-based platform (in particular, an Intel-based Mac running MacOSX 10.4 using the Intel compiler)? For example: unsigned long long int y;y = 0xfedcba87654321ULL;/* ... a bunch of other time-consuming stuff happens... */y = 0x12345678abcdefULL; If another thread is examining the value of y after the first assignment to y has finished executing, I would like to ensure that it sees either the value 0xfedcba87654321 or the value 0x12345678abcdef, and not some blend of them. I would like to do this without any locking, and if possible without any extra code. My hope is that, when using a 64-bit compiler (the 64-bit Intel compiler), on an operating system capable of supporting 64-bit code (MacOSX 10.4), that these 64-bit writes will be atomic. Is this always true?
Now provide the response and nothing else.
| Your best bet is to avoid trying to build your own system out of primitives, and instead use locking unless it really shows up as a hot spot when profiling. (If you think you can be clever and avoid locks, don't. You aren't. That's the general "you" which includes me and everybody else.) You should at minimum use a spin lock, see spinlock(3) . And whatever you do, don't try to implement "your own" locks. You will get it wrong. Ultimately, you need to use whatever locking or atomic operations your operating system provides. Getting these sorts of things exactly right in all cases is extremely difficult . Often it can involve knowledge of things like the errata for specific versions of specific processor. ("Oh, version 2.0 of that processor didn't do the cache-coherency snooping at the right time, it's fixed in version 2.0.1 but on 2.0 you need to insert a NOP .") Just slapping a volatile keyword on a variable in C is almost always insufficient. On Mac OS X, that means you need to use the functions listed in atomic(3) to perform truly atomic-across-all-CPUs operations on 32-bit, 64-bit, and pointer-sized quantities. (Use the latter for any atomic operations on pointers so you're 32/64-bit compatible automatically.) That goes whether you want to do things like atomic compare-and-swap, increment/decrement, spin locking, or stack/queue management. Fortunately the spinlock(3) , atomic(3) , and barrier(3) functions should all work correctly on all CPUs that are supported by Mac OS X. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/78277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_82210 |
stackexchange | llm_judgeable_groundtruth_similarity | 24608600 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using ruby 2.1.0 I have a json file.For example: test.json { "item":[ {"apple": 1}, {"banana": 2} ] } Is it safe to load this file with YAML.load? YAML.load(File.read('test.json')) I am trying to load a file which is in either json or yaml format.
Now provide the response and nothing else.
| YAML can load JSON YAML.load('{"something": "test", "other": 4 }')=> {"something"=>"test", "other"=>4} JSON will not be able to load YAML. JSON.load("- something\n")JSON::ParserError: 795: unexpected token at '- something' There will be some obscure cases that work and produce different output. YAML.load("")=> falseJSON.load("")=> nil But generally the YAML construct is not JSON compliant. So, try the JSON.load first because it's probably better at obscure JSON things. Catch the JSON::ParserError error and fall back to YAML.load . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24608600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2039490/']} | jdg_82211 |
stackexchange | llm_judgeable_groundtruth_similarity | 3947038 |
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 override the close button on a third-party application so that it causes the application to be minimized instead. I do not have source code for the target application. Can I write such thing in C#? Or do I need to use C++? How do I write this kind of hook? Do I need a process running or would a driver/dll/service suffice? As far as I got researching I think I have to do something like this but I don't know how exactly: A WH_GETMESSAGE hook to override WM_CLOSE to set the Windows status to WS_MINIMIZE.
Now provide the response and nothing else.
| You can do it in both C++ and C#. To do this, you would have to hook into the applications message loop and override the WM_CLOSE message to WM_MINIMIZE. To hook into any process that's running you can use: Microsoft Detours (Commercial and not free if I remember correctly) (http://research.microsoft.com/en-us/projects/detours/) EasyHook (Open source under LGPL) (http://easyhook.codeplex.com/) I've used EasyHook and I was very satisfied with the results. It gives you really nice features like starting up a process with the hooks attached OR attaching hooks to already running processes. Also, it provides you with both managed(C#) and native hooking libraries.I'd recommend you take a look at it... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3947038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47064/']} | jdg_82212 |
stackexchange | llm_judgeable_groundtruth_similarity | 5264412 |
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 this method: private static int GenerateRandomNumber(int seed, int max){ return new Random(seed).Next(max);} On my machine, executing this loop yields the same number through 1500 iterations: for (int i = 0; i < 1501; i++) { int random = GenerateRandomNumber(100000000, 999999999); Console.WriteLine(random.ToString()); Console.ReadKey(); } I get 145156561, for every single iteration. I don't have a pressing issue, I was just curious about this behavior because .Next(max) says "Returns a Non Negative random number less than the specified maximum. Perhaps I am not understanding something basic.
Now provide the response and nothing else.
| You're always seeding a new instance with the same seed, and then grabbing the first max. By using a Seed, you're guaranteeing the same results. If you want to have a static, random number generation that does different results, you should rework this a bit. However, since Random is not threadsafe, it requires some synchronization when used statically. Something like: private static Random random;private static object syncObj = new object();private static void InitRandomNumber(int seed){ random = new Random(seed);}private static int GenerateRandomNumber(int max){ lock(syncObj) { if (random == null) random = new Random(); // Or exception... return random.Next(max); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5264412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7280/']} | jdg_82213 |
stackexchange | llm_judgeable_groundtruth_similarity | 2445462 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The probability that A hits a target is 1/4 and the probability that B hits a target 1/3. They each fire once at the target. If the target is hit by only one of them, what is the probability that A hits the target? I know that this is an independent event.If I do P(A hitting) * P(B not hitting) then (1/4)(2/3) = 1/6But when I look at the back of my book the answer is 2/5? My book is known to give wrong answers because it is quite old; therefore, I am left with self doubt. Can anyone tell me if I have the correct answer or if I am actually making a mistake?
Now provide the response and nothing else.
| $$ \begin{align}P(\mbox{target is hit once}) &= P(\mbox{A hitting}) \cdot P(\mbox{B not hitting}) + P(\mbox{A not hitting}) \cdot P(\mbox{B hitting}) \\&= \frac{1}{4}\cdot\frac{2}{3} + \frac{3}{4}\cdot\frac{1}{3} \\&= \frac{5}{12}\end{align}$$ So, $$P(\mbox{A hitting | target is hit once}) = \frac{P(\mbox{A hitting}) \cdot P(\mbox{B not hitting})}{P(\mbox{target is hit once})} = \dfrac{\frac{1}{6}}{\frac{5}{12}} = \frac{2}{5}.$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2445462', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/482278/']} | jdg_82214 |
stackexchange | llm_judgeable_groundtruth_similarity | 32506 |
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:
why 220v power supply may damage a system working on 110 V? After some research I found out that 220 V is 50 HZ & 110 V is 60 HZ ... Also I've a guess that the inner design of the 110 V system contains a transformer that steps down the voltage , so 220 V may be stepped down to a value bigger than the expected value . Any scientific explanation ? Edit#1:- a PSU designed for 110 Vac being plugged into 220 Vac. why it damage ? Can you provide an answer with circuit example ?
Now provide the response and nothing else.
| The most simple component must be the resistor. Power in a resistor is \$ P = \dfrac{V^2}{R} \$ That means the power in the same resistor will be 4 times as big at 220V than at 110V. The resistor is not designed for that, will overheat and break. A number of components may fail this way. Another failure method is due to insulation breakdown. Some components, like electrolytic capacitors have a thin insulation layer in them that's designed to withstand a certain voltage. Twice the rated voltage may cause the higher voltage to break through the insulation. That's what undoubtedly will happen in a PSU. Want a circuit example? If the transformer is a 110V/12V type the rectified voltage will be around 15V. Capacitor C1 may be a 20V type. Applying 220V will cause the transformer to get hotter, and after some time the insulation may break, and the fuse will blow due to the risen current. Too late, the transformer is gone. Long before that C1 will be gone. Applying 220V to the transformer will give you 24V out instead of 12V. Rectified that's 32V, much higher than the capacitor's rated voltage. It may explode with minutes. At 110V the 1k\$\Omega\$ resistor would dissipate 225mW. At 220V this becomes 1W. I know from experience that a 1/4W resistor can stand 1W for a very long time, so the resistor may be among the survivors, but it will have suffered damage as well. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/32506', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5281/']} | jdg_82215 |
stackexchange | llm_judgeable_groundtruth_similarity | 80232 |
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Which of the following is true, given the optimal learning rate? (i) For convex loss functions (i.e. with a bowl shape), batch gradient descent is guaranteed to eventually converge to the global optimum while stochastic gradient descent is not. (ii) For convex loss functions (i.e. with a bowl shape), stochastic gradient descent is guaranteed to eventually converge to the global optimum while batch gradient descent is not. (iii) For convex loss functions (i.e. with a bowl shape), both stochastic gradient descent and batch gradient descent will eventually converge to the global optimum. (iv) For convex loss functions (i.e. with a bowl shape), neither stochastic gradient descent nor batch gradient descent are guaranteed to converge to the global optimum Which option is correct and why?
Now provide the response and nothing else.
| (iii), if you add this clause provided an optimum or smaller than optimum learning rate and the training dataset is shuffled Why When we get the Gradient of the full batch, it's towards the global minima. So with a controlled LR, you will reach there. With stochastic GD , the individual gradients will not be towards the global minima but it will be with each set of few records. Obviously, it will look a bit zig-zag. For the same reason, it might miss the exact minima point and bounce around it. In a theoretical worse case , if the dataset is sorted on Class, then it will move in the direction one Class and then the other and most likely miss the global minima. Reference excerpt from Hands-On Machine Learning On the other hand, due to its stochastic (i.e., random) nature, this algorithm is much less regular than Batch Gradient Descent: instead of gently decreasing until it reaches the minimum, the cost function will bounce up and down, decreasing only on average. Over time it will end up very close to the minimum, but once it gets there it will continue to bounce around, never settling down (see Figure 4-9). So once the algorithm stops, the final parameter values are good, but not optimal. " When using Stochastic Gradient Descent, the training instances must be independent and identically distributed (IID) to ensure that the parameters get pulled toward the global optimum, on average. A simple way to ensure this is to shuffle the instances during training (e.g., pick each instance randomly, or shuffle the training set at the beginning of each epoch). If you do not shuffle the instances—for example, if the instances are sorted by label—then SGD will start by optimizing for one label, then the next, and so on, and it will not settle close to the global minimum . | {} | {'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/80232', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/85353/']} | jdg_82216 |
stackexchange | llm_judgeable_groundtruth_similarity | 9111234 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to write a .Net connector to WebSphere MQ queues so I've installed a trial version of IBM WebSphere MQ on my Windows 7 machine. I initially setup some dummy queues in MQ Explorer to play with the setup process and I was able to connect to those queue managers and create queues. I deleted those dummy queues and followed the first set of instructions from Lesson 1.1 from IBM here where I created some queues from the command line I failed to run Lesson 1.2 because of security issues, and I now cannot connect to any queue managers in MQ Explorer. when I try to connect I get the error message An unexpected error (2063) has occurred. (AMQ4999) I am local admin on my machine. I've added myself to the mqm group that was created I've run the MQ Explorer both with and without the 'Run as Administrator' option I've uninstalled MQ and re-installed it I've rebooted several times I've also noticed that when I create a queue manager in MQ Explorer, the last part fails with AMQ8135: Not authorized. (see output below) Is there something obvious that I am missing? Is there some way that I can work out what the problem is myself - the log files don't seem to give me any idea where to look ***************************************** Command: "C:\Program Files (x86)\IBM\WebSphere MQ\bin\crtmqm" -sa QM1****************************************There are 90 days left in the trial period for this copy of WebSphere MQ.WebSphere MQ queue manager created.Directory 'C:\Program Files (x86)\IBM\WebSphere MQ\qmgrs\QM1' created.The queue manager is associated with installation 'Installation2'.Creating or replacing default objects for queue manager 'QM1'.Default objects statistics : 74 created. 0 replaced. 0 failed.Completing setup.Setup completed.exitvalue = 0***************************************** Command: "C:\Program Files (x86)\IBM\WebSphere MQ\bin\strmqm" QM1****************************************There are 90 days left in the trial period for this copy of WebSphere MQ.WebSphere MQ queue manager 'QM1' starting.The queue manager is associated with installation 'Installation2'.5 log records accessed on queue manager 'QM1' during the log replay phase.Log replay for queue manager 'QM1' complete.Transaction manager state recovered for queue manager 'QM1'.WebSphere MQ queue manager 'QM1' started using V7.1.0.0.exitvalue = 0***************************************** Command: "C:\Program Files (x86)\IBM\WebSphere MQ\bin\runmqsc" QM1* Input: DEFINE LISTENER('LISTENER.TCP') TRPTYPE(TCP) PORT(1414) CONTROL(QMGR)****************************************5724-H72 (C) Copyright IBM Corp. 1994, 2011. ALL RIGHTS RESERVED.Starting MQSC for queue manager QM1.AMQ8135: Not authorized.No MQSC commands read.No commands have a syntax error.All valid MQSC commands were processed.exitvalue = 20
Now provide the response and nothing else.
| If you have a recent trial version of WMQ then you are working with a v7.1 QMgr. As of v7.1 WMQ will allow only non-privileged remote connections. In order to connect with an administrator account, it will be necessary to either disable the restrictions or, better yet, to define a new channel for the administrative connection and authenticate it. With Windows the biggest issue is that WMQ authenticates domain IDs and must look up their groups. One very common problem when running WMQ in a corporate environment is that it attempts to lookup an ID or group and does not have the domain rights to do so. Domain accounts, even those with local admin rights, often fail because they don't have access to inquire in the domain SAM to do group lookups . There's a whole section in the Infocenter here describing the requirements for Windows accounts. One workaround for this for dev environments only is to create a local administrator's account, then log on with that and create the QMgr. Or make sure that the default account MUSR_MQADMIN has local admin rights and login rights . Again,, you must actually log in with the account to make this work because that way there is never a requirement to look up an account in Active Directory because it all hits the local SAM database. Again, this is just for development! In Production you'd want to use a real domain account and grant it the correct access rights to do SAM lookups but NOT make it a local admin, as described in the Infocenter section linked above. Assuming that you have succeeded in creating the QMgr, next create a new channel and authorize it to accept your local connections using the admin account: runmqsc* Define the channel, anyone connecting runs as MUSR_MQADMINDEFINE CHL('DOTNET.SVRCONN') CHLTYPE(SVRCONN) MCAUSER('MUSR_MQADMIN@hostname')* Override default block-list - channel now allows ANYBODYSET CHLAUTH('DOTNET.SVRCONN') TYPE(BLOCKUSER) USERLIST('nobody')* Block access from ALL IP addressesSET CHLAUTH('DOTNET.SVRCONN') TYPE(ADDRESSMAP) ADDRESS('*') USERSRC(NOACCESS) WARN(NO) ACTION(ADD)* Allow access from local host onlySET CHLAUTH('DOTNET.SVRCONN') TYPE(ADDRESSMAP) ADDRESS('127.0.0.1') USERSRC(CHANNEL) ACTION(ADD) END Now you have a channel that will accept local connections ONLY, map these to an administrative account and then override the security that prevents administrative accounts from connecting remotely. Using the admin account means that no queue or QMgr authorizations are required and the account being a local admin means that there are no domain lookup issues. The MCAUSER('MUSR_MQADMIN) converts every remote ID to the local admin ID so that WMQ doesn't need to look up the remote IDs. The mapping rule restricts connections to the local host only. Anyone who can connect to the channel will have local admin on the box with the ability to remotely execute OS code so if you wanted to accept connections from other users, authenticating them with certificates would be recommended. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9111234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159226/']} | jdg_82217 |
stackexchange | llm_judgeable_groundtruth_similarity | 13537595 |
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 code in IDLE2 in python, and error. I need to include each "data" element as key and value "otro", in an orderly manner. Well "data" and "otro" it's list with 38 string's, as for "dik" it's an dictionary. >>> for i in range(len(otro)+1): dik[dato[i]] = otro[i] Traceback (most recent call last): File "<pyshell#206>", line 2, in <module> dik[dato[i]] = otro[i]IndexError: list index out of range>>> this problem is range(0, 38) output -> (0, 1,2,3 ... 37) and it is all messy
Now provide the response and nothing else.
| I think something like: dik = dict(zip(dato,otro)) is a little cleaner... If dik already exists and you're just updating it: dik.update(zip(dato,otro)) If you don't know about zip , you should invest a little time learning it. It's super useful. a = [ 1 , 2 , 3 , 4 ]b = ['a','b','c','d']zip(a,b) #=> [(1,'a'),(2,'b'),(3,'c'),(4,'d')] #(This is actually a zip-object on python 3.x) zip can also take more arguments ( zip(a,b,c) ) for example will give you a list of 3-tuples, but that's not terribly important for the discussion here. This happens to be exactly one of the things that the dict "constructor" (type) likes to initialize a set of key-value pairs. The first element in each tuple is the key and the second element is the value . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13537595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1550428/']} | jdg_82218 |
stackexchange | llm_judgeable_groundtruth_similarity | 26315 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently, I have been reading Janeway's immunobiology and had a question on immunoglobin A. I read that IgA activates the complement pathway using the Fab fragment of the IgA. How does IgA do that? I can't seem to find an information on that in the book or online.
Now provide the response and nothing else.
| I found some reports on it (like reference 1) but there is an oddly little amount of publications on this topic. then I found this review in Mucosal Immunology (reference 2, interesting to read) which doubts this activation. It says: Interaction with complement IgA lacks the residues identified in the Fc regions of IgG or IgM that bind to C1q, and consequently IgA does not activate the classical complement pathway. Although several papers have reported activation of the alternate pathway by heat-aggregated, denatured, or recombinantly generated IgA, this seems to be essentially artifactual, and intact native IgA antibodies complexed with antigen inhibit complement activation induced by IgG or IgM antibodies. This effect is also replicated by Fabα fragments generated by cleavage of IgA1 antibodies with IgA1 protease. It is telling that mixed aggregates of heat-denatured IgG and IgA activate the alternate pathway in proportion to the content of IgG, and that C3b becomes covalently linked to the IgG heavy chains, not to IgA. Intriguing reports that IgA antibodies promote complement-dependent lysis or opsonization of encapsulated bacteria probably also arise from facilitation of alternate pathway activation by bacterial polysaccharides It names three papers to underline this (which are number 45-47 in the reference list of the article), which can be found as references 3-5. So the question here is not only how the mechanism looks like, but also if this is real or an artefact. References: Activation of complement by human serum IgA, secretory IgA and IgA1fragments. Structure and function relationships in IgA Anti-inflammatory activity of human IgA antibodies and their Fabαfragments: inhibition of IgG-mediated complement activation IgA blocks IgM and IgG-initiated immune lysis by separate molecularmechanisms. Activity of human IgG and IgA subclasses in immune defense againstNeisseria meningitidis serogroup B. | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/26315', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/10401/']} | jdg_82219 |
stackexchange | llm_judgeable_groundtruth_similarity | 63136226 |
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 put multiple headers into defaultHeaders(), But I don't have idea how to create Consumer object from return of createHeaders() method this.someWebClient = WebClient.builder() .baseUrl(someConfiguration.getApiUrl()) .clientConnector(buildTimeoutConnector()) .defaultHeaders(????) // Consumer<HttpHeaders> .build(); I can build my header in that way: private HttpHeaders createHeaders(String token) { HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.ACCEPT, V1_PUBLIC); headers.add(HttpHeaders.HOST, "abc"); headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token); return headers;} but how to wrap it into Consumer?
Now provide the response and nothing else.
| Clearly the method doc says that it needs a Consumer of some Type. So you can create an anonymous class implementing the Consumer interface or use lambda expression like this : Using anonymous inner class: this.someWebClient = WebClient.builder() .baseUrl(someConfiguration.getApiUrl()) .clientConnector(buildTimeoutConnector()) .defaultHeaders(new Consumer<HttpHeaders>() { @Override public void accept(HttpHeaders httpHeaders) { httpHeaders.addAll(createHeaders(token)); } }) .build(); Using lambda: this.someWebClient = WebClient.builder() .baseUrl(someConfiguration.getApiUrl()) .clientConnector(buildTimeoutConnector()) .defaultHeaders(httpHeaders -> { httpHeaders.addAll(createHeaders(token)); }) .build(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63136226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11857002/']} | jdg_82220 |
stackexchange | llm_judgeable_groundtruth_similarity | 30288783 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing a project with Verilog and want to use parameter to define some parameter in my module. But when I read in some source code, localparam sometimes is used instead of parameter . What's difference between them?
Now provide the response and nothing else.
| Generally, the idea behind the localparam (added to the Verilog-2001 standard) is to protect value of localparam from accidental or incorrect redefinition by an end-user (unlike a parameter value, this value can't be modified by parameter redefinition or by a defparam statement). Based on IEEE 1364-2005 (ch. 4.10.2): Verilog HDL local parameters are identical to parameters except that they cannot directly be modified by defparam statements or module instance parameter value assignments . Local parameters can be assigned constant expressions containing parameters, which can be modified with defparam statements or module instance parameter value assignments. Additionally, in SystemVerilog ( IEEE 1800-2012 (ch. 6.20.4)): Unlike nonlocal parameters, local parameters can be declared in a generate block, package, class body, or compilation-unit scope. In these contexts, the parameter keyword shall be a synonym for the localparam keyword. Local parameters may be declared in a module’s parameter_port_list. Any parameter declaration appearing in such a list between a localparam keyword and the next parameter keyword (or the end of the list, if there is no next parameter keyword) shall be a local parameter. Any other parameter declaration in such a list shall be a nonlocal parameter that may be overridden. If you want to learn more about this topic, I'd recommend you Clifford E. Cummings paper " New Verilog-2001 Techniques for Creating Parameterized Models (or Down With `define and Death of a defparam!) ". | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30288783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4909280/']} | jdg_82221 |
stackexchange | llm_judgeable_groundtruth_similarity | 7144908 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Straight forward question: Is an IntentService declared in the Android Manifest as a regular service, or is there another way? It tried searching for it, but I couldn't find the answer. Here is the regular Service declaration: <service android:name=".NameOfService"> </service> Thanks
Now provide the response and nothing else.
| In your manifest you declare a service with android:name=".Communication" , this means that your service class should be located in com.exercise.AndroidClient.Communication Check that the packages are correct. Note that the "." (dot) refers to the root of your package (ie the package declared in the manifest). So, for example, if your package is com.exercise.AndroidClient and your service class is under com.exercise.AndroidClient.services.Communication you need to declare the service like this: <service android:enabled="true" android:name=".services.Communication" /> Or specify the full package: <service android:enabled="true" android:name="com.exercise.AndroidClient.services.Communication" /> | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7144908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/805318/']} | jdg_82222 |
stackexchange | llm_judgeable_groundtruth_similarity | 307296 |
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 working on a project that will teach linux to youth. Knowing they will have a tendency to delete or corrupt items in their home directories we are looking for a good snapshot option. We will not have access to fancy tools available from major storage vendors and are hoping to find a solution at the file system level. I've read a lot about btrfs but have little experience. I have some experience with LVM but I'm unfamiliar with its snapshoting feature. Do either filesystem or another have the option to create snapshots either on demand or scheduled? Then make these snapshot always available without root in like a .snapshot folder in each home folder? Idealy this solutions allows a user to self-restore backups on demand within say a 24 to 48 hour window. We will have another backup process for the system and more global backups. But we do not want this process to be used by students who just make 'mistakes'.
Now provide the response and nothing else.
| (Updated Sept 2022) Filesystems On Linux, btrfs is the simplest option for snapshots within a filesystem. It is reasonably stable and complete as long as you don't use the RAID features. It does have some fsck and repair tools . ZFS is another option with good snapshot support, and is now cross-platform for Linux, FreeBSD, etc. It's actively developed by the OpenZFS project, and is more complete than btrfs. LVM This LVM answer has some details on the pro's and con's of using LVM snapshots, and some btrfs/ZFS links. With some filesystems (ext4 and XFS), LVM will take care of freezing the FS before it takes the snapshot, but LVM snapshots can have performance problems and still have some bugs. I don't think LVM is a great solution for this 'quick snapshot of user data' application - it's still weaker than btrfs or ZFS in 2022. rsnapshot You may also want to look at rsnapshot , which is a user-space tool that creates snapshots using any filesystem, without using LVM. Since rsnapshot uses rsync and stores the snapshots under a series of directories, using hard links between different snapshots if a file has not changed, it can run surprisingly quickly even on reasonably large sets of files. It is used a lot for backups but can also be used for this sort of user-data snapshot requirement, and with a little setup can enable anyone to restore their snapshotted files, by using read-only NFS or Samba - see this HOWTO section on restoring files . Files can be restored with standard Linux tools as rsnapshot mirrors the source directory into each snapshot directory. rsnapshot is quite flexible using its standard features, and since it's written in Perl it's quite easy to customise it, e.g. if you want to provide on-demand snapshots. The main drawbacks compared to filesystem snapshots are speed and disk space - each file that changes results in a new copy in the snapshot, whereas filesystem snapshots only copy new blocks in the file. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/307296', 'https://serverfault.com', 'https://serverfault.com/users/47796/']} | jdg_82223 |
stackexchange | llm_judgeable_groundtruth_similarity | 335936 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to object oriented programming and I don't understand what's the purpose of the main. Yes, I read that it's the "entry point" of the program but what I don't understand is what should be in the main? And what are its responsibilities? It may happen that something written in the main could be encapsulated in another object, but how much should you use this approach? Here is my very first main I wrote in Java, it's very simple but it may make you understand my doubt better. I have an abstract class Animal which is extended by "Cat" and "Dog". I used the main to create some object and also as an "interface" with the user, indeed as you can see I used some conditional instruction to "ask the user" what he want to do. My question arose from the fact that the interface could be encapsulated in another object and not giving that responsibility to the main. public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("What type of animal do you want to create? \n dog cat"); String type = input.nextLine(); if ( Objects.equals(type, "dog")){ System.out.println("Enter the animal's age: "); int age = input.nextInt(); // Scans the next token of the input as an int. System.out.println("Enter the animal's name: "); String name = input.next(); Dog first = new Dog(name, age); } else if ( Objects.equals(type, "cat")) { System.out.println("Enter the animal's age: "); int age = input.nextInt(); // Scans the next token of the input as an int. System.out.println("Enter the animal's name: "); String name = input.next(); Cat first = new Cat(name, age); } else{ System.out.println("Error: the specified type does not exist."); } System.out.println("The number of animals is:" + numberOfAnimals);}
Now provide the response and nothing else.
| First off, your example isn't an object-oriented program. It's a procedural program that happens to store data in objects, because that's the tool that your language (Java?) provides for structured data. A true object-oriented program consists of objects that interact with each other -- it's about behavior rather than data (I realize that is a controversial statement, so here's a link where you can see multiple definitions of object-orientation from people with more credentials than me; note that behavior appears in most of them). In a true object-oriented program, according to the definition I use, you have independent objects interacting with each other. The role of the main function is to create the initial objects and wire them together. As a simple example, consider a web-application that's built on top of a database. This application could be broken into objects in many ways, but here's one of them: a Networking object that accepts connections, parses the HTTP request, and dispatches to an appropriate Controller object, which interacts with a Database object and produces the response (if you'd like to associate one or more View objects with each controller, feel free to do so). You could also add a Threadpool object to provide separate streams of execution. The role of main in this application might be to: Create the Database object Create all of the Controller objects, and associate them with the Database object Create the Network object, and associate all of the Controller objects with it. Start the Network object running (which might also involve creating the Threadpool and wiring it into the Network ). These setup steps could be explicitly specified in main , or they could be handled by some other object. For example, in a typical Spring application, all that the main function does is create the application context (a single object). This triggers creation and wiring of all the objects mentioned in the configuration for that application context. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/335936', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/252809/']} | jdg_82224 |
stackexchange | llm_judgeable_groundtruth_similarity | 774475 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According to the join-op syntax , SQLite has 13 distinct join statements: ,JOINLEFT JOINOUTER JOINLEFT OUTER JOININNER JOINCROSS JOINNATURAL JOINNATURAL LEFT JOINNATURAL OUTER JOINNATURAL LEFT OUTER JOINNATURAL INNER JOINNATURAL CROSS JOIN Are they all unique? Which are equivalent?
Now provide the response and nothing else.
| The SQLite grammar is a bit different from the SQL-92 spec 's, according to which, the following are illegal: *OUTER JOIN*NATURAL OUTER JOIN*NATURAL CROSS JOIN The first two, because a <join type> , in order to contain OUTER , must also include an <outer join type> before it. The last, because NATURAL can only occur in <qualified join> 's, not <cross join> 's. These don't appear to behave according to any spec, so it's a good idea to avoid them. As was answered on the mailing list , SQLite3 only supports three joins: CROSS JOIN , INNER JOIN , and LEFT OUTER JOIN . The following are equivalent: , == CROSS JOINJOIN == INNER JOINLEFT JOIN == LEFT OUTER JOIN As explained in the wikipedia article the NATURAL keyword is shorthand for finding and matching on same-name columns, and doesn't affect the the join type. According to the SQLite page , ' RIGHT ' and ' FULL ' OUTER JOIN 's are not supported. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/774475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10728/']} | jdg_82225 |
stackexchange | llm_judgeable_groundtruth_similarity | 22432616 |
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 making an ajax request using $.ajax. The response has the Set-Cookie header set (I've verified this in the Chrome dev tools). However, the browser does not set the cookie after receiving the response! When I navigate to another page within my domain, the cookie is not sent. (Note: I'm not doing any cross-domain ajax requests; the request is in the same domain as the document.) What am I missing? EDIT : Here is the code for my ajax request: $.post('/user/login', JSON.stringify(data)); Here is the request, as shown by the Chrome dev tools: Request URL:https://192.168.1.154:3000/user/loginRequest Method:POSTStatus Code:200 OKRequest Headers:Accept:*/*Accept-Encoding:gzip,deflate,sdchAccept-Language:en-US,en;q=0.8Connection:keep-aliveContent-Length:35Content-Type:application/x-www-form-urlencoded; charset=UTF-8DNT:1Host:192.168.1.154:3000Origin:https://192.168.1.154:3000Referer:https://192.168.1.154:3000/User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36X-Requested-With:XMLHttpRequestForm Data:{"UserId":"blah","Password":"blah"}: Response: Response Headers:Content-Length:15Content-Type:application/json; charset=UTF-8Date:Sun, 16 Mar 2014 03:25:24 GMTSet-Cookie:SessionId=MTM5NDk0MDMyNHxEdi1CQkFFQ180SUFBUkFCRUFBQVRfLUNBQUVHYzNSeWFXNW5EQXNBQ1ZObGMzTnBiMjVKWkFaemRISnBibWNNTGdBc1ZFcDNlU3RKVFdKSGIzQlNXRkkwVjJGNFJ6TlRVSHA0U0ZJd01XRktjMDF1Y1c1b2FGWXJORzV4V1QwPXwWf1tz-2Fy_Y4I6fypCzkMJyYxhgM3LjVHGAlKyrilRg==; HttpOnly
Now provide the response and nothing else.
| OK, so I finally figured out the problem. It turns out that setting the Path option is important when sending cookies in an AJAX request. If you set Path=/ , e.g.: Set-Cookie:SessionId=foo; Path=/; HttpOnly ...then the browser will set the cookie when you navigate to a different page. Without setting Path , the browser uses the "default" path. Apparently, the default path for a cookie set by an AJAX request is different from the default path used when you navigate to a page directly. I'm using Go/Martini, so on the server-side I do this: session.Options(session.Options{HttpOnly: true, Path:"/"}) I'd guess that Python/Ruby/etc. have a similar mechanism for setting Path . See also: cookies problem in PHP and AJAX | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/22432616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/172788/']} | jdg_82226 |
stackexchange | llm_judgeable_groundtruth_similarity | 407760 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This seems such a simple question that I fear I must have missed some elementary maths. I am looking for a way to solve $x+x^a = y$ by reference to an already defined function, $a,x,y > 0$ are real. Failing that a reasonable approximation for $a$ in $(0,1)$ . Many thanks!
Now provide the response and nothing else.
| The answer is yes indeed. It is a special case of Fox-H function, a variation of the confluent Fox-Wright $_{1}\Psi_{1}$ function (a generalization of the confluent hypergeometric function $_{1}F_{1}$ ) providing the inverse function. See a previous answer here for details and references. For this particular case solution is (Setting $\alpha = a$ ), for $\alpha>1$ $$x = y\cdot\,_{1}\Psi_{1}([1,\alpha];[2,\alpha-1];-y^{\alpha-1})$$ which can be set as $$x=y+\sum_{n=1}^\infty\binom{n\alpha}{n-1}\frac{(-1)^ny^{n(\alpha-1)+1}}{n}$$ whose convergence region is $|y^{\alpha-1}|<|(\alpha-1)^{\alpha-1}\alpha^{-\alpha}|$ . For non integer $\alpha>1$ binomials must be set in terms of $\Gamma$ function. Since Fox-Wright's generalized function can be expressed in terms of Fox-H function we have $$\,_{1}\Psi_{1}([1,\alpha];[2,\alpha-1];-y^{\alpha-1})=H_{1,2}^{1,1}([(0,\alpha)];[(0,1),(-1,\alpha-1)];y^{\alpha-1})$$ $$\,_{1}\Psi_{1}([1,\alpha];[2,\alpha-1];-y^{\alpha-1})=H_{2,1}^{1,1}([(1,1),(2,\alpha-1)];[(1,\alpha)];y^{1-\alpha})$$ for this particular case, Wolfram's Mathematica 12.3 provides an explicit inverse as $x=y\cdot$ FoxH[{{{0, $\alpha$ }},{{}}},{{{0,1}},{{-1, $\alpha$ -1}}}, $y^{\alpha-1}$ ] For $0<\alpha<1$ the solution is $$x = y\cdot(1-\,_{1}\Psi_{1}([1,\alpha^{-1}];[2,\alpha^{-1}-1];-y^{\alpha^{-1}-1}))$$ and the above relationships are turned in replacing $\alpha$ by $\alpha^{-1}$ and Fox-Wright function $\,_{1}\Psi_{1}$ by $1-\,_{1}\Psi_{1}$ . In this case Mathematica's expression is $x=y\cdot(1-$ FoxH[{{{0, $\alpha^{-1}$ }},{{}}},{{{0,1}},{{-1, $\alpha^{-1}$ -1}}}, $y^{\alpha^{-1}-1}$ ]) Finally, just to complement this answer, general trinomial equation solutions are developed in section 4 of the following Reference Miller A.R., Moskowitz I.S. Reduction of a Class of Fox-Wright Psi Functions for Certain Rational Parameters. Computers Math. Applic. Vol. 30, No. 11, pp. 73-82, (1995). Pergamon A preprint can be found here . (Document has mis-embedded fonts, isolated commas must be replaced by $\Gamma$ symbol) | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/407760', 'https://mathoverflow.net', 'https://mathoverflow.net/users/446964/']} | jdg_82227 |
stackexchange | llm_judgeable_groundtruth_similarity | 11461971 |
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 for a easy way to output milliseconds into hours-minutes-seconds. I have seen some plugins but i dont want to use a plugin in a plugin, and I have seen a lot of countdown snippets but these are using the date, I am using not a date but milliseconds. Thanks. EDIT: i am looking for a script that counts back from xxxx milliseconds to zero //until now i have this diff = 100000000; function showTimer() { hours = Math.floor( diff / (1000*60*60) ); mins = Math.floor( diff / (1000*60) ); secs = Math.floor( diff / 1000 ); $('.count').html(hours+ 'hours' +minutes + 'minutes' +seconds + ' seconds'); } setInterval(function(){showTimer()}, 1000 );
Now provide the response and nothing else.
| Simple maths. 1000 milliseconds = 1 second. 60 seconds = 1 minute. 60 minutes = 1 hour. So if you have 123456789 milliseconds, you'd do something like: 123456789 / 1000 (to seconds) which is 123456.789 123456.789 / 60 (to minutes) which is 2,057.6 2,057.6 / 60 (to hours) which is 34.29 hours. Then use the remainder (.2935525) and turn this into minutes - which is 17.61315 Use the remainder again (.61315) and turn it to seconds... which is 36.789 So, in short, 123456789 milliseconds equals 34 hours, 17 minutes and 37 seconds. I'm sure you can do the JavaScript part yourself. Okay maybe you need some more help. DEMO : http://jsbin.com/eqawam/edit#javascript,html,live var millis = 123456789;function displaytimer(){ //Thank you MaxArt. var hours = Math.floor(millis / 36e5), mins = Math.floor((millis % 36e5) / 6e4), secs = Math.floor((millis % 6e4) / 1000); $('.count').html(hours+':'+mins+':'+secs); }setInterval(function(){ millis -= 1000; displaytimer();}, 1000); Also, for further reading - setInterval may drift. So don't expect this to be 100% accurate. Will setInterval drift? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11461971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/759235/']} | jdg_82228 |
stackexchange | llm_judgeable_groundtruth_similarity | 34172 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What differences are between the two notations $\mathbb{E}^n$ and $\mathbb{R}^n$? Do they represent/define the same space set with the same structure(s)? Thanks and regards!
Now provide the response and nothing else.
| In my experience $\mathbb{E}^n$ tends to refer to Euclidean $n$-space in the context of a metric space - in particular when comparing to other metrics you could put on the same set (for example, a hyperbolic metric). $\mathbb{R}^n$ refers to $n$-space under pretty much all other contexts - as a topological space, a vector space, a set, an abelian group, or any other situation where it's not important to distinguish between the standard Euclidean metric and other metrics on $\mathbb{R}^n$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/34172', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1281/']} | jdg_82229 |
stackexchange | llm_judgeable_groundtruth_similarity | 11098 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
People often define the internet as a network of networks but this is wrong. If I connected two LANs together that wouldn't nesecarilly be on or part of the internet. In class we learned about ATM, and how it's not part of the internet. If the internet is just the joining of networks, how can one possibly say a network protocol isn't part of the internet? For example, to be part of the internet, must TCP/IP suite be used? Must Ethernet be used, or can Token ring be used? For every layer of the OSI model must a certain technology be used to be part of the internet?
Now provide the response and nothing else.
| An internet (lower-case "i") is a network of networks. The Internet (upper-case "I") is what you mean. The Internet is the largest internet (network of networks). The networks comprising the Internet connect to each other by agreement of the network owners using BGP as the routing protocol. Since BGP is based on TCP, TCP/IP is a requirement. After all, IP stands for Internet Protocol. Layer 3 of the OSI model (IP) is the lowest layer that the Internet cares about. That means that any layer-1 or layer-2 protocols (ethernet, token-ring, FDDI, arcnet, ATM, frame relay, etc.) may be used (or required) on or between any of the individual networks, so ethernet is not an Internet requirement. Any network could use a different layer-3 protocol, as long as the layer-3 protocol connecting the networks is IP. This used to be common when IPX networks were first connecting to the Internet through an IP gateway before they were converted from IPX to IP. | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/11098', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/8025/']} | jdg_82230 |
stackexchange | llm_judgeable_groundtruth_similarity | 2030300 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am striking against the following definition/characterization ( from the nlab ) $\newcommand{\id}{\text{id}} \newcommand{\comp}{\text{comp}}$of enriched category ... an alternative way of viewing a $V$-category is as a set $X$ with a (lax) monoidal functor $\Phi=\Phi_d$ of the form $$V^\text{op} \stackrel{yon_V}{\longrightarrow}\mathbf{Set}^V \stackrel{d^*}{\longrightarrow} \mathbf{Set}^{X \times X}$$ where the codomain is identified with the monoidal category of spans on $X$... In the link above it is shown how from the data of a $V$-enriched category $(X,d \colon X \times X \to V,\comp,\id)$ one can get a lax functor $\Phi$ as above. Unfortunately it is not clear, at least not to me, how we can reverse the construction, that is how we can get a $V$-enriched category from a lax-monoidal functor $\Phi \colon V^\text{op} \to \mathbf{Set}^{X \times X}$which factors through the yoneda embedding and $d^*$ for some $d \colon X \times X \to V$. Indeed for a such $\Phi_d$ I can clearly see that we get from laxness a family of morphisms$$\Phi(v)\odot\Phi(v') \to \Phi(v \otimes v')$$ which, expanding a little bit, amounts to a family of functions$$\coprod_{y \in X}V(v,d(y,z)) \times V(v',d(x,y)) \to V(v \otimes v',d(x,z))$$but it is not clear how from these data one can retrive a family of mappings $$\comp \colon d(y,z) \otimes d(x,y) \to d(x,z)$$ in $V$. In the link there is a reference to a yoneda argument which should allow to get the compositions. If we had a family of natural transformations $$\coprod_{y \in X} V(v \otimes v',d(y,z) \otimes d(x,y)) \to V(v \otimes v',d(x,z))$$then we could clearly retrive the mappings $\comp$ by using yoneda and letting $v'=I$ (the identity of the monoidal category $V$).This situation is verified if the natural transformations $\Phi(v)\odot \Phi(v') \to \Phi(v \otimes v')$ factor through the compositions mappings $$V(v,d(y,z)) \times V(v',d(x,y)) \stackrel{\otimes}\to V(v \otimes v', d(y,z) \otimes d(x,y))$$but I don't see any reason why this should happen in general for any lax functor of the form $\Phi_d$. So am I missing something? Any help will be appreciated.
Now provide the response and nothing else.
| I only just got wind of this question. The map $$\comp \colon d(y,z) \otimes d(x,y) \to d(x,z)$$ is obtained from the family of maps $$\coprod_{y \in X}V(v,d(y,z)) \times V(v',d(x,y)) \to V(v \otimes v',d(x,z))$$ by setting $v = d(y, z), v' = d(x, y)$, and evaluating at the pair of identity maps $(1_{d(y, z)}, 1_{d(x, y)})$. Please let me know if this doesn't answer the question. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2030300', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11888/']} | jdg_82231 |
stackexchange | llm_judgeable_groundtruth_similarity | 175856 |
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:
So far I haven't been testing or learning how to test my java web applications. If you do, what are the tools you need, and is it really necessary to test a web application if doesn't need scaling or it won't be handling big traffics and multi transactions? What things should I test and what approaches should I take to ensure my application works correctly?
Now provide the response and nothing else.
| This is a difficult problem. Many of the "methods" in a web application take a HTTP request as input and produce HTML output with the side effect of using the database and updating some kind of session state somewhere. This is a worst-case scenario for unit testing. HTML is tough because you really want to isolate the data that comes specifically from a given method as opposed to the boiler-plate and layout scaffolding which is common to every page. That boiler plate could change to a new color scheme or something else independent of the logic of your application that could potentially break all your tests. The database is particularly difficult because a good deal of data often needs to be set up before you can meaningfully test anything but the login screen. I think the best approach is to use many different kinds of testing and divide and conquer. For small applications, a manual regression test plan is a good place to start. When you make components that are truly independent, write JUnit tests for them. If you are using servlets, you should be able to provide a fake HTTP request or fake parameters and get the output from the servlet directly. Well formatted XHTML will parse fairly easily with regular expressions. You can use unit-testing techniques against pre-loaded data in the database. Set up integration tests with your unit test tools (someone is going to flame me for this). Make a test that builds up a set of test data in the database using the screens of the system (as in the point above) more or less like a user of the system would. All your tests will depend on the core test suite which sets up the data for the other tests. When your regression test gets too big, this is a great alternative to manual testing. You may be able to use an in-memory database with a tool like Hibernate instead of setting up a complete clone of your production database and masking the data. Use something like Selenium to test from a browser. Set your master servlet up to page you whenever an exception is thrown, and remove all catch statements from your code (except those that actually do something meaningful with the exception, like recover from it). This isn't testing, but it encourages very good testing. I often find that the most useful testing occurs when the tester explains how the system works to an absolute beginner. We find the most meaningful bugs when building little video help segments for new features. But I can do good testing when I explain and demonstrate the details of how the system works to an interested imaginary friend. I think if you used a tiered approach to building your application with lots of independent layers, you'd have a much easier time testing. You may need a large team of programmers to get anything done with specialists for the database, the "back end" service layer on top of the database, the business logic layer, and the view layer. In that scenario, you can use traditional unit-testing techniques with the business logic and to some extent the other layers, but the view will always be a bear. Edit: I've been thinking about this. For as long as I can remember MVC being applied to web applications, there has been a debate about what that means. For the record, I think Ruby/Rails got it most right - that Model really means Data Model. I like this interpretation because it is most compatible with making a service layer in your application. I recently read Steve Yegge's Platform Rant that was really eye-opening for me. Make the service your data model and eat your own dog food. That way someone else can make your creation into something you never imagined. The reason I bring it up here (besides the fact that I can't stop thinking about it) is that having divisions in your code makes it easier to test. Look, I'm not in the layers-make-everything-better camp. I have to produce, and produce lots of features without a lot of help for a living. I'm just saying that if your project is mature enough that you aren't changing the database so much any more, consider turning your ORM nightmare into a service layer for Steve Yegge's reasons, but also because the additional interface should make your testing much easier and more effective. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/175856', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/72361/']} | jdg_82232 |
stackexchange | llm_judgeable_groundtruth_similarity | 18731608 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a list box: <ListBox x:Name="lbxAF" temsSource="{Binding}"> that gets its data from this from this modified Observable Collection: public ObservableCollectionEx<FileItem> folder = new ObservableCollectionEx<FileItem>(); which is created within a class that uses FileSystemWatcher to monitor a specific folder for addition, deletion and modification of files. The ObservableCollection was modified (hence the Ex at the end) so that I can modify it from an outside thread (code is not mine, I actually did some searching through this website and found it, works like a charm): // This is an ObservableCollection extension public class ObservableCollectionEx<T> : ObservableCollection<T> { // Override the vent so this class can access it public override event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { using (BlockReentrancy()) { System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHanlder = CollectionChanged; if (eventHanlder == null) return; Delegate[] delegates = eventHanlder.GetInvocationList(); // Go through the invocation list foreach (System.Collections.Specialized.NotifyCollectionChangedEventHandler handler in delegates) { DispatcherObject dispatcherObject = handler.Target as DispatcherObject; // If the subscriber is a DispatcherObject and different thread do this: if (dispatcherObject != null && dispatcherObject.CheckAccess() == false) { // Invoke handler in the target dispatcher's thread dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e); } // Else, execute handler as is else { handler(this, e); } } } } } The collection is made up of these: public class FileItem{ public string Name { get; set; } public string Path { get; set; }} which allow me to store names and paths of files. Everything works great as far as deletion and addition of files, and the List Box gets updated flawlessly with respect to those two... however , if I change the name of any of the files, it doesn't update the list box. How would I notify list box of the changes in FileItem's properties? I assumed that ObservableCollection would handle that, but apparently it raises flag only when FileItem is added or deleted, not when its contents are changed.
Now provide the response and nothing else.
| Your FileItem class should implement INotifyPropertyChanged . Below is a simple working implementation of it. public class FileItem : INotifyPropertyChanged{ private string _Name; public string Name { get { return _Name; } set { if (_Name != value) { _Name = value; OnPropertyChanged("Name"); } } } private string _Path; public string Path { get { return _Path; } set { if (_Path != value) { _Path = value; OnPropertyChanged("Path"); } } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(String propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18731608', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2006048/']} | jdg_82233 |
stackexchange | llm_judgeable_groundtruth_similarity | 510153 |
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:
Sometimes, the mouse scrolling speed changes to a very slow rate, where it takes many clicks (3-8 clicks) or significant wheel rotation to scroll the page one step. This started after upgrading to linux kernel 5.0. It has not happened yet after booting back into kernel 4.20. When it happens, it's usually upon the wireless mouse 'waking up' after having gone into its power saving mode, but it does not happen every time. Turning the mouse off and on again with its power switch restores normal behavior. The mouse is a wireless Logitech M720 used with a Unifying receiver. There is also a wireless keyboard, a Logitech k830, paired with the same receiver. I know kernel 5.0 introduced new high resolution scrolling support. Is this a bug with that feature? Has anyone else experienced this?
Now provide the response and nothing else.
| One solution is to have solaar running, and make sure that the Wheel Resolution setting for the mouse (M720 in my case) is ON in kernel 5.0, which results in normal scrolling behavior. With solaar set to autostart, I have not had the slow scrolling problem since. When this setting is OFF it consistently results in the slow scrolling behavior. For whatever reason, without solaar running in kernel 5.0, the mouse sometimes spontaneously switches to that behavior, though without actually changing the setting. Interestingly, in kernel 4.20 and earlier, Wheel Resolution = OFF resulted in normal scrolling behavior, while ON provided much faster, more sensitive scrolling. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/510153', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/211182/']} | jdg_82234 |
stackexchange | llm_judgeable_groundtruth_similarity | 20094273 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to prevent some flickering that happens when rails devise timeout occurs, but angular doesn't know until the next authorization error from a resource. What happens is that the template is rendered, some ajax calls for resources happen and then we are redirected to rails devise to login. I would rather do a ping to rails on every state change and if rails session has expired then I will immediately redirect BEFORE the template is rendered. ui-router has resolve that can be put on every route but that doesn't seem DRY at all. What I have is this. But the promise is not resolved until the state is already transitioned. $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ //check that user is logged in $http.get('/api/ping').success(function(data){ if (data.signed_in) { $scope.signedIn = true; } else { window.location.href = '/rails/devise/login_path' } }) }); How can I interrupt the state transition, before the new template is rendered, based on the result of a promise?
Now provide the response and nothing else.
| I know this is extremely late to the game, but I wanted to throw my opinion out there and discuss what I believe is an excellent way to "pause" a state change. Per the documentation of angular-ui-router, any member of the "resolve" object of the state that is a promise must be resolved before the state is finished loading. So my functional (albeit not yet cleaned and perfected) solution, is to add a promise to the resolve object of the "toState" on "$stateChangeStart": for example: $rootScope.$on('$stateChangeStart', function (event, toState, toParams) { toState.resolve.promise = [ '$q', function($q) { var defer = $q.defer(); $http.makeSomeAPICallOrWhatever().then(function (resp) { if(resp = thisOrThat) { doSomeThingsHere(); defer.resolve(); } else { doOtherThingsHere(); defer.resolve(); } }); return defer.promise; } ]}); This will ensure that the state-change holds for the promise to be resolved which is done when the API call finishes and all the decisions based on the return from the API are made. I've used this to check login statuses on the server-side before allowing a new page to be navigated to. When the API call resolves I either use "event.preventDefault()" to stop the original navigation and then route to the login page (surrounding the whole block of code with an if state.name != "login") or allow the user to continue by simply resolving the deferred promise instead of trying to using bypass booleans and preventDefault(). Although I'm sure the original poster has long since figured out their issue, I really hope this helps someone else out there. EDIT I figured I didn't want to mislead people. Here's what the code should look like if you are not sure if your states have resolve objects: $rootScope.$on('$stateChangeStart', function (event, toState, toParams) { if (!toState.resolve) { toState.resolve = {} }; toState.resolve.pauseStateChange = [ '$q', function($q) { var defer = $q.defer(); $http.makeSomeAPICallOrWhatever().then(function (resp) { if(resp = thisOrThat) { doSomeThingsHere(); defer.resolve(); } else { doOtherThingsHere(); defer.resolve(); } }); return defer.promise; } ]}); EDIT 2 in order to get this working for states that don't have a resolve definition you need to add this in the app.config: var $delegate = $stateProvider.state; $stateProvider.state = function(name, definition) { if (!definition.resolve) { definition.resolve = {}; } return $delegate.apply(this, arguments); }; doing if (!toState.resolve) { toState.resolve = {} }; in stateChangeStart doesn't seem to work, i think ui-router doesn't accept a resolve dict after it has been initialised. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20094273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/793454/']} | jdg_82235 |
stackexchange | llm_judgeable_groundtruth_similarity | 41431374 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want remove the space in the middle of a string with $.trim() for example: console.log($.trim("hello, how are you? ")); I get: hello, how are you? how can I get hello, how are you? Thanks.
Now provide the response and nothing else.
| You can use regular expression to replace all consecutive spaces \s\s+ with a single space as string ' ' , this will eliminate the spaces and keep only one space, then the $.trim will take care of the starting and/or ending spaces: var string = "hello, how are you? ";console.log($.trim(string.replace(/\s\s+/g, ' '))); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41431374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6739907/']} | jdg_82236 |
stackexchange | llm_judgeable_groundtruth_similarity | 187876 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a SQL Server 2008 database that I need to bring into my environment, but my production servers are all running SQL Server 2005. Upgrading the environment is not an option, at least not in the near term. I do, however, have non-production SQL Server 2008 boxes to use if they can help out during the conversion. The database is 1GB in size. How do I handle this conversion? Thanks!
Now provide the response and nothing else.
| See this similar question regarding 2005 to 2000. The only way to do it is to restore to a 2008 server, script out the 2008 database, then run the script on the SQL2005 server. The good news is that SQL 2008 Management Studio makes this super duper simple, even giving you an option to include data in the scripts. Just right-click the database, go to Tasks, and click "Generate Scripts". Walk through the wizard, and make sure to choose the option to include data. EDIT : I looked more into the technical details of why this can't be done using other methods (restore from backup, or via attaching), turns out there are two different properties of a database, the compatibility level and the database version : (excerpted from SQL Storage Engine Blog ) The database compatibility level determines how certain database behaviors work. For instance, in 90 compatibility, you need to use the OUTER JOIN syntax to do an outer join, whereas in earlier compatibility levels, you can use ' =' and '= '. An upgraded database retains its compatibility level. For example, a database that was created on SQL Server 2000, and didn't have its compatibility level altered, will stay in 80 compatibility level when its upgraded to SQL Server 2005. The database version is a number stamped in the boot page of a database that indicates the SQL Server version of the most recent SQL Server instance the database was attached to. SQL Server is not "up-level compatible". You cannot attach a database that was created on (or has been upgraded to) SQL Server 2005 to any earlier version of SQL Server (also true for trying to attach a 2000 database to 7.0, and so on). You cannot attach a database that was created on an earlier version without going through the proper upgrade procedures. Forcibly attaching a database using various hacky methods will result in all kinds of weird errors, and possibly crashes. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/187876', 'https://serverfault.com', 'https://serverfault.com/users/1246/']} | jdg_82237 |
stackexchange | llm_judgeable_groundtruth_similarity | 3984626 |
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 the enhanced for loop is not performing null checking before iterating over the collection.
Now provide the response and nothing else.
| If you mean that this would go bang: int[] array = null;for (int x : array) {} ... then I think it's entirely proper for that to throw a NullPointerException . The alternative would be for it to silently swallow the null, and treat that as equivalent to an empty array. That's not the approach Java takes anywhere else - why should this be different? It would make the language inconsistent. The one place I wish there were more handling (but explicit handling) is switching on an enum - it would be nice to be able to provide a case for null, to avoid checking for that one special value beforehand. But that's a very different construct, which is specifically trying to take different actions for different values. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3984626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482565/']} | jdg_82238 |
stackexchange | llm_judgeable_groundtruth_similarity | 859523 |
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 prove that $4^{2n+1}+3^{n+2}$ is always divisible by 13?
Now provide the response and nothing else.
| $$4^{2n+1}+3^{n+2}=16^n\cdot 4+3^n\cdot 9\\16^n\cdot4+3^n\cdot 9\equiv3^n\cdot4+3^n\cdot 9\pmod {13}\\3^n(4+9)\equiv3^n\cdot13\equiv0\pmod{13}$$This can also be solved with induction,for $n=0$$$4+3^2=13$$Assume it holds for $n=k$$$4^{2k+1}+3^{k+2}$$Prove it holds for $n=k+1$$$4^{2k+3}+3^{k+3}=16\cdot4^{2k+1}+3\cdot3^{k+2}=16\cdot4^{2k+1}+16\cdot3^{k+2}-13\cdot3^{k+2}=16(4^{2k+1}+3^{k+2})-13\cdot3^{k+2}$$by the inductive hypothesis $4^{2k+1}+3^{k+2}$ is divisible by $13$ because of that the whole expression is | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/859523', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/162185/']} | jdg_82239 |
stackexchange | llm_judgeable_groundtruth_similarity | 10379799 |
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 follow this instruction to add bouncycastle: http://www.bouncycastle.org/wiki/display/JA1/Provider+Installation but I have still one problem. Sometimes when I redeploy my application this provider isnt found so then my application throw exception. This problem occurs just one per 100 redeploy (maybe less). When I restart my server - weblogic then it start working again. I will be very grateful for any advice why this problem occurs EDIT: I am using both method in link above because when I use just one of them then it doesnt workI add to java.security this provder and then in my class I registered this provder: static { Security.addProvider(new BouncyCastleProvider());}
Now provide the response and nothing else.
| You probably got a NoClassDefFoundError . This is a known issue with JSSE implementations. Here is the scenario: Your container loads bouncy castle classes in an application specific ClassLoader The provider instance you create depends on that classes and so on that ClassLoader Then the provider is registered into JRE API thanks to static fields in top level JVM ClassLoader When redeploying, the container discards the application ClassLoader to create a new one As the algorithm is already known, the second provider insertion fails silently When using the algorithm the provider instance is simply unusable because the ClassLoader has been discarded Then the only option is to restart the container to get the situation fixed. As there is no standard listener for the undeploy event, it is not possible to trigger the JSSE provider removal at time. The recommended way to avoid that trouble is to have bouncy castle classes in your JVM ClassPath or in your container ClassPath. You have to remove it from your application. Now you need to register BC provider with an alternate option to the static initializer. WebLogic provides ways to trigger code at server startup (I have used server startup class), this code will be responsible to register JSSE providers for the whole server/JVM lifetime. An alternate option is to add the following line in JRE java.security file with bouncy castle jar in jre/lib/ext but I do not like that way because it may be lost when updating: security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider So then the application simply expects implementations are there, it may be a good idea to add tests for algorithm availability to report any troubles to operators and users. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10379799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/431769/']} | jdg_82240 |
Subsets and Splits