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
59464935
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 my App I want to use stylistic alternate font for 'a' and not system font . Attaching screenshot which explains the different rendering of the font. How can I enable this behaviour for UILabel and UITextView so that it renders the correct One Storey 'a'? I did find a YouTube video link which explains exactly this but he is using a custom font and it is hardcoded. I want to use system font only but with this alternate character. I might be able to hardcode UILabel with the custom character , I am not sure because I want to use System font . I don't want to use custom Font . What about UITextView which is editable? How can we make it use alternate a as and when the user types? Now provide the response and nothing else.
This is a font feature called "Alternative Stylistic Sets" that you can configure with CoreText. Remember that not all fonts have this option, but the system fonts do. You need to figure out which alternative set you want, however. First, create the font you're interested in: import CoreTextimport UIKitlet baseFont = UIFont.systemFont(ofSize: 72) Then print out its features: print(CTFontCopyFeatures(baseFont)!) Find the section on Alternative Stylistic Sets, and specifically the set you want, "One storey a:" { CTFeatureTypeIdentifier = 35; CTFeatureTypeName = "Alternative Stylistic Sets"; CTFeatureTypeSelectors = ( { CTFeatureSelectorIdentifier = 2; CTFeatureSelectorName = "Straight-sided six and nine"; }, { CTFeatureSelectorIdentifier = 4; CTFeatureSelectorName = "Open four"; }, { CTFeatureSelectorIdentifier = 6; CTFeatureSelectorName = "Vertically centered colon"; }, { CTFeatureSelectorIdentifier = 10; CTFeatureSelectorName = "Vertically compact forms"; }, { CTFeatureSelectorIdentifier = 12; CTFeatureSelectorName = "High legibility"; }, { CTFeatureSelectorIdentifier = 14; CTFeatureSelectorName = "One storey a"; }, ... The important number is the selector (CTFeatureSelectorIdentifier), 14. With that you can create a new font descriptor and new font: let descriptor = CTFontDescriptorCreateCopyWithFeature( baseFont.fontDescriptor, kStylisticAlternativesType as CFNumber, 14 as CFNumber) Or you can do this directly in UIKit if it's more convenient: let settings: [UIFontDescriptor.FeatureKey: Int] = [ .featureIdentifier: kStylisticAlternativesType, .typeIdentifier: 14]let descriptor = baseFont.fontDescriptor.addingAttributes([.featureSettings: [settings]]) (Note the somewhat surprising fact that .featureIdentifier is "CTFeature Type Identifier" and .typeIdentifier is "CTFeature Selector Identifier".) And then you can create a new font (a zero size means to leave the size the same): let font = UIFont(descriptor: descriptor, size: 0) You can use that anywhere that accepts a UIFont.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59464935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8409258/']}
jdg_74541
stackexchange
llm_judgeable_groundtruth_similarity
40371360
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 my code, I was puzzled by Enum instances with the same value not comparing equal. I quickly realized that their id(...) were different. Later, much less quickly, I realized that the only change since it last worked was the import statement: using explicit module path rather than relative. Then I came up with this isolated example. $ lse/$ ls e__init__.py __pycache__/ m1.py m1.pyc m2.py$ python3 --versionPython 3.5.1$ cat e/m1.pyfrom enum import Enumclass E(Enum): x=0$ cat e/m2.pyfrom m1 import E as E1from e.m1 import E as E2print(id(E1), id(E1.x))print(id(E2), id(E2.x)) Let's run it: $ PYTHONPATH=~/test python3 e/m2.py41536520 4265609641537464 42656488 Obviously, equality (which is by identity for Enum ) does not hold. Anyone else out there find this troubling? Let me elaborate. Adding two more files: $ cat e/file1.pyfrom m1 import Eclass C(): def __init__(self): self.x = E.x One more. Note the difference in imports. $ cat e/file2.pyfrom e.m1 import Efrom file1 import Cc = C()print(c.x, E.x)print('Surprise! ->', c.x is E.x) Both are valid imports. Now run it. $ PYTHONPATH=~/test python3 e/file2.pyE.x E.xSurprise! -> False How can I avoid this trap? Is there a reason why I should not be troubled by this? Now provide the response and nothing else.
Later, much less quickly, I realized that the only change since it last worked was the import statement: using explicit module path rather than relative. Python 3 doesn't have implicit relative imports. Your "relative" import is actually another absolute import . You're importing two completely distinct modules, m1 and e.m1 , that happen to come from the same file. If you want to use a relative import in Python 3, you need to make it explicit: from .m1 import E# ^ explicit relative import If you run the program as python3 -m e.m2 you'll avoid the problems with the module search path that allowed both m1 and e.m1 to exist. You can also manually fix sys.path and set __package__ from e/m2.py .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40371360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/443854/']}
jdg_74542
stackexchange
llm_judgeable_groundtruth_similarity
34684527
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 the 5 min quickstart from angular.io website, which contain a file structure like this: angular2-quickstart app app.component.ts boot.ts index.html license.md package.json tsconfig.json the tsconfig.json is a code block like this : { "compilerOptions": { "target": "ES5", "module": "system", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false }, "exclude": [ "node_modules" ]} Also the package.json: { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "tsc": "tsc", "tsc:w": "tsc -w", "lite": "lite-server", "start": "concurrent \"npm run tsc:w\" \"npm run lite\" " }, "license": "ISC", "dependencies": { "angular2": "2.0.0-beta.0", "systemjs": "0.19.6", "es6-promise": "^3.0.2", "es6-shim": "^0.33.3", "reflect-metadata": "0.1.2", "rxjs": "5.0.0-beta.0", "zone.js": "0.5.10" }, "devDependencies": { "concurrently": "^1.0.0", "lite-server": "^1.3.1", "typescript": "^1.7.3" }} I change the sourceMap from true to false, so in the code editor, the map file is not generated again, but the js file still get generated. I want to work on only ts file and don't want to get a brunch of js and js.map file, what should I do to put all my ts files in my regular develop floder like app folder and all the js and js.map files into a folder called dist? A good example of this might be angular2-webpack-quickstart . But I didn't figure out how they do that? Any advice how to do that, of course not manually. Thanks, Now provide the response and nothing else.
Probably late but here is a two-step solution. Step 1 Change system.config.js by updating 'app' to 'dist/app' : var map = { 'app': 'app', // 'dist/app', . . .}; Now it will look like this: var map = { 'app': 'dist/app', // 'dist/app', . . .}; Step 2 Create the dist folder. Edit tsconfig.json and add: "outDir": "dist" The resulting tsconfig.json : { "compilerOptions": { . . . . "outDir": "dist" // Pay attention here }, "exclude": [ . . . ]} Run npm start and you should see all the compiled .js and .map.js files in the dist folder. Note : Go through other answers. They are quite useful and informative too.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/34684527', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2348978/']}
jdg_74543
stackexchange
llm_judgeable_groundtruth_similarity
12603397
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 calculate the width and the height of the selected/highlighted text using JavaScript. I am using the following code written by Tim Down, as the starting point, function getSelectionCoords() { var sel = document.selection, range; var x = 0, y = 0; if (sel) { if (sel.type != "Control") { range = sel.createRange(); range.collapse(true); x = range.boundingLeft; y = range.boundingTop; } } else if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { range = sel.getRangeAt(0).cloneRange(); if (range.getClientRects) { range.collapse(true); var rect = range.getClientRects()[0]; x = rect.left; y = rect.top; } } } return { x: x, y: y };} The left & the top co-ordinates are being displayed correctly. To calculate the width & the height, I need the right & the bottom positions as well. So I added few lines of code to find the bottom & the right positions (Code available here - http://jsfiddle.net/pankajparashar/kv2Bp/ ). But to my surprise, the code displays the left & the right co-ordinates always the same, even though there is visible difference between them (tested only in firefox). There is no problem with the top & the bottom positions, as they are working perfectly, which will help me calculate the height. But to calculate the width, I would still need the correct right co-ordinate. Can anybody point any flaws with the code? or any alternate approach, using which I can calculate the width & the height of the selected text? Now provide the response and nothing else.
Here's some code to get the dimensions of the selection's bounding rectangle. It's pretty similar to the original code. Demo: http://jsfiddle.net/UFkjy/ function getSelectionDimensions() { var sel = document.selection, range; var width = 0, height = 0; if (sel) { if (sel.type != "Control") { range = sel.createRange(); width = range.boundingWidth; height = range.boundingHeight; } } else if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { range = sel.getRangeAt(0).cloneRange(); if (range.getBoundingClientRect) { var rect = range.getBoundingClientRect(); width = rect.right - rect.left; height = rect.bottom - rect.top; } } } return { width: width , height: height };}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12603397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/903446/']}
jdg_74544
stackexchange
llm_judgeable_groundtruth_similarity
44989808
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using this code from a previously asked question a few years ago , however, I believe this is outdated. Trying to run the code, I receive the error above. I'm still a novice in Python, so I could not get much clarification from similar questions. Does anyone know why this is happening? import subprocessdef getLength(filename): result = subprocess.Popen(["ffprobe", filename], stdout = subprocess.PIPE, stderr = subprocess.STDOUT) return [x for x in result.stdout.readlines() if "Duration" in x]print(getLength('bell.mp4')) Traceback Traceback (most recent call last): File "B:\Program Files\ffmpeg\bin\test3.py", line 7, in <module> print(getLength('bell.mp4')) File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in getLength return [x for x in result.stdout.readlines() if "Duration" in x] File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in <listcomp> return [x for x in result.stdout.readlines() if "Duration" in x]TypeError: a bytes-like object is required, not 'str' Now provide the response and nothing else.
subprocess returns bytes objects for stdout or stderr streams by default. That means you also need to use bytes objects in operations against these objects. "Duration" in x uses str object. Use a bytes literal (note the b prefix): return [x for x in result.stdout.readlines() if b"Duration" in x] or decode your data first, if you know the encoding used (usually, the locale default, but you could set LC_ALL or more specific locale environment variables for the subprocess): return [x for x in result.stdout.read().decode(encoding).splitlines(True) if "Duration" in x] The alternative is to tell subprocess.Popen() to decode the data to Unicode strings by setting the encoding argument to a suitable codec: result = subprocess.Popen( ["ffprobe", filename], stdout=subprocess.PIPE, stderr = subprocess.STDOUT, encoding='utf8') If you set text=True (Python 3.7 and up, in previous versions this version is called universal_newlines ) you also enable decoding, using your system default codec , the same one that is used for open() calls. In this mode, the pipes are line buffered by default.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44989808', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7879716/']}
jdg_74545
stackexchange
llm_judgeable_groundtruth_similarity
157243
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I just requested a CSR from my shared web hosting provider, to generate a certificate which I will send back to them to install. (The certificate itself is to be generated properly by an organisation I work for who can provide certificates for our official use.) The hosting company promptly sent me the CSR but also the private key! They even CC'd someone else, and it's in Gmail so Google has presumably already ingested it for advertising purposes. In my humble opinion this seems like a terrible thing to do. I am about to write back to them rejecting this one, and asking to renew the CSR and this time keep the private key - private. Before I make a fool of myself, I'd like to confirm that the private key for an "SSL" (TLS) certificate should never leave the server? I've been working in security-related industries for many years, and used to be a crypto programmer, so I feel I know the topic a little - but I know things change over time. I have read this related question: What issues arise from sharing a SSL certificate's private key? Meta Update: I've realised I've written a poor-quality question format for Stack Exchange - as it's now difficult to accept a specific answer. Apologies for that - all answers covered different and equally interesting aspects. I did initially wonder how to word it for that purpose but drew a blank. Update: I have followed this though with the host and they did "apologise for any inconvenience", promised to keep future private keys "safe" and issued me a new, different CSR. Whether it's generated from the same exposed private key I am currently unsure of. I now also wonder, as it's a shared host, if they've sent me the key for the entire server or if each customer/domain/virtual host gets a key pair. It's an interesting lesson how all the crypto strength in the world can be rendered null and void by a simple human error. Kevin Mitnik would be nodding. Update 2:In response to an answer from user @Beau, I have used the following commands to verify the second CSR was generated from a different secret private key. openssl rsa -noout -modulus -in pk1.txt | openssl md5openssl req -noout -modulus -in csr1.txt | openssl md5openssl req -noout -modulus -in csr2.txt | openssl md5 The first two hashes are identical, the third is different. So thats good news. Now provide the response and nothing else.
If I were in your place I would refuse to accept this SSL certificate.The reason for that is, if someone broke into either of the emails that received the private key, they would be able to download it, and then impersonate the server in different attacks on clients, like man in the middle or similar.Also in the case that one of the receiving email addresses was written incorrectly, someone may already have the private key. There are also probably many more scenarios where this private key could be downloaded and used by an attacker. Also notifying the company about not sharing the private key should be important, to make sure that the company won't sent the private key anywhere else - the private key was sent to you, and some other CC's in this email, but you can not know whether the company didn't sent a separate email with the private key somewhere else. There is a reason why the private key is called a private key Please note that this is mostly my personal opinion, and that I am not an expert with SSL.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/157243', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/121341/']}
jdg_74546
stackexchange
llm_judgeable_groundtruth_similarity
309874
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: Is it accurate to say that the solutions to the Schrodinger Equation tell us the allowed outcomes of a quantum experiment and the probability of observing that outcome? Now provide the response and nothing else.
This answer first of all gives a simple-minded approach which has some numbers, and then a more hairy one which doesn't. The simple approach, with numbers So, first of all, $1367\,\mathrm{W/m^2}$ is the solar constant: it's the measured flux of energy from the Sun at the top of atmosphere (TOA), averaged over a year. So this flux is, the TOA flux for the point on the planet where the Sun is directly overhead (all other points get less). I'll call this $G_0$. But the Earth's orbit has some eccentricity in it, so in fact sometimes this flux is a bit higher, and sometimes it's a bit lower. To first order we could model this by saying that the flux looks like $$G = G_0\times(1 + E\cos (2\pi y))$$ where $E$ is some fudge factor based on the known eccentricity of the planet's orbit, $y$ is the time in years ($y$ is not constrained to be an integer), with $y=0$ being chosen as the point where the Earth is closest to the Sun. Observationally, $E \approx 0.03$. Well, perhaps we want the constant in terms of day of the year, rather than year, which would be more useful. This would then look like $$G = G_0 \times\left(1 + E\cos \left(\frac{2\pi}{365} d\right)\right)$$ Where $d$ is the day number, and $365$ is an approximate thing here: this will be OK for a while, but it will drift. And now you have to realise that climate scientists talk to people who build spacecraft more than they talk to people like me: they work in degrees like engineers do. And $2\pi$ radians is $360$ degrees. So, finally, we get: $$G = G_0 \times \left(1 + E\cos \left(\frac{360}{365} d\right)\right)$$ Which is your formula, and where things are working in degrees. (I'm actually really disappointed now: I started this reply thinking 'aha, this is because you are using a model with a 360-day year (which many climate models have done historically, and many still do in fact) and I can explain this bit of obcsurity'. But no, sadly.) A more hairy approach, without numbers First of all we know the Sun looks quite like a black body at some temperature $T$, so the flux leaving the Sun is $\sigma T^4$ in the normal way. The total power passing through any surface surrounding the Sun is constant, so the flux at a radius $R$ is given by $$\sigma T^4 \left(\frac{R_0}{R}\right)^2$$ Where $R_0$ is the radius of the Sun. We could plug numbers for $T$, $R_0$ and $R$, the average radius of the Earth's orbit, into this and we will get $1367\,\mathrm{W/m^2}$. But the thing to know is how this varies with $R$, since Earth's orbit has some eccentricity. So we want to expand $$\sigma T^4 \left(\frac{R_0}{R + \delta R}\right)^2$$ in terms of $\delta R$: $$\begin{align}\sigma T^4 \left(\frac{R_0}{R + \delta R}\right)^2 &= \sigma T^4\left(\frac{R_0}{R}\right)^2 \times \left(1 - 2\frac{\delta R}{R} + O(\delta R^2)\right)\\&\approx \sigma T^4\left(\frac{R_0}{R}\right)^2 \times \left(1 - 2\frac{\delta R}{R}\right)\end{align}$$ And now, well, we know that $\delta R$ is a periodic function of time, with the period being a year (to a good approximation & ignoring orbital variation), and there's no constant term. So, expressing time, $t$ in years, we can write $\delta R$ as $$\delta R = \sum\limits_{n=1}^{\infty} a_n \sin(2\pi n t) + b_n \cos(2\pi n t)$$ And to first order, and adjusting the zero of $t$ suitably, we get $$\delta R \approx a \cos(2\pi t)$$ where $a= a_1$. So plugging this into the above, we get $$\sigma T^4\left(\frac{R_0}{R}\right)^2 \times \left(1 - 2\frac{a \cos (2\pi t)}{R}\right)$$ Whic is what we wanted.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/309874', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/143577/']}
jdg_74547
stackexchange
llm_judgeable_groundtruth_similarity
47182445
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 reset a form after I've added a value. Form Code Snippet <form [formGroup]="addAttributeForm" fxLayout="column"> <mat-form-field> <input matInput formControlName="title" placeholder="Title" required> <mat-error>This field is required</mat-error> </mat-form-field></form> In the component onSubmit(form: FormGroup) { // do work form.reset();} What I'm observing: The form values are set to empty. But the validation messages are still displayed from mat-error. I've tried form.markAsPristine() , form.markAsUntouched() and combining all three. How can I reset the form so the mat-error is not displayed? Now provide the response and nothing else.
The form group has no "knowledge" about whether the actual HTML form has been submitted or not. It only keeps track of the form values/validity/enabled state. So resetting the form group does reset the values but not any state regarding whether the form has been submitted . To do this, you need to get a hold of the FormGroupDirective and call resetForm() on it. Form Code Snippet <form [formGroup]="addAttributeForm" fxLayout="column"> <!-- ... --></form> In the component @ViewChild(FormGroupDirective) formDirective: FormGroupDirective;onSubmit(form: FormGroup) { // do work this.formDirective.resetForm();}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47182445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1493699/']}
jdg_74548
stackexchange
llm_judgeable_groundtruth_similarity
33492
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Nemesis , the hypothetical "death star", is supposed to be a massive body that orbits the Sun at long distances and periodically sends comets from the Oort Cloud into the inner solar system. These comets impact the Earth and cause extinction events. It hasn't been found, and the theoretical case for it is not compelling anyway . My question here is about this curious line from Richard Muller's page at LBL . Fortunately, several all-sky surveys are underway that should find Nemesis in the next few years, if it is there, and rule out Nemesis if they don't. (Nemesis could hide if it were a black hole, but that is not very plausible.) These surveys include Pan-Starrs and the LSST. How do we know it's not plausible for Nemesis to be a black hole? For that matter, how do we know it's not a neutron star? Now provide the response and nothing else.
If the Sun had been born in a relatively wide binary system with a star that was to become a black hole or neutron star via a supernova, then (a) it is quite likely that such a system would be disrupted by that supernova and we would not be in a binary system now; (b) there should be evidence of the supernova in the form of very high abundances of the daughters of certain short-lived radionuclides incorporated into solar system material. There is some evidence of the latter, but not I think enough for the Sun to have been in a binary system with such a star (though I might be checking this). An alternative argument is that the Sun is captured in orbit by the stellar remnant at a later date. This avoids the supernova problems, but the capture process is inherently unlikely in our Galaxy once stars have left their birth environments, especially capture which is tuned rather precisely to yield just less than zero for the resultant system potential energy of a very wide binary. Capture by a "normal" star would in any case be much more likely than capture by a relatively rare compact object.
{}
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/33492', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/20348/']}
jdg_74549
stackexchange
llm_judgeable_groundtruth_similarity
3730088
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 storing a hard list of SELECT @items := GROUP_CONCAT(ID) FROM table_1 ... etc @items is now a string of numbers: 55,77,99,2038,2844,etc Later, I try to use it in a where clause as such: SELECT * FROM table_2 WHERE table_1.ID IN (@items) This does not work. It seems like it should. I know when I manually pull the data, put it in a variable, then output it it works: list($x) = SELECT @items := GROUP_CONCAT(ID) FROM table_1 ... etc$goodResults = SELECT * FROM table_2 WHERE table_1.ID IN ($x) Any ideas? Thanks. Now provide the response and nothing else.
You may want to use the FIND_IN_SET() function: SELECT * FROM table_1 WHERE FIND_IN_SET(id, @items) > 0; Test case: CREATE TABLE table_1 (id int, group_id int);INSERT INTO table_1 VALUES (1, 1);INSERT INTO table_1 VALUES (2, 1);INSERT INTO table_1 VALUES (3, 1);INSERT INTO table_1 VALUES (4, 1);INSERT INTO table_1 VALUES (5, 1);SELECT @items := GROUP_CONCAT(id) FROM table_1 GROUP BY group_id;SELECT * FROM table_1 WHERE FIND_IN_SET(id, @items) > 0;+------+----------+| id | group_id |+------+----------+| 1 | 1 || 2 | 1 || 3 | 1 || 4 | 1 || 5 | 1 |+------+----------+5 rows in set (0.02 sec) SQL FIDDLE
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3730088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/286467/']}
jdg_74550
stackexchange
llm_judgeable_groundtruth_similarity
8039466
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 look at grate library called Boost Geometry I look at it but see no tutorials on working with anything at least a bit graphical. So I wonder if any one can help providing a simple tutorial on creating some N random poligons (random in color size and form) and saving tham as vector image like SVG ? Now provide the response and nothing else.
So... solved it: on google you can find this old code. It will not compile with latest boost 1.47.0. So you will try to fix it and you'd get here for example on some outdated docs... so long story short here is what you shall do to make it work: Download 3 code files for boost/geometry/extensions/io/svg/ , they are header only so no wories here. and now you can compile fixed, updated for current boost code: #include <iostream>#include <fstream>#include <boost/assign.hpp>#include <boost/algorithm/string.hpp>#include <boost/geometry/geometry.hpp>#include <boost/geometry/io/svg/write_svg.hpp>#include <boost/geometry/geometries/geometries.hpp>#include <boost/geometry/algorithms/envelope.hpp>#include <boost/geometry/io/svg/write_svg.hpp>template <typename Geometry1, typename Geometry2>void create_svg(std::string const& filename, Geometry1 const& a, Geometry2 const& b){ typedef typename boost::geometry::point_type<Geometry1>::type point_type; std::ofstream svg(filename.c_str()); boost::geometry::svg_mapper<point_type> mapper(svg, 400, 400); mapper.add(a); mapper.add(b); mapper.map(a, "fill-opacity:0.5;fill:rgb(153,204,0);stroke:rgb(153,204,0);stroke-width:2"); mapper.map(b, "opacity:0.8;fill:none;stroke:rgb(255,128,0);stroke-width:4;stroke-dasharray:1,7;stroke-linecap:round");}int main(){ using namespace boost::assign; boost::geometry::model::ring<boost::geometry::model::d2::point_xy<double> > ring; ring += boost::geometry::model::d2::point_xy<double>(4.0, -0.5), boost::geometry::model::d2::point_xy<double>(3.5, 1.0), boost::geometry::model::d2::point_xy<double>(2.0, 1.5), boost::geometry::model::d2::point_xy<double>(3.5, 2.0), boost::geometry::model::d2::point_xy<double>(4.0, 3.5), boost::geometry::model::d2::point_xy<double>(4.5, 2.0), boost::geometry::model::d2::point_xy<double>(6.0, 1.5), boost::geometry::model::d2::point_xy<double>(4.5, 1.0), boost::geometry::model::d2::point_xy<double>(4.0, -0.5); boost::geometry::model::box<boost::geometry::model::d2::point_xy<double> > box; boost::geometry::envelope(ring, box); std::cout << "make_envelope:" << boost::geometry::dsv(box) << std::endl; create_svg("make_envelope.svg", ring, box);} this will draw this: (not image but vector svg file openable in google chrome=)) So this is how to create SVG file from vector in C++=)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8039466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/434051/']}
jdg_74551
stackexchange
llm_judgeable_groundtruth_similarity
650778
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 trying to find Fourier series and I see a lot of times that $\int^\pi_{-\pi}$ of absolute $|\cos| \text{ and } |\sin| $ is 4. for example, $\int^\pi_{-\pi} (2-|x|) \cos(x) = 4 \text{ and } \int^\pi_{-\pi} |\sin(x)| = 4$. What is the trick behind integrals over $[-\pi, \pi]$ of absolute-valued cosine and sine? Thanks in advance! Now provide the response and nothing else.
Hint: The integrand $f(x)=(2-|x|) \cos(x)$ is an even function on $I=[-\pi,\pi]$ , so $$\int_I f(x)dx=2\color{blue}{\int_0^{\pi}(2-x)\cos(x)dx}=2\times\color{blue}{2}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/650778', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/48863/']}
jdg_74552
stackexchange
llm_judgeable_groundtruth_similarity
5741111
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 function that removes the last element of the list. (define (remove-last ll) (if (null? (cdr ll)) '() (cons (car ll) (remove-last (cdr ll))))) So from my understanding if we cons a list (eg. a b c with an empty list, i.e. '() , we should get a b c . However, testing in interaction windows (DrScheme), the result was: If (cons '() '(a b c)) (() a b c) If (cons '(a b c) '()) ((a b c)) I'm like what the heck :(!Then I came back to my problem, remove all elements which have adjacent duplicate. For example, (a b a a c c) would be (a b) . (define (remove-dup lst) (cond ((null? lst) '()) ((null? (cdr lst)) (car lst)) ((equal? (car lst) (car (cdr lst))) (remove-dup (cdr (cdr lst)))) (else (cons (car lst) (car (cdr lst)))) ) ) It was not correct, however I realize the answer have a . between a b . How could this happen? `(a . b)` There was only one call to cons in my code above, I couldn't see which part could generate this . . Any idea? Thanks, Now provide the response and nothing else.
cons build pairs, not lists. Lisp interpreters uses a 'dot' to visually separate the elements in the pair. So (cons 1 2) will print (1 . 2) . car and cdr respectively return the first and second elements of a pair. Lists are built on top of pairs. If the cdr of a pair points to another pair, that sequence is treated as a list. The cdr of the last pair will point to a special object called null (represented by '() ) and this tells the interpreter that it has reached the end of the list. For example, the list '(a b c) is constructed by evaluating the following expression: > (cons 'a (cons 'b (cons 'c '())))(a b c) The list procedure provides a shortcut for creating lists: > (list 'a 'b 'c)(a b c) The expression (cons '(a b c) '()) creates a pair whose first element is a list . Your remove-dup procedure is creating a pair at the else clause. Instead, it should create a list by recursively calling remove-dup and putting the result as the second element of the pair. I have cleaned up the procedure a bit: (define (remove-dup lst) (if (>= (length lst) 2) (if (eq? (car lst) (cadr lst)) (cons (car lst) (remove-dup (cddr lst))) (cons (car lst) (remove-dup (cdr lst)))) lst)) Tests: > (remove-dup '(a b c))(a b c)> (remove-dup '(a a b c))(a b c)> (remove-dup '(a a b b c c))(a b c) Also see section 2.2 (Hierarchical Data and the Closure Property) in SICP . For completeness, here is a version of remove-dup that removes all identical adjacent elements: (define (remove-dup lst) (if (>= (length lst) 2) (let loop ((f (car lst)) (r (cdr lst))) (cond ((and (not (null? r))(eq? f (car r))) (loop f (cdr r))) (else (cons (car lst) (remove-dup r))))) lst))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5741111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398398/']}
jdg_74553
stackexchange
llm_judgeable_groundtruth_similarity
38874928
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an object X with a method getY() returning an object Y with a method a() , in typescript.What does it mean an expression like this one: X.getY()!.a() I guess the ! operator is used to check against null, but how does it work concretely? Where is defined in the language? Now provide the response and nothing else.
It's called the "Non-null assertion operator" and it tells the compiler that x.getY() is not null. It's a new typescript 2.0 feature and you can read about it in the what's new page, here's what it says: A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code. // Compiled with --strictNullChecksfunction validateEntity(e?: Entity) { // Throw exception if e is null or invalid entity}function processEntity(e?: Entity) { validateEntity(e); let s = e!.name; // Assert that e is non-null and access name} Edit There's an issue for documenting this feature: Document non-null assertion operator (!)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/38874928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2032922/']}
jdg_74554
stackexchange
llm_judgeable_groundtruth_similarity
4364622
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: how to set header no cache in spring mvc 3 by annotation? not is response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setDateHeader("Expires", 0); Now provide the response and nothing else.
There is no such option. You can use an interceptor: <mvc:annotation-driven/><mvc:interceptors> <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor"> <property name="cacheSeconds" value="0"/> <property name="useExpiresHeader" value="true"/> <property name="useCacheControlHeader" value="true"/> <property name="useCacheControlNoStore" value="true"/> </bean></mvc:interceptors> (taken from here ) On one hand it is logical not to have such annotation. Annotations on spring-mvc methods are primarily to let the container decide which method to invoke (limiting it by a request header, request url, or method). Controlling the response does not fall into this category. On the other hand - yes, it will be handy to have these, because when controllers are unit-tested it is not relevant to test http header stuff (or is it?). And there are @ResponseBody and @ResponseStatus , which do specify some response properties.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4364622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/371430/']}
jdg_74555
stackexchange
llm_judgeable_groundtruth_similarity
14618478
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 certain scenario where I'm using click to insert a div and then mousedown on that div for dragging it around. I have bound the click to the parent container, and the mousedown on the div itself. But when I mousedown on the div, it fires the click on the parent as well, hence inserting multiple divs instead of dragging the already added div! Is there a way to solve this issue? I can't unbind click , since I need to add 2 divs using the click , and then bind mousedown on these. Update: I'm using selector.on(event, handler) type of binding. Now provide the response and nothing else.
Try this way. event.stopPropagation does not stop the click event from firing after mousedown. Mousedown and click events are not related to each other. var mousedownFired = false;$("#id").on('mousedown', function(event) { mousedownFired = true; //code});$("#id").on('click', function(event) { if (mousedownFired) { mousedownFired = false; return; } //code}); Update: Mouse events are triggered like this: mousedown click mouseup If mousedown is triggered, the mousedownFired variable will be set to true . Then in the click event, it will return (i.e. not continue processing the click event), and the mousedownFired variable will be reset to false, so future click events will fire normally. Not going to consider two mousedown or two click events.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14618478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/744519/']}
jdg_74556
stackexchange
llm_judgeable_groundtruth_similarity
7692653
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: You are given N blocks of height 1…N. In how many ways can you arrange these blocks in a row such that when viewed from left you see only L blocks (rest are hidden by taller blocks) and when seen from right you see only R blocks? Example given N=3, L=2, R=1 there is only one arrangement {2, 1, 3} while for N=3, L=2, R=2 there are two ways {1, 3, 2} and {2, 3, 1} . How should we solve this problem by programming? Any efficient ways? Now provide the response and nothing else.
This is a counting problem, not a construction problem, so we can approach it using recursion. Since the problem has two natural parts, looking from the left and looking from the right, break it up and solve for just one part first. Let b(N, L, R) be the number of solutions, and let f(N, L) be the number of arrangements of N blocks so that L are visible from the left. First think about f because it's easier. APPROACH 1 Let's get the initial conditions and then go for recursion. If all are to be visible, then they must be ordered increasingly, so f(N, N) = 1 If there are suppose to be more visible blocks than available blocks, then nothing we can do, so f(N, M) = 0 if N < M If only one block should be visible, then put the largest first and then the others can follow in any order, so f(N,1) = (N-1)! Finally, for the recursion, think about the position of the tallest block, say N is in the k th spot from the left. Then choose the blocks to come before it in (N-1 choose k-1) ways, arrange those blocks so that exactly L-1 are visible from the left, and order the N-k blocks behind N it in any you like, giving: f(N, L) = sum_{1<=k<=N} (N-1 choose k-1) * f(k-1, L-1) * (N-k)! In fact, since f(x-1,L-1) = 0 for x<L , we may as well start k at L instead of 1 : f(N, L) = sum_{L<=k<=N} (N-1 choose k-1) * f(k-1, L-1) * (N-k)! Right, so now that the easier bit is understood, let's use f to solve for the harder bit b . Again, use recursion based on the position of the tallest block, again say N is in position k from the left. As before, choose the blocks before it in N-1 choose k-1 ways, but now think about each side of that block separately. For the k-1 blocks left of N , make sure that exactly L-1 of them are visible. For the N-k blocks right of N , make sure that R-1 are visible and then reverse the order you would get from f . Therefore the answer is: b(N,L,R) = sum_{1<=k<=N} (N-1 choose k-1) * f(k-1, L-1) * f(N-k, R-1) where f is completely worked out above. Again, many terms will be zero, so we only want to take k such that k-1 >= L-1 and N-k >= R-1 to get b(N,L,R) = sum_{L <= k <= N-R+1} (N-1 choose k-1) * f(k-1, L-1) * f(N-k, R-1) APPROACH 2 I thought about this problem again and found a somewhat nicer approach that avoids the summation. If you work the problem the opposite way, that is think of adding the smallest block instead of the largest block, then the recurrence for f becomes much simpler. In this case, with the same initial conditions, the recurrence is f(N,L) = f(N-1,L-1) + (N-1) * f(N-1,L) where the first term, f(N-1,L-1) , comes from placing the smallest block in the leftmost position, thereby adding one more visible block (hence L decreases to L-1 ), and the second term, (N-1) * f(N-1,L) , accounts for putting the smallest block in any of the N-1 non-front positions, in which case it is not visible (hence L stays fixed). This recursion has the advantage of always decreasing N , though it makes it more difficult to see some formulas, for example f(N,N-1) = (N choose 2) . This formula is fairly easy to show from the previous formula, though I'm not certain how to derive it nicely from this simpler recurrence. Now, to get back to the original problem and solve for b , we can also take a different approach. Instead of the summation before, think of the visible blocks as coming in packets, so that if a block is visible from the left, then its packet consists of all blocks right of it and in front of the next block visible from the left, and similarly if a block is visible from the right then its packet contains all blocks left of it until the next block visible from the right. Do this for all but the tallest block. This makes for L+R packets. Given the packets, you can move one from the left side to the right side simply by reversing the order of the blocks. Therefore the general case b(N,L,R) actually reduces to solving the case b(N,L,1) = f(N,L) and then choosing which of the packets to put on the left and which on the right. Therefore we have b(N,L,R) = (L+R choose L) * f(N,L+R) Again, this reformulation has some advantages over the previous version. Putting these latter two formulas together, it's much easier to see the complexity of the overall problem. However, I still prefer the first approach for constructing solutions, though perhaps others will disagree. All in all it just goes to show there's more than one good way to approach the problem. What's with the Stirling numbers? As Jason points out, the f(N,L) numbers are precisely the (unsigned) Stirling numbers of the first kind . One can see this immediately from the recursive formulas for each. However, it's always nice to be able to see it directly, so here goes. The (unsigned) Stirling numbers of the First Kind, denoted S(N,L) count the number of permutations of N into L cycles. Given a permutation written in cycle notation, we write the permutation in canonical form by beginning the cycle with the largest number in that cycle and then ordering the cycles increasingly by the first number of the cycle. For example, the permutation (2 6) (5 1 4) (3 7) would be written in canonical form as (5 1 4) (6 2) (7 3) Now drop the parentheses and notice that if these are the heights of the blocks, then the number of visible blocks from the left is exactly the number of cycles! This is because the first number of each cycle blocks all other numbers in the cycle, and the first number of each successive cycle is visible behind the previous cycle. Hence this problem is really just a sneaky way to ask you to find a formula for Stirling numbers.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7692653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/761330/']}
jdg_74557
stackexchange
llm_judgeable_groundtruth_similarity
15963
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 $X$ and $Y$ be topological spaces. A function $f: X \rightarrow Y$ is defined as continuous if for each open set $U \subset Y$, $f^{-1}(U)$ is open in $X$. This definition makes sense to me when $X$ and $Y$ are metric spaces- it is equivalent to the usual $\epsilon-\delta$ definition. But why is this a good definition when $X$ and $Y$ are not metric spaces? How should we think about this definition intuitively? Now provide the response and nothing else.
One abstract way to think about continuity (in the sense that it generalizes to non-metric spaces) is that it is about error. A function $f : X \to Y$ is continuous at $x$ precisely when $f(x)$ can be "effectively measured" in the sense that, by measuring $x$ closely enough, we can measure $f(x)$ to any desired precision. (In other words, the error in our measurement of $f(x)$ can be controlled. "Precision" here means "to within an arbitrary neighborhood of $f(x)$," so it does not depend on any metric notions.) This is an abstract formulation of one of the most basic assumptions of science: that (most of) the quantities we try to measure ($f(x)$) depend continuously on the parameters of our experiments ($x$). If they didn't, science would be effectively impossible. If you like thinking about limits, a function is continuous if and only if it preserves limits of filters or, equivalently, nets . These are two ways to generalize converge of sequences to spaces which are not first-countable.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/15963', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4457/']}
jdg_74558
stackexchange
llm_judgeable_groundtruth_similarity
1593580
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 get the memory address of the value a pointer points to? in my case it is a void pointer.just assigning it to an uint gives me this error: Error 1 error C2440: 'return' : cannot convert from 'void *' to 'UInt32' thanks! Now provide the response and nothing else.
std::size_t address = reinterpret_cast<std::size_t>(voidptr);// sizeof(size_t) must be greater or equal to sizeof(void*)// for the above line to work correctly. @Paul Hsieh I think it is sufficient to convert void* to size_t in this specific question for three reasons: The questioner didn't specify if hewants a portable solution or not. Hesaid, that it worked with him. I don't know exactly whatthat means butit is clear to me he isworking on IA-32 on Windows or othersystem under protected mode. Thatmeans converting a pointer to aninteger is a defined operation onthat system even if it is not defined by standard C++. Second, I proposed first converting the pointer to int which is clearly meaningless as litb and jalf showed me. I corrected the mistake I've done, and replaced int with size_t . Finally, I tried my hard to find something relevant to what you proposed as a solution in the standards. Unfortunately, I couldn't find anything relevant. I have this reference: ANSI ISO IEC 14882 2003 . I think sellibitze pointed out that it will be part of the coming standards. I really don't know about C, and obviously C99 introduced this perfect solution. I would like someone to show me a portable solution in C++. Please, don't hesitate to correct my mistakes, I am still a student at uni :) Thanks,
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1593580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/97688/']}
jdg_74559
stackexchange
llm_judgeable_groundtruth_similarity
3284473
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In my homework there is an exercise that asks to show the following result: Let $(E,d)$ be a metric space. Show that a subset $A$ is dense in $E$ iff every open set in $(E,d)$ contains an element of $A$ . I was thinking in the case of the empty set. My question: " $\emptyset$ contains an element of $A$ " is false or is vacuously true? If it is false, then the necessary condition for the denseness of $A$ will always be false, because there will always be the (open) empty set in $E$ which does not contain any element of $A$ . In this case, logically, $A$ would never be a dense subset of $E$ . Is my argument right or am I going crazy? Thanks in advance. Now provide the response and nothing else.
The formulation you quoted is slightly wrong, it should have been: Let $(E,d)$ be a metric space. Show that a subset $A$ is dense in $E$ iff every non-empty open set in $(E,d)$ contains an element of $A$ . So you're not going crazy. In the formulation you gave no set will ever be dense and we've defined a "vacuous property". And the corrected formulation (by vacuous truth, as there are no non-empty open subsets to check) indeed allows us even to say that $\emptyset$ is dense in the empty space $\emptyset$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3284473', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/636281/']}
jdg_74560
stackexchange
llm_judgeable_groundtruth_similarity
33664466
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 currently have a navigation drawer with a toolbar that has a title, i wish to centre this title within the toolbar but the toolbar does not seem to take into consideration the drawer icon as you can see in the following picture. whereas when i use the same toolbar layout for other activities that are not inside the navigation drawer the title is centred perfectly, as show in this picture: So how do i get it to take into account this icon? Here is my layout: <android.support.design.widget.AppBarLayout xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:layout_width="match_parent" android:theme="@style/Theme.App.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/black" app:popupTheme="@style/Theme.App.PopupOverlay"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="@color/white" android:textStyle="bold" android:text="Title" android:textSize="16sp" /> </RelativeLayout> </android.support.v7.widget.Toolbar></android.support.design.widget.AppBarLayout> Now provide the response and nothing else.
You need to understand that Toolbar widget extends ViewGroup class, and it has it's own LayoutParams . So you do not require RelativeLayout inside Toolbar, and need to add just single line with TextView. android:layout_gravity="center_horizontal" And final xml should look like this, <android.support.design.widget.AppBarLayout xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:theme="@style/Theme.App.AppBarOverlay" ><android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/black" app:popupTheme="@style/Theme.App.PopupOverlay" > <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Title" android:textColor="@color/white" android:textSize="16sp" android:textStyle="bold" /></android.support.v7.widget.Toolbar>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33664466', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3992148/']}
jdg_74561
stackexchange
llm_judgeable_groundtruth_similarity
55543595
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 written a simple application and when I navigate to my edit page the below error pops up. Microsoft.EntityFrameworkCore.Query[10100] An exception occurred while iterating over the results of a query for context type 'app.Models.ApplicationDbContext'. System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. It seems EF is providing a useful information which I can not understand. The tricky part of this error is that it happens randomly when I navigate to the edit page. Sometime it works, Sometimes it fails to load some properties on Edit.cshtml but still works and sometimes the application crashes with provided error just in my console. Another strange happen is that it dose not generate any 500 or 5xx error. It just simply crashes and stop the application. Here is my Edit.cshtml content: @page@model EditModel@{ ViewData["Title"] = "Edit Book";}<h2>Edit Book</h2><div class="row justify-content-center"> <div class="col-md-6"> <form method="post" class="form-border"> <div asp-validation-summary="All" class="validation-container alert alert-danger"></div> <div class="form-group"> <label asp-for="Book.Name"></label> <input asp-for="Book.Name" class="form-control" /> <span class="form-text text-danger" asp-validation-for="Book.Name"></span> </div> <div class="form-group"> <label asp-for="Book.Description"></label> <input asp-for="Book.Description" class="form-control" /> </div> <div class="form-group"> <label asp-for="Book.Author"></label> <input asp-for="Book.Author" class="form-control" /> </div> <input asp-for="Book.Id" type="hidden"> <button type="submit" class="btn btn-primary">Update</button> <a asp-page="Index" class="btn btn-success">Back To List</a> </form> </div></div> Here is My Edit.cshtm.cs OnGet method: public async void OnGet(int id){ Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id); if(Book == null) { RedirectToPage("Index"); }} I am using .Net Core 2.2.104 Also when I run command dotnet ef --version it generates Entity Framework Core .NET Command-line Tools 2.2.2-servicing-10034 Now provide the response and nothing else.
This is because of your method return type async void . In general, when you are using async void in your code it’s bad news, because: You can’t wait for its completion Any unhandled exceptions will terminate your process (ouch!) So return async Task instead of async void from your method as follows: public async Task OnGet(int id){ Book = await _db.Books.SingleOrDefaultAsync(x => x.Id == id); if(Book == null) { RedirectToPage("Index"); }} For more details: C# – beware of async void in your code Cannot access a disposed object in ASP.NET Core when injecting DbContext
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/55543595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5852708/']}
jdg_74562
stackexchange
llm_judgeable_groundtruth_similarity
5383310
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 the async CTP from Microsoft for .NET,is it possible to catch an exception thrown by an async method in the calling method? public async void Foo(){ var x = await DoSomethingAsync(); /* Handle the result, but sometimes an exception might be thrown. For example, DoSomethingAsync gets data from the network and the data is invalid... a ProtocolException might be thrown. */}public void DoFoo(){ try { Foo(); } catch (ProtocolException ex) { /* The exception will never be caught. Instead when in debug mode, VS2010 will warn and continue. The deployed the app will simply crash. */ }} So basically I want the exception from the async code to bubble up into my calling codeif that is even possible at all. Now provide the response and nothing else.
It's somewhat weird to read but yes, the exception will bubble up to the calling code - but only if you await or Wait() the call to Foo . public async Task Foo(){ var x = await DoSomethingAsync();}public async void DoFoo(){ try { await Foo(); } catch (ProtocolException ex) { // The exception will be caught because you've awaited // the call in an async method. }}//or//public void DoFoo(){ try { Foo().Wait(); } catch (ProtocolException ex) { /* The exception will be caught because you've waited for the completion of the call. */ }} As Stephen Cleary wrote in Async/Await - Best Practices in Asynchronous Programming : Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. Note that using Wait() may cause your application to block, if .NET decides to execute your method synchronously. This explanation http://www.interact-sw.co.uk/iangblog/2010/11/01/csharp5-async-exceptions is pretty good - it discusses the steps the compiler takes to achieve this magic.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5383310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/28149/']}
jdg_74563
stackexchange
llm_judgeable_groundtruth_similarity
15862683
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 returns a PDF which the browser tries to directly display inline. This works correctly. However, if I try to download the file, the download name is not "myPDF.pdf", but instead the ID in the route (myapp/controller/PDFGenerator/ID). Is it possible to set the file download name to be "myPDF.pdf"? public FileStreamResult PDFGenerator(int id){ MemoryStream ms = GeneratePDF(id); byte[] file = ms.ToArray(); MemoryStream output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; HttpContext.Response.AddHeader("content-disposition", "inline; filename=myPDF.pdf"); return File(output, "application/pdf", fileDownloadName="myPDF.pdf");} Now provide the response and nothing else.
No, this is not possible with a PDF displayed inline. You could achieve this if you send the Content-Disposition header with as an attachment: public ActionResult PDFGenerator(int id){ Stream stream = GeneratePDF(id); return File(stream, "application/pdf", "myPDF.pdf");} Also notice how I removed the unnecessary MemoryStream you were using and loading the PDF in memory where you could have directly streamed it to the client which would have been far more efficient.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15862683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1620141/']}
jdg_74564
stackexchange
llm_judgeable_groundtruth_similarity
7766933
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using dynamically created links: <h:link outcome="/page" value="#{name}"> <f:param name="name" value="#{name}"/> </h:link> I would like to attach custom converter for f:param to remove spaces from #{name} etc.But there is no converter property in f:param. Now provide the response and nothing else.
A Converter is intented to convert from submitted String request parameter values to complex objects and vice versa in input fields. However, the <f:param> is pure output only and it will always call toString() on the value. It doesn't support a Converter . Your cleanest and best bet is to create a custom EL function , so that you ultimately end up like: <f:param name="name" value="#{util:prettyUrl(name)}"/> Update : the JSF utility library OmniFaces has since version 1.4 (March 2013) a <o:param> component which extends the <f:param> with support for a fullworthy JSF converter, exactly like as you'd use in <h:outputText converter> . <h:link outcome="/page" value="#{name}"> <o:param name="name" value="#{name}" converter="somePrettyURLConverter" /></h:link> See also the showcase .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7766933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/878418/']}
jdg_74565
stackexchange
llm_judgeable_groundtruth_similarity
49736580
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 @ngrx/entity I want to select an entity by a single id or an array of entities by an array of ids from an entity map. I do not want the select subscriptions inside a component to be triggered when the entity collection gets a new element or an entity item changes, which I did not select at all. This obviously happens to me when I use the selectEntities selector and then pick the IDs from the result. So how can I select 1 or n items by id from an entity collection? Now provide the response and nothing else.
EDIT: as Ethan mentions below, selectors with props were deprecated in v12 . This decision was discussed extensively in an RFC . (Comments further down the thread address how to effectively memoise factory functions .) The currently recommended approach to this is using a factory function : export const selectEntity = id => createSelector( selectEntities, entities => entities[id]);export const selectEntitiesByID = ids => createSelector( selectEntities, entities => ids.map(id => entities[id])); Which are called thus: this.store.pipe( select(selectEntity(someID)));this.store.pipe( select(selectEntitiesByID(arrayOfIDs))); Previously, NgRx supported parameterised selectors by passing props as the last argument to a selector function : export const selectEntity = createSelector( selectEntities, (entities, props) => entities[props.id]);export const selectEntitiesByID = createSelector( selectEntities, (entities, props) => props.ids.map(id => entities[id])); These are invoked exactly as you might expect: this.store.pipe( select(selectEntity, { id: someID }));this.store.pipe( select(selectEntitiesByID, { ids: arrayOfIDs }));
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49736580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2504535/']}
jdg_74566
stackexchange
llm_judgeable_groundtruth_similarity
20059995
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 Python one can pass the dict 1 constructor a sequence of key-value pairs: >>> dict([['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']]){'age': 42, 'name': 'Bob', 'breakfast': 'eggs'} I can't think of any way to do this sort of thing in JavaScript other than defining my own function for the purpose: function pairs_to_object(pairs) { var ret = {}; pairs.forEach(function (p) { ret[p[0]] = p[1]; }); return ret;} But I'm a JS noob... Is there anything built-in for this sort pairs-to-object conversion? 1 For the purposes of this question, I'm treating Python dicts as Python's counterpart of JS objects, although, of course the similarity is limited only to the fact that they are both key-value collections. Now provide the response and nothing else.
Object.fromEntries does the job. It was added to the language with EcmaScript2019. If you don't have support for that function, you could define it yourself with the following ES2015 code: Object.fromEntries = arr => Object.assign({}, ...Array.from(arr, ([k, v]) => ({[k]: v}) )); A nice thing is that this method does the opposite of Object.entries (ES2017), so now you can go back and forth between the object and array representation: const arr = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];const obj = Object.fromEntries(arr);console.log(obj);// ... and back:const arr2 = Object.entries(obj);console.log(arr2); // copy of the original array (omitting duplicate keys) .as-console-wrapper { max-height: 100% !important; top: 0; } ES6 Map There is an alternative to plain objects for key/value pairs: Map . Its constructor accepts the array-of-pairs format: // Demo:const arr = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];const mp = new Map(arr);// Get one particular value:console.log(mp.get('age'));// Get all the keys:console.log(...mp.keys());// Get all the values:console.log(...mp.values());// Get all the key/value pairs:console.log(...mp.entries()); If you really need a plain object, then this is not useful, but a Map might present a viable alternative.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20059995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/559827/']}
jdg_74567
stackexchange
llm_judgeable_groundtruth_similarity
11147468
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 Node.js (with Express.js) to pass a JSON data object from the server to the client view. When I render the JSON object directly to the view I get the JSON object shown on the page as expected (this WORKS): pageprovider.findAllTag( function(error, pages){ res.send(pages);}) And my output looks like this (much bigger, many nested obj) {"green":{"title":"green","pagesContaining": ""}} When I try to pass it to my Jade View like this: pageprovider.findAllTag( function(error, tagsJSONObj){ //res.send(pages); pageprovider.findAll( function(error, pages){ res.render('search_tags.jade', { locals: { title: 'Search by Tags', 'pages': pages, tagsJSON: JSON.stringify(tagsJSONObj) //pass the tags data as a JSON obj } }); }) //pageprovider.findAll}) //pageprovider.findAllTag The problem When I pass 'tagsJSON' to the view, the output includes the html entities: var obj = jQuery.parseJSON( "{&quot;name&quot;: 'value'}"); JQuery throws an error because it doesn't like '"'. How can I get Node to give me the proper quote, or get jQuery to accept this format? Any thoughts? Now provide the response and nothing else.
It's because when you call res.render('search_tags.jade', { locals: { title: 'Search by Tags', 'pages': pages, tagsJSON: JSON.stringify(tagsJSONObj) //pass the tags data as a JSON obj } }); search_tags.jade is meant to output HTML, so it encodes your quotes. You should use a renderer that doesn't HTML escape, or at least change your view so that your params aren't HTML encoded If you don't want something in the output escaped, use !{tagsJSON} within the view. However, when outputting JSON, there's no need for a view. you can just take your object, call JSON.stringify . I don't use JADE so I'm not sure if there is a way to create view that can just call JSON.stringify() , but that's what I've done in JSP, velocity, ASP, PHP and Code Igniter (not using JSON.stringify , instead it uses a JSON tool for the given language)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11147468', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95175/']}
jdg_74568
stackexchange
llm_judgeable_groundtruth_similarity
7034754
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'am trying to download temporary result calculated by JavaScript. Say I have a string str , I want to download a file contains str and named it as data.csv , I'm using the following code: window.open('data:text/csv;charset=utf-8,' + str); The file can be successfully downloaded, but how can I name the file data.csv automatically rather than set the name by hand each time? Now provide the response and nothing else.
You can achieve this using the download attribute for <a> elements. For example: <a href="1251354216241621.txt" download="your-foo.txt">Download Your Foo</a> This attribute indicates that the file should be downloaded (instead of displayed, if applicable) and specifies which filename should be used for the downloaded file. Instead of using window.open() you could generate an invisible link with the download attribute and .click() it. var str = "Name, Price\nApple, 2\nOrange, 3";var uri = 'data:text/csv;charset=utf-8,' + str;var downloadLink = document.createElement("a");downloadLink.href = uri;downloadLink.download = "data.csv";document.body.appendChild(downloadLink);downloadLink.click();document.body.removeChild(downloadLink); Unfortunately this isn't supported in all browsers, but adding it won't make things worse for other browsers: they'll continue to download the files with useless filenames. (This assumes that you're using a MIME type is that their browser attempts to download. If you're trying to let the user download an .html file instead of displaying it, this won't do you any good in unsupported browsers.)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7034754', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302199/']}
jdg_74569
stackexchange
llm_judgeable_groundtruth_similarity
2087439
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ive got a simple menu that upon hover of each item, plays a movie clip, then on mouse_out it plays the movie clip in reverse. What I'm trying to do is to have a third state (active) that is shown upon clicking. I'm thinking I need to do something along the lines of: When clicked, gotoAndStop(5) //Five being the location of my active frame Also remove the event listener that triggers the function to play the movie in reverse.Then when another menu item is clicked, re-add the event listener to the previous menu item so it's not stuck 'active' I can't quite figure out how to do this though. My code is as follows: // IMPORTSimport fl.transitions.*;import fl.transitions.Tween;import fl.transitions.easing.*;import flash.external.ExternalInterface;// EVENT LISTENERS//arrowmcArrow.addEventListener(MouseEvent.MOUSE_OVER,mover);mcArrow.addEventListener(MouseEvent.MOUSE_OUT,mout);//dotsmcDots.addEventListener(MouseEvent.MOUSE_OVER,mover);mcDots.addEventListener(MouseEvent.MOUSE_OUT,mout);//musicmcMusic.addEventListener(MouseEvent.MOUSE_OVER,mover);mcMusic.addEventListener(MouseEvent.MOUSE_OUT,mout);//homemcHome.addEventListener(MouseEvent.MOUSE_OVER,mover);mcHome.addEventListener(MouseEvent.MOUSE_OUT,mout);//padlockmcPadlock.addEventListener(MouseEvent.MOUSE_OVER,mover);mcPadlock.addEventListener(MouseEvent.MOUSE_OUT,mout);// FUNCTIONSfunction mover(e:MouseEvent):void { stopPlayReverse(e.currentTarget as MovieClip); e.currentTarget.play();//var fadeIn:Tween = new Tween(mcToolTip, "alpha", Strong.easeOut, 0, 1, 0.5, true);}function mout(e:MouseEvent):void { var mc:MovieClip = e.currentTarget as MovieClip; if (mc !== null) { mc.addEventListener(Event.ENTER_FRAME, playReverse, false, 0, true); } //var fadeOut:Tween = new Tween(mcToolTip, "alpha", Strong.easeOut, 1, 0, 0.5, true);}function playReverse(e:Event):void { var mc:MovieClip = e.currentTarget as MovieClip; if (mc.currentFrame == 1) { stopPlayReverse(mc); } else { mc.prevFrame(); }}function stopPlayReverse(mc:MovieClip):void { if ((mc!==null) && mc.hasEventListener(Event.ENTER_FRAME)) { mc.removeEventListener(Event.ENTER_FRAME, playReverse); }} Now provide the response and nothing else.
On 1: Yes. Socket libraries are shipped with Cygwin - many socket based apps such as web servers are included in the base distribution. On 2: Yes. I think all of the 'section 2 and 3' system calls in the GNU C runtime and library are implemented by the cygwin runtume. You can check this in the man pages that come with Cygwin. A list of system calls and std lib calls implementd by Cygwin can be found here. On 3: Yes. Pthread is included in Cygwin. The list referred to in the link above mentions pthreads as well. On 4: Anything built against GNU libraries should work with little or no change between Cygwin and Linux (assuming there are no dependencies missing on Cygwin). Depending on CPU architecture you may have to worry about word alignment , endianness and other architecture-specific porting issues, but if you're targeting Windows and Linux on Intel your code would have few if any porting issues arising from CPU architecture. On 5: Cygwin will build a program against its own shared libraries by default but GCC can cross-compile to target other platforms. You could (in theory) set GCC up to cross-compile to any target supported by the compiler. There are plenty of resources on the web about cross-compiling with GCC, and I don't think the process will be materially different on Cygwin. Note that Cygwin binaries will not run on Linux - or Vice-versa. You will still need separate builds for both. On 6: Not sure - at a guess it's included in the standard runtime, perhaps because it was necessary to wrap the Win32 threading API for some reason. On 7: Don't know - it's probably the same on g++ on all platforms. Apparently a compiler bug. Dan Moulding's Answer covers this in more detail. On 8: Yes. IIRC QT is available in the standard builds and it will certainly compile on Cygwin. As with Linux/Unix, QT on Cygwin uses an X11 backend so you will need to have an X server such as XMing running. In order to avoid the dependency on an X server you may want to build QT apps against the Win32 API, . It is possible to do this with MinGW , which is a set of header files and libraries to build native Win32 apps with GCC. MinGW can be used from within a Cygwin environment (an example of GCC on Cygwin cross-compiling to a non-Cygwin target) and the installer from cygwin.com gives you the option of installing it. MinGW is quite mature; it has all of the 'usual suspects' - libraries and header files you would expect to find on a Unix/Linux GCC development environment and is very stable. Itis often the tool of choice for building Win32 ports of open-source software because it is (a) free, (b) supports the libraries used by the software and (c) uses GCC so it is not affected by dialectic variations between MSVC and GCC. However, these dialectic variations in the language and available libraries (for example MSVC doesn't come with an implementation of getopt ) mean that porting programs between MinGW and MSVC can be quite fiddly. My experience - admittedly not terribly extensive as I've only done this a few times - is that porting applications between MinGW32 and Linux is easier than porting between MinGW and MSVC. Obviously apps with non-portable dependencies such as Win32 specific API usage would require the dependent components to be re-written for the new platform but you'll have far fewer problems with differences in the standard libs, header files and language dialect. QT does a fairly good job of providing a platform abstraction layer. It provides APIs for database access, threading, I/O and many other services as well as the GUI. Using the QT APIs where possible should help with portability and the Unix/Linux flavoured libraries that come with MinGW mean that it might give you a good platform for making applications that will port between Win32 and Linux with relatively little platform dependent code. EDIT: The qt development packages in Cygwin are: qt4: Qt application framework (source) qt4-devel-tools: Qt4 Assistant, Designer, and Linguist qt4-doc: Qt4 API documentation qt4-qtconfig: Qt4 desktop configuration app qt4-qtdemo: Qt4 demos and examples You'll probably also need gcc4-g++ and some other bits and pieces. This listing on the cygwin web site has a list of the packages.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2087439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/229558/']}
jdg_74570
stackexchange
llm_judgeable_groundtruth_similarity
39858828
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 similar to a question I asked yesterday but the answer I got doesn't seem to work in this case. I'm getting altitude values in meters from Core Location. I want to display these in a localized form. As an example, the altitude where I am right now is 1839m above sea level. This should be displayed as 6033 feet. The best I can do with MeasurementFormatter is "1.143 mi". let meters : Double = 1839let metersMeasurement = Measurement(value: meters, unit: UnitLength.meters)let measurementFormatter = MeasurementFormatter()measurementFormatter.locale = Locale(identifier: "en_US")let localizedString = measurementFormatter.string(from: metersMeasurement) The .naturalScale option that answered my previous question doesn't help here. I think this is a limitation of the framework, but I wonder if anyone has a workaround for now. Now provide the response and nothing else.
You just need to convert your UnitLength from meters to feet. You can also create a custom US measurement formatter to display it as needed: extension Measurement where UnitType == UnitLength { private static let usFormatted: MeasurementFormatter = { let formatter = MeasurementFormatter() formatter.locale = Locale(identifier: "en_US") formatter.unitOptions = .providedUnit formatter.numberFormatter.maximumFractionDigits = 0 formatter.unitStyle = .long return formatter }() var usFormatted: String { Measurement.usFormatted.string(from: self) }} Playground let value: Double = 1839let meters: Measurement<UnitLength> = .init(value: value, unit: .meters)let feet = meters.converted(to: .feet)let formatted = feet.usFormattedprint(formatted) // "6,033 feet"\n
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39858828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43832/']}
jdg_74571
stackexchange
llm_judgeable_groundtruth_similarity
3618121
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 having 2 problems. 1 - I have a text area in which I am matching a string. If it matches then a timer will start. But that condition will likely be satisfied more than once, so I would like to give a condition that if timer is already running don't do anything, if(!timer.running) then start timer. But it still resets the timer every time. 2 - I have a chat window. For every user activity a sentence will be displayed to it. For each added sentence I have to perform some actions. So i have given conditions and actions to be performed for each sentence in a single function, but the problem is every time the previous already executed commands are also executed one more time. (for example above problem 1.)so once it matches the 1st string it should start search from 2nd line in the text area, i think this can do the trick. any help will be appreciated. public function updateMessage(updateMsg:String) : void{ userActivities.text+=updateMsg+"\n"; if(userActivities.text.indexOf("user connected",0)!=-1) { userTimer=new Timer(delay); if(!userTimer.running) { basetmr=getTimer(); userTimer.addEventListener(TimerEvent.TIMER,chkUserActivities); userTimer.start(); } else { //trace("timerCount.."+userTimer.currentCount); } } else if(userActivities.text.indexOf("user changed the image",0)!=-1 ) { userActivities.text+="Click ReleaseDetails button to release your details to visitor"; } else if(userActivities.text.indexOf("user quit the session",0)!=-1) { userTimer.stop(); }} Now provide the response and nothing else.
You can use DateTime.TryParseExact to see if it can be parsed correctly: bool isValid = false;DateTime dateValue;if(DateTime.TryParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue)){ // DateTime parsed, dateValue contains the parsed DateTime // Can validate dateValue against business rules at this point isValid = (dateValue <= DateTime.Now && dateValue >= DateTime.Now.AddYears(-5));} If you would rather get an exception, you can use DateTime.ParseExact : // Next line throws exception if format not correctDateTime.ParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3618121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/436957/']}
jdg_74572
stackexchange
llm_judgeable_groundtruth_similarity
11600006
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have installed mongodb for mac os through 10gen and I have gone through the documentation to do so. Everything seems fine apart from the configuration file. I can not see it in /etc/mongod.config. Do I have to manually create this config file? And if so how can I go about it? cheers Now provide the response and nothing else.
Unless you have installed a packaged version of MongoDB (for example, using Homebrew or Mac Ports ) you will have to create a config file manually, or just pass the appropriate command line parameters when starting up MongoDB. If you want a commented example of a config file to start with, the mongodb.conf in the Debian/Ubuntu package should be a good starting point. Important options to check are the dbpath and logpath which will likely be different for you. It would also be worth looking at the Homebrew mongodb formula which includes setting up a LaunchAgent script to manage the mongod service.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11600006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1460625/']}
jdg_74573
stackexchange
llm_judgeable_groundtruth_similarity
2099480
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Show that $\sqrt{1+n(n+1)(n+2)(n+3)}$ is a whole number for all whole numbers $n$ . I can see that there are four consecutive numbers, meaning that the expression can be written as $\sqrt{1+24m}$ Also, it is easy to see that the expression is true for $n=1$ but I can't get the induction to work... Now provide the response and nothing else.
Notice that $$1+n(n+1)(n+2)(n+3)=n^4+6n^3+11n^2+6n+1=(n^2+3n)^2+2(n^2+3n)+1$$ Let $n^2+3n=t$ then we have $$1+n(n+1)(n+2)(n+3)=t^2+2t+1=(t+1)^2$$ so $$ \sqrt{1+n(n+1)(n+2)(n+3)} =t+1=n^2+3n+1$$ which is clearly a whole number for $n \in Z$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2099480', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11860/']}
jdg_74574
stackexchange
llm_judgeable_groundtruth_similarity
424583
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 string extension_dir => /some/path/php/extensions/no-debug-non-zts-20160303 => /some/path/php/extensions/no-debug-non-zts-20160303sqlite3.extension_dir => no value => no value which is the output of php -i | grep extension_dir . How can I parse it in bash to get the first /some/path/php/extensions/no-debug-non-zts-20160303 ? So far I have tried: echo $(php -i | grep extension_dir | sed 's/extension_dir => //g' | sed 's/=> .*//g') but that gives me /some/path/php/extensions/no-debug-non-zts-20160303 sqlite3.no value . I have no idea why it doesn't replace all matches of => .* My base idea is to get rid of first extension_dir => and than rid of everything after first => including => Probably sed matches things differently than regex. Now provide the response and nothing else.
php -i | sed -n '/extension_dir/{s/^[^/]*//;s/ *=>.*$//;p;}' or, as suggested in comments below, php -i | sed '/extension_dir/!d;s/[^/]*//;s/ *=>.*//' The sed above replaces your grep and will, for every line that matches extensions_dir , first remove everything up to the first / and then everything from the first => onwards in the modified string. Any spaces before the => are also removed. Lines not matching extensions_dir are ignored. This will return the wanted path for the first line of input, and an empty line for the second. To disregard the second line of input, use /^extension_dir/ instead of /extension_dir/ in the sed above. This will discard the second line since does not start with that string. It's the combination of your two sed scripts that produces the surprising result for the second line of input. The line is sqlite3.extension_dir => no value => no value and the first sed will modify this to sqlite3.no value => no value The second sed will then remove the => no value bit at the end. Note that echo $( ... ) is a bit useless as it gobbles up the newlines in the output of the command inside $( ... ) . Instead test with just the command without the echo or the $( ... ) command substitution. It is possibly this use of echo that has had you confused about the nature of the output from php -i and grep (two matching lines rather than one).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/424583', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/263020/']}
jdg_74575
stackexchange
llm_judgeable_groundtruth_similarity
229335
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there any distribution for two i.i.d. random variables $X,Y$ where the joint distribution of $X-Y$ is uniform over support [0,1]? Now provide the response and nothing else.
No. If $Y$ is ever (with positive probability) $> X$, then $X - Y < 0$, so it can't be $U[0,1]$. If $X$ and $Y$ are iid, $Y$ can not be guaranteed (i.e., with probability $1$) to not be $> X$ unless $X$ and $Y$ are both the same constants with probability 1. In such case $X - Y$ will equal $0$ with probability $1$. Therefore, there exists no iid $X$ and $Y$ such that $X - Y$ is $U[0,1]$.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/229335', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/127336/']}
jdg_74576
stackexchange
llm_judgeable_groundtruth_similarity
34957505
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm creating some modals with Bootstrap . I'm using different div 's as showed in Bootstrap component explanation . What I'm experiencing is that when my screen size is larger than x (mean some unknown value) the div containing my modal-body is pushed up (empty), and the div containing my modal-footer absorb elements on modal-body . This is an image to explain what I'm saying: Normal modal Squeezed modal Code it's the same, just change the screen size. <HTML> <head> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> </head> <body> <div id='modal' class='modal-dialog'> <div class='modal-content'> <div class='modal-header'> <button type='button' class='close' data-dismiss='modal' aria-label='Close'> <span aria-hidden='true'>&times;</span> </button> <h4 class='modal-title'>Change name</h4> </div> <div class='modal-body'> <form id='formModal' method='post' action='giocatori.php'> <div class='form-group col-md-12'> <label>Name</label> <input id='nome_iscrizione' type='text' class='form-control' name='name' value='New name'> </div> </form> </div> <div class='modal-footer'> <button type='button' class='btn btn-default' data-dismiss='modal'>Chiudi</button> <button type='button' class='btn btn-primary'>Salva</button> </div> </div> </div> </body></HTML> If you want experience the squeezed modal, run the snippet and then press on Full page button. How can I avoid squeezed body? Now provide the response and nothing else.
Bootstrap's column classes are designed to be used with row classes, and not combined with other elements/classes. The row and column classes work together to ensure floats get cleared. Try this: <HTML><head> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" /></head><body> <div id='modal' class='modal-dialog'> <div class='modal-content'> <div class='modal-header'> <button type='button' class='close' data-dismiss='modal' aria-label='Close'> <span aria-hidden='true'>&times;</span> </button> <h4 class='modal-title'>Change name</h4> </div> <div class='modal-body'> <form id='formModal' method='post' action='giocatori.php'> <!-- use a row class --> <div class='row'> <!-- keep the col class by itself --> <div class='col-md-4'> <div class='form-group'> <label>Name</label> <input id='nome_iscrizione' type='text' class='form-control' name='name' value='New name'> </div> </div> </div> </form> </div> <div class='modal-footer'> <button type='button' class='btn btn-default' data-dismiss='modal'>Chiudi</button> <button type='button' class='btn btn-primary'>Salva</button> </div> </div> </div></body></HTML>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34957505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4378982/']}
jdg_74577
stackexchange
llm_judgeable_groundtruth_similarity
39975676
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 Parametric Rectified Linear Unit (PReLU) is an interesting and widely used activation function. It seems that Tensorflow ( reference link ) does not provide PReLU. I know that the higher level libraries, such as Keras and TFLearn , has the implementation of it. I would like to know how to implement PReLU in Tensorflow ? Now provide the response and nothing else.
The implementation of PReLU seems straight-forward based on the PreLU implementations (see: Keras , TFLearn and TensorLayer ) of the higher level libraries. My code is as follows: def parametric_relu(_x): alphas = tf.get_variable('alpha', _x.get_shape()[-1], initializer=tf.constant_initializer(0.0), dtype=tf.float32) pos = tf.nn.relu(_x) neg = alphas * (_x - abs(_x)) * 0.5 return pos + neg
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39975676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3930957/']}
jdg_74578
stackexchange
llm_judgeable_groundtruth_similarity
12683364
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 DelayedJob docs mention hooks, including an error hook, but only in the context of custom Job subclasses. This similar question (with no answers) says adding the same hook to the mailer class did not work. What's the trick? Update: In general, I'd like to see how to add hooks to jobs that are triggered using the object.delay.action() syntax, where I don't see an obvious link to a ____Job class. Now provide the response and nothing else.
I was just searching for a solution to this problem too, and I found this gist . I don't know where it comes from (found it on Google), but well, it seems to do the job pretty well, is quite simple, and seems to follow a DelayedJob's plugin system I was not even aware of... Here is a lightly improved one using parts of previous monkey-patch code: # https://gist.github.com/2223758# modifiedmodule Delayed module Plugins class Airbrake < Plugin module Notify def error(job, error) ::Airbrake.notify_or_ignore( :error_class => error.class.name, :error_message => "#{error.class.name}: #{error.message}", :parameters => { :failed_job => job.inspect, } ) super if defined?(super) end end callbacks do |lifecycle| lifecycle.before(:invoke_job) do |job| payload = job.payload_object payload = payload.object if payload.is_a? Delayed::PerformableMethod payload.extend Notify end end end endendDelayed::Worker.plugins << Delayed::Plugins::Airbrake It will add the error's message and payload so that it's available in Airbrake.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12683364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311901/']}
jdg_74579
stackexchange
llm_judgeable_groundtruth_similarity
6738762
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 some cases of HTML cleaning, I would like to retain the text enclosed between the tags(which is the default behaviour of Jsoup) and in some cases, I would like to remove the text as well as the HTML tags. Can someone please throw some light on how I can remove the text enclosed between the HTML tags using Jsoup? Now provide the response and nothing else.
The Cleaner will always drop tags and preserve text. If you need to drop elements (i.e. tags and text / nested elements), you can pre-parse the HTML, remove the elements using either remove() or empty() , then run the resulting through the cleaner. For example: String html = "Clean <div>Text dropped</div>";Document doc = Jsoup.parse(html);doc.select("div").remove();// if not removed, the cleaner will drop the <div> but leave the inner textString clean = Jsoup.clean(doc.body().html(), Whitelist.basic()); If you are using JSoup 1.14.1+ then use Safelist instead of Whitelist , as Whitelist has been deprecated and will be removed in 1.15.1. String clean = Jsoup.clean(doc.body().html(), Safelist.basic());
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6738762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/702813/']}
jdg_74580
stackexchange
llm_judgeable_groundtruth_similarity
17155536
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 FluentValidation for the server side validation. Now I have had it call a function before with Must validation: RuleFor(x => x.UserProfile).Must(ValidateProfile).WithMessage("We are sorry, you have already logged on " + DateTime.Now + ". Please come again tomorrow."); Now, that works because the only parameter that validateProfile takes is UserProfile. it is all good. My problem now is that I am trying to have a function with two parameters validate the data.The function which I am trying to use for validation looks like below: bool IsValid(string promocode, IUserProfile userProfile) Now, I am not sure how to bind IsValid to a fluentValidation. Any ideas? Now provide the response and nothing else.
Where is promocode coming from? The Must method has overloads accepting Func<TProp,bool> , Func<T,TProp,bool> , and Func<T,TProp, PropertyValidatorContext, bool> If promocode is a property of the object being validated, it would be easy to pass something like .RuleFor(x => x.UserProfile).Must( (o, userProfile) => { return IsValid(o.promoCode, userProfile); })
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17155536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/280772/']}
jdg_74581
stackexchange
llm_judgeable_groundtruth_similarity
2173797
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 2d array, dimension 3x10, and I want to sort by values in 2nd row, from lowest to highest value. Now provide the response and nothing else.
Python, per se, has no "2d array" -- it has (1d) lists as built-ins, and (1d) arrays in standard library module array . There are third-party libraries such as numpy which do provide Python-usable multi-dimensional arrays, but of course you'd be mentioning such third party libraries if you were using some of them, rather than just saying "in Python", right ?-) So I'll assume that by "2d array" you mean a list of lists, such as: lol = [ range(10), range(2, 12), range(5, 15) ] or the like -- i.e. a list with 3 items, each item being a list with 10 items, and the "second row" would be the sublist item lol[1] . Yeah, lots of assumptions, but your question is so maddeningly vague that there's no way to avoid making assumptions - edit your Q to clarify with more precision, and an example!, if you dislike people trying to read your mind (and probably failing) as you currently make it impossible to avoid. So under these assumptions you can sort each of the 3 sublists in the order required to sort the second one, for example: indices = range(10)indices.sort(key = lol[1].__getitem__)for i, sublist in enumerate(lol): lol[i] = [sublist[j] for j in indices] The general approach here is to sort the range of indices, then just use that appropriately sorted range to reorder all the sublists in play. If you actually have a different problem, there will of course be different solutions;-).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2173797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257522/']}
jdg_74582
stackexchange
llm_judgeable_groundtruth_similarity
21858311
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 cast an array of floats int the form float* to glm::vec3 ? I thought I had done it before but I lost my hdd. I tried a few C-style and static_cast s but I can't seem to get it working. Now provide the response and nothing else.
The glm documentation tells you how to cast from vec3 to a float* . #include <glm/glm.hpp>#include <glm/gtc/type_ptr.hpp>glm::vec3 aVector(3);glm::mat4 someMatrix(1.0);glUniform3fv(uniformLoc, 1, glm::value_ptr(aVector));glUniformMatrix4fv(uniformMatrixLoc, 1, GL_FALSE, glm::value_ptr(someMatrix)); You use glm::value_ptr . The documentation doesn't say this explicitly, however it seems clear that glm intends these types to be 'layout compatible' with arrays, so that they can be used directly with OpenGL functions. If so then you can cast from an array to vec3 using the following cast: float arr[] = { 1.f, 0.f, 0.f };vec3<float> *v = reinterpret_cast<vec3<float>*>(arr); You should probably wrap this up in your own utility function because you don't want to be scattering this sort of cast all over your codebase.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21858311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1055947/']}
jdg_74583
stackexchange
llm_judgeable_groundtruth_similarity
430726
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: "Real-life" motivation. The German satirical magazine Der Postillon suggested a few measures for deterring smokers from their bad habit. I especially liked the idea of inserting one "prank cigarette" per pack, giving the smoker a reminder in form of a (mild) explosion after lighting it. This motivated the following problem. Problem statement. Suppose we are given $n$ empty packs of cigarettes, each to be filled with $n$ cigarettes. Amongst the $n^2$ cigarettes in total to be distributed to the $n$ empty packs, there are $n$ "prank cigarettes" to be distributed in a uniform manner into the $n$ packs. Questions. Let $M_n$ be the expected value of the maximum number of prank cigarettes any pack receives. Is there an explicit formula for $M_n$ ? If not, do we have $\lim\sup_{n\to\infty}M_n/n > 0$ or $\lim\sup_{n\to\infty}M_n/\log(n) > 0$ ? Let $E_n$ be the expected value of packs without any prank cigarettes. Is there an explicit formula for $E_n$ ? If not, do we have $\lim\sup_{n\to\infty}E_n/n > 0$ or $\lim\sup_{n\to\infty}E_n/\log(n) > 0$ ? Now provide the response and nothing else.
$\newcommand{\Si}{\Sigma}$ Let $X_n$ be the maximum number of prank cigarettes any pack receives, so that $M_n=EX_n$ . Note that $X_n=\max(N_1,\dots,N_n)$ , where $(N_1,\dots,N_n)$ has the multinomial distribution with parameters $n;\frac1n,\dots,\frac1n$ . So, by Theorem 1 or formula (6) of Raab and Steger , \begin{equation*} X_n\sim r_n:=\frac{\ln n}{\ln\ln n} \tag{1}\label{1}\end{equation*} in probability (as $n\to\infty$ ). We will also prove Proposition 1: \begin{equation*} EX_n^2\ll r_n^2. \end{equation*} (As usual, we write $A\ll B$ to mean $A=O(B)$ .) By Proposition 1 and the de la Vallée-Poussin theorem , $X_n/r_n$ is uniformly integrable, which implies \begin{equation*}M_n=EX_n\sim r_n \end{equation*} (which agrees with Qiaochu Yuan's heuristics/conjecture). Proof of Proposition 1: Let $[n]:=\{1,\dots,n\}$ . Note that \begin{equation*} EX_n^2\ll\sum_{m\in[n]}mP(X_n\ge m)=\Si_1+\Si_2, \tag{3}\label{3}\end{equation*} where \begin{equation*} \Si_1:=\sum_{1\le m\le 4r_n}mP(X_n\ge m),\quad \Si_2:=\sum_{4r_n<m\le n}mP(X_n\ge m). \tag{4}\label{4}\end{equation*} It is easy to bound $\Si_1$ : \begin{equation} \Si_1\le\sum_{1\le m\le 4r_n}m\ll r_n^2. \tag{5}\label{5}\end{equation} Let us now bound $\Si_2$ .Recall that $X_n=\max(N_1,\dots,N_n)$ , where $(N_1,\dots,N_n)$ has the multinomial distribution with parameters $n;\frac1n,\dots,\frac1n$ . Note that for each $m\in[n]$ \begin{equation*} P(X_n\ge m)\le\sum_{i\in[n]}P(N_i\ge m) =nP(N_1\ge m). \tag{7}\label{7}\end{equation*} Next, $N_1$ has the binomial distribution with parameters $n$ and $\frac1n$ , and hence \begin{equation*}\begin{aligned} P(N_1\ge m)&=\sum_{k=m}^n\binom nk\frac1{n^k}\Big(1-\frac1n\Big)^{n-k} \\ &\le\sum_{k=m}^n\binom nk\frac1{n^k}\le\sum_{k=m}^n\frac1{k!}\ll\frac1{m!}. \end{aligned}\tag{11}\label{11}\end{equation*} Further, for $m>4r_n$ , eventually (that is, for all large enough $n$ ), \begin{equation*} m!\ge(m/e)^m=\exp(m\ln(m/e)) \\ \ge\exp\Big(4\frac{\ln n}{\ln\ln n}\,\ln\frac{\ln n}{\ln\ln n}\Big)\ge n^3. \tag{13}\label{13}\end{equation*} So, by \eqref{4}, \eqref{7}, \eqref{11}, and \eqref{13}, \begin{equation*} \Si_2\le\sum_{4r_n<m\le n}mnP(N_1\ge m) \\ \ll\sum_{4r_n<m\le n}mn\frac1{n^3}\le1\ll r_n^2. \tag{15}\label{15}\end{equation*} Now Proposition 1 follows immediately from \eqref{3}, \eqref{5}, and \eqref{15}. $\quad\Box$ Quite similarly one can show that \begin{equation*}EX_n^p\sim r_n^p \end{equation*} for each real $p>0$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/430726', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']}
jdg_74584
stackexchange
llm_judgeable_groundtruth_similarity
25739717
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 Symfony I'm using default ORM Doctrine, but this tool can't give me enough methods to manipulate with different cases. I want to write my own classes and using something like DBAL, just for connections making custom SQL queries and fetch the result. Who can give me some examples? Which classes I should use to make my model layer, extend my functionality. Now provide the response and nothing else.
I spent a lot of time to find the answer to this question. So, i'm happy to help you. 1) Change your ExternalLogin method.It usually looks like: if (hasRegistered){ Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);} Now, actually, it is necessary to add refresh_token. Method will look like this: if (hasRegistered){ Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); // ADD THIS PART var ticket = new AuthenticationTicket(oAuthIdentity, properties); var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket); Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext( Request.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket); await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context); properties.Dictionary.Add("refresh_token", context.Token); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);} Now the refrehs token will be generated. 2) There is a problem to use basic context.SerializeTicket in SimpleRefreshTokenProvider CreateAsync method. Message from Bit Of Technology Seems in the ReceiveAsync method, the context.DeserializeTicket is not returning an Authentication Ticket at all in the external login case. When I look at the context.Ticket property after that call it’s null. Comparing that to the local login flow, the DeserializeTicket method sets the context.Ticket property to an AuthenticationTicket. So the mystery now is how come the DeserializeTicket behaves differently in the two flows. The protected ticket string in the database is created in the same CreateAsync method, differing only in that I call that method manually in the GenerateLocalAccessTokenResponse, vs. the Owin middlware calling it normally… And neither SerializeTicket or DeserializeTicket throw an error… So, you need to use Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer to searizize and deserialize ticket. It will be look like this: Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();token.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket)); instead of: token.ProtectedTicket = context.SerializeTicket(); And for ReceiveAsync method: Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();context.SetTicket(serializer.Deserialize(System.Text.Encoding.Default.GetBytes(refreshToken.ProtectedTicket))); instead of: context.DeserializeTicket(refreshToken.ProtectedTicket); 3) Now you need to add refresh_token to ExternalLogin method response.Override AuthorizationEndpointResponse in your OAuthAuthorizationServerProvider. Something like this: public override Task AuthorizationEndpointResponse(OAuthAuthorizationEndpointResponseContext context){ var refreshToken = context.OwinContext.Authentication.AuthenticationResponseGrant.Properties.Dictionary["refresh_token"]; if (!string.IsNullOrEmpty(refreshToken)) { context.AdditionalResponseParameters.Add("refresh_token", refreshToken); } return base.AuthorizationEndpointResponse(context);} So.. thats all! Now, after calling ExternalLogin method, you get url: https://localhost:44301/Account/ExternalLoginCallback?access_token=ACCESS_TOKEN&token_type=bearer&expires_in=300&state=STATE&refresh_token=TICKET&returnUrl=URL I hope this helps)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25739717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3937796/']}
jdg_74585
stackexchange
llm_judgeable_groundtruth_similarity
36149241
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 trying to continuously print dots at the end of a line as a form of indeterminate progress, while a large list of Tasks are running, with this code: start = DateTime.Now;Console.Write("*Processing variables");Task entireTask = Task.WhenAll(tasks);Task progress = new Task(() => { while (!entireTask.IsCompleted) { Console.Write("."); System.Threading.Thread.Sleep(1000); } });progress.Start();entireTask.Wait();timeDiff = DateTime.Now - start;Console.WriteLine("\n*Operation completed in {0} seconds.", timeDiff.TotalSeconds); Where tasks is from List<Task> tasks = new List<Task>(); , and tasks.Add(Task.Run(() => someMethodAsync())); has occurred 10000's of times. This code currently works, however, is this the correct way of accomplishing this, and is this the most cost-effective way? Now provide the response and nothing else.
There are certainly several ways this can be solved and one of them is yours. However it is not really a good practice to start long running tasks especially when they do nothing than synchronous waiting (that is Thread.Sleep). You should consider refactoring your code in a technical and a domain part. The technical part is: Wait until all Tasks in a given collection have completed If that takes longer do regular progress reports The following code might help to understand this a bit better. It starts four tasks which simulate different async operations and waits for all of them to complete. If this takes longer than 250ms the call of WhenAllEx keeps on calling a lambda for reoccuring progress report. static void Main(string[] args){ var tasks = Enumerable.Range(0, 4).Select(taskNumber => Task.Run(async () => { Console.WriteLine("Task {0} starting", taskNumber); await Task.Delay((taskNumber + 1) * 1000); Console.WriteLine("Task {0} stopping", taskNumber); })).ToList(); // Wait for all tasks to complete and do progress report var whenAll = WhenAllEx( tasks, _ => Console.WriteLine("Still in progress. ({0}/{1} completed)", _.Count(task => task.IsCompleted), tasks.Count())); // Usually never wait for asynchronous operations unless your in Main whenAll.Wait(); Console.WriteLine("All tasks finished"); Console.ReadKey();}/// <summary>/// Takes a collection of tasks and completes the returned task when all tasks have completed. If completion/// takes a while a progress lambda is called where all tasks can be observed for their status./// </summary>/// <param name="tasks"></param>/// <param name="reportProgressAction"></param>/// <returns></returns>public static async Task WhenAllEx(ICollection<Task> tasks, Action<ICollection<Task>> reportProgressAction){ // get Task which completes when all 'tasks' have completed var whenAllTask = Task.WhenAll(tasks); for (; ; ) { // get Task which completes after 250ms var timer = Task.Delay(250); // you might want to make this configurable // Wait until either all tasks have completed OR 250ms passed await Task.WhenAny(whenAllTask, timer); // if all tasks have completed, complete the returned task if (whenAllTask.IsCompleted) { return; } // Otherwise call progress report lambda and do another round reportProgressAction(tasks); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36149241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4158169/']}
jdg_74586
stackexchange
llm_judgeable_groundtruth_similarity
28270714
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 update my website, it hints me this problem "{"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated."}" The screenshot is list below, there is a value named RecordDate, it has value, but I will not change anything about that value so I didn't display it on the screen. The problem is MVC automatically update that value for me, and the value of the date becomes 0000-00-01 i think, maybe something else, how to prevent it? just keep the origin value and update other columns. The model class looks like this public class ShiftRecord{ public int ID { get; set; } public int EmployeeID { get; set; } [Display(Name="Company Vehicle?")] [UIHint("YesNo")] public bool IsCompanyVehicle { get; set; } [Display(Name="Own Vehicle?")] [UIHint("YesNo")] public bool IsOwnVehicle { get; set; } //Problem comes from this line [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString="{0:yyyy-MM-dd}")] public DateTime RedordDate { get; set; } [Display(Name="Day Type")] public Nullable<DayType> DayType { get; set; } [Display(Name="Normal Hrs")] public Nullable<int> NormalHours { get; set; } [Display(Name="Time and Half Hrs")] public Nullable<int> TimeAndHalfHours { get; set; } [Display(Name="Double Time Hrs")] public Nullable<int> DoubleTimeHours { get; set; } [Display(Name="Shift Hrs")] public Nullable<int> ShiftHours { get; set; } public string Comment { get; set; } // System manager can leave any comment here public bool IsRead { get; set; } // has this shift record been read public virtual Employee Employee { get; set; } public virtual ICollection<JobRecord> JobRecords { get; set; }} In the controller, I didn't change anything about the model, so it looks like this: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([Bind(Include = "ID,EmployeeID,IsCompanyVehicle,IsOwnVehicle,RecordDate,DayType,NormalHours,TimeAndHalfHours,DoubleTimeHours,ShiftHours,Comment,IsRead")] ShiftRecord shiftrecord) { if (ModelState.IsValid) { db.Entry(shiftrecord).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.EmployeeID = new SelectList(db.Employees, "ID", "LastName", shiftrecord.EmployeeID); return View(shiftrecord); } And I didn't change Edit view as well, the only thing is I made RecordDate unchangeable, changed it from @Html.EditorFor to @Html.DisplayFor <div class="form-group"> @Html.LabelFor(model => model.RedordDate, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DisplayFor(model => model.RedordDate) @Html.ValidationMessageFor(model => model.RedordDate) </div> </div> Now provide the response and nothing else.
Use or_() and like() , the following code should satisfy your need well: from sqlalchemy import or_foo = ['a%', 'b%']DBSession().query(MyTable).filter(or_(*[MyTable.my_column.like(name) for name in foo])) A where condition WHERE my_column LIKE 'a%' OR my_column LIKE 'b%' would be generated from above code. As for why your any() didn't work, I think it's because it requires my_column to be a list (see here ), and, for instance, query(MyTable).filter(MyTable.my_list_column.any(name='abc')) is to return MyTable rows if any element in my_list_column column (a list) of that row is named with 'abc', so it's actually quite different from your need.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28270714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3936113/']}
jdg_74587
stackexchange
llm_judgeable_groundtruth_similarity
10076579
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 starting to learn Ruby (first time programming), and have a basic syntactical question with regards to variables, and various ways of writing code. Chris Pine's "Learn to Program" taught me to write a basic program like this... num_cars_again= 2puts 'I own ' + num_cars_again.to_s + ' cars.' This is fine, but then I stumbled across the tutorial on ruby.learncodethehardway.com, and was taught to write the same exact program like this... num_cars= 2puts "I own #{num_cars} cars." They both output the same thing, but obviously option 2 is a much shorter way to do it. Is there any particular reason why I should use one format over the other? Now provide the response and nothing else.
Whenever TIMTOWTDI (there is more than one way to do it), you should look for the pros and cons. Using "string interpolation" (the second) instead of "string concatenation" (the first): Pros: Is less typing Automatically calls to_s for you More idiomatic within the Ruby community Faster to accomplish during runtime Cons: Automatically calls to_s for you (maybe you thought you had a string, and the to_s representation is not what you wanted, and hides the fact that it wasn't a string) Requires you to use " to delimit your string instead of ' (perhaps you have a habit of using ' , or you previously typed a string using that and only later needed to use string interpolation)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10076579', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1181898/']}
jdg_74588
stackexchange
llm_judgeable_groundtruth_similarity
10591243
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Similar to python: make a variable equal an operator (+,/,*,-) I've got a bit of code where the user can pick a type of comparison to be run, and a value to compare against. I'm curious to know if there's any way in Javascript to turn that user provided comparison value into an actual comparison, allowing me to do something like: if (user_val user_comparison other_val) { do_something();} Instead of having to do something like: if (user_comparison = '<') { if (user_val < other_val) { do_something(); }else if (user_comparison = '<=') { if (user_val <= other_val) { do_something(); }....etc Note that should any of the comparisons be matched, the same code will be executed. Now provide the response and nothing else.
No that is not possible. But you can structure your code in a better way. For example you can have a lookup table: var operator_table = { '>': function(a, b) { return a > b; }, '<': function(a, b) { return a < b; } // ...}; and later: if(operator_table[user_comparison](user_val, other_val)) { // do something} Of course you should also handle the case when user_comparison does not exist in the table. These also gives you a better control over allowed and not allowed operators. Here is a DEMO create by @Jesse .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10591243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/898743/']}
jdg_74589
stackexchange
llm_judgeable_groundtruth_similarity
1867
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My research group focuses on molecular dynamics, which obviously can generate gigabytes of data as part of a single trajectory which must then be analyzed. Several of the problems we're concerned with involve correlations in the data set, which means that we need to keep track of large amounts of data in memory and analyze them, rather than using a more sequential approach. What I'd like to know is what are the most efficient strategies for handling I/O of large data sets into scripts. We normally use Python-based scripts because it makes coding the file I/O much less painful than C or Fortran, but when we have tens or hundreds of millions of lines that need to be processed, it's not so clear what the best approach is. Should we consider doing the file input part of the code in C, or is another strategy more useful? (Will simply preloading the entire array into memory be better than a series of sequential reads of "chunks" (order of megabytes)? Some additional notes: We are primarily looking for scripting tools for post-processing, rather than "on-line" tools—hence the use of Python. As stated above, we're doing MD simulations. One topic of interest is diffusion calculations, for which we need to obtain the Einstein diffusion coefficient:$$D = \frac{1}{6} \lim_{\Delta t \rightarrow \infty} \left< \left( {\bf x}(t + \Delta t) - {\bf x}(t) \right)^2 \right>$$This means we really need to load all of the data into memory before beginning the calculation—all of the chunks of data (records of individual times) will interact with one another. Now provide the response and nothing else.
I'm assuming your question comes from the observation that the I/O causes a significant overhead in your whole analysis. In that case, you can try to overlap I/O with computation. A successful approach depends on how you access the data, and the computation you perform on that data. If you can identify a pattern, or the access to different regions of the data is known beforehand, you can try to prefetch the "next chunks" of data in the background while processing the "current chunks". As a simple example, if you only traverse your file once and process each line or set of lines, you can divide the stream in chunks of lines (or MBs). Then, at each iteration over the chunks, you can load chunk i+1 while processing chunk i. Your situation may be more complex and need more involved solutions. In any case, the idea is to perform the I/O in the background while the processor has some data to work on. If you give more details on your specific problem, we may be able to take a deeper look into it ;) ---- Extended version after giving more details ---- I'm not sure I understand the notation, but well, as you said, the idea is an all-to-all interaction. You also mention that the data may fit in RAM. Then, I would start by measuring the time to load all the data and the time to perform the computation. Now, if the percent of the I/O is low (low as in you don't care about the overhead, whatever it is: 0.5%, 2%, 5%, ...), then just use the simple approach: load data at once, and compute. You will save time for more interesting aspects of your research. if you cannot afford the overhead you may want to look into what Pedro suggested. Keep in mind what Aron Ahmadia mentioned, and test it before going for a full implementation. if the previous are not satisfactory, I would go for some out-of-core implementation[1]. Since it seems that you are performing $n^2$ computations on $n$ data, there is hope :) Some pseudocode (assuming the results of your analysis fit in RAM): load chunk1 and chunk2 for chunks i = 1 to n asynchronously load chunk i+1 for chunks in j = i+1 to n asynchronously load chunk j+1 compute with chunks i, j (* for the first iteration, these are the preloaded chunks 1 and 2 *) Note: this is quick and dirty pseudocode, one would need to adjust the indices. To implement this, it is common to use the so-called double-buffering . Roughly speaking: divide memory in two workspaces; while data is being loaded in the background into workspace 1, processor is computing with the data in workspace 2. At each iteration, exchange the role. I am sorry I cannot come up with a good reference right now. [1] An out-of-core algorithm incorporates some mechanism to (efficiently) deal with data residing on disk. They are called out-of-core as opposed to in-core ("in-RAM").
{}
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/1867', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/348/']}
jdg_74590
stackexchange
llm_judgeable_groundtruth_similarity
51412529
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this question: When i use: async function createElement(req,res){ const time1 = new Date().getTime(); console.log("turn on time 1 ",time1) await new Promise((resolve) => setTimeout(resolve,1000)); await new Promise((resolve) => setTimeout(resolve,1000)); const time2 = new Date().getTime(); console.log("turn on time 2 ",time2) console.log('result : ', time2 - time1);} the result is: turn on time 1 1531957505408turn on time 2 1531957507413result : 2005 and is fine, but when i try use promise.all with await async function createElement(req,res){let fn1 = () => { new Promise((resolve) => { setTimeout(() => { console.log("message from fn1") resolve() },1000) });}let fn2 = () => { new Promise((resolve) => { setTimeout(() => { console.log("message from fn2") resolve() },1000) });}const time1 = new Date().getTime();console.log("turn on time 1 ",time1)let responses = await Promise.all([fn1(),fn2()])console.log("waiting for responses")const time2 = new Date().getTime();console.log("turn on time 2 ",time2)console.log('result : ', time2 - time1);} the result is: turn on time 1 1531957505408turn on time 2 1531957505408result 0message from fn1message from fn2 so... in the case that i need the result to fn1 or/and fn2 for other operation, how i can to wait the response to promise.all Now provide the response and nothing else.
I might be a little late to the party here, but I've come across the same issue and found that the AzureAD authentication middleware is very sparsely documented. Adding the solution here for others struggling with the same question. As you can see at the bottom of the code snippet in the question, the AzureAD provider actually relies on OpenIdConnect and Cookie auth providers under the hoods, and does not implement any authentication logic itself. To accomplish this, two additional authentication schemes are added, using the names defined as AzureADDefaults.OpenIdScheme and AzureADDefaults.CookieScheme , respectively. (Although the names can also be customized when using the AddAzureAD(this Microsoft.AspNetCore.Authentication.AuthenticationBuilder builder, string scheme, string openIdConnectScheme, string cookieScheme, string displayName, Action<Microsoft.AspNetCore.Authentication.AzureAD.UI.AzureADOptions> configureOptions) overload). That, in turn, allows to configure the effective OpenIdConnectOptions and CookieAuthenticationOptions by using the scheme names from above, including access to OpenIdConnectEvents . See this complete example: services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => Configuration.Bind("AzureAd", options)); services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => { options.Events = new OpenIdConnectEvents { OnRedirectToIdentityProvider = async ctxt => { // Invoked before redirecting to the identity provider to authenticate. This can be used to set ProtocolMessage.State // that will be persisted through the authentication process. The ProtocolMessage can also be used to add or customize // parameters sent to the identity provider. await Task.Yield(); }, OnMessageReceived = async ctxt => { // Invoked when a protocol message is first received. await Task.Yield(); }, OnTicketReceived = async ctxt => { // Invoked after the remote ticket has been received. // Can be used to modify the Principal before it is passed to the Cookie scheme for sign-in. // This example removes all 'groups' claims from the Principal (assuming the AAD app has been configured // with "groupMembershipClaims": "SecurityGroup"). Group memberships can be checked here and turned into // roles, to be persisted in the cookie. if (ctxt.Principal.Identity is ClaimsIdentity identity) { ctxt.Principal.FindAll(x => x.Type == "groups") .ToList() .ForEach(identity.RemoveClaim); } await Task.Yield(); }, }; }); services.Configure<CookieAuthenticationOptions>(AzureADDefaults.CookieScheme, options => { options.Events = new CookieAuthenticationEvents { // ... }; });
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51412529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8452960/']}
jdg_74591
stackexchange
llm_judgeable_groundtruth_similarity
15861424
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Redis recommends a method of using SET with optional parameters as a locking mechanism. I.e. SET lock 1 EX 10 NX will set a lock only if it does not already exists and it will expire after 10 second. I'm using Node Redis, which has a set() method, but I'm not sure how to pass it the additional parameters to have the key expire and not be created if it already exists, or even if it's possible. Perhaps I have to use setnx() and expire() as separate calls? Now provide the response and nothing else.
After reading the Node Redis source code, I found that all methods accept an arbitrary number of arguments. When an error about incorrect number of arguments is generated, this is generated by Redis not the node module. My early attempts to supply multiple arguments were because I only had Redis 2.2.x installed, where SET only accepts the NX and EX arguments with 2.6.12. So with Redis 2.6.12 installed, the follow method calls will work with node redis to set a variable if it doesn't exist and set it to expire after 5 minutes: $client->set('hello', 'world', 'NX', 'EX', 300, function(err, reply) {...});$client->set(['hello', 'world', 'NX', 'EX', 300], function(err, reply) {...});
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15861424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2045006/']}
jdg_74592
stackexchange
llm_judgeable_groundtruth_similarity
45539709
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 code below doesn't allow the API user to update only one field by passing one request property. I can remove the null at userObj , but the UI developer will have to pass existing data from the database to do an update, which is not the best practice. Here is my Express route: router.put('/user', (req, res) => { const userObj = { name: req.body.name || null, location: { city: req.body.city || null }, phone: req.body.phone || null }; User.updateUser(req.body.id, userObj)}); Here is my Mongoose model's updateUser function: module.exports.updateUser = (_id, userObj, callback) => { User.findOneAndUpdate({_id}, userObj, { upsert: true, 'new': true }, callback);} Now provide the response and nothing else.
First, to address your issue with updating only a few certain properties, you have to use the $set operator to set only a certain field. When you pass userObj directly to findOneAndUpdate you reset the whole object thus you have to pass all the existing properties. Use $set : User.findOneAndUpdate({_id}, { $set: userObj }, { upsert: true, new: true }, callback); This will update only the properties defined in userObj to their new values and touch nothing else. Also, you could just use findByIdAndUpdate for this very use-case: User.findByIdAndUpdate(_id, { $set: userObj }, { upsert: true, new: true }, callback); Next, you shouldn't be using PUT. Use PATCH. PUT implies putting a resource at some URL, and replacing it entirely if it already exists. PATCH means you update only a few properties of a resource, and does replace the whole thing. This won't affect the app's functionality, but it's a huge semantics issue and end-user issue as they'd expect PATCH.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45539709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8287198/']}
jdg_74593
stackexchange
llm_judgeable_groundtruth_similarity
20560521
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 text file that has date/time, name, amount tipped, total tips I am able to get it reduced to just names (In one arraylist) and amount tipped(in a second arraylist) Now I'm trying to get it to where it adds up the amount tipped per person. So if X tipped 10,20,30,40 it will output X tipped 100. From Text file Dec. 6, 2013, 8:31 p.m. Tip from y25 7687Dec. 6, 2013, 8:30 p.m. Tip from x30 7662Dec. 6, 2013, 8:30 p.m. Tip from z25 7632Dec. 6, 2013, 8:31 p.m. Tip from z25 7687Dec. 6, 2013, 8:30 p.m. Tip from z30 7662Dec. 6, 2013, 8:30 p.m. Tip from x25 7632 Here is where I am at so far import java.io.*;import java.util.*;public class TipTester {public static void main(String[] args) { int lineNumber = 1; List<String> name = new ArrayList<String>(); List<String> tip = new ArrayList<String>(); String fileName = "C:\\Users\\David\\Desktop\\tips.txt"; System.out.println("Reading text from file"); try { FileReader inputFile = new FileReader(fileName); BufferedReader bufferedReader = new BufferedReader(inputFile); String line; while ((line = bufferedReader.readLine()) != null) { if (lineNumber % 2 != 0) { System.out.println(line.substring(line.indexOf("from ") + 5) + "\\"); name.add(line.substring(line.indexOf("from ") + 5) + "\\"); } else { System.out.println(line.substring(0, line.indexOf("\t")) + "\\"); tip.add(line.substring(0, line.indexOf("\t")) + "\\"); } lineNumber ++; } bufferedReader.close(); name.add("-"); tip.add("-"); } catch (Exception e) { System.out.println("Error while reading file line by line: " + e.getMessage()); } }} Now provide the response and nothing else.
I'm gonna have another shot at this question and actually show you how to do this properly with WPF. Be warned though, if you've never done any WPF before then this might be a bit overwhelming at first, but hopefully it should give some idea of just how data-driven WPF is and how powerful it can be once you get the hang of it. First you'll need to create a WPF project and run NuGet package manager to add the MVVM Light package (or add it manually if you prefer). Next you'll want to set up a couple of enums to define your piece type and a class to represent an actual instance of a piece on the board: public enum PieceType{ Pawn, Rook, Knight, Bishop, Queen, King}public enum Player{ White, Black}public class ChessPiece : ViewModelBase{ private Point _Pos; public Point Pos { get { return this._Pos; } set { this._Pos = value; RaisePropertyChanged(() => this.Pos); } } private PieceType _Type; public PieceType Type { get { return this._Type; } set { this._Type = value; RaisePropertyChanged(() => this.Type); } } private Player _Player; public Player Player { get { return this._Player; } set { this._Player = value; RaisePropertyChanged(() => this.Player); } }} Almost everything else from here on is done in XAML. First you need to create a checkerboard brush for the board itself, this can be a bitmap if you like but I'll go ahead and create a geometry drawing instead. This code needs to be placed in your Window.Resources section: <DrawingBrush x:Key="Checkerboard" Stretch="None" TileMode="Tile" Viewport="0,0,2,2" ViewportUnits="Absolute"> <DrawingBrush.Drawing> <DrawingGroup> <GeometryDrawing Brush="Tan"> <GeometryDrawing.Geometry> <RectangleGeometry Rect="0,0,2,2" /> </GeometryDrawing.Geometry> </GeometryDrawing> <GeometryDrawing Brush="Brown"> <GeometryDrawing.Geometry> <GeometryGroup> <RectangleGeometry Rect="0,0,1,1" /> <RectangleGeometry Rect="1,1,1,1" /> </GeometryGroup> </GeometryDrawing.Geometry> </GeometryDrawing> </DrawingGroup> </DrawingBrush.Drawing> </DrawingBrush> Next up you'll need a way to select an image based on the piece you're rendering. There are many ways to do this but the way I'm going to do it here is to declare an Image style and then use triggers that select the appropriate bitmap based on the piece type and player. For this example I'll just hot-link to some clip-art on the wpclipart site. This block of XAML is long but it's just doing the same thing for each piece type: <Style x:Key="ChessPieceStyle" TargetType="{x:Type Image}"> <Style.Triggers> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Pawn}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.White}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_pawn_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Rook}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.White}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_rook_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Knight}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.White}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_knight_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Bishop}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.White}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_bishop_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Queen}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.White}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_queen_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.King}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.White}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_white_king_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Pawn}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.Black}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_pawn_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Rook}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.Black}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_rook_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Knight}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.Black}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_knight_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Bishop}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.Black}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_bishop_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.Queen}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.Black}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_queen_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> <MultiDataTrigger> <MultiDataTrigger.Conditions> <Condition Binding="{Binding Type}" Value="{x:Static local:PieceType.King}"/> <Condition Binding="{Binding Player}" Value="{x:Static local:Player.Black}"/> </MultiDataTrigger.Conditions> <MultiDataTrigger.Setters> <Setter Property="Image.Source" Value="http://www.wpclipart.com/recreation/games/chess/chess_set_1/chess_piece_black_king_T.png" /> </MultiDataTrigger.Setters> </MultiDataTrigger> </Style.Triggers> </Style> And now the board itself. With the above code set up this bit is surprisingly short, we're just going to render an ItemsControl (i.e. a list of items), we'll set the container to be a canvas, we'll set it's background to our checkerboard and for each piece we'll set the position based on the Pos property. Obviously we'll also use the ChessPieceStyle Image style that we set up above to select the correct image to render: <ItemsControl Name="ChessBoard"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas Width="8" Height="8" Background="{StaticResource Checkerboard}"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Grid Width="1" Height="1"> <Image Width="0.8" Height="0.8" Style="{StaticResource ChessPieceStyle}" /> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> <ItemsControl.ItemContainerStyle> <Style> <Setter Property="Canvas.Left" Value="{Binding Pos.X}" /> <Setter Property="Canvas.Top" Value="{Binding Pos.Y}" /> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl> And that's it! We now have everything we need to render a chess board. All that remains is to create an array of our pieces, put it in an ObservableCollection (so that the GUI gets updates when pieces added and removed) and bind it to our chessboard: this.ChessBoard.ItemsSource = new ObservableCollection<ChessPiece> { new ChessPiece{Pos=new Point(0, 6), Type=PieceType.Pawn, Player=Player.White}, new ChessPiece{Pos=new Point(1, 6), Type=PieceType.Pawn, Player=Player.White}, new ChessPiece{Pos=new Point(2, 6), Type=PieceType.Pawn, Player=Player.White}, new ChessPiece{Pos=new Point(3, 6), Type=PieceType.Pawn, Player=Player.White}, new ChessPiece{Pos=new Point(4, 6), Type=PieceType.Pawn, Player=Player.White}, new ChessPiece{Pos=new Point(5, 6), Type=PieceType.Pawn, Player=Player.White}, new ChessPiece{Pos=new Point(6, 6), Type=PieceType.Pawn, Player=Player.White}, new ChessPiece{Pos=new Point(7, 6), Type=PieceType.Pawn, Player=Player.White}, new ChessPiece{Pos=new Point(0, 7), Type=PieceType.Rook, Player=Player.White}, new ChessPiece{Pos=new Point(1, 7), Type=PieceType.Knight, Player=Player.White}, new ChessPiece{Pos=new Point(2, 7), Type=PieceType.Bishop, Player=Player.White}, new ChessPiece{Pos=new Point(3, 7), Type=PieceType.King, Player=Player.White}, new ChessPiece{Pos=new Point(4, 7), Type=PieceType.Queen, Player=Player.White}, new ChessPiece{Pos=new Point(5, 7), Type=PieceType.Bishop, Player=Player.White}, new ChessPiece{Pos=new Point(6, 7), Type=PieceType.Knight, Player=Player.White}, new ChessPiece{Pos=new Point(7, 7), Type=PieceType.Rook, Player=Player.White}, new ChessPiece{Pos=new Point(0, 1), Type=PieceType.Pawn, Player=Player.Black}, new ChessPiece{Pos=new Point(1, 1), Type=PieceType.Pawn, Player=Player.Black}, new ChessPiece{Pos=new Point(2, 1), Type=PieceType.Pawn, Player=Player.Black}, new ChessPiece{Pos=new Point(3, 1), Type=PieceType.Pawn, Player=Player.Black}, new ChessPiece{Pos=new Point(4, 1), Type=PieceType.Pawn, Player=Player.Black}, new ChessPiece{Pos=new Point(5, 1), Type=PieceType.Pawn, Player=Player.Black}, new ChessPiece{Pos=new Point(6, 1), Type=PieceType.Pawn, Player=Player.Black}, new ChessPiece{Pos=new Point(7, 1), Type=PieceType.Pawn, Player=Player.Black}, new ChessPiece{Pos=new Point(0, 0), Type=PieceType.Rook, Player=Player.Black}, new ChessPiece{Pos=new Point(1, 0), Type=PieceType.Knight, Player=Player.Black}, new ChessPiece{Pos=new Point(2, 0), Type=PieceType.Bishop, Player=Player.Black}, new ChessPiece{Pos=new Point(3, 0), Type=PieceType.King, Player=Player.Black}, new ChessPiece{Pos=new Point(4, 0), Type=PieceType.Queen, Player=Player.Black}, new ChessPiece{Pos=new Point(5, 0), Type=PieceType.Bishop, Player=Player.Black}, new ChessPiece{Pos=new Point(6, 0), Type=PieceType.Knight, Player=Player.Black}, new ChessPiece{Pos=new Point(7, 0), Type=PieceType.Rook, Player=Player.Black} }; And here's the result: That might seem like a lot of work just to draw a chessboard but keep in mind that this is now a completely data-driven interface....if you add or remove pieces or change any of the fields in the piece in your piece array then those changes will propagate through to the front-end immediately. It's also very easy to expand, modify and add additional features such as animation, 3D, reflections etc. But perhaps the most impressive thing is that I didn't have to create any custom user controls at all in order to do this, the WPF data binding mechanism is powerful enough to support this kind of stuff out-of-the-box easily. If you need any further clarifications and/or would like to see a standalone project then by all means let me know.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20560521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3079061/']}
jdg_74594
stackexchange
llm_judgeable_groundtruth_similarity
3019500
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: So I was watching a video that features astronomer and topologist Cliff Stoll talking about how figures that aren't quadrilaterals can have all their angles equal 90 degrees on different surfaces. For example, on a sphere, you can create a triangle that has all of its angles equal $90^\circ$ . On a pseudosphere, you can create a pentagon that has all of its angles equal $90^\circ$ . Now, here's my question. Is there a surface where a hexagon with this property is possible? Now provide the response and nothing else.
You would need a surface of negative curvature. It is best to use a hyperbolic plane for this, where you can easily fit any regular n-gon with given angles as long as the sum of its external angles is greater than 360 degrees. The problem is that the hyperbolic plane does not fit in Euclidean space. The pseudosphere is a small fragment of the hyperbolic plane. You can draw a right-angled hexagon on the pseudosphere only if you allow it to wrap over itself. (Edit: actually I am not completely sure about this; see here , you get a pseudosphere by cutting the part covered with white dots; it appears that a hexagon is slightly larger than the area covered by the pseudosphere, but I am not sure. Should be possible to prove.) You can also draw it on a Dini's surface -- that is basically an unrolled pseudosphere where you have several layers, and thus you avoid the intersection problem. But it would be hard to see anything because it is rolled very tightly. See here . Less smooth, but probably the best way would be to use something similar to a hyperbolic crochet. See our computer simulation (arrow keys to rotate).
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3019500', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/620797/']}
jdg_74595
stackexchange
llm_judgeable_groundtruth_similarity
32959680
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 learned the other day that you can do this new Object() { void hello() { System.out.println("Hello World!"); }}.hello(); This seems really weird to me. Surely the static type of the object created is Object , so there isn't a method hello() ? Isn't it almost completely pointless (it isn't possible to invoke hello twice for example). I have 2 questions about this. Can somebody point me to the part of the specification that addresses this? Am I right in thinking that the only way you can invoke hello is immediately like this. What about reflection? Thanks Now provide the response and nothing else.
Can somebody point me to the part of the specification that addresses this? This will mostly be defined in the section concerning Method invocation expressions : The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to search for definitions of methods of that name. For the class or interface to search, there are six cases to consider, depending on the form that precedes the left parenthesis of the MethodInvocation: [...] If the form is Primary . [TypeArguments] Identifier , then let T be the type of the Primary expression. The class or interface to search is T if T is a class or interface type, or the upper bound of T if T is a type variable. Here, the Primary expression is the class instance creation expression . So the type to search is the anonymous type. Am I right in thinking that the only way you can invoke hello is immediately like this. What about reflection? As long as an expression evaluates to the anonymous type T , whether through direct access like you have, or through generics, you have access (regular access rules apply) to the members that T declares. This isn't limited to methods. You can access fields or types, though it's not as useful for types. For example, Object var = new Object() { class Nested { }}.new Nested(); Since there's no way to refer to the nested type without the enclosing type, you can't declare a variable of that nested type. The usefulness declines very quickly. (Presumably, that's also why you can't have a static nested type within this anonymous class.) Reflection also exposes this method. The generated anonymous class contains this method, so you can retrieve it and invoke it. The process is the same. The fact that the instance is from an anonymous class doesn't matter. The same strategy as presented in How do I invoke a Java method when given the method name as a string? applies. For example, Object ref = new Object() { public void method() { System.out.println("hidden"); }};Class<?> anonymousClass = ref.getClass();Method method = anonymousClass.getMethod("method");method.invoke(ref, new Object[0]); Don't ever write code like this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32959680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3973077/']}
jdg_74596
stackexchange
llm_judgeable_groundtruth_similarity
11990200
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 save a button's location in a variable, but I have no idea how to do it.Since the code shows the x and the y of the button, can I also save both x and y separately? Console.WriteLine(button.Location);<X=100,Y=100> I want it to save the X value in var1, and Y value in var2. Now provide the response and nothing else.
You can save it as a single Point or as two different integers: Point location = button.Location;int xLocation = button.Location.X;int yLocation = button.Location.Y; You can then restore the position like this: button.Location = location;button.Location = new Point(xLocation, yLocation); Note: Point is a struct (value type) so changing location will not change button.Location . In other words this will have no effect: Point location = button.Location;location.X += 100; You'd need to do this: Point location = button.Location;location.X += 100;button.Location = location; or button.Location = new Point(button.Location.X + 100, button.Location.Y);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11990200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/905513/']}
jdg_74597
stackexchange
llm_judgeable_groundtruth_similarity
35099265
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 functionality of search users. I have provided a textview and on that textview changed method I'm firing a method to get data from web server. But I'm facing problem when user types letter, because all the api hits done in async task. Service should be hit after 100 milli-sec of wait, means if user types a letter "a" then doesn't type for 100 milli-sec then We have to hit the service. But if user types "a" then "b" then "c", so one service should be hit for "abc", not for all. I followed the official link, but it doesn't help me https://msdn.microsoft.com/en-us/library/jj155759.aspx So basically here is my code textview.TextChange+= (sender,e) =>{ CancellationTokenSource cts = new CancellationTokenSource(); await Task.Delay(500); // here some where I have to pass cancel token var lst = await APIClient.Instance.GetUserSearch("/user/get?searchTerm=" + newText, "application/json",cts); if (lst != null && lst.Count > 0){ lstSearch.AddRange(lst); } } Here is my method to GetUser public async Task<JResponse> GetUserSearch<JResponse>(string uri, string contentType,CancellationToken cts) { try { Console.Error.WriteLine("{0}", RestServiceBaseAddress + uri); string url = string.Format("{0}{1}", RestServiceBaseAddress, uri); var request = (HttpWebRequest)WebRequest.Create(url); request.ContentType = contentType; if (Utility.CurrentUser != null && !string.IsNullOrWhiteSpace(Utility.CurrentUser.AuthToken)) { request.Headers.Add("api_key", Utility.CurrentUser.AuthToken); } request.Method = "POST"; var payload = body.ToString(); request.ContentLength = payload.Length; byte[] byteArray = Encoding.UTF8.GetBytes(body.ToString()); request.ContentLength = byteArray.Length; using (var stream = await request.GetRequestStreamAsync()) { stream.Write(byteArray, 0, byteArray.Length); stream.Close(); } using (var webResponse = await request.GetResponseAsync()) { var response = (HttpWebResponse)webResponse; using (var reader1 = new StreamReader(response.GetResponseStream())) { Console.WriteLine("Finished : {0}", uri); var responseStr = reader1.ReadToEnd(); var responseObj = JsonConvert.DeserializeObject<JResponse>( responseStr, new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }); return responseObj; } } } catch (System.Exception ex) { Utility.ExceptionHandler("APIClient", "ProcessRequestAsync", ex); } return default(JResponse); } Now provide the response and nothing else.
In your example, you are creating a CancellationTokenSource - you need to hold a reference to it, so that the next time the handler is invoked, the previous search can be cancelled. Here is an example console app that you should be able to run, but the important piece is in the handler. private CancellationTokenSource _cts;private async void TextChangedHandler(string text) // async void only for event handlers{ try { _cts?.Cancel(); // cancel previous search } catch (ObjectDisposedException) // in case previous search completed { } using (_cts = new CancellationTokenSource()) { try { await Task.Delay(TimeSpan.FromSeconds(1), _cts.Token); // buffer var users = await _userService.SearchUsersAsync(text, _cts.Token); Console.WriteLine($"Got users with IDs: {string.Join(", ", users)}"); } catch (TaskCanceledException) // if the operation is cancelled, do nothing { } }} Be sure to pass the CancellationToken into all of the async methods, including those that perform the web request, this way you signal the cancellation right down to the lowest level.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35099265', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3850136/']}
jdg_74598
stackexchange
llm_judgeable_groundtruth_similarity
31117849
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 numeric matrix in R with 24 rows and 10,000 columns. The row names of this matrix are basically file names from which I have read the data corresponding to each of the 24 rows. Apart from this I have a separate factor list with 24 entires, specifying the group to which the 24 files belong. There are 3 groups - Alcohols, Hydrocarbon and Ester. The names and the corresponding group to which they belong look like this: > MS.mz[1] "int-354.19" "int-361.35" "int-368.35" "int-396.38" "int-408.41" "int-410.43" "int-422.43"[8] "int-424.42" "int-436.44" "int-438.46" "int-452.00" "int-480.48" "int-648.64" "int-312.14"[15] "int-676.68" "int-690.62" "int-704.75" "int-312.29" "int-326.09" "int-326.18" "int-326.31"[22] "int-340.21" "int-340.32" "int-352.35"> MS.groups[1] Alcohol Alcohol Alcohol Alcohol Hydrocarbon Alcohol Hydrocarbon Alcohol [9] Hydrocarbon Alcohol Alcohol Alcohol Ester Alcohol Ester Ester [17] Ester Alcohol Alcohol Alcohol Alcohol Alcohol Alcohol HydrocarbonLevels: Alcohol Ester Hydrocarbon I wanted to generate a dendrogram to look how the data in the matrix can be clustered. So, I used the following commands: require(vegan)dist.mat<-vegdist(MS.data.scaled.transposed,method="euclidean")clust.res<-hclust(dist.mat)plot(clust.res) and I got a dendogram. Now I want to color the file names in the dendrogram according to the group they belong to i.e Alcohol, Hydrocarbon or Ester. I looked at different examples posted on the forum like Label and color leaf dendrogram in r Label and color leaf dendrogram in R using ape package Clustering with bootstrapping , but could not implement it for my data. I am not sure how to correlate row.names with the MS.groups to get the colored names in the dendrogram. On generating the tree using dendextend (as explained in https://nycdatascience.com/wp-content/uploads/2013/09/dendextend-tutorial.pdf ), I get the following tree Here is the code used to generate it: require(colorspace)d_SIMS <- dist(firstpointsample5[,-1])hc_SIMS <- hclust(d_SIMS)labels(hc_SIMS)dend_SIMS <- as.dendrogram(hc_SIMS)SIMS_groups <- rev(levels(firstpointsample5[, 1]))dend_SIMS <- color_branches(dend_SIMS, k = 3, groupLabels = SIMS_groups)is.character(labels(dend_SIMS)) plot(dend_SIMS)labels_colors(dend_SIMS) <- rainbow_hcl(3)[sort_levels_values(as.numeric(firstpointsample5[,1])[order.dendrogram(dend_SIMS)])]labels(dend_SIMS) <- paste(as.character(firstpointsample5[, 1])[order.dendrogram(dend_SIMS)],"(", labels(dend_SIMS), ")", sep = "")dend_SIMS <- hang.dendrogram(dend_SIMS, hang_height = 0.1)dend_SIMS <- assign_values_to_leaves_nodePar(dend_SIMS, 0.5,"lab.cex")par(mar = c(3, 3, 3, 7))plot(dend_SIMS, main = "Clustered SIMS dataset\n (the labels give the true m/z groups)",horiz = TRUE, nodePar = list(cex = 0.007))legend("topleft", legend = SIMS_groups, fill = rainbow_hcl(3)) Now provide the response and nothing else.
I suspect the function you are looking for is either color_labels or get_leaves_branches_col . The first color your labels based on cutree (like color_branches do) and the second allows you to get the colors of the branch of each leaf, and then use it to color the labels of the tree (if you use unusual methods for coloring the branches (as happens when using branches_attr_by_labels ). For example: # define dendrogram object to play with:hc <- hclust(dist(USArrests[1:5,]), "ave")dend <- as.dendrogram(hc)library(dendextend)par(mfrow = c(1,2), mar = c(5,2,1,0))dend <- dend %>% color_branches(k = 3) %>% set("branches_lwd", c(2,1,2)) %>% set("branches_lty", c(1,2,1))plot(dend)dend <- color_labels(dend, k = 3)# The same as:# labels_colors(dend) <- get_leaves_branches_col(dend)plot(dend) Either way, you should always have a look at the set function, for ideas on what can be done to your dendrogram (this saves the hassle of remembering all the different functions names).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31117849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1709471/']}
jdg_74599
stackexchange
llm_judgeable_groundtruth_similarity
30519693
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to this link http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html , I can easily create a presigned link just adding the life span to getObjectUrl $signedUrl = $client->getObjectUrl($bucket, 'data.txt', '+10 minutes');// > https://my-bucket.s3.amazonaws.com/data.txt?AWSAccessKeyId=[...]&Expires=[...]&Signature=[...] But I get a plain url, you know, without the awsaccesskeyid and expires parameters, Here's my code: $bucket = 'imagenesfc';$keyname = 'NASimagenes/codigoBarraBoleto/1001000098.png';$filepath = 'NASimagenes/codigoBarraBoleto';// Instantiate the client.$s3 = S3Client::factory(array( 'version' => 'latest', 'region' => 'us-west-1')); $signedUrl = $s3->getObjectUrl($bucket, $keyname,'+10 minutes');// > https://my-bucket.s3.amazonaws.com/data.txt?AWSAccessKeyId=[...]&Expires=[...]&Signature=[...] echo $signedUrl."<br>"; EDIT: I have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY as environment variables My echo looks like: https://s3-us-west-1.amazonaws.com/imagenesfc/NASimagenes/codigoBarraBoleto/1001000098.png What's wrong? Now provide the response and nothing else.
Well, if anyone else has any trouble with this like I did, here is the answer, I went into the amazon php development forums and got help from the profesionals. It seems you may be flip-flopping between Version 2 and Version 3 of the SDK or looking at the wrong document. Make sure you are getting the one you intend to use and are looking at the correct documentation. They are different. V3 - Composer Requirement: {"aws/aws-sdk-php": "~3.0"} - User Guide: http://docs.aws.amazon.com/aws-sdk-php/v3/guide/index.html - API Docs: http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html - Pre-signed URL Docs: http://docs.aws.amazon.com/aws-sdk-php/v3/guide/service/s3-presigned-url.html V2 - Composer Requirement: {"aws/aws-sdk-php": "~2.8"} - User Guide: http://docs.aws.amazon.com/aws-sdk-php/v2/guide/index.html - API Docs: http://docs.aws.amazon.com/aws-sdk-php/v2/api/index.html - Pre-signed URL Docs: http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html#creating-a-pre-signed-url Mini step-by-step guide of what you have to do: 1.Install composer, preferably using sudo: sudo curl -sS https://getcomposer.org/installer | sudo php 2.Go to your project folder and create a composer.json file, with the version you want/need, you can find releases here: https://github.com/aws/aws-sdk-php/releases , commands for each version seem to be very version specific, be careful, this was my main problem. { "require": { "aws/aws-sdk-php": "~3.0" } } 3.Then go to your project folder in the terminal, and install sdk via composer and update afterward like: (if you change version you have to update again.) sudo php composer.phar install sudo php composer.phar update 4.Then everything is ready for you to follow proper version documentation, in my case for version "aws/aws-sdk-php": "~3.0" and for presigned url, what worked was: require 'vendor/autoload.php'; use Aws\S3\S3Client; use Aws\S3\Exception\S3Exception; $sharedConfig = [ 'region' => 'us-west-1', 'version' => 'latest' ]; //I have AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY as environment variables $s3Client = new Aws\S3\S3Client($sharedConfig); $cmd = $s3Client->getCommand('GetObject', [ 'Bucket' => $bucket, 'Key' => $keyname ]); $request = $s3Client->createPresignedRequest($cmd, '+20 minutes'); $presignedUrl = (string) $request->getUri(); echo $presignedUrl; I hope this helps anyone facing the same problems as I did.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30519693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2958190/']}
jdg_74600
stackexchange
llm_judgeable_groundtruth_similarity
34441943
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 recently deleted Anaconda and reinstalled python with brew. I've installed everything according to these instructions. Python works great, and all packages I've tested so far also work. I've got ipython installed, but trying to launch it from the terminal gives: -bash: ipython: command not found I've located the installation at: /usr/local/lib/python2.7/site-packages/ipython Following older related questions, I've tried adding this path to .bash_profile but got: -bash: :/usr/local/lib/python2.7/site-packages/ipython: No such file or directory Whenever terminal starts. Some more info: Anaconda installed an removed, El-Capitan 10.11.2, python 2.7. Any help would be much appreciated! EDIT: added some more info to @cel request: echo $PATH gives: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/usr/local/git/bin:/Library/TeX/texbin:/Applications/Sublime Text.app/Contents/SharedSupport/bin which -a python gives: /usr/local/bin/python and /usr/bin/python . EDIT: added the output of python -m pip install ipython to cel's request: Requirement already satisfied (use --upgrade to upgrade): ipython in /usr/local/lib/python2.7/site-packagesRequirement already satisfied (use --upgrade to upgrade): traitlets in /usr/local/lib/python2.7/site-packages (from ipython)Requirement already satisfied (use --upgrade to upgrade): pickleshare in /usr/local/lib/python2.7/site-packages (from ipython)Requirement already satisfied (use --upgrade to upgrade): simplegeneric>0.8 in /usr/local/lib/python2.7/site-packages (from ipython)Requirement already satisfied (use --upgrade to upgrade): decorator in /usr/local/lib/python2.7/site-packages (from ipython)Requirement already satisfied (use --upgrade to upgrade): gnureadline in /usr/local/lib/python2.7/site-packages (from ipython)Requirement already satisfied (use --upgrade to upgrade): appnope in /usr/local/lib/python2.7/site-packages (from ipython)Requirement already satisfied (use --upgrade to upgrade): pexpect in /usr/local/lib/python2.7/site-packages (from ipython)Requirement already satisfied (use --upgrade to upgrade): ipython-genutils in /usr/local/lib/python2.7/site-packages (from traitlets->ipython)Requirement already satisfied (use --upgrade to upgrade): path.py in /usr/local/lib/python2.7/site-packages (from pickleshare->ipython)Requirement already satisfied (use --upgrade to upgrade): ptyprocess>=0.5 in /usr/local/lib/python2.7/site-packages (from pexpect->ipython) Now provide the response and nothing else.
Searching the web for "bash: ipython: command not found" turns up several hits (including this SO question ), but they're not particularly helpful. From the sound of it, you have IPython , the Python package installed, but ipython —the entry point (i.e., wrapper/launcher script) for it—is missing for whatever reason. To check whether this is the case, try running: % python -m IPythonPython 2.7.9 (default, Feb 10 2015, 03:28:08) Type "copyright", "credits" or "license" for more information.IPython 4.0.0 -- An enhanced Interactive Python.? -> Introduction and overview of IPython's features.%quickref -> Quick reference.help -> Python's own help system.object? -> Details about 'object', use 'object??' for extra details.In [1]: If that brings up IPython, then you might try making a shell alias as the SO answer linked above suggests, i.e., put something like this in your shell's startup script: alias ipython='python -m IPython' . Or, create the launcher script yourself. For me, it lives in /usr/local/bin/ipython and contains the following: #!/usr/local/opt/python/bin/python2.7# -*- coding: utf-8 -*-import reimport sysfrom IPython import start_ipythonif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(start_ipython()) Hope this helps. (If it does, please consider up-voting the other SO question as well...) UPDATE : Here are some more possibly-relevant links: ipython: command not found on OSX https://github.com/pypa/pip/issues/426
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/34441943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5712228/']}
jdg_74601
stackexchange
llm_judgeable_groundtruth_similarity
864604
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What do you think is the most efficient algorithm for checking whether a graph represented by an adjacency matrix is connected? In my case I'm also given the weights of each edge. There is another question very similar to mine: How to test if a graph is fully connected and finding isolated graphs from an adjacency matrix That answer seems to be good, except I don't really understand it. How does repeatedly squaring the matrix give information about its connectivity? There is another an answer that claims eigenvectors also give information about the connectivity of the graph, could anyone explain that as well? I'm asking this because I don't have the background to understand the answers given, I'm just solving a problem that has to do with these topics. Searching around on google didn't give me an answer either, so hopefully someone can clear it up. Now provide the response and nothing else.
If you put all 1 on the diagonal of your adjacency matrix $A$ , and all edge weights are positive then when you multiply $A^2 = A*A$ you get a non-zero entry $a_{ij}$ in $A^2$ if and only if there exist non-zero $a_{ik}$ and $a_{kj}$ in $A$ for some $k$ , i.e. there is a path of length $2$ between $i$ and $j$ if $k\neq j$ and $k\neq i$ and there is a path of length $1$ if $k = j$ or $k = i$ . So the non-zero entries in $A^2$ tell you all pairs of nodes that are connected by a path of length $2$ . Similarly the entries in $A^k$ tell you all pairs of nodes that are connected by a path of length $k$ . So if you start with $A$ and keep squaring until you get $A^k$ where $k \geq n$ where $n$ is the number of nodes, then the non-zero entries in row $i$ tell you all the nodes that are connected to node $i$ (since two connected nodes must be connected by a path of length $n$ or less). So if you have a row in $A^k$ that is all non-zero, then the graph is connected. If the graph is not connected, you can similarly tell the connected components from the rows of $A^k$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/864604', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114545/']}
jdg_74602
stackexchange
llm_judgeable_groundtruth_similarity
3815
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to build an explicit $N \times N$ $0/1$-matrix with $N^{1.5}$ ones such that every $N^{0.499} \times N^{0.499}$ submatrix contains less than $N^{0.501}$ ones? Or probably it is possible to build an explicit hitting set for such property. It is easy to see that random matrix has this property with probability exponentially close to $1$. Also, expander mixing lemma is not sufficient to derive this property. I guess pseudorandom generators that fool combinatorial rectangles could help here, but they are designed for uniform distributions and I basically need $B(N^2, N^{-0.5})$ here. Now provide the response and nothing else.
What you are looking for is a one-bit extractor for two independent sources: a function $E:[N]\times [N]\to \{0,1\}$, such that, provided X,Y are random variables with min-entropy 0.499*log(N), E(X,Y) is almost balanced. It's a notorious hard problem. For the parameters you want, I believe it was solved by Bourgain. See here: http://www.cs.washington.edu/homes/anuprao/pubs/bourgain.pdf
{}
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/3815', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/141/']}
jdg_74603
stackexchange
llm_judgeable_groundtruth_similarity
878038
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a name of a property of which I have a few examples: $(1) \quad\color{green}{\text{even number}}+\color{red}{\text{odd number}}=\color{red}{\text{odd number}}$ $(2) \quad \color{green}{\text{rational number}}+\color{red}{\text{irrational number}}=\color{red}{\text{irrational number}}$ $(3) \quad\color{green}{\text{algebraic number}}+\color{red}{\text{transcendental number}}=\color{red}{\text{transcendental number}}$ $(4) \quad\color{green}{\text{real number}}+\color{red}{\text{non-real number}}=\color{red}{\text{non-real number}}$ If I were to generalise, this, I'd say that if we partition a set $X$ into two subsets $S$ and $S^c=X\setminus S$, then the sum of a member of $S$ and a member of $S^c$ is always in either $S^c$ or $S$. My question is: "Is there a name for this property (in these four cases) and is this property true in general?" Also, does anyone have any more examples of this property? Now provide the response and nothing else.
I think this comes from the fact that if you have a group $G$ and $H$ a subgroup of $G$ then if $h\in H$ and $x\not\in H$ we get $xh\not\in H$. The proof is by contradiction, suppose $xh=l$ with $l\in H$. Then postmultiplying by $h^{-1}$ gives $x=lh^{-1}$ which is in $H$ since $H$ is a subgroup of $G$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/878038', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/127192/']}
jdg_74604
stackexchange
llm_judgeable_groundtruth_similarity
2978219
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 without an ID column. When I try to delete from it using ActiveRecord the generated SQL is DELETE FROM table_name WHERE ID=NULL , which obviously doesn't work. Is there any way to delete from the table using ActiveRecord, or at least run a raw SQL delete query with placeholders (so it's not vulnerable to SQL injection)? Now provide the response and nothing else.
Have you tried using ActiveRecord's delete_all method? Here's an excerpt in a sandbox of mine: >> customer = Customer.new(:login => 'foo')=> #<Customer id: nil, status: 0, name: nil, login: "foo", password: nil, salt: nil, api_key: nil, address: nil, town: nil, state: nil, country: "USA", zipcode: nil, balance: #<BigDecimal:1032669b0,'0.0',9(18)>, discount: 0, last_four_cc: nil, auto_renew: false, contact_name: nil, contact_email: nil, domain: "anon.limelock.com", created_at: nil, updated_at: nil>>> customer.save=> true>> Customer.all.count=> 4>> Customer.delete_all(:login => 'foo')=> 1>> Customer.all.count=> 3 The generated SQL is DELETE FROM `customers` WHERE (`customers`.`login` = 'foo') Check out the documentation
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2978219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/259288/']}
jdg_74605
stackexchange
llm_judgeable_groundtruth_similarity
980697
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 following error while loading my index page in FF3.0. Sorry, i am unable to paste the script here as it is 2030 lines of code. element.dispatchEvent is not a function On expansion it gives me below things, fire()()prototype.js?1 (line 3972) _methodized()()prototype.js?1 (line 246) fireContentLoadedEvent()prototype.js?1 (line 4006) [Break on this error] element.dispatchEvent(event); element.dispatchEvent(event); is in line 3972 of prototype.js. I am including prototype.js along with 10s of other js files in my index page. Has anybody came across this kind of error? Please somebody explain me why this error is showing up. Now provide the response and nothing else.
are you using jquery and prototype on the same page by any chance? If so, use jquery noConflict mode, otherwise you are overwriting prototypes $ function. noConflict mode is activated by doing the following: <script src="jquery.js"></script><script>jQuery.noConflict();</script> Note: by doing this, the dollar sign variable no longer represents the jQuery object. To keep from rewriting all your jQuery code, you can use this little trick to create a dollar sign scope for jQuery: jQuery(function ($) { // The dollar sign will equal jQuery in this scope});// Out here, the dollar sign still equals Prototype
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/980697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121102/']}
jdg_74606
stackexchange
llm_judgeable_groundtruth_similarity
75781
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: This is my first question on the forum. I'm wondering if the following proof is valid. Proof: Let $\{A_\lambda\}_{\lambda \in L}$ be an arbitrary collection of disjoint non-empty open subsets of $\mathbb{R}$. Since every non-empty open subset of $\mathbb{R}$ can be written uniquely as a countable union of disjoint open intervals, we can take the union $A = \bigcup\limits_{\lambda \in L}A_\lambda$ and decompose it $A = \bigcup\limits_{n \in \mathbb{N}} I_n$ in disjoint open intervals which forms a countable collection. We can also decompose each $A_\lambda$ as $\bigcup\limits_{m \in \mathbb{N}}J_{\lambda,m}$. For $\lambda \neq \mu \in L$, $A_\lambda \cap A_\mu = \emptyset$ and this is a new representation of $A$: $$A = \bigcup_{n \in \mathbb{N}} I_n = \bigcup_{\substack{\lambda \in L \\ m \in \mathbb{N}}} J_{\lambda,m}$$ No matter how complicated the union over $L$ is, the $J_{\lambda,m}$ are disjoint open intervals. Thus, by the uniqueness, the two collections are exactly the same. As the final argument, we produce an injection $\varphi:\{A_\lambda\} \mapsto \{J_{\lambda,m}\}$ picking for each $A_\lambda$ some $J_{\lambda,m}$. I can't see any fault, but the result seems incredibly strong to me. P.S.: stack exchange has some bug related to \bigcup and \bigcap symbols? Now provide the response and nothing else.
To each of those open disjoint subsets you can associate one and only one rational number (just pick a rational number in the set). Thus you obtain an injection from your family of subsets into the set of rational numbers, which is countable. The conclusion follows that your family must indeed be countable.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/75781', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18223/']}
jdg_74607
stackexchange
llm_judgeable_groundtruth_similarity
20106712
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 situation is this... someone working on the same repo has deleted a branch from his local & remote repo... Most people who have asked about this kind of problem on Stack Overflow, or other sites have the issue of branches still showing in their remote tracking branch list git branch -a at the bottom: * master develop feature_blah remotes/origin/master remotes/origin/develop remotes/origin/feature_blah remotes/origin/random_branch_I_want_deleted However, in MY situation the branch that shouldn't be there, is local: * master develop feature_blah random_branch_I_want_deleted remotes/origin/master remotes/origin/develop remotes/origin/feature_blah When I do any of the following, it doesn't get removed locally: $ git prune I also tried: $ git remote prune origin$ git fetch --prune More useful info: When I check git remote show origin this is how it looks: * remote originFetch URL: utilities:homeconnections_ui.gitPush URL: utilities:homeconnections_ui.gitHEAD branch: masterRemote branches: master tracked develop tracked feature_blah tracked other123 tracked other444 tracked other999 trackedLocal branches configured for 'git pull': develop merges with remote develop feature_blah merges with remote other999 master merges with remote master random_branch_I_want_deleted merges with remote random_branch_I_want_deletedLocal refs configured for 'git push': develop pushes to develop (local out of date) master pushes to master (up to date) feature_blah pushes to feature_blah(up to date) Notice that it's only in the section titled Local branches configured for 'git pull': Why? Now provide the response and nothing else.
I don't blame you for getting frustrated about this. The best way to look at is this. There are potentially three versions of every remote branch: The actual branch on the remote repository (e.g., remote repo at https://example.com/repo.git , refs/heads/master ) Your snapshot of that branch locally (stored under refs/remotes/... ) (e.g., local repo, refs/remotes/origin/master ) And a local branch that might be tracking the remote branch (e.g., local repo, refs/heads/master ) Let's start with git prune . This removes objects that are no longer being referenced, it does not remove references. In your case, you have a local branch. That means there's a ref named random_branch_I_want_deleted that refers to some objects that represent the history of that branch. So, by definition, git prune will not remove random_branch_I_want_deleted . Really, git prune is a way to delete data that has accumulated in Git but is not being referenced by anything. In general, it doesn't affect your view of any branches. git remote prune origin and git fetch --prune both operate on references under refs/remotes/... (I'll refer to these as remote references). It doesn't affect local branches. The git remote version is useful if you only want to remove remote references under a particular remote. Otherwise, the two do exactly the same thing. So, in short, git remote prune and git fetch --prune operate on number 2 above. For example, if you deleted a branch using the git web GUI and don't want it to show up in your local branch list anymore ( git branch -r ), then this is the command you should use. To remove a local branch, you should use git branch -d (or -D if it's not merged anywhere). FWIW, there is no git command to automatically remove the local tracking branches if a remote branch disappears.
{}
{'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/20106712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446936/']}
jdg_74608
stackexchange
llm_judgeable_groundtruth_similarity
3327767
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As far as I understand, DirectFB offers hardware acceleration for many kinds of graphics cards. Additionally, it's smaller, faster, and uses up less memory than X11. Why then, is it not more mainstream than it is now? Here's what I'm really unsure about: Do common GTK+/Qt programs need to be ported to it? On the DirectFB site, there's a project for porting Firefox to it. Why is that even necessary, if GTK+ has the ability to use DirectFB directly? The way I (probably incorrectly) understand it, is that Firefox should output to GTK+, which should output to DirectFB, which should output to the hardware. Please correct me if I'm wrong about that. Now provide the response and nothing else.
If you're stressing about X as a source of overhead on a modern Linux system you probably aren't looking in the right place. X was designed a really long time ago for computers much less powerful than a modern cell phone. If you look at "top" and see X using memory, there's a lot of work to do to figure out the actual X overhead. There are memory maps that aren't "real" memory, and there are resources (such as big blocks of pixels) allocated on behalf of apps. Bottom line the memory shown for X in top isn't what one might think. People also hear that X uses the "network" and think this is going to be a performance bottleneck. "Network" here means local UNIX domain socket, which has negligible overhead on modern Linux. Things that would bottleneck on the network, there are X extensions to make fast (shared memory pixmaps, DRI, etc.). Threads in-process wouldn't necessarily be faster than the X socket, because the bottlenecks have more to do with the inherent problem of coordinating multiple threads or processes accessing the same hardware, than with the minimal overhead of local sockets. The multi-process setup has a lot of advantages, such as being much harder to crash. See Google Chrome for example, using multiple processes to be more robust - and it turns out, also to run fast. Less processes does not necessarily mean more modern. There are many reasons apps using GTK don't transparently port to DirectFB. For Firefox, one is that it uses X directly sometimes. Also, some toolkit-independent stuff such as the browser plugin interface uses X directly. Flash plugin would not work on DirectFB for example. Even apps that don't use X directly would often assume the normal X-based desktop environment exists (GNOME, etc.). Another issue with replacing X is driver support, where both of the better graphics cards (NVidia, ATI) have proprietary drivers that are a good bit more capable than the free drivers, and those proprietary drivers are tied to X. And of course there's migration path. If you have hundreds of apps using X and no clear end-user downside to X, nobody is going to switch to something where no apps work. Most likely, the solution here would be a rootless X server running on a new window system, so old apps still work. Old is not always bad. X was very well-designed by smart people, and that has allowed it to evolve and change and still work many years later. Anyway all a long way of saying, basically switching away from X is tons of effort, it really works fine, and "works fine" has never applied to any of the alternatives (at least if you want to be able to run most apps on most hardware). There are issues with X - such as the impossibility of doing an atomic screen update, something the Wayland project is looking at - but most of the issues are really cosmetic for users (e.g. non-atomic updates) or cosmetic for developers (old deprecated extensions and the like). It just isn't true that one could drop X and magically have something much smaller and faster. That's mostly based on people speculating that "old" and "uses network" must be slow and bloated, but again, X was designed for really really crappy hardware. I used to run X (and Emacs!) fine on my 386 with maybe 8 megs of RAM or something like that.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3327767', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_74609
stackexchange
llm_judgeable_groundtruth_similarity
1258169
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 haven't figured out that yet: I have a mainViewController that switches two views, viewControllerA and ViewControllerB. The way I switch the view is by having a UIButton (mainButton) in the mainViewController, and clicking on it switches viewControllerA <--> ViewControllerB. Now here is my problem. My ViewControllerA has a UIButton (ButtonA). And I want that by clicking on it, it tells the mainViewController to switch to the other view (viewControllerB) In other words, the child view (viewControllerA) should send a message to the mainViewController(its parent view) that it wants to fire a method that belongs to the main view, not to itself (viewA). How could I achieve that please? Now provide the response and nothing else.
When communication to parent objects you have a few design patterns to choose from. Delegation and Notification are both good choices. The big idea here is communication with loose coupling. Notifications use a Singleton to handle communication while Delegation uses weak references to parent objects. (Check out Cocoa With Love: retain cycles ) If you go with delegation, you can create an informal protocol for your ViewControllerA which MainViewController must conform to. You may call it the ViewControllerADelegate protocol: @protocol ViewControllerADelegate @optional - (void)bringSubViewControllerToFront:(UIViewController*)aController; @end Or ViewControllerA can post a notification: [[NSNotificationCenter defaultCenter] postNotificationName:@"MyFunkyViewSwitcherooNotification" object:self]; And MainViewController should be listenting if it wants to know: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(swapThoseViews:) name:@"MyFunkyViewSwitcherooNotification" object:nil];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1258169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/117330/']}
jdg_74610
stackexchange
llm_judgeable_groundtruth_similarity
281365
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: As per the memory layout of C program ,constant variables are stored in the Initialized data segment of the RAM. But as per some of the Microcontroller memory layout ,const variables are stored in FLASH Memory.I have also seen that the size of BIN file of my code increases when I change const variables to Macro definitions? Help me clear this ambiguity. I used Nuc2240 Cortex M0 . Now provide the response and nothing else.
If you were writing assembler, you would decide which locations are used to hold which constants or variables, through org or similar directives. When you are writing C, the C tool chain you're using will store stuff where it's been programmed to. Variables obviously tend to go in RAM, constants can go in either RAM or Flash, program tends to go in Flash. It's all down to how the tool for that particular target processor has been designed, where it gets its instruction from where to put stuff. It might all be baked into the code, in which case you don't get any say, it goes where the tool chain's creators chose to send it. It may take directives from somewhere (source code, command line, make file, environmental variable) so that you can rebase stuff. Read your specific documentation. It's not physics, it's all down to the whim of man.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/281365', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/128030/']}
jdg_74611
stackexchange
llm_judgeable_groundtruth_similarity
286297
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 suspicion that I'm using the finally block incorrectly, and that I don't understand the fundamentals of its purpose... function myFunc() { try { if (true) { throw "An error"; } } catch (e) { alert (e); return false; } finally { return true; } } This function will run the catch block, alert "An error", but then return true. Why doesn't it return false? Now provide the response and nothing else.
The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception. more The finally block will always run, try returning true after your try block function myFunc() { try { if (true) { throw "An error"; } return true; } catch (e) { alert (e); return false; } finally { //do cleanup, etc here } }
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/286297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9021/']}
jdg_74612
stackexchange
llm_judgeable_groundtruth_similarity
18938152
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 date ranges, (start1,end1):::>>date1 && (start2,end2):::>>date2 . I want to check if the two dates isOverLaped. My flow chart I assume "<>=" operators is valid for comparing . boolean isOverLaped(Date start1,Date end1,Date start2,Date end2) { if (start1>=end2 && end2>=start2 && start2>=end2) { return false; } else { return true; }} Any Suggestion will be appreciated. Now provide the response and nothing else.
You can use Joda-Time for this. It provides the class Interval which specifies a start and end instants and can check for overlaps with overlaps(Interval) . Something like DateTime now = DateTime.now();DateTime start1 = now;DateTime end1 = now.plusMinutes(1);DateTime start2 = now.plusSeconds(50);DateTime end2 = now.plusMinutes(2);Interval interval = new Interval( start1, end1 );Interval interval2 = new Interval( start2, end2 );System.out.println( interval.overlaps( interval2 ) ); prints true since the end of the first interval falls between the start and end of the second interval.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18938152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1283715/']}
jdg_74613
stackexchange
llm_judgeable_groundtruth_similarity
12040986
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 below exception when trying to call service from SOAPUI . When I open the endpoint in browser, it displays the wsdl fine. WARN org.apache.cxf.phase.PhaseInterceptorChain - Interceptor for {http://contract.premsisc.usst.com/}PaidClaimFacadeService has thrown exception, unwinding noworg.apache.cxf.interceptor.Fault: Message part {http://contract.premsisc.uss`enter code here`t.com/}findPaidClaims was not recognized. (Does it exist in service WSDL?) at org.apache.cxf.interceptor.DocLiteralInInterceptor.handleMessage(DocLiteralInInterceptor.java:194) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:255) at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:113) at org.apache.cxf.transport.servlet.ServletDestination.invoke(ServletDestination.java:97) at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:461) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:188) at org.apache.cxf.transport.servlet.AbstractCXFServlet.invoke(AbstractCXFServlet.java:148) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:179) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:103) at javax.servlet.http.HttpServlet.service(HttpServlet.java:738) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:159) at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1655) at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1595) at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:104) at com.ibm.ws.webcontainer.filter.WebAppFilterChain._doFilter(WebAppFilterChain.java:77) at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:908) at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:932) at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:500) at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178) at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:91) at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:864) at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1583) at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:186) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384) at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:272) at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214) at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113) at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165) at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217) at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161) at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204) at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775) at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905) at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1550) My wsdl as in WAS 7 server <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://contract.premsisc.usst.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="PaidClaimFacadeService" targetNamespace="http://contract.premsisc.usst.com/"><wsdl:types><xs:schema xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://contract.premsisc.usst.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="unqualified" targetNamespace="http://contract.premsisc.usst.com/"><xs:element name="findPaidClaims" type="tns:findPaidClaims"/><xs:element name="findPaidClaimsResponse" type="tns:findPaidClaimsResponse"/><xs:complexType name="findPaidClaims"><xs:sequence><xs:element minOccurs="0" name="Product" type="xs:string"/></xs:sequence></xs:complexType><xs:complexType name="findPaidClaimsResponse"><xs:sequence><xs:element name="return" type="xs:boolean"/></xs:sequence></xs:complexType><xs:element name="PremDiscountService" type="tns:PremDiscountService"/><xs:complexType name="PremDiscountService"><xs:sequence/></xs:complexType></xs:schema></wsdl:types><wsdl:message name="findPaidClaims"><wsdl:part element="tns:findPaidClaims" name="parameters"></wsdl:part></wsdl:message><wsdl:message name="PremDiscountServiceException"><wsdl:part element="tns:PremDiscountService" name="PremDiscountServiceException"></wsdl:part></wsdl:message><wsdl:message name="findPaidClaimsResponse"><wsdl:part element="tns:findPaidClaimsResponse" name="parameters"></wsdl:part></wsdl:message><wsdl:portType name="PaidClaimFacade"><wsdl:operation name="findPaidClaims"><wsdl:input message="tns:findPaidClaims" name="findPaidClaims"></wsdl:input><wsdl:output message="tns:findPaidClaimsResponse" name="findPaidClaimsResponse"></wsdl:output><wsdl:fault message="tns:PremDiscountServiceException" name="PremDiscountServiceException"></wsdl:fault></wsdl:operation></wsdl:portType><wsdl:binding name="PaidClaimFacadeServiceSoapBinding" type="tns:PaidClaimFacade"><soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/><wsdl:operation name="findPaidClaims"><soap:operation soapAction="" style="document"/><wsdl:input name="findPaidClaims"><soap:body use="literal"/></wsdl:input><wsdl:output name="findPaidClaimsResponse"><soap:body use="literal"/></wsdl:output><wsdl:fault name="PremDiscountServiceException"><soap:fault name="PremDiscountServiceException" use="literal"/></wsdl:fault></wsdl:operation></wsdl:binding><wsdl:service name="PaidClaimFacadeService"><wsdl:port binding="tns:PaidClaimFacadeServiceSoapBinding" name="PaidClaimFacadePort"><soap:address location="http://localhost:9084/premdisc/services/PaidClaimFacadeService"/></wsdl:port></wsdl:service></wsdl:definitions> My Soap Request in SOAPUI : <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:con="http://contract.premsisc.usst.com/"> <soapenv:Header/> <soapenv:Body> <con:findPaidClaims> <!--Optional:--> <Product>abc</Product> </con:findPaidClaims> </soapenv:Body></soapenv:Envelope> Soap Response in Soap UI: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <soap:Fault> <faultcode>soap:Client</faultcode> <faultstring>Message part {http://contract.premsisc.usst.com/}findPaidClaims was not recognized. (Does it exist in service WSDL?)</faultstring> </soap:Fault> </soap:Body></soap:Envelope> and this is how I configured the jaxws:endpoint <jaxws:endpoint id="paidClaimWs" implementor="#paidClaimFacadeImpl" address="/PaidClaimFacadeService" wsdlLocation="/wsdl/PaidClaimFacade.wsdl" serviceName="msg:PaidClaimFacadeService" endpointName="msg:PaidClaimFacadePort" xmlns:msg="http://contract.premsisc.usst.com/"> </jaxws:endpoint> Now provide the response and nothing else.
This means that you are calling an operation which does not exits in your WSDL file. {http://contract.premsisc.usst.com/}findPaidClaims was not recognized This is your target name space: http://contract.premsisc.usst.com/ And this is your operation: findPaidClaims If you'll check your WSDL you will see that there is no such operation like: findPaidClaims . EDIT Now the problem is clear. Your namespaces in WSDL file are wrong.This is fixed WSDL and it will work. I don't know if you run some validation of your WSDL file, but my IntelliJ show the errors. So I fixed them: <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://contract.premdisc.hcsc.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="PaidClaimFacadeService" targetNamespace="http://contract.premdisc.hcsc.com/"> <wsdl:types> <xs:schema xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://contract.premsisc.usst.com/types" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="unqualified" targetNamespace="http://contract.premsisc.usst.com/types"> <xs:element name="findPaidClaims" type="tns:findPaidClaims"/> <xs:element name="findPaidClaimsResponse" type="tns:findPaidClaimsResponse"/> <xs:complexType name="findPaidClaims"> <xs:sequence> <xs:element minOccurs="0" name="Product" type="xs:string"/> </xs:sequence> </xs:complexType> <xs:complexType name="findPaidClaimsResponse"> <xs:sequence> <xs:element name="return" type="xs:boolean"/> </xs:sequence> </xs:complexType> <xs:element name="PremDiscountService" type="tns:PremDiscountService"/> <xs:complexType name="PremDiscountService"> <xs:sequence/> </xs:complexType> </xs:schema> </wsdl:types> <wsdl:message name="findPaidClaims"> <wsdl:part element="tns:findPaidClaims" name="parameters"></wsdl:part> </wsdl:message> <wsdl:message name="PremDiscountServiceException"> <wsdl:part element="tns:PremDiscountService" name="PremDiscountServiceException"></wsdl:part> </wsdl:message> <wsdl:message name="findPaidClaimsResponse"> <wsdl:part element="tns:findPaidClaimsResponse" name="parameters"></wsdl:part> </wsdl:message> <wsdl:portType name="PaidClaimFacade"> <wsdl:operation name="findPaidClaims"> <wsdl:input message="tns:findPaidClaims" name="findPaidClaims"></wsdl:input> <wsdl:output message="tns:findPaidClaimsResponse" name="findPaidClaimsResponse"></wsdl:output> <wsdl:fault message="tns:PremDiscountServiceException" name="PremDiscountServiceException"></wsdl:fault> </wsdl:operation> </wsdl:portType> <wsdl:binding name="PaidClaimFacadeServiceSoapBinding" type="tns:PaidClaimFacade"> <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> <wsdl:operation name="findPaidClaims"> <soap:operation soapAction="" style="document"/> <wsdl:input name="findPaidClaims"> <soap:body use="literal"/> </wsdl:input> <wsdl:output name="findPaidClaimsResponse"> <soap:body use="literal"/> </wsdl:output> <wsdl:fault name="PremDiscountServiceException"> <soap:fault name="PremDiscountServiceException" use="literal"/> </wsdl:fault> </wsdl:operation> </wsdl:binding> <wsdl:service name="PaidClaimFacadeService"> <wsdl:port binding="tns:PaidClaimFacadeServiceSoapBinding" name="PaidClaimFacadePort"> <soap:address location="http://localhost:9084/premdisc/services/PaidClaimFacadeService"/> </wsdl:port> </wsdl:service></wsdl:definitions> The problem was that you had different namespace as your xmlns:tns and targetNamespace . Look closely at your WSDL. xmlns:tns="http://contract.premdisc.hcsc.com/"targetNamespace="http://contract.premsisc.usst.com/" You see that in your file they are different, but they must be the same. And for your XSD you need to use different namespace. Something like: xmlns:tns="http://contract.premsisc.usst.com/types" As it was in your file: xmlns:tns="http://contract.premsisc.usst.com/"targetNamespace="http://contract.premdisc.hcsc.com/" Ass you can see they are also different. Compare the file I fixed and your file and will see the difference. Try it with fixed file and it will work.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12040986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/991739/']}
jdg_74614
stackexchange
llm_judgeable_groundtruth_similarity
44836984
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: To get a ZoneId it goes like: ZoneId.of("America/Sao_Paulo"); or ZoneId.of(ZoneId.SHORT_IDS.get("BET")); Why would be the reason for not existing an Enum of such values, like: ZoneId.of(ZoneIds.AMERICA_SAO_PAULO); which seems less error-prone and a lot more auto-complete friendly? Now provide the response and nothing else.
I believe it's because the list of all possible timezones names can change regardless of Java version. Timezone information comes with Java installation (usually in the folder <java-home>/lib/zi , or in jre/lib/tzdb.dat file in newer versions). But this information can be updated without changing the Java version (using the Timezone Updater Tool ). If the timezone data is updated (but Java version stays the same) and a new zone ID is created, there would be no equivalent Enum for it, leaving the API "incomplete". And timezone data changes faster than JDK updates - even if it didn't, it's not always possible to update the JDK version in production environments as soon as we'd like. I can't speak for the API creators, but I think they decided to leave it the way it is because the namespace can increase faster than the JDK is updated, and maintaining the enums up-to-date would be an endless and always-incomplete job. If you really want to check if a timezone name is valid, you can do: if (ZoneId.getAvailableZoneIds().contains("America/Sao_Paulo")) { // America/Sao_Paulo is a valid ID} Or just call ZoneId.of("zone-name") and catch the ZoneRulesException . I've just called ZoneId.getAvailableZoneIds() in JDK 1.8.0_131 and it has 600 entries. Probably nobody wanted to create 600 enum constants. One could argue that they could've done something similar to java.util.Locale class, which has a few entries for some languages (like English, German, French, etc). But how to decide which timezones "deserve" a constant? Maybe they just decided to not think too much about that and "hey, forget it, just use a String with the zone name" . Another possible reason can be the fact that ZoneId.of() method was designed to also receive UTC offsets (such as +05:00 , -0300 , +09:30:15 and so on). As the offsets accept hours, minutes and seconds, there are hundreds of possible offsets and creating enums for each one would be impractical. Again, one could argue "Hey, create just the enums for the names and forget about the offsets" . But the possible reasons for not creating enum names were already discussed above.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44836984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3670143/']}
jdg_74615
stackexchange
llm_judgeable_groundtruth_similarity
5744507
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 build a server to accept client connection with a very high frequency and load (each user will send a request each 0.5 seconds and should get a response in under 800ms, I should be able to support thousands of users on one server). The assumption is that the SQL Server is finely tuned and will not pose a problem. (assumption that of course might not be true) I'm looking to write a non-blocking server to accomplish this. My back end is an SQL Server which is sitting on another machine. It doesn't have to be updated live - so I think I can cache most of the data in memory and dump it to the DB every 10-20 seconds. Should I write the server using C# (which is more compatible with SQL Server)? maybe Python with Tornado? What should be my considerations when write a high-performance server? EDIT: (added more info) The Application is a game server. I don't really know the actual traffic - but this is the prognosis and the server should support it and scale well. It's hosted "in the cloud" in a Datacenter. Language doesn't really matter. Performance does. (a Web service can be exposed on the SQL Server to allow other languages than .NET) The connections are very frequent but small (very little data is returned and little computations are necessary). It should hold most of the data in the memory for fastest performance. Any thoughts will be much appreciated :) Thanks Now provide the response and nothing else.
When the provided example is built in release mode and then JIT-ed into 64-bit machine code, it does not contain enough information for the debugger to correlate the breakpoint with any particular machine instruction. That’s why debugger never stops at this breakpoint during execution of a JIT-ed machine code. It just does not know where to stop. Probably it is some kind of misbehavior or even a bug in 64-bit CLR debugger because it is reproducible only when it is JIT-ed into 64-bit machine code but not into 32-bit machine code. When the debugger sees a breakpoint in your code it tries to find out a machine instruction in the JIT-ed code that corresponds to the location marked by the breakpoint. First, it needs to find an IL instruction that corresponds to a breakpoint location in your C# code. Then it needs to find a machine instruction that corresponds to the IL command. Then it sets a real breakpoint on the found machine instruction and starts execution of the method. In your case, it looks like that the debugger just ignores a breakpoint because it cannot map it to a particular machine instruction. The debugger cannot find an address of a machine instruction that immediately follows if…else statement. The if…else statement and the code inside it somehow causes this behavior. It does not matter what statement follows the if…else. You can replace the Console.WriteLine(“2”) statement with some other one and you will be still able to reproduce the issue. You will see that the C# compiler emits a try…catch block around the logic that reads the list if you will disassemble the resulting assembly with Reflector. It is a documented feature of the C# compiler. You can read more about it at The foreach statement A try…catch…finally block has a pretty invasive effect on a JIT-ed code. It uses the Windows SEH mechanism under the hood and rewrites your code badly. I cannot find a link to a good article right now but I’m sure that you can find one out there if you are interested. It is what happens here. The try…finally block inside of if…else statement causes the debugger to hiccup. You can reproduce your issue with a much simple code. bool b = false;if (b){ try { b = true; } finally { b = true; }}else{ b = true;}b = true; This code does not call any external functions (it eliminates effect of method inlining proposed by one of the answers) and it compiles directly into IL without any additional coded added by the C# compiler. It is reproducible only in release mode because in the debug mode the compiler emits the IL NOP instruction for every line of your C# code. The IL NOP instruction does nothing and it is directly compiled to the CPU NOP instruction by the JITer that does nothing too. The usefulness of this instruction is that it can be used by the debugger as an anchor for breakpoints even if the rest of the code is badly rewritten by the JITer. I was able to make the debugger to work correctly by putting one NOP instruction right before the statement that follows the if…else. You can read more about NOP operations and debugger mapping process here Debugging IL You can try to use WinDbg and SOS extension for it to examine JIT-ed version of the method. You can try to examine machine code that JIT-er generates and try to understand why it cannot map back that machine code to particular line of C#. Here are couple link about using WinDbg for breaking in managed code and getting a memory address of a JIT-ed method. I believe that you should be able to find a way to get JIT-ed code for a method from there: Setting a breakpoint in WinDbg for Managed Code , SOS Cheat Sheet (.NET 2.0/3.0/3.5) . You can also try to report an issue to Microsoft. Probably this is a CLR debugger bug. Thank you for the interesting question.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5744507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/239279/']}
jdg_74616
stackexchange
llm_judgeable_groundtruth_similarity
26860762
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Herewith I added my source code of web.xml <?xml version="1.0" encoding="UTF-8"?><web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name>ussd</display-name> <servlet> <servlet-name>init</servlet-name> <jsp-file>/init.jsp</jsp-file> <load-on-startup>1</load-on-startup> </servlet> <context-param> <param-name>javax.ws.rs.core.Application</param-name> <param-value>com.dialog.mife.ussd.api.USSDApplication</param-value> </context-param> <context-param> <param-name>resteasy.providers</param-name> <param-value>com.dialog.mife.ussd.exception.NotFoundException</param-value> </context-param> <context-param> <param-name>resteasy.servlet.mapping.prefix</param-name> <param-value>/</param-value> </context-param> <listener> <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class> </listener> <servlet> <servlet-name>Resteasy</servlet-name> <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class> </servlet> <servlet> <servlet-name>ServletAdaptor</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Resteasy</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ServletAdaptor</servlet-name> <url-pattern>/webresources/*</url-pattern> </servlet-mapping></web-app> Hibernate.cfg.xml.My Web service project goes with Jersey+Hibernate.. <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <property name="hibernate.bytecode.use_reflection_optimizer">false</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.password">xxx</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/USSD</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property> <property name="connection.pool_size">1</property> <property name="hibernate.connection.autocommit">true</property> <mapping class="com.xxx.xxx.xxx.xxx.Application" /> </session-factory></hibernate-configuration> Here is HibernateUtil Class public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Exception ex) { ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } Here is my errorI added Hibernate latest jar files.[ hibernate-core-4.3.7.Final.jar ] SEVERE: StandardWrapper.Throwablejava.lang.NoClassDefFoundError: Could not initialize class com.dialog.mife.ussd.util.HibernateUtil at org.apache.jsp.init_jsp.jspInit(init_jsp.java:23) at org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:48) at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:180) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.init(JspServlet.java:138) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5123) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5407) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744)Nov 11, 2014 2:06:11 PM org.apache.catalina.core.StandardContext loadOnStartupSEVERE: Servlet /ussd threw load() exceptionjava.lang.NoClassDefFoundError: Could not initialize class com.dialog.mife.ussd.util.HibernateUtil at org.apache.jsp.init_jsp.jspInit(init_jsp.java:23) at org.apache.jasper.runtime.HttpJspBase.init(HttpJspBase.java:48) at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:180) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) at org.apache.jasper.servlet.JspServlet.init(JspServlet.java:138) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5123) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5407) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Please help me to sort out this issuethanks Now provide the response and nothing else.
This Kind of an error can be happened when initialization of SessionFactory fails. You have mentioned that you are using hibernate-core-4.3.7 . The way you are initializing the SessionFactory is not the correct for this version. Use Hibernate version 3.x or change the way you are initializing the SessionFactory . Below is the correct way to build the session factory in Hibernate 4.x + . Configuration configuration = new Configuration().configure();StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());SessionFactory factory = configuration.buildSessionFactory(builder.build());
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26860762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3898057/']}
jdg_74617
stackexchange
llm_judgeable_groundtruth_similarity
143224
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: Since the spectra of hydrogen and antihydrogen are the same, how do astronomers know which one they're detecting? Is, perhaps, the Lamb shift in antihydrogen different? Now provide the response and nothing else.
One cannot tell by the light spectra. Hydrogen and antihydrogen would give the same lines in the spectrum. The prevalence of matter over antimatter from other evidence indicates matter is predominant in the observable universe, and here is a nice review . How do we really know that the universe is not matter-antimatter symmetric? The Moon: Neil Armstrong did not annihilate, therefore the moon is made of matter. The Sun: Solar cosmic rays are matter, not antimatter. The other Planets: We have sent probes to almost all. Their survival demonstrates that the solar system is made of matter. The Milky Way: Cosmic rays sample material from the entire galaxy. In cosmic rays, protons outnumber antiprotons $10^4$ to $1$ . The Universe at large: This is tougher. If there were antimatter galaxies then we should see gamma emissions from annihilation. Its absence is strong evidence that at least the nearby clusters of galaxies (e.g., Virgo) are matter-dominated. At larger scales there is little proof. However, there is a problem, called the "annihilation catastrophe" which probably eliminates the possibility of a matter-antimatter symmetric universe. Essentially, causality prevents the separation of large chucks of antimatter from matter fast enough to prevent their mutual annihilation in the early universe. So the Universe is most likely matter dominated. So the astronomers presume they are detecting hydrogen, based on the analysis above.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/143224', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/31819/']}
jdg_74618
stackexchange
llm_judgeable_groundtruth_similarity
94888
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: Why are the continents wider at the north and tapering towards the south? Now provide the response and nothing else.
The fundamental unit that makes up the continental land masses is called a craton . Basically a craton is a chunk of crust that is small enough to resist being broken up by tectonic forces, so it has existed since continental crust first formed. The continents we see today are not fundamental units, but instead are made up of lots of cratons that have aggregated. For example Africa is made up of five cratons of essentially random shapes and sizes. The continents we see today originated when the supercontinent Pangea broke up. The breaks happened at the edges of cratons, but exactly where the breaks happened was effectively random. It would have been impossible for a Paleozoic geologist to predict exactly which cratons were going to end up in which continent. The point of all this is that the shapes of the continents are random accidents related to exactly how the tectonic plates were moving when Pangea broke up. Even if it's true that all continents are wider at the top then the bottom (which is debatable) this is by chance and there is no deep underlying significance to the observation.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/94888', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/37360/']}
jdg_74619
stackexchange
llm_judgeable_groundtruth_similarity
18198307
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 get the data associated with an order on the woocommerce plugin (wordpress). Currently, I have written my own plugin that contains the code: <?php global $woocommerce;$order = new WC_Order($order_id);$order_shipping_total = $order->get_shipping();echo $order_shipping_total;?> This is just to test it out, I don't believe this is working- BUT what I actually need is to get a list of the orders that have a certain order status, and then be able to access the fields(like first name) for each order in this list. How do I go about doing this?Also, what files do I include to make this work? The class-wc-order() file? Now provide the response and nothing else.
Recently i worked for Export of Orders Data in XML. $args = array( 'post_type' => 'shop_order', 'post_status' => 'publish', 'meta_key' => '_customer_user', 'posts_per_page' => '-1');$my_query = new WP_Query($args);$customer_orders = $my_query->posts;foreach ($customer_orders as $customer_order) { $order = new WC_Order(); $order->populate($customer_order); $orderdata = (array) $order; // $orderdata Array will have Information. for e.g Shippin firstname, Lastname, Address ... and MUCH more.... Just enjoy!}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18198307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2189190/']}
jdg_74620
stackexchange
llm_judgeable_groundtruth_similarity
7945932
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this function in PostgreSQL, but I don't know how to return the result of the query: CREATE OR REPLACE FUNCTION wordFrequency(maxTokens INTEGER) RETURNS SETOF RECORD AS$$BEGIN SELECT text, count(*), 100 / maxTokens * count(*) FROM ( SELECT text FROM token WHERE chartype = 'ALPHABETIC' LIMIT maxTokens ) as tokens GROUP BY text ORDER BY count DESCEND$$LANGUAGE plpgsql; But I don't know how to return the result of the query inside the PostgreSQL function. I found that the return type should be SETOF RECORD , right? But the return command is not right. What is the right way to do this? Now provide the response and nothing else.
Use RETURN QUERY : CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int) RETURNS TABLE (txt text -- also visible as OUT param in function body , cnt bigint , ratio bigint) LANGUAGE plpgsql AS$func$BEGIN RETURN QUERY SELECT t.txt , count(*) AS cnt -- column alias only visible in this query , (count(*) * 100) / _max_tokens -- I added parentheses FROM ( SELECT t.txt FROM token t WHERE t.chartype = 'ALPHABETIC' LIMIT _max_tokens ) t GROUP BY t.txt ORDER BY cnt DESC; -- potential ambiguity END$func$; Call: SELECT * FROM word_frequency(123); Defining the return type explicitly is much more practical than returning a generic record . This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query. Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example. But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case ( RETURN QUERY SELECT ... ) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion: Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC . Example: Select first row in each GROUP BY group? Repeat the expression ORDER BY count(*) . (Not required here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See: Naming conflict between function parameter and result of JOIN with USING clause Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples, you may want more explicit names. Added a missing ; and corrected a syntax error in the header. (_max_tokens int) , not (int maxTokens) - data type after name. While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Or work with numeric or a floating point type. See below. Alternative This is what I think your query should actually look like (calculating a relative share per token ): CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int) RETURNS TABLE (txt text , abs_cnt bigint , relative_share numeric) LANGUAGE plpgsql AS$func$BEGIN RETURN QUERY SELECT t.txt, t.cnt , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2) -- AS relative_share FROM ( SELECT t.txt, count(*) AS cnt FROM token t WHERE t.chartype = 'ALPHABETIC' GROUP BY t.txt ORDER BY cnt DESC LIMIT _max_tokens ) t ORDER BY t.cnt DESC;END$func$; The expression sum(t.cnt) OVER () is a window function . You could use a CTE instead of the subquery. Pretty, but a subquery is typically cheaper in simple cases like this one (mostly before Postgres 12). A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters). round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/7945932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/734984/']}
jdg_74621
stackexchange
llm_judgeable_groundtruth_similarity
32572460
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to make text box accept only specific characters. My TextBox is bound to the following: private string _CompanyID; public string CompanyID { get { return _CompanyID; } set { _CompanyID = UniversalHelpers.sReturnCorrectColumnName(value); OnPropertyChanged("CompanyID"); } } Where this is the function that is being called: public static string sReturnCorrectColumnName(string sInput) { if(!string.IsNullOrWhiteSpace(sInput)) return Regex.Replace(sInput, @"[^a-zA-Z]", string.Empty).ToUpper(); else return sInput; } (I am allowing only a-z & A-Z, nothing else). Finally my TextBox looks like this: <TextBox Text="{Binding ExcelBindings.CompanyID, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> What I don't understand is, that user can still write anything he wants, even though my Mode is set to TwoWay. What am I doing wrong? Now provide the response and nothing else.
You should use a custom UI element there that restricts the input on the view-side using “classic” solutions like change listeners. For example, you can just create a simple subtype of TextBox that overrides the OnPreviewTextInput method. There, you can decide when some input should go through, or when you want to prevent it. For example, this is a custom TextBox that takes only characters from the ASCII alphabet: public class AlphabetTextBox : TextBox{ private static readonly Regex regex = new Regex("^[a-zA-Z]+$"); protected override void OnPreviewTextInput(TextCompositionEventArgs e) { if (!regex.IsMatch(e.Text)) e.Handled = true; base.OnPreviewTextInput(e); }} Of course, you could also make the regular expression a property of the text box and allow people to set it from XAML. That way, you would get a very reusable component which you can use for various applications.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32572460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1539189/']}
jdg_74622
stackexchange
llm_judgeable_groundtruth_similarity
1768317
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Show that $\sin(x) > \ln(x+1)$ when $x \in (0,1)$. I'm expected to use the maclaurin series (taylor series when a=0) So if i understand it correctly I need to show that: $$\sin(x) = \lim\limits_{n \rightarrow \infty} \sum_{k=1}^{n} \frac{(-1)^{k-1}}{(2k-1)!} \cdot x^{2k-1} > \lim\limits_{n \rightarrow \infty} \sum_{k=1}^{n} \frac{(-1)^{k-1}}{k} \cdot x^k = \ln(x+1)$$ I tried to show that for any k the general term in the bigger sum is greater then the other one (the general term in the smaller sum) but its not true :(. $$\frac{(-1)^{k-1} \cdot x^{2k-1}}{(2k-1)!} > \frac{(-1)^{k-1} \cdot x^k}{k}$$ when k is odd we get: $$\frac{x^{k-1}}{(2k-1)!} > \frac{1}{k}$$ and this is a contradiction since : $x^{k-1} < 1$ for any $x \in (0,1)$ and $k > 1$ and $(2k-1)! > k $ so for any $k > 1 $ its $\frac{x^{k-1}}{(2k-1)!} < \frac{1}{k}$ and if $k=1$ its $\frac{x^{k-1}}{(2k-1)!} = \frac{1}{k}$. What am I doing wrong and how i'm supposed to prove it ? Thanks in advance for help . Now provide the response and nothing else.
As the series are alternating with summands strictly decreasing in absolute value (at least for $0<x<1$), we have$$ \sin x>x-\frac16x^3$$and$$ \ln(1+x)<x-\frac12x^2+\frac13x^3$$Hence the difference is$$ \sin x-\ln(1+x)>\frac12x^2-\frac12x^3=\frac12x^2(1-x)>0.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1768317', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97326/']}
jdg_74623
stackexchange
llm_judgeable_groundtruth_similarity
24607969
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 layers (= AnchorPanes) stacked one of the other with a StackPane. So both layer fill the whole scene. The problem is, that only the top layer receives mouse events. Thats how the scene is build: Only Button B receives click events but Button A not. If I set Layer B to mouse transparent ( layerB.setMouseTransparent(true) ), Button A receives mouse events. But mouse transparent effects also all children, so Button B dont receives mouse events any more. How to get Button A and Button B to receive mouse events? Here is the full working source: public class LayerTest extends Application { @Override public void start(final Stage primaryStage) throws Exception { final Node layerA = createLayerA(); final Node layerB = createLayerB(); final Parent root = new StackPane(layerA, layerB); final Scene scene = new Scene(root); primaryStage.setScene(scene); primaryStage.setWidth(250); primaryStage.setHeight(200); primaryStage.show(); } private Node createLayerA() { final AnchorPane layerA = new AnchorPane(); final Button buttonA = new Button("Button A"); AnchorPane.setLeftAnchor(buttonA, 10d); AnchorPane.setTopAnchor(buttonA, 10d); buttonA.setOnMouseClicked(e -> System.out.println("Button A clicked")); layerA.getChildren().setAll(buttonA); return layerA; } private Node createLayerB() { final AnchorPane layerB = new AnchorPane(); final Button buttonB = new Button("Button B"); AnchorPane.setRightAnchor(buttonB, 10d); AnchorPane.setBottomAnchor(buttonB, 10d); buttonB.setOnMouseClicked(e -> System.out.println("Button B clicked")); layerB.getChildren().setAll(buttonB); return layerB; } public static void main(String[] args) { launch(args); }} Now provide the response and nothing else.
Solution Add the following line to your sample code: layerB.setPickOnBounds(false); This will allow the mouse to interact with the visible elements you can see through the layers of your stacked elements. If elements in the top layer overlap elements in the bottom layer clicking on the part of the top layer which overlaps the bottom layer will have the top layer consume the mouse event and the bottom layer will not receive it (which is probably what you want). Alternate Interpretation If you actually wanted to intercept and handle the mouse event in all layers then see the linked questions from Uluk's comments: JavaFX 2 event dispatching to underlying nodes JavaFx, event interception/consumption Method Description A description of the setPickOnBounds method: Defines how the picking computation is done for this node when triggered by a MouseEvent or a contains function call. If pickOnBounds is true, then picking is computed by intersecting with the bounds of this node, else picking is computed by intersecting with the geometric shape of this node. Panes have no visible background by default, so why they should consume mouse events? For modena.css, the default stylesheet that ships with JavaFX 8, Panes actually do have a very faint shaded background by default, so they can consume mouse events. To prevent this you can either set the background color of the pane to null or set the Pane to mouseTransparent . This behavior changed between JavaFX 2 and JavaFX 8. JavaFX 2 shipped with a default stylesheet named caspian.css, which does not set a background for Panes.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24607969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/854600/']}
jdg_74624
stackexchange
llm_judgeable_groundtruth_similarity
352368
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've made a small change to an integration component and have prepared unit tests to cover my work. All new and existing unit tests are passing. It will take a substantial amount of time to configure and run the component locally as I will need to restore databases, check firewall rules etc. The definition of Done in terms of development work is unclear. Is a unit test a better replacement for works-on-my-machine? Is it seen as unprofessional if I do not confirm the changes manually before passing work over to a test team? Now provide the response and nothing else.
Is a unit test a better replacement for works-on-my-machine? Yes, it's absurdly better. Unless you've got some sort of containerization to guarantee the configuration of your environment, running on your local machine guarantees nothing. And even then, doing it by hand is just asking for others to screw up doing the same thing by hand. Unit tests verify that the functionality itself works, quickly, reliably, repeatably. Is it seen as unprofessional if I do not confirm the changes manually before passing work over to a test team? It can be. Different work environments have different standard operating procedures and expectations. I expect that most environments either wouldn't care that you only ran the unit tests or wouldn't care enough to know that you only ran the unit tests. Personally, I'll only manually verify things that are for some reason prohibitive to unit test or being picked up by an abundantly sensitive stakeholder.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/352368', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/195338/']}
jdg_74625
stackexchange
llm_judgeable_groundtruth_similarity
3337419
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 my template, I have the following: <ul class="tabbed" id="network-tabs"> {% if user.is_authenticated %} <li><a href="{% url acct-my-profile %}">My Account</a></li> <li><a href="{% url acct-logout %}">Log Out</a></li> {% else %} <li><a href="{% url acct-login %}">Log in</a></li> <li><a href="{% url acct-register %}">Register</a></li> {% endif %} </ul> It seems to work fine, unless the page been created has a @login_required decorator, in which case the page works fine but the navigation appears as if the user is not logged in, even when they are. Now provide the response and nothing else.
You should check your view function to see where the user variable is coming from. Unless you're specifically passing user into the context from the view, that's your problem. You do have access to request.user , though, and that will always return true in a template rendered from a view that has the @login_required decorator. The reason I can tell you for certain that there's nothing wrong with the decorator, though, is that in the code for User and AnonymousUser (located in django.contrib.auth.models ) the is_authenticated method strictly returns true for User and false for AnonymousUser . The decorator does not and cannot change that. And what that means is that your template isn't actually getting a User object where you're checking user .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3337419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/196423/']}
jdg_74626
stackexchange
llm_judgeable_groundtruth_similarity
5391394
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 enter the values in a range like 1-60. The EditText shouldn't accept values like 61,62..., or 0,-1,-2... How can we give the range 1-60 to EditText in android?I have done in main.xml as <EditText android:layout_height="wrap_content" android:id="@+id/editText1" android:layout_width="160dip" android:inputType="number"> </EditText> Now provide the response and nothing else.
You can assign a TextWatcher to your EditText and listen for text changes there, for example: public void afterTextChanged(Editable s) { try { int val = Integer.parseInt(s.toString()); if(val > 60) { s.replace(0, s.length(), "60", 0, 2); } else if(val < 1) { s.replace(0, s.length(), "1", 0, 1); } } catch (NumberFormatException ex) { // Do something }} As mentioned by Devunwired, notice that calls to s.replace() will call the TextWatcher again recursively. It is typical to wrap these changes with a check on a boolean "editing" flag so the recursive calls skip over and simply return while the changes that come from within.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5391394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/769225/']}
jdg_74627
stackexchange
llm_judgeable_groundtruth_similarity
19234719
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 read that hashtables are thread-safe because it is synchronized. consider this code snippet if(!hashtable.contains(key)){hashtable.put(key,value);} The operations on hashtable may not be synchronized. for example, if Thread t1 access the hastable and check for key and at the same time Thread t2 checks for key, before t1 executes put. now two threads are inside the if block and overwriting of key-value happens. so synchronized block is necessary. synchronized {if(!hashtable.contains(key)){ hashtable.put(key,value); }} Is this understanding correct? or is hastables safe on the operations that is performed upon hastables. I got this doubt while I was reading this post on race condition Now provide the response and nothing else.
You are correct that you need the synchronized block. The Hashtable's methods are synchronized , but you still have the possibility of having a race when calling multiple methods outside of a synchronized block. The built-in synchronization prevents problems when two threads call put at the same time for example. You might also want to look into ConcurrentHashMap
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19234719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1988876/']}
jdg_74628
stackexchange
llm_judgeable_groundtruth_similarity
231770
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: The Incremental approach is a method of software development where the model is designed, implemented and tested incrementally (a little more is added each time) until the product is finished. It involves both development and maintenance. The product is defined as finished when it satisfies all of its requirements The Iterative Design is a design methodology based on a cyclic process of prototyping, testing, analyzing, and refining a product or process. Based on the results of testing the most recent iteration of a design, changes and refinements are made. This process is intended to ultimately improve the quality and functionality of a design. In iterative design, interaction with the designed system is used as a form of research for informing and evolving a project, as successive versions, or iterations of a design are implemented. It seems both methods are about creating a part of the system , refining it to pass all the test cases , adding another component of the system and refining it again , these gets repeated untill the system is finished. What is the actual difference between these two ways of designing software How is it possible to combine these two methods to form iterative and incremental design approach Now provide the response and nothing else.
The Incremental Approach uses a set number of steps and development goes from start to finish in a linear path of progression. Incremental development is done in steps from design, implementation, testing/verification, maintenance. These can be broken down further into sub-steps but most incremental models follow that same pattern. The Waterfall Model is a traditional incremental development approach. The Iterative Approach has no set number of steps, rather development is done in cycles. Iterative development is less concerned with tracking the progress of individual features. Instead, focus is put on creating a working prototype first and adding features in development cycles where the Increment Development steps are done for every cycle. Agile Modeling is a typical iterative approach. The incremental model was originally developed to follow the traditional assembly line model used in factories. Unfortunately, software design and development has little in common with manufacturing physical goods. Code is the blueprint not the finished product of development. Good design choices are often 'discovered' during the development process. Locking the developers into a set of assumptions without the proper context may lead to poor designs in the best case or a complete derailing of the development in the worst. The iterative approach is now becoming common practice because it better fits the natural path of progression in software development. Instead of investing a lot of time/effort chasing the 'perfect design' based on assumptions, the iterative approach is all about creating something that's 'good enough' to start and evolving it to fit the user's needs. tl;dr - If you were writing an essay under the Incremental Model, you'd attempt to write it perfectly from start to finish one sentence at at time. If you wrote it under the Iterative Model, you'd bang out a quick rough draft and work to improve it through a set of revision phases. Update: I modified my definition for 'Incremental Approach' to fit a more practical example. If you have ever had to deal with contracting the Incremental Approach is how most contracts are carried out (especially for the military). Despite the many subtle variations of the typical 'Waterfall Model' most/all of them are applied the same way in practice. The steps go as follows: Contract Award Preliminary Design Review Critical Design Review Specification Freeze Development Fielding/Integration Verification Reliability Testing The PDR and CDR are where the spec is created and revised. Once the spec is complete, it should be frozen to prevent scope creep. Integration occurs if the software is used to extend a pre-existing system. Verification is for checking that the application matches the spec. Reliability is a test to prove that the application will be reliable over the long term, this can be specified much like a SLA (Service Level Agreement) where the system is required to sustain a certain percentage of uptime (ex 99% uptime for 3 months). This model works great for systems that are straightforward to specify on paper but difficult to produce. Software is very difficult to specify on paper to any appreciable degree of detail (ex UML). Most 'business types' in charge of management/contracting fail to realize that -- when it comes to software development -- the code itself is the spec. Paper specifications often take as much or more time/effort to write as the code itself and they usually prove to be incomplete/inferior in practice. Incremental approaches attempt to the wasted time/resources by treating the code itself as the specification. Instead of running the paper spec through multiple revision steps, the code itself goes through multiple cycles of revision.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/231770', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/113266/']}
jdg_74629
stackexchange
llm_judgeable_groundtruth_similarity
1602078
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: There are $n$ prisoners and $n$ hats. Each hat is colored with one of $k$ given colors. Each prisoner is assigned a random hat, but the number of each color hat is not known to the prisoners. The prisoners will be lined up single file where each can see the hats in front of him but not behind. Starting with the prisoner in the back of the line and moving forward, they must each, in turn, say only one word which must be one of the $k$ given colors. If the word matches their hat color they are released, if not, they are killed on the spot. They can set up a strategy before the test, so they choose a strategy that maximizes the number of definitely released prisoners (that number is called the number of the strategy . What is that number? Now provide the response and nothing else.
Label the colors $\{1,2,3\dots k\}$. The first one says the sum of the hats in front of him $\bmod k$ (the last $n-1$ persons). After this the second one can deduce which number corresponds to the color of his hat (by subtracting the sum that he can see minus the sum previously said). The third person, having heard all of this, can now deduce the sum of the last $n-2$ people, and by substracting this from the sum of the hats he sees (last $n-3$) he can deduce which hat he has. This process continues on to the last person. All of them are saved except for the first one, which survives with probability $\frac{1}{k}$. It is clear that no matter which strategy we follow, the probability the first person survives is $\frac{1}{k}$. So this strategy is optimal. The maximum strategy number is hence $n-1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1602078', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/125366/']}
jdg_74630
stackexchange
llm_judgeable_groundtruth_similarity
443640
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Running this code as a regular user throws HttpListenerException (access denied). Snippet runs ok as an administator class Program{ static void Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://myip:8080/app/"); listener.Start(); //.... and so on }} i went ahead and added the uri using netsh (netsh http show lists the uri) netsh http add urlacl url=http://+:8080/app user=domain\user still getting the same error. Adding ACLs did work for other projects (they didn't use HttpListener though). I tried multiple port/application name combinations, nothing works. Any ideas what might be the cause? Running .Net 3.5 SP1 on Vista Now provide the response and nothing else.
I do not understand why but here it is. It seems that the cause is that my network card is configured with 2 IPs. if in the code i specify one of the ips (like i did in question above) listener.Prefixes.Add("http://myip1:8080/app/"); then to avoid exception i need to register it with IP-bound weak wildcard netsh http add urlacl url=http://myip1:8080/app user=domain\user however if i add prefix with the strong wildcard (plus sign) listener.Prefixes.Add("http://+:8080/app/"); and register with the same wild card netsh http add urlacl url=http://+:8080/app user=domain\user then there is no error and i can access my app from both ip.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/443640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14074/']}
jdg_74631
stackexchange
llm_judgeable_groundtruth_similarity
51087960
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Symfony version(s) affected: ~4.0 DescriptionI am using laravel(5.6.*) and write simple eloquent query as follows. $query = "something";$products = Product::where('title', $query)->paginate($limit); But i get "Object of class Symfony\Component\HttpFoundation\ParameterBag could not be converted to string" Yesterday it is working perfectly fine and today i don't know what happened.Please help me with this.I am providing simple search functionality using that query. Please check screen shot for more information. Update Please look at new code but still no luck in that. function get(Request $request) { $limit = 10; $query = ""; if ($request->has('limit')) { $limit = $request->limit; } if ($request->has('query')) { $query = $request->query; } $products = Product:: where('title','like', '%'.$query.'%') ->orWhere('variant_title', 'like', '%'.$query.'%') ->orWhere('variant_sku', 'like', '%'.$query.'%') ->orWhere('tags', 'like', '%'.$query.'%') ->paginate($limit); $products = $products->withPath('/products'); return $products; } Now provide the response and nothing else.
Oh man after lots of hours debugging finally i found that You cannot use "query" key for your request as it is used in package. I feel like they should mention parameters they used in classes. So final code would be like this. function get(Request $request) { $limit = 10; $str = ""; if ($request->has('limit')) { $limit = $request->limit; } if ($request->has('str')) { $str = $request->str; } $products = Product:: where('title','like', '%'.$str.'%') ->orWhere('variant_title', 'like', '%'.$str.'%') ->orWhere('variant_sku', 'like', '%'.$str.'%') ->orWhere('tags', 'like', '%'.$str.'%') ->paginate($limit); $products = $products->withPath('/products'); return $products;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51087960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5141834/']}
jdg_74632
stackexchange
llm_judgeable_groundtruth_similarity
25937413
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to add values to a 2D vector by using both indices. When I run my program, I get the windows message saying the program has stopped working. Using Dev-C++ to debug showed that there was a segmentation fault (I am not sure what this means). Please do not suggest using arrays, I have to use vectors for this assignment. #include <iostream>#include <vector>using namespace std;int main(int argc, char** argv) { vector< vector<int> > matrix;cout << "Filling matrix with test numbers.";for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { matrix[i][j] = 5; // causes program to stop working }}} I have created a test case where I want to fill a 3X3 matrix with the value 5. I suspect that it has something to do with the size of the 2D vector not being specifically defined. How would I fill a 2D vector with values by using the indices? Now provide the response and nothing else.
As written, this is problematic, you are trying to write to a vector for which you did not yet allocate memory. Option 1 - Resize your vectors ahead of time vector< vector<int> > matrix;cout << "Filling matrix with test numbers.";matrix.resize(4); // resize top level vectorfor (int i = 0; i < 4; i++){ matrix[i].resize(4); // resize each of the contained vectors for (int j = 0; j < 4; j++) { matrix[i][j] = 5; }} Option 2 - Size your vector when you declare it vector<vector<int>> matrix(4, vector<int>(4)); Option 3 - Use push_back to resize the vector as needed. vector< vector<int> > matrix;cout << "Filling matrix with test numbers.";for (int i = 0; i < 4; i++){ vector<int> temp; for (int j = 0; j < 4; j++) { temp.push_back(5); } matrix.push_back(temp);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25937413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2221827/']}
jdg_74633
stackexchange
llm_judgeable_groundtruth_similarity
11787313
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: According to Spring's documentation the way to use the TaskExecutor is as follows: import org.springframework.core.task.TaskExecutor;public class TaskExecutorExample { private class MessagePrinterTask implements Runnable { private String message; public MessagePrinterTask(String message) { this.message = message; } public void run() { System.out.println(message); } } private TaskExecutor taskExecutor; public TaskExecutorExample(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void printMessages() { for(int i = 0; i < 25; i++) { taskExecutor.execute(new MessagePrinterTask("Message" + i)); } }} However, if MessagePrinterTask has autowired dependencies they will not be configured by Spring because we are instantiating our bean outside of Spring's context (at least that's how I understand it) even though Spring will provide the actual thread creation. If MessagePrinterTask were to have autowired dependencies how do we get Spring to recognize them? I tried the following modified example to no avail (and yes, autowiring is enabled properly): import org.springframework.core.task.TaskExecutor;public class TaskExecutorExample { @Component private class MessagePrinterTask implements Runnable { @Autowired private autoWiredDependency; public void run() { autoWiredDependency.doNotThrowNullPointerExceptionPlease(); } } private TaskExecutor taskExecutor; public TaskExecutorExample(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void printMessages() { for(int i = 0; i < 25; i++) { taskExecutor.execute(new MessagePrinterTask()); } }} Now provide the response and nothing else.
There are two ways I think that you can go about this: a. Provide the dependencies to the Task - this way: class MessagePrinterTask implements Runnable { public MessagePrinterTask(ADependency aDependency){ this.aDependency = aDependency; } private ADependency aDependency; public void run() { aDependency.doNotThrowNullPointerExceptionPlease(); }} And in your TaskExectorExample which can be the singleton: import org.springframework.core.task.TaskExecutor;public class TaskExecutorExample { @Autowired private ADependency aDependency; @Autowired public TaskExecutorExample(TaskExecutor taskExecutor) { this.taskExecutor = taskExecutor; } public void printMessages() { for(int i = 0; i < 25; i++) { taskExecutor.execute(new MessagePrinterTask(this.aDependency)); } }} b. Using @Configurable annotation on your MesasgePrinterTask, this will inject in dependencies into MessagePrinterTask even though it is instantiated outside of a Spring Container - there are some catches in using @Configurable though(requires AspectJ): @Configurableclass MessagePrinterTask implements Runnable {
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11787313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/641785/']}
jdg_74634
stackexchange
llm_judgeable_groundtruth_similarity
84305
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I encountered a problem which roughly translates to the following in mathematical terms: Given a directed graph, find an optimal vertex partitioning to maximize the edges inside partitions (strong cohesion) and minimize them between partitions (loose coupling). I've yet to find the exact metric to optimize for but is there an algorithm that can do something like this? Now provide the response and nothing else.
Your conjecture is true in the light of the following statements. Proposition 1. A prime $p$ has the form $x^2+24y^2$ if and only if $p\equiv 1\pmod{24}$. Proposition 2. A prime square $p^2$ divides $\Phi_{24}(n)$ for some $n$ if and only if $p\equiv 1\pmod{24}$. Proof of Proposition 1. The four equivalence classes of binary quadratic forms of discriminant $-96$ are represented by $x^2+24y^2$, $3x^2+8y^2$, $4x^2+4xy+7y^2$, $5x^2+2xy+5y^2$. Looking at the values in $(\mathbb{Z}/96\mathbb{Z})^\times$ assumed by these four quadratic forms, we see that they are in four different genera. This means that if $Q(x,y)$ is any of these forms and $p\geq 5$ is any prime, then $Q(x,y)$ represents $p$ if and only if it does so modulo $96$. In particular, $x^2+24y^2$ represents $p$ if and only if $p\equiv 1,25,49,73\pmod{96}$, i.e. when $p\equiv 1\pmod{24}$. Proof of Proposition 2. By Hensel's Lemma, the square of a prime $p\geq 5$ divides $\Phi_{24}(n)$ for some $n$ if and only if $p$ divides $\Phi_{24}(m)$ for some $m$. The latter property holds if and only if $\mathbb{F}_p$ contains a primitive $24$-th root of unity, i.e. when $p\equiv 1\pmod{24}$. References: Rose - A course in number theory; Cox - Primes of the form $x^2+ny^2$
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/84305', 'https://mathoverflow.net', 'https://mathoverflow.net/users/20175/']}
jdg_74635
stackexchange
llm_judgeable_groundtruth_similarity
366443
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 $R$ be a commutative ring with characteristic $0$ , namely it contains the field of rational numbers. Higher Algebra Proposition 7.1.4.10 tells that the category of commutative $R$ -dg-algebras $\mathrm{CAlg^{dg}}(R)$ has a model structure induced from the projective model structure on chain complexes $\mathrm{Ch}(R)$ , where weak equivalences are quasi-isomorphisms and fibrations are surjections (so, a morphism of commutative dg-algebras is a fibration or a weak equivalence if its underlying morphism of chain complexes is such). In the proof of the following Proposition 7.1.4.11, an unproved claim (a condition in 4.5.4.7) is implicitly used, namely: The forgetful functor $\mathrm{CAlg^{dg}}(R) \to \mathrm{Ch}(R)$ preserves fibrant-cofibrant objects. Now, every object is fibrant with respect to the considered model structures, so this claim boils down to check that if $A$ is a cofibrant object in $\mathrm{CAlg^{dg}}(R)$ , then its underlying chain complex is cofibrant with respect to the projective model structure on $\mathrm{Ch}(R)$ . How can I prove this? If $R$ were a field then it would be very easy, because every chain complex over a field is cofibrant. I feel that I should somehow use that $R$ has characteristic $0$ (it contains $\mathbb Q$ ), but can't precisely figure out how. Now provide the response and nothing else.
1. $(K,+)$ and $(\mathbb R,+)$ are isomorphic. The additive group of any field $K$ is a vector space over its prime field ( $\mathbb F_p$ or $\mathbb Q$ ), hence it is determined up to isomorphism by the characteristic of $K$ and its degree over the prime field (which is just $|K|$ for uncountable $K$ ). Here, $K$ and $\mathbb R$ are both fields of characteristic $0$ and cardinality $2^\omega$ . 2a. There exists a surjective homomorphism $K^\times\to\mathbb R^\times$ . Observe that $\mathbb R^\times\simeq\{1,-1\}\times(\mathbb R_{>0},{\times})\simeq C_2\times\mathbb Q^{(2^\omega)}$ . In any finite field of odd characteristic, squares are an index- $2$ subgroup of the multiplicative group. This is a first-order property, hence it also holds in $K$ , i.e., $[K^\times:(K^\times)^2]=2$ . We start by constructing a surjective homomorphism $(K^\times)^2\to\mathbb R_{>0}$ . Let $G$ be the quotient of $(K^\times)^2$ by its torsion part. Since there are only countably many roots of unity in $K$ , $G$ is a torsion-free group of cardinality $2^\omega$ , hence it has rank $2^\omega$ , i.e., we may fix a $\mathbb Q$ -linearly independent subset $\{a_r:r\in\mathbb R_{>0}\}\subseteq G$ . Then $a_r\mapsto r$ extends to a surjective homomorphism $\langle a_r:r\in\mathbb R_{>0}\rangle\to\mathbb R_{>0}$ . Since $\mathbb R_{>0}$ is divisible, we can extend it to a homorphism $G\to\mathbb R_{>0}$ , which we compose with the quotient map to obtain $\phi\colon (K^\times)^2\to\mathbb R_{>0}$ . Finally, let us fix $a\in K^\times\smallsetminus(K^\times)^2$ . Then $\phi$ extends to a surjective homomorphism $K^\times\to\mathbb R^\times$ by putting $\phi(ax)=-\sqrt{\phi(a^2)}\phi(x)$ for $x\in (K^\times)^2$ . 2b. Whether there exists a surjective homomorphism (or isomorphism) $\mathbb R^\times\to K^\times$ depends on the ultrafilter. Let $$I_2=\{n:p_n\not\equiv1\pmod4\},$$ and for odd prime $q$ , $$I_q=\{n:p_n\not\equiv1\pmod q\}.$$ Notice that for $p,q$ odd and $p\ne q$ , the fact that $\mathbb F_{p_n}^\times\simeq C_{p_n-1}$ implies $$n\in I_q\iff\mathbb F_{p_n}\models\forall x\,\exists y\,(y^q=x),\tag{$*$}$$ and $$n\in I_2\iff\mathbb F_{p_n}\models\forall x\,\exists y\,(x^2=y^4).\tag{$**$}$$ Also notice that by Dirichlet’s theorem on primes in arithmetic progressions, the family $\{I_q:q\text{ prime}\}$ has the strong finite intersection property, hence it is included in a nonprincipal ultrafilter. Case I: $I_q\notin\mathcal U$ for some $q$ . Then there is no surjective homomorphism $\mathbb R^\times\to K^\times$ . Indeed, then the positive first-order formulas in $(*)$ and $(**)$ hold in $\mathbb R^\times$ and in all its quotients, whereas if $I_q\notin\mathcal U$ , the corresponding formula fails in $K$ . Case II: $\{I_q:q\text{ prime}\}\subseteq\mathcal U$ . Then $\mathbb R^\times\simeq K^\times$ . The condition ensures that the formulas $(*)$ and $(**)$ hold in $K$ , thus $(K^\times)^2$ is divisible. Moreover, the $q$ -th roots for odd $q$ are unique (as this is again a first-order property), and similarly, there is no square root of $-1$ . This implies that the torsion part of $K^\times$ is just $\{1,-1\}\simeq C_2$ , and $K^\times\simeq C_2\times(K^\times)^2$ , where $(K^\times)^2$ is a torsion-free divisible group of cardinality $2^\omega$ , i.e., it is isomorphic to $\mathbb Q^{(2^\omega)}$ . The arguments above actually used very little about pseudofinite fields. They can be easily extended to get the following characterization. Let $K$ be a field: There exists a surjective homomorphism $K^\times\to\mathbb R^\times$ iff $|K|\ge2^\omega$ and there is a nonsquare in $K$ . There exists a surjective homomorphism $\mathbb R^\times\to K^\times$ iff $|K|\le2^{\omega}$ , all elements of $K$ have $n$ th roots for all odd $n$ , and for each $x\in K$ , $x$ or $-x$ has a square root. $K^\times\simeq\mathbb R^\times$ iff $|K|=2^\omega$ , there are exactly two roots of unity in $K$ , and $K$ satisfies the conditions in 2.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/366443', 'https://mathoverflow.net', 'https://mathoverflow.net/users/20883/']}
jdg_74636
stackexchange
llm_judgeable_groundtruth_similarity
11523150
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 write a PowerShell script to monitor % CPU utilization of a SQL Server process. I'd like to record snapshots of this number every day so we can monitor it over time and watch for trends. My research online said this WMI query should give me what I want: Get-WmiObject -Query "SELECT PercentProcessorTime FROM win32_PerfFormattedData_PerfProc_Process WHERE Name='SqlServr'" When I run the WMI query I usually get a value somewhere between 30-50% However, when I watch the process in Resource Monitor it usually averages at less than 1% CPU usage I know the WMI query is simply returning snapshot of CPU usage rather than an average over a long period of time so I know the two aren't directly comparable. Even so, I think the snapshot should usually be less than 1% since the Resource Monitor average is less than 1%. Does anybody have any ideas on why there is such a large discrepancy? And how I can get an accurate measurement of the CPU usage for the process? Now provide the response and nothing else.
Everything I've learned about WMI and performance counters over the last couple of days. WMI stands for Windows Management Instrumentation. WMI is a collection of classes registered with the WMI system and the Windows COM subsystem. These classes are known as providers and have any number of public properties that return dynamic data when queried. Windows comes pre-installed with a large number of WMI providers that give you information about the Windows environment. For this question we are concerned with the Win32_PerfRawData* providers and the two wrappers that build off of it. If you query any Win32_PerfRawData* provider directly you'll notice the numbers it returns are scary looking. That's because these providers give the raw data you can use to calculate whatever you want. To make it easier to work with the Win32_PerfRawData* providers Microsoft has provided two wrappers that return nicer answers when queried, PerfMon and Win32_PerfFormattedData* providers. Ok, so how do we get a process's % CPU utilization? We have three options: Get a nicely formatted number from the Win32_PerfFormattedData_PerfProc_Process provider Get a nicely formatted number from PerfMon Calculate the % CPU utilization for ourselves using Win32_PerfRawData_PerfProc_Process We will see that there is a bug with option 1 so that it doesn't work in all cases even though this is the answer usually given on the internet. If you want to get this value from Win32_PerfFormattedData_PerfProc_Process you can use the query mentioned in the question. This will give you the sum of the PercentProcessorTime value for all of this process's threads. The problem is that this sum can be >100 if there is more than 1 core but this property maxes out at 100. So, as long as the sum of all this process's threads is less than 100 you can get your answer by dividing the process's PercentProcessorTime property by the core count of the machine. If you want to get this value from PerfMon in PowerShell you can use Get-Counter "\Process(SqlServr)\% Processor Time" . This will return a number between 0 - (CoreCount * 100). If you want to calculate this value for yourself the PercentProcessorTime property on the Win32_PerfRawData_PerfProc_Process provider returns the CPU time this process has used. So, you'll need to take two snapshots we'll call them s1 and s2. We'll then do (s2.PercentProcessorTime - s1.PercentProcessorTime) / (s2.TimeStamp_Sys100NS - s1.TimeStamp_Sys100NS). And that is the final word. Hope it helps you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11523150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1066291/']}
jdg_74637
stackexchange
llm_judgeable_groundtruth_similarity
3756383
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 android, most event listener methods return a boolean value. What is that true/false value mean ? what will it result in to the subsequence events ? class MyTouchListener implements OnTouchListener { @Override public boolean onTouch(View v, MotionEvent event) { logView.showEvent(event); return true; }} Regarding to the above example, if return true in onTouch method,I found every touch event(DOWN,UP,MOVE,etc) has been captured according to my logView . On the contrary,if return false, onely the DOWN event been captured. So it's seemd that return false will prevent the event to propagate. Am I correct ? Furthermore, in a OnGestureListener , many methods have to return a boolean value too. Do they have the same meaning ? Now provide the response and nothing else.
If you return true from an ACTION_DOWN event you are interested in the rest of the events in that gesture. A "gesture" in this case means all events until the final ACTION_UP or ACTION_CANCEL . Returning false from an ACTION_DOWN means you do not want the event and other views will have the opportunity to handle it. If you have overlapping views this can be a sibling view. If not it will bubble up to the parent.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3756383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/388887/']}
jdg_74638
stackexchange
llm_judgeable_groundtruth_similarity
648741
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to build a controllable constant current sink circuit. I have found a circuit that I liked and tried a simulation. I wanted to get 0-20mA of current using a 0-2V control signal. Everything is alright, but if the load resistance gets too high, the current kind of saturates. I couldn't analyze the circuit properly and I can't figure out what is causing this. Could you please give a few opinions? Now provide the response and nothing else.
The limitation is the 28V you are using to supply the current. If you simplify the load circuit, you'll see what I mean: simulate this circuit – Schematic created using CircuitLab I've replaced the transistor with a wire. When you drive the transistor hard, it acts like a short circuit. If you calculate the current through just the load and the current detect resistor, then you'll see that you can't get more than 13mA through it. To get more current through a large value resistor (load,) you'll need a higher voltage power supply. You'd need a supply voltage of at least 40V to get 20mA through your 2k load resistor.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/648741', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/311265/']}
jdg_74639
stackexchange
llm_judgeable_groundtruth_similarity
1508985
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 JDBC Date column, which if a i use getDate is get the ' date ' part only 02 Oct 2009 but if i use getTimestamp i get the full ' date ' 02 Oct 2009 13:56:78:890 . This is excatly what i want. However the 'date' returned by getTimestamp 'ignores' the GMT values, suppose date; 02 Oct 2009 13:56:78:890 , i end up getting 02 Oct 2009 15:56:78:890 My date was saved as a +2GMT date on the database but the application server is on GMT i.e 2hrs behind How can still get my date as is, 02 Oct 2009 13:56:78:890 Edit I get the date +2 on the client side that is on GMT +2 Now provide the response and nothing else.
That's the difference between Timestamp and other temporal types in MySQL. Timestamp is saved as Unix time_t in UTC but other types store date/time literally without zone information. When you call getTimestamp(), MySQL JDBC driver converts the time from GMT into default timezone if the type is timestamp. It performs no such conversion for other types. You can either change the column type or do the conversion yourself. I recommend former approach.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1508985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67796/']}
jdg_74640