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
5911439
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 plot some arrows using matploblib with the quiver function. But I want to choose the length of each arrow individually using an array. http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.quiver http://matplotlib.sourceforge.net/examples/pylab_examples/quiver_demo.html In these demos and documentation, it is show that you can change scales proportionally to units (x,y, width, height, xy, inches, ...), is there a way to define a scale for each arrow? Now provide the response and nothing else.
To specify each arrow's location and vector and length is an over-specification of the quiver plot. So what you need to do is change the data that you are plotting. If you have the vector field U and V (same U and V as your examples), you can normalize them by: N = numpy.sqrt(U**2+V**2) # there may be a faster numpy "normalize" functionU2, V2 = U/N, V/N Then you can apply whatever scaling factor array you want: U2 *= FV2 *= F
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5911439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/709252/']}
jdg_74641
stackexchange
llm_judgeable_groundtruth_similarity
28848
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: Least common multiple of $A$ and $B$ that is greater than $C$. Is there any algorithm to find it without prime factorization? Now provide the response and nothing else.
Any common multiple of $A$ and $B$ is a multiple of the least common multiple, $\mathrm{lcm}(A,B)$. The least common multiple can be found using the identity$$\mathrm{lcm}(A,B)\gcd(A,B) = |AB|.$$The $\gcd$ can be found using the Euclidean Algorithm, which does not require you to find the prime factorization. So you can find the least common multiple without knowing the prime factorization. Once you know the lcm, call it $K$, then you are merely looking for the smallest integer $n$ such that $nK\gt C$. This is $n = \lceil \frac{C}{K}\rceil$ if $K\neq 0$. (And of course, if $K=0$, then that means that at least one of $A$ and $B$ is equal to $0$, and there is no solution). In summary: Find the greatest common divisor (e.g., using the Euclidean algorithm); Compute $M=|AB|/\gcd(A,B)$. Find the smallest integer $k$ greater than or equal to $C/M$. The multiple you want is $kM$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/28848', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8670/']}
jdg_74642
stackexchange
llm_judgeable_groundtruth_similarity
13402029
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 the side bar become fixed at the top after scrolling to a certain point. var sidebarTopPos = $('#sidebar').offset().top;$(window).scroll(function(event) { if ($(window).scrollTop() >= sidebarTopPos) { $('#sidebar').css({ position: 'fixed', top: 0 }); } else { $('#sidebar').css({ position: 'relative' }); }}); Take a look at this jsfiddle The whole thing works fine when I drag the scrollbar down. However, when I try to scroll using the mousewheel, I see the annoying flicker when the side bar changes from "relative" to "fixed" I've tried so many things. Please help. EDIT : Maybe I should have been more clear. The side bar "flickers" only when it crosses the top div Now provide the response and nothing else.
I was having the same issue, it seems to be a bug that occurs when there is too much going on for your browser to handle based on your computer GPU, Memory, CPU, etc..., I was able to fix it by adding the following transform code to the fixed position element, ( transform: translateZ(0);-webkit-transform: translateZ(0); ) that forces the browser to use hardware acceleration to access the device’s graphical processing unit (GPU) to make pixels fly. Web applications, on the other hand, run in the context of the browser, which lets the software do most (if not all) of the rendering, resulting in less horsepower for transitions. But the Web has been catching up, and most browser vendors now provide graphical hardware acceleration by means of particular CSS rules. Using -webkit-transform: translate3d(0,0,0); will kick the GPU into action for the CSS transitions, making them smoother (higher FPS). Note: translate3d(0,0,0) does nothing in terms of what you see. it moves the object by 0px in x,y and z axis. It's only a technique to force the hardware acceleration. #sidebar { /* MAGIC HAPPENS HERE */ transform: translateZ(0); -webkit-transform: translateZ(0);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13402029', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1781557/']}
jdg_74643
stackexchange
llm_judgeable_groundtruth_similarity
42682357
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 assuming it's a bug since I didn't have any problems until the new update. So I cant use the gradle console to debug my app because I have this warning - "Configuration on demand is an incubating feature. NDK is missing a "platforms" directory. If you are using NDK, verify the ndk.dir is set to a valid NDK directory. It is currently set to C:\Users\Emily Thacker\AppData\Local\Android\Sdk\ndk-bundle. If you are not using NDK, unset the NDK variable from ANDROID_NDK_HOME or local.properties to remove this warning." I am pretty sure I am not using NDK and I dont see how I can fix this problem here is my local.properties ## This file is automatically generated by Android Studio.# Do not modify this file -- YOUR CHANGES WILL BE ERASED!## This file should *NOT* be checked into Version Control Systems,# as it contains information specific to your local configuration.## Location of the SDK. This is only used by Gradle.# For customization when using a Version Control System, please read the# header note.sdk.dir=C\:\\Users\\Emily Thacker\\AppData\\Local\\Android\\Sdk Also I do not see a ANDROID_NDK_HOME file in my directory. Now provide the response and nothing else.
I was able to prevent this annoying message; here is what worked for me. BACKGROUND: I am not using the NDK at all, and had never installed the NDK. However, as mentioned in another answer here by xsveda, this is a Gradle bug that is documented here: https://code.google.com/p/android/issues/detail?id=228424 and so even the "NDK-innocent" may become its victims. The problem is that Gradle is computing the location of an NDK folder by just tacking on the string "/ndk-bundle" to the SDK folder location, even if you have never installed the NDK. After establishing this false expectation of an NDK folder existing in a particular location, each time you build, Gradle gives you a warning that you're "missing" that folder. This is just a warning and does not prevent your build from completing, but it is annoying. HOW I STOPPED THE ANNOYING MESSAGE: Since disk space is cheap, and my time is precious to me, I humored this bug by installing the NDK, even though I do not intend to use it. To do this, you can go to: File -> Project Structure -> SDK Location and look in the Android NDK location field. If you have not installed the NDK, this field will be empty. In that case, below that field will be a link for installing the NDK. Click on that link and install it. It takes a few minutes. Once the installation completes and you close the installation progress dialog, the location of the NDK will be automatically written into the Android NDK location field. This will be something like: C:\dev\astudiosdk\ndk-bundle Click the OK button and build again. The error disappears. Note that you may be able to just type the expected folder into this field; I did not try that. But I don't know whether that might cause some other problems, especially if you eventually decide to actually use the NDK.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42682357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7307846/']}
jdg_74644
stackexchange
llm_judgeable_groundtruth_similarity
189924
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Say I have a 5v linear voltage regulator circuit with a supply voltage of 24v. If the 5v citcuit is using 20amps how many amps will the 24v supply need to deliver? Or will the current be the same? Now provide the response and nothing else.
A linear voltage regulator acts pretty much like an intelligent resistor setting it's value in such way that the voltage behind it is regulated to the wanted voltage. Because of that, the current at the input is almost the same as the current of the output. It will be higher because the linear regulator needs some current as well to do its thing. This also means, that a linear voltage regulator is wasting all the energy to heat, which in your case would turn to be a whopping 380W ((Vin-Vout)*Iin), so that would be a really beefy linear regulator and require a lot of cooling. I'd say it's very impractical. For a case like that a switching regulator will probably be the better choice, as it converts the voltage with a certain efficiency. In good designs it can be very high, 90% or higher is achievable. That means that the input power is higher than the output power but the current would be lower (for a step down converter): $$ \eta = \frac{P_{out}}{P_{in}} \rightarrow P_{in} = \frac{P_{out}}{\eta}$$ In your example with 90% efficiency the input power would be just 111W (instead of 480W for the linear regulator). And the current on the 24V side would turn out to be just 4.63A. Switching regulators have their downsides as well, like a higher output voltage ripple.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/189924', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/68249/']}
jdg_74645
stackexchange
llm_judgeable_groundtruth_similarity
9072320
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 been playing around with programming for arduino but today i've come across a problem that i can't solve with my very limited C knowledge.Here's how it goes.I'm creating a pc application that sends serial input to the arduino (deviceID, command, commandparameters). This arduino will transmit that command over RF to other arduino's. depending on the deviceID the correct arduino will perform the command. To be able to determine the deviceID i want to split that string on the ",".this is my problem, i know how to do this easily in java (even by not using the standard split function), however in C it's a totally different story. Can any of you guys tell me how to get this working? thanks /* Serial Event example When new serial data arrives, this sketch adds it to a String. When a newline is received, the loop prints the string and clears it. A good test for this is to try it with a GPS receiver that sends out NMEA 0183 sentences. Created 9 May 2011 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/SerialEvent */String inputString; // a string to hold incoming databoolean stringComplete = false; // whether the string is completeString[] receivedData;void setup() { // initialize serial: Serial.begin(9600); // reserve 200 bytes for the inputString: inputString.reserve(200);}void loop() { // print the string when a newline arrives: if (stringComplete) { Serial.println(inputString); // clear the string: inputString = ""; stringComplete = false; }}/* SerialEvent occurs whenever a new data comes in the hardware serial RX. This routine is run between each time loop() runs, so using delay inside loop can delay response. Multiple bytes of data may be available. */void serialEvent() { while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); if (inChar == '\n') { stringComplete = true; } // add it to the inputString: if(stringComplete == false) { inputString += inChar; } // if the incoming character is a newline, set a flag // so the main loop can do something about it: }}String[] splitCommand(String text, char splitChar) { int splitCount = countSplitCharacters(text, splitChar); String returnValue[splitCount]; int index = -1; int index2; for(int i = 0; i < splitCount - 1; i++) { index = text.indexOf(splitChar, index + 1); index2 = text.indexOf(splitChar, index + 1); if(index2 < 0) index2 = text.length() - 1; returnValue[i] = text.substring(index, index2); } return returnValue;}int countSplitCharacters(String text, char splitChar) { int returnValue = 0; int index = -1; while (index > -1) { index = text.indexOf(splitChar, index + 1); if(index > -1) returnValue+=1; } return returnValue;} I have decided I'm going to use the strtok function.I'm running into another problem now. The error happened is SerialEvent.cpp: In function 'void splitCommand(String, char)': SerialEvent:68: error: cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)' SerialEvent:68: error: 'null' was not declared in this scope Code is like, String inputString; // a string to hold incoming datavoid splitCommand(String text, char splitChar) { String temp; int index = -1; int index2; for(temp = strtok(text, splitChar); temp; temp = strtok(null, splitChar)) { Serial.println(temp); } for(int i = 0; i < 3; i++) { Serial.println(command[i]); }} Now provide the response and nothing else.
This is an old question, but i have created some piece of code that may help: String getValue(String data, char separator, int index){ int found = 0; int strIndex[] = {0, -1}; int maxIndex = data.length()-1; for(int i=0; i<=maxIndex && found<=index; i++){ if(data.charAt(i)==separator || i==maxIndex){ found++; strIndex[0] = strIndex[1]+1; strIndex[1] = (i == maxIndex) ? i+1 : i; } } return found>index ? data.substring(strIndex[0], strIndex[1]) : "";} This function returns a single string separated by a predefined character at a given index. For example: String split = "hi this is a split test";String word3 = getValue(split, ' ', 2);Serial.println(word3); Should print 'is'. You also can try with index 0 returning 'hi' or safely trying index 5 returning 'test'. Hope this help!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9072320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/736886/']}
jdg_74646
stackexchange
llm_judgeable_groundtruth_similarity
1392820
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 well aware that in C++ int someValue = i++;array[i++] = otherValue; has different effect compared to int someValue = ++i;array[++i] = otherValue; but every once in a while I see statements with prefix increment in for-loops or just by their own: for( int i = 0; i < count; ++i ) { //do stuff} or for( int i = 0; i < count; ) { //do some stuff; if( condition ) { ++i; } else { i += 4; }} In the latter two cases the ++i looks like an attempt to produce smarty-looking code. Am I overseeing something? Is there a reason to use ++i instead of i++ in the latter two cases? Now provide the response and nothing else.
Look at possible implementations of the two operators in own code: // Pre-incrementT*& operator ++() { // Perform increment operation. return *this;}// Post-incrementT operator ++(int) { T copy = *this; ++*this; return copy;} The postfix operator invokes the prefix operator to perform its own operation: by design and in principle the prefix version will always be faster than the postfix version, although the compiler can optimize this in many cases (and especially for builtin types). The preference for the prefix operator is therefore natural; it’s the other that needs explanation: why are so many people intrigued by the use of the prefix operator in situations where it doesn’t matter – yet nobody is ever astonished by the use of the postfix operator.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1392820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57428/']}
jdg_74647
stackexchange
llm_judgeable_groundtruth_similarity
13875786
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 make some callbacks from member functions and everything was ok until I tried to use a template class derived from 2 classes as callback object when I got the following error: error C2440: 'reinterpret_cast' : Pointers to members have different representations; cannot cast between them This thing signaled me that member function pointers have different representations(doh!) What are these representations? What is the difference between them? Now provide the response and nothing else.
Danny Kalev explains this quite nicely : The Underlying Representation of Pointers to Members Although pointers to members behave like ordinary pointers, behind the scenes their representation is quite different. In fact, a pointer to member usually consists of a struct containing up to four fields in certain cases. This is because pointers to members have to support not only ordinary member functions, but also virtual member functions, member functions of objects that have multiple base classes, and member functions of virtual base classes. Thus, the simplest member function can be represented as a set of two pointers: one holding the physical memory address of the member function, and a second pointer that holds the this pointer. However, in cases like a virtual member function, multiple inheritance and virtual inheritance, the pointer to member must store additional information. Therefore, you can't cast pointers to members to ordinary pointers nor can you safely cast between pointers to members of different types. To get a notion of how your compiler represents pointers to members, use the sizeof operator. In the following example, the sizes of a pointer to data member and a pointer to a member function are taken. As you can see, they have different sizes, hence, different representations: struct A{ int x; void f();};int A::*pmi = &A::x;void (A::*pmf)() = &A::f;int n = sizeof (pmi); // 8 byte with my compilerint m = sizeof (pmf); // 12 bytes with my compiler Note that each of these pointers may have a different representation, depending on the class in question and whether the member function is virtual.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13875786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336578/']}
jdg_74648
stackexchange
llm_judgeable_groundtruth_similarity
67733861
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After I update my Angular Application from Angular 11.2.12 to Angular 12.0.0 Angular CLI: 12.0.0Node: 14.15.4Package Manager: npm 6.14.10OS: win32 x64Angular: undefined...Package Version------------------------------------------------------@angular-devkit/architect 0.1200.0 (cli-only)@angular-devkit/core 12.0.0 (cli-only)@angular-devkit/schematics 12.0.0 (cli-only)@schematics/angular 12.0.0 (cli-only)typescript 4.2.4 ng serve generating browser application bundles takes horrible long. Build at: 2021-05-28T06:03:02.008Z - Hash: 3b63141b76ac88698d67 - Time: 63941ms <- change one line in templateBuild at: 2021-05-28T06:08:04.424Z - Hash: e684399b5f80b2b4d785 - Time: 59834ms <- change property nameBuild at: 2021-05-28T06:10:05.725Z - Hash: 8125e1bdc31a25d398b5 - Time: 65621ms <- change one line in model I try different properties for ng serve , at the moment I use: ng serve --source-map=true --hmr --live-reload After update to Angular 12.0.0 I generate an complete new angular app and take over the angular.json to my application myapp : angular.json { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "myapp": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, "root": "", "sourceRoot": "src", "prefix": "myapp", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/myapp", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.json", "inlineStyleLanguage": "scss", "assets": ["src/favicon.ico", "src/assets"], "styles": ["./node_modules/@angular/material/_theming.scss", "src/styles.scss"], "scripts": [] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "500kb", "maximumError": "1mb" }, { "type": "anyComponentStyle", "maximumWarning": "2kb", "maximumError": "4kb" } ], "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "outputHashing": "all" }, "development": { "buildOptimizer": false, "optimization": { "scripts": true, "styles": false, "fonts": false }, "vendorChunk": true, "extractLicenses": false, "sourceMap": true, "namedChunks": true } }, "defaultConfiguration": "production" }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "myapp:build" }, "configurations": { "production": { "browserTarget": "myapp:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "myapp:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "inlineStyleLanguage": "scss", "assets": ["src/favicon.ico", "src/assets"], "styles": ["./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "src/styles.scss"], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": ["tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json"], "exclude": ["**/node_modules/**"] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "myapp:serve" }, "configurations": { "production": { "devServerTarget": "myapp:serve:production" } } } } } }, "defaultProject": "myapp"} Is there something I can do to speed up the Generating browser application bundles (phase: sealing) ? Now provide the response and nothing else.
I try to do a lot of stuff to solve that issue, but hopefully I can reduce my changes to two important points: update angular 12.0.0 to angular 12.0.2 set defaultConfiguration in angular.json to development ( "defaultConfiguration": "development" ) "defaultConfiguration": "production" Build at: 2021-05-29T06:49:51.461Z - Hash: 9d68fbaa715d790c89ed - Time: 29446ms <- change one character in stringBuild at: 2021-05-29T06:50:31.850Z - Hash: cc2399413ce6f0800553 - Time: 32195ms <- change one character in string "defaultConfiguration": "development" Build at: 2021-05-29T06:52:16.258Z - Hash: b9b4991fa89ef1e785fc - Time: 781ms <- change one character in stringBuild at: 2021-05-29T06:52:27.484Z - Hash: 3838e3c45e33228591f9 - Time: 622ms <- change one character in string final angular.json "sourceMap": true is important for me simply call ng serve , no additional parameters needed { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "dotbot": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, "root": "", "sourceRoot": "src", "prefix": "dotbot", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/dotbot", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.json", "inlineStyleLanguage": "scss", "assets": ["src/favicon.ico", "src/assets"], "styles": ["./node_modules/@angular/material/_theming.scss", "src/styles.scss"], "scripts": [] }, "configurations": { "production": { "budgets": [ { "type": "initial", "maximumWarning": "500kb", "maximumError": "1mb" }, { "type": "anyComponentStyle", "maximumWarning": "2kb", "maximumError": "4kb" } ], "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "outputHashing": "all" }, "development": { "buildOptimizer": false, "optimization": { "scripts": false, "styles": false, "fonts": false }, "vendorChunk": true, "extractLicenses": false, "sourceMap": true, "namedChunks": true } }, "defaultConfiguration": "development" }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "dotbot:build" }, "configurations": { "production": { "browserTarget": "dotbot:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "dotbot:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "inlineStyleLanguage": "scss", "assets": ["src/favicon.ico", "src/assets"], "styles": ["./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "src/styles.scss"], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": ["tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json"], "exclude": ["**/node_modules/**"] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "dotbot:serve" }, "configurations": { "production": { "devServerTarget": "dotbot:serve:production" } } } } } }, "defaultProject": "dotbot"}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/67733861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8314501/']}
jdg_74649
stackexchange
llm_judgeable_groundtruth_similarity
26184409
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 creating a simply story, which will occasionally prompt the user to hit ENTER. It works the first time I prompt for it, but then it will immediately execute the other prompts, maybe because the program runs so fast by the time you let the ENTER key up, it already ran the check for the prompts. Any ideas? Code Below. System.out.println("...*You wake up*..."); System.out.println("You are in class... you must have fallen asleep."); System.out.println("But where is everybody?\n"); promptEnterKey(); System.out.println("You look around and see writing on the chalkboard that says CBT 162"); promptEnterKey();//////////////////////////////////////////////////////public void promptEnterKey(){ System.out.println("Press \"ENTER\" to continue..."); try { System.in.read(); } catch (IOException e) { e.printStackTrace(); }} Now provide the response and nothing else.
The reason why System.in.read is not blocking the second time is that when the user presses ENTER the first time, two bytes will be stored corresponding to \r and \n . Instead use a Scanner instance: public void promptEnterKey(){ System.out.println("Press \"ENTER\" to continue..."); Scanner scanner = new Scanner(System.in); scanner.nextLine();}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26184409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3500376/']}
jdg_74650
stackexchange
llm_judgeable_groundtruth_similarity
1183480
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an equation of the form $(a+x)^2 + (b+x)^2 +(c+x)^2 + (d+x)^2-e=0$ where $a$, $b$, $c$, $d$ and $e$ are known. My question is how would I derive $x$. Now provide the response and nothing else.
hint : Use $(a+x)^2 = a^2+2ax+x^2$, and similarly expand the other $3$ squares, then combine like terms and rewrite it in the form $Ax^2+Bx + C = 0$ and use a quadratic formula !
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1183480', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/198225/']}
jdg_74651
stackexchange
llm_judgeable_groundtruth_similarity
36328063
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm developing a Spring Boot application with Spring Data JPA. I'm using a custom JPQL query to group by some field and get the count. Following is my repository method. @Query(value = "select count(v) as cnt, v.answer from Survey v group by v.answer")public List<?> findSurveyCount(); It's working and result is obtained as follows: [ [1, "a1"], [2, "a2"]] I would like to get something like this: [ { "cnt":1, "answer":"a1" }, { "cnt":2, "answer":"a2" }] How can I achieve this? Now provide the response and nothing else.
Solution for JPQL queries This is supported for JPQL queries within the JPA specification . Step 1 : Declare a simple bean class package com.path.to;public class SurveyAnswerStatistics { private String answer; private Long cnt; public SurveyAnswerStatistics(String answer, Long cnt) { this.answer = answer; this.count = cnt; }} Step 2 : Return bean instances from the repository method public interface SurveyRepository extends CrudRepository<Survey, Long> { @Query("SELECT " + " new com.path.to.SurveyAnswerStatistics(v.answer, COUNT(v)) " + "FROM " + " Survey v " + "GROUP BY " + " v.answer") List<SurveyAnswerStatistics> findSurveyCount();} Important notes Make sure to provide the fully-qualified path to the bean class, including the package name. For example, if the bean class is called MyBean and it is in package com.path.to , the fully-qualified path to the bean will be com.path.to.MyBean . Simply providing MyBean will not work (unless the bean class is in the default package). Make sure to call the bean class constructor using the new keyword. SELECT new com.path.to.MyBean(...) will work, whereas SELECT com.path.to.MyBean(...) will not. Make sure to pass attributes in exactly the same order as that expected in the bean constructor. Attempting to pass attributes in a different order will lead to an exception. Make sure the query is a valid JPA query, that is, it is not a native query. @Query("SELECT ...") , or @Query(value = "SELECT ...") , or @Query(value = "SELECT ...", nativeQuery = false) will work, whereas @Query(value = "SELECT ...", nativeQuery = true) will not work. This is because native queries are passed without modifications to the JPA provider, and are executed against the underlying RDBMS as such. Since new and com.path.to.MyBean are not valid SQL keywords, the RDBMS then throws an exception. Solution for native queries As noted above, the new ... syntax is a JPA-supported mechanism and works with all JPA providers. However, if the query itself is not a JPA query, that is, it is a native query, the new ... syntax will not work as the query is passed on directly to the underlying RDBMS, which does not understand the new keyword since it is not part of the SQL standard. In situations like these, bean classes need to be replaced with Spring Data Projection interfaces. Step 1 : Declare a projection interface package com.path.to;public interface SurveyAnswerStatistics { String getAnswer(); int getCnt();} Step 2 : Return projected properties from the query public interface SurveyRepository extends CrudRepository<Survey, Long> { @Query(nativeQuery = true, value = "SELECT " + " v.answer AS answer, COUNT(v) AS cnt " + "FROM " + " Survey v " + "GROUP BY " + " v.answer") List<SurveyAnswerStatistics> findSurveyCount();} Use the SQL AS keyword to map result fields to projection properties for unambiguous mapping.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/36328063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3037257/']}
jdg_74652
stackexchange
llm_judgeable_groundtruth_similarity
571149
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In this question when I solve for time I get $t=-1$ & $t=5$ . What does it actually mean at $t=-1$ ? Now provide the response and nothing else.
This is a great example about limitations of mathematical models applied to physics. For solving the problem, you use the very well know, quadratic equations for the motion of the ball. This means that the resulting motion is a parabola, and then math says that there are 2 different solutions for the problem. Now, after doing the math, you have to put that in context of the physical problem you're trying to solve. These quadratic equations only work when the force (and hence the acceleration) is constant. This constant force is the gravity, so whenever this assumption is not valid, the equations are not valid as well. This implies that your model is valid only in a limited time range: from the moment when the ball stops touching the element responsible for giving the initial velocity (probably a hand throwing it upwards), and to the moment it touches the ground. However, the quadratic equations are valid for any time, this means, they represent an infinite theoretical motionand you have to manually select the range of time where the motion is valid. The usual is to choose $t=0$ as the time when the ball leaves the hand, so the solution $t=-1\,s$ means this solution occurs outside the valid range. I tried to explain this with a cartoon, the red line represents the motion of the ball, the solid part is the range where the assumptions are valid, and the slashed where they are not.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/571149', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/271508/']}
jdg_74653
stackexchange
llm_judgeable_groundtruth_similarity
39990
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: If a star is 13000 light years away, doesn't that mean we are seeing 13000-year-old light? If it does, then does that mean when we discover a planet with dimming star light, we are seeing a planet that is 13000 years old? Are we seeing a 13k-year-old orbit? Now provide the response and nothing else.
In one word, yes. Anything and everything we see, we see the way it was a certain time ago—about 1.3 seconds for the Moon, about 13,000 years for your hypothetical planet. Like @Richyt pointed out, there is no way for information to travel faster than the speed of light. Because any and all celestial objects gravitationally affect any and all others, orbits are not frozen in time and do “evolve.” If this planet is the only “major” thing gravitating around its star, its orbit will change very slowly, but there is still a change, which may or may not be noticeable in 13,000 years, depending on many factors such as the proximity of the planet to its star (the closer it is, the stronger relativistic orbital precession would be—e.g. it is 43″/century for Mercury, 8.6″/century for Venus, and 3.8″/century for the Earth [source for these latter two: https://arxiv.org/pdf/0802.0176.pdf).
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/39990', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/37006/']}
jdg_74654
stackexchange
llm_judgeable_groundtruth_similarity
18128473
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 Git Bash v1.8.1, with a few aliases (for testing): [alias] ekko = !echo $1 && echo $1 ekko2 = !sh -c 'echo $1 && echo $1' But when I run them, I see: > git ekko mastermastermaster master And: > git ekko2 master(blank line) (blank line) My intended behavior is: > git ekko mastermastermaster I'm fairly new to aliases - I'm looking for a way to ensure that my arguments are consumed entirely, and not appended to the end of the alias. Some sleuthing indicates this behavior changed somewhere around Git v1.7.x, and I haven't yet determined exactly how to accomplish this: Git Alias - Multiple Commands and Parameters Now provide the response and nothing else.
Your ekko2 alias is really close... What you really want is this: [alias] ekko2 = !sh -c 'echo $1 && echo $1' - Git aliases that execute shell commands do substitute the $n variables, but they also append any arguments you pass them to the end of the command. So in your first example git ekko master is equivalent to echo master && echo master master , which explains its output. Your second example is closer, but you're passing "master" to the sh command, which is just ignoring the extra argument. By adding - to the end of the alias, you're telling sh that the arguments that follow are intended for the script sh is executing, and not for sh itself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18128473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88111/']}
jdg_74655
stackexchange
llm_judgeable_groundtruth_similarity
472917
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have a requirement for one of my clients that they would like all user passwords stored in the Description field of AD. Now this is all well and good initially because we use a script to roll out new users. However the problem comes because another one of their requirements is to have passwords changed on logon. So in effect, they'd like a user to logon initally, change their password and have that new password automatically saved into an AD attribute. The only thing I can think of at the moment is to do this via a logon script, that shows a password change prompt and does the change and logs it into the attribute of that user account then change the logon script to a correct one for everyday use. Is there any other way of doing this through the built in 'must change password on next logon' setting or am I already looking at the best way of doing this Cheers -Edit- Alright well, I know it's a bad idea. What i'll end up doing is using a password filter as in one of the answers and just save the passwords outside of active directory and just pass the file on to ICT staff manually Now provide the response and nothing else.
While I think your idea is insane there are ways to accomplish this. Active Directory permits you to insert a DLL on Domain Controllers that will capture the password provided by a user. You can do any arbitrary action you like within the filter like storing the password. One example is the Password Filter DLL this DLL captures the password update event and can call eny arbitrary program you like. In the past I had used this to call a python script which would generate an SHA1 password compatible with the Google Apps accounts.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/472917', 'https://serverfault.com', 'https://serverfault.com/users/156345/']}
jdg_74656
stackexchange
llm_judgeable_groundtruth_similarity
19081355
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 some scenario where I should use multiple background color to one div. It's better for me rather than using background images or additional div. But, I can't find easier way to use it by CSS. So, I need help about some scenario. Please, see the image: (1) I want to build "A". for that I wrote: div.A { background: linear-gradient(to right, #9c9e9f, #f6f6f6); } But, after writing that code, it'll like "B". But, I want exactly like "A". So, by css/css3 how can I do it(without adding more divs)? (2) Is it possible to make one portion smaller than other portion? For example, at "C", blue color is smaller(at height) than the other portion. How, can I apply multiple background color to one div with making one portion smaller like "C"(without adding additional divs to "C")? Update:After @Mohammad's answer, I've tried with that way. But, for "C" scenario, I can't decrease the height of blue portion. Can you please, tell me how can I do it? jsfiddle.net/mFjQ6 Now provide the response and nothing else.
The A div can actually be made without :before or :after selector but using linear gradient as your first try. The only difference is that you must specify 4 positions. Dark grey from 0 to 50% and ligth grey from 50% to 100% like this: background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); As you know, B div is made from a linear gradient having 2 positions like this: background: linear-gradient(to right, #9c9e9f 0%,#f6f6f6 100%); For the C div, i use the same kind of gradient as div A ike this: background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); But this time i used the :after selector with a white background like if the second part of your div was smaller. * Please note that I added a better alternative below. Check this jsfiddle or the snippet below for complete cross-browser code. div{ position:relative; width:80%; height:100px; color:red; text-align:center; line-height:100px; margin-bottom:10px;}.a{ background: #9c9e9f; /* Old browsers */ background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(50%,#9c9e9f), color-stop(50%,#f6f6f6), color-stop(100%,#f6f6f6)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* IE10+ */ background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#f6f6f6 50%,#f6f6f6 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6',GradientType=1 ); /* IE6-9 */}.b{ background: #9c9e9f; /* Old browsers */ background: -moz-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(100%,#f6f6f6)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(left, #9c9e9f 0%,#f6f6f6 100%); /* IE10+ */ background: linear-gradient(to right, #9c9e9f 0%,#f6f6f6 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6',GradientType=1 ); /* IE6-9 */}.c{ background: #9c9e9f; /* Old browsers */ background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #33ccff 50%, #33ccff 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, right top, color-stop(0%,#9c9e9f), color-stop(50%,#9c9e9f), color-stop(50%,#33ccff), color-stop(100%,#33ccff)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(left, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* IE10+ */ background: linear-gradient(to right, #9c9e9f 0%,#9c9e9f 50%,#33ccff 50%,#33ccff 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#33ccff',GradientType=1 ); /* IE6-9 */}.c:after{ content:""; position:absolute; right:0; bottom:0; width:50%; height:20%; background-color:white;} <div class="a">A</div><div class="b">B</div><div class="c">C</div> There is also an alternative for the C div without using a white background to hide the a part of the second section.Instead, we make the second part transparent and we use the :after selector to act as a colored background with the desired position and size. See this jsfiddle or the snippet below for this updated solution. div { position: relative; width: 80%; height: 100px; color: red; text-align: center; line-height: 100px; margin-bottom: 10px;}.a { background: #9c9e9f; /* Old browsers */ background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(50%, #9c9e9f), color-stop(50%, #f6f6f6), color-stop(100%, #f6f6f6)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* IE10+ */ background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, #f6f6f6 50%, #f6f6f6 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6', GradientType=1); /* IE6-9 */}.b { background: #9c9e9f; /* Old browsers */ background: -moz-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(100%, #f6f6f6)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(left, #9c9e9f 0%, #f6f6f6 100%); /* IE10+ */ background: linear-gradient(to right, #9c9e9f 0%, #f6f6f6 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#f6f6f6', GradientType=1); /* IE6-9 */}.c { background: #9c9e9f; /* Old browsers */ background: -moz-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, right top, color-stop(0%, #9c9e9f), color-stop(50%, #9c9e9f), color-stop(50%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0))); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(left, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%); /* IE10+ */ background: linear-gradient(to right, #9c9e9f 0%, #9c9e9f 50%, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0) 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#9c9e9f', endColorstr='#ffffff00', GradientType=1); /* IE6-9 */}.c:after { content: ""; position: absolute; right: 0; top: 0; width: 50%; height: 80%; background-color: #33ccff; z-index: -1} <div class="a">A</div><div class="b">B</div><div class="c">C</div>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19081355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1896653/']}
jdg_74657
stackexchange
llm_judgeable_groundtruth_similarity
2910536
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'd like to do a Regex.Split on some separators but I'd like to keep the separators. To give an example of what I'm trying: "abc[s1]def[s2][s3]ghi" --> "abc", "[s1]", "def", "[s2]", "[s3]", "ghi" The regular expression I've come up with is new Regex("\\[|\\]|\\]\\[") . However, this gives me the following: "abc[s1]def[s2][s3]ghi" --> "abc", "s1", "def", "s2", "", "s3", "ghi" The separators have disappeared (which makes sense given my regex). Is there a way to write the regex so that the separators themselves are preserved? Now provide the response and nothing else.
Use zero-length maching lookarounds; you want to split on (?=\[)|(?<=\]) That is, anywhere where we assert a match of a literal [ ahead, or where we assert a match of literal ] behind. As a C# string literal, this is @"(?=\[)|(?<=\])" See also regular-expressions.info/Lookarounds Related questions Java split is eating my characters. -- has many examples Example in Java System.out.println(java.util.Arrays.toString( "abc[s1]def[s2][s3]ghi".split("(?=\\[)|(?<=\\])") )); // prints "[abc, [s1], def, [s2], [s3], ghi]" System.out.println(java.util.Arrays.toString( "abc;def;ghi;".split("(?<=;)") )); // prints "[abc;, def;, ghi;]" System.out.println(java.util.Arrays.toString( "OhMyGod".split("(?=(?!^)[A-Z])") )); // prints "[Oh, My, God]"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2910536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23562/']}
jdg_74658
stackexchange
llm_judgeable_groundtruth_similarity
54682024
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to read through the names of the Rows and create a new column with just the final element i.e. "C", "c2" Mo2GeC 302.737Mo2PC 300.034Mo2AsC 278.077Sc3AlC2 126.561Sc3GaC2 121.334Sc3InC2 163.455 Now provide the response and nothing else.
1) Ensure your login.component.ts file also injects the service. constructor(public user:LoginService) 2) Ensure that no module or component has a providers array containing your service. If you register the service using the providedIn: 'root' as you have, and don't register the service again in any providers array, then the service should be a singleton and work as you expect. Also, the naming of your getters and setters is incorrect. The getter and setter should have the same name, as they are just another way to define a property: get user():string{ return this.username; } set user(val: string){ this.username = val; } get token():string{ return this.token; } set token(val:string){ this.token=val; } get fullName():string{ return this.fullname; } set fullName(val:string){ this.fullname=val; } You then access those getter/setter properties just like any other declared properties. this.fullName = "Joe Smith"; // to set the value and call the setter console.log(this.fullName); // to reference the value. In your customer component: constructor(public loginService:LoginService) { } loadData() { console.log(this.loginService.user) } NOTE: I renamed your constructor parameter to better identify it. In your login component: constructor(public loginService:LoginService) { } fLogin(user, pass) { this.loginService.user = user; }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54682024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11059563/']}
jdg_74659
stackexchange
llm_judgeable_groundtruth_similarity
62300
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 need to evaluate the security of a cryptographic library. In particular I am targeting a part of the library where I believe the private key is exposed for a limited time in the RAM. Any ideas or pointers on how to go about checking the RAM for this key. I was thinking about dumping memory after some specific user interactions. But how do I start with this, any tools recommended? I am home in the security world, I know about memory layouts, usage, countermeasures against memory attacks etc. Just not in Android. As for starter it is sufficient if the tools/techniques require custom kernel flashing or rooted devices. But in the end it should be applicable in real life situations where the target device is an out-of-the-box OEM device. Now provide the response and nothing else.
I had the same need and after looking around I ended up writing my own program. Usage: memdump <pid>memdump <pid> <ip-address> <port> The former will output the entire process memory to stdout, and the latter to the TCP port of your choice (you'll likely use netcat on the other end). #include <stdio.h>#include <stdlib.h>#include <limits.h>#include <sys/ptrace.h>#include <sys/socket.h>#include <arpa/inet.h>void dump_memory_region(FILE* pMemFile, unsigned long start_address, long length, int serverSocket){ unsigned long address; int pageLength = 4096; unsigned char page[pageLength]; fseeko(pMemFile, start_address, SEEK_SET); for (address=start_address; address < start_address + length; address += pageLength) { fread(&page, 1, pageLength, pMemFile); if (serverSocket == -1) { // write to stdout fwrite(&page, 1, pageLength, stdout); } else { send(serverSocket, &page, pageLength, 0); } }}int main(int argc, char **argv) { if (argc == 2 || argc == 4) { int pid = atoi(argv[1]); long ptraceResult = ptrace(PTRACE_ATTACH, pid, NULL, NULL); if (ptraceResult < 0) { printf("Unable to attach to the pid specified\n"); return; } wait(NULL); char mapsFilename[1024]; sprintf(mapsFilename, "/proc/%s/maps", argv[1]); FILE* pMapsFile = fopen(mapsFilename, "r"); char memFilename[1024]; sprintf(memFilename, "/proc/%s/mem", argv[1]); FILE* pMemFile = fopen(memFilename, "r"); int serverSocket = -1; if (argc == 4) { unsigned int port; int count = sscanf(argv[3], "%d", &port); if (count == 0) { printf("Invalid port specified\n"); return; } serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (serverSocket == -1) { printf("Could not create socket\n"); return; } struct sockaddr_in serverSocketAddress; serverSocketAddress.sin_addr.s_addr = inet_addr(argv[2]); serverSocketAddress.sin_family = AF_INET; serverSocketAddress.sin_port = htons(port); if (connect(serverSocket, (struct sockaddr *) &serverSocketAddress, sizeof(serverSocketAddress)) < 0) { printf("Could not connect to server\n"); return; } } char line[256]; while (fgets(line, 256, pMapsFile) != NULL) { unsigned long start_address; unsigned long end_address; sscanf(line, "%08lx-%08lx\n", &start_address, &end_address); dump_memory_region(pMemFile, start_address, end_address - start_address, serverSocket); } fclose(pMapsFile); fclose(pMemFile); if (serverSocket != -1) { close(serverSocket); } ptrace(PTRACE_CONT, pid, NULL, NULL); ptrace(PTRACE_DETACH, pid, NULL, NULL); } else { printf("%s <pid>\n", argv[0]); printf("%s <pid> <ip-address> <port>\n", argv[0]); exit(0); }} To cross-compile it for Android your Android.mk should look like this: LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE := memdumpLOCAL_SRC_FILES := memdump.cinclude $(BUILD_EXECUTABLE)
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/62300', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/50257/']}
jdg_74660
stackexchange
llm_judgeable_groundtruth_similarity
166724
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: Quick note: this is not a duplicate of CSRF protection with custom headers (and without validating token) despite some overlap. That post discusses how to perform CSRF protection on Rest endpoints without discussing if it is actually necessary. Indeed, many CSRF/Rest questions I've read on this site talk about securing the endpoints via CSRF tokens without actually discussing whether or not it is necessary. Hence this question. Is CSRF Protection necessary for Rest API endpoints? I've seen lots of discussion about securing REST endpoints against CSRF attacks, but having given the topic lots of thought, I'm very certain that CSRF tokens on a REST endpoint grant zero additional protection. As such, enabling CSRF protection on a REST endpoint just introduces some useless code to your application, and I think it should be skipped. I may be missing something though, hence this question. I think it will help to keep in mind why CSRF protection is necessary in the first place, and the attack vectors it protects against: Why CSRF? It really boils down to the browsers ability to automatically present login credentials for any request by sending along cookies. If a session id is stored in a cookie the browser will automatically send it along with all requests that go back to the original website. This means that an attacker doesn't actually have to know authentication details to take an action as the victim user. Rather, the attacker just has to trick the victims browser into making a request, and the credentials to authenticate the request will ride along for free. Enter a REST API Rest API endpoints have a very important difference from other requests: they are specifically stateless, and should never accept/use data from either a cookie or session. As a result, a REST API that sticks to the standard is automatically immune to such an attack. Even if a cookie was sent up by the browser, any credentials associated with the cookie would be completely ignored. Authentication of calls to a REST API are done in a completely different fashion. The most common solution is to have some sort of authentication key (an OAuth Token or the like) which is sent along in the header somewhere or possibly in the request body itself. Since authentication is application-specific, and since the browser itself doesn't know what the authentication token is, there is no way for a browser to automatically provide authentication credentials even if it is somehow tricked into visiting the API endpoint. As a result, a cookie-less REST endpoint is completely immune from CSRF attacks. Or am I missing something? Now provide the response and nothing else.
I wasn't originally aiming for a self-answer, but after more reading I've come up with what I believe to be a comprehensive answer that also explains why some might still be interested in CSRF protection on REST endpoints. No cookies = No CSRF It really is that simple. Browsers send cookies along with all requests. CSRF attacks depend upon this behavior. If you do not use cookies, and don't rely on cookies for authentication, then there is absolutely no room for CSRF attacks, and no reason to put in CSRF protection. If you have cookies, especially if you use them for authentication, then you need CSRF protection. If all you want to know is "Do I need CSRF protection for my API endpoint?" you can stop right here and leave with your answer. Otherwise, the devil is in the details. h/t to paj28: While cookies are the primary attack vector for CSRF attacks, you are also vulnerable if you use HTTP/Basic authentication. More generally, if the browser is able automatically pass along login credentials for your app, then CSRF matters. In my experience cookies are the most common technology being exploited to make CSRF happen, but there are some other authentication methods that are used which can result in the same vulnerability. REST = Stateless If you ask someone "what is REST" you will get variety of answers that discuss a variety of different properties. You can see as much because someone asked that question on stack overflow: https://stackoverflow.com/questions/671118/what-exactly-is-restful-programming One property of REST that I have always relied upon is that it is stateless. The application itself has state of course. If you can't store data in a database somewhere, your application is going to be pretty limited. In this case though, stateless has a very specific and important meaning: REST applications don't track state for the client-side application. If you are using sessions, then you are (almost certainly) keeping track of client-side state, and you are not a REST-full application. So an application that uses sessions (especially for logins) that are tracked via cookies is not a REST-full application (IMO), and is certainly vulnerable to CSRF attacks, even if it otherwise looks like a REST application. I think it is worth a quick note that one reason that client-side statelessness is important for REST applications is that the ability of intermediaries to cache responses is also a desirable part of the REST paradigm. As long as the application is tracking client-side state, caching is not possible. Rest ≠ Cookieless For these reasons, I initially assumed that a fully-compliant REST application would never need sessions, never need cookies, and therefore never need CSRF security. However, there is at least one use-case that may prefer cookies anyway: persistent logins. Consider a typical client-side (in this case browser, not mobile) web application. You get started by logging in, which uses a REST API to validate user credentials and in return is given a token to authorize future requests. For single page applications, you can just keep that token in memory, but doing so will effectively log the user out if they close the page. As a result, it would be good to persist the state somewhere that can last longer than a single browser session. Local storage is an option, but is also vulnerable to XSS attacks: a successful XSS attack can result in the attacker grabbing your login tokens and sending them off to the attacker to be used at their discretion. For this reason, I have seen some suggest using cookies to store login tokens. With a cookie you can set the http-only flag, which prevents the application from reading the cookie after it is set. As a result, in the event of an XSS attack, the attacker can still make calls on your behalf, but they can't walk away with the authorization token all together. This use of cookies doesn't directly violate the statelessness requirement of REST because the server still isn't tracking client-side state. It is just looking for authentication credentials in a cookie, rather than the header. I mention this because it is potentially a legitimate reason to use cookies with a REST API, although it is obviously up to a given application to balance the various security and usability concerns. I would personally try to avoid using cookies with REST APIs, but there may very well be reasons to use them anyway. Either way, the overall answer is simple: if you are using cookies (or other authentication methods that the browser can do automatically) then you need CSRF protection. If you aren't using cookies then you don't.
{}
{'log_upvote_score': 9, 'links': ['https://security.stackexchange.com/questions/166724', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/149676/']}
jdg_74661
stackexchange
llm_judgeable_groundtruth_similarity
9963015
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 like to have a query like this: select data from table where (x > 1 and x < 100) or (x > 250 and x < 300) In ORMlite, that's possible using this code: final QueryBuilder<Data,Integer> qb = queryBuilder();final Where<Data, Integer> w = qb.where();w.or( w.gt("x", 1).and().lt("x", 100), w.gt("x", 250).and().lt("x", 300)) While thats great if one knows the conditions beforehand & at the time of coding, I need the conditions to be dynamically added. Basically that method public com.j256.ormlite.stmt.Where<T,ID> or(com.j256.ormlite.stmt.Where<T,ID> left, com.j256.ormlite.stmt.Where<T,ID> right, com.j256.ormlite.stmt.Where<T,ID>... others) is not enough.It needs another or method that supports a ArrayList of Where conditions. Thanks for any suggestions. Now provide the response and nothing else.
While thats great if one knows the conditions beforehand & at the time of coding, I need the conditions to be dynamically added. In ORMLite Where.or(Where<T, ID> left, Where<T, ID> right, Where<T, ID>... others) is a bit of a syntax hack. When you call: w.or( w.gt("x", 1).and().lt("x", 100), w.gt("x", 250).and().lt("x", 300)); What the or() method gets is: w.or(w, w); You really could rewrite it as: w.gt("x", 1).and().lt("x", 100);w.gt("x", 250).and().lt("x", 300);w.or(w, w); The or method there is only using the arguments to count how many clauses it needs to pop off of the stack. When you call gt and lt and others, it pushes items on a clause stack. The and() method pulls 1 item off the stack and then takes another item in the future. We do these syntax hacks because we want to support linear, chained, and argument based queries: w.gt("x", 1);w.and();w.lt("x", 100); versus: w.gt("x", 1).and().lt("x", 100); versus: w.and(w.gt("x", 1), w.lt("x", 100)); But this means that you have the power to simplify your code immensely by using the Where.or(int many) method. So in the or example above can also be: w.gt("x", 1).and().lt("x", 100);w.gt("x", 250).and().lt("x", 300);// create an OR statement from the last 2 clauses on the stackw.or(2); So you don't need the conditions list at all. All you need is a counter. So you could do something like: int clauseC = 0;for (int i : values) { if (i == 1) { w.le(C_PREIS, 1000); clauseC++; } else if (i == 2) { w.gt(C_PREIS, 1000).and().le(C_PREIS, 2500); clauseC++; } else if (i == 3) { w.gt(C_PREIS, 2500).and().le(C_PREIS, 5000); clauseC++; } else if (i == 4) { w.gt(C_PREIS, 5000).and().le(C_PREIS, 10000); clauseC++; } else if (i == 5) { w.gt(C_PREIS, 10000); clauseC++; }}// create one big OR(...) statement with all of the clauses pushed aboveif (clauseC > 1) { w.or(clauseC);} If i can only be 1 to 5 then you can just use values.size() and skip the clauseC . Notice that if we are only adding one clause then we can skip the OR method call entirely. Oh, and the following statement will not work: target.or().raw(first.getStatement()); because target and first are the same object. first.getStatement() dumps the entire SQL WHERE clause which I don't think is what you want.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9963015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375209/']}
jdg_74662
stackexchange
llm_judgeable_groundtruth_similarity
4637821
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 code in Android such that my app can analyze an incoming SMS and perhaps block it or do something(maybe move to a different SMS folder) BEFORE the SMS actually raises a notification telling the user of a new SMS? I would target Android 2.1 and above. I would want to analyse incoming SMS for user specified spam words, and if found would want to delete/mark as read/move the message to a different folder. Now provide the response and nothing else.
I use this code, as a BroadcastReceiver: public void onReceive(Context context, Intent intent) { //this stops notifications to others this.abortBroadcast(); //---get the SMS message passed in--- Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (bundle != null) { //---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i=0; i<msgs.length; i++){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str += "SMS from " + msgs[i].getOriginatingAddress(); from = msgs[i].getOriginatingAddress(); str += " :"; str += msgs[i].getMessageBody().toString(); msg = msgs[i].getMessageBody().toString(); str += "\n"; } if(checksomething){ //make your actions //and no alert notification and sms not in inbox } else{ //continue the normal process of sms and will get alert and reaches inbox this.clearAbortBroadcast(); } } remember to add it in manifest and add a higgest priority (100) for broadcast or sms will go first to inbox and get the alert notification. <receiver android:name=".SmsReceiver"> <intent-filter android:priority="100"> <action android:name="android.provider.Telephony.SMS_RECEIVED"></action> </intent-filter> </receiver> Hope it helps you.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4637821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/341791/']}
jdg_74663
stackexchange
llm_judgeable_groundtruth_similarity
8740322
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 to use <ref bean="service" /> and when to use <ref local="service" /> in Spring? Now provide the response and nothing else.
Specifying the target bean by using the bean attribute of the ref tag is the most general form, and will allow creating a reference to any bean in the same BeanFactory/ApplicationContext (whether or not in the same XML file), or parent BeanFactory/ApplicationContext. The value of the bean attribute may be the same as either the id attribute of the target bean, or one of the values in the name attribute of the target bean. <ref bean="someBean"/> Specifying the target bean by using the local attribute leverages the ability of the XML parser to validate XML id references within the same file. The value of the local attribute must be the same as the id attribute of the target bean. The XML parser will issue an error if no matching element is found in the same file. As such, using the local variant is the best choice (in order to know about errors are early as possible) if the target bean is in the same XML file. <ref local="someBean"/> This is from the Spring source reference here
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8740322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1077644/']}
jdg_74664
stackexchange
llm_judgeable_groundtruth_similarity
4782590
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have some confusion about its meaning or definition. Isn't that some code that produce or calculate new data values? (Says Zelle in his book) Then I wonder if a string data type is an expression. If it is, then what does eval() do when its argument is a string? The book by Zelle says eval(<string>) evaluates string as an expression, what does that exactly mean if string is already an expression? And if string is not an expression, then how come it can occur after print ? Now provide the response and nothing else.
Expressions represent something, like a number, a string, or an instance of a class. Any value is an expression! Anything that does something is a statement. Any assignment to a variable or function call is a statement. Any value contained in that statement in an expression. foo = "hello" is a statement that assigns foo to the value of the expression "hello". Since the code "hello" is a simple expression, meaning it contains no operations, nothing is actually evaluated, so foo is just assigned to "hello ". More complex expressions actually evaluate things, like adding numbers. Using the word expression seems like it is making things more confusing. Expressions are nothing but values, except they can have operations like addition or subtraction. eval evaluates the string as if it were a python expression. Eval does takes an expression as an argument. However, there's nothing special about this since every single value is an expression . Saying "eval takes a value as an argument" is saying exactly the same thing, but it sounds much simpler. :D eval( "2+2" ) passes the string "2+2" to the function. The function evaluates the expression contained in the string, which comes out to 4. The book by Zelle says eval(<string>) evaluates string as an expression, what does that exactly mean if string is already an expression? Any string is an expression since it represents a value. However, what is in the string has absolutely no impact on it being an expression. If its a value, its an expression. When it is "evaluated as an expression by eval", the characters inside the string are executed as if they were a python expression.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4782590', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587547/']}
jdg_74665
stackexchange
llm_judgeable_groundtruth_similarity
37954
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Song of Songs 1:2 Hebrew: יִשָּׁקֵ֙נִי֙ מִנְּשִׁיקֹ֣ות פִּ֔יהוּ כִּֽי־טֹובִ֥ים דֹּדֶ֖יךָ מִיָּֽיִן׃ KJV: Let him kiss me with the kisses of his mouth: for thy love is better than wine. LXX: φιλησάτω με ἀπὸ φιλημάτων στόματος αὐτοῦ, ὅτι ἀγαθοὶ μαστοί σου ὑπὲρ οἶνον Brenton Septuagint Translation: Let him kiss me with the kisses of his mouth: for thy breasts are better than wine. Why might the LXX translators have chosen to render דֹּדֶ֖יךָ as μαστοί σου, when this seems to be an inaccurate translation? I have observed the following interesting points which might be "clues" דֹּדֶ֖יךָ is gramatically plural (which is why Young's Literal Translation says "better are thy loves than wine.") דּוֹד doesn't just mean "love." It can also mean "uncle" or "beloved" . What's interesting is that forms of דּוֹד appear throughout Song of Songs but the LXX doesn't always translate them in the same way. (compare 1:2 with 7:11, for instance) Now provide the response and nothing else.
The consonantal text, דדיך, can be read דַּדַּיִך, from דַּד "nipple" (Ezekiel 23:3,8,21). This was the reading used in translating דדיך as μαστοί σου. The meaning "beloved" is consistently spelled דּוֹד in Song of Songs. The lack of the letter ו in this and all other cases in the book (1:4, 4:10, 7:13) renders all of them ambiguous between "love" and "nipple."
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/37954', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/23036/']}
jdg_74666
stackexchange
llm_judgeable_groundtruth_similarity
187060
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider the tree graph used in part of my solution to this question : Each level $i$ has $i!$ nodes, and the branching ratio is $i+1$ : I kludged together code to generate this graph (with code better left un-reproduced). Is there an elegant method for generating such a tree graph for arbitrary number of levels? A three-dimensional layout might look like this: but I'd prefer a better embedding at the higher- $n$ levels, closer to this: Now provide the response and nothing else.
here is my elegant implementation l[c_]:=TakeList[Range@Sum[k!,{k,c}],Range@c!][[c-1]];T[x_]:=Graph[(F=Flatten)@Table[MapThread[#->#2&,{Sort@F@Table[l@i,i],l[i+1]}],{i,2,x+1}]];T@3 which returns but if your Mathematica version doesn't support TakeList here is another way s[x_] := Sum[k!,{k,x}];z[y_] := Partition[Range[s@y+1,s[y+1]],1+y];v[n_] := Table[{Flatten[z[n-1]][[i]]->z[n][[i,j]]},{i,n!},{j,n+1}];tree[t_] := Graph[Flatten[Array[v@#&,t],3]];tree@3 tree@6
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/187060', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/9735/']}
jdg_74667
stackexchange
llm_judgeable_groundtruth_similarity
1242986
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $M_n(\mathbb{F})$ be the set of all $n\times n$ with entries in $\mathbb{F}$ and let $\exp:M_n(\mathbb{C})\to M_n(\mathbb{C})$ be defined by $$ \exp(A)=\sum_{k=0}^{\infty}\frac{A^k}{k!},$$ for all $A\in M_n(\mathbb{C}).$ I want to prove that $\exp$ is a surjective map from $M_n(\mathbb{C})$ to $GL(n,\mathbb{C})=\left\{A\in M_n(\mathbb{C})\,\middle| \det(A)\neq0\right\}$, how do I go about that? I mean saying that $\exp:M_n(\mathbb{R})\to GL(n,\mathbb{R})$ is an analogous to saying $\exp:\mathbb{R}\to \mathbb{R}_{>0}$ and this is also pretty intuitive, since, in analogy with the case of numbers, $A^0=I\;\forall A$, so$\exp(0)=I+0+\frac{0^2}{2!}+\dots=I$, so even for $A=0$ we get $\det\left(\exp(A)\right)\neq0$ and so because of the first term we can never get a zero determinant. But I have no idea how to prove the subjectiveness. Thanks in advance. Now provide the response and nothing else.
First, this result is false if $\Bbb C$ is replaced by $\Bbb R$ (even after making reasonable additional hypotheses to avoid the most obvious counterexamples) as Travis remarks, so one should use something specific for the complex numbers. Given a linear operator $\phi$ that we wish to realise as in the image of $\exp$ , one may decompose the vector space as direct sum of its generalised eigenspaces $E_\lambda$ , and since $\phi$ is assumed invertible, one always has $\lambda\neq0$ . If the restriction of $~\phi$ to each $~E_\lambda$ lies in the image of $\exp$ applied to the space of linear operators of $~E_\lambda$ , then one can combine a choice of pre-images of $\phi|_{E_\lambda}$ to obtain a a pre-image of $~\phi$ . In other words it suffices to consider the case where there is just one generalised eigenspace: so $\def\id{\mathrm{id}}\phi-\lambda\id$ is nilpotent for some $\lambda\neq0$ . Since $\exp(A+B)=\exp(A)\exp(B)$ for commuting $A,B$ , and multiples of $\id$ commute with anything, one may factor $\phi=\lambda\id\circ (\id-N)$ where $N=\lambda^{-1}(\lambda\id-\phi)$ is nilpotent, which reduces us to the cases of a nonzero scalar operator $\lambda\id$ on one hand, and of that of a unipotent operator $\id-N$ on the other. For the former case it suffices to choose a logarithm of the complex number $~\lambda$ . For the latter case one has an algebraic formula for the logarithm: $$ \log(\id-N)=-\sum_{k=1}^{n-1}\frac{N^k}k \qquad\text{when $N^n=0$;}$$ this completes the proof.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1242986', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74861/']}
jdg_74668
stackexchange
llm_judgeable_groundtruth_similarity
18246547
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can I get the name of the time zone of the client by using jQuery? Example: Pacific S.A. Standard Time, Greenwich Standard Time, like this: https://en.wikipedia.org/wiki/List_of_time_zones_by_country Timezonelist Now provide the response and nothing else.
Can I get the name of the time zone of the client by using jQuery? No. jQuery has only one date/time function, which is $.now() . If you meant JavaScript , the answer is still no . You can only obtain a time zone offset from date.getTimezoneOffset() . You can't get a time zone - at least not in all browsers. Refer to the timezone tag wiki 's section titled: "Time Zone != Offset" You can guess at the time zone, by using the jsTimeZoneDetect library, but it is just a guess. It may or may not be accurate. You can also now use moment.js with the moment-timezone add on. It now supports time zone guessing with moment.tz.guess() . If you can guarantee your users are running in an environment that fully supports the ECMAScript Internationalization API , you can get the user's time zone like this: Intl.DateTimeFormat().resolvedOptions().timeZone You can review the compatibility table , under DateTimeFormat - resolvedOptions().timezone defaults to the host environment to determine which environments this will work in. Honestly, the best thing to do is to just give your user a screen somewhere that they can select their timezone. You might use a drop-down list, or you might use a map-based timezone picker - like this one . You can use jsTimeZoneDetect as a default value, but your user should be able to change it. Also, all of these are going to give you an IANA time zone identifier, such as America/Los_Angeles . But the examples you gave appear to be Windows time zone ids (for use with TimeZoneInfo in .net). You should read the timezone tag wiki , and then also this question: How to translate between Windows and IANA time zones?
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18246547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1112798/']}
jdg_74669
stackexchange
llm_judgeable_groundtruth_similarity
553515
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 option "RETURNS NULL ON NULL INPUT" for a scalar UDF (see CREATE FUNCTION ) stops the function body executing if the parameter is null and simply returns NULL. That is, it short circuits. Does anyone know how it handles multiple parameters? It would be useful to short circuit a function call with multiple parameters, say if the first one is NULL at least. When I have time, I'll use profiler to try and trace the udf calls.I've searched but can't find anything.. more likely I may not have used the correct search terms. In the meantime, does anyone have any ideas or experience? Answers from the other RDBMS worlds are welcome too.. this is an ANSI setting and I saw results for DB2 and MySQL in my searches Edit, based on comment: For non-CLR functions only CheersS Edit:I don't need to run profiler. Doh!This demonstrates the behaviour: CREATE FUNCTION dbo.ufnTest ( @dummy tinyint)RETURNS tinyintWITH RETURNS NULL ON NULL INPUTASBEGIN RETURN 1ENDGOSELECT dbo.ufnTest(0), dbo.ufnTest(NULL)GOALTER FUNCTION dbo.ufnTest ( @dummy tinyint)RETURNS tinyint--WITH RETURNS NULL ON NULL INPUTASBEGIN RETURN 1ENDGOSELECT dbo.ufnTest(0), dbo.ufnTest(NULL)GOALTER FUNCTION dbo.ufnTest ( @dummy tinyint, @dummy2 tinyint)RETURNS tinyintWITH RETURNS NULL ON NULL INPUTASBEGIN RETURN 1ENDGOSELECT dbo.ufnTest(0, 2), dbo.ufnTest(NULL, 2), dbo.ufnTest(0, NULL)GOALTER FUNCTION dbo.ufnTest ( @dummy tinyint, @dummy2 tinyint)RETURNS tinyint--WITH RETURNS NULL ON NULL INPUTASBEGIN RETURN 1ENDGOSELECT dbo.ufnTest(0, 2), dbo.ufnTest(NULL, 2), dbo.ufnTest(0, NULL)GO Now provide the response and nothing else.
Yes , a function that specifies RETURNS NULL ON NULL INPUT will short-circuit if any of its parameters are NULL . The documentation does suggest this, although it's unclear and appears to be referring only to CLR functions. (I think this is Microsoft's attempt to clarify that the NULL behaviour specified in CREATE FUNCTION will override the OnNullCall attribute on the CLR method.) I've tested this with non-CLR functions in both SQL2005 and SQL2008 and it short-circuits exactly as expected.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/553515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/27535/']}
jdg_74670
stackexchange
llm_judgeable_groundtruth_similarity
13350676
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was getting an error io.MalformedByteSequenceException: Invalid byte 2 of 2-byte UTF-8 sequence The solution is to read and write file in UTF-8. My code is: InputStream input = null;OutputStream output = null;OutputStreamWriter bufferedWriter = new OutputStreamWriter( output, "UTF8");input = new URL(url).openStream();output = new FileOutputStream("DirectionResponse.xml");byte[] buffer = new byte[1024];for (int length = 0; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length);}BufferedReader br = new BufferedReader(new FileReader("DirectionResponse.xml" ));FileWriter fstream = new FileWriter("ppre_DirectionResponse.xml");BufferedWriter out = new BufferedWriter(fstream); I'm reading a url and writing it to a file DirectionResponse.xml . Then reading DirectionResponse.xml and writing the same as *ppre_DirecionResponse.xml* for processing. How do I change this so that reading and writing is done in UTF-8? Now provide the response and nothing else.
First, you need to call output.close() (or at least call output.flush() ) before you reopen the file for input. That's probably the main cause of your problems. Then, you shouldn't use FileReader or FileWriter for this because it always uses the platform-default encoding (which is often not UTF-8). From the docs for FileReader : The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. You have the same problem when using a FileWriter . Replace this: BufferedReader br = new BufferedReader(new FileReader("DirectionResponse.xml" )); with something like this: BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream("DirectionResponse.xml"), "UTF-8")); and similarly for fstream .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13350676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/905911/']}
jdg_74671
stackexchange
llm_judgeable_groundtruth_similarity
380088
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: We say a set $A\subseteq\mathbb{Z}$ is arithmetical if there are integers $a>0,b\geq 0$ such that $A=\{ax+b:x\in\mathbb{Z}\}$ . Is there $S\subseteq\mathbb{Z}$ such that $$S\cap A\neq\varnothing \neq (\mathbb{Z}\setminus S)\cap A$$ for every arithmetical set $A\subseteq\mathbb{Z}$ ? Now provide the response and nothing else.
Yes. Enumerate all arithmetic sets $A_1, A_2, \ldots$ . Choose $n_k\in A_k$ with $|n_k|>2^k$ . The set $\{n_1, n_2, \ldots\}$ intersects any arithmetic set by construction, but it has zero density, thus does not contain a whole arithmetic set. Actually you may construct such $S$ for each infinite sequence $A_1, A_2, \ldots$ of infinite sets: on $k$ -th step choose $n_k\in A_k\cap S$ and $m_k\in A_k\setminus S$ so that $n_1, m_1, n_2, m_2, \ldots$ remain distinct.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/380088', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8628/']}
jdg_74672
stackexchange
llm_judgeable_groundtruth_similarity
8858404
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: UIView provides for the "aspect fit" content mode. However, I've subclasses UIView and would like to draw a UIImage using drawInRect with an aspect fit. Is there any way for me to access that functionality without using a UIImageView? Now provide the response and nothing else.
The math for that is a little bit hairy, but fortunately, here's a solution I prepared earlier: - (UIImage *)imageScaledToSize:(CGSize)size{ //create drawing context UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f); //draw [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)]; //capture resultant image UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image;}- (UIImage *)imageScaledToFitSize:(CGSize)size{ //calculate rect CGFloat aspect = self.size.width / self.size.height; if (size.width / aspect <= size.height) { return [self imageScaledToSize:CGSizeMake(size.width, size.width / aspect)]; } else { return [self imageScaledToSize:CGSizeMake(size.height * aspect, size.height)]; }} The first function is equivalent to "scale to fill", the second (which calls the first) is equivalent to "aspect fit". These methods were written as a category on UIImage so to use them from within another class you'll need to tweak them by passing the image in as a second parameter (or just make a category on UIImage like I did).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8858404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1002430/']}
jdg_74673
stackexchange
llm_judgeable_groundtruth_similarity
9240192
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 tried the below query: select empno from ( select empno from emp order by sal desc )where rownum = 2 This is not returning any records. When I tried this query select rownum,empno from ( select empno from emp order by sal desc) It gives me this output: ROWNUM EMPNO 1 7802 2 7809 3 7813 4 7823 Can anyone tell me what's the problem with my first query? Why is it not returning any records when I add the ROWNUM filter? Now provide the response and nothing else.
To explain this behaviour, we need to understand how Oracle processes ROWNUM. When assigning ROWNUM to a row, Oracle starts at 1 and only increments the value when a row is selected; that is, when all conditions in the WHERE clause are met. Since our condition requires that ROWNUM is greater than 2, no rows are selected and ROWNUM is never incremented beyond 1. The bottom line is that conditions such as the following will work as expected. .. WHERE rownum = 1; .. WHERE rownum <= 10; While queries with these conditions will always return zero rows. .. WHERE rownum = 2; .. WHERE rownum > 10; Quoted from Understanding Oracle rownum You should modify you query in this way in order to work: select empnofrom ( select empno, rownum as rn from ( select empno from emp order by sal desc ) )where rn=2; EDIT : I've corrected the query to get the rownum after the order by sal desc
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9240192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1138658/']}
jdg_74674
stackexchange
llm_judgeable_groundtruth_similarity
60540985
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: State does get set on the scroll, but logged from the eventlistener, it seems to be stuck at the initial value. I guess it's something to do with scrolling being set when the side effect's defined, but how could I trigger a state change from a scroll otherwise? Same goes for any window event I presume. Here's a codesandbox example: https://codesandbox.io/s/react-test-zft3e const [scrolling, setScrolling] = useState(false); useEffect(() => { window.addEventListener("scroll", () => { console.log(scrolling); if (scrolling === false) setScrolling(true); }); }, []); return ( <> scrolling: {scrolling} </> ); Now provide the response and nothing else.
So your anonymous function is locked on initial value of scrolling . It's how closures works in JS and you better find out some pretty article on that, it may be tricky some time and hooks heavily rely on closures. So far there are 3 different solutions here: 1. Recreate and re-register handler on each change useEffect(() => { const scrollHandler = () => { if (scrolling === false) setScrolling(true); }; window.addEventListener("scroll", scrollHandler); return () => window.removeEventListener("scroll", scrollHandler); }, [scrolling]); while following this path ensure your are returning cleanup function from useEffect . It's good default approach but for scrolling it may affect performance because scroll event triggers too often. 2. Access data by reference const scrolling = useRef(false); useEffect(() => { const handler = () => { if (scrolling.current === false) scrolling.current = true; }; window.addEventListener("scroll", handler); return () => window.removeEventListener("scroll", handler); }, []); return ( <> scrolling: {scrolling} </> ); downside: changing ref does not trigger re-render. So you need to have some other variable to change it triggering re-render. 3. Use functional version of setter to access most recent value (I see it as preferred way here): useEffect(() => { const scrollHandler = () => { setScrolling((currentScrolling) => { if (!currentScrolling) return true; return false; }); }; window.addEventListener("scroll", scrollHandler); return () => window.removeEventListener("scroll", scrollHandler);}, []); Note Btw even for one-time use effect you better return cleanup function anyway . PS Also by now you don't set scrolling to false , so you could just get rid of condition if(scrolling === false) , but sure in real world scenario you may also run into something alike.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60540985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13010984/']}
jdg_74675
stackexchange
llm_judgeable_groundtruth_similarity
1204817
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 image path string stored in a database It goes like: img/uploads/imagename.jpg I have a controller: $this->image = new Image($wines->image)//this is assuming that I have a wines table with the image property$this->image->resize(60, 250, Image::AUTO)echo $this->image->render();//the problem is nothing is rendered//Is there a better way of doing this? the image path that I am passing at the Image object //instantiation is the result of a query Now provide the response and nothing else.
The quick answer: switch off AutoSize . The big problem here is that the label will not change its height automatically (only width). To get this right you will need to subclass the label and include vertical resize logic. Basically what you need to do in OnPaint is: Measure the height of the text (Graphics.MeasureString). If the label height is not equal to the height of the text set the height and return. Draw the text. You will also need to set the ResizeRedraw style flag in the constructor.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1204817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_74676
stackexchange
llm_judgeable_groundtruth_similarity
24365548
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 started programming in Scala, coming from Python and Java I was wondering what the correct way or the accepted way is when defining objects/classes in Scala. Scala supports, just like python, to add several class or object definitions in a single file. So purely from an accepted structure perspective, does every object need to be defined in its own file or are you allowed to choose this yourself? Now provide the response and nothing else.
There is a chapter in the official Scala Style Guide on this. It's pretty clear in itself, but I'll just leave some quotes here. The core idea is: As a rule, files should contain a single logical compilation unit. By “logical” I mean a class, trait or object. There is, of course, an exception for companion objects: One exception to this guideline is for classes or traits which have companion objects. Companion objects should be grouped with their corresponding class or trait in the same file. There is also the fact that sealed only works within the same file. Despite what was said above, there are some important situations which warrant the inclusion of multiple compilation units within a single file. One common example is that of a sealed trait and several sub-classes. Because of the nature of sealed superclasses (and traits), all subtypes must be included in the same file. Most of the time, case classes are just simple data containers and can be grouped together. Another case is when multiple classes logically form a single, cohesive group, sharing concepts to the point where maintenance is greatly served by containing them within a single file. Finally, there is a naming convention for exempted multi-unit Scala files: All multi-unit files should be given camelCase names with a lower-case first letter. So: put your Scala classes and objects in separate files, unless they fall into one of the three mentioned exceptions.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24365548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/656754/']}
jdg_74677
stackexchange
llm_judgeable_groundtruth_similarity
31656645
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, in my script, shell a function that prints a message on the console. It can be called from any other function. function print_message{ echo "message content"} The problem is, in shell, functions like echo or printf that usually print data on standard output redirect their messages to the calling function instead as a return value. return_value=$(print_message) # this line print nothing.echo $return_value # This line print the message. I don't want to have to do it. I would like to avoid this behavior and print it directly on standard - or error - output. Is there a way to do it? Or am I just wrong to want to use functions in shell, and should I use instead a huge script to handle any comportment? Now provide the response and nothing else.
The $(...) calling syntax captures standard output. That is its job. That's what it does. If you want static messages that don't get caught by that then you can use standard error (though don't do this for things that aren't error message or debugging messages, etc. please). You can't have a function which outputs to standard output but that doesn't get caught by the $(...) context it is running in because there's only one standard output stream. The best you could do for that would be to detect when you have a controlling terminal/etc. and write directly to that instead (but I'd advise not doing that most of the time either). To redirect to standard error for the function entirely you can do either of these. print_message() { echo "message content" >&2} or print_message() { echo "message content"} >&2 The difference is immaterial when there is only one line of output but if there are multiple lines of output then the latter is likely to be slightly more optimized (especially when the output stream happens to be a file). Also avoid the function keyword as it isn't POSIX/spec and isn't as broadly portable.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31656645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4745527/']}
jdg_74678
stackexchange
llm_judgeable_groundtruth_similarity
936220
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Occasionally when stopping a systemd service with systemctl stop test-server it will fail mentioning that the job was canceled: Unable to stop service test-server: Job for test-server.service canceled. What could cause stopping of the service to be canceled? Note: The stop is actually initiated from an Ansible playbook, but can't see how that would be related. Now provide the response and nothing else.
Every unit in systemd has a job slot internally, and there can be only one job installed for the unit at a time. Jobs encapsulate state change requests for units in general, but their effects vary according to the unit type. In services, they may initiate a state change request, but the action may run even when you cancel the installed job (or cancel and replace with another job type, which will keep the other one in the waiting state until that operation completes, since the unit_start/stop functions internally can also decide when a certain job is runnable). As an illustration, if you have a stop action that takes a long time, then calling start while the stop job is running will with the default job mode (replace) cancel the installed/running stop job, and install a start job in the unit's job slot. Since unit_stop has previously initiated a transition to deactivating (and whatever maps to the service's internal sub state - stop, stop-sigterm, stop-sigkill, stop-final, stop-final-sigterm, stop-final-sigkill), unit_start will now return -EAGAIN, which causes systemd to put the start job in JOB_WAITING state, and on the next state change it will be added to run queue, checked if runnable again, and depending on the result, be run or put in waiting again (from unit_notify). Everytime a job is run it is deleted from the run queue. This is basically why systemctl start will just be waiting all that time (if you don't use --no-block). This was an overview on some moving parts here. There are three things to keep in mind about jobs: They have a type (start, stop, restart, reload, etc), a result (timeout, done, canceled, dependency, skipped, etc) and a mode (replace, isolate, flush, etc). Modes apply to an entire transaction (the requested job and its requirement and propagatively dependent jobs applied together in a consistent manner), there is documentation on what each of them do. In your specific case, it appears that when you do a systemctl stop, another job comes in and replaces your stop job, and the systemctl client disconnects as the job it enqueued was canceled. This could be due to some dependency, or something else (like ExecStop= ends up calling systemctl start unit (which only works the first time) or something similar, or a unit that Wants/Requires/BindsTo the same unit starting up triggering a start job that replaces the stop job you triggered, etc). It could be a service that is socket activated, and due to a busy connection, is retriggered, enqueuing a start job due to the Triggers= dependency in the socket unit, cancelling your stop job. It could also be a timer or something else: in short, the stop job is being replaced due to some other job coming in and replacing it. Ofcourse, as you note, this is all prone to races, it may or may not happen, so it happens occasionally in your case. It would be a good idea to review your setup to avoid these issues.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/936220', 'https://serverfault.com', 'https://serverfault.com/users/37524/']}
jdg_74679
stackexchange
llm_judgeable_groundtruth_similarity
2341397
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 do know how to find domain for most of the functions I find but this one's a bit off. A step-by-step response would be appreciated.$$f(x)=\log_2(\log_3(\log_2(\log_3(\log_2x))))$$Thanks in advance! Now provide the response and nothing else.
Using the fact $\log_bx>a\iff x>b^a$ (when $b>1$) we can reason as follows: $$\begin{array}{ll} & \log_2\log_3\log_2\log_3\log_2 x \quad \textrm{exists} \\ \iff & \phantom{\log_2}\log_3\log_2\log_3\log_2x>0 \\ \iff & \phantom{\log_2\log_3}\log_2\log_3\log_2x>3^0=1 \\ \iff & \phantom{\log_2\log_3\log_2}\log_3\log_2 x>2^1=2 \\ \iff & \phantom{\log_2\log_3\log_2\log_3}\log_2 x>3^2=9 \\ \iff & \phantom{\log_2\log_3\log_2\log_3\log_2}x>2^9=512. \end{array} $$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2341397', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/456059/']}
jdg_74680
stackexchange
llm_judgeable_groundtruth_similarity
4349
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'm sure many of you have probably seen (online or in-person) the DEFCON 18 presentation, demonstrating what can happen if you steal a hacker's computer. For those who haven't, the link is below. It's quite an entertaining presentation. (Warning: Video may be NSFW/NSFLE due to offensive language and some censored, full nudity.) http://www.youtube.com/watch?v=U4oB28ksiIo The video demonstrates how, after having his desktop computer stolen, one hacker used a combination of DynDNS updates and remote access services to recover the system and some data. However, as the presenter admits himself, this is only possible through leaving open what some may consider major security holes. The hard drive was not encrypted. The thief was able to use the system without authentication & authorization. Remote access services present a larger attack surface. Had the system been secured more thoroughly, his data would have been very well protected. However, he would not have been as likely to recover the hardware. Hardware is something that directly equates to cold, hard cash. Data on the other hand, especially data that has been properly backed up to off-site storage, has less of a direct impact on one's bottom line - particularly for home users. In corporate environments, data theft can be a huge fiasco. However, for average Joe User, the risk can range from mild inconvenience to still-mostly-preventable identity theft, or just a general loss of some privacy. How could one weigh the pros of hardware recovery against the cons of data loss, or vice-versa? Are there particular scenarios where each protection scheme particularly outweighs the other? Can there be a good compromise between the two - a scenario in which all of your data is tightly guarded, but your system is configured to be easily trackable? Now provide the response and nothing else.
Following Neal's suggestion, I am adapting my earlier comment in to an answer... with a bit more detail which is hopefully easier to understand :-) My laptop's hard-drive is fully encrypted so the data on it is safe from thieves and the such. However, I still have Prey (tracker) installed on it with an open access Guest account because I always keep my laptop on standby - this means that if my laptop was to be stolen, it will most definitely be in the standby state, in an unencrypted state(!). This gives me the advantage of tracking it down if the thief was to just power it on and access the guest account. It also gives me the advantage of having the HDD encrypted if the thief was to shut it down or take the battery out. That is my compromise... a compromise which comes with several advantages and disadvantages. Pros: Full volume encryption so all data is protected if laptop is ever powered down Guest (standard, non-admin) account has no access to my user directory or any other for that matter If all goes well, (this is also a negative as I will explain below) the thief will play around on the Guest account long enough for me to get several reports back from the tracker with a location, picture and other potentially useful information Negatives: My compromise pretty much relies on a 'typical', not-so-smart thief (which most of them are thankfully :))... a thief that won't be looking for hacks and other privilege escalation exploits which could potentially leave my files open for access. If laptop is powered down straight away then I have no way of tracking the laptop... however, see point 1 on the positives list :)
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/4349', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/953/']}
jdg_74681
stackexchange
llm_judgeable_groundtruth_similarity
16385507
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to recursively copy over a directory and render all .j2 files in there as templates. For this I am currently using the following lines: - template: > src=/src/conf.d/{{ item }} dest=/dest/conf.d/{{ item|replace('.j2','') }} with_lines: find /src/conf.d/ -type f -printf "%P\n" Now I'm looking for a way to remove unmanaged files from this directory. For example if I remove a file/template from /src/conf.d/ I want Ansible to remove it from /dest/conf.d/ as well. Is there some way to do this? I tried fiddling around with rsync --delete , but there I got a problem with the templates which get their suffix .j2 removed. Now provide the response and nothing else.
I'd do it like this, assuming a variable defined as 'managed_files' up top that is a list. - shell: ls -1 /some/dir register: contents- file: path=/some/dir/{{ item }} state=absent with_items: contents.stdout_lines when: item not in managed_files
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16385507', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1986344/']}
jdg_74682
stackexchange
llm_judgeable_groundtruth_similarity
42126105
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 believe that onAttachedToWindow() is called when the onCreate() 's setContentView(R.layout.myLayout.xml) is called. So can I assume then that in the activity lifecycle that onDetachedFromWindow() is called when the activity is destroyed? My question is how do I tie these two call back hooks to the activities lifecycle? Can I say that onAttachedToWindow() is tied to onCreate() and onDetachedFromWindow() is tied to onDestroy() ? Now provide the response and nothing else.
Technically speaking onAttachedToWindow is called after onResume (and it happens only once perlifecycle). ActivityThread.handleResumeActivity call will add DecorView to the current WindowManger which will in turn call WindowManagerGlobal.addView() which than traverse all the views and call onAttachedToWindow on each view. onDetachedFromWindow is tied with onDestroy
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42126105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/835883/']}
jdg_74683
stackexchange
llm_judgeable_groundtruth_similarity
4362278
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 attached property of type ObservableCollection on a control. If I add or remove items from the collection, the ui does not update. However if I replace the collection within with a new one the ViewModel the ui does update. Can someone give me an example of what I need to do within the Dependency object so that it can handle changes within the collection? Part of the dependency object is listed below: public class RadCalendarBehavior : DependencyObject{private static void OnSpecialDaysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){ var calendar = d as RadCalendar; if (e.NewValue != null) { calendar.DayTemplateSelector = new SpecialDaySelector((ObservableCollection<DateTime>)e.NewValue, GetSpecialDayTemplate(d)); }}public static ObservableCollection<DateTime> GetSpecialDays(DependencyObject obj){ return (ObservableCollection<DateTime>)obj.GetValue(SpecialDaysProperty);}public static void SetSpecialDays(DependencyObject obj, ObservableCollection<DateTime> value){ obj.SetValue(SpecialDaysProperty, value);}public static readonly DependencyProperty SpecialDaysProperty = DependencyProperty.RegisterAttached("SpecialDays", typeof(ObservableCollection<DateTime>), typeof(RadCalendarBehavior), new UIPropertyMetadata(null, OnSpecialDaysChanged));}} I understand that I need to register that the collection has changed, but I am unsure how to do this within the dependency property Now provide the response and nothing else.
A change within the collection won't trigger the OnSpecialDaysChanged callback, because the value of the dependency property hasn't changed. If you need to react to detect changes with the collection, you need to handle the event CollectionChanged event manually: private static void OnSpecialDaysChanged(DependencyObject d, DependencyPropertyChangedEventArgs e){ var calendar = d as RadCalendar; if (e.OldValue != null) { var coll = (INotifyCollectionChanged)e.OldValue; // Unsubscribe from CollectionChanged on the old collection coll.CollectionChanged -= SpecialDays_CollectionChanged; } if (e.NewValue != null) { var coll = (ObservableCollection<DateTime>)e.NewValue; calendar.DayTemplateSelector = new SpecialDaySelector(coll, GetSpecialDayTemplate(d)); // Subscribe to CollectionChanged on the new collection coll.CollectionChanged += SpecialDays_CollectionChanged; }}private static void SpecialDays_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e){ // handle CollectionChanged}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4362278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/335876/']}
jdg_74684
stackexchange
llm_judgeable_groundtruth_similarity
8284943
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does anyone know a (preferably C# .Net) library that would allow me to locate, in voice recordings, those segments in which a specific person is speaking? Now provide the response and nothing else.
It's possible with the toolkit SHoUT: http://shout-toolkit.sourceforge.net/index.html It's written in C++ and tested for Linux, but it should also run under Windows or OSX. The toolkit was a by-product of my PhD research on automatic speech recognition (ASR). Using it for ASR itself is perhaps not that straightforward, but for Speech Activity Detection (SAD) and diarization (finding all speech of one specific person) it is quite easy to use. Here is an example: Create a headerless pcm audio file of 16KHz, 16bits, little-endian, mono. I use ffmpeg to create the raw files: ffmpeg -i [INPUT_FILE] -vn -acodec pcm_s16le -ar 16000 -ac 1 -f s16le [RAW_FILE] Prefix the headerless data with little endian encoded file size (4 bytes). Be sure the file has .raw extension, as shout_cluster detects file type based on extension. Perform speech/non-speech segmentation: ./shout_segment -a [RAW_FILE] -ams [SHOUT_SAD_MODEL] -mo [SAD_OUTPUT] The output file will provide you with segments in which someone is speaking (labeled with "SPEECH". Of course, because it is all done automatically, the system might make mistakes..), in which there is sound that is not speech ("SOUND"), or silence ("SILENCE"). Perform diarization: ./shout_cluster -a [RAW_FILE] -mo [DIARIZATION_OUTPUT] -mi [SAD_OUTPUT] Using the output of the shout_segment, it will try to determine how many speakers were active in the recording, label each speaker ("SPK01", "SPK02", etc) and then find all speech segments of each of the speakers. I hope this will help!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8284943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113824/']}
jdg_74685
stackexchange
llm_judgeable_groundtruth_similarity
5418403
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 developed a web application that works well on chrome and firefox. However when it came to testing time and it doesn't work properly in IE. It just doesn't seem to actually get the request? here's the Javascript code: function createXMLHttpRequest() { var xmlhttp = false; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else if(window.ActiveXObject) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { xmlhttp = false; } } } return xmlhttp;};function checkForData(){ var target = document.getElementById('accordion'); var loading = document.getElementById('controls'); var xhr = createXMLHttpRequest(); loading.innerHTML = '<img src="../images/loading.gif" width=20 height=20 />Querying the Database'; xhr.open('GET','getData.php',true); xhr.send(null); xhr.onload = function(){ loading.innerHTML = '<a href="../classes/php/print.php" />Print Report</a><br/><br/><a href="../index.php" />HomePage</a><br/><a href="../classes/php/actionedClass.php" />Refresh</a><br/><a href="../classes/php/logout.php" />Logout</a><br/>'; target.innerHTML = xhr.responseText;// addPrettyness(); }; xhr.onerror = function (){ target.innerHTML = 'Failed :('; };}function addPrettyness(){ $(function() { var stop = false; $( "#accordion h3" ).click(function( event ) { if ( stop ) { event.stopImmediatePropagation(); event.preventDefault(); stop = false; } }); $( "#accordion" ) .accordion({ collapsible: true, header: "> div > h3"}); });}function checkAgain(){ setInterval('checkForData()',30000); //Every 30 seconds run the check for new data script}function changeAction(action, actionChangeId){ xhr = new XMLHttpRequest(); if(action == 0){ var loading = document.getElementById('controls'); loading.innerHTML = '<img src="../images/loading.gif" width=20 height=20 />Sending to the Database'; xhr.open('GET','../classes/php/actionNo.php?actionChangeId='+actionChangeId,true); xhr.send(); xhr.onload = function(){ checkForData(); }; xhr.onerror = function(){ alert('Failed to change action... Try again please!'); }; }else if(action == 1){ xhr = new XMLHttpRequest(); var loading = document.getElementById('controls'); loading.innerHTML = '<img src="../images/loading.gif" width=20 height=20 />Sending to the Database'; xhr.open('GET','../classes/php/actionYes.php?actionChangeId='+actionChangeId,true); xhr.send(); xhr.onload = function(){ checkForData(); }; xhr.onerror = function(){ alert('Failed to change action... Try again please!'); }; }}function startEngine(){ checkForData(); //checkAgain();}window.onload = startEngine; and the .php file it requests from echos back a string result to the javascript. Now provide the response and nothing else.
As mentioned here , Internet Explorer supports the onload event of the XMLHttpRequest object only since version 9. So, for IE 8 and below, you can do it in the old fashioned way: xhr.onreadystatechange = function(){ //ready? if (xhr.readyState != 4) return false; //get status: var status = xhr.status; //maybe not successful? if (status != 200) { alert("AJAX: server status " + status); return false; } //Got result. All is good. loading.innerHTML = '<a href="../classes/php/print.php" />Print Report</a>' + '<br/><br/><a href="../index.php" />HomePage</a><br/>' + '<a href="../classes/php/actionedClass.php" />Refresh</a><br/>' + '<a href="../classes/php/logout.php" />Logout</a><br/>'; target.innerHTML = xhr.responseText; return true;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5418403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84546/']}
jdg_74686
stackexchange
llm_judgeable_groundtruth_similarity
3647805
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a Django model, I'm trying to list all of its fields. I've seen some examples of doing this using the _meta model attribute, but doesn't the underscore in front of meta indicate that the _meta attribute is a private attribute and shouldn't be accessed directly? ... Because, for example, the layout of _meta could change in the future and not be a stable API? Is _meta an exception to this rule? Is it stable and ready to use or is it considered bad practice to access it? Or is there a function or some other way to introspect the fields of a model without using the _meta attribute? Below is a list of some links showing how to do this using the _meta attribute Any advice is much appreciated. django object get/set field http://www.djangofoo.com/80/get-list-model-fields How to introspect django model fields? Now provide the response and nothing else.
_meta is private, but it's relatively stable. There are efforts to formalise it, document it and remove the underscore, which might happen before 1.3 or 1.4. I imagine effort will be made to ensure things are backwards compatible, because lots of people have been using it anyway. If you're particularly concerned about compatibility, write a function that takes a model and returns the fields. This means if something does change in the future, you only have to change one function. def get_model_fields(model): return model._meta.fields I believe this will return a list of Field objects. To get the value of each field from the instance, use getattr(instance, field.name) . Update: Django contributors are working on an API to replace the _Meta object as part of a Google Summer of Code. See: - https://groups.google.com/forum/#!topic/django-developers/hD4roZq0wyk - https://code.djangoproject.com/wiki/new_meta_api
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3647805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226081/']}
jdg_74687
stackexchange
llm_judgeable_groundtruth_similarity
329895
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: Here is WPF application consisting from 3 UserControl s: UserControl3 is a part of UserControl2 content. I keep MVVM during developing and using Prism . I need to invoke custom class method (which is model in terms of MVVM) in UserControl3 from view-model of UserControl1 . The restriction that service in UserControl3 can't be singleton. I suppose to do it one of the following way: Using event aggregator from Prism. UserControl1 view-model is publisher and UserControl3 model is subscriber. For this I'll need to create unique Id in Window and pass it to UserControl1 and UserControl3 . Creating service instance in Window and pass it to UserControl1 and UserControl3 . Then UserControl1 just invoke method on this instance. Window pass UserControl2 instance to UserControl1 . View-model in UserControl1 will just invoke method of UserControl2 , which will invoke method of UserControl3 and so on. It seems like 2 and 3 approaches violates MVVM. What will you prefer? Now provide the response and nothing else.
I turned the Car into a state machine of sorts using State Pattern . Notice no switch or if-then-else statements are used for state selection. In this cases all states are inner classes but it could be implemented otherwise. Each state contains the valid states it can change to. User is prompted for the next state in case more than one is possible, or simply to confirm in case only one is possible. You can compile it and run it to test it. I used a graphic dialog box because it was easier that way to run it interactively in Eclipse. The UML diagram is taken from here . import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.swing.JOptionPane;public class Car { private State state; public static final int ST_OFF=0; public static final int ST_IDDLE=1; public static final int ST_DRIVE=2; public static final int ST_REVERSE=3; Map<Integer,State> states=new HashMap<Integer,State>(); public Car(){ this.states.put(Car.ST_OFF, new Off()); this.states.put(Car.ST_IDDLE, new Idle()); this.states.put(Car.ST_DRIVE, new Drive()); this.states.put(Car.ST_REVERSE, new Reverse()); this.state=this.states.get(Car.ST_OFF); } private abstract class State{ protected List<Integer> nextStates = new ArrayList<Integer>(); public abstract void handle(); public abstract void change(); protected State promptForState(String prompt){ State s = state; String word = JOptionPane.showInputDialog(prompt); int ch = -1; try { ch = Integer.parseInt(word); }catch (NumberFormatException e) { } if (this.nextStates.contains(ch)){ s=states.get(ch); } else { System.out.println("Invalid option"); } return s; } } private class Off extends State{ public Off(){ super.nextStates.add(Car.ST_IDDLE); } public void handle() { System.out.println("Stopped");} public void change() { state = this.promptForState("Stopped, iddle="+Car.ST_IDDLE+": "); } } private class Idle extends State{ private List<Integer> nextStates = new ArrayList<Integer>(); public Idle(){ super.nextStates.add(Car.ST_DRIVE); super.nextStates.add(Car.ST_REVERSE); super.nextStates.add(Car.ST_OFF); } public void handle() { System.out.println("Idling");} public void change() { state=this.promptForState("Idling, enter 0=off 2=drive 3=reverse: "); } } private class Drive extends State{ private List<Integer> nextStates = new ArrayList<Integer>(); public Drive(){ super.nextStates.add(Car.ST_IDDLE); } public void handle() {System.out.println("Driving");} public void change() { state=this.promptForState("Idling, enter 1=iddle: "); } } private class Reverse extends State{ private List<Integer> nextStates = new ArrayList<Integer>(); public Reverse(){ super.nextStates.add(Car.ST_IDDLE); } public void handle() {System.out.println("Reversing");} public void change() { state = this.promptForState("Reversing, enter 1=iddle: "); } } public void request(){ this.state.handle(); } public void changeState(){ this.state.change(); } public static void main (String args[]){ Car c = new Car(); c.request(); //car is stopped c.changeState(); c.request(); // car is iddling c.changeState(); // prompts for next state c.request(); c.changeState(); c.request(); c.changeState(); c.request(); }}
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/329895', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/230076/']}
jdg_74688
stackexchange
llm_judgeable_groundtruth_similarity
131913
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a follow-up question to this question . Let's say we want to minimize the following function f wrt. x and y . The approach is to minimize first wrt. to y and then wrt. x . If this approach makes sense is not part of the question. f[x_, y_] := (x - 2)^2 + x ( y - 2)^2dx[x_, y_] := Block[{xs}, D[f[xs, y], xs] /. xs -> x]dy[x_, y_] := Block[{ys}, D[f[x, ys], ys] /. ys -> y]fy[x_?NumericQ] := y /. FindRoot[dy[x, y] == 0, {y, 20}]dxnoy[x_] := dx[x, fy[x]] Now using FindRoot on dxnoy yields the correct result: FindRoot[{dxnoy[x] == 0}, {{x, 5}}](* {x -> 2.} *) However, the process seems to be inefficient. Using EvaluationMonitor in FindRoot reveals that the exact same points x are evaluated multiple times: Last[Reap[FindRoot[{dxnoy[x] == 0}, {{x, 5}}, EvaluationMonitor :> Sow[x]]]](* {{5., 5., 5., 2., 2., 2.}} *) Why is that? Or better: How can it be avoided? It seems to me that the performance could be a factor 3 better if it wouldn't evaluate the points x=5 and x=2 three times each. Now provide the response and nothing else.
I speculate that the following is occurring. As I noted in a comment above, the actual values of x returned by EvaluationMonitor are Last[Reap[FindRoot[{dxnoy[x] == 0}, {{x, 5}}, EvaluationMonitor :> Sow[{x}]]]]NumberForm[%, 25](* {{{5.}, {5.}, {5.000000074505806}, {2.}, {2.}, {2.0000000298023224}}} *) To use the "Newton" method, FindRoot must evaluate both the dxnoy[x] and its derivative at each point. Since FindRoot cannot see inside dxnoy[x] , it must evaluate the derivative numerically. This would seem to account for the second evaluation at x == 5. , followed by the evaluation at x == 5.000000074505806. It then does the same at x == 2 . Convergence is rapid, because dxnoy[x] is quadratic. Evaluation of the derivative numerically at x == 2. can be avoided by Last[Reap[FindRoot[{dxnoy[x] == 0}, {{x, 5}}, EvaluationMonitor :> Sow[{x}], Method -> {"Newton", "UpdateJacobian" -> 2}]]]NumberForm[%, 25](* {{{5.}, {5.}, {5.000000074505806}, {2.}}} *) The second evaluation at x == 5. still seems unnecessary.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/131913', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/38410/']}
jdg_74689
stackexchange
llm_judgeable_groundtruth_similarity
21985859
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 use MagicalRecords but by some reason MR_SHORTHAND does not work for me. I have added these lines below to Prefix.pch #define MR_SHORTHAND#import "CoreData+MagicalRecord.h" In case when app calls + createEntity method the app terminates due unrecognized selector. But if I write MR_createEntity everything works fine. Team *team = [Team MR_createEntity]; // This line works but Team *team = [Team createEntity]; // This line does not workwith reason: '+[Team createEntity]: unrecognized selector sent to class 0x74b8c' Now provide the response and nothing else.
I know we haven't announced it publicly prior to this answer, but we've decided to deprecate shorthand support, and remove it in the upcoming MR3 release. Shorthand support is an interesting idea and feature, but it is not something we want to maintain. We would rather focus our efforts on getting the data centric part of MagicalRecord to be as solid and reusable as possible. That said, you're certainly welcome to fix it yourself and submit a patch to the older branch of MagicalRecord. Some things to look at are: Make sure the shorthand selectors are included, and add new ones if they are not present Make sure you've used the MagicalRecord class once prior to this call. All the shorthand support is initialized in the class initializer method. If you're using Cocoapods, you may need to update your pod spec reference to 'MagicalRecord/Shorthand'
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21985859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/587415/']}
jdg_74690
stackexchange
llm_judgeable_groundtruth_similarity
2468090
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 $\emptyset \neq U \subsetneq \mathbb{R}^n$ be an open set and denote by $C_c^\infty (U)$ the space of smooth functions with support contained in $U$. On this we have the following metric $$ d(f,g) = \sum_{k\geq 0} \frac{\Vert f - g \Vert_{C^k(U)}}{1+ \Vert f - g \Vert_{C^k(U)}} $$ where $$ \Vert f \Vert_{C^k(U)} = \sup_{\substack{\alpha\in \mathbb{N}^n: \ \vert \alpha\vert \leq k} \\ \quad x\in U} \vert \partial_x^\alpha f(x) \vert.$$ One can prove that $(C_c^\infty (U),d )$ is not a complete metric space (the support might accumulate at the boundary, preventing the limit to belong to $C_c^\infty (U)$). My question is the following: Does there exist a metric $\tilde{d}$ on $C_c^\infty (U)$ such that $(C_c^\infty (U), \tilde{d})$ is a complete metric space and such that the topology coincides with the one induced by $d$? Now provide the response and nothing else.
No, such a metric doesn't exist. Let $(K_n)_{n\in \mathbb{N}}$ a sequence of compact subsets of $U$ such that $K_n \subset \operatorname{int} K_{n+1}$ for all $n$ and $$U = \bigcup_{n \in \mathbb{N}} K_n.$$ Then $$F_n = \{ f \in C_c^{\infty}(U) : \operatorname{supp} f \subset K_n\}$$ is a proper closed (linear) subspace of $C_c^{\infty}(U)$ for every $n$, hence has empty interior. But $$C_c^{\infty}(U) = \bigcup_{n\in \mathbb{N}} F_n,$$ so this is not a Baire space.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2468090', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/331816/']}
jdg_74691
stackexchange
llm_judgeable_groundtruth_similarity
46202147
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a clean way to create destructurable objects in-line. kotlin.Pair and kotlin.Triple cover a lot of use cases, but sometimes there are more objects that are needed to be passed. One sample use case is RX's zip function, where the results of several I/O calls need to be mapped into another object: Single .zip(repositoryA.loadData(someId), repositoryB.loadData(someId), repositoryC.loadAll(), repositoryD.loadAll()), { objectA, objectB, objectsC, objectsD -> /*some Kotlin magic*/ } ) .map { (objectA, objectB, objectsC, objectsD) -> /*do the mapping*/ } I am trying to figure out what would go in the "some Kotlin magic" part. If there were only 3 repositories, it would be Triple(objectA, objectB, objectsC) Do I need to create a new data class for this, and for any n-tuple case, or is there another way? Now provide the response and nothing else.
Basics Let's see how destructuring works: Kotlin defines a convention for this, i.e. componentX() operator functions are an example of the principle of conventions used in Kotlin in many places. These componentX() functions are used by the compiler for the initialization of variables in destructuring declarations. For example in Pair<A,B> these functions look as follows: operator fun component1(): A = first operator fun component2(): B = second As you can see these are operators , specially handled functions.These componentX() functions can be provided by the developer and will automatically be produced by the compiler for data classes. Pair also is such a data class btw. Answer Thus, just go ahead and use data classes whenever you need more than a Triple . For example, a class MultiComponent defined as this: data class MultiComponent(val x: Int, val y: Int, val z: Int, val a: Int, val b: Int, val c: Int) will be compiled to a class with functions component1() , component2() , ..., component6() and can be used in destructuring declarations: val (q, w, e, r, t, z) = MultiComponent(1, 2, 3, 4, 5, 6)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/46202147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/356629/']}
jdg_74692
stackexchange
llm_judgeable_groundtruth_similarity
1417938
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 AM GM inequality for nonnegative real numbers $a_1,a_2,\ldots,a_n$, How to show that if equality holds then $a_1=a_2=\ldots=a_n,$ using method of induction? Now provide the response and nothing else.
Edit Sorry, I read now that you wanted a proof using induction. The proof below does not. I let it stand, since I think it is a nice proof, and someone might thing it is helpful. For two terms, the statement follows by expanding$$0\leq (a_1-a_2)^2,$$and noting that the inequality is an equality precisely when $a_1=a_2$. Now suppose, to get a contradiction, that not all $a_i$, $1\leq i\leq n$ are equal and that the AM equals the GM, i.e.$$\frac{a_1+a_2+a_3+\cdots+a_n}{n}=(a_1a_2\cdots a_n)^{1/n}.$$ We can without loss of generality assume that $a_1\neq a_2$. Then, if we replace $a_1$ and $a_2$ by their arithmetic mean, $$\tilde{a}_1=\frac{a_1+a_2}{2},\quad \tilde{a}_2=\frac{a_1+a_2}{2},$$we get $n$ numbers $\tilde{a}_1$, $\tilde{a}_2$, $a_3$, $\ldots$, $a_n$, that has the same arithmetic mean as the original one, but what happens with the geometric mean? From the AM-GM inequality with two terms$$\tilde{a}_1\tilde{a}_2=\Bigl(\frac{a_1+a_2}{2}\Bigr)^2 > a_1a_2.$$Note the strict inequality (which is a result of the case of two terms).Hence,$$\frac{\tilde{a}_1+\tilde{a}_2+a_3+\cdots+a_n}{n}=\frac{a_1+a_2+a_3+\cdots+a_n}{n}=(a_1a_2\cdots a_n)^{1/n}<(\tilde{a}_1\tilde{a}_2a_3\cdots a_n)^{1/n}$$contradicting the AM-GM inequality.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1417938', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/266265/']}
jdg_74693
stackexchange
llm_judgeable_groundtruth_similarity
1081413
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Why would these two commands report free space so differently? This started happening last year on several Ubuntu 18.04 VMs from time to time. df reports 100% used while du -smh shows only 2.3G of the 4.0G (total) in use. This is often followed by rsyslog or syslog-ng filling up /var with error messages when the syslog server is down for maintenance. # df -mh /varFilesystem Size Used Avail Use% Mounted on/dev/mapper/new_vg-var 4.0G 3.9G 0 100% /var# du -smh /var2.3G /var# fuser /var Now provide the response and nothing else.
Most common reasons for df to be larger than du: You're not running du on the entire filesystem. You don't have access privileges on all the directories. You did something like du -s /filesystem/* , and you're missing the dotfiles at the top. Rerun as du -sx /filesystem (Rare) You have shadowed some of your filesystem with another mount. By mounting on top, du cannot reach the files to determine the size. Can size them by unmounting the shadowing filesystem or often with a loop mount of the original filesystem. You have files that are still open, but deleted. du cannot access them to read any longer, but they still take space. Try lsof +aL1 /filesystem to find the orphaned files and the process holding them open. When the process closes the file, the space will be released. Most common reason for df to be smaller than du: There's an additional filesystem mounted inside and your du is descending into it and counting that space as well. Rerun as du -sx /filesystem
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/1081413', 'https://serverfault.com', 'https://serverfault.com/users/503708/']}
jdg_74694
stackexchange
llm_judgeable_groundtruth_similarity
140469
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 am sure many of you remember the XKCD Heartbleed Explanation . In the same spirit, I would like to request an explanation for how the latest branded vulnerability, Dirty COW , works. Is it possible to explain it to someone like me, who have no idea how the Linux kernel works or what a "copy-on-write" is? Please note that I am not looking for an explanation of what it does , but of how and why it works. Now provide the response and nothing else.
I'm not a linux kernel expert, but I am familiar with the concepts involved and I read Linus' comment and the diff. I'll give it a go - perhaps people can correct me if I get it wrong and we'll hash things out together. Copy On Write is an internal memory concept where, primarily for performance reasons, operations that make a copy of a section of memory don't actually get their own copy unless and until they make a change to that memory - at which point, you quickly make their copy, make the change to that and hand it back to them. The advantage is that you don't have to do the work of making the copy unless and until they actually change it - faster, less memory usage, better caching. The bug here is in the code that does that copying. It appears that there is a race condition in that copy (or actually in the bookkeeping around that copy). A race condition happens when two different processes or threads are accessing the same resource and step on each other. In this case, what happens is that the memory is flagged to be writeable before it is actually copied - if two threads are working very closely to each other, the second can take advantage of the writeable flag and actually write to the original memory, not the copy. The exploit is that this lets a process elevate itself by getting write access to the kernel's own understanding of it. The kernel knows what user each process is running at - by taking a copy of that memory that kernel is using to store that info using Copy On Write, then using this Dirty COW bug, they can actually write the user info into the kernel's own copy. So they write that the process is being run as root.. and then they can do anything. The demo program uses that to write to a file only writeable by root, but it could have done literally anything. The fix was to separate out a new flag saying they are doing a CopyOnWrite, instead of using the Write flag for both.
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/140469', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/98538/']}
jdg_74695
stackexchange
llm_judgeable_groundtruth_similarity
46122
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: OpenCV 2.4.2 took 6 hours to compile on the Raspberry Pi and I'd love to package everything up as a deb but I have never done that before. How can I package the compiled files so that they download or include the necessary other libraries? Now provide the response and nothing else.
I thought I would add a better answer for anyone else observing this thread. So, if you've already gone through the trouble of building opencv on the device, you've probably followed the instructions here: http://docs.opencv.org/doc/tutorials/introduction/linux_install/linux_install.html In which case, if you don't add the -D args to dynamically override CMake parameters in step two and you instead just run cmake .. inside the build directory (you created), it will generate a CMakeCache.txt file. If you edit the CMakeCache.txt file, you can change: CPACK_BINARY_DEB:BOOL=ON ...in addition to the other specified variables in the above opencv link. Instead of running make or make install ... just run make package and the magic happens. Warning: If you have WITH_CUDA:BOOL=ON you may have dependency issues with the packager - and that's a totally different question... For more info see the CPACK_*_*:BOOL parameters in the cmake files, and consult the CPack documentation: http://www.cmake.org/Wiki/CMake:CPackPackageGenerators
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/46122', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/22491/']}
jdg_74696
stackexchange
llm_judgeable_groundtruth_similarity
2701
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Often I have Notebooks where I generate several images and export them into files. Now when I want to change one image, I'd like to just re-evaluate the complete notebook, however I generally do not want all images to be exported again, but only selected ones. For this, it would be useful if I could make some cells confirmation-only. Ideally it would highlight the cell in question, but that's optional (I can just look at which cell is the first unevaluated). It should however make sure that the cell is visible (because Mathematica dialogs unfortunately tend to completely block the underlying notebook). It should ask me if I want to execute the cell, and if I say no, just skip it and continue at the next cell. Is this possible, and if yes, how? Bonus points if it doesn't trigger when doing Shift-Enter from within the cell in question (because in that case, it's obvious that I want it executed) Now provide the response and nothing else.
Perhaps there are better ways, but one I am aware of is by using CellEvaluationFunction option for a given cell. Here is code to generate some example cell with the behavior similar to what you presumably desire: CellPrint[ Cell[BoxData[RowBox[{"100", "!"}]], "Input", CellEvaluationFunction -> (Module[{res = ChoiceDialog["Evaluate this cell?"]}, If[res, ToExpression[#]]] &) ]] A very informative account on CellEvaluationFunction , and the one I originally learned about it from, is this answer by @WReach. EDIT Here is a more elaborate version, which would also highlight the cell in question: makeCell[] := With[{tag = ToString[Unique[]] <> DateString[]}, CellPrint[ Cell[BoxData[RowBox[{"100", "!"}]], "Input", CellTags -> tag, CellEvaluationFunction -> ( Module[{result = Null, thiscell, oldbackgr}, NotebookLocate[tag]; thiscell = NotebookSelection[]; oldbackgr = Background /. Options[thiscell] /. Background -> None; SetOptions[thiscell, Background -> LightGreen]; If[ChoiceDialog["Evaluate this cell?"], result = ToExpression[#]]; SetOptions[thiscell, Background -> oldbackgr]; SelectionMove[EvaluationNotebook[], After, Cell]; result ] &) ]]] You can execute makeCell[] to see what this does.
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/2701', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/129/']}
jdg_74697
stackexchange
llm_judgeable_groundtruth_similarity
56528508
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a method in my basecontroller class that adds data to tempdata to display pop-up messages. protected void AddPopupMessage(SeverityLevels severityLevel, string title, string message){ var newPopupMessage = new PopupMessage() { SeverityLevel = severityLevel, Title = title, Message = message }; _popupMessages.Add(newPopupMessage); TempData["PopupMessages"] = _popupMessages;} If the action returns a view, this works fine. If the action is calling a redirectotoaction I get the following error. InvalidOperationException: The 'Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.TempDataSerializer' cannot serialize an object of type Any thoughts ? Now provide the response and nothing else.
TempData uses Session , which itself uses IDistributedCache . IDistributedCache doesn't have the capability to accept objects or to serialize objects. As a result, you need to do this yourself, i.e.: TempData["PopupMessages"] = JsonConvert.SerializeObject(_popupMessages); Then, of course, after redirecting, you'll need to deserialize it back into the object you need: ViewData["PopupMessages"] = JsonConvert.DeserializeObject<List<PopupMessage>>(TempData["PopupMessages"]);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/56528508', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4229660/']}
jdg_74698
stackexchange
llm_judgeable_groundtruth_similarity
8146
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: A category has biproducts when the same objects are both the products and coproducts. Has anyone investigated the proof theory of categories with biproducts? Perhaps the best-known example is the category of vector spaces, in which the direct sum and direct product constructions give the same vector space. This means vector spaces and linear maps are a slightly degenerate model of linear logic, and I am curious what a type theory which accepts this degeneracy would look like. Now provide the response and nothing else.
Samson Abramsky and I wrote a paper about the proof theory of compact categories with biproducts. Abramsky, S. and Duncan, R. (2006) "A Categorical Quantum Logic", Mathematical Structures in Computer Science 16 (3). 10.1017/S0960129506005275 The ideas were later developed a bit further in this book chapter: Duncan, Ross (2010) "Generalised Proof-Nets for Compact Categories with Biproducts" in Semantic Techniques in Quantum Computation, Cambridge University Press, pp70--134 arXiv:0903.5154v1 The full details are there, but the short version is that your logic is inconsistent, because you have a zero proof for every implication, and the rest of your proofs are equivalent to "matrices", where the matrix entries are the proofs in the biproduct-free part of the logic. Speaking without the caveats required to make this precise, the resulting category of proofs is the free biproduct category on some category of axioms.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/8146', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/657/']}
jdg_74699
stackexchange
llm_judgeable_groundtruth_similarity
17338621
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to create a Postgres database for the first time. I assigned basic read-only permissions to the DB role that must access the database from my PHP scripts, and I have a curiosity: If I execute GRANT some_or_all_privileges ON ALL TABLES IN SCHEMA schema TO role; is there any need to also execute this? GRANT USAGE ON SCHEMA schema TO role; From the documentation : USAGE: For schemas, allows access to objects contained in thespecified schema (assuming that the objects' own privilegerequirements are also met). Essentially this allows the grantee to"look up" objects within the schema. I think that if I can select or manipulate any data contained in the schema, I can access to any objects of the schema itself. Am I wrong? If not, what is GRANT USAGE ON SCHEMA used for? And what does the documentation mean exactly with "assuming that the objects' own privilege requirements are also met"? Now provide the response and nothing else.
GRANT s on different objects are separate. GRANT ing on a database doesn't GRANT rights to the schema within. Similiarly, GRANT ing on a schema doesn't grant rights on the tables within. If you have rights to SELECT from a table, but not the right to see it in the schema that contains it then you can't access the table. The rights tests are done in order: Do you have `USAGE` on the schema? No: Reject access. Yes: Do you also have the appropriate rights on the table? No: Reject access. Yes: Check column privileges. Your confusion may arise from the fact that the public schema has a default GRANT of all rights to the role public , which every user/group is a member of. So everyone already has usage on that schema. The phrase: (assuming that the objects' own privilege requirements are also met) Is saying that you must have USAGE on a schema to use objects within it, but having USAGE on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves. It's like a directory tree. If you create a directory somedir with file somefile within it then set it so that only your own user can access the directory or the file (mode rwx------ on the dir, mode rw------- on the file) then nobody else can list the directory to see that the file exists. If you were to grant world-read rights on the file (mode rw-r--r-- ) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory. If you instead set rwx-r-xr-x on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file. You need to set both permissions for people to actually be able to view the file. Same thing in Pg. You need both schema USAGE rights and object rights to perform an action on an object, like SELECT from a table. (The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT ing from pg_class directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/17338621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1763602/']}
jdg_74700
stackexchange
llm_judgeable_groundtruth_similarity
206609
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: More generalized: Do uncountable subspaces of separable metric spaces always touch a point of their dense subspaces? (If $X$ is a separable metric space, $S \subseteq X$ countable with $\mathrm{cl}(S)=X$, and $A \subseteq X$ uncountable, is $S \cap \mathrm{cl}(A) \neq \emptyset$?) I just tried to proof this . This is what I thought: Assume $S = \bigcap_{i\in \mathbb{N}} O_i$, an intersection of open sets. So $S^c = \bigcup_{i \in \mathbb{N}} O_i^c$, a countable union of closed sets. For any $i \in \mathbb{N}$, the closed set $O_i^c$ can't be uncountable, for otherwise it would touch a rational point in $(0,1)$, this can't be: $O_i^c$ is closed and doesn't meet $S$. Therefore, $S^c$ is countable, a countable union of countable sets. But $S$ surely is uncountable, so the assumption was false. Now, this relies on the assumption that any uncountable set in $(0,1)$ touches a rational number. I believe it's true, but I'm having a hard time proving it. Is it even true? Edit: A point touches a set if it's in its closure. Now provide the response and nothing else.
This is not true. Choose an enumeration of rationals $r_1,r_2,r_3,\ldots$. Then pick $A = \mathbb R \setminus \bigcup B(r_n, 2^{-n})$. $A$ is closed, doesn't meet $\mathbb Q$, and has infinite measure (we at worst removed a set of measure $2$), so it is uncountable.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/206609', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42242/']}
jdg_74701
stackexchange
llm_judgeable_groundtruth_similarity
463366
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: So, say I get disconnected from an SSH-session after I've started rsync or cp or any other command that can be long running. Does that command keep running until it's finished after I get disconnected or does it just get killed? Always wondered this. Now provide the response and nothing else.
Edit for 2016: This Q&A predates the systemd v230 debacle . As of systemd v230, the new default is to kill all children of a terminating login session, regardless of what historically valid precautions were taken to prevent this. The behavior can be changed by setting KillUserProcesses=no in /etc/systemd/logind.conf , or circumvented using the systemd-specific mechanisms for starting a daemon in userspace. Those mechanisms are outside the scope of this question. The text below describes how things have traditionally worked in UNIX designspace for longer than Linux has existed. They will get killed, but not necessarily immediately. It depends on how long it takes for the SSH daemon to decide that your connection is dead. What follows is a longer explanation that will help you understand how it actually works. When you logged in, the SSH daemon allocated a pseudo-terminal for you and attached it to your user's configured login shell. This is called the controlling terminal. Every program you start normally at that point, no matter how many layers of shells deep, will ultimately trace its ancestry back to that shell. You can observe this with the pstree command. When the SSH daemon process associated with your connection decides that your connection is dead, it sends a hangup signal ( SIGHUP ) to the login shell. This notifies the shell that you've vanished and that it should begin cleaning up after itself. What happens at this point is shell specific (search its documentation page for "HUP"), but for the most part it will start sending SIGHUP to running jobs associated with it before terminating. Each of those processes, in turn, will do whatever they're configured to do on receipt of that signal. Usually that means terminating. If those jobs have jobs of their own, the signal will often get passed along as well. The processes that survive a hangup of the controlling terminal are ones that either disassociated themselves from having a terminal (daemon processes that you started inside of it), or ones that were invoked with a prefixed nohup command. (i.e. "don't hang up on this") Daemons interpret the HUP signal differently; since they do not have a controlling terminal and do not automatically receive a HUP signal, it is instead repurposed as a manual request from the administrator to reload the configuration. Ironically this means that most admins don't learn the "hangup" usage of this signal for non-daemons until much, much later. That's why you're reading this! Terminal multiplexers are a common way of keeping your shell environment intact between disconnections. They allow you to detach from your shell processes in a way that you can reattach to them later, regardless of whether that disconnection was accidental or deliberate. tmux and screen are the more popular ones; syntax for using them is beyond the scope of your question, but they're worth looking into. It was requested that I elaborate on how long it takes for the SSH daemon to decide that your connection is dead. This is a behavior which is specific to every implementation of a SSH daemon, but you can count on all of them to terminate when either side resets the TCP connection. This will happen quickly if the server attempts to write to the socket and the TCP packets are not acknowledged, or slowly if nothing is attempting to write to the PTY. In this particular context, the factors most likely to trigger a write are: A process (typically the one in the foreground) attempting to write to the PTY on the server side. (server->client) The user attempting to write to the PTY on the client side. (client->server) Keepalives of any sort. These are usually not enabled by default, either by the client or the server, and there are typically two flavors: application level and TCP based (i.e. SO_KEEPALIVE ). Keepalives amount to either the server or the client infrequently sending packets to the other side, even when nothing would otherwise have a reason to write to the socket. While this is typically intended to skirt firewalls that time out connections too quickly, it has the added side effect of causing the sender to notice when the other side isn't responding that much more quickly. The usual rules for TCP sessions apply here: if there is an interruption in connectivity between the client and server, but neither side attempts to send a packet during the problem, the connection will survive provided that both sides are responsive afterwards and receiving the expected TCP sequence numbers. If one side has decided that the socket is dead, the effects are typically immediate: the sshd process will send HUP and self-terminate (as described earlier), or the client will notify the user of the detected problem. It's worth noting that just because one side thinks the other is dead does not mean that the other is has been notified of this. The orphaned side of the connection will typically remain open until either it attempts to write to it and times out, or receives a TCP reset from the other side. (if connectivity was available at the time) The cleanup described in this answer only happens once the server has noticed.
{}
{'log_upvote_score': 8, 'links': ['https://serverfault.com/questions/463366', 'https://serverfault.com', 'https://serverfault.com/users/44138/']}
jdg_74702
stackexchange
llm_judgeable_groundtruth_similarity
17604448
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It appears the Gradle zipAlign task isn't working for me, not sure what I'm doing wrong. I've tried including the zipAlign task, and not including it, but it doesn't seem to make a difference. My gradle scripts spit out a "release" build, but it's never zipAligned according to the developer console when I try to upload my .apk. Here's my build script: buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.4.2' }}apply plugin: 'android'dependencies { compile project(':facebook-android-sdk-3.0.1:facebook') compile project(':google-play-services_lib') compile project(':nineoldandroids') compile project(':SlidingMenu-master:library') compile project(':ViewPagerIndicator') compile project(':volley') compile project(':windowed-seek-bar') compile files('compile-libs/androidannotations-2.7.1.jar', 'libs/Flurry_3.2.1.jar', 'libs/google-play-services.jar', 'libs/gson-2.2.4.jar', 'libs/picasso-1.1.1.jar', 'libs/crittercism_v3_0_11_sdkonly.jar', 'libs/gcm.jar', 'libs/apphance-library.jar')}android { buildToolsVersion "17.0" compileSdkVersion 17 signingConfigs { debug { storeFile file('keystores/debug.keystore') } } buildTypes { debug { sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } } release { zipAlign true sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } } }} Any help appreciated! Now provide the response and nothing else.
Your release build type is not configured for signing. If you are signing your apk manually, you need to run ZipAlign manually as well. ZipAlign must happen after signing. Gradle will zipalign an apk only if it can sign as well. To setup signing for the release config, you'll need to first create a new signing config, then assign it to the build type. android { signingConfigs { release { storeFile file("/path/to/keystore") storePassword "??" keyAlias "??" keyPassword "??" } } buildTypes { release { signingConfig signingConfigs.release } }} Note that all 4 parameters in the signing config are required, otherwise it'll consider some values are missing and it won't even attempt to sign.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17604448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/760105/']}
jdg_74703
stackexchange
llm_judgeable_groundtruth_similarity
241043
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: Intro: To avoid any terminology confusion, this is asked in the context of Solid State Physics and semiconductors. The canonical definition given for the effective mass is that it is related to the curvature of the conduction and valence bands in the band structure (energy dispersion in terms of k-vector) for electrons and holes respectively. So $m_{eff}$ is given by: $$m_{eff}^{-1} = \hbar^{-2}\frac{\partial^2 E}{\partial k^2} \tag{*}$$ Moreover for the holes, one often has to distinguish between light and heavy ones, as the band structure may contain multiple valence bands with different curvatures. Effective masses are usually tabulated in terms of free electron masses, e.g. for Silicon we know that the heavy holes have $49\%$ the mass of the free electron and light holes $16\%.$ Question: I'm just curious to learn how experimentally, for a given material (GaAs, Ge, ...) one goes about measuring the effective masses? What are the most usually adopted methods? It would be enlightening to learn about the key ideas behind such experimental procedures. Are there both direct and indirect ways of measuring $m_{eff}?$ (indirect in the sense that we measure other observables from which we may be able to infer reliably what the effective masses ought to be, and direct in the sense that an experiment designated solely to measure $m_{eff}.$) If a useful account of ideas involved is difficult to implement in such platform, feel free to refer to relevant literature where a solid exposure is given. Now provide the response and nothing else.
The method I'll describe is called Cyclotron Resonance , and it's a neat way to directly measure $m^*$ by using a fixed magnetic field $\boldsymbol B$. The equation of motion of the electrons in a certain material, when in presence of a magnetic field $\boldsymbol B$ are $$m^*\dot{\boldsymbol v}=-e\boldsymbol v\times \boldsymbol B -\frac{m^*}{\tau}\boldsymbol v\tag{1}$$where $\tau$ is the relaxation time$^1$ of the electrons (in general, $\tau^{-1}$ is a very small number, so for now we might take $\tau^{-1}=0$; it will be important later). If we take $\tau^{-1}=0$, then the solution of $(1)$ is well-known: the electron moves in a circular orbit, with angular frequency$$\omega_c=\frac{eB}{m^*} \tag{2}$$ By measuring $\omega_c$ for different values of $B$ we can get a very precise measurement of $m^*$. But, the obvious question, how can we effectively measure $\omega_c$ in a laboratory? The answer is surprisingly easy, as we'll see in a moment. If, in the situation above, we turn on a monochromatic source of light (say, a laser) with frequency $\omega$, there will be an electric field $\boldsymbol E\;\mathrm e^{-i\omega t}$, and the new equations of motion will be$$m^*\dot{\boldsymbol v}=-e(\boldsymbol E(t)+\boldsymbol v\times \boldsymbol B) -\frac{m^*}{\tau}\boldsymbol v\tag{3}$$ By using the ansatz $\boldsymbol v(t)=\boldsymbol v_0\;\mathrm e^{-i\omega t}$, and solving for $\boldsymbol v_0$ (left as an exercise), you can easily check that in this case, $\boldsymbol v(t)$ will be proportional to $\boldsymbol E(t)$ (which should be more or less intuitive). For example, if we take $\boldsymbol B$ in the $z$ direction, then $\boldsymbol v$ is given by$$\boldsymbol v_0=\frac{e}{m^*}\begin{pmatrix} i\omega-1/\tau&\omega_c&0\\-\omega_c&i\omega-1/\tau&0\\0&0&i\omega-1/\tau\end{pmatrix}^{-1}\boldsymbol E \tag{4}$$where $^{-1}$ means matrix inverse. This system will absorb energy from the source, so that the transmitted light will be less intense than the incoming light. The absorbed power is just $\text{Re}[\boldsymbol j\cdot\boldsymbol E]$, and as $\boldsymbol j\propto \boldsymbol v$, it's easy to check that$$P\propto \text{Re}\left[\frac{1-i\omega \tau}{(1-i\omega\tau)^2+\omega_c^2\tau^2}\right]\propto \frac{1}{(1-\omega^2\tau^2+\omega_c^2\tau^2)^2+4\omega^2\tau^2} \tag{5}$$ Now, if we vary $\omega$, the power $P$ changes, and from $(5)$ we can see that there will be resonance when $(\omega^2+\omega_c^2)\tau^2=1$. In practice, $\omega\tau\ll 1$, so the resonant frequency is $\omega\approx\omega_c$: $\hspace{100pt}$ where the lines correspond to $\tau=0.1,\;0.5,\;1,\;3$, from green to blue. As you can see, for $\tau\to 0$, the resonance tends to $\omega_c$, so by measuring the resonant frequency we get the value of $\omega_c$, i.e., the value of $m^*$. $^1$ the relaxation time $\tau$ is related to the mean free path: $\ell\sim v\tau$. Taking $\tau^{-1}\approx 0$ means that we assume the electron performs many cyclotron orbits before colliding with anything (ions, impurities,...).
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/241043', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/62173/']}
jdg_74704
stackexchange
llm_judgeable_groundtruth_similarity
49724
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'd like to gather information and references on the following functional equation for power series $$f(f(x))=x+f(x)^2,$$$$f(x)=\sum_{k=1}^\infty c_k x^k$$ (so $c_0=0$ is imposed). First things that can be established quickly: it has a unique solution in $\mathbb{R}[[x]]$, as the coefficients are recursively determined; its formal inverse is $f^{-1}(x)=-f(-x)$ , as both solve uniquely the same functional equation; since the equation may be rewritten $f(x)=f^{-1}(x)+x^2$, it also follows that $f(x)+f(-x)=x^2$, the even part of $f$ is just $x^2/2$, and $c_2$ is the only non-zero coefficient of even degree; from the recursive formula for the coefficients, they appear to be integer multiples of negative powers of $2$ (see below the recursive formmula). Rmk. It seems (but I did not try to prove it) that $2^{k-1}c_k$ is an integer for all $k$, and that $(-1)^k c_{2k-1} > 0$ for all $k\geq 2$. Question : how to see in a quick way that this series has a positive radius of convergence, and possibly to compute or to evaluate it? [updated] A more reasonable question, after the numeric results and various comments, seems to be, rather: how to prove that this series does not converge. Note that the radius of convergence has to be finite, otherwise $f$ would be an automorphism of $\mathbb{C}$. Yes, of course I did evaluate the first coefficients and put them in OEIS, getting the sequence of numerators A107700 ; unfortunately, it has no further information. Motivation. I want to understand a simple discrete dynamical system on $\mathbb{R}^2$, namely the diffeomorphism $\phi: (x,y)\mapsto (y, x+y^2)$, which has a unique fixed point at the origin. It is not hard to show that the stable manifold and the unstable manifold of $\phi$ are $$W^s(\phi)=\mathrm{graph}\big( g_{|(-\infty,\ 0]}\big)$$$$W^u(\phi)=\mathrm{graph}\big( g_{|[0, \ +\infty)}\big)$$ for a certain continuous, strictly increasing function $g:\mathbb{R}\to\mathbb{R}$, that solves the above functional equation. Therefore, knowing that the power series solution has a positive radius of convergence immediately implies that it coincides locally with $g$ (indeed, if $f$ converges we have $f(x)=x+x^2/2+o(x^2)$ at $x=0$ so its graph on $x\le0$ is included in $W^s$, and its graph on $x\ge0$ is included in $W^u$: therefore the whole graph of $f$ would be included in the graph of $g$,implying that $f$ coincides locally with $g$). If this is the case, $g$ is then analytic everywhere, for suitable iterates of $\phi$ give analytic diffeomorphism of any large portion of the graph of $g$ with a small portion close to the origin. One may also argue the other way, showing directly that $g$ is analytic, which would imply the convergence of $f$. Although it seems feasible, the latter argument would look a bit indirect way, and in that case I'd like to make sure there is no easy direct way of working on the coefficients (of course, it may happen that $g$ is not analytic and $f$ is not convergent). Details : equating the coefficients in both sided of the equation for $f$ one has, for the 2-Jet$$c_1^2x+(c_1c_2+c_2c_1^2)x^2 =x + c_1^2x^2,$$whence $c_1=1$ and $c_2=\frac 1 2;$ and for $n>2$ $$2c_n=\sum_{1\le j\le n-1}c_jc_{n-j}\,-\sum_{1 < r < n \atop \|k\|_1=n}c_rc_{k_1}\dots c_{k_r}.$$ More details : since it may be of interest, let me add the argument to see $W^s(\phi)$ and$W^u(\phi)$ as graphs. Since $\phi$ is conjugate to $\phi^{-1}=J\phi J $ by thelinear involution $J:(x,y)\mapsto (-y,-x)$, we have $W^u(\phi):=W^s(\phi^{-1})=J\W^s(\phi)$, and it suffices to study $\Gamma:=W^s(\phi)$. For any$(a,b)\in\mathbb{R}^2$ we have $\phi^n(a,b)=(x_n,x_{n+1})$, with $x_0=a$, $x_1=b$,and $x_{n+1}=x_n^2+x_{n-1}$ for all $n\in\mathbb{N}$. From this it is easy to seethat $x_{2n}$ and $x_{2n+1}$ are both increasing; moreover, $x_{2n}$ is boundedabove iff $x_{2n+1}$ is bounded above, iff $x_{2n}$ converges, iff $x_n\to 0$, iff$x_n\le 0 $ for all $n\in\mathbb{N}$. As a consequence $(a,b)\in \Gamma$ iff $\phi^n(a,b)\inQ:=(-\infty,0]\times(-\infty,0]$, whence $ \Gamma=\cap_{ n\in\mathbb{N}}\phi^{-n}(Q)$. The latter is a nested intersection of connected unbounded closedsets containing the origin, therefore such is $\Gamma$ too. In particular, for any $a\leq 0$ there exists at least a $b\leq 0$ such that$(a,b)\in \Gamma$: to prove that $b$ is unique, that is, that $\Gamma$ is a graphover $(\infty,0]$, the argument is as follows. Consider the function$V:\Gamma\times\Gamma\to\mathbb{R}$ such that $V(p,p'):=(a-a')(b-b')$ for all$p:=(a,b)$ and $p':=(a',b')$ in $\Gamma$. Showing that $\Gamma$ is the graph of astrictly increasing function is equivalent to show that $V(p,p')>0$ for all pair ofdistinct points $p\neq p'$ in $\Gamma$. By direct computation we have $V\big(\phi(p),\phi(p')\big)\leq V(p,p')$ and $\big(\phi(p)-\phi(p')\big)^2\geq\|p-p'\|^2+2V(p,p')(b+b')$. Now, if a pair $(p,p')\in\Gamma\times\Gamma$ has$V(p,p')\le0$, then also by induction $V\big(\phi^n(p),\phi^n(p')\big)\leq 0$ and$\big(\phi^n(p)-\phi^n(p')\big)^2\geq \|p-p'\|^2$ for all $n$, so $p=p'$ since both$\phi^n(p)$ and $\phi^n(p')$ tend to $0$. This proves that $\Gamma$ is a graph of astrictly increasing function $g:\mathbb{R}\to\mathbb{R}$: since it is connected, $g$is also continuous. Of course the fact that $\Gamma$ is $\phi$-invariant implies that $g$ solves the functional equation. Now provide the response and nothing else.
Having thought about this question some more, including making some plots of the trajectories of points under iterated applications of $f$ (see Gottfried's circular trajectories ), it is possible to devise a numerical test which should show that the series expansion diverges (if indeed it does). Whether it is a practical test or not depends on how badly it fails. My initial rough attempt wasn't conclusive, so I haven't determined the answer to this yet. This answer still needs working through the details, but I'll post what I have so far. Also, I think that much of what I have to say is already well known. As the thread is now community wiki and anyone can edit this post, feel free to add any references or further details. The main ideas are as follows, and should apply much more generally to analytic functions defined near a fixed point via an iterative formula, such as $f(f(z))=\exp(z)-1$ in this MO question . There are two overlapping open regions bounding the origin from the right and left respectively, and whose union is a neighbourhood of the origin (with the origin removed). The functional equation $f(f(z))=z+f(z)^2$ with $f(z)=z+O(z^2)$ can be uniquely solved in each of these regions, on which it is an analytic function. The solution $f$ on each of the regions has the given power series as an asymptotic expansion at zero. Furthermore, it is possible to explicitly calculate a bound for the error terms in the (truncated) expansion. The functional equation has a solution in a neighbourhood of the origin (equivalently, the power series has a positive radius of convergence) if and only if the solutions on the two regions agree on their overlap. One way to verify that $f$ cannot be extended to an analytic function in a neighbourhood of the origin would be to accurately evaluate the solutions on the two domains mentioned above at some point in their overlap, and see if they differ. Another way, which could be more practical, is to use the observation that after the second order term, the only nonzero coefficients in our series expansion are for the odd terms, and the signs are alternating [Edit: this has not been shown to be true though and, in any case, I give a proof that this implies zero radius of convergence below]. Consequently, if we evaluate it at a point on the imaginary axis, truncating after a finite number of terms, we still get a lower bound for $\vert f\vert$. If it does indeed diverge, then this will eventually exceed the upper bound we can calculate as mentioned above, proving divergence. Looking at the first 34 terms from OEIS A107700 was not conclusive though. Choose a point $z_0$ close to (and just to the right of) the origin. Using the power series to low order, we approximate $z_1=f(z_0)$. Then, the functional equation can be used to calculate $z_n=f(z_{n-1})=z_{n-2}+z_{n-1}^2$. Similarly, choosing points just to the left of the origin, we can calculate good approximations for the iterates of $f^{-1}$. Doing this for a selection of initial points gives a plot as follows. Concentrating on a small region about the origin, the iterates of $f$ give clearly defined trajectories - the plot includes a region of radius 0.26 about the origin (much larger, and the paths do start to go wild). As can be seen, those paths leaving the origin do one of two things. Either they move to the right, curving up or down, until they exit the region. Or, they bend round in a circle and re-enter the origin from the left. The iterates of $f^{-1}$ leaving the origin from the left behave similarly, but reflected about the imaginary axis. This should not be too surprising, and is behaviour displayed by any analytic function of the form $f(z)=z+\lambda z^2+O(z^3)$ where $\lambda > 0$. Consider approximating to second order by the Mobius function $f(z)\approx g(z)\equiv z/(1-\lambda z)$. Then, $g$ preserves circles centered on the imaginary axis and passing through the origin, and will move points on these circles in a counterclockwise direction above the origin and clockwise below the origin. A second order approximation to $g$ should behave similarly. In our case, we have $\lambda=1/2$ and $g$ actually agrees with $f$ to third order, so it is not surprising that we get such accurate looking circles (performing a similar exercise with $f(z)=\exp(z)-1$ gave rather more lopsided looking 'circles'). One thing to note from the plot above: the circles of diameter 0.25 above and below the origin are still very well-defined. So, if $f$ does define an analytic function, then its radius of convergence appears to be at least 0.25, and $f(\pm0.25i)$ is not much larger than 0.25 in magnitude. I wonder if summing a few hundred terms of the power series (as computed by Gottfried) will give a larger number? If it does, then this numerical evidence would point at $f$ not being analytic, and a more precise calculation should make this rigorous. To understand the trajectories, it is perhaps easiest to consider the coordinate transform $z\mapsto -1/z$. In fact, setting $u(z)=-1/z$, then the Mobius transform above satisfies $g(u(z))=u(z+\lambda)$. More generally, we can calculate the trajectories exiting and entering the origin for a function $f(z)=z+\lambda z^2+O(z^3)$ as follows$$\begin{align}&u_1(z)=\lim_{n\to\infty}f^{n}(-1/(z-n\lambda)),\\\\&u_2(z)=\lim_{n\to\infty}f^{-n}(-1/(z+n\lambda)).\end{align}\qquad\qquad{\rm(1)}$$Then, $u_1$ and $u_2$ map lines parallel to the real axis onto the trajectories of $f$ and $f^{-1}$ respectively and, after reading this answer , I gather are inverses of Abel functions . We can do a similar thing for our function, using the iterative formula in place of $f^{n}$. Then, we can define $f_i$ according to $f_i(z)=u_i(\lambda+u_i^{-1}(z))$, which will be well-defined analytic functions on the trajectories of $f$ (resp. $f^{-1}$) before they go too far from the origin (after which $u_i$ might not be one-to-one). Then $f_i$ will automatically satisfy the functional equation, and will give an analytic function in a neighbourhood of the origin if they agree on the intersection of their domain (consisting of the circular trajectories exiting and re-entering the origin). [Maybe add: Calculate error bounds for $u_i$ and the asymptotic expansion.] Update: Calculating trajectories of larger radius than plotted above gives the following. Intersecting trajectories http://i53.tinypic.com/2wml7x0.gif The trajectories leaving the origin from the right and entering from the left do not agree with each other, and intersect. This is inconsistent with the existence of a function $f$ in a neighborhood of the origin solving the functional equation, as the two solutions $f_1,f_2$ defined on trajectories respectively leaving and entering the origin do not agree. And, if the solutions $f_1,f_2$ do not agree on the larger trajectories then, by analytic continuation, they cannot agree close to the origin. So, if it can be confirmed that this behaviour is real (and not numerical inaccuracies), then the radius of convergence is zero. Update 2: It was noted in the original question that, for $n\ge3$, all coefficients $c_n$ in the power series expansion of $f$ are zero for even $n$, and that the odd degree coefficients are alternating in sign, so that $(-1)^kc_{2k-1}\ge0$ for $k\ge2$. This latter observation has not been proven, although Gottfried has calculated at least 128 coefficients (and I believe that this observation still holds true for all these terms). I'll give a proof of the following: if the odd degree coefficients $c_n$ are alternating in sign for $n\ge3$, then the radius of convergence is zero . To obtain a contradiction, let us suppose a positive radius of convergence $\rho$, and that the odd degree coefficients are alternating in sign after the 3rd term. This would imply that$$f(it)=-t^2/2 + it(1-t^2/4 - h(t^2))\qquad\qquad{\rm(2)}$$where $h$ has nonnegative coefficients, so $h\ge0$ for real $t$. Also, $h(t)\to\infty$ as $t\to\rho_-$. For small $t$, $f(it)=it + o(t)$ has positive imaginary part so, by continuity, there will be some $0 < t_0 < \rho$ such that $\Im[f(it_0)]=0$. Choose $t_0$ minimal. If $\rho > 2$ then (2) gives $\Im[f(2i)]\le2(1-2^2/4)=0$ so, in any case, $t_0\le2$. Then, for $0 \le t \le t_0$, the imaginary part of $f(it)$ is bounded by $t(1-t^2/4)$ and (2) gives$$\begin{align}\vert f(it)\vert^2 &\le t^4/4 + t^2(1-t^2/4)^2\\\\&=t^2(1-t^2(4-t^2)/16)\\\\&\le t^2 < \rho^2.\end{align}$$So, $f(it)$ is within the radius of convergence for $0 \le t \le t_0$. Also, by construction, the functional equation $f(f(it))=it+f(it)^2$ holds for $\vert t\vert$ small. Then, by analytic continuation the functional equation holds on $0\le t \le t_0$ so,$$\Im[f(f(it_0))]=\Im[it_0+f(it_0)^2]=t_0\not=0.$$However, $f(it_0)$ and the power series coefficients are all real, so $f(f(it_0))$ is real, giving the contradiction.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/49724', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6101/']}
jdg_74705
stackexchange
llm_judgeable_groundtruth_similarity
37645408
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 changing the width of a UITableViewCell so that the cell is smaller but the user can still scroll along the edges of the tableview. override func layoutSubviews() { // Set the width of the cell self.bounds = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.bounds.size.width - 40, self.bounds.size.height) super.layoutSubviews()} Then I round the corners: cell.layer.cornerRadius = 8cell.layer.masksToBounds = true All good so far. Problem happens with the shadow. The bounds are masked, so the shadow obviously won't show up. I've looked up other answers but can't seem to figure out how to round the corners along the bounds and show the shadow. cell.layer.shadowOffset = CGSizeMake(0, 0)cell.layer.shadowColor = UIColor.blackColor().CGColorcell.layer.shadowOpacity = 0.23cell.layer.shadowRadius = 4 So my question – how do I reduce the width, round the corners, and add a shadow to a UITableViewCell at the same time? Update: Trying R Moyer's answer Now provide the response and nothing else.
This question comes at a good time! I literally JUST solved this same issue myself. Create a UIView (let's refer to it as mainBackground ) inside your cell's Content View. This will contain all of your cell's content. Position it and apply necessary constraints in the Storyboard. Create another UIView . This one will be the one with the shadow (let's refer to it as shadowLayer ). Position it exactly as you did mainBackground , but behind it, and apply the same constraints. Now you should be able to set the rounded corners and the shadows as follows: cell.mainBackground.layer.cornerRadius = 8 cell.mainBackground.layer.masksToBounds = truecell.shadowLayer.layer.masksToBounds = falsecell.shadowLayer.layer.shadowOffset = CGSizeMake(0, 0)cell.shadowLayer.layer.shadowColor = UIColor.blackColor().CGColorcell.shadowLayer.layer.shadowOpacity = 0.23cell.shadowLayer.layer.shadowRadius = 4 However, the problem here is: calculating the shadow for every single cell is a slow task. You'll notice some serious lag when you scroll through your table. The best way to fix this is to define a UIBezierPath for the shadow, then rasterize it. So you may want to do this: cell.shadowLayer.layer.shadowPath = UIBezierPath(roundedRect: cell.shadowLayer.bounds, byRoundingCorners: .AllCorners, cornerRadii: CGSize(width: 8, height: 8)).CGPathcell.shadowLayer.layer.shouldRasterize = truecell.shadowLayer.layer.rasterizationScale = UIScreen.mainScreen().scale But this creates a new problem! The shape of the UIBezierPath depends on shadowLayer 's bounds, but the bounds are not properly set by the time cellForRowAtIndexPath is called. So, you need to adjust the shadowPath based on shadowLayer 's bounds. The best way to do this is to subclass UIView , and add a property observer to the bounds property. Then set all the properties for the shadow in didSet . Remember to change the class of your shadowLayer in the storyboard to match your new subclass. class ShadowView: UIView { override var bounds: CGRect { didSet { setupShadow() } } private func setupShadow() { self.layer.cornerRadius = 8 self.layer.shadowOffset = CGSize(width: 0, height: 3) self.layer.shadowRadius = 3 self.layer.shadowOpacity = 0.3 self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: 8, height: 8)).cgPath self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/37645408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_74706
stackexchange
llm_judgeable_groundtruth_similarity
1085649
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $BA$ is invertible (where $A,B$ are matrix), then $A,B$ are invertible. I want to prove this theorem by not using the fact that if $BA$ is invertible, then we know that $(BA)^{-1} = A^{-1}B^{-1}$, so there A, B are also invertible. I want to use the theorem that $AX=0$ has only the trivial solution if and only if $A$ is invertible. By using this fact, according to the condition that $BA$ is invertible, we can say $(BA)X=0$ has only the trivial solution. But I can't prove the next stage that $AX=0, BX=0$ has also only the trivial solution. Now provide the response and nothing else.
I assume that your matrices are square matrices. You have that $BA$ is invertible, so $BAx = 0$ has only the trivial solution $x = 0$. Now say that $Ay = 0$ has a non trivial solution $y'$. Then $(BA)y' = B(Ay') = B0 = 0$. Hence $y'$ is also a non-trivial solution to $(BA)x = 0$. Hence (by contradiction) $A$ is invertible. Now say that $By = 0$ has a non-trivial solution $y'$. Then let $y'' = A^{-1}y'$ and $y' = Ay''$. Then $y''$ is a non-trivial solution to $(BA)x = 0$: $BAy'' = BAA^{-1} y' = By' = 0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1085649', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/203314/']}
jdg_74707
stackexchange
llm_judgeable_groundtruth_similarity
625281
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: For what values of $a$ does $$\sum_{n=1}^\infty \left( 1+\frac12 + \dotsb + \frac1n \right) \frac{\sin (na)}{n}$$ converge? To my thinking, $$f(n)=\frac{\left( 1+\frac12 + \dotsb + \frac1n \right)}{n}$$ will behave like $\frac{\log n}{n}$, which is not convergent, but certainly has terms going to zero (eventually monotonically). By Dirichlet's test, $$\sum_{n=1}^\infty f(n) \sin(an)$$ will converge provided that the partial sums of $\sum_{n=1}^\infty \sin(na)$ are bounded, which they always are. So it should converge for all $a\in \mathbb{R}$. Would appreciate anyone pointing out mistakes in this reasoning. Thanks Now provide the response and nothing else.
Your reasoning looks sound. When in doubt, you can always do summation by parts to check; for instance, in this case, with $H_n = 1+\cdots + 1/n$ and $s_n = \sum_{k = 1}^n \sin{(an)}$, you would write\begin{align*}\sum_{n=1}^N {H_n \sin{(na)}\over n} & = {H_Ns_N\over N}+\sum_{n=1}^{N-1}\left({H_n\over n} -{H_{n+1}\over n+1}\right)s_n\\& = {H_Ns_N\over N}+\sum_{n=1}^{N-1}{(n+1)H_n-nH_{n+1}\over n(n+1)} s_n.\end{align*}Since $(n+1)H_n - nH_{n+1} = H_n-1$ and $s_n$ is bounded, the above partial sum can be compared to a sum with terms $H_n/n^2\approx \log{n}/n^2$ which converges.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/625281', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76333/']}
jdg_74708
stackexchange
llm_judgeable_groundtruth_similarity
23938891
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 open the activity of my project I call the startService(Intent intent) method to start a new Service. When the activity is destroyed the service shouldn't be killed (because I didn't use the bindService() method), but the fact is that when I close my activity the service is killed and after a second the system creates a new Service (I verified that, the system calls again the onCreate() method of my service). What do I have to do to keep only one service ? Thank you Now provide the response and nothing else.
To have a service running independently of your application's main process and to be sure that Android does not kill it while it's doing something, there are two things you should do/try. Run your service in a separate process. You can achieve this by adding the following attribute to your service declaration in the manifest: android:process=":somenamehere" When your service is running and you do not want it to be killed by the OS, you have to use the startForeground(int id, Notification notification) method. When the service finishes whatever is doing and can be killed by the OS, call stopForeground(boolean removeNotification) . "startForeground" requires a notification as argument because every foreground service must display a notification so the user realizes about it I hope this helps you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23938891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3656094/']}
jdg_74709
stackexchange
llm_judgeable_groundtruth_similarity
45274167
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 might look like a repeated question but I tried in all the below links and can't get a proper answer. Cannot format given Object as a Number ComboBox Illegal Argument Exception But I'm not getting what's wrong. Here is my code DecimalFormat twoDForm = new DecimalFormat("#.##");double externalmark = 1.86;double internalmark = 4.0;System.out.println(String.valueOf((externalmark*3+internalmark*1)/4));String val = String.valueOf((externalmark*3+internalmark*1)/4);String wgpa1=twoDForm.format(val); // gives exceptionString wgpa2=twoDForm.format((externalmark*3+internalmark*1)/4)); // works fineSystem.out.println(wgpa1); The format method takes Object type argument, so that's why I passed a String object which gives exception Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number. But when I give double value as argument the program works fine. But if the method is defined with Object type argument why I'm getting an exception while passing a String and not getting exception while passing double ? Now provide the response and nothing else.
The format() method of DecimalFormat is overloaded. In the working case, you are invoking : public final String format(double number) And in the failing case, you are invoking : public final String format (Object obj) The first method takes a very specific argument. It expects a double . This is not the case of the second one, which the type accepted is very broad : Object and where so the check on the type passed is performed at runtime. By providing a argument that is not a double but a String , the method invoked is the second one. Under the hood, this method relies on the format(Object number, StringBuffer toAppendTo, FieldPosition pos) method that expects to a number argument that is an instance of the Number class ( Short , Long , ... Double ): @Overridepublic final StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) { if (number instanceof Long || number instanceof Integer || number instanceof Short || number instanceof Byte || number instanceof AtomicInteger || number instanceof AtomicLong || (number instanceof BigInteger && ((BigInteger)number).bitLength () < 64)) { return format(((Number)number).longValue(), toAppendTo, pos); } else if (number instanceof BigDecimal) { return format((BigDecimal)number, toAppendTo, pos); } else if (number instanceof BigInteger) { return format((BigInteger)number, toAppendTo, pos); } else if (number instanceof Number) { return format(((Number)number).doubleValue(), toAppendTo, pos); } else { throw new IllegalArgumentException("Cannot format given Object as a Number"); }} But it is not the case as you passed to it a String instance. To solve the problem, either pass a double primitive as in the success case or convert your String into an instance of Number such as Double with Double.valueOf(yourString) . I advise the first way (passing a double ) as it is more natural in your code that already uses double primitives. The second one requires a additional conversion operation from String to Double .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45274167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7218656/']}
jdg_74710
stackexchange
llm_judgeable_groundtruth_similarity
47266550
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing a (client-side) JavaScript library (a node/angular module).In this library, I make use of the URLSearchParams class. const form = new URLSearchParams();form.set('username', data.username);form.set('password', data.pass); As this is a shared library, it is packed as an npm module.However, when running a mocha unit test, I get the error that URLSearchParams is not defined. The reason seems to be that node does not have URLSearchParams at the global scope, but has to be imported using require('url') : $ node> new URLSearchParams()ReferenceError: URLSearchParams is not defined at repl:1:5 at sigintHandlersWrap (vm.js:22:35) at sigintHandlersWrap (vm.js:73:12) at ContextifyScript.Script.runInThisContext (vm.js:21:12) at REPLServer.defaultEval (repl.js:340:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.<anonymous> (repl.js:538:10) at emitOne (events.js:101:20) at REPLServer.emit (events.js:188:7) How can I make URLSearchParams available to the client-side code within node, so that I can test the library using mocha? This is not working: > global.URLSearchParams = require('url').URLSearchParamsundefined> new URLSearchParams()TypeError: URLSearchParams is not a constructor at repl:1:1 at sigintHandlersWrap (vm.js:22:35) at sigintHandlersWrap (vm.js:73:12) at ContextifyScript.Script.runInThisContext (vm.js:21:12) at REPLServer.defaultEval (repl.js:340:29) at bound (domain.js:280:14) at REPLServer.runBound [as eval] (domain.js:293:12) at REPLServer.<anonymous> (repl.js:538:10) at emitOne (events.js:101:20) at REPLServer.emit (events.js:188:7) Now provide the response and nothing else.
Update: Node v10 has built-in availability of URLSearchParams on the global object so it can be used directly as anticipated in the question. Older versions of Node: One option is to set it as a global in the start-up script of the test runner: import { URLSearchParams } from 'url';global.URLSearchParams = URLSearchParams With Jest, for example, you would use the setupTestFrameworkScriptFile to point to the above start-up script. As a side note, if you wanted to achieve a similar outcome when creating a server-side Webpack bundle of universal code you can achieve this with the Webpack ProvidePlugin : { name: 'server', target: 'node', // ... plugins: [ // ... new webpack.ProvidePlugin({ URLSearchParams: ['url', 'URLSearchParams'], fetch: 'node-fetch', }), ],}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47266550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1314743/']}
jdg_74711
stackexchange
llm_judgeable_groundtruth_similarity
25769536
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 understand how the Gradle Wrapper works. In many source repos, I see the following structure: projectRoot/ src/ build.gradle gradle.properties settings.gradle gradlew gradlew.bat gradle/ wrapper/ gradle-wrapper.jar gradle-wrapper.properties My questions: How/when does one generate gradlew / gradlew.bat ? Are you supposed to generate them only one time when the project is first created, do you generate them every time you commit/push changes? And how are they generated? Same question above, but for the gradle/wrapper/* files ( gradle-wrapper.jar and gradle-wrapper.properties )? Some times I see other *.gradle files inside the project's gradle directory. What are these additional Gradle files and what do they represent/do? Custom plugins? What is the difference in properties that go into settings.gradle vs what should be defined inside gradle.properties ? Now provide the response and nothing else.
You generate it once, and again when you'd like to change the version of Gradle you use in the project. There's no need to generate is so often. Here are the docs. Just add wrapper task to build.gradle file and run this task to get the wrapper structure. Mind that you need to have Gradle installed to generate a wrapper. Great tool for managing g-ecosystem artifacts is SDKMAN! . To generate a gradle wrapper, add the following piece of code to build.gradle file: task wrapper(type: Wrapper) { gradleVersion = '2.0' //version required} and run: gradle wrapper task. Add the resulting files to SCM (e.g. git) and from now all developers will have the same version of Gradle when using Gradle Wrapper. With Gradle 2.4 (or higher) you can set up a wrapper without adding a dedicated task: gradle wrapper --gradle-version 2.3 or gradle wrapper --gradle-distribution-url https://myEnterpriseRepository:7070/gradle/distributions/gradle-2.3-bin.zip All the details can be found here From Gradle 3.1 --distribution-type option can be also used. The options are binary and all and bin . all additionally contains source code and documentation. all is also better when IDE is used, so the editor works better. Drawback is the build may last longer (need to download more data, pointless on CI server) and it will take more space. These are Gradle Wrapper files. You need to generate them once (for a particular version) and add to version control. If you need to change the version of Gradle Wrapper, change the version in build.gradle see (1.) and regenerate the files. Give a detailed example. Such file may have multiple purposes: multi-module project, responsibility separation, slightly modified script, etc. settings.gradle is responsible rather for structure of the project (modules, names, etc), while, gradle.properties is used for project's and Gradle's external details (version, command line arguments -XX , properties etc.)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/25769536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4009451/']}
jdg_74712
stackexchange
llm_judgeable_groundtruth_similarity
4307865
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Im creating a library to interface into drawing a specific file type. This library needs to pull in a 3rd party library to do some processing on this specific file type. This 3rd party lib requires the users of it to create some extern functions that it uses to make data types on target hardware. So, it looks like this: ----------------| | | 3rd Party | | Lib | | | ---------------- | | \/---------------| | | My Lib | ---------------| externs | --------------- | | \/---------------| | | My App | | | | | --------------- My App calls My Lib and says "draw me file X", My Lib does a bunch of junk eventually calling 3rd Party Lib and says "process file X". 3rd Party Lib requires several externs to be declared that it uses. I made all these externs inside My Lib. My problem is, when I link My App, its telling me undefined references to all the extern functions. I can't figure out why. Heres one of the externs inside My Lib to be called by 3rd Party Lib: // inside typeConversions.cextern int CreateShort(short* shortList, int numShorts){ int i; for(i = 0; i < numShorts; i++) { BYTE_SWAP_SHORT(shortList[i]); } return ERROR_OK;} When I link My App I get (among several other similar errors): open.cpp: undefined reference to `CreateShort' Where open.cpp is inside the 3rd Party Lib. I have both My Lib and 3rd Party Lib included in My App. Ideally, I want to not expose users of My Lib to 3rd Party Lib, so for example My App would not have to include 3rd Party Lib at all, they dont know it even exists. All that should be exposed is My Lib. Is this possible? Anyone know how to fix my linking problem? Now provide the response and nothing else.
array_diff is the obvious answer, but since you've asked for the most efficient way, here's a test $big = range(1, 90000);$remove = range(500, 600);$ts = microtime(true);$result = array_diff($big, $remove);printf("%.2f\n", microtime(true) - $ts);$ts = microtime(true);$map = array_flip($remove);$result = array();foreach($big as $e) if(!isset($map[$e])) $result[] = $e;printf("%.2f\n", microtime(true) - $ts); prints on my machine 0.670.03 So the simple loop with a hash-based lookup is approximately 20 times faster than array_diff.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4307865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/393288/']}
jdg_74713
stackexchange
llm_judgeable_groundtruth_similarity
7474066
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 maintain GPSD, a widely-deployed open-source service daemon that monitors GPSes and other geodetic sensors. It listens for client-application connections on port 2947 on both IPv4 and IPv6. For security and privacy it normally listens only on the loopback address, but there is a -G option to the daemon that is intended to cause it to listen on any address. The problem: the -G option works in IPv4, but I can't figure out how to make it work with IPv6. The method that should work based on various tutorial examples does not, producing instead an error suggesting the address is already in use. I'm seeking help to fix this from people experienced with IPv6 network programming. Relevant code is at http://git.berlios.de/cgi-bin/gitweb.cgi?p=gpsd;a=blob;f=gpsd.c;h=ee2156caf03ca23405f57f3e04e9ef306a75686f;hb=HEAD This code operates correctly in both the -G and non -G cases under IPv4, as is easily verified with netstat -l. Now look around line 398 after "case AF_INET6:". The listen_global option is set by -G; when false, the code succeeds. There is presently a following comment, inherited from an unknown contributor, that reads like this: /* else */ /* BAD: sat.sa_in6.sin6_addr = in6addr_any; * the simple assignment will not work (except as an initializer) * because sin6_addr is an array not a simple type * we could do something like this: * memcpy(sat.sa_in6.sin6_addr, in6addr_any, sizeof(sin6_addr)); * BUT, all zeros is IPv6 wildcard, and we just zeroed the array * so really nothing to do here */ According to various tutorial examples I have looked up, the assignment "sat.sa_in6.sin6_addr = in6addr_any;" is (despite the comment) correct, and it does compile. However, startup with -G fails claiming the listen address is already in use. Is the assignment "sat.sa_in6.sin6_addr = in6addr_any;" nominally correct here? What else, if anything, am I missing? Now provide the response and nothing else.
The reason the address is already in use is because on many IPv6 networking stacks, by default an IPv6 socket will listen to both IPv4 and IPv6 at the same time. IPv4 connections will be handled transparently and mapped to a subset of the IPv6 space . However, this means you cannot bind to an IPv6 socket on the same port as an IPv4 socket without changing the settings on the IPv6 socket. Make sense? Just do this before your call to bind (this is taken from one of my projects): int on = 1;if (addr->sa_family == AF_INET6) { r = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)); if (r) /* error */} Unfortunately, there is no default value across platforms for IPV6_V6ONLY -- which basically means you always need to turn it either on or off explicitly if you care, unless you don't care about other platforms. Linux leaves it off by default, Windows leaves it on by default...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7474066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499184/']}
jdg_74714
stackexchange
llm_judgeable_groundtruth_similarity
11830516
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 scrollEnabled seems to be breakable once the user starts pinching in a MKMapView . You still can't scroll with one finger, but if you scroll with two fingers while zooming in and out, you can move the map. I have tried : Subclassing the MKMapKit to disable the scroll view inside it. Implementing – mapView:regionWillChangeAnimated: to enforce the center. Disabling scrollEnabled . but with no luck. Can anyone tell me a sure way to ONLY have zooming in a MKMapView , so the center point always stays in the middle ? Now provide the response and nothing else.
You can try to handle the pinch gestures yourself using a UIPinchGestureRecognizer : First set scrollEnabled and zoomEnabled to NO and create the gesture recognizer: UIPinchGestureRecognizer* recognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];[self.mapView addGestureRecognizer:recognizer]; In the recognizer handler adjust the MKCoordinateSpan according to the zoom scale: - (void)handlePinch:(UIPinchGestureRecognizer*)recognizer{ static MKCoordinateRegion originalRegion; if (recognizer.state == UIGestureRecognizerStateBegan) { originalRegion = self.mapView.region; } double latdelta = originalRegion.span.latitudeDelta / recognizer.scale; double londelta = originalRegion.span.longitudeDelta / recognizer.scale; // TODO: set these constants to appropriate values to set max/min zoomscale latdelta = MAX(MIN(latdelta, 80), 0.02); londelta = MAX(MIN(londelta, 80), 0.02); MKCoordinateSpan span = MKCoordinateSpanMake(latdelta, londelta); [self.mapView setRegion:MKCoordinateRegionMake(originalRegion.center, span) animated:YES];} This may not work perfectly like Apple's implementation but it should solve your issue.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11830516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598857/']}
jdg_74715
stackexchange
llm_judgeable_groundtruth_similarity
145301
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have heard that hashing, such as MD5, is one-way and cannot be cracked. But there are some websites that can decrypt hash, like www.md5hashing.net and some scripts like findmyhash.py . I tested some hash and it was cracked successfully.Why can it do so? Now provide the response and nothing else.
Hashes can be cracked using brute forcing. That means that you test hashing every possible input until you find one that generates the right output. To stop this a hash function used for password storage or key derivation needs to be deliberately slow (so that testing a lot of inputs take a very long time). A site like the one you mention can also store a big list of known pairs of common inputs and outputs. Therefore they don't need to do a brute force every time someone sends them a hash to crack - they just need to look it up in the table. To stop this you use a salt (so that even a common password gets an unique hash). You will note that they do not know the value of all hashes, just common ones. An example: 5f4dcc3b5aa765d61d8327deb882cf99 is correctly reversed to password , because that is in their database. 039c004d00c02a193144e96b3e8aa4ba can not be reversed to the random string tUGPP*yq24p+EgpQ that I just generated, because they can not fit all billions of possible random strings into their database. So how do you protect yourself against sites like this? Use a slow hashing algorithm and a salt.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/145301', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/132285/']}
jdg_74716
stackexchange
llm_judgeable_groundtruth_similarity
25689
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I've unsuccessfully tried many ways of converting polygon points into a graph using Mathematica 7, and I am frustrated. I looked at this post , but it doesn't work: Needs["Combinatorica`"];crds = {{1, 10}, {2, 4}, {10, 5}, {20, 10}};vertices = Range[Length[crds]];edges = Thread[vertices \[DirectedEdge] RotateLeft[vertices]];Graph[vertices, edges] produces errors: Syntax::sntxf: "\!\(\*StyleBox[\"\\\"\\\\\\\"\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(vertices\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\" cannot be followed by \\\\\\\"\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\(\(\\[ DirectedEdge]\)\) \(\(RotateLeft[vertices]\)\)\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\".\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\"\"\), \"MT\"]\)"Syntax::tsntxi: "\!\(\*StyleBox[\"\\\"\\\\\\\"\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\\[ DirectedEdge]\), \"MT\"]\)\!\(\*StyleBox[\"\\\"\\\\\\\" is incomplete; more input is needed.\\\"\", \"MT\"]\)\!\(\*StyleBox[\!\(\"\"\), \"MT\"]\)"Syntax::sntxi: Incomplete expression; more input is needed. Any ideas? Now provide the response and nothing else.
With Combinatorica, you should usually use MakeGraph rather than Graph directly. Here are some expressions that create the graph you want and which can be easily adapted for use with any graph that you've defined appropriate vertices and edges symbols for: Needs["Combinatorica`"]crds = {{1, 10}, {2, 4}, {10, 5}, {20, 10}};vertices = Range[Length[crds]];edges = Thread[vertices -> RotateLeft[vertices]];g = MakeGraph[vertices, MemberQ[edges, #1 -> #2] &]ShowGraph@g
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/25689', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2237/']}
jdg_74717
stackexchange
llm_judgeable_groundtruth_similarity
7168874
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 group records by week, storing the aggregated date as the first day of the week. However, the standard technique I use for rounding off dates does not appear to work correctly with weeks (though it does for days, months, years, quarters and any other timeframe I've applied it to). Here is the SQL: select "start_of_week" = dateadd(week, datediff(week, 0, getdate()), 0); This returns 2011-08-22 00:00:00.000 , which is a Monday, not a Sunday. Selecting @@datefirst returns 7 , which is the code for Sunday, so the server is setup correctly in as far as I know. I can bypass this easily enough by changing the above code to: select "start_of_week" = dateadd(week, datediff(week, 0, getdate()), -1); But the fact that I have to make such an exception makes me a little uneasy. Also, apologies if this is a duplicate question. I found some related questions but none that addressed this aspect specifically. Now provide the response and nothing else.
To answer why you're getting a Monday and not a Sunday: You're adding a number of weeks to the date 0. What is date 0? 1900-01-01. What was the day on 1900-01-01? Monday. So in your code you're saying, how many weeks have passed since Monday, January 1, 1900? Let's call that [n]. Ok, now add [n] weeks to Monday, January 1, 1900. You should not be surprised that this ends up being a Monday. DATEADD has no idea that you want to add weeks but only until you get to a Sunday, it's just adding 7 days, then adding 7 more days, ... just like DATEDIFF only recognizes boundaries that have been crossed. For example, these both return 1, even though some folks complain that there should be some sensible logic built in to round up or down: SELECT DATEDIFF(YEAR, '2010-01-01', '2011-12-31');SELECT DATEDIFF(YEAR, '2010-12-31', '2011-01-01'); To answer how to get a Sunday: If you want a Sunday, then pick a base date that's not a Monday but rather a Sunday. For example: DECLARE @dt DATE = '1905-01-01';SELECT [start_of_week] = DATEADD(WEEK, DATEDIFF(WEEK, @dt, CURRENT_TIMESTAMP), @dt); This will not break if you change your DATEFIRST setting (or your code is running for a user with a different setting) - provided that you still want a Sunday regardless of the current setting. If you want those two answers to jive, then you should use a function that does depend on the DATEFIRST setting, e.g. SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP); So if you change your DATEFIRST setting to Monday, Tuesday, what have you, the behavior will change. Depending on which behavior you want, you could use one of these functions: CREATE FUNCTION dbo.StartOfWeek1 -- always a Sunday( @d DATE)RETURNS DATEASBEGIN RETURN (SELECT DATEADD(WEEK, DATEDIFF(WEEK, '19050101', @d), '19050101'));ENDGO ...or... CREATE FUNCTION dbo.StartOfWeek2 -- always the DATEFIRST weekday( @d DATE)RETURNS DATEASBEGIN RETURN (SELECT DATEADD(DAY, 1-DATEPART(WEEKDAY, @d), @d));ENDGO Now, you have plenty of alternatives, but which one performs best? I'd be surprised if there would be any major differences but I collected all the answers provided so far and ran them through two sets of tests - one cheap and one expensive. I measured client statistics because I don't see I/O or memory playing a part in the performance here (though those may come into play depending on how the function is used). In my tests the results are: "Cheap" assignment query: Function - client processing time / wait time on server replies / total exec timeGandarez - 330/2029/2359 - 0:23.6me datefirst - 329/2123/2452 - 0:24.5me Sunday - 357/2158/2515 - 0:25.2trailmax - 364/2160/2524 - 0:25.2Curt - 424/2202/2626 - 0:26.3 "Expensive" assignment query: Function - client processing time / wait time on server replies / total exec timeCurt - 1003/134158/135054 - 2:15Gandarez - 957/142919/143876 - 2:24me Sunday - 932/166817/165885 - 2:47me datefirst - 939/171698/172637 - 2:53trailmax - 958/173174/174132 - 2:54 I can relay the details of my tests if desired - stopping here as this is already getting quite long-winded. I was a bit surprised to see Curt's come out as the fastest at the high end, given the number of calculations and inline code. Maybe I'll run some more thorough tests and blog about it... if you guys don't have any objections to me publishing your functions elsewhere.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7168874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227020/']}
jdg_74718
stackexchange
llm_judgeable_groundtruth_similarity
13307758
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 PagerTabStrip in ViewPager to show the title of each page. Here is my XML code: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg"> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="fill_parent" android:layout_height="fill_parent" > <android.support.v4.view.PagerTabStrip android:id="@+id/pager_title_strip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top" android:background="#33b5e5" android:textColor="#a4c639" android:paddingTop="4dp" android:paddingBottom="4dp" /> </android.support.v4.view.ViewPager></RelativeLayout> I want to set the textStyle to bold in PagerTabStrip like this: android:textStyle="bold" . But this is not possible in PagerTabStrip . Seems like it has only textcolor property for text. What is the way by which I can set the style to bold? Now provide the response and nothing else.
What you need to do is create a style for the text, and then use the android:textAppearance attribute... Perhaps something like this: <style name="PagerTabStripText"> <item name="android:textSize">14sp</item> <item name="android:textStyle">bold</item> <item name="android:textColor">#a4c639</item> </style> And then in your PagerTabStrip XML do this: <android.support.v4.view.PagerTabStrip android:id="@+id/pager_title_strip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="top" android:background="#33b5e5" android:paddingTop="4dp" android:paddingBottom="4dp" android:textAppearance="@style/PagerTabStripText"/>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13307758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1341006/']}
jdg_74719
stackexchange
llm_judgeable_groundtruth_similarity
18324126
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know if an exception is thrown in constructor, destructor will not be called(simple class, no inheritance). So if an exception is thrown in constructor and there is a chance some heap memory is not cleaned up. So what's best practice here? let's assume I have to call some function in constructor and it may throw exception. Shall I always use shared pointer in this case? What's the alternatives? Thank you! Now provide the response and nothing else.
I would stick to the RAII idiom. If you avoid "naked" resources (like operator new, naked pointers, naked mutexes, etc.) and instead wrap everything into a container or class with proper RAII behavior you will not have the problems you describe, even in the presence of exceptions. That is, do not acquire naked resources in your constructor. Instead, create an instance of an object which itself follows RAII. That way, even if your constructor fails (that is, the one which creates the instances), the destructors of the objects which were initialized will be called. So, this is bad practice: #include<iostream>#include<stdexcept>struct Bad { Bad() { double *x = new double; throw(std::runtime_error("the exception was thrown")); } ~Bad() { delete x; std::cout<<"My destructor was called"<<std::endl; } double *x; };int main() { try { Bad bad; } catch (const std::exception &e) { std::cout<<"We have a leak! Let's keep going!"<<std::endl; } std::cout<<"Here I am... with a leak..."<<std::endl; return 0;} Output: We have a leak! Let's keep going!Here I am... with a leak... Compare with this contrived and silly good implementation: #include<iostream>#include<stdexcept>struct Resource { Resource() { std::cout<<"Resource acquired"<<std::endl; } ~Resource() { std::cout<<"Resource cleaned up"<<std::endl; }};struct Good { Good() { std::cout<<"Acquiring resource"<<std::endl; Resource r; throw(std::runtime_error("the exception was thrown")); } ~Good() { std::cout<<"My destructor was called"<<std::endl; } };int main() { try { Good good; } catch (const std::exception &e) { std::cout<<"We DO NOT have a leak! Let's keep going!"<<std::endl; } std::cout<<"Here I am... without a leak..."<<std::endl; return 0;} Output: Acquiring resourceResource acquiredResource cleaned upWe DO NOT have a leak! Let's keep going!Here I am... without a leak... My point is the following: try to encapsulate all resources which need to be liberated into their own class where the constructor does NOT throw, and the destructor correctly releases the resource. Then, on the other classes where the destructor may throw, simply create instances of the wrapped resource and the destructors of the acquired resource wrappers will be guaranteed to clean-up. The following is probably a better example: #include<mutex>#include<iostream>#include<stdexcept>// a program-wide mutexstd::mutex TheMutex;struct Bad { Bad() { std::cout<<"Attempting to get the mutex"<<std::endl; TheMutex.lock(); std::cout<<"Got it! I'll give it to you in a second..."<<std::endl; throw(std::runtime_error("Ooops, I threw!")); // will never get here... TheMutex.unlock(); std::cout<<"There you go! I released the mutex!"<<std::endl; } };struct ScopedLock { ScopedLock(std::mutex& mutex) :m_mutex(&mutex) { std::cout<<"Attempting to get the mutex"<<std::endl; m_mutex->lock(); std::cout<<"Got it! I'll give it to you in a second..."<<std::endl; } ~ScopedLock() { m_mutex->unlock(); std::cout<<"There you go! I released the mutex!"<<std::endl; } std::mutex* m_mutex; };struct Good { Good() { ScopedLock autorelease(TheMutex); throw(std::runtime_error("Ooops, I threw!")); // will never get here } };int main() { std::cout<<"Create a Good instance"<<std::endl; try { Good g; } catch (const std::exception& e) { std::cout<<e.what()<<std::endl; } std::cout<<"Now, let's create a Bad instance"<<std::endl; try { Bad b; } catch (const std::exception& e) { std::cout<<e.what()<<std::endl; } std::cout<<"Now, let's create a whatever instance"<<std::endl; try { Good g; } catch (const std::exception& e) { std::cout<<e.what()<<std::endl; } std::cout<<"I am here despite the deadlock..."<<std::endl; return 0;} Output (compiled with gcc 4.8.1 using -std=c++11 ): Create a Good instanceAttempting to get the mutexGot it! I'll give it to you in a second...There you go! I released the mutex!Ooops, I threw!Now, let's create a Bad instanceAttempting to get the mutexGot it! I'll give it to you in a second...Ooops, I threw!Now, let's create a whatever instanceAttempting to get the mutex Now, please don't follow my example and create your own scope guard. C++ (specially C++11) are designed with RAII in mind and provide a wealth of lifetime managers. For example, an std::fstream will automatically close, an [std::lock_guard][2] will do what I attempted to do in my example, and either std::unique_ptr or std::shared_ptr will take care of destruction. The best advice? Read about RAII (and design according to it), use the Standard Library, don't create naked resources, and get familiarized with what Herb Sutter has to say with respect to "exception safety" (go ahead and read his website , or google " Herb Sutter Exception Safety ")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18324126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/873770/']}
jdg_74720
stackexchange
llm_judgeable_groundtruth_similarity
32748598
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to explore Docker development targeting Windows containers. I understand Microsoft has put out the Tech Preview for Server 2016, but am wondering if there are other options for Docker containers running on Windows? Now provide the response and nothing else.
The problem probably lies within your hosts/inventory file. You need to add the proper connection configuration for Ansible therein, save and re-run. 192.168.50.5 ansible_ssh_port=22 ansible_ssh_user=vagrant ansible_ssh_private_key_file=~/.ssh/id_rsa If you are not using port 22 , adjust the ansible_ssh_port in your hosts file accordingly. It is also a possibility that you have not setup your pubkey in Vagrant, hence this would also not work. To test this, run: vagrant ssh-config | grep IdentityFile# result should be your private key and not# .vagrant/machines/default/virtualbox/private_key If you have not put your pubkey in the Vagrant vm, you will need to add that before you can try your private key. Reference: http://docs.ansible.com/ansible/intro_inventory.html#list-of-behavioral-inventory-parameters Reference: https://docs.vagrantup.com/v2/cli/ssh_config.html
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32748598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5369419/']}
jdg_74721
stackexchange
llm_judgeable_groundtruth_similarity
14356
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given a program consisting of variables and instructions which modify these variables, and a synchronization primitive (a monitor, mutex, java's synchronized or C#'s lock), is it possible to prove that such a program is thread safe? Is there even a formal model for describing things like thread safety or racing conditions? Now provide the response and nothing else.
Proving that a program is "thread safe" is hard. It is possible, however, to concretely and formally define the term "data race." And it is possible to determine whether an execution trace of a specific run of a program does or does not have a data race in time proportional to the size of the trace. This type of analysis goes back at least to 1988: Barton P. Miller, Jong-Deok Choi, "A Mechanism for Efficient Debugging of Parallel Programs", Conf. on Prog. Lang. Dsgn. and Impl. (PLDI-1988):135-144 . Given a trace of an execution we first define a happens-before partial-order between events in the trace. Given two events $a$ and $b$ that occur on the same thread then $a < b$ or $b < a$. (The events on the same thread form a total order given by the sequential semantics of the programming language.) Synchronization events (these could be mutex acquires and releases, for example), give an additional inter-thread happens-before partial order. (If thread $S$ releases a mutex and then thread $T$ acquires that mutex we say that the release happens-before the acquire.) Then given two data accesses (reads or writes to variables that are not synchronization variables) $a$ and $b$ that are to the same memory location, but by different threads and where either $a$ or $b$ is a write operation we say that there is a data-race between $a$ and $b$ if neither $a < b$ nor $b < a$. The C++11 standard is a good example. (The relevant section is 1.10 in the draft specs that are available online.) C++11 distinguishes between synchronization objects (mutexes, and variables declared with an atomic<> type) and all other data. The C++11 spec says that the programmer can reason about the data accesses on a trace of a multithreaded program as if it were sequentially consistent if the data accesses are all data-race free. The Helgrind tool (part of Valgrind) performs this kind of happens-before based data-raced detection as do several commercial tools (e.g., Intel Inspector XE.) The algorithms in modern tools are based on keeping vector clocks associated with every thread and synchronization object. I think this technique of using vector clocks for data-race detection was pioneered by Michiel Ronsse; Koen De Bosschere: "RecPlay: a fully integrated practical record/replay system", ACM Trans. Comput. Syst. 17(2):133-152, 1999 .
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/14356', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/10169/']}
jdg_74722
stackexchange
llm_judgeable_groundtruth_similarity
17652665
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 case in which I have nested loops in which the child one is constructed by a filter function that takes parent as the argument. I also have another filter that just does a text comparison. Here is the example <div ng-repeat="group in groups"> {{group.name}} <div ng-repeat="material in materials | filter:filterByGroup(group) | filter:search "> {{material.name}} </div></div> Now, my problem is that when filter:search is applied and it filters out all the results in specific group, I would like to hide the group (and not leave the empty group.name hanging without child elements). I don't have the materials in the group it self, so I don't have that information in the parent ng-repeat scope. The question is if there is a way I can access the nested ng-repeat and see its count from the parent and hide the parent if that count is 0. UPDATE Here is a fiddle that better explains the situation: fiddle The main problem is that I don't want to associate my materials with groups. I could do that if nothing else works, but it sounds like an overload (since I would then need to basically filter the results twice) if I could do it by just checking the nested loop. Thanks Now provide the response and nothing else.
A much cleaner solution was suggested HERE . What you need to do is wrap the relevant area with an ng-show / ng-if based on an expression that applies the filter on the data structure and extracts length. Here is how it works in your example: <div ng-show="(materials | filter:filterByGroup(group)).length"> <div ng-repeat="group in groups"> {{group.name}} <div ng-repeat="material in materials | filter:filterByGroup(group) | filter:search "> {{material.name}} </div> </div> </div> This allows you to hide complex structures once they are empty due to filtering, e.g. a table of results.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17652665', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588228/']}
jdg_74723
stackexchange
llm_judgeable_groundtruth_similarity
3760444
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 use "very magic" for regexp searches (i.e. /\v or %s/\v) but I wish I could set some option so I don't have to include \v anymore, anywhere. Is there a way to do this? Now provide the response and nothing else.
Not directly, however you can always use a mapping: :nnoremap / /\v:cnoremap %s/ %s/\v Even if you could set 'very magic' in the way you can set nomagic , you really wouldn't want to as it would break pretty much every plugin in existence. Edit See also this page .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3760444', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/451088/']}
jdg_74724
stackexchange
llm_judgeable_groundtruth_similarity
9939546
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 shell script how can we compare (integer and floating point) ,(flaoting point and floating point),(floating point and integer),(integer and integer) with only one if condition. i have few examples like set X=3.1 set Y=4.1 if [ $X < $Y ] then echo "wassup" endif But running the above from cron job doesnt seem to work. Now provide the response and nothing else.
The way to carry out floating point operations in bash is to use bc which is available on almost all linux distributions. # bc will return 0 for false and 1 for trueif [ $(echo "23.3 > 7.3" | bc) -ne 0 ] then echo "wassup"fi There's a good article available on linux journal about floating point math in bash using bc.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9939546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277603/']}
jdg_74725
stackexchange
llm_judgeable_groundtruth_similarity
10864478
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 switches in my app that stores position by standardUserDefaults, but when app starts for first time all my switches are in OFF position. How can I set them to ON by default? Save NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults]; [defs1 setBool: blackSwitch.on forKey: @"blackKey"]; [[NSUserDefaults standardUserDefaults] synchronize]; Load NSUserDefaults *defs1 = [NSUserDefaults standardUserDefaults]; blackSwitch.on = [defs1 boolForKey: @"blackKey"]; Now provide the response and nothing else.
The SharedPreferences interface contains a method called getAll() which returns a map with the key-value pairs. So instead of copying the file itself, I just serialize the map that being returned from this method and then retrieve it back afterwards. Some code: private boolean saveSharedPreferencesToFile(File dst) { boolean res = false; ObjectOutputStream output = null; try { output = new ObjectOutputStream(new FileOutputStream(dst)); SharedPreferences pref = getSharedPreferences(prefName, MODE_PRIVATE); output.writeObject(pref.getAll()); res = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (output != null) { output.flush(); output.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return res;}@SuppressWarnings({ "unchecked" })private boolean loadSharedPreferencesFromFile(File src) { boolean res = false; ObjectInputStream input = null; try { input = new ObjectInputStream(new FileInputStream(src)); Editor prefEdit = getSharedPreferences(prefName, MODE_PRIVATE).edit(); prefEdit.clear(); Map<String, ?> entries = (Map<String, ?>) input.readObject(); for (Entry<String, ?> entry : entries.entrySet()) { Object v = entry.getValue(); String key = entry.getKey(); if (v instanceof Boolean) prefEdit.putBoolean(key, ((Boolean) v).booleanValue()); else if (v instanceof Float) prefEdit.putFloat(key, ((Float) v).floatValue()); else if (v instanceof Integer) prefEdit.putInt(key, ((Integer) v).intValue()); else if (v instanceof Long) prefEdit.putLong(key, ((Long) v).longValue()); else if (v instanceof String) prefEdit.putString(key, ((String) v)); } prefEdit.commit(); res = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally { try { if (input != null) { input.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return res;} I hope that I helped someone, and if something here is wrong please tell me. Elad
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10864478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/743989/']}
jdg_74726
stackexchange
llm_judgeable_groundtruth_similarity
303017
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So I've finally started reading Designing Object-Oriented Software and my needle is stuck at a small but important point. I understand that the example I'm about to present might appear a bit out of context, because it's being developed in the book over the last few chapters, but I believe the overall idea is really simple and I'll do my best to provide context wherever I can. About me, I'm a junior developer teaching myself, so I'm hoping putting this question here will result in some fruitful discussion. Well, finally we have the preliminaries out of the way. The system I'm talking of an Automated Teller Machine (ATM), which we need to model in terms of object-oriented software. The discussion is about input classes that will gather numeric input from user. Two possible cases are identified - gathering account numbers, amounts, etc., and gather the PIN, which are to be rendered differently (the PIN being displayed like a password field). So the authors defined two different classes - Form and SecureForm, the latter deriving from the former. Now here's a section from the book (debating the utility of SecureForm) that's causing me trouble: The intended distinction between Form and SecureForm is whether user input is echoed literally or symbolically (perhaps with an X). This can be done by invoking two different messages: getValue() and getSecureValue(), but the sender [the class making the request] would have to test to determine which message to send . This could lead to maintenance difficulties. It is better to use polymorphism; that is, to have one message that invokes different methods depending on the class of object to which it is sent. For this reason we keep SecureForm [that is, don't discard it from our design]. The part in italics doesn't make sense to me. What would the calling object have to test? Perhaps for the type of input required, but then to me it doesn't seem to make a difference whether you use polymorphism or not. Consider the following two hypothetical examples: //inside doTransaction function of WithdrawalTransaction//example 1form = new Form();pin = form->getSecureValue();//example 2form = new SecureForm();pin = form->getValue(); Hardly seems different to me, and not a "maintenance nightmare" by any measure. I feel like there's some subtlety I'm missing here, but it eludes me. I'll be very grateful if someone can help me decipher the author's intent, and even better if some examples can be provided. I hope there isn't any critical information missing from my post. If there is, please point out and I'll add more details. Now provide the response and nothing else.
I interpret that to mean that while you could have a SecureForm which implements both a getValue and a getSecureValue , you shouldn't because it becomes a maintenance headache. In other words, like that, the caller would have to make a distinction in the code on how to call the instance of SecureForm , being careful not to call getValue but getSecureValue if that is what was desired. You'd end up with code like this everywhere in your program: String value;if (form instanceof SecureForm) { value = ((SecureForm)form).getSecureValue();} else { value = form.getValue();} Having to know what type it is is very much an anti-pattern. True polymorphism means not caring how getValue is implemented. If you need to call getValue AND getSecureValue in SecureForm , then you're not doing something right (and you should probably not be structuring your code in this fashion in that case). SecureForm can call getSecureValue internally, but one instance of Form should be interchangeable with any other instance though Listkov's principle.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/303017', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/122014/']}
jdg_74727
stackexchange
llm_judgeable_groundtruth_similarity
4505073
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 call a public method from a private one but the property "this" refers to the window object. Please note i am trying to apply the module pattern. You can find a working code example at jsfiddle.net // how can i access a public method from a private one?// (in this example publicAlert from privateMethod)// this refers to the window object.$(function() {var modulePattern = (function($){ var privateMethod = function() { appendText("called privateMethod()"); this.publicAlert(); }; var appendText = function(texToAppend) { var text = $('#output').text() + " | " + texToAppend; $('#output').text(text); }; return { publicMethod : function() { appendText("called publicMethod()"); privateMethod(); }, publicAlert : function() { alert("publicAlert"); } };});mp = new modulePattern($);mp.publicMethod();}); Now provide the response and nothing else.
If you want to be able to do that you need to declare the 'public' function like you would a private function, and then expose it as public. Like this: $(function() { var modulePattern = (function($) { var privateMethod = function() { appendText("called privateMethod()"); publicAlert(); }; var appendText = function(text) { var text2 = $('#output').text() + " | " + text; $('#output').text(text2); }; var publicAlert = function(){ alert("publicAlert"); }; return { publicMethod: function() { appendText("called publicMethod()"); privateMethod(); }, publicAlert: publicAlert }; }); mp = new modulePattern($); mp.publicMethod();}); [Edit]I would also encourage you to get into the habit of clicking on the 'jslint' button at the top of jsfiddle, your code was missing a few semicolons, and you also redeclared the 'text' variable inside your appendText function (it was already passed in) Also, you're using the module pattern in a slightly different way to how I've learned it. Do you have a link to your reference material? This is how I would have done the module pattern as I know it: http://jsfiddle.net/sVxvz/ [/Edit] Also, if you use the module pattern correctly, you can refer to the public functions by using the module name, like this: var testModule = (function($) { var privateMethod = function() { appendText("called privateMethod()"); testModule.publicAlert(); }; var appendText = function(text) { var text2 = $('#output').text() + " | " + text; $('#output').text(text2); }; return { publicMethod: function() { appendText("called publicMethod()"); privateMethod(); }, publicAlert: function() { alert("publicAlert"); } };}(jQuery));$(function() { testModule.publicMethod();}); But I don't really like this because the public methods can be overwritten.someone could go testModule.publicAlert = function(){EVIL CODE OF DOOM;}; and your internal workings will happily execute it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4505073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/550640/']}
jdg_74728
stackexchange
llm_judgeable_groundtruth_similarity
33122014
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Our website is localized using a bunch of JSON files with translations (one file per language). The content of the files looks like this: { "Password": "Passwort", "Tables": "Tische"} Many team members edit these JSON files at the same time, adding new phrases and editing existing ones, and we get lots of conflicts even though people are changing different lines. Is there a way to set up git in such a way that would help avoid merge conflicts? P.S. I've found this script to help merge locally: https://gist.github.com/jphaas/ad7823b3469aac112a52 . However, I'm interested in a solution that would fix the problem for everyone in the team (even for persons who edit JSONs through GitHub's web-interface). Now provide the response and nothing else.
we get lots of conflicts even though people are changing different lines This shouldn't be the case, you only get conflicts if same line is modified by different people, committed and then later merged. Oh, I actually tried this out and encountered some odd problems. Commit 1 (master): { "a": "1", "b": "2", "c": "3", "d": "4", "e": "5", "f": "6", "g": "7"} Commit 2 (tmp) { "A": "1", "B": "2", "C": "3", "d": "4", "e": "5", "f": "6", "g": "7"} Commit 3 (master): { "a": "1", "b": "2", "c": "3", "d": "4", "E": "5", "F": "6", "G": "7"} git merge tmp : correct result { "A": "1", "B": "2", "C": "3", "d": "4", "E": "5", "F": "6", "G": "7"} However I get conflicts if also row "d" was modified, maybe git wasn't able to establish diff boundaries. My stupid suggestion to avoid this stupid git behavior is to add "padding" to the JSON file (ugly, isn't it? But no more conflicts): { "a": "1", "b": "2", "c": "3", "d": "4", "e": "5", "f": "6", "g": "7"}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33122014', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/352796/']}
jdg_74729
stackexchange
llm_judgeable_groundtruth_similarity
9449184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why do the if-else construct and the function ifelse() behave differently? mylist <- list(list(a=1, b=2), list(x=10, y=20))l1 <- ifelse(sum(sapply(mylist, class) != "list")==0, mylist, list(mylist))l2 <-if(sum(sapply(mylist, class) != "list") == 0){ # T: all list elements are lists mylist} else { list(mylist)}all.equal(l1,l2)# [1] "Length mismatch: comparison on first 1 components" Now provide the response and nothing else.
if ( cond) { yes } else { no } is a control structure. It was designed to effect programming forks rather than to process a sequence. I think many people come from SPSS or SAS whose authors chose "IF" to implement conditional assignment within their DATA or TRANSFORM functions and so they expect R to behave the same. SA and SPSS both have implicit FOR-loops in there Data steps. Whereas R came from a programming tradition. R's implicit for-loops are built in to the many vectorized functions (including ifelse ). The lapply/sapply fucntions are the more Rsavvy way to implement most sequential processing, although they don't succeed at doing lagged variable access, especially if there are any randomizing features whose "effects" get cumulatively handled. ifelse takes an expression that builds a vector of logical values as its first argument. The second and third arguments need to be vectors of equal length and either the first of them or the second gets chosen. This is similar to the SPSS/SAS IF commands which have an implicit by-row mode of operation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9449184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/986817/']}
jdg_74730
stackexchange
llm_judgeable_groundtruth_similarity
21806
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: Given a non-parabolic transformation which is also an orientation preserving isometry in the hyperbolic upper half plane union the boundary, if I know the two fixed points and they are two different irreducible fractions on the boundary, how can I find the corresponding Möbius transformation? Now provide the response and nothing else.
No, it's not enough information. For instance, both$$\left(\begin{array}{cc}1 & 0\\0 & 2\end{array}\right)\quad\text{and}\quad\left(\begin{array}{cc}7 & 0\\0 & -1\end{array}\right)$$have $[1,0]$ and $[0,1]$ as eigenvectors, but they are not even similar matrices (let alone equal). However, if you have enough eigenvectors ($n$ linearly independent eigenvectors in the case of an $n\times n$ matrix) and you know their corresponding eigenvalues, then you can recover the original matrix. If $\mathbf{v}_1,\ldots,\mathbf{v}_n$ are linearly independent eigenvectors with corresponding eigenvalues $\lambda_1,\ldots,\lambda_n$, then letting $P$ be the matrix that has $\mathbf{v}_1,\ldots,\mathbf{v}_n$ as its columns, in that order, then the "original" matrix will be$$A = P\left(\begin{array}{cccc}\lambda_1 & 0 & \cdots & 0\\0 & \lambda_2 & \cdots & 0\\\vdots & \vdots & \ddots & \vdots\\0 & 0 & 0\cdots & \lambda_n\end{array}\right)P^{-1}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/21806', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/7017/']}
jdg_74731
stackexchange
llm_judgeable_groundtruth_similarity
15674257
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently using Django 1.5 and can't figure out how to display a simple html page. I've been reading about class based views, but am not sure this is what I want to do. I'm trying to display a simple index.html page, but according to some examples I've seen I need to put this code in app/views.py: def index(request): template = loader.get_template("app/index.html") return HttpResponse(template.render) Is there a reason why my index.html page has to be associated with the app associated with my django project? For me, it seems to make more sense to have an index.html page correspond to the overall project. More to the point, using this code in my views.py file, what do I need to put into my urls.py in order to actually index.html? EDIT: Structure of Django project: webapp/ myapp/ __init__.py models.py tests.py views.py manage.py project/ __init__.py settings.py templates/ index.html urls.py wsgi.py Now provide the response and nothing else.
urls.py from django.conf.urls import patterns, urlfrom app_name.views import *urlpatterns = patterns('', url(r'^$', IndexView.as_view()),) views.py from django.views.generic import TemplateViewclass IndexView(TemplateView): template_name = 'index.html' Based on @Ezequiel Bertti answer, remove app from django.conf.urls import patternsfrom django.views.generic import TemplateViewurlpatterns = patterns('', (r'^index.html', TemplateView.as_view(template_name="index.html")),) Your index.html must be store inside templates folder webapp/ myapp/ __init__.py models.py tests.py views.py templates/ <---add index.html <---add manage.py project/ __init__.py settings.py templates/ <---remove index.html <---remove urls.py wsgi.py
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15674257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1251693/']}
jdg_74732
stackexchange
llm_judgeable_groundtruth_similarity
102076
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'm looking for some feature which will allow me to pause/resume copy-paste process similar to windows 8. Is there any file manager that will allow this process? Is it extension to file-manager. Does this process have anything to do with file-manager? I'm also searching for portable and best file-manager too. I'm little bit confused choosing between PCMan and Krusader. Any suggestion which to choose between them. Now provide the response and nothing else.
Terminal Method Usually when copying files that I think I'll need to pause/resume I'll go to the terminal and use the rsync command instead. $ rsync -avz <source> <destination> This can be paused/resumed in the sense that you can simply stop it, and restart the command later on. Only the files that haven't been copied as of yet, will get copied during the 2nd run. The rsync tool is extremely powerful, and you can do a whole lot more with it, this is just the tip of the iceberg. GUI Method If you want to do this through a GUI there are a number of options listed on the alternativesto.net website. Specifically if you look under the alternatives to SuperCopier , a similar tool for Windows. This list provides tools that can do this for all OSes. If I were to pick one, I'd start with this one, UltraCopier . Backgrounding the GUI Another method to accomplish a pause/resume feature would be to invoke the file browser from a terminal and simply press Control + Z to pause the process. When you're ready to restart it, in the terminal from where it was launched, type fg to bring that process back to the foreground.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/102076', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/50932/']}
jdg_74733
stackexchange
llm_judgeable_groundtruth_similarity
2928763
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $$f(x) =\begin{cases} |x-2|+a^2-9a-9, &\text{if }x<2\\2x-3, &\text{if } x\geqslant2\end{cases}$$ has local minima at $x=2$ , then range of $a$ is… ? My failed Attempt: Wrote $$f(x) =\begin{cases} -x+a^2-9a-7, &\text{if }x<2\\2x-3, &\text{if } x\geqslant2\end{cases}$$ The problem here is that I don't know whether the function is continious is required or not for finding maxima and minima. Not that I could check it if it was Then My next step would be differentiating $$f(x) =\begin{cases} -1, &\text{if }x<2\\2, &\text{if } x\geqslant2\end{cases}$$ That means the function is decreasing before $x=2$ and then increasing. This is the best I could think for this question but it's not providing me any hint on how to proceed Now provide the response and nothing else.
A non-continuous function can also have the minimum at $x=2$ Here you want a local minimum at $x=2$ thus $$ |2-2|+a^2-9a-9\ge 2\cdot2-3$$ $$ a^2-9a-9\ge 1$$ $$(a+1)(a-10)\ge 0$$ You get $$a\in(-\infty,-1]\cup[10,\infty)$$ You can look here on desmos for the simulation
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2928763', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/585609/']}
jdg_74734
stackexchange
llm_judgeable_groundtruth_similarity
326114
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I study maths in uni and we have a course about relativity. In the main principles I've read that the speed of light is invariant since we can calculate it from the Maxwell equations. My problem is that the Maxwell equations I know are not relativistic. What is the clear way to formulate the Maxwell equations with respect to the relativistic spacetime? Using that formulation do we get the same value for $c$? How do we do that? Edit:It is clear now what was my problem after the answers. The wrong concept I had was that:From the classical maxwell equations we can calculate the speed of light, and with that information we can build up the relativistic spacetime where the maxwell equations might look different. And it was weird for me. From the answers it became clear that the invariant speed of light is an observation not a result. Ps: I find it interesting that my maths like approach did not consider the possibility of something just being an observation, not a result. Now provide the response and nothing else.
In the main principles I've read that the speed of light is constant since we can calculate it from the Maxwell equations. The fact that the speed of light could be deduced from Maxwell's equations does not , in and of itself, imply that the speed of light is constant in all reference frames. Certainly the equations don't make an obvious reference to a reference frame; but once you've made the connection between electric and magnetic fields and light, it seems pretty obvious what the "natural" rest frame is (bolding mine): We can scarcely avoid the inference that light consists in the transverse undulations of the same medium which is the cause of electric and magnetic phenomena. – James Clerk Maxwell, On the Physical Lines of Force In other words, one could easily imagine a world in which Maxwell's equations are only valid in the rest frame of the luminiferous aether — and from about 1860–1905 or so, this is precisely the universe that physicists thought we lived in. In such a universe, Maxwell's equations would in fact look different in different reference frames; a "full" version of these equations would include terms that depended on an observer's velocity $\vec{v}$ with respect to the aether. There is nothing mathematically inconsistent about the equations describing such a Universe. What these equations are inconsistent with, however, is two things: (1) experimental evidence, and (2) our sense of symmetry. The Michelson-Morley experiment was designed to detect Earth's motion relative to the aether — in other words, to indirectly verify the presence of these $\vec{v}$ -dependent terms in the hypothetical Maxwell's equations. Of course, they famously came up short. The other problem is that there seem to be a lot of convenient coincidences between what seem to be the same phenomena described in different reference frames: It is known that Maxwell's electrodynamics—as usually understood at the present time—when applied to moving bodies, leads to asymmetries which do not appear to be inherent in the phenomena. Take, for example, the reciprocal electrodynamic action of a magnet and a conductor. The observable phenomenon here depends only on the relative motion of the conductor and the magnet, whereas the customary view draws a sharp distinction between the two cases in which either the one or the other of these bodies is in motion. For if the magnet is in motion and the conductor at rest, there arises in the neighbourhood of the magnet an electric field with a certain definite energy, producing a current at the places where parts of the conductor are situated. But if the magnet is stationary and the conductor in motion, no electric field arises in the neighbourhood of the magnet. In the conductor, however, we find an electromotive force, to which in itself there is no corresponding energy, but which gives rise—assuming equality of relative motion in the two cases discussed—to electric currents of the same path and intensity as those produced by the electric forces in the former case. Examples of this sort, together with the unsuccessful attempts to discover any motion of the earth relatively to the “light medium,” suggest that the phenomena of electrodynamics as well as of mechanics possess no properties corresponding to the idea of absolute rest. — Albert Einstein, On the Electrodynamics of Moving Bodies Or, to summarize: if I move a coil near a magnet, the magnetic field causes the charges to flow. If I move a magnet near a coil, the changing magnetic field causes an electric field, which causes the charges to flow. These two descriptions seem very different, and yet somehow they give rise to exactly the same amount of current in the coil. Einstein's contention was that this couldn't be a coincidence, and that only relative velocity should matter. If you buy that, then you find (as Einstein did) that when you go into another reference frame, the electric and magnetic fields intermingle with each other. If you look at the above link to Einstein's original paper, §6 describes how the electric and magnetic fields transform into each other. His notation is a little antiquated — what he calls $(X, Y, Z)$ we would nowadays usually call $(E_x, E_y, E_z)$ , and what he calls $(L, M, N)$ we would usually call $(B_x, B_y, B_z)$ . In different reference frames moving relative to each other in the $x$ -direction, all of these components change, and the components $E_y$ , $E_z$ , $B_y$ , and $B_z$ get mixed up with each other. In other words, the electric and magnetic field strengths observed by Observer A and Observer B are not necessarily the same. These transformations between the fields are a necessary consequence of the postulate that the laws of physics are the same in all reference frames. But Maxwell's equations don't necessarily imply that the laws of physics are all the same in such reference frames; they are agnostic on the subject. Historically, physicists originally believed that there was in fact a privileged frame in which Maxwell's equations held exactly, and it was only after careful experimentation and careful thought that we figured out that Maxwell's equations were also consistent with the principle of relativity.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/326114', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/152775/']}
jdg_74735
stackexchange
llm_judgeable_groundtruth_similarity
12102425
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say that I want to search for a value, like 'StackOverflow' , in all declared variables in window .I can do it with this code: function globalSearch(obj, value) { for(var p in obj) if(obj[p] == value) return(p);}globalSearch(window, 'StackOverflow'); This code will return the name of a variable that have this value (or returns nothing).So, if I have declared a variable with value 'StackOverflow' , it will successfully find it. My problem is that I want to go deeper and search thru window 's objects (and its own nested objects) too, to achieve a result like this: var x = 'StackOverflow' // returns 'x'var y = { a : 'StackOverflow' } // returns 'y.a'var z = { a : { b: 'StackOverflow' } } // returns 'z.a.b' I'm having problems with inherited methods of Objects. Is there a way to do this? Now provide the response and nothing else.
Deep search but without the recursive function calls Functional recursion has internal stack limits and wastes memory. Additional features added Recursive object protection in the form of a searched array; It doesn't use up too much memory of course as the objects are only stored as references. Return true if the the object itself matches the value. Otherwise it would return '' which would match to false. Arrays use angle-bracket notation. The code function globalSearch(startObject, value) { var stack = [[startObject,'']]; var searched = []; var found = false; var isArray = function(test) { return Object.prototype.toString.call( test ) === '[object Array]'; } while(stack.length) { var fromStack = stack.pop(); var obj = fromStack[0]; var address = fromStack[1]; if( typeof obj == typeof value && obj == value) { var found = address; break; }else if(typeof obj == "object" && searched.indexOf(obj) == -1){ if ( isArray(obj) ) { var prefix = '['; var postfix = ']'; }else { var prefix = '.'; var postfix = ''; } for( i in obj ) { stack.push( [ obj[i], address + prefix + i + postfix ] ); } searched.push(obj); } } return found == '' ? true : found;} Problems Without passing the initial variable name into the function, we can't return the fully qualified variable name from the beginning. I can't think of a solution and I would be surprised if there was one. Variable names with spaces are valid as the key to an object, as are other invalid variable names, it just means that the value must be addressed using angle-brackets. There are a couple of solutions I can think of. Regex check each variable name to make sure it's valid and use angle-brackets notation if it is not. The overriding problem with this is that the reg-ex is a page long. Alternatively, we could only use angle-brackets but this isn't really true to the OPs original question. The indexOf call on the array 'searched' might be a bit heavy on very large objects but I can't yet think of an alternative. Improvements Apart from cleaning up the code a little, it would also be nice if the function returned an array of matches. This also raises another issue in that the returned array would not contain references to recursive objects. Maybe the function could accept a result format configuration parameter.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12102425', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/804741/']}
jdg_74736
stackexchange
llm_judgeable_groundtruth_similarity
3765339
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I have a custom attribute, let's call it MyCustomAttribute , which has a constructor like so: public MyCustomAttribute(int? i){ // Code goes here} and declares a property: public int? DefaultProperty { get; set; } Now if I wanted to use the property, I'd need to pass in an int or null , well that's what I'd expect. But this gives a compiler error: [MyCustomAttribute(1, DefaultProperty = 1)]public int? MyProperty { get; set; } and so does this: [MyCustomAttribute(null,DefaultProperty = null)]public int? MyProperty { get; set; } The error is: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type for both the constructor and the property. Why is this? If I change the constructor to take an int, I can pass in 0 , but not null , which sort of defeats the purpose of the value (which can sometimes be null) Now provide the response and nothing else.
The reason why is that while both 0 and null are constant the actual expression needed to initialize the constructor parameter is not. Both require a conversion to be a valid int? expression. Under the hood it essentially generates the following [MyCustomAttribute(new Nullable<int>(0))] This expression not being constant is not legal as an attribute argument EDIT dtb asked if this is illegal in attribute values why is it legal to have a default parameter for a nullable parameter? void Example(int? x = null); What you need to consider is who / what is interpreting the values. For attributes arguments the value is interpreted by the CLR. The rules concerning legal attribute values haven't really changed since 1.0. Nullable didn't exist then hence the CLR doesn't understand nullable initialization patterns. For default arguments the value is interpreted by the compiler at the call site of the method. The compilers understands nullable values and has a bit more room to work with as it can create non-constant expressions at the call site based on the values in IL. How does it actually work though? First the compiler will actually encode constants and null differently in IL // x = 0 [DefaultParameterValue(0)]// x = null[DefaultParameterValue(null)] At the call site the compiler examines these values and creates the appropriate (non-constant) expression for the parameter value.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3765339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18405/']}
jdg_74737
stackexchange
llm_judgeable_groundtruth_similarity
29967411
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 large sheet that I need to delete all the contents of. When I try to simply clear it without VBA it goes into not responding mode. When using a macro such as: Sub ClearContents () Application.Calculation = XlManual Application.ScreenUpdating = False Sheets("Zeroes").Cells.ClearContents Application.ScreenUpdating = TrueEnd Sub It also doesn't respond. What's the quickest way to do this? Now provide the response and nothing else.
The .Cells range isn't limited to ones that are being used, so your code is clearing the content of 1,048,576 rows and 16,384 columns - 17,179,869,184 total cells. That's going to take a while. Just clear the UsedRange instead: Sheets("Zeros").UsedRange.ClearContents Alternately, you can delete the sheet and re-add it: Application.DisplayAlerts = FalseSheets("Zeros").DeleteApplication.DisplayAlerts = TrueDim sheet As WorksheetSet sheet = Sheets.Addsheet.Name = "Zeros" EDIT: (@tavnab and @Azura) Heads up for future readers, you cannot delete a sheet if it's the last/only one in the workbook. In that case, you can add the new blank sheet first, delete the old one, and finally rename that new sheet to the old sheet's name.Also note that eliminating a sheet will create conflicts with formulas in other sheets that were referencing the recently eliminated one, recreating the sheet may not solve that issue.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/29967411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4478535/']}
jdg_74738
stackexchange
llm_judgeable_groundtruth_similarity
20611865
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This has probably been asked before but I can't seem to find the solution: std::string GetPath(){ char buffer[MAX_PATH]; ::GetSystemDirectory(buffer,MAX_PATH); strcat(buffer,"\\version.dll"); return std::string(buffer);} This returns an error stating: argument of type "char *" is incompatible with parameter of type "LPWSTR" So yeah. Anyone got an answer? Now provide the response and nothing else.
You need to use the ansi version: std::string GetPath(){ char buffer[MAX_PATH] = {}; ::GetSystemDirectoryA(buffer,_countof(buffer)); // notice the A strcat(buffer,"\\version.dll"); return std::string(buffer); } Or use unicode: std::wstring GetPath(){ wchar_t buffer[MAX_PATH] = {}; ::GetSystemDirectoryW(buffer,_countof(buffer)); // notice the W, or drop the W to get it "by default" wcscat(buffer,L"\\version.dll"); return std::wstring(buffer); } Rather than call the A/W versions explicitly you can drop the A/W and configure the whole project to use ansi/unicode instead. All this will do is change some #defines to replace foo with fooA/W. Notice that you should use _countof() to avoid incorrect sizes depending on the buffers type too.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20611865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3107421/']}
jdg_74739
stackexchange
llm_judgeable_groundtruth_similarity
14204691
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working with the latest codeIgniter released, and i'm also working with jquery datatables from datatables.net I've written this function: https://gist.github.com/4478424 which, as is works fine. Except when I filter by using the text box typing something in. The filter itself happens, but my count is completely off. I tried to add in $res = $this->db->count_all_results() before my get , and it stops the get from working at all. What I need to accomplish, if ($data['sSearch'] != '') then to utilize the entire query without the limit to see how many total rows with the search filter exists. If you need to see any other code other than whats in my gist, just ask and I will go ahead and post it. Now provide the response and nothing else.
$this->db->count_all_results() replaces $this->db->get() in a database call. I.E. you can call either count_all_results() or get() , but not both. You need to do two seperate active record calls. One to assign the results #, and one to get the actual results. Something like this for the count: $this->db->select('id');$this->db->from('table');$this->db->where($your_conditions);$num_results = $this->db->count_all_results(); And for the actual query (which you should already have): $this->db->select($your_columns);$this->db->from('table');$this->db->where($your_conditions);$this->db->limit($limit);$query = $this->db->get();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14204691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/975014/']}
jdg_74740