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
|
1645671
|
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:
When m = 2, series is 1,2,3,4,5.. m = 3 : 1,3,6,10,15..m = 4 : 1,4,10,20,35..m = 5 : 1,5,15,35,70..m = 6 : 1,6,21,56,126.. So given value of m, can I find the entire series ? Thank you
Now provide the response and nothing else.
|
As usual $[n]=\{1,\ldots,n\}$. $\sum_{k=1}^{n-1}\binom{n}k$ is clearly the number of non-empty, proper subsets of $[n]$, since $\binom{n}k$ is the number of subsets of size $k$. Now let $A_k$ be the number of subsets of $[n]$ with maximum element $k$; clearly $|A_k|=2^{k-1}$, since the rest of $A_k$ can be any subset of $[k-1]$. Thus, $$\left|\bigcup_{k=1}^nA_k\right|=\sum_{k=1}^n2^{k-1}=1+\sum_{k=1}^{n-1}2^k\;.\tag{1}$$ On the other hand, $\bigcup_{k=1}^nA_k$ is clearly the set of non-empty subsets of $[n]$, so $(1)$ counts all of the non-empty, proper subsets of $[n]$ plus the set $[n]$ itself. Subtracting $1$ for the set $[n]$ leaves the desired result: both $\sum_{k=1}^{n-1}\binom{n}k$ and $\sum_{k=1}^{n-1}2^k$ count the non-empty, proper subsets of $[n]$, and they must therefore be equal.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1645671', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/297144/']}
|
jdg_377141
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21566649
|
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 just getting started into python and flask (for the raspberry pi). I want a web application that would execute some python code to pan and tilt a camera and display a video stream. My code up until now for flask is: from flask import Flask, render_templateimport timeimport serial#ser = serial.Serial('/dev/ttyUSB0',9600)app = Flask(__name__)@app.route('/')@app.route('/<cmd>') #each button in my html redirects to a specified directorydef execute(cmd=None): if cmd == "down": print "Moving Down" #ser.write("D") if cmd == "up": print "Moving Up" #ser.write("U") if cmd == "left": print "Moving Left" # ser.write("L") if cmd == "right": print "Moving Right" #ser.write("R") if cmd == "reset": print "Reseting.." #ser.write("X") return render_template("main.html")if __name__ == "__main__": app.run(host='0.0.0.0', port=8080, debug=True) The problem is my code relies on the each button redirecting to a new directory, while this does work well, it refreshes the page each time which means my embedded video reloads and buffers again. Is there a better way of detecting a button press and then executing python code using flask?
Now provide the response and nothing else.
|
I would split it out into two routes to make it easier to see what you have to do: LEFT, RIGHT, UP, DOWN, RESET = "left", "right", "up", "down", "reset"AVAILABLE_COMMANDS = { 'Left': LEFT, 'Right': RIGHT, 'Up': UP, 'Down': DOWN, 'Reset': RESET}@app.route('/')def execute(): return render_template('main.html', commands=AVAILABLE_COMMANDS)@app.route('/<cmd>')def command(cmd=None): if cmd == RESET: camera_command = "X" response = "Resetting ..." else: camera_command = cmd[0].upper() response = "Moving {}".format(cmd.capitalize()) # ser.write(camera_command) return response, 200, {'Content-Type': 'text/plain'} Then in your template you just need to use some JavaScript to send off the request: {# in main.html #}{% for label, command in commands.items() %} <button class="command command-{{ command }}" value="{{ command }}"> {{ label }} </button>{% endfor %}{# and then elsewhere #}<script>// Only run what comes next *after* the page has loadedaddEventListener("DOMContentLoaded", function() { // Grab all of the elements with a class of command // (which all of the buttons we just created have) var commandButtons = document.querySelectorAll(".command"); for (var i=0, l=commandButtons.length; i<l; i++) { var button = commandButtons[i]; // For each button, listen for the "click" event button.addEventListener("click", function(e) { // When a click happens, stop the button // from submitting our form (if we have one) e.preventDefault(); var clickedButton = e.target; var command = clickedButton.value; // Now we need to send the data to our server // without reloading the page - this is the domain of // AJAX (Asynchronous JavaScript And XML) // We will create a new request object // and set up a handler for the response var request = new XMLHttpRequest(); request.onload = function() { // We could do more interesting things with the response // or, we could ignore it entirely alert(request.responseText); }; // We point the request at the appropriate command request.open("GET", "/" + command, true); // and then we send it off request.send(); }); }}, true);</script>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21566649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3264137/']}
|
jdg_377142
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
113827
|
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:
Buildroot is generating images for an embedded device where they should run. This is working very well. In those images, the rootfs is included. Due to some research, I'd like to look into that generated file (e.g. different compression modes set by the Buildroot were applied and now shall be checked if they were correctly done), but I can't find something useful in the Net. As far as I know, the difference between a uImage and zImage is just a small header, so u-boot is able to read that binary file. But I can open neither uImage nor the zImage. Can anyone give me a hint of how to decompress those (u/z)Images on the host?
Now provide the response and nothing else.
|
mkimage -l uImage Will dump the information in the header. tail -c+65 < uImage > out Will get the content. tail -c+65 < uImage | gunzip > out will get it uncompressed if it was gzip-compressed. If that was an initramfs, you can do cpio -t < out or pax < out to list the content. If it's a ramdisk image, you can try and mount it with: mount -ro loop out /mnt file out could tell you more about what it is.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/113827', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/56989/']}
|
jdg_377143
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4062982
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ok so I know that Set , List and Map are interfaces but what makes the first line of code any better than the second line? List myArr = new ArrayList();ArrayList myArr = new ArrayList();
Now provide the response and nothing else.
|
If you use the first form, you are saying all you are ever going to use is the functionality of the List interface - nothing else, especially nothing extra added by any implementation of it. This means you can easily change the implementation used (e.g. just substitute LinkedList for ArrayList in the instantiation), and not worry about it breaking the rest of the code because you might have used something specific to ArrayList .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4062982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/406777/']}
|
jdg_377144
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50857625
|
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 Java, we've got some code that takes a complex java object and serializes it to json. It then writes that json directly to the markup of a page, in a script tag, assigning it to a variable. // Get object as JSON using JacksonObjectWriter jsonWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();String json = jsonWriter.writeValueAsString(complexObject);// Write JSON out to page, and assign it to a javascript variable.Writer out = environment.getOut();out.write("var data = " + json); The complex object can have end user content in it, which could open us up to XSS attacks. How can I get a json version of the complex java object that has each json attribute HTML escaped, to protect against XSS injection? I've read the OWASP XSS Guide and the best I've come up with so far is this, which HTML escapes the entire JSON string, then undoes the quotes, so it can be assigned to a variable in javascript. I'm sure there are better ways to do this, but this seems to work. Any suggestions? private String objectToHtmlEscapedJson(Object value) { try { String result = jsonWriter.writeValueAsString(value); result = StringEscapeUtils.escapeHtml(result); result = result.replace(""", "\""); return result; } catch (JsonProcessingException e) { return "null"; }}
Now provide the response and nothing else.
|
A possible approach could be to iterate over the object entries and individually escape each key and value once the node is constructed by your chosen library. Following my comment above, I've implemented a simple recursive solution using both Jackson (from your question) and GSON , a different library where objects are slightly easier to construct and the code is more readable. The escaping mechanism used is the OWASP Java Encoder : Jackson private static JsonNode clean(JsonNode node) { if(node.isValueNode()) { // Base case - we have a Number, Boolean or String if(JsonNodeType.STRING == node.getNodeType()) { // Escape all String values return JsonNodeFactory.instance.textNode(Encode.forHtml(node.asText())); } else { return node; } } else { // Recursive case - iterate over JSON object entries ObjectNode clean = JsonNodeFactory.instance.objectNode(); for (Iterator<Map.Entry<String, JsonNode>> it = node.fields(); it.hasNext(); ) { Map.Entry<String, JsonNode> entry = it.next(); // Encode the key right away and encode the value recursively clean.set(Encode.forHtml(entry.getKey()), clean(entry.getValue())); } return clean; }} GSON private static JsonElement clean(JsonElement elem) { if (elem.isJsonPrimitive()) { // Base case - we have a Number, Boolean or String JsonPrimitive primitive = elem.getAsJsonPrimitive(); if(primitive.isString()) { // Escape all String values return new JsonPrimitive(Encode.forHtml(primitive.getAsString())); } else { return primitive; } } else if (elem.isJsonArray()) { // We have an array - GSON requires handling this separately JsonArray cleanArray = new JsonArray(); for(JsonElement arrayElement: elem.getAsJsonArray()) { cleanArray.add(clean(arrayElement)); } return cleanArray; } else { // Recursive case - iterate over JSON object entries JsonObject obj = elem.getAsJsonObject(); JsonObject clean = new JsonObject(); for(Map.Entry<String, JsonElement> entry : obj.entrySet()) { // Encode the key right away and encode the value recursively clean.add(Encode.forHtml(entry.getKey()), clean(entry.getValue())); } return clean; }} Sample input (both libraries): { "nested": { "<html>": "<script>(function(){alert('xss1')})();</script>" }, "xss": "<script>(function(){alert('xss2')})();</script>"} Sample output (both libraries): { "nested": { "<html>": "<script>(function(){alert('xss1')})();</script>" }, "xss": "<script>(function(){alert('xss2')})();</script>"}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50857625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26510/']}
|
jdg_377145
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4646786
|
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 planning to use dynamic keyword for my new project. But before stepping in, I would like to know about the pros and cons in using dynamic keyword over Reflection. Following where the pros, I could find in respect to dynamic keyword: Readable\Maintainable code. Fewer lines of code. While the negatives associated with using dynamic keyword, I came to hear was like: Affects application performance. Dynamic keyword is internally a wrapper of Reflection. Dynamic typing might turn into breeding ground for hard to find bugs. Affects interoperability with previous .NET versions. Please help me on whether the pros and cons I came across are sensible or not?
Now provide the response and nothing else.
|
Please help me on whether the pros and cons I came across are sensible or not? The concern I have with your pros and cons is that some of them do not address differences between using reflection and using dynamic. That dynamic typing makes for bugs that are not caught until runtime is true of any dynamic typing system. Reflection code is just as likely to have a bug as code that uses the dynamic type. Rather than thinking of it in terms of pros and cons, think about it in more neutral terms. The question I'd ask is "What are the differences between using Reflection and using the dynamic type?" First: with Reflection you get exactly what you asked for. With dynamic, you get what the C# compiler would have done had it been given the type information at compile time . Those are potentially two completely different things. If you have a MethodInfo to a particular method, and you invoke that method with a particular argument, then that is the method that gets invoked , period. If you use "dynamic", then you are asking the DLR to work out at runtime what the C# compiler's opinion is about which is the right method to call. The C# compiler might pick a method different than the one you actually wanted. Second: with Reflection you can (if your code is granted suitably high levels of trust) do private reflection. You can invoke private methods, read private fields, and so on. Whether doing so is a good idea, I don't know. It certainly seems dangerous and foolish to me, but I don't know what your application is. With dynamic, you get the behaviour that you'd get from the C# compiler; private methods and fields are not visible. Third: with Reflection, the code you write looks like a mechanism . It looks like you are loading a metadata source, extracting some types, extracting some method infos, and invoking methods on receiver objects through the method info. Every step of the way looks like the operation of a mechanism . With dynamic, every step of the way looks like business logic . You invoke a method on a receiver the same way as you'd do it in any other code. What is important? In some code, the mechanism is actually the most important thing. In some code, the business logic that the mechanism implements is the most important thing. Choose the technique that emphasises the right level of abstraction. Fourth: the performance costs are different. With Reflection you do not get any cached behaviour, which means that operations are generally slower, but there is no memory cost for maintaining the cache and every operation is roughly the same cost. With the DLR, the first operation is very slow indeed as it does a huge amount of analysis, but the analysis is cached and reused. That consumes memory, in exchange for increased speed in subsequent calls in some scenarios. What the right balance of speed and memory usage is for your application, I don't know.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4646786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/350670/']}
|
jdg_377146
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5174594
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Anyone have a listing of the default font settings Apple uses in the UITableViewCells, UILabel etc? Also the positioning information for the textLabel in the UITableViewCell both grouped and plain would be fantastic.
Now provide the response and nothing else.
|
Are you familiar with the debugger? It knows all. To get access to the layout, try the following in gdb. I set the breakpoint in - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath which is called right before the cell is displayed (note: there's a background image in my cell) (gdb) po cell<UITableViewCell: 0x59e9920; frame = (0 66; 320 44); text = '396 Studio'; autoresize = W; layer = <CALayer: 0x59e9a00>>(gdb) po [cell subviews]<__NSArrayM 0x4eaf730>( <UIImageView: 0x59ea660; frame = (0 0; 320 100); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x59ea690>>, <UITableViewCellContentView: 0x59e9eb0; frame = (9 0; 302 44); layer = <CALayer: 0x59ea070>>)(gdb) po [[[cell subviews] objectAtIndex:1] subviews]<__NSArrayM 0x4eaf700>( <UILabel: 0x59e9170; frame = (0 0; 0 0); text = '396 Studio'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x59e91e0>>, <UITableViewLabel: 0x59e65c0; frame = (0 0; 0 0); text = 'Houston'; clipsToBounds = YES; userInteractionEnabled = NO; layer = <CALayer: 0x59e6690>>)(gdb) po [0x59e9170 font]<UICFFont: 0x5e12610> font-family: "Helvetica"; font-weight: bold; font-style: normal; font-size: 0px(gdb) p (CGRect)[cell frame]$1 = { origin = { x = 0, y = 66 }, size = { width = 320, height = 44 }} po = print object p = print, but you have to cast the value to the type you know it is no property access cell.frame - use objective-c methods [cell frame] Also, here is a 4 year old, but still useful article on iPhone fonts: daring fireball .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5174594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/519493/']}
|
jdg_377147
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
283759
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I use tmux to develop, with two panes: one to edit the code, and one to compile it. I need to switch pane very often to launch the compile command (say " mvn install "). How can I bind a key (say " Ctrl + B C ") to launch that specific command in the other pane (or without any pane at all)?
Now provide the response and nothing else.
|
C-b c already has a standard binding which it might be wise to leave unchanged. Choosing another character, eg C-b C you can setup a binding in your ~/.tmux.conf file as follows: bind C send-keys -t.- 'mvn install' Enter The -t.- means "the other pane". Enter stands for the key of that name, i.e. the newline at the end of the command.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/283759', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/170834/']}
|
jdg_377148
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5529
|
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am confused, can evolution ( speciation ) really occur in such a short time ? In 1971, biologists moved five adult pairs of Italian wall lizards from their home island of Pod Kopiste, in the South Adriatic Sea, to the neighboring island of Pod Mrcaru. Now, an international team of researchers has shown that introducing these small, green-backed lizards, Podarcis sicula , to a new environment caused them to undergo rapid and large-scale evolutionary changes." Here is a short video featuring the scientist. Two related articles: http://www.sciencedaily.com/releases/2008/04/080417112433.htm http://news.nationalgeographic.com/news/2008/04/080421-lizard-evolution.html Edit: I asked a similar question previously about two people having 44 chromosomes and their possibility of creating a new species. You might like to read/answer that as well: Can two humans with 44 chromosomes produce viable offspring?
Now provide the response and nothing else.
|
I am confused, can evolution ( speciation ) really occur in such a short time? Well, Evolution and Speciation are not the same. Evolution is the adaptation of an existing species to an environment over generations. Speciation is the development of a new species, and the definition of "species" can vary depending on who you talk to - but a very commonly accepted one is that two individuals cannot produce fertile offspring. However, the answer is still Yes . Evolution can occur in as little as two generations because that's all the time it takes for a change in the DNA to be exhibited in the newest generation. For instance, Lactase Persistence - which allows the bearers to ingest dairy products without digestive stress into adulthood - has evolved at least twice in humans in separate groups. Both are the result of either one or two point mutations (single changes in a Nucleotide within the DNA). The result is that at one point in time for each appearance of lactase persistence, a child was born that could drink milk into adulthood while their parents and cousins could not. That is evolution; the child was better adapted to the resources available, and because lactase persistence either... Provided a significant advantage over their kin in the environment (which is likely, as being able to digest milk in an agrarian society opens up a new source of energy)... or Didn't hinder the child's ability to grow and produce fertile offspring of their own... ...it has persisted in the populations where it initially evolved. Speciation is a little trickier, but that's because there isn't a known qualitative way to differentiate species at the genetic level quite yet. It could be a few key gene changes, it could be a whole genome difference of 10%, or a million other factors. Practically speaking, though, Speciation is simply the result of accumulated genome changes that at some point prevent the members of one group from producing fertile offspring with their ancestral group. Because we simply don't know how much of or where the genome has to change, it's certainly possible that speciation could occur in the same time period as it takes to evolve: Two generations . Since I'm doubting the wall lizards have a generational time of >37 years (don't mistake it for lifespan, humans can reproduce in our teens - even if we live into our 80's), it's definitely possible that the wall lizards could evolve (and potentially speciate) in such a short amount of time. With organisms that have a very, very short generational time - like E. coli or other bacteria - you can observe the Evolution of populations in days or hours.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/5529', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/504/']}
|
jdg_377149
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50691469
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is the code I am working upon. I dont know where I am going wrong. package mcdcpairwise;import java.io.*;import java.util.*;public class Permutation{ public static void main(String[] args) { String a="000"; String b="|&"; for (int i=0; i < a.length(); i++){ if (i % 2 != 0){ a = a.substring(0,i-1) + b.substring(0,i-1). + a.substring(i, a.length()) + b.substring(i, b.length()); System.out.println(a); } } }} The error I am facing is: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2 at java.lang.String.substring(String.java:1967) at mcdcpairwise.Permutation.main(Permutation.java:13) The output should be : 0|0&0
Now provide the response and nothing else.
|
You have several issues: You're not calling an actual API, you're scraping a web page, which means that: you're most likely violating Google's TOS you're more likely to get rate-limited (or be detected as abuse and blacklisted) at some point if you're fetching this page too often you're dependent on any change made in the HTML structure of the web page You're scraping the page every single time you need to convert an amount to another currency, which means that any failure makes your currency conversion fail. What you should do: load exchange rates from a legitimate feed or API load them on a regular basis (via a cron job for example) and save them to a local database , that will be used to perform currency conversions This way, even if an API call fails, you still have access to a slightly outdated exchange rate, which is better than a failure in most cases. Where do you find a trustable exchange rate feed? There are plenty of APIs, free or not, that offer this service. A good source I know of is the European Central Bank, who provides an XML feed that's been there for years and provides exchange rates for 32 currencies relative to EUR . OpenExchangeRates also offers a free plan with a limit of 1,000 requests per month, which is enough to refresh rates every hour. It provides exchange rates for 170 currencies, relative to USD . How do you store the values in your database? Whichever feed you choose, you need to parse it (if XML) or json_decode() it (if JSON) and store the values in your database. Ideally, set up a cron job to run your import script daily or even hourly. The actual parsing and importing steps are outside the scope of this question, but let's assume a simple MySQL table that holds the records: CREATE TABLE exchange_rate( target_currency CHAR(3) COLLATE ascii_bin NOT NULL PRIMARY KEY, exchange_rate DOUBLE NOT NULL); How to properly handle currency conversions based on rates relative to a single currency? This is a question I've answered recently . The feeds above give you rates to convert the base currency ( EUR or USD ) to another currency, but do not give you a clue on how to convert between two arbitrary currencies. I would suggest you use a proper library that handles these conversions for you, such as brick/money - disclaimer: I'm the author . Here is how you would configure it to load your exchange rates from the table above: use Brick\Money\CurrencyConverter;use Brick\Money\ExchangeRateProvider\PDOProvider;use Brick\Money\ExchangeRateProvider\PDOProviderConfiguration;use Brick\Money\ExchangeRateProvider\BaseCurrencyProvider;// set to whatever your rates are relative to$baseCurrency = 'USD';// use your own credentials, or re-use your existing PDO connection$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');$configuration = new PDOProviderConfiguration();$configuration->tableName = 'exchange_rate';$configuration->exchangeRateColumnName = 'exchange_rate';$configuration->targetCurrencyColumnName = 'target_currency';$configuration->sourceCurrencyCode = $baseCurrency;// this provider loads exchange rates from your database$provider = new PDOProvider($pdo, $configuration);// this provider calculates exchange rates relative to the base currency$provider = new BaseCurrencyProvider($provider, $baseCurrency);// this currency converter can now handle any currency pair$converter = new CurrencyConverter($provider); And how you would use it: use Brick\Math\RoundingMode;use Brick\Money\Money;$money = Money::of(10, 'EUR'); // EUR 10.00$converter->convert($money, 'CAD', RoundingMode::DOWN); // CAD 15.27
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50691469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9894389/']}
|
jdg_377150
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1832958
|
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 $e$ be an edge of $K_n$- the complete graph on $n$ vertices.Prove that the number of labelled spanning trees of $K_n-e$ is $(n-2)n^{n-3}$. I think the answer lies in using some modified form of Prüfer's sequence but I can't quite nail it.
Now provide the response and nothing else.
|
You know that $K_n$ has $n^{n-2}$ spanning trees, right? You want to find out how many of those spanning trees do not contain the edge $e.$ You can do that by finding the number of spanning trees that do contain $e$ and subtracting that from $n^{n-2}.$ By symmetry, each edge of $K_n$ is in the same number of spanning trees, call that number $t.$ Let $p$ be the number of pairs $(T,e)$ where $T$ is a spanning tree of $K_n$ and $e$ is an edge of $T.$ On the one hand, $p=\binom n2t,$ since there are $\binom n2$ edges and each edge is in $t$ spanning trees. On the other hand, $p=n^{n-2}(n-1),$ since there are $n^{n-2}$ spanning trees and each spanning tree contains $n-1$ edges. Solving the equation $\binom n2t=n^{n-2}(n-1)$ for $t,$ we get $t=2n^{n-3}.$ Finally, the number of spanning trees of $K_n-e$ is$$n^{n-2}-2n^{n-3}=\boxed{(n-2)n^{n-3}}.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1832958', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/127598/']}
|
jdg_377151
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4159545
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A metric $d$ is a function $d:X \times X \to \mathbb{R}$ such that $d(x,y)\geq 0$ and equals $0$ iff $x=y$ . $d(x,y)=d(y,x)$ and the triangle inequality holds. From these requirements, the only things that are used is that the codomain has a $0$ , a $+$ operation and a linear order. So, it seems, we could in principle define a metric by a function $d: X \times X \to G$ such the same expressions hold, and where $G$ is an ordered group. My question is, what usual theorems do we lose by picking that definition? In particular, some key questions come to mind If there is a metric on a space $X$ , when allowing for other groups in the codomain, does that imply there is a metric with codomain $\mathbb{R}$ ? That is, does the collection of metrizable spaces expand with the new definition? A kind of converse to the previous one, for any infinite ordered group $G$ , if there is metric with codomain $\mathbb R$ , is there necessarily one with codomain $G$ that generates the same topology? (it being infinite is necessary as the trivial group satisfies all the metric properties but always generates the discrete topology).
Now provide the response and nothing else.
|
The "ultimate generalisation" of such an idea (it's old) is due to Kopperman all topologies come from generalised metrics (Amer. Math. Monthly (95) 1988, nr 2, 89-97). I saw his talk on this around that time... He considers a semigroup $A$ (so just an associative binary operation) with identity $0$ and $\infty \neq 0$ an absorbing element and calls it a value semigroup if If $a+x=b$ and $b+y=a$ , then $a=b$ . In that case $a \le b$ iff $\exists x: a+x=b$ defines a partial order on $A$ . For each $b$ there is a unique $a$ so that $b+b =a$ (and we write $b = \frac12 a$ ). For all $a,b$ , $a \land b = \inf\{a,b\}$ exists. For all $a,b,c$ we have $(a \land b) + c = (a+c) \land (b+c)$ . A set $P \subseteq A$ , where $A$ is a value semigroup, is called a set of positives if $a,b \in P \to a \land b \in P$ . $r \le a$ and $r \in P$ implies $a \in P$ . if $r \in P$ then $\frac12 r \in P$ as well. if $a \le b+r$ for each $r \in P$ , then $a \le b$ . Finally, if $X$ is a set, $A$ is a value semi-group, $P \subseteq A$ a set of positives, and $d: X \times X \to A$ a function that obeys $d(x,x)=0$ for all $x$ and $d(x,z) \le d(x,y) + d(y,z)$ for all $x,y,z \in X$ , then $(X,A,P,d)$ is called a "continuity space". For $x \in X, r \in P$ we define $B[x,r] = \{y \in X: d(x,y) \le r\}$ and then $\mathcal{T} = \{O \subset X\mid \forall x \in O: \exists r \in P: B[x,r]\subseteq O\}$ defines a topology on $X$ and (Kopperman's theorem) every topology on $X$ is of this form.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4159545', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/580826/']}
|
jdg_377152
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13031250
|
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 interested in function delete_all_between($char1, $char2, $string) that will search given $string for $char1 and $char2 and, if such has been found, clear $string from substring between these two characters, including $char1 and $char2 itself. Example: $string = 'Some valid and <script>some invalid</script> text!';delete_all_between('<script>', '</script>', $string); Now, $string should contain just 'Some valid and text'; //note two spaces between 'and text' Does someone have quick solution?
Now provide the response and nothing else.
|
<?php$string = 'Some valid and <script>some invalid</script> text!';$out = delete_all_between('<script>', '</script>', $string);print($out);function delete_all_between($beginning, $end, $string) { $beginningPos = strpos($string, $beginning); $endPos = strpos($string, $end); if ($beginningPos === false || $endPos === false) { return $string; } $textToDelete = substr($string, $beginningPos, ($endPos + strlen($end)) - $beginningPos); return delete_all_between($beginning, $end, str_replace($textToDelete, '', $string)); // recursion to ensure all occurrences are replaced}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13031250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1352994/']}
|
jdg_377153
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50312999
|
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 parsing dates and times in Rust using the chrono crate . The dates and times are from a website in which the date and time are from different sections of the page. The date is shown in the format %d/%m/%Y (example: 27/08/2018). The time is shown with only the hour (example: 12, 10, 21, etc.) I want to store these datetimes as UTC so that I can compute time remaining until a given datetime from now in a "timezone agnostic" way. I know which timezone these datetimes are from (Paris time). I created a NaiveDate from the date input (this is a work in progress so there's no error handling yet): let naive_date = NaiveDate::parse_from_str(date, "%d/%m/%Y").unwrap() From that point on, what would be the best way to get the UTC DateTime , given that I have a string with the hour? I am lost in the various TimeZone / Offset traits, and do not know if I should use a Local , or FixedOffset and then convert to Utc .
Now provide the response and nothing else.
|
The Chrono documentation could probably be improved to make it easier to find how to do these things. Assuming this is your starting point: use chrono::{DateTime, FixedOffset, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};// The date you parsedlet date = NaiveDate::from_ymd(2018, 5, 13);// The known 1 hour time offset in secondslet tz_offset = FixedOffset::east(1 * 3600);// The known timelet time = NaiveTime::from_hms(17, 0, 0);// Naive date time, with no time zone informationlet datetime = NaiveDateTime::new(date, time); You can then use the FixedOffset to construct a DateTime : let dt_with_tz: DateTime<FixedOffset> = tz_offset.from_local_datetime(&datetime).unwrap(); If you need to convert it to a DateTime<Utc> , you can do this: let dt_with_tz_utc: DateTime<Utc> = Utc.from_utc_datetime(&dt_with_tz.naive_utc());
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50312999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1062022/']}
|
jdg_377154
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1176636
|
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:
Integral: $$I=\int_0^{1/2}\frac{\ln(1+2x)}{1+4x^2}{\rm d}x$$ One thing to quickly do it take $y=2x$:$$I=\frac12\int_0^1\frac{\ln(1+y)}{1+y^2}{\rm d}y$$I took $y=\tan z$:$$I=\frac12\int_0^{\pi/4}\ln(1+\tan z){\rm d}z$$Now substitute $u=\pi/4-z$:$$I=\frac12\int_0^{\pi/4}[\ln2-\ln(1+\tan z)]{\rm d}z=\frac\pi8\ln2-I\\I=\frac\pi{16}\ln 2$$Any other methods?
Now provide the response and nothing else.
|
We have \begin{align}I &= \frac{1}{2} \int_0^1 \frac{\ln(1 + y)}{1 + y^2}\, dy\\& = \frac{1}{2}\int_0^1\int_0^1 \frac{y}{(1 + ry)(1 + y^2)}\, dr\, dy\\& = \frac{1}{2}\int_0^1 \int_0^1 \frac{y}{(1 + ry)(1 + y^2)}\, dy\, dr\\&= \frac{1}{2}\int_0^1 \int_0^1 \left(\frac{r}{(1 + r^2)(1 + y^2)} + \frac{y}{(1 + r^2)(1 + y^2)}- \frac{r}{(1 + r^2)(1 + ry)}\right)\, dy\, dr\\&= \frac{1}{2}\int_0^1 \left(\frac{r}{1 + r^2}\cdot \frac{\pi}{4} + \frac{1}{2(1 + r^2)}\ln(2) - \frac{\ln(1 + r)}{1 + r^2}\right)\, dr\\&= \frac{1}{2}\left(\frac{\pi}{8}\ln(2) + \frac{\pi}{8}\ln(2)\right) - I\\&= \frac{\pi}{8}\ln(2) - I\end{align} So $2I = \frac{\pi}{8}\ln(2)$, or $$I = \frac{\pi}{16}\ln(2).$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1176636', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/67609/']}
|
jdg_377155
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16010680
|
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 started using Redis in my project with the help of the Jedis library. All is working fine but now I have a problem that my functional tests requires Redis to be up which I want to avoid in my Continuous Integration. What is the best way to do this?
Now provide the response and nothing else.
|
Here are few options you have for functional/integration testing: Just start an instance of redis on you CI server. All tests will be responsible to do proper clean up after execution. Try somehow to control redis process, i.e. have some shell script or job on CI server to start/stop it before/after running tests. At least some of the burden of setup/cleanup is removed from tests, as for each independent build you will have independent redis setup. Control redis further by using some in-memory solution like the one you mention for cassandra(if it exists). One thing to mention is that integration tests should not replace unit tests. Unit tests should probably be preferred and they can cover more cases whereas integration tests can be used just to check that all parts of application play nicely together. And i think this is the reason why a lot of people choose to go for option number one. Here is a similar question about mongodb The answer has a link to the project which works for second option(controls mongodb process) If you follow some related links on the project page there's also something called nosql-unit . This one i think tries to cover option three. I didn't use it but looks like it has something for redis too.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16010680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111052/']}
|
jdg_377156
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5117
|
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:
Imagine there's a company A that releases a new graphics adapter. Who manages the process that results in this new graphics adapter being supported by the Linux kernel in the future? How does that proceed? I'm curious how kernel support for any new hardware is handled; on Windows companies develop drivers on their own, but how does Linux get specific hardware support?
Now provide the response and nothing else.
|
Driver support works the same way as with all of open source: someone decides to scratch their own itch. Sometimes the driver is supplied by the company providing the hardware, just as on Windows. Intel does this for their network chips, 3ware does this for their RAID controllers, etc. These companies have decided that it is in their best interest to provide the driver: their "itch" is to sell product to Linux users, and that means ensuring that there is a driver. In the best case, the company works hard to get their driver into the appropriate source base that ships with Linux distros. For most drivers, that means the Linux kernel. For graphics drivers, it means X.org . There's also CUPS for printer drivers, NUT for UPS drivers, SANE for scanner drivers, etc. The obvious benefit of doing this is that Linux distros made after the driver gets accepted will have support for the hardware out of the box. The biggest downside is that it's more work for the company to coordinate with the open source project to get their driver in, for the same basic reasons it's difficult for two separate groups to coordinate anything. Then there are those companies that choose to offer their driver source code directly, only. You typically have to download the driver source code from their web site, build it on your system, and install it by hand. Such companies are usually smaller or specialty manufacturers without enough employees that they can spare the effort to coordinate with the appropriate open source project to get their driver into that project's source base. A rare few companies provide binary-only drivers instead of source code. An example are the more advanced 3D drivers from companies like NVIDIA. Typically the reason for this is that the company doesn't want to give away information they feel proprietary about. Such drivers often don't work with as many Linux distros as with the previous cases, because the company providing the hardware doesn't bother to rebuild their driver to track API and ABI changes. It's possible for the end user or the Linux distro provider to tweak a driver provided as source code to track such changes, so in the previous two cases, the driver can usually be made to work with more systems than a binary driver will. When the company doesn't provide Linux drivers, someone in the community simply decides to do it. There are some large classes of hardware where this is common, like with UPSes and printers. It takes a rare user who a) has the hardware; b) has the time; c) has the skill; and d) has the inclination to spend the time to develop the driver. For popular hardware, this usually isn't a problem because with millions of Linux users, these few people do exist. You get into trouble with uncommon hardware.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/5117', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3086/']}
|
jdg_377157
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
36502
|
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 $f:\mathbb{R}^n\rightarrow \mathbb{R}^n$ be such that $\left\| f(x)-f(y)\right\| =\left\| x-y\right\|$. Is $f$ necessarily surjective? If this is so, you can prove (Mazur-Ulam Theorem) that $f$ is affine, and hence you could classify all isometries of $\mathbb{R}^n$. However, at the moment, I can't think of any good ideas to prove that $f$ is surjective. For that matter, is it even the case that $f$ must be surjective? Any ideas would be most welcomed. Thanks much!
Now provide the response and nothing else.
|
Let's assume WLOG that $f(0) = 0$. For every $r$, it follows that $f$ defines an isometry from the sphere of radius $r$ to the sphere of radius $r$. Proposition: Any isometry $f : X \to X$ of a compact metric space is bijective. Proof. $f$ is clearly injective. Suppose $f$ is not bijective. Then $f(X)$ is compact, so given $x \in X \setminus f(X)$ the distance $\text{dist}(x, f(X))$ is positive. Pick $\epsilon < \text{dist}(x, f(X))$. Let $N$ be the smallest positive integer for which $X$ admits a cover by $N$ open sets of diameter less than $\epsilon$. No such set containing $x$ can intersect $f(X)$, but by pulling back along $f$ it follows that we can find a cover of $X$ by $N-1$ open sets of diameter less than $\epsilon$; contradiction. (In fact any isometry of a compact metric space is a homeomorphism, since a continuous bijection from a compact space to a Hausdorff space is necessarily closed.) Apparently there are counterexamples to the above when $X$ is not compact, but I don't know any nice ones off the top of my head.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/36502', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10109/']}
|
jdg_377158
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26246867
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I do ping www.google.com I get the error message 'ping' is not recognized as an internal or external command operable program or batch file. Here is an example: Then: What could I be doing wrong? I'm using Windows 7, 64 bit There was some tutorial online that said to look up Systems32. And that didnt even show up. In the search at the image there I have also restarted my computer I've had this for over 6 months and its really beginning to cause me problems. Also if you believe this is off topic please explain first :P
Now provide the response and nothing else.
|
Most likely something has removed the system32 directory from your path. Have you installed the Java SDK? It has a reputation for doing that. To check this, at the command prompt type path (followed by enter) If c:\windows\system32 isn't there, it needs to be added back in. To do this: From the desktop, Right click 'Computer', click 'Properties' then click 'Advanced system settings' - this should bring up the System Properties - Advanced tabClick 'Enviornment Variables'Select the system variables 'PATH'Edit PATH and add this line to the front c:\windows\system32;or to be generic (in case you've installed windows on a different drive) %SystemRoot%\system32Start a new command window to check if this has worked (or reboot) existing command windows will use the old path
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26246867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3204869/']}
|
jdg_377159
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
958123
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using in PowerShell, how can I check if an application is locking a file? I like to check which process/application is using the file, so that I can close it.
Now provide the response and nothing else.
|
You can do this with the SysInternals tool handle.exe . Try something like this: PS> $handleOut = handlePS> foreach ($line in $handleOut) { if ($line -match '\S+\spid:') { $exe = $line } elseif ($line -match 'C:\\Windows\\Fonts\\segoeui\.ttf') { "$exe - $line" } }MSASCui.exe pid: 5608 ACME\hillr - 568: File (---) C:\Windows\Fonts\segoeui.ttf...
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/958123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48834/']}
|
jdg_377160
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15181311
|
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 try to start a decision tree with python and sklearn.Working approach was like this: import pandas as pdfrom sklearn import treefor col in set(train.columns): if train[col].dtype == np.dtype('object'): s = np.unique(train[col].values) mapping = pd.Series([x[0] for x in enumerate(s)], index = s) train_fea = train_fea.join(train[col].map(mapping)) else: train_fea = train_fea.join(train[col])dt = tree.DecisionTreeClassifier(min_samples_split=3, compute_importances=True,max_depth=5)dt.fit(train_fea, labels) Now I try to make the same thing with DictVectorizer, but my code doesn't work: from sklearn.feature_extraction import DictVectorizervec = DictVectorizer(sparse=False)train_fea = vec.fit_transform([dict(enumerate(sample)) for sample in train])dt = tree.DecisionTreeClassifier(min_samples_split=3, compute_importances=True,max_depth=5)dt.fit(train_fea, labels) I've got a error in last line: "ValueError: Number of labels=332448 does not match number of samples=55". As I learnt from documentation DictVectorize was designed to transform nominal features into numerical ones. What do I do wrong? corrected (thanks ogrisel for pushing me to make a full example): import pandas as pdimport numpy as npfrom sklearn import tree################################### working exampletrain = pd.DataFrame({'a' : ['a', 'b', 'a'], 'd' : ['e', 'e', 'f'], 'b' : [0, 1, 1], 'c' : ['b', 'c', 'b']})columns = set(train.columns)columns.remove('b')train_fea = train[['b']]for col in columns: if train[col].dtype == np.dtype('object'): s = np.unique(train[col].values) mapping = pd.Series([x[0] for x in enumerate(s)], index = s) train_fea = train_fea.join(train[col].map(mapping)) else: train_fea = train_fea.join(train[col])dt = tree.DecisionTreeClassifier(min_samples_split=3, compute_importances=True,max_depth=5)dt.fit(train_fea, train['c'])########################################### example with DictVectorizer and errorfrom sklearn.feature_extraction import DictVectorizervec = DictVectorizer(sparse=False)train_fea = vec.fit_transform([dict(enumerate(sample)) for sample in train])dt = tree.DecisionTreeClassifier(min_samples_split=3, compute_importances=True,max_depth=5)dt.fit(train_fea, train['c']) Last code was fixed with a help of ogrisel: import pandas as pdfrom sklearn import treefrom sklearn.feature_extraction import DictVectorizerfrom sklearn import preprocessingtrain = pd.DataFrame({'a' : ['a', 'b', 'a'], 'd' : ['e', 'x', 'f'], 'b' : [0, 1, 1], 'c' : ['b', 'c', 'b']})# encode labelslabels = train[['c']]le = preprocessing.LabelEncoder()labels_fea = le.fit_transform(labels) # vectorize training datadel train['c']train_as_dicts = [dict(r.iteritems()) for _, r in train.iterrows()]train_fea = DictVectorizer(sparse=False).fit_transform(train_as_dicts)# use decision treedt = tree.DecisionTreeClassifier()dt.fit(train_fea, labels_fea)# transform resultpredictions = le.inverse_transform(dt.predict(train_fea).astype('I'))predictions_as_dataframe = train.join(pd.DataFrame({"Prediction": predictions}))print predictions_as_dataframe everything works
Now provide the response and nothing else.
|
The way you enumerate your samples is not meaningful. Just print them to make it obvious: >>> import pandas as pd>>> train = pd.DataFrame({'a' : ['a', 'b', 'a'], 'd' : ['e', 'e', 'f'],... 'b' : [0, 1, 1], 'c' : ['b', 'c', 'b']})>>> samples = [dict(enumerate(sample)) for sample in train]>>> samples[{0: 'a'}, {0: 'b'}, {0: 'c'}, {0: 'd'}] Now this is syntacticly a list of dicts but nothing like what you would expect. Try to do this instead: >>> train_as_dicts = [dict(r.iteritems()) for _, r in train.iterrows()]>>> train_as_dicts[{'a': 'a', 'c': 'b', 'b': 0, 'd': 'e'}, {'a': 'b', 'c': 'c', 'b': 1, 'd': 'e'}, {'a': 'a', 'c': 'b', 'b': 1, 'd': 'f'}] This looks much better, let's now try to vectorize those dicts: >>> from sklearn.feature_extraction import DictVectorizer>>> vectorizer = DictVectorizer()>>> vectorized_sparse = vectorizer.fit_transform(train_as_dicts)>>> vectorized_sparse<3x7 sparse matrix of type '<type 'numpy.float64'>' with 12 stored elements in Compressed Sparse Row format>>>> vectorized_array = vectorized_sparse.toarray()>>> vectorized_arrayarray([[ 1., 0., 0., 1., 0., 1., 0.], [ 0., 1., 1., 0., 1., 1., 0.], [ 1., 0., 1., 1., 0., 0., 1.]]) To get the meaning of each column, ask the vectorizer: >>> vectorizer.get_feature_names()['a=a', 'a=b', 'b', 'c=b', 'c=c', 'd=e', 'd=f']
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15181311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1956483/']}
|
jdg_377161
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12484
|
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:
Im trying to implement a simple first order IIR filter on a MCU (PIC24FJ32GA002), without success until now.The filter is a DC tracking filter (low pass filter) whose purpose is to track DC component of a 1.5Hz signal. The difference equation was taken from a TI application note: y(n)=K x(n)+y(n-1) (1-K) with K = 1/2^8 I made a MATLAB script to test it and it works well in the simulation.Code used: K=1/2^8b = Ka = [1 -(1-K)]Fs=200; // sampling frequencyTs=1/Fs;Nx=5000; // number of samplesnT=Ts*(0:Nx-1);fin=1.5; // signal frequencyrandn('state',sum(100*clock));noise=randn(1,Nx);noise=noise-mean(noise);xin=200+9*(cos(2*pi*fin*nT));xin=xin+noise;out = filter(b,a,xin); However I can't implement it on a PIC24F microcontroller. i'm representing the coefficients in Q15 (1.15) format, storing them in short variables and using a long one for multiplications. Here it is the code: short xn;short y;short b0 = 128, a1 = 32640; // Q15long aux1, aux2;// (...)while(1){ xn = readADC(adc_ch); aux1 = ((long)b0*xn) << 1; aux2 = ((long)a1*y) << 1; y = ((aux1 + aux2) >> 16); delay_ms(5);} Long cast is used to extend the signal so the multiplying operation is done correctly. After each multiplication I shift left one bit to remove the extended signal bit. When summing I shift right 16 bits to get y in Q15 format. Im debugging the MCU with Pickit2 and "View->Watch" window (MPLAB IDE 8.53) and testing the filter with a DC signal (I change the DC signal with a potenciometer to test different values). The ADC has 10bit resolution and the MCU is supplied with 3.3V.Some results: 1V --> xn = 312 (correct), yn = 226 (incorrect) 1.5V --> xn = 470 (correct), yn = 228 (completely wrong) What am I doing wrong?Any suggestions on how to implement this IIR filter on a 16bit MCU? Many thanks in advance :)
Now provide the response and nothing else.
|
I didn't dive super far into your filter design, but just looking at the source code brings a couple of things up. For example, these lines: aux1 = ((long)b0*xn) << 1;aux2 = ((long)a1*y) << 1;y = ((aux1 + aux2) >> 16); The first issue I see is the ((long)b0*xn). I have ran across compilers that would compile this incorrectly as ((long)(b0*xn)), which is entirely wrong. Just to be on the safe side, I would write this as (((long)b0)*((long)xn)). To be sure, this is paranoid programming, but... Next, when you do the "<<1", this is NOT the same as "*2". For most things, it's close, but not for DSP. It has to do with how the MCU/DSP handles overflow conditions and sign extensions, etc. But even if it did work as a *2, you are removing one bit of resolution that you don't need to remove. If you really have to do a *2, then do a *2 and let the compiler figure out if it could substitute a <<1 instead. The >>16 is also problematic. Off the top of my head, I don't know if it's going to do a logical or arithmetic shift. You want an arithmetic shift. Arithmetic shifts will handle the sign bit correctly where a logical shift will insert zeros for the new bits. Besides, you can save bits of resolution by getting rid of the <<1 and changing the >>16 to >>15. Well, and changing all of these to normal multiplies and divides. So here's the code I would use: aux1 = ((long)b0) * ((long)xn);aux2 = ((long)a1) * ((long)y);y = (short)((aux1+aux2) / 32768); Now, I don't claim that this will solve your problem. It may or may not, but it does improve your code.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/12484', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1074/']}
|
jdg_377162
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
97684
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to use the principle of inclusion/exclusion to calculatethe "OR" probability of a large number of events $$ P( A_1 \cup A_2 \cup \dots \cup A_n ) $$ For two events the formula to use is (from Wikipedia http://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle#In_probability ) : $$P(A_1\cup A_2)=P(A_1)+P(A_2)-P(A_1\cap A_2) $$. For three events : $$ P(A_1\cup A_2\cup A_3)=P(A_1)+P(A_2)+P(A_3) -P(A_1\cap A_2)-P(A_1\cap A_3)-P(A_2\cap A_3)+P(A_1\cap A_2\cap A_3) $$ For n events : $$P\biggl(\bigcup_{i=1}^n A_i\biggr) {} =\sum_{i=1}^n P(A_i)-\sum_{i<j}P(A_i\cap A_j)\qquad+\sum_{i<j<k}P(A_i\cap A_j\cap A_k)- \cdots\ +(-1)^{n-1}\, P\biggl(\bigcap_{i=1}^n A_i\biggr)$$ The latter contains a very large number of terms, making it hard to compute. So I thought it might be possible to use a trick. If this works, I am surely not the first one to come up with this. The idea, illustrated on 4-event example, is$$ P( A_1 \cup A_2 \cup A_3 \cup A_4 ) $$is equivalent to$$ P( (A_1 \cup A_2) \cup (A_3 \cup A_4) )$$is equivalent to$$ P( A_1 \cup A_2) + P( A_3 \cup A_4) - P( A_1 \cup A_2) * P( A_3 \cup A_4) $$. The 2-event unions can be computed by the formula above. This can be applied to $n$ events also. The algorithm always unifies 2 events to a new event, which is then combined with another unified event. So each step reduces the number of events to $n/2$ or $n/2+1$ if $n$ is odd. The procedure is repeated until a single union probability remains. This makes it possible to reduce the required computational steps to $ O(log n) $ (or something like that). I have tested this by numerically comparing the results of the procedure for 3 events and 4 events. It seems to work. So my questions are: Is this wrong? And is there any literature reference on this approach?
Now provide the response and nothing else.
|
As @HaoYe's comment points out, your recursion via divide-and-conquer is notquite right: it is not the case that$$P(A_1\cup A_2\cup A_3\cup A_4) = P( A_1 \cup A_2) + P( A_3 \cup A_4) - P( A_1 \cup A_2) * P( A_3 \cup A_4)$$but rather that$$P(A_1\cup A_2\cup A_3\cup A_4) = P( A_1 \cup A_2) + P( A_3 \cup A_4) - P\left(( A_1 \cup A_2) \cap ( A_3 \cup A_4)\right).$$In any case, the principle of inclusion/exclusion gives a very pretty formulathat rarely can be used in practice because the probabilities of all thosevarious intersections are not easy to determine. One case where the probabilities can be calculated is when the $n$ events are mutually independent , butin this special case, the general formula should not be used at all! For $n$ mutually independent events $A_1, A_2, \ldots, A_n$, use DeMorgan's theorem to write $$P\left(\bigcup_{i=1}^n A_i\right) = 1 - P\left(\bigcap_{i=1}^n A_i^c\right)= 1 - \prod_{i=1}^n P(A_i^c)= 1 - \prod_{i=1}^n \left[1 - P(A_i)\right]\tag{1}$$ and calculate $P(A_1\cup A_2\cup\cdots\cup A_n)$ using $n-1$ multiplications and $n+1$ subtractions. In other words, for Heaven's sake, resist the temptation to multiply out those terms in square brackets on the right because you will end up with the inclusion/exclusion formula which you should try to avoid at all costs.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/97684', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/28836/']}
|
jdg_377163
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42936941
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to work on a function for an assignment and I'm new to coding. Part of it is to make user insert item to list by entering the desired item and the index without the built-in functions. Currently, I've got the code to replace the item in that index but I can't get it to do what it's supposed to. Object is the item, and the list is in the main function. def add(list, obj, index): nlist = [] print("Your list ", list) item = input("Insert item: ") index = int(input("Index: ")) i = 0 for e in list: if i < index: nlist.append(e) i += 1 elif i == index: nlist.append(obj) i += 1 elif i > index: nlist.append(e) i += 1 print("Your new list ", nlist)
Now provide the response and nothing else.
|
Imagine you have one of those magnetic train sets. like You want to add a train car after the second one. So you'd break apart the train between index 1 and 2 and then attach it. The front part is everything from 0 to 1 and the second part is everything from 2 till the end. Luckily, python has a really nice slice syntax: x[i:j] means slice from i (inclusive) to j (exclusive). x[:j] means slice from the front till j and x[i:] means slice from i till the end. So we can do def add(lst, obj, index): return lst[:index] + [obj] + lst[index:]
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42936941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7621575/']}
|
jdg_377164
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20179154
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have 3 div's, 200px,300px and 200px how can I align them side by side, all the examples I have seen only include 2. I have Div1,Div2 working correctly but Div3 for some reason slides under Div1 lie this picture This is my code <div style=" border-right:1px solid black; width:200px; float:left; position:relative; "> //div1 </div> <div style=" border-right:1px solid black; width:300px; padding:10px;float:left; position:relative;"> //div2 </div> <div style=" float: left; width: 200px;position:relative">//div3 </div> The Div1 has the shorter content on it, how can I make the border to the right as long as the border in Div2 ?
Now provide the response and nothing else.
|
All the elements in one line Wrap the div elements in a wrapper: <div id="wrapper"> <div id="first">first</div> <div id="second">second</div> <div id="third">third</div></div> Then set the width of the wrapper, and float all three div s: #wrapper { width:700px; clear:both;}#first { background-color:red; width:200px; float:left;}#second { background-color:blue; width:300px; float:left;}#third { background-color:#bada55; width:200px; float:left;} Also, use IDs and/or classes, and keep the CSS separate from the HTML. This makes the code easier to read and maintain. The fiddle . All elements in one line, same height To accomplish the "same height" part, you can use display:table , display:table-row , and display:table-cell to get matching heights. It uses an extra div, so the HTML looks like: <div id="wrapper"> <div id="row"> <div id="first">first</div> <div id="second">second<br><br></div> <div id="third">third</div> </div></div> The floats can then be removed, so the CSS looks like: #wrapper { display:table; width:700px;}#row { display:table-row;}#first { display:table-cell; background-color:red; width:200px;}#second { display:table-cell; background-color:blue; width:300px;}#third { display:table-cell; background-color:#bada55; width:200px;} The fiddle . The Flexbox Way If you're only supporting newer browsers (IE 10 and up), Flexbox is another good choice. Make sure to prefix for better support. More on the prefixes can be found here . The HTML <div class="container"> <div class="first">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div> <div class="second">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil ratione rerum deserunt reiciendis numquam fugit dolor eligendi fuga sit. Hic, tempore. Error, temporibus possimus deserunt quisquam rerum dolor quam natus.Fugiat nam recusandae doloribus culpa obcaecati facere eligendi consectetur cum eveniet quod et, eum, libero esse voluptates. Ut commodi consequuntur eligendi doloremque deserunt modi animi explicabo aperiam, non, quas qui!</div> <div class="third">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet obcaecati, rem. Ullam quia quae, ad, unde saepe velit incidunt, aliquid eum facere obcaecati molestiae? Repellendus tempore magnam facere, sint similique!</div></div> The CSS .container { display:flex; justify-content:center;}.container > div { margin:10px; background-color:#bada55;}.first, .third { width:200px;}.second { width:300px;} The Codepen . The Grid Way You can accomplish this with grid now, too, though browser support might be an issue if you're supporting older browsers. It's the same HTML as with the flexbox example, with just different CSS: The CSS .container { display:grid; grid-template-columns: repeat(3, 1fr); grid-auto-rows: 1fr; grid-column-gap: 10px; width:700px;}.container > div { background-color:#bada55;}.first, .third { width:200px;}.second { width:300px;} The codepen .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20179154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1949387/']}
|
jdg_377165
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13914698
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Background I'm creating some SQL to assist with security auditing; this will take security info from various systems databases and from Active Directory and will produce a list of all anomalies (i.e. cases where accounts are closed in one system but not others. Current Code To get a list of users who are a member of a security group I run the below SQL: if not exists(select 1 from sys.servers where name = 'ADSI') EXEC sp_addlinkedserver 'ADSI', 'Active Directory Services 2.5', 'ADSDSOObject', 'adsdatasource'SELECT sAMAccountName, displayName, givenName, sn, isDeleted --, lastLogonTimestamp --, lastLogon (Could not convert the data value due to reasons other than sign mismatch or overflow.)FROM OPENQUERY(ADSI, 'SELECT sAMAccountName, displayName, givenName, sn, isDeletedFROM ''LDAP://DC=myDomain,DC=myCompany,DC=com''WHERE objectCategory = ''Person''AND objectClass = ''user'' AND memberOf = ''CN=mySecurityGroup,OU=Security Groups,OU=UK,DC=myDomain,DC=myCompany,DC=com''')order by sAMAccountName Problem / Question I'd like this code to be able to work recursively; i.e. if a user is a member of a group which is a member of the specified group, they should be included too (for the full hierarchy). Does anyone know how to do this through SQL? UPDATE I've now resolved a few issues (not related to the quoted problem, but some other issues I'd had). lastLogon was throwning an error. This was because the server version was x86. Using an x64 database resolved the problem. lastLogon was returned as a number. Added some code to convert this to DateTime2. I was able to move the group name out of a hard coded string by making OpenQuery itself dynamic, so within the context of OpenQuery the generated string looks static. .. --create linked serverif not exists(select 1 from sys.servers where name = 'ADSI')begin --EXEC sp_addlinkedserver 'ADSI', 'Active Directory Services 2.5', 'ADSDSOObject', 'adsdatasource' EXEC master.dbo.sp_addlinkedserver 'ADSI', 'Active Directory Service Interfaces', 'ADSDSOObject', 'adsdatasource' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'collation compatible', @optvalue=N'false' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'data access', @optvalue=N'true' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'dist', @optvalue=N'false' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'pub', @optvalue=N'false' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'rpc', @optvalue=N'false' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'rpc out', @optvalue=N'false' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'sub', @optvalue=N'false' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'connect timeout', @optvalue=N'0' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'collation name', @optvalue=null EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'lazy schema validation', @optvalue=N'false' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'query timeout', @optvalue=N'0' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'use remote collation', @optvalue=N'true' EXEC master.dbo.sp_serveroption @server=N'ADSI', @optname=N'remote proc transaction promotion', @optvalue=N'true'enddeclare @path nvarchar(1024) = 'DC=myDomain,DC=myCompany,DC=com'declare @groupCN nvarchar(1024) = 'CN=My Security Group,OU=Security Groups,OU=UK,' + @path, @sql nvarchar(max)--construct the query we send to ADset @sql = 'SELECT sAMAccountName, displayName, givenName, sn, isDeleted, lastLogonFROM ''LDAP://' + replace(@path,'''','''''') + '''WHERE objectCategory = ''Person''AND objectClass = ''user'' AND memberOf = ''' + replace(@groupCN,'''','''''') + ''''--now wrap that query in the outer queryset @sql = 'SELECT sAMAccountName, displayName, givenName, sn, isDeleted, case when cast([lastLogon] as bigint) = 0 then null else dateadd(mi,(cast([lastlogon] as bigint) / 600000000), cast(''1601-01-01'' as datetime2)) end LastLogonFROM OPENQUERY(ADSI, ''' + replace(@sql,'''','''''') + ''')order by sAMAccountName'--now run itexec(@sql)
Now provide the response and nothing else.
|
Though this is an old post, Google still likes to toss it to the top of the results, so as I struggled with this same problem a great deal, I wanted to post my findings/solution, with credit to Riverway for getting me on the right track. Create a Stored Procedure: CREATE PROCEDURE [dbo].[GetLdapUserGroups] ( @LdapUsername NVARCHAR(max) )ASBEGINDECLARE @Query NVARCHAR(max), @Path NVARCHAR(max)SET @Query = ' SELECT @Path = distinguishedName FROM OPENQUERY(ADSI, '' SELECT distinguishedName FROM ''''LDAP://DC=DOMAIN,DC=COM'''' WHERE objectClass = ''''user'''' AND sAMAccountName = ''''' + @LdapUsername + ''''' '')'EXEC SP_EXECUTESQL @Query, N'@Path NVARCHAR(max) OUTPUT', @Path = @Path OUTPUT SET @Query = ' SELECT cn AS [LdapGroup] FROM OPENQUERY (ADSI, ''<LDAP://DOMAIN.COM>; (&(objectClass=group)(member:1.2.840.113556.1.4.1941:= ' + @Path + ')); cn, adspath;subtree'') ORDER BY cn;'EXEC SP_EXECUTESQL @QueryEND Then, call your SP by just passing the username: DECLARE @UserGroup table (LdapGroup nvarchar(max))INSERT INTO @UserGroup exec Datamart.dbo.GetLdapUserGroups @LdapUser I'm then using a hash table to correctly match the AD group to the SQL data and what the end user should see. DECLARE @RptPermissions table (ldapGroup nvarchar(max),scholarshipCode nvarchar(50),gender nvarchar(2))INSERT INTO @RptPermissions VALUES('EMP_Enrollment_Admissions','ALL','MF') In my case, I'm using this to pull the SSRS user variable and pass it into the query for selecting the records based on AD group membership. ;WITH CTE_Permissions AS( SELECT p.scholarshipCode ,p.gender FROM @UserGroup AS g JOIN @RptPermissions AS p ON g.ldapGroup = p.ldapGroup) ... Later in the query JOIN CTE_Permissions AS p ON s.SCHOLARSHIP_ID = p.scholarshipCode OR p.scholarshipCode = 'ALL' Hope this helps.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13914698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/361842/']}
|
jdg_377166
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
270778
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I love to type bash scripts, but if I prepare multiple tools, project's root directory is filled with so many shell scripts. That's why I prefer using Makefile. Makefile is good. However I want to build my makefiles just as regular bash scripts. Eg: Think that I wrote a bash script very quickly with the following content: #!/bin/bashecho "hello"cd ~do-some-work.sh my-parameter I can run this script with $ ./my-important-task.sh . If I wanted to move that script into makefile, I should do the following: SHELL := /bin/bash my-important-task: echo "hello" ;\ cd ~ ;\ do-some-work.sh my-parameter but I want the following: my-important-task: [[copy and paste the my-important-task.sh file]] Is there anyway to accomplish this goal?
Now provide the response and nothing else.
|
If you really want to “write exactly bash scripts into Makefiles” then you'll need to do it a bit indirectly. If you just paste the script after the target line, then you'll run into two problems that just cannot be bypassed: the command lines need to be indented with a tab, and dollar signs need to be escaped. If you use GNU make (as opposed to BSD make, Solaris make, etc.), then you can define your script as a variable using the multi-line definition syntax , and then use the value function to use the raw value of the variable, bypassing expansion. In addition, as explained by skwllsp , you need to tell make to execute the command list for each target as a single shell script rather than line by line, which you can do in GNU make by defining a .ONESHELL target . define my_important_task =# script goes hereendefmy-important-task: ; $(value my_important_task).ONESHELL:
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/270778', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/65781/']}
|
jdg_377167
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35883
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't know if it's just me, but I am very skeptical of statistics in general. I can understand it in dice games, poker games, etc. Very small, simple, mostly self-contained repeated games are fine. For example, a coin landing on its edge is small enough to accept the probability that landing heads or tails is ~50%. Playing a $10 game of poker aiming for a 95% win is fine. But what if your entire life savings + more is dependent on you hitting a win or not? How would knowing that you'd win in 95% of the time in that situation will help me at all? Expected value doesn't help much there. Other examples include a life-threatening surgery. How does that help knowing that it is 51% survival rate versus 99% survival rate given existing data? In both cases, I don't think it will matter to me what the doctor tells me, and I would go for it. If actual data is 75%, he might as well tell me (barring ethics and law), that there is a 99.99999% chance of survival so I'd feel better. In other words, existing data doesn't matter except binomially. Even then, it doesn't matter if there is a 99.99999% survival rate, if I end up dying from it. Also, earthquake probability. It doesn't matter if a strong earthquake happened every x (where x > 100) years on average. I have no idea if an earthquake will happen ever in my lifetime. So why is it even useful information? A less serious example, say, 100% of the places I've been to that I love are in the Americas, indifferent to 100% of the places I've been to in Europe, and hate 100% of the places that I have been to in Asia. Now, that by no means mean that I wouldn't find a place that I love in Asia on my next trip or hate in Europe or indifferent in America, just by the very nature that the statistics doesn't capture all of the information I need, and I probably can never capture all of the information I need, even if I have traveled to over x% of all of those continents. Just because there are unknowns in the 1-x% of those continents that I haven't been to. (Feel free to replace the 100% with any other percentage). I understand that there is no way to brute force everything and that you have to rely on statistics in many situations, but how can we believe that statistics are helpful in our one shot situation, especially when statistics basically do not extrapolate to outlier events? Any insights to get over my skepticism of statistics?
Now provide the response and nothing else.
|
First I think that you may be confusing "statistics" meaning a collection of numbers or other facts describing a group or situation, and "statistics" meaning the science of using data and information to understand the world in the face of variation (others may be able to improve on my definitions). Statisticians use both senses of the word, so it is not surprising when people mix them up. Statistics (the science) is a lot about choosing strategies and choosing the best strategy even if we only get to apply it once. Some times when I (and others) teach probability we use the classic Monty Hall problem (3 doors, 2 goats, 1 car) to motivate it and we show how we can estimate probabilities by playing the game a bunch of times (not for prizes) and we can see that the "switch" strategy wins 2/3 of the time and the "stay" strategy only wins 1/3 of the time. Now if we had the opportunity to play the game a single time we would know some things about which strategy gives a better chance of winning. The surgery example is similar, you will only have the surgery (or not have the surgery) once, but don't you want to know which strategy benifits more people? If your choices are surgery with some chance greater than 0% of survival or no surgery and 0% of survival, then yes there is little difference between the surgery having 51% survival and 99.9% survival. But what if there are other options as well, you can choose between surgery, doing nothing (which has 25% survival) or a change of diet and exercise which has 75% survival (but requires effort on your part), now wouldn't you care about if the surgery option has 51% vs. 99% survival? Also consider the doctor, he will be doing more than just your surgery. If surgery has 99.9% survival then he has no reason to consider alternatives, but if it only has 51% survival then while it may be the best choice today, he should be looking for other alternatives that increase that survival. Yes even with 90% survival he will loose some patients, but which strategy gives him the best chance of saving the most patients? This morning I wore my seat belt while driving (my usual strategy), but did not get in any accidents, so was my strategy a waste of time? If I knew when I would get in an accident then I could save time by only putting on the seat belt on those occasions and not on others. But I don't know when I will be in an accident so I will stick with my wear the seat belt strategy because I believe it will give me the best chance if I ever am in an accident even if that means wasting a bit of time and effort in the high percentage (hopefully 100%) of times that there is no accident.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/35883', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/13919/']}
|
jdg_377168
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30336222
|
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 try solve this problem I know that, I can do that like for i in range(1,input()): print int(str(i)*i) It works, but I can't use strings, so i have idea to dothat like for i in range(1,input()): sum+=10**i print i*((1+sum)%10**i) for i=1 1*(1+10)%10, for i=2 2*((1+110)%100), for i=3 3*((1+1110)%1000) etc. But it doesn't work and have more than 2 lines :( Anyone have idea how to solve this problem ? Generally i know how to solve this problem mathematic but i don't know how to do that in python ( no use string and write no more than 2 lines)
Now provide the response and nothing else.
|
Something that helps here is the equation for a " Repunit ". Taking the equation for the i'th Repunit from that Wikipedia page, and substituting 10 in for b (base 10), we get the equation (10**i - 1) / (10 - 1) or (10**i - 1) / 9 . This results in the sequence: 1, 11, 111, 1111... . Multiplying by i, we achieve the desired result: >>> for i in range(1, input()):... print(i * (10**i - 1) // 9)5<Enter>1 223334444
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30336222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4899128/']}
|
jdg_377169
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4967641
|
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 column graph, that shows a trend of consumption over time,The y-axis being consumption and x-axis being time in month, I have to implement a target consumption. I implemented a target, by adding data field with a Line chart type, this is a constant, and will just display a horizontal line. The problem i am facing is, if there is only one month, the line disappears? is there a way not to have it disappear, or is there a better way to add line target in column charts in SSRS I am using SSRS 2008
Now provide the response and nothing else.
|
Adding a StripLine may do what you want. They are a little hard to find, but here is how: 1) Make sure that the properties window is open beforehand. If it isn't, either hit F4 or go to the View Menu -> Properties Window. 2) Left click on your vertical axis to select it. 3) Select the StripLines entry in the Properties Window and click the ellipsis: 4) Click Add 5) Starting off, the stripline is invisible, so it can be a bit hard to adjust. :). To make it visible as a thin line, set BorderStyle to "Solid". Adjust the color with BorderColor and width with BorderWidth (not StripWidth). While positioning the line, I like to set the color to something obnoxious and make it wide to make it easier to spot. 5) To position it, you want to set the IntervalOffsetType to match the type of your interval you have set on the vertical axis. Then IntervalOffset to the y-value of where you want your target line to appear. Since you only want 1 line to appear and not repeat, you must keep Interval set to auto . 6) Once you get it positioned, make final adjustments to the appearance.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4967641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/526858/']}
|
jdg_377170
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4305323
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a student of Undergraduate studies , and I am facing little problem in granting rights of ownership to a user A to a stored procedure being owned by user B in database Oracle 10g mode =xe. Please help me in writing sql commands for granting rights of ownership on stored procedure xyz to another user A.
Now provide the response and nothing else.
|
I'm not sure that I understand what you mean by "rights of ownership". If User B owns a stored procedure, User B can grant User A permission to run the stored procedure GRANT EXECUTE ON b.procedure_name TO a User A would then call the procedure using the fully qualified name, i.e. BEGIN b.procedure_name( <<list of parameters>> );END; Alternately, User A can create a synonym in order to avoid having to use the fully qualified procedure name. CREATE SYNONYM procedure_name FOR b.procedure_name;BEGIN procedure_name( <<list of parameters>> );END;
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4305323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358261/']}
|
jdg_377171
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
524836
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
i have this: echo $MSG | sed -e $'s/;/\\\n/g' I want to put the result of that sed in a new variable called $MSG2 Something like: $MSG2=echo $MSG|sed -e $'s/;/\\\n/g' How can i do it? Thank you!
Now provide the response and nothing else.
|
For your task, you don't need pipelines or sed. It can all be done much more efficiently using builtin bash commands like this: NewMsg=${MSG//;/$'\n'} ${MSG//;/$'\n'} is an example of pattern substitution . It replaces every occurrence of ; with a newline character. The result is saved in the shell variable NewMsg . As an example: $ Msg='1;2;3'$ NewMsg=${Msg//;/$'\n'}$ echo "$NewMsg"123 Notes: It is best practice to use lower-case or mixed-case shell variables. The system uses all caps for its variables and you don't want to accidentally overwrite one of them. Unless you explicitly want word splitting and pathname expansion always put your shell variables in double-quotes. Thus, when temped to use echo $MSG , use instead echo "$MSG" . Also, unless you know what characters are going to be in the string that you are echoing, echo has problems and it is safer and more portable to use printf '%s\n' "$MSG" . For more details, see Stéphane Chazelas' very informative discussion of echo vs printf . Be aware that if you do use command substitution, $(...) , the shell will remove all trailing newlines. While this is usually helpful, there are times when the change is unwanted.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/524836', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/357806/']}
|
jdg_377172
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48225293
|
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 just started messing around with the Kotlin programming language, which is pretty much cooler than Java. I have some doubts related to static methods and fields: Q1: Official document says Kotlin can also generate static methods for functions defined in named objects or companion objects if you annotate those functions as @JvmStatic. But if you see below I can access bar() method as a static method, which works without using @JvmStatic annotation. But on official doc its throwing error -> Kotlin static method . Class C{ companion object{ @JvmStatic fun foo() { } fun bar(); }}fun main(args: Array<String>) { C.foo(); C.bar(); //this line works fine} Q2: Do I really need @JvmStatic and @JvmField to make things static? As you can see with companion object, things are working as expected.
Now provide the response and nothing else.
|
You can access members of a companion object as C.bar() in Kotlin , but not in Java. Without @JvmStatic , you would need to use C.Companion.bar() in Java , just as said in the docs. Note that, without @JvmStatic , the function is compiled to an instance (non-static) method that is called on C.Companion in Java (and Kotlin simply shortens it to a call on C , but it's the same under the hood), so yes, you need either @JvmStatic and @JvmField to make a declaration in a companion object compile into a static member. Basically, @JvmStatic and @JvmField are tools for Java interoperation that help with creating Java-friendly APIs, and if you don't need to call the Kotlin members from Java (e.g. they are internal to your Kotlin project, or you are developing a library that is unlikely to be used with Java), you can leave them as they are.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48225293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2032561/']}
|
jdg_377173
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
282644
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is the function $f:\Bbb R \rightarrow \Bbb R$ defined as $f(x)=\sin(x^2)$, for all $x\in\Bbb R$, periodic? Here's my attempt to solve this: Let's assume that it is periodic. For a function to be periodic, it must satisfy $f(x)=f(T+x)$ for all $x\in\Bbb R$, so it must satisfy the relation for $x=0$ as well. So we get that $T^2=k\pi \iff T=\sqrt{k\pi}$, $k\in\Bbb N$ (since $T$ must be positive, we remove the $-\sqrt{k\pi}$ solution). So what now? I tried taking $x=\sqrt\pi$ and using the $T$ I found, and I get this: $$ \sin\pi=\sin(T+\sqrt\pi)\iff-1=\sin(\pi(\sqrt k+1)^2)\iff k+2\sqrt k+1=3/2+l $$Is this enough for contradiction? The left side of equation is sometimes irrational and gets rational only when $k$ is perfect square, which doesn't happen periodic, while the right hand side is always rational. Or I'm still missing some steps? Thanks.
Now provide the response and nothing else.
|
Let $f : \mathbb{R} \to \mathbb{R}$ be periodic with period $T$. The range of $f$ is precisely $f([0, T])$; in particular, if $f$ is continuous, the range of $f$ is bounded. If $f$ is differentiable, then $f'$ is periodic with period $T$. Note that $f(x) = \sin(x^2)$ is differentiable and $f'(x) = 2x\cos(x^2)$ which is unbounded. Therefore, $f'$ cannot be periodic by the first point, and hence $f$ cannot be periodic by the second point.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/282644', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/24269/']}
|
jdg_377174
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
115685
|
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does 'top' indicate low memory usage, whilst 'free' indicates high memory usage? Mem: 262144k total, 225708k used, 36436k free, 47948k buffersSwap: 262136k total, 40k used, 262096k free, 110704k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1652 root 15 0 79456 14m 1728 S 0.0 5.6 0:00.02 miniserv.pl 3544 root 15 0 87920 3356 2584 R 0.0 1.3 0:00.01 sshd 3707 root 16 0 86704 3104 2416 S 0.0 1.2 0:00.00 sshd 3708 sshd 15 0 61864 1452 872 S 0.0 0.6 0:00.00 sshd 3548 root 16 0 10872 1432 1116 S 0.0 0.5 0:00.00 bash 1908 root 15 0 10876 1392 1072 S 0.0 0.5 0:00.00 sh 918 root 15 0 60520 1204 664 S 0.0 0.5 0:00.07 sshd 3624 root 15 0 12584 1180 920 R 0.0 0.5 0:00.00 top 926 root 18 0 19672 1152 576 S 0.0 0.4 0:00.00 crond 1 root 15 0 10324 704 588 S 0.0 0.3 0:00.02 init 311 root 16 -4 12580 704 388 S 0.0 0.3 0:00.06 udevd 874 root 16 0 5884 592 472 S 0.0 0.2 0:00.06 syslogd 877 root 18 0 3780 420 336 S 0.0 0.2 0:00.00 klogd Total MEM usage = 12.1% However, 226mb used out of 262mb, with 36mb free - i.e. 86.25% used. Even taking in to account the swap, total memory 262mb*2 = 524mb. Given 226mb is used, 43.12% is used. Both are much higher than the actual processed listed by top. The server is a fresh 256MB VPS running CentOS 5.2 - haven't installed anything on it yet. Running webadmin; i.e. no Plesk. This question is fundamentally about the conflicting information that seems to be given by top; but I am also wondering if this memory usage is normal, for a server that isn't running any particularly memory intensive applications. I intend to install Apache/Ruby EE/Passenger; however if memory usage is already this high, I'm unsure how well it is going to handle it.
Now provide the response and nothing else.
|
Top, that is the figure in the %MEM column, is counting the amount of RSS memory (Resident Segment Size, basically pages physically in memory that have real data on them) as a percentage of total physical memory in your machine or VPS. On the other hand, free is counting just that, the amount of physical memory pages that have no data on them, and have not been assigned to buffers, cache or the kernel. In a Unix like operating system, the OS tries hard to keep that number as low as possible by using free pages for disk cache. The only time you'll likely a high value of free memory is just after your machine boots, or if you quit a program that was consuming a large amount of physical memory itself. Is this memory usage normal ? The short answer is yes. It is typical for Unix programs to allocate (that is ask the OS for) significantly more memory than they would use. If you look at the VSS column, for the processes listed the total is over 463mb. That is because A lot of the memory accounted against each process will be physically mapped to the same library, say glibc The OS generally overcommits memory to the application, on the basis that most applications never come to collect on what they have asked for. Figure out process memory usage is more an art than a science IMHO, see the discussions on http://lwn.net . My advice is to keep a close eye on iostat -xm and ensure that your machine is not swapping heavily.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/115685', 'https://serverfault.com', 'https://serverfault.com/users/24628/']}
|
jdg_377175
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14981003
|
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 table that have several field and each of them update separately by separate ViewModel , Now I wanna to get the latest Value of a specific field (maybe it has updated in fifth record of my table) , OK? now what I have write is look like this : public ViewResult ShowPiece() { var context = new SiteContext(); var showPiece = context.Portraits.LastOrDefault(); return View(showPiece); } but when I run the application and navigate above action , I got thie Error : LINQ to Entities does not recognize the method , and this method cannot be translated into a store expression... what is the problem with that ??
Now provide the response and nothing else.
|
Use descending ordering (by date, or id) and FirstOrDefault which is supported : var showPiece = context.Portraits .OrderByDescending(p => p.Date) .FirstOrDefault(); Another option, is select portrait which has max date (id) via subquery (as Evelie suggested in comments): var showPiece = context.Portraits .FirstOrDefault(p => p.Date == context.Portraits.Max(x => x.Date)); I made a little investigation here. In first case (ordering) following query is generated: SELECT TOP (1) [t0].*FROM [Portraits] AS [t0]ORDER BY [t0].[Date] DESC In second case (getting max): SELECT TOP (1) [t0].*FROM [Portraits] AS [t0]WHERE [t0].[Date] = (( SELECT MAX([t1].[Date]) FROM [Portraits] AS [t1] )) Execution plan is almost same, but in second case Top is executed twice. Thus Top costs 0% comparing to Index Scan, this should not be a problem.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14981003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2058768/']}
|
jdg_377176
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
649341
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the above figure, the wedge is been accelerated towards right as shown in figure. According to my teacher it is possible to keep the block at rest or even accelerate it in the upward direction along the the inclined plane of wedge. To explain he taught us about pseudo forces. Stating that in the Wedge frame we can assume a pseudo force in the right on the block as shown in figure. He also said that we can also do the same from ground frame but when I am trying to do it I am not finding any force that resists the motion of of the wedge down the inclined plane.
Now provide the response and nothing else.
|
According to my teacher it is possible to keep the block at rest or even accelerate it in the upward direction along the the inclined plane of wedge. I think you are confusing the words of your teacher. What your teacher is actually trying to say is that it is possible to keep the block at rest or even accelerate it in the upward direction with respect to the wedge and what you perceived is that it is possible to keep the block at rest or accelerate it upwards with respect to ground which is absolutely incorrect. Let's understand it through a thought experiment, consider the following bullet train with a block kept on it, suppose there is no friction. Now let us consider the motion of the block from different frames when the train is accelerating. Train frame Suppose we are moving along the train with the same acceleration and speed. Then there are three possible motions of the block that we can see Block moving downwards with respect to the train when the trains acceleration is very low. Block at rest with respect to the train . Block moving upwards with respect to train along its inclined top. This is the extreme case where the train is accelerating quite fast. All of this can be explained using pseudo force that you depicted in your diagram. Ground Frame Now let us analyse the situation from the ground frame. What do we see if we see the above scenario while standing on the ground ? Let us examine the extreme case of block moving upwards, when standing on the ground we will see that the block is climbing the incline top of the train as well as moving forward so the net movement of the block will be at some angle to the horizontal like this in the above figure the net acceleration of the block is depicted with pink coloured vector along with its components, the horizontal component will be deducted when the observer is moving along the train so he sees the block to be moving upwards only. The above motion can be explained by the following diagram The other sceneries can be explain in similar manner. Note : A scenario in which the net motion of the block is along the incline top of the train is not possible as there is no force that supports this motion.The net acceleration cannot be inclined to the left of horizontal as shown below. The reason why the above scenario is not possible it is because in order for it to be possible the force along the incline plane must be greater than the force along the horizontal which is not possible.And you can cross check it from your own tron fbd as the force along the incline plane is $ma cos \theta $ which is always less than $ma$ itself. Thus the net acceleration of the block from ground frame is always towards right of the vertical axis as shown below. Hope it's clear to you now.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/649341', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/305704/']}
|
jdg_377177
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1871372
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
def l = ["My", "Homer"]String s = "Hi My Name is Homer"def list = s.split(" ")println listlist.each{it -> l.each{it1 -> if (it == it1) println "found ${it}" }} I want to check whether big list ( list ) contains all elements of sublist ( l )Does groovy have any built in methods to check this or what I have in the above code will do?
Now provide the response and nothing else.
|
You could use Groovy's Collection.intersect(Collection right) method and check whether the returned Collection is as big as the one that's passed as argument. You have to use the String.tokenize() method before to generate a List from the String instead of String.split() which returns a String array: def sublist = ["My", "Homer"]def list = "Hi My Name is Homer".tokenize()assert sublist.size() == list.intersect(sublist).size() Alternatively, you could use Groovy's Object.every(Closure closure) method and check if each element of the sublist is contained in the list: assert sublist.every { list.contains(it) } However, the shortest way is using the standard Java Collection API: assert list.containsAll(sublist)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1871372', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44286/']}
|
jdg_377178
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7819498
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone have sample code for plotting ellipsoids? There is one for sphere on matplotlib site, but nothing for ellipsoids. I am trying to plot x**2 + 2*y**2 + 2*z**2 = c where c is a constant (like 10) that defines an ellipsoid. I tried the meshgrid(x,y) route, reworked the equation so z is on one side, but the sqrt is a problem. The matplotlib sphere example works with angles, u,v , but I am not sure how to work that for ellipsoid.
Now provide the response and nothing else.
|
Here is how you can do it via spherical coordinates: from mpl_toolkits.mplot3d import Axes3Dimport matplotlib.pyplot as pltimport numpy as npfig = plt.figure(figsize=plt.figaspect(1)) # Square figureax = fig.add_subplot(111, projection='3d')coefs = (1, 2, 2) # Coefficients in a0/c x**2 + a1/c y**2 + a2/c z**2 = 1 # Radii corresponding to the coefficients:rx, ry, rz = 1/np.sqrt(coefs)# Set of all spherical angles:u = np.linspace(0, 2 * np.pi, 100)v = np.linspace(0, np.pi, 100)# Cartesian coordinates that correspond to the spherical angles:# (this is the equation of an ellipsoid):x = rx * np.outer(np.cos(u), np.sin(v))y = ry * np.outer(np.sin(u), np.sin(v))z = rz * np.outer(np.ones_like(u), np.cos(v))# Plot:ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b')# Adjustment of the axes, so that they all have the same span:max_radius = max(rx, ry, rz)for axis in 'xyz': getattr(ax, 'set_{}lim'.format(axis))((-max_radius, max_radius))plt.show() The resulting plot is similar to The program above actually produces a nicer looking "square" graphics. This solution is strongly inspired from the example in Matplotlib's gallery .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7819498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/423805/']}
|
jdg_377179
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
909395
|
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 have two programs that both behave nearly identically: they both take in any numbers you give them and can tell you the arithmetic mean and how many numbers were given. However, when you don't give them any numbers, one says the arithmetic mean is 0.0 , and the other says it's NaN ("Not a Number"). Which of these answers, if any, is more correct, and why? Note: Although I use "programs" as a metaphor here, this isn't a programming question; I could've just as easily said "computers", "machines", "wise men", etc. and my question would be the same
Now provide the response and nothing else.
|
From a statistical point-of-view, the average of no sample points should not exist. The reason is simple. The average is an indication of the centre of mass of the distribution. Clearly, for no observations there can be no way to prefer one location vs. another as their centre of mass since the the empty set is translation invariant. More mathematically, taking the average is a linear operation, which means if you add a constant $c$ to each observation, then the average $a$ becomes $a+c$. Now if you add $c$ to each observation in the empty set, you get the empty set again, and thus the average will have to satisfy $a+c=a$ for all $c$, clearly nonsense.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/909395', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26772/']}
|
jdg_377180
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7928820
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Scope I need to scroll to certain position smoothly and then "jump" to another position with setSelection(anotherPosition) . This is done to create an illusion of smooth scrolling of (e.g.) 100 items in ListView . smoothScrollToPosition(100) lasts too much, you know. Problem setSelection() doesn't wait till smoothScrollToPositio n finishes its work, so setSelection() is being called immediately and user sees quick jumping only; Code private final int scrollableItems = 20;int firstVisiblePosition = mListView.getFirstVisiblePosition();if (firstVisiblePosition < scrollableItems) { mListView.smoothScrollToPosition(0);} else { mListView.smoothScrollToPosition(firstVisiblePosition - scrollableItems); mListView.setSelection(0);}mListView.clearFocus(); Idea OK, we could change logic of smoothness illusion: first setSelection() , then scroll smoothly (we're scrolling to the very first item on top of the list): int firstVisiblePosition = mListView.getFirstVisiblePosition(); if (firstVisiblePosition < scrollableItems) { mListView.smoothScrollToPosition(0); } else { mListView.setSelection(scrollableItems); mListView.smoothScrollToPosition(0); } mListView.clearFocus();
Now provide the response and nothing else.
|
final ListView listView = ...;View listItemView = ...;listView.smoothScrollBy(listItemView.getHeight() * NUMBER_OF_VIEWS, DURATION * 2);listView.postDelayed(new Runnable() { public void run() { listView.smoothScrollBy(0, 0); // Stops the listview from overshooting. listView.setSelection(0); }}, DURATION); Of course, direction of the scroll etc. would need to be adjusted for your use case (go to the top of the list) EDIT : Old solution could overshoot if the velocity of the scroll was too high, smoothScrollBy(0,0) will stop the smooth scrolling before setting the selection properly and immediately.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7928820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/691993/']}
|
jdg_377181
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4129196
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What's the difference between Process.fork and the new Process.spawn methods in Ruby 1.9.2 and which one is better to run another program in a subprocess? As far as I understand Process.fork accepts block of code and Process.spawn takes a system command plus some other parameters. When I should use one instead of the other?
Now provide the response and nothing else.
|
What's the difference between Process.fork and the new Process.spawn methods in Ruby 1.9.2 Process.fork allows you to run ruby code in another process. Process.spawn allows you to run another program in another process. Basically Process.spawn is like using Process.fork and then calling exec in the forked process, except that it gives you more options. and which one is better to run another program in a subprocess? If you need backwards compatibility, use fork + exec as spawn is not available in 1.8. Otherwise use spawn since running another program in a subprocess is exactly what spawn is made for. As far as I understand Process.fork accepts block of code and Process.spawn takes a system command plus some other parameters. Exactly. When I should use one instead of the other? Use fork if you need to run arbitrary ruby code in a separate process (you can't do that with spawn ). Use spawn if you need to invoke an application in a subprocess.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4129196', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/270663/']}
|
jdg_377182
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4122451
|
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 need help.We want to show that the matrix $A$ is symmetric definite positive for all $n$ where $n$ is the size of the matrix $A$ . Here is $A$ : $$A = \begin{bmatrix} 1& -1& 0& ...& 0\\ -1& 2& -1& \ddots & \vdots\\ 0& -1& 2& \ddots &0\\ \vdots & \ddots & \ddots& \ddots &-1 \\0 & ... &0 & -1& 2\end{bmatrix} $$ I tried brute forcing by calculating for $x$ a vector of size $n$ , $x^TAx$ , but it seems tricky. Thanks for your help
Now provide the response and nothing else.
|
HINT: The matrix is symmetric and diagonally dominant , so positive semidefinite. To show that it is actually positive definite, you need to check that the kernel is null. Take a vector in the kernel. You notice that the first two components are equal, and then, the components are in arithmetic progression, but then notice the relation between the last two components. Thus the vector is $0$ . $\bf{Added:}$ . Place $-\epsilon < 0$ instead of $-1$ , and call the matrix $M_{\epsilon}$ . For every $\epsilon \in [0,1)$ the matrix is strictly diagonally dominant, so the eigenvalues are not $0$ . The eigenvalues of $M_{\epsilon}$ vary continuously with $\epsilon$ . Now the eigenvalues of $M_{0}$ are $>0$ , so no eigenvalue of $M= M_1$ can be negative.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4122451', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/921913/']}
|
jdg_377183
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23966149
|
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 this string "Initial: At(Forest), MonsterAt(Chimera,Forest), Alive(Chimera)" to be parsed into: "At(Forest)" , "MonsterAt(Chimera, Forest)" , and "Alive(Chimera)" (I don't need "Initial:"). I used this code from ( java - split string using regular expression ): String[] splitArray = subjectString.split( "(?x), # Verbose regex: Match a comma\n" + "(?! # unless it's followed by...\n" + " [^(]* # any number of characters except (\n" + " \\) # and a )\n" + ") # end of lookahead assertion"); this is the output (the underscore is a space): Initial: At(Forest)_MonsterAt(Chimera,Forest)_Alive(Chimera) but I don't want to have a space before the string ("_Alive(Chimera)"), and I want to remove the "Initial: " after splitting. If I removed the spaces (except for "Initial") from the original string the output is this: Initial: At(Forest),MonsterAt(Chimera,Forest),Alive(Chimera)
Now provide the response and nothing else.
|
Here is a nice function in vanilla JS that handles things: var format = function(num){ var str = num.toString().replace("$", ""), parts = false, output = [], i = 1, formatted = null; if(str.indexOf(".") > 0) { parts = str.split("."); str = parts[0]; } str = str.split("").reverse(); for(var j = 0, len = str.length; j < len; j++) { if(str[j] != ",") { output.push(str[j]); if(i%3 == 0 && j < (len - 1)) { output.push(","); } i++; } } formatted = output.reverse().join(""); return("$" + formatted + ((parts) ? "." + parts[1].substr(0, 2) : ""));}; However, for jQuery, you could always turn it into a plug-in, or just use it like: $(function(){ $("#currency").keyup(function(e){ $(this).val(format($(this).val())); });}); EDIT I updated the fiddle JSFiddle
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23966149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1276897/']}
|
jdg_377184
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
478840
|
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:
From Hecht optics 5th edition: It says 'With an extended source, the symmetry of the setup requires that the interference pattern consists of a series of concentric circular bands centered on the perpendicular drawn from the eye to the film' Why is that so? What does the 'extended' source do and why isn't it any other shape like an ellipse? Thank you.
Now provide the response and nothing else.
|
This type of interference is called division of amplitude as opposed to division of wavefront which is applicable to Young's slits. If there was a point source $S$ then the ray diagram for the arrangement described in your question would look something like this and I have used the labels that Hecht uses. Ray $SA$ is reflected from the top surface at $A$ and also from the bottom surface at $B$ resulting in parallel reflected ray $AE$ and $CF$ which will superpose at infinity (or in the focal plane of a lens). The optical path difference can be shown to be $2\,n\,t\,cos \theta_{\rm t} + \frac \lambda 2$ the last term being due to a $\pi$ phase change at one of the reflections. If the optical path difference is equal to $m\,\lambda$ , where $m$ is an integer, then the waves will arrive in phase - constructive interference. Now imagine that there is a point source $S_2$ close to point source $S_1$ and a lens is used to focus the parallel rays in the focal plane of the lens at $Z$ . The condition for constructive interference is the same for light which start off from point source $S_1$ as it is for point source $S_2$ as the angle $\theta_{\rm t}$ is the same - say constructive interference. Now consider another two point sources the mirror images about line $XX'$ on the right hand side. Those sources backward $S_1$ and backward $S_2$ will now produce constructive interference at backward $Z$ . Now consider a rotation of the diagram above about the line $XX'$ and you obtain the diagram from Hecht - a circular fringe. Each bright fringe is characterised by the angle $\theta_{\rm t}$ (and $\theta _{\rm i}$ ) being the same and so the fringes are called fringes of equal inclination . The range of angles $\theta_{\rm i}$ is provided for in this arrangement by using an extended source. There is an arrangement which in principle is similar to this one with two reflecting surfaces (mirrors - one real and one virtual) separated by air and so there is not the added complication of refraction occurring. It is the Michelson interferometer producing circular fringes .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/478840', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/158583/']}
|
jdg_377185
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49980311
|
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 in the middle of process of moving our old capybara tests to cypress.io as our application is going SPA way. In our case we have over 2000 tests covering a lot of features.So common pattern to test feature is to have an user with created and published offer. On the beginning I wrote case where cypress were going trough page and clicking everything. It worked but I saw that offer create + publish took almost 1,5 minute to finish. And sometimes we need multiple offers. So we have a test which takes 5 minutes and we have 1999 left to rewrite. We came up with REST API to create offer and user, basically shortcut for test env preparation. I came to the point where everything is working using async/await . So here's the thing. If I want to use normal async JS code with cypress I get Error: Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise. Here's how it looks like: const faker = require('faker') import User from '../../support/User'; describe('Toggle button for description offer', () => { const user = new User({ first_name: faker.name.firstName(), last_name: faker.name.firstName(), email: `QA_${faker.internet.email()}`, password: 'xxx' }) let offer = null before(async () => { await user.createOnServer() offer = await user.createOffer() await offer.publish() }) beforeEach(() => { user.login() cy.visit(`/offers/${offer.details.id}`) cy.get('.offer-description__content button').as('showMoreButton') }) it('XXX', function () { ...some test }) }) This snippet works as expected. Firstly it fires before and creates whole env then when it's done it goes further to beforeEach and starts testing. Now I would like to merge before and beforeEach like before(async () => { await user.createOnServer() offer = await user.createOffer() await offer.publish() user.login() cy.visit(`/offers/${offer.details.id}`) cy.get('.offer-description__content button').as('showMoreButton') }) Which will fail because of async keyword.Now the question is: how to rewrite it to use async/await and cypress commands together? I tried to rewrite it with normal Promise but It won't work too ... Any help appreciated.
Now provide the response and nothing else.
|
Your problem stems from the fact that cypress commands are not promises , although behaving like promises. I can think of two options: Try to refactor your test code to not use async/await, as these commands don't behave as expected when running your code on cypress (check this bug ). Cypress already has a whole way of dealing with async code as it creates a command queue that always run sequentially and in the expected order. That means you could observe the effects of your async code to validate that it happened before moving forward on your test. For instance, if User.createUserOnServer must wait a successful API call, add code to your test that will wait for the request to complete, using cy.server(), cy.route() and cy.wait() , like below: cy.server();cy.route('POST', '/users/').as('createUser');// do something to trigger your request here, like user.createOnServer()cy.wait('@createUser', { timeout: 10000}); Use another third-party library that changes how cypress works with async/await, like cypress-promise . This lib may help you to treat cypress commands as promises that you can await in your before code (read more about it in this article ).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49980311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5688733/']}
|
jdg_377186
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60581617
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently using ts-node with express in production and it's working well so far. Is there any reason that I should compile and run .js instead?
Now provide the response and nothing else.
|
According to Blake Embrey, the author of ts-node , you can use it in production BUT you should use it with the --transpile-only flag. Example: ts-node --transpile-only ./src/start.ts If you are compiling with transpile only, it will have a lower memory footprint as no type information will be generated. However, it can come to problems when you are using reflect-metadata (with experimental support for decorators). In short: Use ts-node --transpile-only (there is also ts-node-transpile-only ) in production when you are not using reflect-metadata . Otherwise, use tsc in combination with classic node .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/60581617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1315706/']}
|
jdg_377187
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33640864
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have a class Foo(val a: String, val b: Int, val c: Date) and I want to sort a list of Foo s based on all three properties. How would I go about this?
Now provide the response and nothing else.
|
Kotlin's stdlib offers a number of useful helper methods for this. First, you can define a comparator using the compareBy() method and pass it to the sortedWith() extension method to receive a sorted copy of the list: val list: List<Foo> = ...val sortedList = list.sortedWith(compareBy({ it.a }, { it.b }, { it.c })) Second, you can let Foo implement Comparable<Foo> using the compareValuesBy() helper method: class Foo(val a: String, val b: Int, val c: Date) : Comparable<Foo> { override fun compareTo(other: Foo) = compareValuesBy(this, other, { it.a }, { it.b }, { it.c })} Then you can call the sorted() extension method without parameters to receive a sorted copy of the list: val sortedList = list.sorted() Sorting direction If you need to sort ascending on some values and descending on other values, the stdlib also offers functions for that: list.sortedWith(compareBy<Foo> { it.a }.thenByDescending { it.b }.thenBy { it.c }) Performance considerations The vararg version of compareValuesBy is not inlined in the bytecode meaning anonymous classes will be generated for the lambdas. However, if the lambdas themselves don't capture state, singleton instances will be used instead of instantiating the lambdas everytime. As noted by Paul Woitaschek in the comments, comparing with multiple selectors will instantiate an array for the vararg call everytime. You can't optimize this by extracting the array as it will be copied on every call. What you can do, on the other hand, is extract the logic into a static comparator instance and reuse it: class Foo(val a: String, val b: Int, val c: Date) : Comparable<Foo> { override fun compareTo(other: Foo) = comparator.compare(this, other) companion object { // using the method reference syntax as an alternative to lambdas val comparator = compareBy(Foo::a, Foo::b, Foo::c) }}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/33640864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/615306/']}
|
jdg_377188
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1960911
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to evaluate this limit for an assignment. $$\lim_{x \to \infty} \sqrt{x^2-6x +1}-x$$ I have tried to rationalize the function:$$=\lim_{x \to \infty} \frac{(\sqrt{x^2-6x +1}-x)(\sqrt{x^2-6x +1}+x)}{\sqrt{x^2-6x +1}+x}$$ $$=\lim_{x \to \infty} \frac{-6x+1}{\sqrt{x^2-6x +1}+x}$$ Then I multiply the function by $$\frac{(\frac{1}{x})}{(\frac{1}{x})}$$ Leading to $$=\lim_{x \to \infty} \frac{-6+(\frac{1}{x})}{\sqrt{(\frac{-6}{x})+(\frac{1}{x^2})}+1}$$ Taking the limit, I see that all x terms tend to zero, leaving -6 as the answer. But -6 is not the answer. Why is that?
Now provide the response and nothing else.
|
You should have gotten, after the last step: $$\lim_{x \to \infty} \frac{-6+\frac1x}{\sqrt{1-\frac6x +\frac1{x^2}}+1}=\frac{-6}{2}=-3$$ so in fact you only had a minor, though pretty influential, arithmetical mistake.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1960911', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/312560/']}
|
jdg_377189
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51743
|
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:
When performing hierarchical clustering, one can use many metrics to measure the distance between clusters. Two such metrics imply calculation of the centroids and means of data points in the clusters. What is the difference between the mean and the centroid? Aren't these the same point in cluster?
Now provide the response and nothing else.
|
As far as I know, the "mean" of a cluster and the centroid of a single cluster are the same thing, though the term "centroid" might be a little more precise than "mean" when dealing with multivariate data. To find the centroid, one computes the (arithmetic) mean of the points' positions separately for each dimension. For example, if you had points at: (-1, 10, 3), (0, 5, 2), and (1, 20, 10), then the centroid would be located at ((-1+0+1)/3, (10+5+20)/3, (3+2+10)/3), which simplifies (0, 11 2/3, 5). (NB: The centroid does not have to be--and rarely is---one of the original data points) The centroid is also sometimes called the center of mass or barycenter, based on its physical interpretation (it's the center of mass of an object defined by the points). Like the mean, the centroid's location minimizes the sum-squared distance from the other points. A related idea is the medoid , which is the data point that is "least dissimilar" from all of the other data points. Unlike the centroid, the medoid has to be one of the original points. You may also be interested in the geometric median which is analgous to the median, but for multivariate data. These are both different from the centroid. However, as Gabe points out in his answer , there is a difference between the "centroid distance" and the "average distance" when you're comparing clusters. The centroid distance between cluster $A$ and $B$ is simply the distance between $\text{centroid}(A)$ and $\text{centroid}(B)$. The average distance is calculated by finding the average pairwise distance between the points in each cluster. In other words, for every point $a_i$ in cluster $A$, you calculate $\text{dist}(a_i, b_1)$, $\text{dist}(a_i, b_2)$ , ... $\text{dist}(a_i, b_n)$ and average them all together.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/51743', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/21754/']}
|
jdg_377190
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12204571
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a simple input field like this. <div class="search"> <input type="text" value="y u no work"/></div> And I'm trying to focus() it inside a function.So inside of a random function (doesn't matter what function it is) I have this line … $('.search').find('input').focus(); This works just fine on every Desktop whatsoever. However it doesn't work on my iPhone. The field is not getting focused and the keyboard is not shown on my iPhone. For testing purposes and to show you guys the problem I did a quick sample: $('#some-test-element').click(function() { $('.search').find('input').focus(); // works well on my iPhone - Keyboard slides in});setTimeout(function() { //alert('test'); //works $('.search').find('input').focus(); // doesn't work on my iPhone - works on Desktop}, 5000); Any idea why the focus() wouldn't work with the timeout function on my iPhone. To see the live example, test this fiddle on your iPhone. http://jsfiddle.net/Hc4sT/ Update: I created the exact same case as I'm currently facing in my current project. I have a select-box that should — when "changed" — set the focus to the input field and slide-in the kexboard on the iphone or other mobile devices. I found out that the focus() is set correctly but the keyboard doesn't show up. I need the keyboard to show up.
Now provide the response and nothing else.
|
Actually, guys, there is a way. I struggled mightily to figure this out for [LINK REMOVED] (try it on an iPhone or iPad). Basically, Safari on touchscreen devices is stingy when it comes to focus() ing textboxes. Even some desktop browsers do better if you do click().focus() . But the designers of Safari on touchscreen devices realized it's annoying to users when the keyboard keeps coming up, so they made the focus appear only on the following conditions: 1) The user clicked somewhere and focus() was called while executing the click event. If you are doing an AJAX call, then you must do it synchronously, such as with the deprecated (but still available) $.ajax({async:false}) option in jQuery. 2) Furthermore -- and this one kept me busy for a while -- focus() still doesn't seem to work if some other textbox is focused at the time. I had a "Go" button which did the AJAX, so I tried blurring the textbox on the touchstart event of the Go button, but that just made the keyboard disappear and moved the viewport before I had a chance to complete the click on the Go button. Finally I tried blurring the textbox on the touchend event of the Go button, and this worked like a charm! When you put #1 and #2 together, you get a magical result that will set your login forms apart from all the crappy web login forms, by placing the focus in your password fields, and make them feel more native. Enjoy! :)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12204571', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1444475/']}
|
jdg_377191
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
629272
|
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 been trying serve multiple directories in one location so that all files can be access on /sys/assets/--FILE-- regardless of where is the file physically locate in the following folder location /sys { alias /var/www/website_api/sys/public; try_files $uri $uri/ /sys/index.php$is_args$args; location ~ \.php { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(.*)$; include /etc/nginx/fastcgi_params; } location /sys/assets { alias /var/www/website_api/sys/app/assets/javascripts/; } location /sys/assets { alias /var/www/website_api/sys/app/assets/stylesheets/; } location /sys/assets { alias /var/www/website_api/sys/app/assets/images/; }} Goal: /sys/assets/javascriptFile.js/sys/assets/stylesheetFile.css/sys/assets/image.png
Now provide the response and nothing else.
|
You can't have duplicate prefixed locations in your configuration. However, that's possible to do what you expect using try_files directive : location /sys { alias /var/www/website_api/sys/public; try_files $uri $uri/ /sys/index.php$is_args$args; location ~ \.php { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(.*)$; include /etc/nginx/fastcgi_params; } location ~ ^/sys/assets/?(.*)$ { root /var/www/website_api/sys/app/assets; try_files /javascripts/$1 /stylesheets/$1 /assets/images/$1; }} If you absolutely need to spare inappropriate filesystem lookups (i.e. kernel stat() calls under Linux), you can also do it more precisely using multiple regex locations matching suitable file extensions : location /sys { alias /var/www/website_api/sys/public; try_files $uri $uri/ /sys/index.php$is_args$args; location ~ \.php { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(.*)$; include /etc/nginx/fastcgi_params; } location ~ ^/sys/assets/?.*\.css$ { rewrite '^/sys/assets/(.*)$' '/$1' break; root /var/www/website_api/sys/app/assets/stylesheets; } location ~ ^/sys/assets/?.*\.(gif|ico|jpe?g|png|svg)$ { rewrite '^/sys/assets/(.*)$' '/$1' break; root /var/www/website_api/sys/app/assets/images; } location ~ ^/sys/assets/?.*\.js$ { rewrite '^/sys/assets/(.*)$' '/$1' break; root /var/www/website_api/sys/app/assets/javascripts; }}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/629272', 'https://serverfault.com', 'https://serverfault.com/users/242844/']}
|
jdg_377192
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6575210
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I pass the id of an element that triggers an onclick event to the event handling function. I am doing something like this- <link onclick="doWithThisElement(id_of_this_element)" />
Now provide the response and nothing else.
|
Instead of passing the ID, you can just pass the element itself: <link onclick="doWithThisElement(this)" /> Or, if you insist on passing the ID: <link id="foo" onclick="doWithThisElement(this.id)" /> Here's the JSFiddle Demo: http://jsfiddle.net/dRkuv/
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6575210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530153/']}
|
jdg_377193
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7977265
|
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 no understanding about how one can cast int to float, step by step? Assume I have a signed integer number which is in binary format. Moreover, I want cast it to float by hand. However, I can't. Thus, CAn one show me how to do that conversion step by step? I do that conversion in c, many times ? like; int a = foo ( ); float f = ( float ) a ; But, I haven't figure out what happens at background. Moreover, To understand well, I want do that conversion by hand. EDIT: If you know much about conversion, you can also give information about for float to double conversion. Moreover, for float to int
Now provide the response and nothing else.
|
Floating point values (IEEE754 ones, anyway) basically have three components: a sign s ; a series of exponent bits e ; and a series of mantissa bits m . The precision dictates how many bits are available for the exponent and mantissa. Let's examine the value 0.1 for single-precision floating point: s eeeeeeee mmmmmmmmmmmmmmmmmmmmmmm 1/n0 01111011 10011001100110011001101 ||||||||||||||||||||||+- 8388608 |||||||||||||||||||||+-- 4194304 ||||||||||||||||||||+--- 2097152 |||||||||||||||||||+---- 1048576 ||||||||||||||||||+----- 524288 |||||||||||||||||+------ 262144 ||||||||||||||||+------- 131072 |||||||||||||||+-------- 65536 ||||||||||||||+--------- 32768 |||||||||||||+---------- 16384 ||||||||||||+----------- 8192 |||||||||||+------------ 4096 ||||||||||+------------- 2048 |||||||||+-------------- 1024 ||||||||+--------------- 512 |||||||+---------------- 256 ||||||+----------------- 128 |||||+------------------ 64 ||||+------------------- 32 |||+-------------------- 16 ||+--------------------- 8 |+---------------------- 4 +----------------------- 2 The sign is positive, that's pretty easy. The exponent is 64+32+16+8+2+1 = 123 - 127 bias = -4 , so the multiplier is 2 -4 or 1/16 . The bias is there so that you can get really small numbers (like 10 -30 ) as well as large ones. The mantissa is chunky. It consists of 1 (the implicit base) plus (for all those bits with each being worth 1/(2 n ) as n starts at 1 and increases to the right), {1/2, 1/16, 1/32, 1/256, 1/512, 1/4096, 1/8192, 1/65536, 1/131072, 1/1048576, 1/2097152, 1/8388608} . When you add all these up, you get 1.60000002384185791015625 . When you multiply that by the 2 -4 multiplier, you get 0.100000001490116119384765625 , which is why they say you cannot represent 0.1 exactly as an IEEE754 float. In terms of converting integers to floats, if you have as many bits in the mantissa (including the implicit 1), you can just transfer the integer bit pattern over and select the correct exponent. There will be no loss of precision. For example a double precision IEEE754 (64 bits, 52/53 of those being mantissa) has no problem taking on a 32-bit integer. If there are more bits in your integer (such as a 32-bit integer and a 32-bit single precision float, which only has 23/24 bits of mantissa) then you need to scale the integer. This involves stripping off the least significant bits (rounding actually) so that it will fit into the mantissa bits. That involves loss of precision of course but that's unavoidable. Let's have a look at a specific value, 123456789 . The following program dumps the bits of each data type. #include <stdio.h>static void dumpBits (char *desc, unsigned char *addr, size_t sz) { unsigned char mask; printf ("%s:\n ", desc); while (sz-- != 0) { putchar (' '); for (mask = 0x80; mask > 0; mask >>= 1, addr++) if (((addr[sz]) & mask) == 0) putchar ('0'); else putchar ('1'); } putchar ('\n');}int main (void) { int intNum = 123456789; float fltNum = intNum; double dblNum = intNum; printf ("%d %f %f\n",intNum, fltNum, dblNum); dumpBits ("Integer", (unsigned char *)(&intNum), sizeof (int)); dumpBits ("Float", (unsigned char *)(&fltNum), sizeof (float)); dumpBits ("Double", (unsigned char *)(&dblNum), sizeof (double)); return 0;} The output on my system is as follows: 123456789 123456792.000000 123456789.000000integer: 00000111 01011011 11001101 00010101float: 01001100 11101011 01111001 10100011double: 01000001 10011101 01101111 00110100 01010100 00000000 00000000 00000000 And we'll look at these one at a time. First the integer, simple powers of two: 00000111 01011011 11001101 00010101 ||| | || || || || | | | +-> 1 ||| | || || || || | | +---> 4 ||| | || || || || | +-----> 16 ||| | || || || || +----------> 256 ||| | || || || |+------------> 1024 ||| | || || || +-------------> 2048 ||| | || || |+----------------> 16384 ||| | || || +-----------------> 32768 ||| | || |+-------------------> 65536 ||| | || +--------------------> 131072 ||| | |+----------------------> 524288 ||| | +-----------------------> 1048576 ||| +-------------------------> 4194304 ||+----------------------------> 16777216 |+-----------------------------> 33554432 +------------------------------> 67108864 ========== 123456789 Now let's look at the single precision float. Notice the bit pattern of the mantissa matching the integer as a near-perfect match: mantissa: 11 01011011 11001101 00011 (spaced out).integer: 00000111 01011011 11001101 00010101 (untouched). There's an implicit 1 bit to the left of the mantissa and it's also been rounded at the other end, which is where that loss of precision comes from (the value changing from 123456789 to 123456792 as in the output from that program above). Working out the values: s eeeeeeee mmmmmmmmmmmmmmmmmmmmmmm 1/n0 10011001 11010110111100110100011 || | || |||| || | |+- 8388608 || | || |||| || | +-- 4194304 || | || |||| || +------ 262144 || | || |||| |+-------- 65536 || | || |||| +--------- 32768 || | || |||+------------ 4096 || | || ||+------------- 2048 || | || |+-------------- 1024 || | || +--------------- 512 || | |+----------------- 128 || | +------------------ 64 || +-------------------- 16 |+---------------------- 4 +----------------------- 2 The sign is positive. The exponent is 128+16+8+1 = 153 - 127 bias = 26 , so the multiplier is 2 26 or 67108864 . The mantissa is 1 (the implicit base) plus (as explained above), {1/2, 1/4, 1/16, 1/64, 1/128, 1/512, 1/1024, 1/2048, 1/4096, 1/32768, 1/65536, 1/262144, 1/4194304, 1/8388608} . When you add all these up, you get 1.83964955806732177734375 . When you multiply that by the 2 26 multiplier, you get 123456792 , the same as the program output. The double bitmask output is: s eeeeeeeeeee mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm0 10000011001 1101011011110011010001010100000000000000000000000000 I am not going to go through the process of figuring out the value of that beast :-) However, I will show the mantissa next to the integer format to show the common bit representation: mantissa: 11 01011011 11001101 00010101 000...000 (spaced out).integer: 00000111 01011011 11001101 00010101 (untouched). You can once again see the commonality with the implicit bit on the left and the vastly greater bit availability on the right, which is why there's no loss of precision in this case. In terms of converting between floats and doubles, that's also reasonably easy to understand. You first have to check the special values such as NaN and the infinities. These are indicated by special exponent/mantissa combinations and it's probably easier to detect these up front ang generate the equivalent in the new format. Then in the case where you're going from double to float, you obviously have less of a range available to you since there are less bits in the exponent. If your double is outside the range of a float, you need to handle that. Assuming it will fit, you then need to: rebase the exponent (the bias is different for the two types). copy as many bits from the mantissa as will fit (rounding if necessary). padding out the rest of the target mantissa (if any) with zero bits.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7977265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_377194
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32376651
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an array object: [ { id:1, name: 'Pedro'}, { id:2, name: 'Miko'}, { id:3, name: 'Bear'}, { id:4, name: 'Teddy'}, { id:5, name: 'Mouse'}] And I have an array with ids [1, 3, 5], How can I filter the array object to leave records only with id's from the second one?
Now provide the response and nothing else.
|
If Array.includes() is supported, you can use it with Array.filter() to get the items: const array = [ { id: 1, name: 'Pedro'}, { id: 2, name: 'Miko'}, { id: 3, name: 'Bear'}, { id: 4, name: 'Teddy'}, { id: 5, name: 'Mouse'}];const filterArray = [1,3,5];const result = array.filter(({ id }) => filterArray.includes(id));console.log(result); If includes is not supported, you can use Array.indexOf() instead: var array = [ { id: 1, name: 'Pedro'}, { id: 2, name: 'Miko'}, { id: 3, name: 'Bear'}, { id: 4, name: 'Teddy'}, { id: 5, name: 'Mouse'}];var filterArray = [1,3,5];var result = array.filter(function(item) { return filterArray.indexOf(item.id) !== -1;});console.log(result);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32376651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1303193/']}
|
jdg_377195
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
390693
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been fiddling with ASP.NET MVC since the CTP, and I like a lot of things they did, but there are things I just don't get. For example, I downloaded beta1, and I'm putting together a little personal site/resume/blog with it. Here is a snippet from the ViewSinglePost view: <% // Display the "Next and Previous" links if (ViewData.Model.PreviousPost != null || ViewData.Model.NextPost != null) { %> <div> <% if (ViewData.Model.PreviousPost != null) { %> <span style="float: left;"> <% Response.Write(Html.ActionLink("<< " + ViewData.Model.PreviousPost.Subject, "view", new { id = ViewData.Model.PreviousPost.Id })); %> </span> <% } if (ViewData.Model.NextPost != null) { %> <span style="float: right;"> <% Response.Write(Html.ActionLink(ViewData.Model.NextPost.Subject + " >>", "view", new { id = ViewData.Model.NextPost.Id })); %> </span> <% } %> <div style="clear: both;" /> </div> <% } %> Disgusting! (Also note that the HTML there is temporary placeholder HTML, I'll make an actual design once the functionality is working) . Am I doing something wrong? Because I spent many dark days in classic ASP, and this tag soup reminds me strongly of it. Everyone preaches how you can do cleaner HTML. Guess, what? 1% of all people look at the outputted HTML. To me, I don't care if Webforms messes up my indentation in the rendered HTML, as long as I have code that is easy to maintain...This is not! So, convert me, a die hard webforms guy, why I should give up my nicely formed ASPX pages for this? Edit: Bolded the "temp Html/css" line so people would stfu about it.
Now provide the response and nothing else.
|
Compared to Web Forms, MVC is simultaneously a lower-level approach to HTML generation with greater control over the page output and a higher-level, more architecturally-driven approach. Let me capture Web Forms and MVC and show why I think that the comparison favors Web Forms in many situations - as long as you don't fall into some classic Web Forms traps. Web Forms In the Web Forms model, your pages correspond directly to the page request from the browser. Thus, if you are directing a user to a list of Books, you'll likely have a page somewhere called "Booklist.aspx" to which you'll direct him. In that page, you'll have to provide everything needed to show that list. This includes code for pulling data, applying any business logic, and displaying the results. If there is any architectural or routing logic affecting the page, you'll have to code the architectural logic on the page as well. Good Web Forms development usually involves the development of a set of supporting classes in a separate (unit-testable) DLL. These class(es) will handle business logic, data access and architectural/routing decisions. MVC MVC takes a more "architectural" view of web application development: offering a standardized scaffold upon which to build. It also provides tools for automatically generating model, view and controller classes within the established architecture. For example, in both Ruby on Rails (just "Rails" from here on out) and ASP.NET MVC you'll always start out with a directory structure that reflects their overall model of web application architecture. To add a view, model and controller, you'll use a command like Rails's "Rails script/generate scaffold {modelname}" (ASP.NET MVC offers similar commands in the IDE). In the resulting controller class, there will be methods ("Actions") for Index (show list), Show, New and Edit and Destroy (at least in Rails, MVC is similar). By default, these "Get" Actions just bundle up the Model and route to a corresponding view/html file in the "View/{modelname}" directory (note that there are also Create, Update and Destroy actions that handle a "Post" and route back to Index or Show). The layout of directories and files is significant in MVC. For example, in ASP.NET MVC, the Index method for a "Book" object will likely just have one line: "Return View();" Through the magic of MVC, this will send the Book model to the "/View/Books/Index.aspx" page where you'll find code to display Books. Rails's approach is similar although the logic is a bit more explicit and less "magic." A View page in an MVC app is usually simpler than a Web Forms page because they don't have to worry as much about routing, business logic or data handling. Comparison The advantages of MVC revolve around a clean separation of concerns and a cleaner, more HTML/CSS/AJAX/Javascript-centric model for producing your output. This enhances testability, provides a more standardized design and opens the door to a more "Web 2.0" type of web site. However, there are some significant drawbacks as well. First, while it is easy to get a demo site going, the overall architectural model has a significant learning curve. When they say "Convention Over Configuration" it sounds good - until you realize that you have a book's-worth of convention to learn. Furthermore, it is often a bit maddening to figure out what is going on because you are relying on magic rather than explicit calls. For example, that "Return View();" call above? The exact same call can be found in other Actions but they go to different places. If you understand the MVC convention then you know why this is done. However, it certainly doesn't qualify as an example of good naming or easily understandable code and it is much harder for new developers to pick up than Web Forms (this isn't just opinion: I had a summer intern learn Web Forms last year and MVC this year and the differences in productivity were pronounced - in favor of Web Forms). BTW, Rails is a bit better in this regard although Ruby on Rails features dynamically-named methods that take some serious getting-used-to as well. Second, MVC implicitly assumes that you are building a classic CRUD-style web site. The architectural decisions and especially the code generators are all built to support this type of web application. If you are building a CRUD application and want to adopt a proven architecture (or simply dislike architecture design), then you should probably consider MVC. However, if you'll be doing more than CRUD and/or you are reasonably competent with architecture then MVC may feel like a straightjacket until you really master the underlying routing model (which is considerably more complex than simply routing in a WebForms app). Even then, I've felt like I was always fighting the model and worried about unexpected outcomes. Third, if you don't care for Linq (either because you are afraid that Linq-to-SQL is going to disappear or because you find Linq-to-Entities laughably over-produced and under powered) then you also don't want to walk this path since ASP.NET MVC scaffolding tools are build around Linq (this was the killer for me). Rails's data model is also quite clumsy compared to what you can achieve if you are experienced in SQL (and especially if you are well-versed in TSQL and stored procedures!). Fourth, MVC proponents often point out that MVC views are closer in spirit to the HTML/CSS/AJAX model of the web. For example, "HTML Helpers" - the little code calls in your vew page that swap in content and place it into HTML controls - are much easier to integrate with Javascript than Web Forms controls. However, ASP.NET 4.0 introduces the ability to name your controls and thus largely eliminates this advantage. Fifth, MVC purists often deride Viewstate. In some cases, they are right to do so. However, Viewstate can also be a great tool and a boon to productivity. By way of comparison, handling Viewstate is much easier than trying to integrate third-party web controls in an MVC app. While control integration may get easier for MVC, all of the current efforts that I've seen suffer from the need to build (somewhat grody) code to link these controls back to the view's Controller class (that is - to work around the MVC model). Conclusions I like MVC development in many ways (although I prefer Rails to ASP.NET MVC by a long shot). I also think that it is important that we don't fall into the trap of thinking that ASP.NET MVC is an "anti-pattern" of ASP.NET Web Forms. They are different but not completely alien and certainly there is room for both. However, I prefer Web Forms development because, for most tasks , it is simply easier to get things done (the exception being generation of a set of CRUD forms). MVC also seems to suffer, to some extent, from an excess of theory. Indeed, look at the many questions asked here on SO by people who know page-oriented ASP.NET but who are trying MVC. Without exception, there is much gnashing of teeth as developers find that they can't do basic tasks without jumping through hoops or enduring a huge learning curve. This is what makes Web Forms superior to MVC in my book: MVC makes you pay a real world price in order to gain a bit more testability or, worse yet, to simply be seen as cool because you are using the latest technology. Update: I've been criticized heavily in the comments section - some of it quite fair. Thus, I have spent several months learning Rails and ASP.NET MVC just to make sure I wasn't really missing out on the next big thing! Of course, it also helps ensure that I provide a balanced and appropriate response to the question. You should know that the above response is a major rewrite of my initial answer in case the comments seem out of synch. While I was looking more closely into MVC I thought, for a little while, that I'd end up with a major mea culpa. In the end I concluded that, while I think we need to spend a lot more energy on Web Forms architecture and testability, MVC really doesn't answer the call for me. So, a hearty "thank you" to the folks that provided intelligent critiques of my initial answer. As to those who saw this as a religious battle and who relentlessly engineered downvote floods, I don't understand why you bother (20+ down-votes within seconds of one another on multiple occasions is certainly not normal). If you are reading this answer and wondering if there is something truly "wrong" about my answer given that the score is far lower than some of the other answers, rest assured that it says more about a few people who disagree than the general sense of the community (overall, this one has been upvoted well over 100 times). The fact is that many developers don't care for MVC and, indeed, this is not a minority view (even within MS as the blogs seem to indicate).
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/390693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1965/']}
|
jdg_377196
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1594171
|
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 method with the following signature: void MyMethod(Delegate d){}; void MyMethod(Expression exp){}; void MyMethod(object obj){}; However, this fails to compile: MyMethod((int a) => a) with the following error: "Cannot convert lambda expression to type 'object' because it is not a delegate type" Why doesn't this work? Edit: I know that this works. The compiler compiles the lambda expression to a delgate in this case I think. void MyMethod(Func<int, int> d){}; Kind regards,
Now provide the response and nothing else.
|
Because the type System.Delegate isn't a "Delegate". It's just the base class. You have to use a delegate type with the correct signature. Define your Method as follows: void MyMethod(Func<int, int> objFunc) EDIT: MyMethod(object) doesn't work because a lambda expression has no type at it's own, but the type is inferred from the type of the location it is assigned to. So object doesn't work either. You HAVE to use a delegate type with the correct signature.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1594171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21586/']}
|
jdg_377197
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50464141
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It seems that from TypeScript 2.4 onwards String Enums are a feature. However the following does not work: enum Foo { A = "A", B = "B"}var foo : Foo = "A"; Initializer type string not assignable to variable type Foo String literals work: type Foo = "A" | "B"; But what if I want to use an enum ? Is there a way around this?
Now provide the response and nothing else.
|
You can use an index expression to get the value of the enum: enum Foo { A = "A", B = "BB"}var foo : Foo = Foo["A"];var fooB : Foo = Foo["B"]; Note that the key will be the name of the member not the value. You could also use a type assertion, but you will not get errors if you assign a wrong value: var foo : Foo = "A" as Foo;var foo : Foo = "D" as Foo; // No error
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50464141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/777510/']}
|
jdg_377198
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48199077
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a list of numpy arrays. I want to calculate the average of values in these arrays.For example: import numpy as nparrays = [np.random.random((4,2)) for _ in range(3)] How can I have the average of elements in this array? That is I want the results to be of shape (4,2) where each element is the average of corresponding indices for arrays in the list.I know I can write a for loop to achieve this, but there should be a better numpy way.
Now provide the response and nothing else.
|
Use the functional form of np.mean : >>> import numpy as np>>> arrays = [np.random.random((4,2)) for _ in range(3)]>>> np.mean(arrays, axis=0) This converts your list of arrays to a 3D array of shape (3, 4, 2) and then takes the mean along axis 0 . You can also use Python's sum : >>> sum(arrays)/len(arrays) For small lists like your example this is actually faster. Some timings ( m is the length of the list): m: 3 n:4 k: 2numpy 0.01291340 mspython 0.00295936 msm: 10 n:100 k: 100numpy 0.14189354 mspython 0.09465128 msm: 1000 n:10 k: 10numpy 0.43023768 mspython 0.45201713 ms Benchmarking code: import numpy as npfrom timeit import timeitimport typesdef setup(m, n, k): return list(np.random.random((m, n, k)))def f_numpy(a): return np.mean(a, axis=0)def f_python(a): return sum(a)/len(a)for args in [(3, 4, 2), (10, 100, 100), (1000, 10, 10)]: data = setup(*args) print('m: {} n:{} k: {}'.format(*args)) for name, func in list(globals().items()): if not name.startswith('f_') or not isinstance(func, types.FunctionType): continue print("{:16s}{:16.8f} ms".format(name[2:], timeit( 'f(data)', globals={'f':func, 'data':data}, number=1000)))
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48199077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3450064/']}
|
jdg_377199
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8059919
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Been watching a WWDC video today about new features in xCode 4. They have mentioned that it a good idea to use log message actions on breakpoints along with "automatically continue after evaluation actions" enabled to output a variable's value for instance instead of using NSLogs all the time. lets say I have something like that: NSLog(@"URL is : %@", userDocumentsURL); How would I write a log message action to display userDocumentsURL's value? Is it really a good idea to use the above method instead of NSLog?
Now provide the response and nothing else.
|
Create a Breakpoint 'Log Message' action. For the log message include something like: URL is @(char*) [[userDocumentsURL description] UTF8String]@ Alternatively you can create a breakpoint 'Debugger command' action similar to: po [NSString stringWithFormat:@"URL is: %@", userDocumentsURL] I prefer using breakpoint actions for logging, as it's arguably easier to clear out a bunch of breakpoints than it is to remove NSLogs. A possible downside to using breakpoints in this fashion is that they are significantly slower (during debugging) than a direct NSLog.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8059919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/518248/']}
|
jdg_377200
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29640206
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Some of the custom fonts I've loaded onto my app are getting cut off when displayed in a UILabel. I have multiple custom fonts that I need to properly display. How can I fix this?
Now provide the response and nothing else.
|
As stated, I had a very annoying problem where custom fonts in a UILabel would get cut off due to something . I later found out it was due to ascenders and descenders (font characteristics). After much searching I found a solution that required you to download a program, adjust the font's ascender and descender using terminal and then test it out on your app until it's perfect. This would be fine if I didn't have to do this for 20+ fonts. So I decided to dig around and see if I could access the a font's ascender and descender values. Turns out UIFont has those exact attributes! With that information, I was able to subclass UILabel and adjust its frame dynamically by adding the ascender and descender values (use absolute value as it is negative) to its height. Here's a snippet of the implementation code below, the last line is the money line: UIFont *font = [UIFont fontWithName:nameOfFontUsed size:44.0];NSDictionary *attrsDict = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];NSMutableAttributedString *theString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@", enteredString] attributes:attrsDict];//Add other attributes you desireNSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;paragraphStyle.lineHeightMultiple = 5.0;[theString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [theString length])];[self setAttributedText:theString];[self sizeToFit];[self setFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height+font.ascender+ABS(font.descender))];
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29640206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/834310/']}
|
jdg_377201
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8540539
|
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 this ^[S-s][0-9]{4}$ to validate my string, but not working properly. my string has to be in the form of the Letter S (upper-case or lower-case) followed by 4 digits, e.g. S1234 . Looks like it works for Letters above S, meaning if I enter w1234 it validates correct, but if I enter a letter below s, like a1234 it doesn’t validate. Thanks.
Now provide the response and nothing else.
|
You need to get rid of the dash: ^[Ss][0-9]{4}$ dashes within [...] denote character ranges. Thus S-s in regex would mean "every character in Unicode character table between S and s" and as those two are not adjacent, you end up with a bunch of matched chars.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8540539', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/282807/']}
|
jdg_377202
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
62315597
|
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 create a Java program that checks to see if an input password has at least three lowercase letters, 2 uppercase letters, and 1 digit. This is what I have so far: Scanner inputDevice = new Scanner(System.in); boolean valid= false; String password; do{ System.out.print("Enter a password that contains at least 2 uppercase letters, three lowercase letters, and at least 1 digit: "); password = inputDevice.nextLine(); boolean Upper; boolean Lower; boolean Digit; int UpperCount=0; int LowerCount=0; int DigitCount=0; for(int i=0; i<password.length(); i++){ if (Character.isUpperCase(password.charAt(i))); UpperCount++;} if (UpperCount<2) Upper=false; else Upper=true; for(int i=0; i<password.length(); i++){ if (Character.isLowerCase(password.charAt(i))); LowerCount++;} if (LowerCount<3) Lower=false; else Lower=true; for(int i=0; i<password.length(); i++){ if (Character.isDigit(password.charAt(i))); DigitCount++;} if (DigitCount<1) Digit=false; else Digit=true; if ((Digit == false) || (Upper == false) || (Lower == false)) System.out.print("The password did not have enough of the following:"); if (Upper == false) System.out.print("\nuppercase letters"); if (Lower == false) System.out.print("\nlowercase letters"); if (Digit ==false) System.out.print("\ndigits"); if ((Digit==true)&&(Upper==true)&&(Lower==true)) valid=true; }while(valid!=true); System.out.println("Valid password"); I have been wrestling with it for a while now. Some problems I have had have been: The counts not resetting to zero when returning to the top of the loop. The loop not recognizing digits or putting completely wrong outputs based on my test runs. Now it is just skipping the loop entirely and goes to the Valid Password statement no matter what I type into the input to test. At this point I am really frustrated and could use some help.
Now provide the response and nothing else.
|
If you check the Google Developer TOS which you agreed to when you created your account on Google developer console It is against the TOS for you to share this file with anyone. This is secret and only intended for the developer or team of developers who created it. This pertains to the entire client secret json file you download from Google developer console or google cloud console. Again DO not share your google secret file. No matter what the accepted answer stays about how problematic it may or may not, nor does it matter what type of client it is. Sharing the client secret file would be volatilizing the TOS you agreed to. My corrections for another answer on this thread here The answer in question has some statements that i strongly disagree with and feel may cause confusion to developers. Let me start by saying I am not an employee of Google, my comments are my own and from my experience with working googles oauth / identity server server for eight+ years and contact with google identity team. I am concerned that some of the information in the answer above may confuse some developers. Rather than just saying dont share them the other question tries incorrectly IMO to explain why it wouldn't be so bad to share them. I will explain why you should never share them beyond the fact that its against googles TOS. The security implications depend on the type of client secret. You can tell the difference by whether the key in the JSON file is installed or web. The type of client has no effect upon I how great the security risk would be. If we ignore the definition of what a constitutes a security risk completely and just say that any chance anyone could get access to a users account or authenticate a user on behalf of the project, would constitute to big of a security risk then there is no difference. Using the following command I could authenticate myself all i need is the credentials file for your project https://accounts.google.com/o/oauth2/auth?client_id= {clientid}.apps.googleusercontent.com&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope= https://www.googleapis.com/auth/analytics.readonly&response_type=code This would only work 100% of the time for an installed application. Why is this bad if i am just authenticating my own user. I could then use my evil powers to send so many requests against the API that the target google developer project would be locked down by Google for spamming. If i have stolen another users login and password i can login to them from your Google developer project and i have access to their data and Google thinks its you hacking them. This is a little harder with a web application due to the Redirect URI, However a lot of developers include add localhost as a redirect uri when in development and forget to take it out (Please never leave localhost as a redirect uri when you are in proudcution) . So in the event you have left redirect URI as a valid redirect URI in a web browser client then I can do the exact same thing. Remember I am now able to authenticate users based upon your project to access mostly my own data. However if you have also set up access to client data for example via google drive I may be able to access that as well. (Note: Im not Sure on this one i havent actually tried.) If i have manged though man in the middle attack or some other means to get a users refresh token, and I have the client secret file I can now access users data because I can create new access tokens with my refresh token for as long as i want. This is probably a bit harder to achieve. Web application secrets If the client secret is of the web type, then yes: you should absolutely not post it, and invalidate it if it gets exposed. This would allow a malicious entity to impersonate your backend and perform actions on your users' accounts on your behalf. As stated above this will only be the case if the developer in question has left the redirect uri open for localhost or the person who now has your client secret file also has access to your web server. One very important fact is that if you have left localhost open i can then put up my own website using your credentials and set it up so it look exactly like your website. Users then think they are logging into Your super awesome app when in fact they are logging into Hacker Super awesome app giving them access to the users data. Again google thinks its you hacking them. Installed application secrets If the client secret is an installed-type secret, then it's less problematic to share privately, as it doesn't grant the sorts of abilities a web application secret does, such as the ability to authenticate as users who grant your application permission to access their data. As the documentation notes, "in this context, the client secret is obviously not treated as a secret." This is completely false Installed applications give the exact same permissions as web applications there is no difference with-regard to Oauth2 access an access token is an access token no matter if it was created for an installed application or a web application. As stated above security risk with giving out access to your installed application this is actually worse. As there are no redirect uris with installed applications. Anyone that has access to your client secret file could authenticate users who assume they are you because they are being shown your consent screen. Not only is your Google developer project being hjacked but your reputation to your users who think that they are authenticating to Super awesome app and in fact they are not granting the person who has stolen your credentials access to their data. I would like to add one last thing. If you give another person your project credentials. The client secret json file. You are giving them access to make calls on your behalf. If you have bulling set up lets say against google maps api. You will be charged for the calls they make. I hope this helps to clear up some of the confusion related to the accepted anwser.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62315597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13724327/']}
|
jdg_377203
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
355540
|
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:
My company is rewriting our web application from scratch. It's a large enterprise level application with a complex domain in the finance industry. We are using an ORM (Entity framework) for persistence. In essence, half of our application centers around gathering raw data from the user, storing it, and then the other half of the application that contains most of our actual domain logic takes that raw data to create our domain picture which differs greatly from those original raw inputs, and passes it into a calc engine, runs calcs, and spits out results, which are then displayed to the user. In a DDD approach using layers, it seems like CRUD operations go through the domain layer. but at least in our case, this doesn't seem to make sense. When a user goes to the edit screen to change an investment account for instance, the fields on the screen are the exact fields stored in the database, not the domain representation used later for calculations. So why would I load the domain representation of the investment account when the edit screen needs the database representation (raw inputs)? After the user clicks "Done" on the investment account screen, and a POST is done to the controller, the controller now has pretty much an exact database representation of the investment account that it needs to save. But for some reason, I'm supposed to load the domain representation to make modifications instead of just mapping the controller's model directly to the database model (Entity framework model)? So in essence I'm mapping a data model to the domain model, just so it can then be mapped back to the data model to persist. How does that make sense?
Now provide the response and nothing else.
|
How does that make sense? Short answer: it doesn't . Longer answer: the heavyweight patterns for developing a domain model don't apply to those portions of your solution that are just a database. Udi Dahan had an interesting observation that may help clarify this Dahan considers that a service has to have both some sort of functionality and some data. If it does not have data, then it is just a function. If all that it does is performing CRUD operations on data, then it is database. The point of the domain model, after all, is to ensure that all of the updates to the data maintain the current business invariant. Or, to put it another way, the domain model is responsible for ensuring that the database that acts as the system of record is correct. When you are dealing with a CRUD system, you usually aren't the system of record for the data. The real world is the book of record, and your database is just a locally cached representation of the real world. For instance, most information that appears in a user profile, like an email address, or a government issued identification number, has a source of truth that lives outside of your business -- it's somebody else's mail administrator that assigns and revokes email addresses, not your app. It's the government that assigns SSNs, not your app. So you aren't normally going to be doing any domain validation on the data coming to you from the outside world; you might have checks in place to ensure that the data is well formed and properly sanitized ; but its not your data - your domain model doesn't get a veto. In a DDD approach using layers, it seems like CRUD operations go through the domain layer. but at least in our case, this doesn't seem to make sense. That's right for the case where the database is the book of record . Ouarzy put it this way . Working on lots of legacy code though, I observe common mistakes to identify what is inside the domain, and what is outside. An application can be considered CRUD only if there is no business logic around the data model. Even in this (rare) case, your data model is not your domain model. It just means that, as no business logics is involved, we don’t need any abstraction to manage it, and thus we have no domain model. We use the domain model to manage the data that belongs inside the domain; the data from outside the domain is already managed somewhere else -- we're just caching a copy. Greg Young uses warehouse systems as a primary illustration of solutions where the book of record is somewhere else (ie: the warehouse floor). The implementation he describes is a lot like yours -- one logical database to capture messages received from the warehouse, and then a separate logical database caching the conclusions drawn from the analysis of those messages. So maybe we have two bounded contexts here? Each with a different model for an investment account Maybe. I'd be reluctant to tag it as a bounded context, because it's not clear what other baggage comes along with it. It might be that you have two contexts, it might be one context with subtle differences in the ubiquitous language that you haven't picked up yet. Possible litmus test: how many domain experts do you need; two domain experts to cover this spectrum, or just one who talks about the components in different ways? Basically, you might be able to guess how many bounded contexts you have by working Conway's law backwards. If you consider bounded contexts to be aligned with services, it may be easier: should you be able to deploy these two pieces of functionality independently? Yes suggests two bounded contexts; but if they need to be kept synchronized, then maybe its just one.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/355540', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/280428/']}
|
jdg_377204
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9858699
|
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 update a parent component from a composite component event using f:ajax . The composite component is here: <cc:interface> <cc:attribute name="update" /> <cc:attribute name="customid" required="true"/> <cc:attribute name="val" required="true"/> <cc:attribute name="selectedvalue" required="true"/></cc:interface><cc:implementation> <h:panelGrid columns="2" style="font-size: 10px" > <p:selectOneMenu id="#{cc.attrs.customid} value="#{cc.attrs.selectedvalue}"> <f:selectItems value="#{cc.attrs.val}"/> <f:ajax event="change" render="#{cc.attrs.update" /> </p:selectOneMenu> <p:commandButton type="button" icon="ui-icon-plus" onclick="dlg.show();" /> </h:panelGrid></cc:implementation> Now when using this component as follows: <h:form> <ez:combo customid="make" val="#{vehicleBean.makes}" selectedvalue="#vehicleBean.vehicle.make}" update="model" /> <p:selectOneMenu id="model" value="#{vehicleBean.vehicle.model}"> <f:selectItems value="#{vehicleBean.models}" /> </p:selectOneMenu></h:form> I get the following error: contains an unknown id 'model' - cannot locate it in the context of the component make
Now provide the response and nothing else.
|
Since the component to update is outside the cc you have to address it in a different way. First give your form an id: <h:form id="myform"> Then address the target component from your cc like this: render=":myform:model" Notice the trailing colon which lets JSF search the attribute from the document root.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9858699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1290985/']}
|
jdg_377205
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12408561
|
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 line like this: <%= f.input :state_id, :input_html => {:value => (policy_address.state.name rescue nil)}, :required => true, :collection => states.map {|s| [ s.name, s.id] }, :include_blank => 'Please select'%> I want to exclude a value from the states.map collection. I thought that this would work but it doesn't: <%= f.input :state_id, :input_html => {:value => (policy_address.state.name rescue nil)}, :required => true, :collection => states.map {|s| [ s.name, s.id] unless s.name == "excluded_state" }, :include_blank => 'Please select'%> I put in unless s.name == "excluded_state , but, again, it's not working: What am I doing wrong?
Now provide the response and nothing else.
|
map doesn't allow to skip values. You have to reject unwanted elements first. states.reject { |s| s.name == "excluded_state" }.map { |s| [s.name, s.id] } Another (dirtier) solution is to return nil for excluded elements and use Array#compact on the resulting array to remove those nil elements: states.map { |s| s.name == "excluded_state" ? nil : [s.name, s.id] }.compact
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12408561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/830035/']}
|
jdg_377206
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16829616
|
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 integrated requirejs with angular app.. before intregrating requirejs, <input type="number" value="{{cart.quantity}}" ng-model="cart.quantity" /> was showing the value in input box. But after integrating with requirejs, input box with type="number" not showing me the value..input box with type="text" is working. How can I show value with type="number" ? Thanks
Now provide the response and nothing else.
|
I just ran into this same issue and managed to solve it. In my case, the model is being obtained via a RESTful $resource and the value for the amount is being provided as a string to the field, which in turn wipes out the value. In order to address this, I ended up doing the following in my controller: $scope.cart = Cart.get(id: $routeParams.id, function(cart){ cart.quantity = parseFloat(cart.quantity, 10);}); which turns the value into a float, prior to updating the view. One gotcha I ran into is that my first attempt was setting $scope.cart.quantity = parseFloat($scope.cart.quantity, 10) immediately after the get . This was not working since the value was overwritten when the async call to get completed. $scope.cart = Cart.get(id: $routeParams.id);$scope.cart.quantity = parseFloat($scope.cart.quantity, 10); // This won't work Hope this helps.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16829616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1716498/']}
|
jdg_377207
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32829
|
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:
Recent news stories have reported on the discovery of a lost Mayan city by William Gadoury, a 15-year-old from Canada. According to these reports, Gadoury noticed a correspondence between the locations of Mayan cities and Mayan constellations (the articles I have read do not go into more detail) and then analysed satellite imagery in the region of a "missing" city, and noticed the outlines of several rectangular structures beneath a forest canopy. For example, see this article in The Independent, which says William Gadoury, from Quebec, came up with the theory that the Maya civilization chose the location of its towns and cities according to its star constellations. He found Mayan cities lined up exactly with stars in the civilization's major constellations. Studying the star map further, he discovered one city was missing from a constellation of three stars. Using satellite images provided by the Canadian Space Agency and then mapped on to Google Earth, he discovered the city where the third star of the constellation suggested it would be. Is there any truth to this story? What evidence is there to suggest that Gadoury has discovered a hidden Mayan city (as opposed to, for example, some reasonably old but much more recent set of man-made structures hidden beneath the forest canopy)?
Now provide the response and nothing else.
|
Probably not. There are two factors here: Did the Mayans actually base their city locations on their civilization's constellations? Given A, is the structure discovered actually a city? The answer to both is probably "No". This article has multiple updates that feature expert commentary on both issues. On the constellation issue, from Ivan Šprajc from the Institute of Anthropological and Spatial Studies in Slovenia: Very few Maya constellations have been identified, and even in these cases we do not know how many and which stars exactly composed each constellation. It is thus impossible to check whether there is any correspondence between the stars and the location of Maya cities. In general, since we know of several environmental facts that influenced the location of Maya settlements, the idea correlating them with stars is utterly unlikely. OK, but maybe he got lucky and the structure he found was actually a city anyway. In reality, it is almost certainly a cornfield that is a few decades old: Thomas Garrison, an anthropologist at USC Dornsife and an expert in remote sensing, says these objects are relic corn fields (or milpas): I applaud the young kid’s effort and it’s exciting to see such interest in the ancient Maya and remote sensing technology in such a young person. However, ground-truthing is the key to remote sensing research. You have to be able to confirm what you are identifying in a satellite image or other type of scene. In this case, the rectilinear nature of the feature and the secondary vegetation growing back within it are clear signs of a relic milpa. I’d guess its been fallow for 10-15 years. This is obvious to anyone that has spent any time at all in the Maya lowlands. David Stuart, an anthropologist from The Mesoamerica Center-University of Texas at Austin summarizes the situation: The current news of an ancient Maya city being discovered is false...The ancient Maya didn't plot their ancient cities according to constellations. Seeing such patterns is a rorschach process, since sites are everywhere, and so are stars. The square feature that was found on Google is indeed man-made, but it's an old fallow cornfield, or milpa.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/32829', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/2873/']}
|
jdg_377208
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4699417
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Im creating an application where i need to position a ImageView depending on the Orientation of the device. I use the values from a MagneticField and Accelerometer Sensors to calculate the device orientation with SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerValues, magneticFieldValues)SensorManager.getOrientation(rotationMatrix, values);double degrees = Math.toDegrees(values[0]); My problem is that the positioning of the ImageView is very sensitive to changes in the orientation. Making the imageview constantly jumping around the screen. (because the degrees change) I read that this can be because my device is close to things that can affect the magneticfield readings. But this is not the only reason it seems. I tried downloading some applications and found that the " 3D compass " and " Compass " remains extremely steady in its readings (when setting the noise filter up), i would like the same behavior in my application. I read that i can tweak the "noise" of my readings by adding a " Low pass filter ", but i have no idea how to implement this (because of my lack of Math). Im hoping someone can help me creating a more steady reading on my device, Where a little movement to the device wont affect the current orientation.Right now i do a small if (Math.abs(lastReadingDegrees - newReadingDegrees) > 1) { updatePosition() } To filter abit of the noise. But its not working very well :)
Now provide the response and nothing else.
|
Though I havn't used the compass on Android, the basic processing shown below (in JavaScript) will probably work for you. It's based on the low pass filter on the accelerometer that's recommended by the Windows Phone team with modifications to suit a compass (the cyclic behavior every 360"). I assume the compass reading is in degrees, a float between 0-360, and the output should be similar. You want to accomplish 2 things in the filter: If the change is small, to prevent gitter, gradually turn to that direction. If the change is big, to prevent lag, turn to that direction immediatly (and it can be canceled if you want the compass to move only in a smooth way). For that we will have 2 constants: The easing float that defines how smooth the movement will be (1 is no smoothing and 0 is never updating, my default is 0.5). We will call it SmoothFactorCompass. The threshold in which the distance is big enough to turn immediatly (0 is jump always, 360 is never jumping, my default is 30). We will call it SmoothThresholdCompass. We have one variable saved across the calls, a float called oldCompass and it is the result of the algorithm. So the variable defenition is: var SmoothFactorCompass = 0.5;var SmoothThresholdCompass = 30.0;var oldCompass = 0.0; and the function recieves newCompass, and returns oldCompass as the result. if (Math.abs(newCompass - oldCompass) < 180) { if (Math.abs(newCompass - oldCompass) > SmoothThresholdCompass) { oldCompass = newCompass; } else { oldCompass = oldCompass + SmoothFactorCompass * (newCompass - oldCompass); }}else { if (360.0 - Math.abs(newCompass - oldCompass) > SmoothThresholdCompass) { oldCompass = newCompass; } else { if (oldCompass > newCompass) { oldCompass = (oldCompass + SmoothFactorCompass * ((360 + newCompass - oldCompass) % 360) + 360) % 360; } else { oldCompass = (oldCompass - SmoothFactorCompass * ((360 - newCompass + oldCompass) % 360) + 360) % 360; } }} I see that the issue was opened 5 months ago and probably isn't relevant anymore, but I'm sure other programmers might find it useful. Oded Elyada.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4699417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/246234/']}
|
jdg_377209
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25894509
|
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 getting the following error when trying to execute statemet.executeUpdate() in my code: Local variable statement defined in an enclosing scope must be final or effectively final. This is my code so far: import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;.import org.eclipse.swt.SWT;import org.eclipse.swt.events.MouseAdapter;import org.eclipse.swt.events.MouseEvent;import org.eclipse.swt.widgets.Button;import org.eclipse.swt.widgets.Display;import org.eclipse.swt.widgets.Label;import org.eclipse.swt.widgets.Shell;import org.eclipse.swt.widgets.Text;public class a1 { protected Shell shell; private Text text; private Text text_1; private Text text_2; private Text text_3; /** * Launch the application. * @param args */ public static void main(String[] args) { try { a1 window = new a1(); window.open(); } catch (Exception e) { e.printStackTrace(); } } /** * Open the window. */ public void open() { Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Create contents of the window. */ protected void createContents() { Connection connect = null; ResultSet resultSet = null; try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { connect = DriverManager.getConnection("jdbc:mysql://localhost/railwaydb", "root", ""); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } Statement statement = null; // statements allow to issue SQL queries to the database try { statement = connect.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } shell = new Shell(); shell.setSize(450, 300); shell.setText("SWT Application"); Label lblName = new Label(shell, SWT.NONE); lblName.setBounds(10, 43, 47, 15); lblName.setText("Name"); Label lblFrom = new Label(shell, SWT.NONE); lblFrom.setBounds(10, 74, 55, 15); lblFrom.setText("From"); Label lblTo = new Label(shell, SWT.NONE); lblTo.setBounds(10, 105, 55, 15); lblTo.setText("To"); Label lblPrice = new Label(shell, SWT.NONE); lblPrice.setBounds(10, 137, 55, 15); lblPrice.setText("Price"); text = new Text(shell, SWT.BORDER); text.setBounds(64, 43, 76, 21); text_1 = new Text(shell, SWT.BORDER); text_1.setBounds(64, 74, 76, 21); text_2 = new Text(shell, SWT.BORDER); text_2.setBounds(64, 105, 76, 21); text_3 = new Text(shell, SWT.BORDER); text_3.setBounds(64, 137, 76, 21); Label lblRailwayDatabase = new Label(shell, SWT.NONE); lblRailwayDatabase.setBounds(174, 10, 97, 15); lblRailwayDatabase.setText("Railway Database"); Label lblCreateView = new Label(shell, SWT.NONE); lblCreateView.setBounds(189, 43, 76, 15); lblCreateView.setText("Create View"); Button btnName = new Button(shell, SWT.CHECK); btnName.setBounds(189, 73, 93, 16); btnName.setText("Name"); Button btnFrom = new Button(shell, SWT.CHECK); btnFrom.setBounds(189, 105, 93, 16); btnFrom.setText("From"); Button btnTo = new Button(shell, SWT.CHECK); btnTo.setBounds(189, 137, 93, 16); btnTo.setText("To"); Button btnPrice = new Button(shell, SWT.CHECK); btnPrice.setBounds(189, 171, 93, 16); btnPrice.setText("Price"); Button btnInsert = new Button(shell, SWT.NONE); btnInsert.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { String name = text.getText(); String from = text_1.getText(); String to = text_2.getText(); String price = text_3.getText(); String query = "INSERT INTO booking (name, fromst, tost, price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')"; try { statement.executeUpdate(query); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); btnInsert.setBounds(10, 171, 75, 25); btnInsert.setText("Insert"); Button btnView = new Button(shell, SWT.NONE); btnView.setBounds(307, 74, 75, 25); btnView.setText("View"); Button btnIndex = new Button(shell, SWT.NONE); btnIndex.setBounds(307, 127, 75, 25); btnIndex.setText("Index"); }} I also tried to set statement final but the declaration gives me another error.
Now provide the response and nothing else.
|
You have a scope problem indeed, because statement is a local method variable defined here: protected void createContents() { ... Statement statement = null; // local variable ... btnInsert.addMouseListener(new MouseAdapter() { // anonymous inner class @Override public void mouseDown(MouseEvent e) { ... try { statement.executeUpdate(query); // local variable out of scope here } catch (SQLException e1) { e1.printStackTrace(); } ... });} When you try to access this variable inside mouseDown() method you are trying to access a local variable from within an anonymous inner class and the scope is not enough. So it definitely must be final (which given your code is not possible) or declared as a class member so the inner class can access this statement variable. Sources: Anonymous Classes How are Anonymous (inner) classes used in Java? How to solve it? You could... Make statement a class member instead of a local variable: public class A1 { // Note Java Code Convention, also class name should be meaningful private Statement statement; ...} You could... Define another final variable and use this one instead, as suggested by @HotLicks: protected void createContents() { ... Statement statement = null; try { statement = connect.createStatement(); final Statement innerStatement = statement; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } ...} But you should... Reconsider your approach. If statement variable won't be used until btnInsert button is pressed then it doesn't make sense to create a connection before this actually happens. You could use all local variables like this: btnInsert.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { try { Class.forName("com.mysql.jdbc.Driver"); try (Connection connect = DriverManager.getConnection(...); Statement statement = connect.createStatement()) { // execute the statement here } catch (SQLException ex) { ex.printStackTrace(); } } catch (ClassNotFoundException ex) { e.printStackTrace(); }});
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25894509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4043524/']}
|
jdg_377210
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25810625
|
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 developing a swift application that at some point I have a code similar to this: import UIKitclass ViewController: UIViewController { private var a: UIImageView! private var b: UIImageView! private var c: UILabel! private var d: UILabel! private var e: UILabel! private var f: UILabel! private var g: UIView! private var h: UIView! private var i: UIView! private var j: UIView! private var k: UIImageView! private var l: UIView! private var m: UIView! private var n: UIView! private var o: UIView! private var p: UIScrollView! private var q: UIView! override func viewDidLoad() { super.viewDidLoad() let viewBindingsDict = ["a" : a, "b" : b, "c" : c, "d" : d, "e" : e, "f" : f, "g" : g, "h" : h, "i" : i, "j" : j, "k" : k, "l" : l, "m" : m, "n" : n, "o" : o, "p" : p] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }} For some reason, when I add this code, xcode gets stuck and I can't do anything else. Opening the Activity Monitor, it displays sourcekitservice and swift using more than 100% CPU. I've created this sample project with the code above : https://dl.dropboxusercontent.com/u/1393279/aaaaaaa.zip I've already tried cleaning derived data, reinstalling Xcode, rebooting, waiting minutes, etc. It just doesn't work.
Now provide the response and nothing else.
|
Something similar happened to me a few times, and I solved it by splitting long statements into multiple lines . I tested your code in a playground, and I immediately noticed the SourceKitService process eating 100% of my CPU. In your code the longest statement I see is the dictionary initialization, so a first approach would be to make it mutable and initialize with a short number of items per line. Swift doesn't provide a += operator for dictionaries, so we first need one (kudos to @shucao ): func +=<K, V> (inout left: Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> { for (k, v) in right { left.updateValue(v, forKey: k) } return left} With that in your toolset, you can initialize the dictionary as follows: var viewBindingsDict = ["a" : a, "b" : b, "c" : c, "d" : d, "e" : e]viewBindingsDict += ["f" : f, "g" : g, "h" : h, "i" : i, "j" : j]viewBindingsDict += ["k" : k, "l" : l, "m" : m, "n" : n, "o" : o]viewBindingsDict += ["p" : p] choosing a max of 5 items per line. But in your code you declared the dictionary as immutable - swift doesn't provide any statement to initialize an immutable after its declaration - fortunately we can use a closure to achieve that: let viewBindingsDict = { () -> [String:UIView] in var bindings = ["a" : self.a, "b" : self.b, "c" : self.c, "d" : self.d, "e": self.e] bindings += ["f": self.f, "g" : self.g, "h" : self.h, "i" : self.i, "j" : self.j] bindings += ["k" : self.k, "l" : self.l, "m" : self.m, "n" : self.n, "o" : self.o] bindings += ["p": self.p] return bindings}()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25810625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3931494/']}
|
jdg_377211
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9898499
|
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 cannot seem to get Maven to bundle the ojdbc6.jar file into my project's war file. I have it working within the POM file when specifying a dependency directly for Hibernate tools. But it won't get bundled with the project's war file, and therefore my project won't run on Tomcat. I have tried every solution I can find out there on the net, including those specified for this question here: Find Oracle JDBC driver in Maven repository Most recently, I did the following: Download the jar file to my machine Run the following command to install the jar into my local repository: mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.3 -Dpackaging=jar -Dfile=ojdbc6.jar -DgeneratePom=true (I've tried all kinds of variants of that command, too.) Finally, I put the dependency into my pom file: <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version></dependency> I run a clean build, but it fails: mvn -U clean package[INFO] Scanning for projects...[INFO] [INFO] ------------------------------------------------------------------------[INFO] Building jazztwo 0.0.1[INFO] ------------------------------------------------------------------------Downloading: http://repo1.maven.org/maven2/com/oracle/ojdbc6/11.2.0.3/ojdbc6-11.2.0.3.jar[INFO] ------------------------------------------------------------------------[INFO] BUILD FAILURE[INFO] ------------------------------------------------------------------------[INFO] Total time: 0.700s[INFO] Finished at: Tue Mar 27 15:06:14 PDT 2012[INFO] Final Memory: 3M/81M[INFO] ------------------------------------------------------------------------[ERROR] Failed to execute goal on project jazztwo: Could not resolve dependencies for project edu.berkeley:jazztwo:war:0.0.1: Could not find artifact com.oracle:ojdbc6:jar:11.2.0.3 in central (http://repo1.maven.org/maven2) -> [Help 1] Why doesn't this work? I'm ready to throw expensive computer parts across the room. This has wasted so much time. (Thank you, Oracle. How much did we pay you again?) Is it because I'm on a Mac, perhaps?
Now provide the response and nothing else.
|
It is better to add new Maven repository (preferably using your own artifactory) to your project instead of installing it to your local repository. Maven syntax: <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version></dependency>... <repositories> <repository> <id>codelds</id> <url>https://code.lds.org/nexus/content/groups/main-repo</url> </repository> </repositories> Grails example: mavenRepo "https://code.lds.org/nexus/content/groups/main-repo"build 'com.oracle:ojdbc6:11.2.0.3'
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9898499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337819/']}
|
jdg_377212
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56183201
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two images and would like to make it obvious where the differences are. I want to add color to the two images such that a user can clearly spot all the differences within a second or two. For example, here are two images with a few differences: leftImage.jpg: rightImage.jpg: My current approach to make the differences obvious, is to create a mask (difference between the two images), color it red, and then add it to the images. The goal is to clearly mark all differences with a strong red color. Here is my current code: import cv2# load imagesimage1 = cv2.imread("leftImage.jpg")image2 = cv2.imread("rightImage.jpg")# compute differencedifference = cv2.subtract(image1, image2)# color the mask redConv_hsv_Gray = cv2.cvtColor(difference, cv2.COLOR_BGR2GRAY)ret, mask = cv2.threshold(Conv_hsv_Gray, 0, 255,cv2.THRESH_BINARY_INV |cv2.THRESH_OTSU)difference[mask != 255] = [0, 0, 255]# add the red mask to the images to make the differences obviousimage1[mask != 255] = [0, 0, 255]image2[mask != 255] = [0, 0, 255]# store imagescv2.imwrite('diffOverImage1.png', image1)cv2.imwrite('diffOverImage2.png', image1)cv2.imwrite('diff.png', difference) diff.png: diffOverImage1.png diffOverImage2.png Problem with the current code: The computed mask shows some differences but not all of them (see for example the tiny piece in the upper right corner, or the rope thingy on the blue packet). These differences are shown only very lightly in the computed mask, but they should be clearly red like the other differences. Input: 2 images with some differences. Expected Output: 3 images: the two input images but with the differences highlighted (clearly highlighted in a configurable color), and a third image containing only the differences (the mask).
Now provide the response and nothing else.
|
Method #1: Structural Similarity Index (SSIM) To visualize differences between two images, we can take a quantitative approach to determine the exact discrepancies between images using the Structural Similarity Index (SSIM) which was introduced in Image Quality Assessment: From Error Visibility to Structural Similarity . This method is already implemented in the scikit-image library for image processing. You can install scikit-image with pip install scikit-image . Using the skimage.metrics.structural_similarity function from scikit-image, it returns a score and a difference image, diff . The score represents the structural similarity index between the two input images and can fall between the range [-1,1] with values closer to one representing higher similarity. But since you're only interested in where the two images differ, the diff image is what we'll focus on. Specifically, the diff image contains the actual image differences with darker regions having more disparity. Larger areas of disparity are highlighted in black while smaller differences are in gray. All differences -> Significant region differences The gray noisy areas are probably due to .jpg lossy compression. We would obtain a cleaner result if we used a lossless compression image format. The SSIM score after comparing the two images show that they are very similar. Image Similarity: 91.9887% Now we filter through the diff image since we only want to find the large differences between the images. We iterate through each contour, filter using a minimum threshold area to remove the gray noise, and highlight the differences with a bounding box. Here's the result. To visualize the exact differences, we fill the contours onto a mask and on the original image. from skimage.metrics import structural_similarityimport cv2import numpy as np# Load imagesbefore = cv2.imread('left.jpg')after = cv2.imread('right.jpg')# Convert images to grayscalebefore_gray = cv2.cvtColor(before, cv2.COLOR_BGR2GRAY)after_gray = cv2.cvtColor(after, cv2.COLOR_BGR2GRAY)# Compute SSIM between the two images(score, diff) = structural_similarity(before_gray, after_gray, full=True)print("Image Similarity: {:.4f}%".format(score * 100))# The diff image contains the actual image differences between the two images# and is represented as a floating point data type in the range [0,1] # so we must convert the array to 8-bit unsigned integers in the range# [0,255] before we can use it with OpenCVdiff = (diff * 255).astype("uint8")diff_box = cv2.merge([diff, diff, diff])# Threshold the difference image, followed by finding contours to# obtain the regions of the two input images that differthresh = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)contours = contours[0] if len(contours) == 2 else contours[1]mask = np.zeros(before.shape, dtype='uint8')filled_after = after.copy()for c in contours: area = cv2.contourArea(c) if area > 40: x,y,w,h = cv2.boundingRect(c) cv2.rectangle(before, (x, y), (x + w, y + h), (36,255,12), 2) cv2.rectangle(after, (x, y), (x + w, y + h), (36,255,12), 2) cv2.rectangle(diff_box, (x, y), (x + w, y + h), (36,255,12), 2) cv2.drawContours(mask, [c], 0, (255,255,255), -1) cv2.drawContours(filled_after, [c], 0, (0,255,0), -1)cv2.imshow('before', before)cv2.imshow('after', after)cv2.imshow('diff', diff)cv2.imshow('diff_box', diff_box)cv2.imshow('mask', mask)cv2.imshow('filled after', filled_after)cv2.waitKey() Limitations: Although this method works very well, there are some important limitations. The two input images must have the same size/dimensions and also suffers from a few problems including scaling, translations, rotations, and distortions. SSIM also does not perform very well on blurry or noisy images. For images that do not have the same dimensions, we must switch from identifying pixel-similarity to object-similarity using deep-learning feature models instead of comparing individual pixel values. See checking images for similarity with OpenCV using Dense Vector Representations for scale-invariant and transformation indifferent images. Note: scikit-image version used is 0.18.1 . Method #2: cv2.absdiff For completeness, OpenCV provides a very simple built-in method using cv2.absdiff but the results are not as good as SSIM and also does not calculate a similarity score between the two images. This method only generates a difference image. The results are very washed and still suffers from the same limitations. Although this method is much simpler, the recommendation is to use SSIM. import cv2# Load images as grayscaleimage1 = cv2.imread("left.jpg", 0)image2 = cv2.imread("right.jpg", 0)# Calculate the per-element absolute difference between # two arrays or between an array and a scalardiff = 255 - cv2.absdiff(image1, image2)cv2.imshow('diff', diff)cv2.waitKey()
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56183201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5698626/']}
|
jdg_377213
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1524
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Paul makes reference to a physician named Luke: Luke the beloved physician greets you, as does Demas.—Colossians 4:14 ( ESV ) Tradition also assigns Luke as author of the gospel that bears its name and the history of the early church: the Acts of the Apostles. Many commentators have assumed this is one and the same man known to Paul, which influences their understanding of those texts. What are the limits of interpretation of Luke/Acts, specifically with regards to the reference to a Luke in Colossians 4:14?
Now provide the response and nothing else.
|
Was the Luke of Colossians the author of Luke/Acts? Probably. As the two volumes do not themselves include the author's name, we can't be sure that the author was named Luke at all. However, Luke is only mentioned 3 times in Paul's letters and there is no indication there that he was a particularly prominent personage. Therefore, any external evidence for Luke as author is somewhat stronger than it would be if Luke were already recognized as an authority in the church. According to Wikipedia , "Irenaeus, Tertullian, Clement of Alexandria, Origen, and the Muratorian Canon all regarded Luke as the author of the Luke-Acts" Also, P 75 clearly labels the end of the Gospel with Λουκᾶς: One reason Luke might have been assigned authorship, however, is Paul's reference to him as a physician, which implied a man of great learning. ( Galen , for instance, was known both as a medical doctor and as a philosopher. Intellectual typecasting was less common in those days.) Since both Luke and Acts are masterfully written histories in the classic style, it might have been tempting to make that connection. However, it does seem unlikely that no other names would have been mentioned if the authorship were simply an educated guess. (Compare with the suggestions for who wrote Hebrew to see the significance.) One intriguing hint that the Luke of Colossians 4:14 is the author of Luke is the word choice in the "eye of the needle" saying. Rather than ῥαφίς , which refers to a sewing needle , Luke uses βελόνη , which apparently refers to a surgical needle . A medical doctor of the time would have had a wide variety of tools for dealing with injuries and may very well have imagined preparing to close a wound rather than preparing to fix a garment when he heard the saying. Does it matter to interpretation that Luke was a doctor? This is a far thornier question. When it comes to understanding Luke 22:36-38 , I tend to agree with you: there's very little reason to bring up Luke's profession at all. But in the broad sense, I think it does matter. In fact, I think knowing something about the author matters a great deal when it comes to interpreting any text. Knowing who an author is can aid in understanding what he wrote and why . While we should not be slave to authorial intent (especially when we can only speculate about it), we should be guided by it (especially when recorded in the work itself). Thankfully, we know what the author of Luke/Acts was trying to accomplish: Inasmuch as many have undertaken to compile a narrative...it seemed good to me also...to write an orderly account for you...that you may have certainty concerning the things you have been taught.—elision of Luke 1:1-4 ( ESV ) In other words, Luke was acting primarily as a historian (commissioned by Theophilus) in his writing. We must always evaluate his work in those terms first. In broad terms, the care and attention to detail required of a doctor would have served Luke well as a historian. This is born out in Luke's meticulous usage of official titles . When we compare his output to Mark (who seems to mis-remember minor details ) or Josephus (who displays considerable bias ), we find Luke a man of even temperament and thoughtful care. These are evident even if we did not know or suspect that the author was a doctor, but knowing that detail fills in another piece of the puzzle.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/1524', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/367/']}
|
jdg_377214
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9741620
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I disable CKEditor to get me every time , when i don't want them? I'm using CKEditor with jQuery adapter. I don't want to have any tags.
Now provide the response and nothing else.
|
After some research I might shed some light on this issue - unfortunately there is no out-of-the-box solution. In the CKEditor there are four ways a no-break space can occur (anybody know more?): Automatic filling of empty blocks . This can be disabled in the config: config.fillEmptyBlocks = false; Automatic insertion when pressing TAB-key . This can be disabled in the config: config.tabSpaces = 0; Converting double spaces to SPACE+NBSP. This is a browser behavior and will thus not be fixed by the CKEditor team . It could be fixed serverside or by a clientside javascript onunload. Maybe this php is a start: preg_replace('/\s \s/ig', ' ', $text); By copy & paste. If you paste a UTF-8 no-break space or double-spaces CKEditor will convert it automatically. The only solution I see here is doing a regex as above. config.forcePasteAsPlainText = true; doesn't help. Summary: To get rid of all no-break spaces you need to write an additional function that cleans user input. Comments and further suggestions are greatly appreciated! (I'm using ckeditor 3.6.4)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9741620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/969724/']}
|
jdg_377215
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52090161
|
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 get data of a mat-select specifically the text and its value. This is how I implemented the mat-select so far.. <mat-select placeholder="Transaction Type" (selectionChange)="selected($event)" formControlName="TransactionTypeID"> <mat-option *ngFor="let t of transactionTypes" [value]="t.TransactionTypeID"> {{ t.TransactionType }} </mat-option></mat-select> This is how I get the value in the .ts file: this.formDetail.get('TransactionTypeID').value, This is my attempt to get the text or 't.TransactionType': selected(event: MatSelectChange) { console.log(event);} Can you please show me how to do this? Thank you.
Now provide the response and nothing else.
|
Update : 2020 (Updated answer as per the new version of angular material) The below old answer worked for the OP at the time question was asked. But I observed comments on the old answer and output event, change of mat-select has been deprecated in the new version of angular material. So, the correct answer is Working Stackblitz HTML: <mat-form-field> <mat-select (selectionChange)="selectedValue($event)"> <mat-option [value]="'GB'">Great Britain</mat-option> <mat-option [value]="'US'">United States</mat-option> <mat-option [value]="'CA'">Canada</mat-option> </mat-select></mat-form-field> selectionChange will give us an object contains 2 properties value & source value will hold selected option value and To get the selected option text, you can simply call triggerValue on source like below TS: selectedValue(event: MatSelectChange) { this.selectedData = { value: event.value, text: event.source.triggerValue }; console.log(this.selectedData);} Old Answer With normal change event, you can get the value like below In the .html file <mat-select placeholder="Transaction Type" (change)="selected($event)" formControlName="TransactionTypeID"> <mat-option *ngFor="let t of transactionTypes" [value]="t.TransactionTypeID"> {{t.TransactionType}} </mat-option></mat-select> In the .ts file selected(event) { let target = event.source.selected._element.nativeElement; let selectedData = { value: event.value, text: target.innerText.trim() }; console.log(selectedData);}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52090161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3825246/']}
|
jdg_377216
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
521101
|
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 understand what the Java java.security.Signature class does. If I compute an SHA1 message digest, and then encrypt that digest using RSA, I get a different result to asking the Signature class to sign the same thing: // Generate new keyKeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();PrivateKey privateKey = keyPair.getPrivate();String plaintext = "This is the message being signed";// Compute signatureSignature instance = Signature.getInstance("SHA1withRSA");instance.initSign(privateKey);instance.update((plaintext).getBytes());byte[] signature = instance.sign();// Compute digestMessageDigest sha1 = MessageDigest.getInstance("SHA1");byte[] digest = sha1.digest((plaintext).getBytes());// Encrypt digestCipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, privateKey);byte[] cipherText = cipher.doFinal(digest);// Display resultsSystem.out.println("Input data: " + plaintext);System.out.println("Digest: " + bytes2String(digest));System.out.println("Cipher text: " + bytes2String(cipherText));System.out.println("Signature: " + bytes2String(signature)); Results in (for example): Input data: This is the message being signed Digest: 62b0a9ef15461c82766fb5bdaae9edbe4ac2e067 Cipher text: 057dc0d2f7f54acc95d3cf5cba9f944619394711003bdd12... Signature: 7177c74bbbb871cc0af92e30d2808ebae146f25d3fd8ba1622... I must have a fundamental misunderstanding of what Signature is doing - I've traced through it, and it appears to be calling update on a MessageDigest object, with the algorithm set to SHA1 as I would expect, then getting the digest, then doing the encryption. What's making the results differ? EDIT: Leonidas made me check whether the signature scheme is supposed to do what I think it does. There are two types of signature defined in the RFC : RSASSA-PKCS1-v1_5 RSASSA-PSS The first of these (PKCS1) is the one I describe above. It uses a hash function to create a digest, and then encrypts the result with a private key. The second algorithm uses a random salt value, and is more secure but non-deterministic. The signature produced from the code above does not change if the same key is used repeatedly, so I don't think it can be PSS. EDIT: Here's the bytes2string method I was using: private static String bytes2String(byte[] bytes) { StringBuilder string = new StringBuilder(); for (byte b : bytes) { String hexString = Integer.toHexString(0x00FF & b); string.append(hexString.length() == 1 ? "0" + hexString : hexString); } return string.toString();}
Now provide the response and nothing else.
|
OK, I've worked out what's going on. Leonidas is right, it's not just the hash that gets encrypted (in the case of the Cipher class method), it's the ID of the hash algorithm concatenated with the digest: DigestInfo ::= SEQUENCE { digestAlgorithm AlgorithmIdentifier, digest OCTET STRING } Which is why the encryption by the Cipher and Signature are different.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/521101', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37416/']}
|
jdg_377217
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52848
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $f(z)=\sum_{n\geq 0}a_n z^n$ be a Taylor series with rational coefficients with infinitely non-zero $a_n$ which convergesin a small neighboorhood around $0$. Furthermore, assume that \begin{align*}f(z)=\frac{P(z)}{Q(z)},\end{align*}where $P(z)$ and $Q(z)$ are coprime monic complex polynomials . By developing $\frac{P(z)}{Q(z)}$ as a power sereis around $0$ and comparing it with $f(z)$ we obtain infinitely many polynomial equations in the roots of $P(z)$ and $Q(z)$ which are equal to rational numbers so this seems to force the roots of $P(z)$ and $Q(z)$ to be algebraic numbers. Q: How does one prove this rigourously?
Now provide the response and nothing else.
|
Let there be two fields $k\subset K$, and let $f\in k[[x]]$ be a formal power series with coefficients in $k$. If $f\in K(x)$ (rational functions with coefficients in $K$) then $f\in k(x)$. A proof of this is given in J.S. Milne's notes on Etale Cohomology (lemma 27.9).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/52848', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11765/']}
|
jdg_377218
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38811877
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a Spark DataFrame df , I want to find the maximum value in a certain numeric column 'values' , and obtain the row(s) where that value was reached. I can of course do this: # it doesn't matter if I use scala or python, # since I hope I get this done with DataFrame APIimport pyspark.sql.functions as Fmax_value = df.select(F.max('values')).collect()[0][0]df.filter(df.values == max_value).show() but this is inefficient since it requires two passes through df . pandas.Series / DataFrame and numpy.array have argmax / idxmax methods that do this efficiently (in one pass). So does standard python (built-in function max accepts a key parameter, so it can be used to find the index of the highest value). What is the right approach in Spark? Note that I don't mind whether I get all the rows that where the maximum value is achieved, or just some arbitrary (non-empty!) subset of those rows.
Now provide the response and nothing else.
|
If schema is Orderable (schema contains only atomics / arrays of atomics / recursively orderable structs) you can use simple aggregations: Python : df.select(F.max( F.struct("values", *(x for x in df.columns if x != "values")))).first() Scala : df.select(max(struct( $"values" +: df.columns.collect {case x if x!= "values" => col(x)}: _*))).first Otherwise you can reduce over Dataset (Scala only) but it requires additional deserialization: type T = ???df.reduce((a, b) => if (a.getAs[T]("values") > b.getAs[T]("values")) a else b) You can also oredrBy and limit(1) / take(1) : Scala : df.orderBy(desc("values")).limit(1)// ordf.orderBy(desc("values")).take(1) Python : df.orderBy(F.desc('values')).limit(1)# ordf.orderBy(F.desc("values")).take(1)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38811877', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336527/']}
|
jdg_377219
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
87306
|
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:
Famously, the path integral of quantum field theory is related to the partition function of statistical mechanics via a Wick rotation and there is therefore a formal analogy between the two. I have a few questions about the relation between the two objects. Loop diagrams in quantum field theory have a nice interpretation in terms of virtual particles. What is the interpretation of loops in statistical mechanics? Does the relation between the two objects imply that for every quantum mechanical phenomenon there's a corresponding statistical mechanics phenomenon and vice versa? If not, where does the analogy fail? If so, what would be the phenomena analogous to the Aharonov-Bohm (AB) effect? It's hard for me to see the analog for any quantum effect that depends on phase interference like the AB effect.
Now provide the response and nothing else.
|
I think it will depend the kind of statistical mechanics. For classical statistical mechanics, there is no time, so it is really hard to imagine a nice physical picture of the propagation of something. But nevertheless we still talk of loops as propagating "particles" (we give the "momenta", for instance, which is conserved, etc.).Interestingly, renormalization (a la Wilson) is easier to understand on a physical ground in statistical physics, where the coarse graining has a very nice interpretation. On the other hand, in quantum statistical physics, the analogy is bit more direct, though time is still imaginary, so nothing really propagates. But in some sense, we still sum over all the possibilities (in a static sense, though). In this case, AB effect will give the quantization of the flux, or the Quantum Hall Effect. Anyway, concerning the first question, keep in mind that loops, Feynman diagrams and virtual particles are artifacts of pertubation theory, and therefore have no real physical interpretation.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/87306', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/26866/']}
|
jdg_377220
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44027492
|
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 maven release plugin with Jenkins for CICD. For various reasons, we don't do SNAPSHOTs as we are supposed. We set up Jenkins to run build against master branch with version like 0.1, 1.0. And we would like to up the version number of release every time we run Jenkins. These are the commands I had in Jenkinsfile: sh "mvn -B release:clean"sh "mvn -B release:prepare"sh "mvn -B release:perform" Ended up getting error You don't have a SNAPSHOT project in the reactor projects list . No surprise there since release:prepare always looks for a SNAPSHOT branch. Is there a way to get around it? I found this option -DignoreSnapshots for prepare but it did not work.
Now provide the response and nothing else.
|
The release plugin is intended to have a 1.0-SNAPSHOT before running release plugin mvn -B release:prepare where it will change the version to a release version 1.0 and afterwards it will change them to 1.1-SNAPSHOT (so called next dev version). During release:perform the tagged state of your build 1.0 will be checked out from version control and will be executing mvn clean deploy . Furthermore using the release plugin can be done via: mvn -B release:prepare release:perform And in cases where something is going wrong you can do mvn release:clean (but you need to remove tags if have been created manually). If you will have only releases that will not work...Apart from that SNAPSHOT is not a branch it is a version thing... You can accomplish what you like via build-helper-maven-plugin and versions-maven-plugin : mvn build-helper:parse-version versions:set \ -DnewVersion=\${parsedVersion.majorVersion}.\ ${parsedVersion.minorVersion}. \ ${parsedVersion.nextIncrementalVersion} \ versions:commit After that you should commit this changes into version control (best be done via Pipelines in Jenkins). Furthermore via scm-maven-plugin : mvn scm-maven-plugin:commit
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44027492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3358927/']}
|
jdg_377221
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13997927
|
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 that you have a large collection of key/value pairs, where the value is some arbitrary real number. You're interested in creating a data structure supporting the following operations: Insert , which adds a new key/value pair to the collection, Delete , which removes a key/value pair from the collection, Percentile , which tells which percentile the value associated with a given key is in, and Tell-Percentile , which accepts a percentile number and returns the key whose value is the lowest value at at least the given percentile. This data structure could be used, for example, to efficiently determine what percentile a given student is in when receiving a stream of nationwide test scores, or to identify hospitals that have unusually good or bad quality of service. Is there a way to make these operations run efficiently (say, sublinear time?)
Now provide the response and nothing else.
|
One possible way to implement this data structure is to use a hybrid of an order statistic tree and a hash table . An order statistic tree is a type of balanced binary search tree that, in addition to the normal binary search tree operations, supports two more operations: Rank (key), which returns the number of elements in the tree smaller than a given element, and Select (k), which returns the kth smallest element in the tree. Order statistic trees can be built by augmenting a normal balanced binary search tree (say, a red/black tree or an AVL tree ) with extra information that is preserved during rotations. In this way, all of the normal BST operations on an order statistic tree can be made to run in O(log n) time, with the extra operations also running in O(log n) time. Now, let's suppose that you were purely storing values scores, rather than key/percentile scores. In this case, it would be very simple to implement the percentile lookups as follows. Store all of the values in the order statistic tree. To determine the percentile score for a given value, use the rank operation on the order statistic tree to look up what index that value appears at. This gives a number, in the range from 0 to n - 1 (where n is the number of elements in the tree), denoting the position of that score in the order statistic tree. You can then multiply that number by 99 / (n - 1), to get a percentile score for the value that runs in the range from 0 to 99, as required. To determine the lowest value greater than some percentile, you can use the select operation as follows. Given a percentile between 0 and 99, multiple that percentile by 99 / (n - 1) to get a real number between 0 and n - 1, inclusive. Taking the ceiling of that number produces a natural number in the range 0 to n - 1, inclusive. Using the select operation on the order statistic tree then can be used to find the first value in the range that is at or above the given percentile. However, these operations assume that we have purely values in the data structure, not key/value pairs. To make this operation work for key/value pairs, we will augment our data structure as follows: Rather than just storing values, we will store key/value pairs in each node. The order statistic tree will sort the key/value pairs purely by their value, with the key carried around as satellite data. We will store a secondary hash table that maps keys to their associated values. These two changes make it possible to implement the needed functionality for our data structure. To get the data structure to do percentile lookups by key, we first query the hash table with the given key to look up its associated value. We then do a percentile lookup on the value as done before. To get the data structure to tell us a key whose value is the first at or above a given percentile, we do a normal find-percentile operation on the order statistic tree as described above, then look up the key associated with the given value. If we assume that the hash table uses chained hashing, then the time required for each operation is given below: Insert : O(log n) time to insert the value/key pair into the order statistic tree, plus O(1) amortized time to insert the key/value pair into the hash table. Total time is O(log n) amortized. Delete : O(log n) time to delete the value/key pair from the order statistic tree, plus (1) amortized time to delete the key/value pair from the hash table. Total time is O(log n) amortized. Percentile : O(1) expected time to look up the value associated with the key, O(log n) time to do the rank operation, and O(1) extra time to map the rank to a percentile. Total time is O(log n) expected. Find-Percentile : O(1) time required to map the percentile to a rank, and O(log n) time required to do the select operation. Total time is O(log n) worst-case. Hope this helps!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13997927', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/501557/']}
|
jdg_377222
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22504131
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are manually updating the data in Database but it's not refelecting immediatley in UI.Please tell me how to get the updated data in entity framework ?I saw some of the forums, refresh method will reflect the updated changes in entity framework.is it right way or any suggestions let me know. Thanks
Now provide the response and nothing else.
|
As pointed out in the comment by Lambart to the other answer, the solution doesn't work for changing the target version for all the modules altogether. Also, observe that setting the target level for the project is fine, but this target version is overridden by the one specified in a module. If you, like me, are unlucky and need to work on a 100+ modules Java monolith, then changing modules one by one will be a pain. My solution is "annoying" but works under LINUX. I assume in the example that you want to update form 1.5 to 1.8 . Step 1) You have to go in the .idea folder and look for the file compiler.xml . Replace all the target values in the tag <module> , e.g. target="1.5" to target="1.8" Step 2) go in the project folder and run the following script find . -type f -name "*.iml" -print0 | xargs -0 sed -i "s/JDK_1_5/JDK_1_8/g" to replace all the language level in the modules to be JDK8 compliant.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22504131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3392135/']}
|
jdg_377223
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
668231
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose we have a simple RL circuit. At $t=0$ , I close the switch so that current starts flowing in the circuit. When the steady state is achieved, current $i=\frac{\epsilon}{R}$ would be flowing in the circuit due to which an energy $\frac{Li^2}{2}$ will be stored in the magnetic field lines on inductor. But as soon as the switch is opened, the current would become $0$ , which make the magnetic field lines disappear suddenly, which according to Faraday's law must induce an emf. But as the circuit is open no current will flow in it (according to my teacher, charge can never accumulate in a circuit. So if current flows in open circuit, it would mean that charge is accumulating in it) . If there is no current how can the energy in magnetic field lines disappear suddenly? Isn't this a voilation of law of conservation of energy? Ps: I read the answer given in a similar question Where the energy stored in magnetic field goes? but I kinda disagree with the point that in superconducting coil, current will keep flowing because according to Prof. Walter Lewin, no electric field can exist inside a superconducting coil, so current cannot exist in the coil. Only surface currents must exist.
Now provide the response and nothing else.
|
This is a situation where the simple rules are insufficient. You simply cannot analyze that circuit any more than you can solve x+2=x+3.What happens in the real world is that the inductor creates enough emf to form a spark in the switch. This means the switch no longer acts like an ideal switch. In the real world, we call this effect "flyback.". It can damage components, so we typically design circuits to prevent this from occuring. For example, it is common to see a flyback resistor in parallel with the inductor on large motors. It gives the current somewhere to go.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/668231', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/303758/']}
|
jdg_377224
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10748212
|
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 simple way to call a function every 60 minutes. How can I do this? I'm making a MineCraft bukkit plugin, and this is what I have: package com.webs.playsoulcraft.plazmotech.java.MineRegen;import java.util.logging.Logger;import org.bukkit.Location;import org.bukkit.block.Block;import org.bukkit.event.block.Action;import org.bukkit.event.player.PlayerInteractEvent;import org.bukkit.plugin.java.JavaPlugin;public class Main extends JavaPlugin{ public final Logger log = Logger.getLogger("Minecraft"); @Override public void onEnable() { this.log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); this.log.info("Plaz's Mine Regen is now enabled!"); this.log.info("Copyright 2012 Plazmotech Co. All rights reserved."); this.log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } @Override public void onDisable() { this.log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); this.log.info("Plaz's Mine Regen is now disabled!"); this.log.info("Copyright 2012 Plazmotech Co. All rights reserved."); this.log.info("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); } public void onPlayerInteract(PlayerInteractEvent event) { final Action action = event.getAction(); if (action == Action.LEFT_CLICK_BLOCK) { Location l1 = event.getClickedBlock().getLocation(); } else if (action == Action.RIGHT_CLICK_BLOCK) { Location l2 = event.getClickedBlock().getLocation(); } }} I need to run a function I will implement every hour, how? Remember: The function will use l1, and l2. Also, how can I loop this to get every block inbetween?
Now provide the response and nothing else.
|
Create a Timer object and give it a TimerTask that performs the code you'd like to perform. Timer timer = new Timer ();TimerTask hourlyTask = new TimerTask () { @Override public void run () { // your code here... }};// schedule the task to run starting now and then every hour...timer.schedule (hourlyTask, 0l, 1000*60*60); If you declare hourlyTask within your onPlayerInteract function, then you can access l1 and l2 . To make that compile, you will need to mark both of them as final . The advantage of using a Timer object is that it can handle multiple TimerTask objects, each with their own timing, delay, etc. You can also start and stop the timers as long as you hold on to the Timer object by declaring it as a class variable or something. I don't know how to get every block in between.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10748212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1239203/']}
|
jdg_377225
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25467750
|
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 update my Document but it's not working 100% . // Initialize connection onceMongoClient.connect("mongodb://localhost:27017/testDB", function(err, database) { //"mongodb://localhost:27017/test" if(err) throw err; db = database;}); My collection row looks like: { "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "name:paco", "status:student" } Now if I want to update the row over the Document as follows: db.collection('user', function(err, collection){ collection.update({'_id':ObjectID(req.session.loggedIn)}, {image : filename}, {w:1}, function(err, result){ console.log(result); I am getting just: { "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "image:filename" } How can I make an update to get my data like this??: { "_id" : ObjectId("53f9379ce9575bbe9ec29581"), "name:paco", "status:student" , "image:filename"}
Now provide the response and nothing else.
|
Doing an update the way you did it is going to retrieve the document in your collection with the specified _id , then it is going to replace the content of this document with what you specified as your second parameter. In your case, it will retrieve the document with _id 53f9379ce9575bbe9ec29581 , and replace the existing fields with the field you passed, image:filename (that means the existing fields will be removed, as you noticed). What you want to do is use the $set operator. This operator will not touch the document retrieved, but only modify the field that you specified, or add it if it does not exist. So your update command should look something like this: db.collection('user').update({'_id':ObjectID(req.session.loggedIn)}, {$set: {image : filename}}, {w:1}, function(err, result){ console.log(result);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25467750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3954586/']}
|
jdg_377226
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7132503
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
SA,What I know is that Objective-C is a strict superset of C.. But when I've tried a very simple enum example that I used to use in C, it didn't work in objective C, Here's the code: #import <Foundation/Foundation.h>int main(void){ typedef enum { SUN, MON, TUES }DAYS; DAYS d = MON; NSLog(@"%@", d); return 0;} #include <stdio.h>int main(void){ typedef enum { SUN, MON, TUES }DAYS; DAYS d = MON; printf("%d\n", d); return 0;} In C, it works perfectly, but in objective-c (I am using GNUstep on WIN) it crashes when executing (no compile-time errors) Can anyone tell me why?
Now provide the response and nothing else.
|
%@ is an object specifier and enums are an int (signed or unsigned). To print an enum in Objective-C you need to use %d in your NSLog . NSLog(@"%d", d); Your original example was crashing because it expected d to be an object so it would try and send the description message to an object residing at memory address 1 (the value of MON ).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7132503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/171950/']}
|
jdg_377227
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28132869
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
s->duplicate() returns an object of type Box* , but I'm getting an error initializing it with Box* . It looks like it's being converted back to Shape* . What is the point of having covariant return types if it's converted back to the base class pointer?: struct Shape{ virtual Shape* duplicate() { return new Shape; }};struct Box : Shape{ virtual Box* duplicate() { return new Box; }};int main(){ Shape* s = new Box; Box* b = s->duplicate();} Error: main.cpp:22:12: error: cannot initialize a variable of type 'Box *' with an rvalue of type 'Shape *' Box* b = s->duplicate(); ^ ~~~~~~~~~~~~~~1 error generated.
Now provide the response and nothing else.
|
Although Box::duplicate is being invoked at runtime (via virtual dispatch), and although Box::duplicate does override Shape::duplicate (covariantly), and although Box::duplicate does return a Box* , you'll still get a Shape* pointer because you are calling duplicate() through a Shape* pointer, and Shape* is the return type of Shape::duplicate() , and the compiler only sees you calling Shape::duplicate , not Box::duplicate . C++ is not able to dynamically select types, so this is the best it can do. Your Box* is being automatically converted to a Shape* on the way out of Box::duplicate . As Barry said, "it still has to compile at compile time, and at compile time all we know is that it returns a Shape* ". Then, to make it into a Box* again, you need to explicitly cast it (using static_cast or dynamic_cast ) because no implicit down-conversion exists. [C++11: 10.3/7]: The return type of an overriding function shall be either identical to the return type of the overridden function or covariant with the classes of the functions . [..] [C++11: 10.3/8]: If the return type of D::f differs from the return type of B::f , the class type in the return type of D::f shall be complete at the point of declaration of D::f or shall be the class type D . When the overriding function is called as the final overrider of the overridden function, its result is converted to the type returned by the (statically chosen) overridden function (5.2.2). [..] In the standard text, a pertinent example follows.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28132869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1594090/']}
|
jdg_377228
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2300089
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $A$ be a $2 \times 2$ real matrix such that $\det(A + A^T)=8, \det(A + 2A^T)=27$. Find $\det(A)$ I cannot solve this other than making a tedious calculus so a faster solution is appreciated.
Now provide the response and nothing else.
|
Consider the polynomial: $$P(x)=\det(A+xA^{T})$$ Since $A$ is a $2\times 2$ matrix, then the degree of $P$ is 2, and you have that: $$P(1)=8,P(2)=27$$ Our task, reduces to finding $P(0)=\det(A)$ which is the constant term, but the dominant term is $\det{(A^T)}=\det(A)$, so the constant term and the dominating one are equal, hence: $$P(x)=a(x^2+1)+bx$$ We have two equations and two unknowns, hence we deduce that: $$a=11,b=-14$$ And $\det(A)=a=11$ EDIT: Here, I show that the dominating term is $\det(A^T)$ for a $n\times n$ matrix $A$, we write $A=(a_{ij})$, then recall by the initial definition of the determinant: $$\det(A+xA^T)=\sum_{\sigma}\epsilon{(\sigma)}\prod_{i}(a_{\sigma(i),i}+xa_{i,\sigma(i)})$$ Expanding the product, we observe that the coefficient associated with $x^n$ is: $$\sum_{\sigma}\epsilon{(\sigma)}\prod_{i}a_{i,\sigma(i)}=\det(A^T)$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2300089', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_377229
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
59031198
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am getting the Object ChatRoomEntity with entitymanager.findOne method. The ChatRoomEntity has the variable messages which is a OneToMany - ManyToOne Relation. I have no problems to select that but how do I get the user which sent the message. Its a variable on MessageEntity with a OneToMany Relation. So basically I want to select a room and all messages of it. But all messages should also have their values on fromUser .I select the room like this: this.entityManager.findOne(ChatRoomEntity, {where: {id: roomToJoin.id}, relations: ['activeUsers', 'messages']}).then(roomEntity => {// some code} Here my entities: UserEntity @Entity()export class UserEntity { @PrimaryGeneratedColumn() id: number; @CreateDateColumn() registrationDate: Date; @ManyToMany(type => ChatRoomEntity, room => room.activeUsers, {cascade: true}) @JoinTable() activeChatRooms: ChatRoomEntity[]; @OneToMany(type => ChatRoomMessageEntity, msg => msg.fromUser) chatRoomMessages: ChatRoomMessageEntity[];} ChatRoomEntity @Entity()export class ChatRoomEntity { @PrimaryGeneratedColumn() id: number; @Column('varchar', {nullable: true}) title: string; @OneToMany(type => ChatRoomMessageEntity, chatrmsg => chatrmsg.chatRoom) messages: ChatRoomMessageEntity[]; @ManyToMany(type => UserEntity, user => user.activeChatRooms) activeUsers: UserEntity[];} ChatRoomMessageEntity @Entity()export class ChatRoomMessageEntity { @PrimaryGeneratedColumn() id: number; @Column('varchar', {nullable: true}) message: string; @CreateDateColumn() creationDate: Date; @ManyToOne(type => UserEntity, user => user.chatRoomMessages) fromUser: UserEntity; @ManyToOne(type => ChatRoomEntity, chatRoom => chatRoom.messages) chatRoom: ChatRoomEntity;}
Now provide the response and nothing else.
|
We can load sub-relations by using 'relation.subrelation' within the relations array itself like this: relations: ['relation1', 'relation2', 'relation2.subrelation1'] So for your case, instead of using join you can simply do something like this: this.entityManager.findOne(ChatRoomEntity, { where: {id: roomToJoin.id}, relations: ['activeUsers', 'messages', 'messages.fromUser'], }).then(roomEntity => {... This is specified here: https://github.com/typeorm/typeorm/blob/master/docs/find-options.md#basic-options
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/59031198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8524732/']}
|
jdg_377230
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21085105
|
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 MediaStore.Images.Media.DATA uri for an image how I can get MediaStore.Images.ImageColumns.ORIENTATION using that uri ? I am getting a NullPointerException. Following is my code, private int getOrientation(Context context, Uri photoUri) {Log.v("orientatioon", "not crashed01");Cursor cursor = context.getContentResolver().query(photoUri, new String[] { MediaStore.Images.ImageColumns._ID,MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);Log.v("orientatioon", "not crashed02");cursor.moveToFirst();Log.v("orientatioon", "not crashed 03");int i=cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION));Log.v("orientatioon", ""+i);cursor.close();return i;} I am getting a NullPointerException at cursor.moveToFirst() line of code.
Now provide the response and nothing else.
|
Actually both answers are right and they must be used simultaneously. /** * @return 0, 90, 180 or 270. 0 could be returned if there is no data about rotation */public static int getImageRotation(Context context, Uri imageUri) { try { ExifInterface exif = new ExifInterface(imageUri.getPath()); int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); if (rotation == ExifInterface.ORIENTATION_UNDEFINED) return getRotationFromMediaStore(context, imageUri); else return exifToDegrees(rotation); } catch (IOException e) { return 0; }}public static int getRotationFromMediaStore(Context context, Uri imageUri) { String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION}; Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null); if (cursor == null) return 0; cursor.moveToFirst(); int orientationColumnIndex = cursor.getColumnIndex(columns[1]); return cursor.getInt(orientationColumnIndex);}private static int exifToDegrees(int exifOrientation) { if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { return 90; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) { return 180; } else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { return 270; } else { return 0; }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21085105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2235888/']}
|
jdg_377231
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
325499
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If we pick randomly two points inside a circle centred at $O$ with radius $R$, and draw two circles centred at the two points with radius equal to the distance between them, what is the expected area of the intersection of the two cirlces that contain the origin $O$.
Now provide the response and nothing else.
|
Let $\vec{x}_1$ and $\vec{x}_2$ be the two points. Let $r = |\vec{x}_1 - \vec{x}_2|$ be the distance between them. By elementary geometry, if you draw two circle of radius $r$ using these two points as center, the area of their intersection is given by $(\frac{2\pi}{3} - \frac{\sqrt{3}}{2})r^2$. Notice the picking of two points are independent, we have:$$E\left[ \vec{x}_1 \cdot \vec{x}_2 \right] = E\left[\vec{x}_1\right] \cdot E\left[\vec{x}_2\right] = \vec{0} \cdot \vec{0} = 0$$This implies$$E\left[|\vec{x}_1 - \vec{x}_2|^2\right] = E\left[|\vec{x}_1|^2 + |\vec{x}_2|^2\right] = 2\frac{\int_0^R r^3 dr}{\int_0^R rdr} = R^2$$ As a result, the expected area of the intersection is $(\frac{2\pi}{3} - \frac{\sqrt{3}}{2})R^2$. Update for those who are curious Let $\mathscr{C}$ be the set of events such that the intersection contains the origin, then:$$\begin{align}\operatorname{Prob}\left[\,\mathscr{C} \right] &= \frac{2\pi + 3\sqrt{3}}{6\pi}\\E\left[\,|\vec{x}_1 - \vec{x}_2|^2 : \mathscr{C}\right] &= \frac{20\pi + 21\sqrt{3}}{6(2\pi + 3\sqrt{3})}\end{align}$$and the expected area of intersection conditional to containing the center is given by:$$\frac{(4\pi - 3\sqrt{3})(20\pi + 21\sqrt{3})}{36(2\pi + 3\sqrt{3})}$$ To evaluate $E\left[ \varphi(\vec{x}_1,\vec{x}_2) ) : \mathscr{C} \right]$ for any function $\varphi( \vec{x}_1, \vec{x}_2 )$ which is symmetric and rotational invariant w.r.t its argument, you need to compute an integral of the from: $$\int_{\frac{\pi}{3}}^{\pi} \frac{d\theta}{\pi} \left[2\int_{0}^{R} \frac{2udu}{R^2} \left( \int_{\alpha(\theta)u}^{u} \frac{2vdv}{R^2} \phi( \vec{x}_1, \vec{x}_2 ) \right) \right] $$ where $u \ge v$ are $|\vec{x}_1|$ and $|\vec{x}_2|$ sorted in descending order.$\theta$ is the angle between $\vec{x}_1$ and $\vec{x}_2$. The mysterious $\alpha(\theta)$ is $\max(2\cos(\theta),0)$ for $\theta \in [\frac{\pi}{3},\pi]$. The integral is a big mess and I need a computer algebra system to crank that out.I won't provide more details on this part not relevant to the main answer.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/325499', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/65216/']}
|
jdg_377232
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
127998
|
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 asked to find all positive integers $n$ such that $\phi(n)=6$, and to prove that I have found all solutions. The way I am tackling this is by constructing all combinations of prime powers such that when passed to Euler's function will yield $6$. For example, I know that $\phi(7)=6$, $\phi(3^2)=6$, and $\phi(2)=1$. Therefore, the numbers should be $7$, $7\cdot2=14$, $3^2=9$, and $3^2\cdot2=18$. I believe that there cannot possibly be any others because of the way the $\phi$ function is defined. What do you guys think?
Now provide the response and nothing else.
|
We give an "examination of all cases" solution. Use the fact that $\varphi(n)$ is multiplicative . Let$$n=2^a p_1^{e_1}p_2^{e_2}\cdots p_k^{e_k},$$where the $p_i$ are distinct odd primes, the $e_i$ are $\ge 1$, and $a \ge 0$.Then $$\varphi(n)=\varphi(2^a)\varphi(p_1^{e_1})\varphi(p_2^{e_2})\cdots \varphi(p_k^{e_k}).$$ We find all $n$ such that $\varphi(n)=6$. If $k \ge 2$, then since $\varphi(p_i^{e_i})$ is even, $\varphi(n)$ is divisible by $4$, so cannot be equal to $6$. If $k=0$, then $\varphi(n)=\varphi(2^a)$. But $\varphi(2^a)=1$ if $a=0$ and $\varphi(2^a)=2^{a-1}$ if $a \ge 1$. So if $k=0$ we cannot have $\varphi(n)=6$.We conclude that $k=1$. Thus $n$ must have the shape $2^ap^e$, where $a \ge 0$ and $p$ is an odd prime. But $\varphi(p^e)=p^{e-1}(p-1)$. It follows that $p \le 7$. If $p=7$, then $p-1=6$, so we must have $e=1$ and $\varphi(2^a)=1$. This gives the solutions $n=7$ and $n=14$. We cannot have $p=5$, for $4$ divides $\varphi(5^e)$. Let $p=3$. If $e \ge 3$, then $\varphi(3^e)\ge (3^2)(2)$. So we are left with the possibilities $e=1$ and $e=2$. If $e=1$, then $\varphi(n)=\varphi(2^a)(2)$. This cannot be $6$. Finally, we deal with the case $e=2$. Note that $\varphi(3^2)=6$. So to have $\varphi(2^a3^2)=6$, we need $\varphi(2^a)=1$, which gives $n=9$ and $n=18$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/127998', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25134/']}
|
jdg_377233
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1361618
|
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 following code does not compile, saying " error C2248: 'A::getMe' : cannot access private member declared in class 'A'". Why? I am trying to call the public interface. class B{};class A{public: const B& getMe() const;private: B& getMe(); };int main(){A a;const B& b = a.getMe();return 0;}
Now provide the response and nothing else.
|
Part of the problem which wasn't mentioned in other answers is that accessibility and visibility are independent concepts in C++. The B& A::getMe() private member is visible in main even if it isn't accessible. So in your call a.getMe() there are two overloaded members to consider, B& A::getMe() and B const& A::getMe() const . As a is not const it is the private member which is selected. Then you get an error because it isn't accessible. If you hadn't the private non const member function, you would have the const member as the only possibility and it would have be called as a const member can be called on non const object. Note that if visibility was conditioned to accessibility, you could have other kind of confusing behavior: you refactor a member, putting a call to a private member outside the class. Now, the private member is no more accessible and so the call is to a different member which is public. That silent change of behavior can lead to bugs hard to track. In conclusion: whatever are the rule of your language, never overload with different accessibility, it leads to confusion.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1361618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19501/']}
|
jdg_377234
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10364854
|
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 call app.run(debug=True) in my flask file. and I have it deployed with uWSGI and nginx (I followed these instructions ) uwsgi -s /tmp/uwsgi.sock -w flask_file_name:app -H /path/to/virtual/env --chmod-socket 666 But when I get an error, I don't get any debug information in the browser or in the uWSGI log. Any ideas? flask_file_name.py: from flask import Flask, make_response, Response, jsonifyimport jsonapp = Flask(__name__)app.debug = True@app.route("/")def hello(): return "Hello World!"if __name__ == '__main__': app.run()
Now provide the response and nothing else.
|
According to the Flask mailing list you cannot use Flask's debug option with uWSGI , because it's not to be used in a forking environment. You see 502 because flask/werkzeug do not send any data to the webserver, so nginx will returns a 502. You can emulate the debugger using --catch-exceptions option in uWSGI (but please do not do it in production) So, the reason you're seeing 502s will be because of that. The fix would be to add --catch-exceptions to uWSGI on execution.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10364854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221693/']}
|
jdg_377235
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46583052
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
my idea is to create a google sheet, make it public and then access it from my work computer linux/bash to read/write values on a daily basis. i have a public google doc sheet that anyone can find/edit.this is the sheet ID: 1F6jh6756xNDlDYIvZm_3TrXb59EFEFHGEC7jdWz-Nx0 doing it by the book https://developers.google.com/sheets/api/samples/reading curl 'https://sheets.googleapis.com/v4/spreadsheets/1F6jh6756xNDlDYIvZm_3TrXb59EFEFHGEC7jdWz-Nx0/values/Sheet1!A1:A3' returns: { "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" }} i've read a lot and especialy here Google Sheet API v4 i've found a complicated solution. that is if you want to access your public sheet in a short 1 hour period. you browse to https://developers.google.com/oauthplayground/ get authorization for the v4 api, then get "Authorization code", then get "Refresh token", and finally "Access token". using this "Access token" you can access the public sheet like this curl 'https://sheets.googleapis.com/v4/spreadsheets/1F6jh6756xNDlDYIvZm_3TrXb59EFEFHGEC7jdWz-Nx0/values/Sheet1!A1:A3' -H "Authorization: Bearer ya29.GlvaBLjrTdsSuSllr3u2nAiC-BOsjvIOE1x5afU3xiafB-FTOdLWDtfabuIMGF1rId5BsZxiTXxrx7VDEtxww4Q1uvW9zRndkfm3I2LZnT1HK2nTWzX_6oXu-NAG" returns: { "range": "Sheet1!A1:A3", "majorDimension": "ROWS", "values": [ [ "a1" ], [ "a2" ], [ "a3" ] ]} perfect. in theory the "Access token" expires after an hour, the "Refresh token" never expires. so you would save the tokens, try to read the sheet with the "Access token", if it fails use the "Refresh token" to gain a new "Access token" and carry on. but, i've had a dozen of "Refresh token"s that were redeemed/expired, "Authorization code"s expired, all in all nothing works after a few hours. why? how can i access my google sheet form bash with curl without this kind of authorization?especially since my sheet is public and can be edited by anyone with a browser. is there another way to do this with some other permanent authorization?why not use email and pass? "API key" is mentioned but never explained. can some one please explain this method step by step?
Now provide the response and nothing else.
|
All Google APIs require that you create a project on Google developer console and identify yourself and your application, even to access public data. Since you have set the sheet to public you can just go to google developer console and create a public api key remember to active the google sheets api. Then just add key=[YourKey] as a parameter on your request. Update Dev console: Create project and get key: Google developer console -> create a project -> credentials drop down -> API Key Enable it: Google developer console -> library find sheets enable it. Update : { "error": { "code": 403, "message": "The request is missing a valid API key.", "status": "PERMISSION_DENIED" } } Means that you have not identified yourself to Google. In 2015 Google Start to require that we identify ourselves you cant just use a Google API without telling google who you are. You do that by creating a project on [Google developer console 1 . Create an API key and use that API key in all of your requests. This only works with Public data. https://sheets.googleapis.com/v4/spreadsheets/1F6jh6756xNDlDYIvZm_3TrXb59EFEFHGEC7jdWz-Nx0/values/Sheet1!A1:A3?key=YOurKEY Note: With private user data you would need to use OAuth and use either access_token=your token or set the header Authorization: Bearer ya29.GlvaBLjrTdsSuSllr3u2nAiC-BOsjvIOE1x5afU3xiafB-FTOdLWDtfabuIMGF1rId5BsZxiTXxrx7VDEtxww4Q1uvW9zRndkfm3I2LZnT1HK2nTWzX_6oXu-NAG. An access token is not the same as a API Key.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46583052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_377236
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13008843
|
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 developing a wp7 application, can we capture a tap event from Applicationbar on wp7? I have tried the below 4 ways, but they all failed. Mouse event Manipulation event TouchPoint GetureService/GestureListener Any idea? Thanks!
Now provide the response and nothing else.
|
The updated example below works with ember.js RC1 -- 03/14/2013 First you need to add a pagination like mixin as one doesn't yet exist in the ember core var get = Ember.get, set = Ember.set;Ember.PaginationMixin = Ember.Mixin.create({ pages: function() { var availablePages = this.get('availablePages'), pages = [], page; for (i = 0; i < availablePages; i++) { page = i + 1; pages.push({ page_id: page.toString() }); } return pages; }.property('availablePages'), currentPage: function() { return parseInt(this.get('selectedPage'), 10) || 1; }.property('selectedPage'), nextPage: function() { var nextPage = this.get('currentPage') + 1; var availablePages = this.get('availablePages'); if (nextPage <= availablePages) { return Ember.Object.create({id: nextPage}); }else{ return Ember.Object.create({id: this.get('currentPage')}); } }.property('currentPage', 'availablePages'), prevPage: function() { var prevPage = this.get('currentPage') - 1; if (prevPage > 0) { return Ember.Object.create({id: prevPage}); }else{ return Ember.Object.create({id: this.get('currentPage')}); } }.property('currentPage'), availablePages: function() { return Math.ceil((this.get('content.length') / this.get('itemsPerPage')) || 1); }.property('content.length'), paginatedContent: function() { var selectedPage = this.get('selectedPage') || 1; var upperBound = (selectedPage * this.get('itemsPerPage')); var lowerBound = (selectedPage * this.get('itemsPerPage')) - this.get('itemsPerPage'); var models = this.get('content'); return models.slice(lowerBound, upperBound); }.property('selectedPage', 'content.@each')}); Next you need to use the mixin above in your ArrayController like so PersonApp.PersonController = Ember.ArrayController.extend(Ember.PaginationMixin, { itemsPerPage: 2}); Next you can add a simple helper view to display the page numbers as li tags PersonApp.PaginationView = Ember.View.extend({ templateName: 'pagination', tagName: 'li', page: function() { return Ember.Object.create({id: this.get('content.page_id')}); }.property()}); Your routes might look something like this (nested page under the parent) PersonApp.Router.map(function(match) { this.resource("person", { path: "/" }, function() { this.route("page", { path: "/page/:page_id" }); });});PersonApp.PersonPageRoute = Ember.Route.extend({ model: function(params) { return Ember.Object.create({id: params.page_id}); }, setupController: function(controller, model) { this.controllerFor('person').set('selectedPage', model.get('id')); }});PersonApp.PersonRoute = Ember.Route.extend({ model: function(params) { this.controllerFor('person').set('selectedPage', 1); return PersonApp.Person.find(); }}); And finally, you need to add some html to display it <script type="text/x-handlebars" data-template-name="application"> <div id="main"> {{ outlet }} </div></script><script type="text/x-handlebars" data-template-name="person"><table width="250px"> <thead><th>id</th><th>username</th></thead><tbody> {{#each person in controller.paginatedContent}} <tr> <td>{{person.id}}</td> <td>{{view Ember.TextField valueBinding="person.username"}}</td> </tr> {{/each}}</tbody></table><div name="prev">{{#linkTo 'person.page' prevPage target="controller"}}Prev{{/linkTo}}</div><ul class="pagination gui-text"> {{#each pages}} {{view PersonApp.PaginationView contentBinding="this"}} {{/each}}</ul><div name="next">{{#linkTo 'person.page' nextPage target="controller"}}Next{{/linkTo}}</div></script><script type="text/x-handlebars" data-template-name="pagination">{{#with view}}{{#linkTo 'person.page' page}} {{content.page_id}}{{/linkTo}} {{/with}}</script> Here is a full working project with this in action if you want to see it work https://github.com/toranb/ember-pagination-example
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13008843', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1287439/']}
|
jdg_377237
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2177866
|
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 $f:\mathbb{R} \rightarrow \mathbb{R}$ be a continuous function such that $f(x+y)=f(x)f(y), \ \forall x,y\in \mathbb{R}$. Prove: if $f \not \equiv 0$, then there exists constant $a$ such that $f(x)=a^x.$ I tried to deduce the result from this question and this question , but had hard time with it. Any help appreciated.
Now provide the response and nothing else.
|
First note that $f(0+0) = f(0)^2$, thus $f(0)$ is either $1$ or $0$. If it was $0$ then $f(x+0) = f(x)f(0) = 0$ and then $f\equiv 0$ which contradicts our hypothesis. It must be that $f(0) = 1$. Let $a = f(1)$. Then $f(2) = a^2$. $f(3) = f(1)f(2) = a^3$ and inductively, $f(n) = a^n$ for all positive integer $n$. Conversely, $f(1-1) = f(1)f(-1) = 1$, so $f(-1) = a^{-1}$ and now one can reason as before to conclude that $f(n) = a^n$ for any integer $n$. Now to compute $f(p/q)$ where $p$ and $q$ are integers and $q$ is positive, we have that $a^p = f(p) = f(\underbrace{p/q + \ldots + p/q}_{q\text{ times}}) = f(p/q)^q$, thus $f(p/q) = \sqrt[q]{f(p)} = a^{p/q}$. Now, we know that $f(x) = a^x$ for any rational number $x$. Since the set of rationals is dense in the set of reals, then by the continuity of $f$, it must be that $f(x) = a^x$ for any real number $x$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2177866', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/385242/']}
|
jdg_377238
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7065338
|
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 create a chat script, and check for check new replies. I need to a while Once every 4 seconds checking new message in file db.php Sample : function while_check_seen(){ $(".replay").delay(4000).load("../db_pms.php?action=check"); while_check_seen()} This while worked, but used a lot of CPU! Can anyone suggest a better way?
Now provide the response and nothing else.
|
It seems that JDK7 process intern in a different way as before. I tested it with build 1.7.0-b147 and got "both are equal", but when executing it (same bytecode) with 1,6.0_24 I do not get the message. It also depends where the String b2 =... line is located in the source code. The following code also does not output the message: class Test { public static void main(String... args) { String s1 = "Good"; s1 = s1 + "morning"; String s2 = "Goodmorning"; System.out.println(s1.intern()); //just changed here s1.intern() and the if condition runs true if(s1 == s2) { System.out.println("both are equal"); } //now it works. }} it seems like intern after not finding the String in its pool of strings, inserts the actual instance s1 into the pool. The JVM is using that pool when s2 is created, so it gets the same reference as s1 back. On the other side, if s2 is created first, that reference is stored into the pool. This can be a result of moving the interned Strings out from the permanent generation of the Java heap. Found here: Important RFEs Addressed in JDK 7 In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. Not sure if that is a bug and from which version... The JLS 3.10.5 states The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents. so the question is how pre-existing is interpreted, compile-time or execute-time: is "Goodmorning" pre-existing or not? I prefer the way it WAS implemented before 7...
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7065338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/878563/']}
|
jdg_377239
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15136943
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to validate my form so that is out of two blank fields, at least one field must be filled and two fields also can be filled; but can't leave any field blank. I'm using jquery-1.9.1-min.js and here is my html page. <form action="#" class="send_form" id="forgot_pass_form" method="POST"> <fieldset> <div class="send_row"> <label class="padding-top10">Email</label> <input type="text" class="send_email" id="email" name="email" /> <em>You need to type an email address</em> </div> <div class="send_row option">OR</div> <div class="send_row"> <label class="padding-top10">Username</label> <input type="text" class="send_username" id="uname" name="uname" /> </div> <div class="send_row send_submitforgotuser"> <input type="submit" value="Submit" /> </div> </fieldset> </form> Any suggestion how to do it.... ? sofar I have tried jQuery.validator.addMethod("require_from_group", function(value, element, options) { alert("xxx"); var valid = $(options[1], element.form).filter(function() { return $(this).val(); }).length >= options[0]; if(!$(element).data('reval')) { var fields = $(options[1], element.form); fields.data('reval', true).valid(); fields.data('reval', false); } return valid;}, jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields.")); Still not getting friutful output.
Now provide the response and nothing else.
|
You are attempting to use validator.addMethod which is part of the jQuery Validate plugin . You'll need to include this plugin in your code if you haven't already. Then use the require_from_group rule that's already part of the Validate plugin's additional-methods.js file . (Don't forget to include the additional-methods.js file too.) rules: { myfieldname: { require_from_group: [1, ".class"] }} First parameter is the number of items to be required. Second parameter is the class assigned to all elements in your grouping. I added a send class to your two input elements. Also use the groups option to consolidate the two messages into one. jQuery : $(document).ready(function () { $('#forgot_pass_form').validate({ // initialize the plugin groups: { // consolidate messages into one names: "uname email" }, rules: { uname: { require_from_group: [1, ".send"] }, email: { require_from_group: [1, ".send"] } } }); // for your custom message jQuery.extend(jQuery.validator.messages, { require_from_group: jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields.") });}); Working Demo: http://jsfiddle.net/sgmvY/1/ EDIT : As per Github, there is an open issue with the require_from_group method. Until it's fixed, the developer is recommending this solution below. Since you would manually add the revised method into your code, there is no need to include the additional-methods.js file. New Working Demo: http://jsfiddle.net/kE7DR/2/ $(document).ready(function () { jQuery.validator.addMethod("require_from_group", function (value, element, options) { var numberRequired = options[0]; var selector = options[1]; var fields = $(selector, element.form); var filled_fields = fields.filter(function () { // it's more clear to compare with empty string return $(this).val() != ""; }); var empty_fields = fields.not(filled_fields); // we will mark only first empty field as invalid if (filled_fields.length < numberRequired && empty_fields[0] == element) { return false; } return true; // {0} below is the 0th item in the options field }, jQuery.format("'Please enter either username/ email address to recover password'/Please fill out at least {0} of these fields.")); $('#forgot_pass_form').validate({ // initialize the plugin groups: { names: "uname email" }, rules: { uname: { require_from_group: [1, ".send"] }, email: { require_from_group: [1, ".send"] } } });});
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15136943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2119435/']}
|
jdg_377240
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.