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
67889309
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 created new project - client - on Angular 11.Then updated ng version to 12 Angular.Then installed Universal:ng add @nguniversal/express-engine Then I'm trying to run my Universal Angular, but it throws error: npm run dev:ssr [email protected] dev:ssrng run client:serve-ssr This is a simple server for use in testing or debugging Angular applications locally.It hasn't been reviewed for security issues. DON'T USE IT FOR PRODUCTION! Configuration 'development' is not set in the workspace.npm ERR! code 1npm ERR! path E:\PRACTICE\MYPETPROJECTS\tanechka\clientnpm ERR! command failednpm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c ng run client:serve-ssr npm ERR! A complete log of this run can be found in:npm ERR! C:\Users\1\AppData\Local\npm-cache_logs\2021-06-08T14_35_07_681Z-debug.log angular.json { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "client": { "projectType": "application", "schematics": { "@schematics/angular:component": { "style": "scss" } }, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/client/browser", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.scss" ], "scripts": [], "vendorChunk": true, "extractLicenses": false, "buildOptimizer": false, "sourceMap": true, "optimization": false, "namedChunks": true }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "namedChunks": false, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "6kb", "maximumError": "10kb" } ] } }, "defaultConfiguration": "" }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "client:build" }, "configurations": { "production": { "browserTarget": "client:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "client: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", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "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": "client:serve" }, "configurations": { "production": { "devServerTarget": "client:serve:production" } } }, "server": { "builder": "@angular-devkit/build-angular:server", "options": { "outputPath": "dist/client/server", "main": "server.ts", "tsConfig": "tsconfig.server.json", "optimization": false, "sourceMap": true, "extractLicenses": false }, "configurations": { "production": { "outputHashing": "media", "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "sourceMap": false, "extractLicenses": true } }, "defaultConfiguration": "production" }, "serve-ssr": { "builder": "@nguniversal/builders:ssr-dev-server", "configurations": { "development": { "browserTarget": "client:build:development", "serverTarget": "client:server:development" }, "production": { "browserTarget": "client:build:production", "serverTarget": "client:server:production" } }, "defaultConfiguration": "development" }, "prerender": { "builder": "@nguniversal/builders:prerender", "options": { "routes": [ "/" ] }, "configurations": { "production": { "browserTarget": "client:build:production", "serverTarget": "client:server:production" }, "development": { "browserTarget": "client:build:development", "serverTarget": "client:server:development" } }, "defaultConfiguration": "production" } } } }, "defaultProject": "client"} package.json { "name": "client", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e", "dev:ssr": "ng run client:serve-ssr", "serve:ssr": "node dist/client/server/main.js", "build:ssr": "ng build && ng run client:server", "prerender": "ng run client:prerender" }, "private": true, "dependencies": { "@angular/animations": "~12.0.3", "@angular/common": "~12.0.3", "@angular/compiler": "~12.0.3", "@angular/core": "~12.0.3", "@angular/forms": "~12.0.3", "@angular/platform-browser": "~12.0.3", "@angular/platform-browser-dynamic": "~12.0.3", "@angular/platform-server": "~12.0.3", "@angular/router": "~12.0.3", "@nguniversal/express-engine": "^12.0.1", "express": "^4.15.2", "rxjs": "~6.6.0", "tslib": "^2.0.0", "zone.js": "~0.11.4" }, "devDependencies": { "@angular-devkit/build-angular": "~12.0.3", "@angular/cli": "~12.0.3", "@angular/compiler-cli": "~12.0.3", "@nguniversal/builders": "^12.0.1", "@types/express": "^4.17.0", "@types/jasmine": "~3.6.0", "@types/node": "^12.11.1", "codelyzer": "^6.0.0", "jasmine-core": "~3.7.1", "jasmine-spec-reporter": "~5.0.0", "karma": "~6.3.3", "karma-chrome-launcher": "~3.1.0", "karma-coverage": "~2.0.3", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "^1.6.0", "protractor": "~7.0.0", "ts-node": "~8.3.0", "tslint": "~6.1.0", "typescript": "~4.2.4" }} I tried to add 'development' to 'configurations' of serve: "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "client:build" }, "configurations": { "production": { "browserTarget": "client:build:production" }, "development": { "browserTarget": "client:build:production" } } }, But it didn't work. Now provide the response and nothing else.
FIXED Angular 12 Universal running serve:ssr but showing Configuration 'development' is not set in the workspace My angular project was updated from 11 to 12. I need to add angular universal for some reason and got same issue. Trying to add development in architect.configurations where contents copied from production, but not working. Finally, I removed :development in serve-ssr.configurations.development and it works well. In angular.json snippet "serve-ssr": { "builder": "@nguniversal/builders:ssr-dev-server", "configurations": { "development": { "browserTarget": "<YOUR_PROJECT_NAME>:build", <--- remove `:development` here "serverTarget": "<YOUR_PROJECT_NAME>:server" <--- remove `:development` here }, "production": { "browserTarget": "<YOUR_PROJECT_NAME>:production", "serverTarget": "<YOUR_PROJECT_NAME>:server:production" } }, "defaultConfiguration": "development" },
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67889309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13488354/']}
jdg_77341
stackexchange
llm_judgeable_groundtruth_similarity
151118
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm about to make a new Linux install, which will be primarily used for programming. I've seen benchmarks showing speed improvement of 64-bit version, however, I have hard time of telling how much these benchmarks translate to improvement in every day usage. And of course there are other aspects to consider. Usage I have in mind: mainly programming Python, with occasional C, C++ and Java; IDEs, which are using Java platforms (Eclipse and IntelliJ); on very rare occasions having to compile for 32-bit platform; not planning to have more than 64GB of RAM anytime soon (and I don't mind using PAE kernels ); machine in question has 4GB RAM and Athlon II X2; What are pros and cons of choosing either i386 or x86_64 distro? Now provide the response and nothing else.
In the mainstream Linux-based distro's, the amd64 version is completely on par with the x86 one, so as far as software availability goes, you have nothing to fear either way (a few obscure platform-specific hacks aside). Also, it is possible, albeit with some severe hacking, to run 32-bit code on a 64-bit kernel, so if you absolutely have to, there are probably ways to make that happen. And if all else fails, you can always install a 32-bit virtual machine to compile for that particular architecture. CPU-performance-wise, there isn't much difference either way: some applications benefit from 64-bit operations (typically, these are applications that have to deal with large integers and such); others don't get any benefit and might even run a tiny bit faster on a 32-bit kernel, especially if they need to handle a lot of natively-sized integers or pointer (which take up twice as much space on a 64-bit platform). However, if you want to use more than 4 GB of RAM, 32-bit kernels do carry a real performance penalty, because you have to use PAE to make it happen. As a general rule of thumb, these days I'd say go with 64-bits, unless you have strong reasons not to, most notably: you are using 32-bit libraries that you cannot recompile to a 64-bit platform (e.g. because you don't have the sources) you need to use a package from your distro that isn't included in the 64-bit distribution and cannot be installed from other trusted sources you are short on physical RAM (many programs use significantly less RAM on 32-bit systems, and 'short on RAM' invariably means 'less than 4 GB') you are coding for 32-bit production systems (you want to eliminate as many differences as possible; for example, PHP's ip2long function has a nasty gotcha that only shows on 32-bit systems)
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/151118', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/14510/']}
jdg_77342
stackexchange
llm_judgeable_groundtruth_similarity
1314013
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: From Munkres'(pg 160): Example 1:If $\mathbb{Q}$ is the subspace of $\mathbb{R}$ consisting of the rational numbers, then each component of $\mathbb{Q}$ is a single point. How do I see that each component of the rational numbers is a singleton? Now provide the response and nothing else.
It suffices to prove that any two (distinct) rational numbers $q_1<q_2$ are in the different components. You can take an irrational number $q_1<r<q_2$, and then set $A = \{q \in \mathbb{Q} : q < r\}$ and $B = \{q \in \mathbb{Q} : q > r\}$. Then $(A,B)$ is a separation of $\mathbb{Q}$, and $q_1 \in A$, $q_2 \in B$. Thus $q_1$ and $q_2$ are in the different components.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1314013', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/217966/']}
jdg_77343
stackexchange
llm_judgeable_groundtruth_similarity
51130622
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 working on a test app for android and need to parse the JSON test data. The JSON looks like this: {"id":1,"name":"Test Test","questions":[{"id":1,"test":1,"text":"Kannst du diese Frage beantworten?","answers":[{"id":1,"question":1,"text":"Ja, das ist richtig.","correct":1},{"id":2,"question":1,"text":"Diese Antwort ist falsch.","correct":0},{"id":3,"question":1,"text":"Diese hier ist ebenfalls nicht so ganz korrekt.","correct":0}]},{"id":2,"test":1,"text":"Diese Frage hier ist nicht korrekt.","answers":[{"id":4,"question":2,"text":"Ich glaube dir nicht, das hier ist eh richtig.","correct":1},{"id":5,"question":2,"text":"Diese Antwort ist falsch.","correct":0},{"id":6,"question":2,"text":"Diese hier ist ebenfalls nicht so ganz korrekt.","correct":0}]}]} What I need is to extract the questions and its' child data. What I tried is: JSONObject jObject = new JSONObject(result);String test = jObject.getJSONObject("id").getJSONArray("questions").toString(); And String myString = jObject .getJSONObject("questions").getJSONObject("answers").getString("text"); Now provide the response and nothing else.
Just try this code after deleting your existing migration for updating name, php artisan make:migration rename_author_id_in_posts_table --table=posts It will create one migration and then replace up() and down() functions with this in that created migration, public function up(){ Schema::table('posts', function (Blueprint $table) { $table->renameColumn('author_ID', 'user_id'); });} And down() function with this, public function down(){ Schema::table('posts', function (Blueprint $table) { $table->renameColumn('user_id', 'author_ID'); });} For more information about migration, you can go through this link Laravel Migrations . I hope this will work for you. If any doubts please comment. PROBLEM WITH YOUR MIGRATION: You are using Schema::create() method for change in table, As you have already created migration for posts table,You don't need to do Schema::create() just use Schema::table() method to update and change in any fields. Schema::create('posts', function (Blueprint $table) { $table->renameColumn('author_ID', 'user_id'); });
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51130622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8396297/']}
jdg_77344
stackexchange
llm_judgeable_groundtruth_similarity
32878795
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: what I'm trying to accomplish is to run commands inside of a Docker container that has already been created on a Digital Ocean Ubuntu/Docker Droplet using Ansible. Can't seem to find anything on this, or I'm majorly missing something. This is my Ansible task in my play book. I'm very new to Ansible so any advice or wisdom would be greatly appreciated. - name: Test Deploy hosts: [my-cluster-of-servers]tasks: - name: Go Into Docker Container And Run Multiple Commands docker: name: [container-name] image: [image-ive-created-container-with-on-server] state: present command: docker exec -it [container-name] bash Now provide the response and nothing else.
After discussion with some very helpful developers on the ansible github project , a better way to do this is like so: - name: add container to inventory add_host: name: [container-name] ansible_connection: docker changed_when: false- name: run command in container delegate_to: [container-name] raw: bash If you have python installed in your image, you can use the command module or any other module instead of raw. If you want to do this on a remote docker host, add: ansible_docker_extra_args: "-H=tcp://[docker-host]:[api port]" to the add_host block. See the Ansible documentation for a more complete example.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32878795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3996221/']}
jdg_77345
stackexchange
llm_judgeable_groundtruth_similarity
19923091
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 going through all possible sample on internet to solve this. Still it is an headache. I just want to avoid the 'public' in www.mylaravelsite.com/public/ and make it like www.mylaravelsite.com for the root directory. Now I do not want to avoid the security concern,So I learned .htaccess would be the best way. Any solution friends ? & advance thanks for interacting ! Now provide the response and nothing else.
Let's assume you have this folder structure in your server .cpanel/public_html/public_ftp/.. And the laravel folder structure is app/bootstrap/public/vendor/composer.jsonartisan.. You can create a folder name mylaravelsite on your server inline with public_html and public_ftp folder, and copy to it the whole laravel application except the public folder because you will paste all of it contents on the public_html , so you have now: .cpanel/public_html/public_html/packagespublic_html/vendorpublic_html/index.phppublic_html/.htaccess...public_ftp/mylaravelsite/mylaravelsite/appmylaravelsite/bootstrap... On your public_html/index.php change the following line: require __DIR__.'/../bootstrap/autoload.php';$app = require_once __DIR__.'/../bootstrap/start.php'; to require __DIR__.'/../mylaravelsite/bootstrap/autoload.php';$app = require_once __DIR__.'/../mylaravelsite/bootstrap/start.php'; and also don't forget to change /mylaravelsite/bootstrap/paths.php public path, you might use it. 'public' => __DIR__.'/../public', to 'public' => __DIR__.'/../../public_html', Your site should be running.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19923091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2174878/']}
jdg_77346
stackexchange
llm_judgeable_groundtruth_similarity
67560587
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 integrate authentication with next-auth library in an Application. I have been following the official tutorial given here https://github.com/nextauthjs/next-auth-example/ . The problem with the given example is that I need to check if there is a session on every page that requires authentication like this. import { useState, useEffect } from 'react'; import { useSession } from 'next-auth/client' export default function Page () { const [ session, loading ] = useSession() // Fetch content from protected route useEffect(()=>{ const fetchData = async () => { const res = await fetch('/api/examples/protected') const json = await res.json() } fetchData() },[session]) // When rendering client side don't display anything until loading is complete if (typeof window !== 'undefined' && loading) return null // If no session exists, display access denied message if (!session) { return <Layout><AccessDenied/></Layout> } // If session exists, display content return ( <Layout> <h1>Protected Page</h1> <p><strong>{content || "\u00a0"}</strong></p> </Layout> ) } or like this for Server-side checking import { useSession, getSession } from 'next-auth/client' import Layout from '../components/layout' export default function Page () { // As this page uses Server Side Rendering, the `session` will be already // populated on render without needing to go through a loading stage. // This is possible because of the shared context configured in `_app.js` that // is used by `useSession()`. const [ session, loading ] = useSession() return ( <Layout> <h1>Server Side Rendering</h1> <p> This page uses the universal <strong>getSession()</strong> method in <strong>getServerSideProps()</strong>. </p> <p> Using <strong>getSession()</strong> in <strong>getServerSideProps()</strong> is the recommended approach if you need to support Server Side Rendering with authentication. </p> <p> The advantage of Server Side Rendering is this page does not require client side JavaScript. </p> <p> The disadvantage of Server Side Rendering is that this page is slower to render. </p> </Layout> ) } // Export the `session` prop to use sessions with Server Side Rendering export async function getServerSideProps(context) { return { props: { session: await getSession(context) } } } This is a lot of headaches as we need to manually right on every page that requires auth, Is there any way to globally check if the given route is a protected one and redirect if not logged in instead of writing this on every page? Now provide the response and nothing else.
Yes you need to check on every page and your logic is okay ( showing spinner untll the auth state is available) however,you can lift authentication state up, so you don't repeat the auth code for every page, _app component is a perfect place for this, since it naturally wraps all other components (pages). <AuthProvider> {/* if requireAuth property is present - protect the page */} {Component.requireAuth ? ( <AuthGuard> <Component {...pageProps} /> </AuthGuard> ) : ( // public page <Component {...pageProps} /> )} </AuthProvider> AuthProvider component wraps logic for setting up third party providers (Firebase, AWS Cognito, Next-Auth) AuthGuard is the component where you put your auth check logic . You will notice that AuthGuard is wrapping the Component (which is the actual page in Next.js framework). So AuthGuard will show the loading indicator while querying the auth provider, and if auth is true it will show the Component if auth is false, it could show a login popup or redirect to the login page. About Component.requireAuth this is a handy property that is set on every page to mark the Component as requiring auth, if that prop is false AuthGuard is never rendered. I've written about this pattern in more detail: Protecting static pages in Next.js application And I've also made an example demo app (source)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/67560587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6907768/']}
jdg_77347
stackexchange
llm_judgeable_groundtruth_similarity
56504
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: V10 introduces an operator form for several functions perhaps primarily due to their role in queries as part of introducing data science functionality. At first pass it seems a lot of effort to add some syntactic sugar (given an equivalent pure functional form only ever requires an extra couple of symbols - ( # , & ) )? For example, Map[f,#]&[{a,b,c}] can now be shortened to Map[f][{a,b,c}] , - slightly more compact but then again perhaps not such an improvement on an existing operator (short) form - f/@{a,b,c} . So, are there some compelling examples that illustrate the rationale behind the introduction of this new construct? Conclusion To summarize the points made in all the informative responses: In addition to avoiding the symbols ( (#&) ) operator forms can eliminate the need for Function in nested definitions. The gains of using operator form are cumulative as they are chained together either in postfix, prefix or for some, infix form. While not necessarily restricted to this area the motivation and applicability of operator forms stems from the need to provide functions as arguments in Dataset . Many operator forms are built-in but when not they can be readily defined. The pure and operator forms are not always semantically equivalent (natively or user-defined) with, for example, Query using their different patterns to interpret differently. They can potentially be used to improve efficiency not just via code's reduced leaf-count but in reduced algorithmic complexity. They are potentially a rich source of language improvement from mimicking natural language patterns, code refactoring, debugging or automated and non-deterministic parsing via corpus-derived context. Update V 10.3.1 ( 01/01/16 ) A new answer gives an overview of the idioms used for system operator forms and how these can be intermingled with user-defined operator forms. Now provide the response and nothing else.
I would have liked to have more experience with the operator forms before this question was asked as I am short on examples, and I'm sure my opinion will evolve over time. Nevertheless I think I have enough familiarity with similar syntax to provide some useful comments. Taliesin Beynon provided some background for this functionality in Chat: Operator forms have turned out to be a huge win for writing readable code. Unfortunately I can't remember whether it was Stephen or me who first suggested them, so I don't know who should get the credit :). Either way it was a major (and risky) decision, and I had to argue with a lot of people in the company who remained skeptical, so credit goes to Stephen for just pushing it through. But they were motivated by the needs of Dataset's query language, which is an interesting historical detail I think. We see that m_goldberg is correct in seeing operator forms as being important to Dataset . Taliesin also claims that operator forms are "a huge win" for readability. I agree with this and have been a proponent of SubValues definitions , which is basically what "operator forms" are. I also like Currying (1) , (2) though I haven't embraced it to the same degree. You comment that operator forms only save a few characters over anonymous functions and this is usually true, but these characters, and more importantly the semantics behind them, are nevertheless significant. Being able to treat functions with partially specified parameters as functions (Currying) frees us from the cruft or baggage of a lot of Slot and Function use. Surely these are easier to read and write: fn[1] /@ list (* fn[1, #] & /@ list *)SortBy[list, Extract @ 2] (* SortBy[list, Extract[#, 2] &] *) Note that I did not choose to use the operator form of SortBy here. Since Mathematica uses a generally functional language these kinds of operations are frequent , which mean that these effects quickly compound. Code that contains multiple Slot Functions can be quite hard to read as it is not always clear which # belongs to which & . As a hurriedly contrived example consider this snippet: (SortBy[#, Mod[#, 5] &] &) /@ (Append[#, 11] &) /@ Partition[Range@9, 3] If we first provide "operators forms" for functions that do not presently have them: partition[n_][x_] := Partition[x, n]mod[n_][m_] := Mod[m, n] Then write the line above using such forms in all applicable places: SortBy[mod @ 5] /@ Append[11] /@ partition[3] @ Range @ 9 This is a considerable streamlining of syntax and much easier to read. The example above is also semantically simpler: Unevaluated[(SortBy[#1, Mod[#1, 5] &] &) /@ (Append[#1, 11] &) /@ Partition[Range[9], 3]] // LeafCountUnevaluated[SortBy[mod @ 5] /@ Append[11] /@ partition[3] @ Range @ 9] // LeafCount 2011 Theoretically that could pay dividends in performance though I am uncertain of the present reality of this. Some operations are slower, possibly due to an inability to compile, while others are faster. However I believe that this simplification opens the door for future optimizations.
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/56504', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2249/']}
jdg_77348
stackexchange
llm_judgeable_groundtruth_similarity
48464444
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a list and I want to display my li elements horizontally and 3 per row. I've been trying to get what I want, but no luck. Is there a solution? <div class="serv"> <ul> @foreach(App\Http\Controllers\HomeController::getservice($service->id) as $key => $value) <li> <span class="h3-service">{{$value->title}}</span> <p>{!!$value->description!!}</p> </li> @endforeach </ul></div> .serv ul { display: inline-flex; margin: 0; padding: 0; width: 33%; text-align: left; float: left;}.serv ul li { list-style: none; display: inline-block; padding: 0;}.serv ul li span { padding: 0;} Now provide the response and nothing else.
Flex container: You probably want to use display: flex not inline-flex . Add flex-wrap: wrap to allow wrapping onto multiple lines. Remove width: 33% if you wish it to take entire space avaiable. For 3 items per row, add on the flex items: flex-basis: 33.333333% You can also use the flex 's shorthand like the following: flex: 0 0 33.333333% => which also means flex-basis: 33.333333% . .serv ul { display: flex; flex-wrap: wrap; padding-left: 0;}.serv ul li { list-style: none; flex: 0 0 33.333333%;} <div class="serv"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> </ul></div>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/48464444', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7916141/']}
jdg_77349
stackexchange
llm_judgeable_groundtruth_similarity
316131
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 linux kernel oops, how do you go about diagnosing the problem? In the output I can see a stack trace which seems to give some clues. Are there any tools that would help find the problem? What basic procedures do you follow to track it down? Unable to handle kernel paging request for data at address 0x33343a31Faulting instruction address: 0xc50659ecOops: Kernel access of bad area, sig: 11 [#1]tpsslr3Modules linked in: datalog(P) manet(P) vnet wlan_wep wlan_scan_sta ath_rate_sample ath_pci wlan ath_hal(P)NIP: c50659ec LR: c5065f04 CTR: c00192e8REGS: c2aff920 TRAP: 0300 Tainted: P (2.6.25.16-dirty)MSR: 00009032 CR: 22082444 XER: 20000000DAR: 33343a31, DSISR: 20000000TASK = c2e6e3f0[1486] 'datalogd' THREAD: c2afe000GPR00: c5065f04 c2aff9d0 c2e6e3f0 00000000 00000001 00000001 00000000 0000b3f9GPR08: 3a33340a c5069624 c5068d14 33343a31 82082482 1001f2b4 c1228000 c1230000GPR16: c60f0000 000004a8 c59abbe6 0000002f c1228360 c340d6b0 c5070000 00000001GPR24: c2aff9e0 c5070000 00000000 00000000 00000003 c2cc2780 c2affae8 0000000fNIP [c50659ec] mesh_packet_in+0x3d8/0xdac [manet]LR [c5065f04] mesh_packet_in+0x8f0/0xdac [manet]Call Trace:[c2aff9d0] [c5065f04] mesh_packet_in+0x8f0/0xdac [manet] (unreliable)[c2affad0] [c5061ff8] IF_netif_rx+0xa0/0xb0 [manet][c2affae0] [c01925e4] netif_receive_skb+0x34/0x3c4[c2affb10] [c60b5f74] netif_receive_skb_debug+0x2c/0x3c [wlan][c2affb20] [c60bc7a4] ieee80211_deliver_data+0x1b4/0x380 [wlan][c2affb60] [c60bd420] ieee80211_input+0xab0/0x1bec [wlan][c2affbf0] [c6105b04] ath_rx_poll+0x884/0xab8 [ath_pci][c2affc90] [c018ec20] net_rx_action+0xd8/0x1ac[c2affcb0] [c00260b4] __do_softirq+0x7c/0xf4[c2affce0] [c0005754] do_softirq+0x58/0x5c[c2affcf0] [c0025eb4] irq_exit+0x48/0x58[c2affd00] [c000627c] do_IRQ+0xa4/0xc4[c2affd10] [c00106f8] ret_from_except+0x0/0x14--- Exception: 501 at __delay+0x78/0x98 LR = cfi_amdstd_write_buffers+0x618/0x7ac[c2affdd0] [c0163670] cfi_amdstd_write_buffers+0x504/0x7ac (unreliable)[c2affe50] [c015a2d0] concat_write+0xe4/0x140[c2affe80] [c0158ff4] part_write+0xd0/0xf0[c2affe90] [c015bdf0] mtd_write+0x170/0x2a8[c2affef0] [c0073898] vfs_write+0xcc/0x16c[c2afff10] [c0073f2c] sys_write+0x4c/0x90[c2afff40] [c0010060] ret_from_syscall+0x0/0x38--- Exception: c01 at 0xfd98a50 LR = 0x10003840Instruction dump:419d02a0 98010009 800100a4 2f800003 419e0508 2f170000 419a0098 3d20c507a0e1002e 81699624 39299624 7f8b4800 419e007c a0610016 7d264b78Kernel panic - not syncing: Fatal exception in interruptRebooting in 1 seconds.. Now provide the response and nothing else.
An Oops gives a bunch of information useful in diagnosing a crash. It starts with the address of the crash, the reason ("access of bad area") and the contents of the registers. The call trace answers the question "how did we get here". The first item in the list happened most recently. Working backwards, an interrupt happened ( do_IRQ ) because the Atheros WiFi adapter received a packet ( ath_rx_poll ). The routine passed it to the generic WiFi code ( ieee80211_input ) which in turn passed it up to the network stack ( netif_receive_skb ). To figure out the exact code causing the problem, you can run gdb /usr/src/linux/vmlinux and then disassemble the function in question, which might be mesh_packet_in() . Might, because the faulting instruction (0xc50659ec) looks to be outside of mesh_packet_in() (0xc5065f04). You might also try the gdb command (gdb) info line 0xc50659ec to figure out which function contains this address.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/316131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20889/']}
jdg_77350
stackexchange
llm_judgeable_groundtruth_similarity
134023
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: 'Mercury' was included in one of the possible answers for this exam question: Name a metal that an inert electrode could be made from. My answer was 'platinum' which was also a possible answer, but I’m curious how mercury, which is a liquid metal, could be used as an electrode during electrolysis? Now provide the response and nothing else.
The dropping mercury electrode (DME) is a working electrode made of mercury and used in polarography . Experiments run with mercury electrodes are referred to as forms of polarography even if the experiments are identical or very similar to a corresponding voltammetry experiment which uses solid working electrodes. Like other working electrodes these electrodes are used in electrochemical studies using three electrode systems when investigating reaction mechanisms related to redox chemistry among other chemical phenomena. Source: dropping mercury electrode Massive thanks to Ed V for advice in the comments prompting my research
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/134023', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/87609/']}
jdg_77351
stackexchange
llm_judgeable_groundtruth_similarity
11678696
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What's a good way to interface Python running on OS X with a cloud-based SQL Server database? EDIT: With pyodbc I'm getting this error: >>> import pyodbc>>> cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=adsf.com;DATABASE=asdf;UID=asdf;PWD=asdf')Traceback (most recent call last): File "<stdin>", line 1, in <module>pyodbc.Error: ('00000', '[00000] [iODBC][Driver Manager]dlopen({SQL Server}, 6): image not found (0) (SQLDriverConnect)') Now provide the response and nothing else.
Summary I'm using a Mac on Yosemite Version 10.10.1 trying to connect to a MS SQL Server database. I searched and couldn't find an updated detailed answer so here's a writeup that is mostly from this amazing article here . I'm adding it on stackoverflow in case the link dies. The idea is that we'll have the following layers to setup/connect. Layers PART 1 - pyodbc PART 2 - freeTDS (can check with tsql) PART 3 - unixODBC (can check with isql) PART 4 - MS SQL (can check with a regular python program) Steps Install Homebrew from here - this is a package manager for Mac OSX. The article shows how to use another package manager 'MacPorts'. For my instructions, they're with homebrew. Basically homebrew has a folder 'cellar' that holds different versions of packages. Instead of modifying your normal files, it instead points to these homebrew packages. We need to install Pyodbc, but pyodbc uses iODBC drivers by default (which comes installed with mac), but many people have issues making it work. So, we're going to use an alternative called unixodbc , which we would install in the future. For now, we need to configure the pyodbc installation such that it works with unixodbc. Go to PyPi and download pyodbc tarball and uncompress it. Then change these lines in setup.py : elif sys.platform == 'darwin': # OS/X now ships with iODBC. settings['libraries'].append('iodbc') to: elif sys.platform == 'darwin': # OS/X now ships with iODBC. settings['libraries'].append('odbc') and now run python setup.py install . This makes our pyodbc installation use unixodbc drivers by default. Perfect! Install FreeTDS with brew install freetds --with-unixodbc (FreeTDS is the driver that sits between the Mac ODBC and MS SQL Server, this chart here shows which version of TDS you should be using based on your specific Microsoft Server version; e.g. tds protocol 7.2 for Microsoft SQL Server 2008). Configure freetds.conf file (The file should be in '/usr/local/etc/freetds.conf', which for Homebrew is a link to say '/usr/local/Cellar/freetds/0.91_2/etc', but yours might be somewhere different depending on version). I edited the global and added my database info to the end (for some reason 'tds version = 7.2' would throw an error, but still work, while 8.0 just works): [global]# TDS protocol versiontds version = 8.0[MYSERVER]host = MYSERVERport = 1433tds version = 8.0 Verify FreeTDS installed correctly with: tsql -S myserver -U myuser -P mypassword (you should see a prompt like this if it worked) locale is "en_US.UTF-8"locale charset is "UTF-8"using default charset "UTF-8"1> Install unixODBC with brew install unixodbc . Setup your unixODBC config files , which includes odbcinst.ini (driver configuration), and odbc.ini (DSN configuration file). By default, my files were in: /Library/ODBC (Note: NOT my user library aka /Users/williamliu/Library). Or they could also be in your homebrew installation directory /usr/local/Cellar/unixodbc/<version>/etc . Open up your ' odbcinst.ini ' file and then add the following (Note: Different if you use MacPorts. For Homebrew, this file is a link to the homebrew version e.g. mine is in '/usr/local/Cellar/freetds/0.91_2/lib/libtdsodbc.so'): [FreeTDS]Description=FreeTDS Driver for Linux & MSSQL on Win32Driver=/usr/local/lib/libtdsodbc.soSetup=/usr/local/lib/libtdsodbc.soUsageCount=1 Open up your ' odbc.ini ' and then add the following (this is usually along with odbcinst.ini : [MYSERVER]Description = Test to SQLServerDriver = FreeTDSTrace = YesTraceFile = /tmp/sql.logDatabase = MYDATABASEServername = MYSERVERUserName = MYUSERPassword = MYPASSWORDPort = 1433Protocol = 8.0ReadOnly = NoRowVersioning = NoShowSystemTables = NoShowOidColumn = NoFakeOidIndex = No Verify unixODBC installed correctly with: isql MYSERVER MYUSER MYPASSWORD . If you get an error that you cannot connect, then add -v to check what the verbose output is and fix it. Otherwise, you should see this: +---------------------------------------+| Connected! || || sql-statement || help [tablename] || quit || |+---------------------------------------+ Now verify pyodbc works with a python program. Run python in the shell or a .py file with this and you should get your query back: import pyodbcimport pandasimport pandas.io.sql as psqlcnxn = pyodbc.connect('DSN=MYSERVER;UID=MYUSER;PWD=MYPASSWORD')cursor = cnxn.cursor()sql = ("SELECT * FROM dbo.MYDATABASE")df = psql.frame_query(sql, cnxn) You can refer to the documentation of pyodbc to get more help after this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11678696', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/613705/']}
jdg_77352
stackexchange
llm_judgeable_groundtruth_similarity
139281
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'm preparing to consider the outcome of training a lot of people (>25) to use Mercurial coming from a centralized mindset. I've done it with individuals and had success with it, although the time invested in each one has been different and most of them have been both proactive and open to trying something new. I was wondering if there was someone here with experience giving such training to a large group of people as I would like to find out what are the do's and don'ts... of course, this would be more oriented towards dealing with those resistant to change , and a don't I can come to think of is telling them to avoid cheat-sheets mapping commands, as Joel Spolsky suggests . Now provide the response and nothing else.
I work as a Mercurial consultant and I've found that it's not too hard to explain DVCS to new users, provided that you don't confuse them. So what I do is: Emphasize the core principles. The history model in Mercurial is actually very clean and simple. In particular, I find that branches are modeled better in Mercurial than in, say, Subversion. Talk with the users about how working together should work in an ideal world: I do a bit of work on my machine, you do a bit of work on your machine and we later reconcile (merge) our work. Then show them how Mercurial implements exactly this model. Emphasize the centralized workflow. A lot of guides and tutorials put a lot of emphasis on the distributed aspect of DVCS — my experience is that this is not very important! Especially not in an organization where you already use a big centralized VCS. The important part is the new and improved workflows. Emphasize simple use cases. Let the users get hands-on experience from playing with the tool. First they will commit and push/pull with a central server. Later you can guide them through a more structured scenario where they create a feature branch, make some commits, and merge it back. We've made some training material that we call a Mercurial Kick-Start . I've used it several times and it normally has enough content for two or three days, depending on how much I talk.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/139281', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/10869/']}
jdg_77353
stackexchange
llm_judgeable_groundtruth_similarity
17295024
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 clicking li item. i set active attribute to css class but li has a link to forward another page. active css disappear? how to do this? i have been used localstorage to cache my old selected li item. i can not find any solution. How to make alive active class setting after refreshing? how to set active class alive after refreshing page? <script type="text/javascript">$(document).ready(function () { $("li").click(function () { var id = $(this).attr("id"); console.log(id); var selectedolditem = localStorage.getItem('selectedolditem'); if (selectedolditem != null) { $('#' + selectedolditem).siblings().find("active").removeClass("active"); $('#' + selectedolditem).addClass("active"); localStorage.clear(); return; } $('#'+id).siblings().find("active").removeClass("active"); $('#' + id).addClass("active"); localStorage.setItem("selectedolditem", id); });}); Now provide the response and nothing else.
The problem with your code is you are trying to retrieve it onclick. That's the wrong logic. The correct logic is: when the page loads, retrieve it. When the li is clicked, store it. You also have a problem when using find("active") , you need to use the class character . otherwise it will search for elements with the tag name active not the class. $(document).ready(function () { $("li").click(function () { var id = $(this).attr("id"); $('#' + id).siblings().find(".active").removeClass("active"); // ^ you forgot this $('#' + id).addClass("active"); localStorage.setItem("selectedolditem", id); }); var selectedolditem = localStorage.getItem('selectedolditem'); if (selectedolditem != null) { $('#' + selectedolditem).siblings().find(".active").removeClass("active"); // ^ you forgot this $('#' + selectedolditem).addClass("active"); }});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17295024', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298875/']}
jdg_77354
stackexchange
llm_judgeable_groundtruth_similarity
2000204
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 $2$ points $A(-2,0)$ and $B(0,4)$ and a line $y=x.$ Find the coordinate of a point $C$ on the line So that Perimeter of a $\triangle ABC$ is minimum $\bf{My\; Try::}$ Let Coordinate of Point $P(x,y)$ Here We have to Minimize $AB+BC+CA = 2\sqrt{5}+\sqrt{(x+2)^2+y^2}+\sqrt{x^2+(y-4)^2}$ So We have to Minimize $CA+CB$ So $$\min\left(\sqrt{(x+2)^2+y^2}+\sqrt{x^2+(y-4)^2}\right)$$ So Using Minkowski Inequality:: $$\sqrt{(x+2)^2+y^2}+\sqrt{x^2+(y-4)^2}\geq \sqrt{(x+2-x)^2+(y-y+4)^2} = 2\sqrt{5}$$ and equality hold when $$\frac{x+2}{-x} = \frac{y}{-(y-4)}\Rightarrow 2x+4=y$$ So solving $2x+4=y$ and $y=x\;,$ We get $(x,y) = (-4,-4)$ Although I have used Minkowski Inequality, But i did not understand how can i solve it Using Image of point $A$ or $B$ with respect to line $y=x$ plz explain me using Figure, Thanks Now provide the response and nothing else.
We know light travels along path of least time. Using this, you get $C = (0,0)$ , which is not very hard to justify. The Length $AB$ is fixed. So we seek to minimise $AC + CB$ , where Fermat's principle tells us that its minimum would be along reflected path. So we take reflection of $A$ about $y = x$ , and find distance $A'B$ So the perimeter will be P = $A'B + AB$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2000204', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14311/']}
jdg_77355
stackexchange
llm_judgeable_groundtruth_similarity
2072693
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: Suppose I have a matrix function $A(t)$ with $$\lVert A(t) - B\rVert \le ct^\alpha$$ in some matrix norm (this will work for any norm, I guess). So, in a sense $A(t)\rightarrow B$ for $t\rightarrow 0$ in $\mathcal{O}(t^\alpha)$. Plus, we have $A(0) = B$. I happen to know the eigenvalues of $B$, but I don't know a thing about the eigenvalues of $A(t)$. Plus, $A(t)$ does not have any favorable structure, in particular, no symmetry. So, what can you say about the eigenvalues of $A(t)$? In particular: What about the spectral radius of $\lambda_{A(t)}$? Does it converge to the spectral radius of $B$? Do we have $\lambda_{A(t)}\rightarrow\lambda_B$ for $t\rightarrow 0$ for all eigenvalues $\lambda_{A(t)}$ of $A(t)$? And finally: is the speed of convergence $\mathcal{O}(t^\alpha)$ the same for the eigenvalues/spectral radius as for the matrix function? The last question is actually the most important one. If the eigenvalues of $B$ are all zero, the eigenvalues as well as the spectral radius of $A(t)$ would go to zero as $\mathcal{O}(t^\alpha)$... Any help would be appreciated, incl. references to (standard?) textbooks or papers on this matter. Maybe there is a counterexample? So far, in all numerical examples I have seen/done, all properties above do hold. Edit : To provide a bit more background: The matrices $A(t)$ are iteration matrices which depend on a time-step size $t$. They are not this ugly, but showing convergence of this iteration has proven to be rather difficult. In the simplest case, they look like$$A(t) = (I-tQ_1)^{-1}(t(Q_2-Q_1)+B)$$with identity matrix $I$ and some matrices $Q_1,Q_2$, which do not have any particular structure we were able to exploit so far.Now, if I can make that conclusion about the spectral radius as described above, I can state that the spectral radius is smaller than 1, i.e. the iteration converges, if the time-step size $t$ is small enough. Edit: Does this answer help? Also, this question might be related to perturbation theory for eigenvalue problems (with non-symmetric matrices, though, and $B$ is not diagonalizable). Now provide the response and nothing else.
Parts (1) and (2) -- Yes. The coefficients of the characteristic polynomial are continuous functions of $A(t)$ (they are polynomials in the entries of $A(t)$!) and the roots of a polynomial are continuous functions of the coefficients . Part (3): If $B$ has non-trivial Jordan blocks, this can fail. For example,$$\begin{pmatrix} 0 & 1 \\ -t & 0 \end{pmatrix} = \begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix} + O(t)$$as $t \to 0$, but the eigenvalues are $\pm \sqrt{t}$, which is not $O(t)$. I believe that this is true when $B$ is diagonalizable. (I know that it is diagonalizable if $B$ has distinct eigenvalues, and I'll write up that argument if this one fails.) We may as well assume $B$ is diagonalized. Let's concentrate on a particular eigenvalue $\lambda$ of $B$, with multiplicity $m$; we might as well assume $\lambda =0$. So $B = \mathrm{diag}(0,0,\cdots,0, \lambda_2, \lambda_3, ..., \lambda_k)$ with $m$ zeroes. Suppose that $B-A(t)$ is $O(t^a)$. Explicitly expanding the determinant, the coefficient of $x^k$ in $\det(x \mathrm{Id} - B)$ is $O(t^{a(m-k)})$ for $k < m$, and the coefficient of $x^m$ does not go to $0$ as $t \to 0$. So the Newton polygon of the characteristic polynomial passes through $(m,0)$ and stays above the line from $(m,0)$ to $(0,ma)$. This shows that the bottom $m$ roots of the characteristic polynomial vanish at rate $O(t^a)$ or faster as $t \to 0$ (and the other roots do not vanish.) It occurs to me that it is worth sketching the argument for the Newton polygon claim directly so you can see how straightforward it is without learning the whole Newton polygon technology. Here is what I am claiming: Lemma Fix $C>0$. Then there is a $D>0$ such that, if $f(u,z) = \sum_i f_i(u) z^i$ is holomorphic in $z$ on the disc of radius $1$, with $$|f_i(u)/f_m(u)| < \begin{cases} C u^{m-i} & i < m \\ C & i > m \end{cases}$$then $f(u, \ )$ has $m$ roots in the disc of radius $D u$ for all sufficiently small $u$. Proof sketch Consider $\oint \tfrac{f'}{f} dz$ where the integral is around the circle of radius $Du$. Write $f = f_m(u) z^m (1+\mbox{other terms})$ and $f' = m f_m(u) z^{m-1} (1+\mbox{other terms})$ so the integral is $\oint m \tfrac{dz}{z} + \mbox{other terms}$. Use the above conditions to bound the other terms.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2072693', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/402051/']}
jdg_77356
stackexchange
llm_judgeable_groundtruth_similarity
72453
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem like the following: 1) There are six measurements for each individual with large within-subject variance 2) There are two groups (Treatment and Control) 3) Each group consists of 5 individuals 4) I want to perform a significance test comparing the two groups to know if the group means are different from one another. The data looks like this: And I have run some simulations using this code which does t tests to compare the group means. The group means were calculated by taking the means of the individual means. This ignores within-subject variability : n.simulations<-10000 pvals=matrix(nrow=n.simulations,ncol=1) for(k in 1:n.simulations){ subject=NULL for(i in 1:10){ subject<-rbind(subject,as.matrix(rep(i,6))) } #set.seed(42) #Sample Subject Means subject.means<-rnorm(10,100,2) #Sample Individual Measurements values=NULL for(sm in subject.means){ values<-rbind(values,as.matrix(rnorm(6,sm,20))) } out<-cbind(subject,values) #Split into GroupA and GroupB GroupA<-out[1:30,] GroupB<-out[31:60,] #Add effect size to GroupA GroupA[,2]<-GroupA[,2]+0 colnames(GroupA)<-c("Subject", "Value") colnames(GroupB)<-c("Subject", "Value") #Calculate Individual Means and SDS GroupA.summary=matrix(nrow=length(unique(GroupA[,1])), ncol=2) for(i in 1:length(unique(GroupA[,1]))){ GroupA.summary[i,1]<-mean(GroupA[which(GroupA[,1]==unique(GroupA[,1])[i]),2]) GroupA.summary[i,2]<-sd(GroupA[which(GroupA[,1]==unique(GroupA[,1])[i]),2]) } colnames(GroupA.summary)<-c("Mean","SD") GroupB.summary=matrix(nrow=length(unique(GroupB[,1])), ncol=2) for(i in 1:length(unique(GroupB[,1]))){ GroupB.summary[i,1]<-mean(GroupB[which(GroupB[,1]==unique(GroupB[,1])[i]),2]) GroupB.summary[i,2]<-sd(GroupB[which(GroupB[,1]==unique(GroupB[,1])[i]),2]) } colnames(GroupB.summary)<-c("Mean","SD") Summary<-rbind(cbind(1,GroupA.summary),cbind(2,GroupB.summary)) colnames(Summary)[1]<-"Group" pvals[k]<-t.test(GroupA.summary[,1],GroupB.summary[,1], var.equal=T)$p.value } And here is code for plots: #Plotspar(mfrow=c(2,2))boxplot(GroupA[,2]~GroupA[,1], col="Red", main="Group A", ylim=c(.9*min(out[,2]),1.1*max(out[,2])), xlab="Subject", ylab="Value")stripchart(GroupA[,2]~GroupA[,1], vert=T, pch=16, add=T)#abline(h=mean(GroupA[,2]), lty=2, lwd=3)for(i in 1:length(unique(GroupA[,1]))){ m<-mean(GroupA[which(GroupA[,1]==unique(GroupA[,1])[i]),2]) ci<-t.test(GroupA[which(GroupA[,1]==unique(GroupA[,1])[i]),2])$conf.int[1:2] points(i-.2,m, pch=15,cex=1.5, col="Grey") segments(i-.2, ci[1],i-.2, ci[2], lwd=4, col="Grey" )}legend("topleft", legend=c("Individual Means +/- 95% CI"), bty="n", pch=15, lwd=3, col="Grey")boxplot(GroupB[,2]~GroupB[,1], col="Light Blue", main="Group B", ylim=c(.9*min(out[,2]),1.1*max(out[,2])), xlab="Subject", ylab="Value")stripchart(GroupB[,2]~GroupB[,1], vert=T, pch=16, add=T)#abline(h=mean(GroupB[,2]), lty=2, lwd=3)for(i in 1:length(unique(GroupB[,1]))){ m<-mean(GroupB[which(GroupB[,1]==unique(GroupB[,1])[i]),2]) ci<-t.test(GroupB[which(GroupB[,1]==unique(GroupB[,1])[i]),2])$conf.int[1:2] points(i-.2,m, pch=15,cex=1.5, col="Grey") segments(i-.2, ci[1],i-.2, ci[2], lwd=4, col="Grey" )}legend("topleft", legend=c("Individual Means +/- 95% CI"), bty="n", pch=15, lwd=3, col="Grey")boxplot(Summary[,2]~Summary[,1], col=c("Red","Light Blue"), xlab="Group", ylab="Average Value", ylim=c(.9*min(Summary[,2]),1.1*max(Summary[,2])), main="Individual Averages")stripchart(Summary[,2]~Summary[,1], vert=T, pch=16, add=T)points(.9, mean(GroupA.summary[,1]), pch=15,cex=1.5, col="Grey")segments(.9, t.test(GroupA.summary[,1])$conf.int[1],.9, t.test(GroupA.summary[,1])$conf.int[2], lwd=4, col="Grey")points(1.9, mean(GroupB.summary[,1]), pch=15,cex=1.5, col="Grey")segments(1.9, t.test(GroupB.summary[,1])$conf.int[1],1.9, t.test(GroupB.summary[,1])$conf.int[2], lwd=4, col="Grey")legend("topleft", legend=c("Group Means +/- 95% CI"), bty="n", pch=15, lwd=3, col="Grey")hist(pvals, breaks=seq(0,1,by=.05), col="Grey", main=c(paste("# sims=", n.simulations), paste("% Sig p-values=",100*length(which(pvals<0.05))/length(pvals)))) Now, it seems to me that because each individual mean is an estimate itself, that we should be less certain about the group means than shown by the 95% confidence intervals indicated by the bottom-left panel in the figure above. Thus the p-values calculated are underestimating the true variability and should lead to increased false-positives if we wish to extrapolate to future data. So what is the correct way to analyze this data? Bonus: The example above is a simplification. For the actual data: 1) The within-subject variance is positively correlated with the mean. 2) Values can only be multiples of two. 3) The individual results are not roughly normally distributed. They suffer from zero floor effect, and have long tails at the positive end. 4) Number of Subjects in each group are not necessarily equal. Previous literature has used the t-test ignoring within-subject variability and other nuances as was done for the simulations above. Are these results reliable? If I can extract some means and standard errors from the figures how would I calculate the "correct" p-values. EDIT: Ok, here is what actual data looks like. There is also three groups rather than two: dput() of data: structure(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 2, 0, 16, 2, 16, 2, 8, 10, 8, 6, 4, 4, 8, 22, 12, 24, 16, 8, 24, 22, 6, 10, 10, 14, 8, 18, 8, 14, 8, 20, 6, 16, 6, 6, 16, 4, 2, 14, 12, 10, 4, 10, 10, 8, 4, 10, 16, 16, 2, 8, 4, 0, 0, 2, 16, 10, 16, 12, 14, 12, 8, 10, 12, 8, 14, 8, 12, 20, 8, 14, 2, 4, 8, 16, 10, 14, 8, 14, 12, 8, 14, 4, 8, 8, 10, 4, 8, 20, 8, 12, 12, 22, 14, 12, 26, 32, 22, 10, 16, 26, 20, 12, 16, 20, 18, 8, 10, 26), .Dim = c(108L, 3L), .Dimnames = list( NULL, c("Group", "Subject", "Value"))) EDIT 2: In response to Henrik's answer:So if I instead perform anova followed by TukeyHSD procedure on the individual averages as shown below, I could interpret this as underestimating my p-value by about 3-4x? My goal with this part of the question is to understand how I, as a reader of a journal article, can better interpret previous results given their choice of analysis method. For example they have those "stars of authority" showing me 0.01>p>.001. So if i accept 0.05 as a reasonable cutoff I should accept their interpretation? The only additional information is mean and SEM. #Get Invidual Meanssummary=NULLfor(i in unique(dat[,2])){sub<-which(dat[,2]==i)summary<-rbind(summary,cbind(dat[sub,1][3],dat[sub,2][4],mean(dat[sub,3]),sd(dat[sub,3])))}colnames(summary)<-c("Group","Subject","Mean","SD")TukeyHSD(aov(summary[,3]~as.factor(summary[,1])+ (1|summary[,2])))# Tukey multiple comparisons of means# 95% family-wise confidence level# # Fit: aov(formula = summary[, 3] ~ as.factor(summary[, 1]) + (1 | summary[, 2]))# # $`as.factor(summary[, 1])`# diff lwr upr p adj# 2-1 -0.672619 -4.943205 3.597967 0.9124024# 3-1 7.507937 1.813822 13.202051 0.0098935# 3-2 8.180556 2.594226 13.766885 0.0046312 EDIT 3: I think we are getting close to my understanding. Here is the simulation described in the comments to @Stephane: #Get Subject Meansmeans<-aggregate(Value~Group+Subject, data=dat, FUN=mean)#Initialize "dat2" dataframedat2<-dat#Initialize within-Subject sds<-.001pvals=matrix(nrow=10000,ncol=2)for(j in 1:10000){#Sample individual measurements for each subjecttemp=NULLfor(i in 1:nrow(means)){temp<-c(temp,rnorm(6,means[i,3], s))}#Set new valuesdat2[,3]<-temp#Take means of sampled values and fit to modeldd2 <- aggregate(Value~Group+Subject, data=dat2, FUN=mean)fit2 <- lm(Value~Group, data=dd2)#Save sd and pvaluepvals[j,]<-cbind(s,anova(fit2)[[5]][5])#Update sds<-s+.001}plot(pvals[,1],pvals[,2], xlab="Within-Subject SD", ylab="P-value") Now provide the response and nothing else.
I take the freedom to answer the question in the title, how would I analyze this data. Given that we have replicates within the samples, mixed models immediately come to mind, which should estimate the variability within each individual and control for it. Hence I fit the model using lmer from lme4 . However, as we are interested in p-values, I use mixed from afex which obtains those via pbkrtest (i.e., Kenward-Rogers approximation for degrees-of-freedom). (afex also already sets the contrast to contr.sum which I would use in such a case anyway) To control for the zero floor effect (i.e., positive skew), I fit two alternative versions transforming the dependent variable either with sqrt for mild skew and log for stronger skew. require(afex)# read the dput() in as dat <- ... dat <- as.data.frame(dat)dat$Group <- factor(dat$Group)dat$Subject <- factor(dat$Subject)(model <- mixed(Value ~ Group + (1|Subject), dat))## Effect stat ndf ddf F.scaling p.value## 1 (Intercept) 237.730 1 15 1 0.0000## 2 Group 7.749 2 15 1 0.0049(model.s <- mixed(sqrt(Value) ~ Group + (1|Subject), dat))## Effect stat ndf ddf F.scaling p.value## 1 (Intercept) 418.293 1 15 1 0.0000## 2 Group 4.121 2 15 1 0.0375(model.l <- mixed(log1p(Value) ~ Group + (1|Subject), dat))## Effect stat ndf ddf F.scaling p.value## 1 (Intercept) 458.650 1 15 1 0.0000## 2 Group 2.721 2 15 1 0.0981 The effect is significant for the untransformed and sqrt dv. But are these model sensible? Let's plot the residuals. png("qq.png", 800, 300, units = "px", pointsize = 12)par(mfrow = c(1, 3))par(cex = 1.1)par(mar = c(2, 2, 2, 1)+0.1)qqnorm(resid(model[[2]]), main = "original")qqline(resid(model[[2]]))qqnorm(resid(model.s[[2]]), main = "sqrt")qqline(resid(model.s[[2]]))qqnorm(resid(model.l[[2]]), main = "log")qqline(resid(model.l[[2]]))dev.off() It seems that the model with sqrt trasnformation provides a reasonable fit (there still seems to be one outlier, but I will ignore it). So, let's further inspect this model using multcomp to get the comparisons among groups: require(multcomp)# using bonferroni-holm correction of multiple comparisonsummary(glht(model.s[[2]], linfct = mcp(Group = "Tukey")), test = adjusted("holm"))## Simultaneous Tests for General Linear Hypotheses## ## Multiple Comparisons of Means: Tukey Contrasts## ## ## Fit: lmer(formula = sqrt(Value) ~ Group + (1 | Subject), data = data)## ## Linear Hypotheses:## Estimate Std. Error z value Pr(>|z|) ## 2 - 1 == 0 -0.0754 0.3314 -0.23 0.820 ## 3 - 1 == 0 1.1189 0.4419 2.53 0.023 *## 3 - 2 == 0 1.1943 0.4335 2.75 0.018 *## ---## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1## (Adjusted p values reported -- holm method)# using default multiple comparison correction (which I don't understand)summary(glht(model.s[[2]], linfct = mcp(Group = "Tukey")))## Simultaneous Tests for General Linear Hypotheses## ## Multiple Comparisons of Means: Tukey Contrasts## ## ## Fit: lmer(formula = sqrt(Value) ~ Group + (1 | Subject), data = data)## ## Linear Hypotheses:## Estimate Std. Error z value Pr(>|z|) ## 2 - 1 == 0 -0.0754 0.3314 -0.23 0.972 ## 3 - 1 == 0 1.1189 0.4419 2.53 0.030 *## 3 - 2 == 0 1.1943 0.4335 2.75 0.016 *## ---## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1## (Adjusted p values reported -- single-step method) Punchline: group 3 differs from the other two groups which do not differ among each other.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/72453', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/31334/']}
jdg_77357
stackexchange
llm_judgeable_groundtruth_similarity
26536
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: China's FAST (Five-hundred-meter Aperture Spherical radio Telescope) is the largest radio telescope in the world.(This is huge!!!) As we all know Space Telescopes are better than Earth-Based telescopes always.(Hubble space telescope was such a tremendous success)Even though ground-based observatories are usually located in highly elevated areas with minimal light pollution, but still they contend with atmospheric turbulence, which limits the sharpness of images taken from this vantage point. What if all the space agencies collaborate together to build a telescope half the size of China's FAST in moon(Even smaller than half),even then it will be more powerful than the "FAST" right(because the atmosphere of moon is very less dense)?Will it be impractical?It may take decades to build one but still the outcome will be huge(We may even look and find aliens!!) (Taking in account that Elon Musk is already planning Colonization of Mars)This project looks somewhat tamable than that,right? Is there a possibility of this happening? Is it feasible enough? Now provide the response and nothing else.
It's very unlikely that large optical telescopes will ever be built on the Moon, because the Moon is almost the worst possible place to build them. (The surfaces any of the planets other than Earth are worse.) It has no particular advantages over orbit and costs a lot more to build there. The Moon looked like a good location when observatory technology was film-based, because observatories required people and people needed a base to live in and work best under gravity. But we now have the technology to shade an orbiting telescope from the Sun, point it exquisitely accurately, and take endless photos without changing the film -- all in orbit. Orbit is easier to get to than the Lunar surface -- even the Webb (should it ever launch) which will be parked a million miles from Earth, is easier to get to than the surface of the moon. If we had the space capabilities to build a giant reflector on the Moon, we could build an even bigger and better one in orbit for the same cost. You spoke of FAST. FAST is a radio telescope. It's likewise much cheaper to build radio telescopes in orbit than on the Lunar surface. The one possible advantage of the Moon is that the far side of the Moon might have advantages of being especially radio quiet. But even there, it seems likely that any space radio telescope would be a large array of radio telescopes joined to form a giant synthetic aperture, and that would almost certainly want to be much larger than earth-based instruments -- for which the Moon is already too small.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/26536', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/22623/']}
jdg_77358
stackexchange
llm_judgeable_groundtruth_similarity
29593471
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 string with { and } how can I take all of them and reverse them, so all { become } and } become { ? I can't do this: str = str.replace("}", "{");str = str.replace("{", "}"); because that will make A face the same way as B then it will replace B which will all change them to the same direction. I tried doing this: str = str.replace(["{", "}"], ["}", "{"]); But that just doesn't seem to do anything (not even error out). So, what can I do to invert them? Now provide the response and nothing else.
You could use a regexp with a callback function to solve this: str.replace(/\{|\}/g, function(match) { return match == "}" ? "{" : "}";});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29593471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1778465/']}
jdg_77359
stackexchange
llm_judgeable_groundtruth_similarity
2427155
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 sort the data of a core data NSSet (I know we can do it only with arrays but let me explain...). I have an entity user who has a relationship to-many with the entity recipe. A recipe has the attributes name and id.I would like to get the data such that: NSArray *id = [[user.recipes valueForKey:@"identity"] allObjects];NSArray *name = [[user.recipes valueForKey:@"name"] allObjects]; if I take the object at index 1 in both arrays, they correspond to the same recipe... Thanks Now provide the response and nothing else.
You need to sort the recipes first: NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];NSArray *sortedRecipes = [[recipes allObjects] sortedArrayUsingDescriptors:sortDescriptors]; you can then extract an array of attributes from the sorted recipes array and the results will remain in sorted order: NSArray *sortedNames = [sortedRecipes valueForKey:@"name"];NSArray *sortedIdentities = [sortedRecipes valueForKey:@"identity"];
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2427155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276439/']}
jdg_77360
stackexchange
llm_judgeable_groundtruth_similarity
188941
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: A very peculiar thing is happening when I wrap a Graph with GraphPlot. The picture below shows the correct vertex labeling. However, GraphPlot changes the vertex labeling! Am I misusing this function or is this something I should report to Wolfram? I'm running version 11.0.1.0. Below is some code to reproduce the issue (but with a simpler graph). {gph = Graph[{2 -> 1, 5 -> 0, 7 -> 6, 8 -> 7, 10 -> 8, 0 -> 2, 2 -> 3, 3 -> 4, 5 -> 10, 8 -> 9}, VertexLabels -> "Name"],GraphPlot[gph, VertexLabeling -> True]} Interestingly enough, using a built-in function (like KaryTree) yields expected results: {KaryTree[15, VertexLabels -> "Name"], GraphPlot[KaryTree[15], VertexLabeling -> True]} My work-around is using Graph and formatting it exactly how I want, but I would like to understand why the vertex labeling is incorrect! Now provide the response and nothing else.
GraphPlot supports inputs in several different formats. Originally, it took either a list of Rule s or an adjacency matrix. With a rule-list input, it displays the vertex labels you would expect. But the adjacency matrix does not contain information about vertex names. Thus with a matrix input, it uses vertex indices (not names) for labelling. In 11.3 (and probably all the way back to at least 10.0), GraphPlot also takes Graph expressions as input. But it handles Graph s by converting them to a matrix (not a rule list!) first. Thus the vertex names are lost, and it will use vertex indices instead. Workaround: convert the graph to a rule list yourself. GraphPlot[Rule @@@ EdgeList@gph, VertexLabeling -> True, DirectedEdges -> True, Method -> "LayeredDrawing"]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/188941', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6028/']}
jdg_77361
stackexchange
llm_judgeable_groundtruth_similarity
5800433
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem deserializing a json string with Gson.I receive an array of commands. The command can be start, stop , some other type of command. Naturally I have polymorphism, and start/stop command inherit from command. How can I serialize it back to the correct command object using gson? Seems that I get only the base type, that is the declared type and never the runtime type. Now provide the response and nothing else.
This is a bit late but I had to do exactly the same thing today. So, based on my research and when using gson-2.0 you really don't want to use the registerTypeHierarchyAdapter method, but rather the more mundane registerTypeAdapter . And you certainly don't need to do instanceofs or write adapters for the derived classes: just one adapter for the base class or interface, provided of course that you are happy with the default serialization of the derived classes. Anyway, here's the code (package and imports removed) (also available in github ): The base class (interface in my case): public interface IAnimal { public String sound(); } The two derived classes, Cat: public class Cat implements IAnimal { public String name; public Cat(String name) { super(); this.name = name; } @Override public String sound() { return name + " : \"meaow\""; };} And Dog: public class Dog implements IAnimal { public String name; public int ferocity; public Dog(String name, int ferocity) { super(); this.name = name; this.ferocity = ferocity; } @Override public String sound() { return name + " : \"bark\" (ferocity level:" + ferocity + ")"; }} The IAnimalAdapter: public class IAnimalAdapter implements JsonSerializer<IAnimal>, JsonDeserializer<IAnimal>{ private static final String CLASSNAME = "CLASSNAME"; private static final String INSTANCE = "INSTANCE"; @Override public JsonElement serialize(IAnimal src, Type typeOfSrc, JsonSerializationContext context) { JsonObject retValue = new JsonObject(); String className = src.getClass().getName(); retValue.addProperty(CLASSNAME, className); JsonElement elem = context.serialize(src); retValue.add(INSTANCE, elem); return retValue; } @Override public IAnimal deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME); String className = prim.getAsString(); Class<?> klass = null; try { klass = Class.forName(className); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new JsonParseException(e.getMessage()); } return context.deserialize(jsonObject.get(INSTANCE), klass); }} And the Test class: public class Test { public static void main(String[] args) { IAnimal animals[] = new IAnimal[]{new Cat("Kitty"), new Dog("Brutus", 5)}; Gson gsonExt = null; { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(IAnimal.class, new IAnimalAdapter()); gsonExt = builder.create(); } for (IAnimal animal : animals) { String animalJson = gsonExt.toJson(animal, IAnimal.class); System.out.println("serialized with the custom serializer:" + animalJson); IAnimal animal2 = gsonExt.fromJson(animalJson, IAnimal.class); System.out.println(animal2.sound()); } }} When you run the Test::main you get the following output: serialized with the custom serializer:{"CLASSNAME":"com.synelixis.caches.viz.json.playground.plainAdapter.Cat","INSTANCE":{"name":"Kitty"}}Kitty : "meaow"serialized with the custom serializer:{"CLASSNAME":"com.synelixis.caches.viz.json.playground.plainAdapter.Dog","INSTANCE":{"name":"Brutus","ferocity":5}}Brutus : "bark" (ferocity level:5) I've actually done the above using the registerTypeHierarchyAdapter method too, but that seemed to require implementing custom DogAdapter and CatAdapter serializer/deserializer classes which are a pain to maintain any time you want to add another field to Dog or to Cat.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5800433', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/712077/']}
jdg_77362
stackexchange
llm_judgeable_groundtruth_similarity
15581687
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 display pictures on the JPanel but I keep getting the error : java.lang.IllegalArgumentException: input == null! I don't understand what is happening. Here is the code I am using: public void actionPerformed(ActionEvent e) { try { Image image=ImageIO.read(getClass().getResource("img/" +num.getText()+".jpg")); Image resized = image.getScaledInstance(200, 200, 100); pictureFrame.setIcon(new ImageIcon(resized)); } catch (Exception ex){ ex.printStackTrace(); }} This just leads to me getting the error! Stack trace produces the following: Java.lang.IllegalArgumentException: input == null! at javax.imageio.ImageIO.read(ImageIO.java:1362) at work.Item.actionPerformed(Item.java:96) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6297) at javax.swing.JComponent.processMouseEvent(JComponent.java:3275) at java.awt.Component.processEvent(Component.java:6062) at java.awt.Container.processEvent(Container.java:2039) at java.awt.Component.dispatchEventImpl(Component.java:4660) at java.awt.Container.dispatchEventImpl(Container.java:2097) at java.awt.Component.dispatchEvent(Component.java:4488) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4236) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166) at java.awt.Container.dispatchEventImpl(Container.java:2083) at java.awt.Window.dispatchEventImpl(Window.java:2489) at java.awt.Component.dispatchEvent(Component.java:4488) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:668) at java.awt.EventQueue.access$400(EventQueue.java:81) at java.awt.EventQueue$2.run(EventQueue.java:627) at java.awt.EventQueue$2.run(EventQueue.java:625) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98) at java.awt.EventQueue$3.run(EventQueue.java:641) at java.awt.EventQueue$3.run(EventQueue.java:639) at java.security.AccessController.doPrivileged(Native Method) at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87) at java.awt.EventQueue.dispatchEvent(EventQueue.java:638) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) How can I solve this? I have checked the location of the image, and have tried from different locations and always get the same error! I'm using the Netbeans IDE. Now provide the response and nothing else.
Assuming getClass() returns com.foo.bar.MyActionListener , getClass().getResource("img/foo.jpg") looks for a file named foo.jpg in the package com.foo.bar.img . If the image is not in this package, or if it is in this package but its root directory is not in the classpath, the method will return null. If the img folder is at the root of the classpath, you should use getClass().getResource("/img/foo.jpg") (note the leading / ), or getClass().getClassLoader().getResource("img/foo.jpg") .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15581687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2201158/']}
jdg_77363
stackexchange
llm_judgeable_groundtruth_similarity
10505166
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 plain java I'd use: public User(String name, String email) { this.name = name; this.email = f(email); this.admin = false;} However, I couldn't find a simple standard way to do in rails (3.2.3), with ActiveRecords. 1. override initialize def initialize(attributes = {}, options = {}) @name = attributes[:name] @email = f(attributes[:email]) @admin = falseend but it might be missed when creating a record from the DB 2. using the after_initialize callback by overriding it: def after_initialize(attributes = {}, options = {}) ...end or with the macro: after_initialize : my_own_little_initdef my_own_little_init(attributes = {}, options = {}) ...end but there may be some deprecation issues . There are some other links in SO , but they may be out-of-date. So, what's the correct/standard method to use? Now provide the response and nothing else.
Your default values should be defined in your Schema when they will apply to ALL records. So def change creates_table :posts do |t| t.boolean :published, default: false t.string :title t.text :content t.references :author t.timestamps endend Here, every new Post will have false for published. If you want default values at the object level, it's best to use Factory style implementations: User.build_admin(params)def self.build_admin(params) user = User.new(params) user.admin = true userend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10505166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/192958/']}
jdg_77364
stackexchange
llm_judgeable_groundtruth_similarity
399078
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 tired of always trying to guess, if I should escape special characters like ' ()[]{}| ' etc. when using many implementations of regexps. It is different with, for example, Python, sed, grep, awk, Perl, rename, Apache, find and so on.Is there any rule set which tells when I should, and when I should not, escape special characters? Does it depend on the regexp type, like PCRE, POSIX or extended regexps? Now provide the response and nothing else.
Which characters you must and which you mustn't escape indeed depends on the regex flavor you're working with. For PCRE, and most other so-called Perl-compatible flavors, escape these outside character classes: .^$*+?()[{\| and these inside character classes: ^-]\ For POSIX extended regexes (ERE), escape these outside character classes (same as PCRE): .^$*+?()[{\| Escaping any other characters is an error with POSIX ERE. Inside character classes, the backslash is a literal character in POSIX regular expressions. You cannot use it to escape anything. You have to use "clever placement" if you want to include character class metacharacters as literals. Put the ^ anywhere except at the start, the ] at the start, and the - at the start or the end of the character class to match these literally, e.g.: []^-] In POSIX basic regular expressions (BRE), these are metacharacters that you need to escape to suppress their meaning: .^$*[\ Escaping parentheses and curly brackets in BREs gives them the special meaning their unescaped versions have in EREs. Some implementations (e.g. GNU) also give special meaning to other characters when escaped, such as \? and +. Escaping a character other than .^$*(){} is normally an error with BREs. Inside character classes, BREs follow the same rule as EREs. If all this makes your head spin, grab a copy of RegexBuddy . On the Create tab, click Insert Token, and then Literal. RegexBuddy will add escapes as needed.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/399078', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37511/']}
jdg_77365
stackexchange
llm_judgeable_groundtruth_similarity
67032
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: Why is $x^{1/n}$ continuous for positive $x,n$ where $n$ is an integer? I can't see how it follows from the definition of limit. And I don't see any suitable inequalities so is this an application of Bernoulli's or Jensen's inequality? Now provide the response and nothing else.
The idea is that $f(x) = x^{1/n}$ is Lipschitz in a small neighborhood of any point $x > 0$. We need the following estimate. For $x, y > 0$, denote $u := f(x)$ and $v := f(y)$, so that $x = u^n$ and $y = v^n$. Then we can bound $|f(x)-f(y)|$ by $$\begin{align*}|f(x) - f(y)| = |u-v| &= \left| \frac{x-y}{u^{n-1} + u^{n-2} v + \cdots + u v^{n-2} + v^{n-1}} \right| \\ &\leqslant \frac{|x-y|}{u^{n-1}}= \frac{|x-y|}{x^{\frac{n-1}{n}}}.\end{align*}$$Therefore, for any $a > 0$, $f$ is $\ell$-Lipschitz in the neighborhood $\left[\frac{a}{2}, 2a \right]$ of $a$ for $\ell = \ell(a) = \left( \frac{a}{2} \right)^{- \frac{n-1}{n}}$. Continuity at $a$ follows from this. $\qquad \diamond$ Remarks. In fact, $f$ is also differentiable at every $a > 0$. Moreover, it is possible to strengthen the above proof to obtain the derivative as well. It turns out the function is Hölder continuous on every interval $[0, a]$, though it is not Lipschitz (assuming $n > 1$). Therefore, $f$ is continuous but not differentiable at the origin. While Mariano's answer explicitly uses that $f(x)$ is the inverse function to $g(x) = x^n$, we also exploit this fact -- but implicitly. Indeed, since $g$ is invertible and has nonzero derivative at every point in $[0, \infty)$, the inverse function theorem guarantees that $f$ is also differentiable at every $a > 0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/67032', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/16600/']}
jdg_77366
stackexchange
llm_judgeable_groundtruth_similarity
495599
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I hear a lot of "audio-foolery" going around about capacitors and I have always steered clear of multiplayer ceramic caps because I was under the impression that they are microphonic. I am designing a circuit that will be used in a club environment, eg 100dB to 110dB (spl). For this reason I want to be very careful of microphonic effects as that is some serious shaking! Not to mention the unit will be the same table as the sub-woofers. I am reading a good bit online, but I wanted to ask some people with first hand experience and this is the place for it I feel. - The question : Would NP0/C0G multi-layer ceramic caps be equivalent in this situation to using film capacitors? What realistic considerations should I be factoring into my decision as from a manufacturing point of view, this will bring cost down enormously as well as ease of procurement. Thank you for your time. Now provide the response and nothing else.
All capacitors are microphonic, this means vibration will cause variations in distance between capacitor plates (by compressing the dielectric) thus capacitance will vary. This does not change the amount of charge stored in the capacitor though, electrons don't magically disappear. If the cap has no DC bias on it, then the variation in capacitance might affect whatever circuit it is used in. If the cap has DC bias on it, due to Q=CV we have two broad cases. If the cap is used in a high impedance circuit, we can assume negligible current will flow, so Q will stay constant. So variations in C cause variations in V, which are proportional to V. This is your tube microphone preamp DC-blocking cap which makes a loud THUMP in the speakers when you tap it. The bulkier the cap, and the more "audiophile" it is, the worse it will be usually. If the cap has AC voltage on it, then the vibration-generated voltage will be AM modulated by whatever AC voltage is on the cap. So, big audiophile film caps should be "audible" as in "it sounds different" if the circuit allows it (high impedance and voltage on the cap). I've never found a microphonic electrolytic cap... If the cap is used in a low-impedance circuit, then V is constant and variations in C cause current to flow. This is usually not a problem, especially for decoupling caps, as there will be a voltage regulator to keep voltage constant anyway. On top of that, X7R and other high-K ceramics are piezoelectric. They can act as piezo loudspeakers if the voltage on them varies, this is often what makes switching power supplies whine (besides magnetostriction in coils and transformers). Likewise they act as piezoelectric microphones. Bending or squeezing a X7R cap doesn't just change capacitance, due to piezoelectric effect it also generates charge. This has no consequence for power supply decoupling (low impedance) but for high-impedance circuits it's easy to notice. For example I had a voltage regulator with a X7R cap decoupling its high-impedance Reference node. Its output would wobble when the board flexed or vibrated. As a general rule if a voltage needs to be stable, don't just check for tempco, also tap components with a plastic pencil and check on the scope. C0G/NP0 are not piezoelectric at all. They're ceramic, but not the same material as X7R/Z5U etc. They also have very little microphony due to being very hard and difficult to compress. They're less microphonic than big film types which can also have mechanical resonances. They are also cheap, accurate, and have ridiculously low distortion (like below -120dB or 1ppm). I had a DAC board where badly cleaned solder flux generated more distortion than the NP0 caps. To summarize, high-K (X7R and the like) and NP0 are complimentary. X7R is the ideal cap for decoupling: high capacity per volume and per $, small, low ESR/ESL, no electrolyte to dry up, and the price to pay is that it sucks at what doesn't matter for decoupling (accuracy, tempco, microphony, distortion, etc). C0G is very close to an ideal capacitor, but at much lower capacity per volume and per $, and only available in small values. Most likely causes of microphony problems in your design are: Big film caps used as signal DC-blocking (use electrolytics). X7Rs or other high-K ceramics on high impedance nodes like voltage references (due to their inaccuracy, large capacitance versus voltage variation, and huge distortion, they are never used in signal path anyway). High impedance low signal amplitude cables. Ggood microphone cables ones have anti-microphony filing like cotton. Bad microphone cables THUMP when someone steps on them. Also vibration can cause contacts/connectors/pots to rub and scratch... if the thing is attached to a subwoofer, make sure the board doesnt' have a mechanical resonance in the frequency band of interest, for example due to a heavy cap or heat sink in the middle and standoffs only in the corners, that could cause it to wobble and eventually crack your solder joints... you might have to add standoffs in some places. TL/DR: Yes, use NP0.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/495599', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/183092/']}
jdg_77367
stackexchange
llm_judgeable_groundtruth_similarity
48006551
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 send a large pandas.DataFrame to a remote server running MS SQL. The way I do it now is by converting a data_frame object to a list of tuples and then send it away with pyODBC's executemany() function. It goes something like this: import pyodbc as pdb list_of_tuples = convert_df(data_frame) connection = pdb.connect(cnxn_str) cursor = connection.cursor() cursor.fast_executemany = True cursor.executemany(sql_statement, list_of_tuples) connection.commit() cursor.close() connection.close() I then started to wonder if things can be sped up (or at least more readable) by using data_frame.to_sql() method. I have came up with the following solution: import sqlalchemy as sa engine = sa.create_engine("mssql+pyodbc:///?odbc_connect=%s" % cnxn_str) data_frame.to_sql(table_name, engine, index=False) Now the code is more readable, but the upload is at least 150 times slower ... Is there a way to flip the fast_executemany when using SQLAlchemy? I am using pandas-0.20.3, pyODBC-4.0.21 and sqlalchemy-1.1.13. Now provide the response and nothing else.
After contacting the developers of SQLAlchemy, a way to solve this problem has emerged. Many thanks to them for the great work! One has to use a cursor execution event and check if the executemany flag has been raised. If that is indeed the case, switch the fast_executemany option on. For example: from sqlalchemy import [email protected]_for(engine, 'before_cursor_execute')def receive_before_cursor_execute(conn, cursor, statement, params, context, executemany): if executemany: cursor.fast_executemany = True More information on execution events can be found here . UPDATE: Support for fast_executemany of pyodbc was added in SQLAlchemy 1.3.0 , so this hack is not longer necessary.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48006551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/940490/']}
jdg_77368
stackexchange
llm_judgeable_groundtruth_similarity
531368
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: i'm doing a regression using EViews, but one of eight independent variable has the same values for all sample and shows near singular matrix error, my supervisor said that it still could be done as she said that a lot a research (especially likert scale) has the same value. Here are the data As you can see the data on the 8th column has the same value. I search the internet but couldn't find a solution, this is my first time doing a regression analysis so maybe i searched the wrong keyword. if really appreciate if someone could help me Thank you Now provide the response and nothing else.
If you think of the "independent" variables as "predictors," then it does no good to include a "predictor" that doesn't differ among cases. That particular "predictor" can't help predict anything, and you can't get a regression coefficient for it. The Wikipedia entry on simple linear regression , for a single predictor and single outcome, shows the simplest case. The formula for calculating the regression coefficient $\widehat\beta$ is: $$\widehat\beta = \frac{ \sum_{i=1}^n (x_i - \bar{x})(y_i - \bar{y}) }{ \sum_{i=1}^n (x_i - \bar{x})^2 } \\[6pt] $$ where $x_i$ are the individual predictor values and $\bar x$ is their mean. If all of the $x_i$ values are the same, then $(x_i - \bar{x})=0$ for all cases. Both the numerator and denominator are thus 0; there is no uniquely defined value $\widehat\beta$ . It doesn't get any better in the multiple-regression (multiple-predictor) context. For multiple regression to work, the columns of the design matrix need to be linearly independent. That is, you can't be able to write any column as a weighted sum or the other columns, or else you have perfect multicollinearity and an undefined solution. For numeric values like yours, the design matrix is the matrix or predictor values along with a column of 1s representing the model intercept. If one predictor is constant, it thus is a constant multiple of that intercept column in the design matrix. That perfect multicollinearity prevents finding a unique solution to the regression if you include an intercept in the model. Your sense is correct and, based on what you've presented here, your supervisor is incorrect. Remove such constant "predictors" from your model. If your supervisor insists on claiming that it needs to be included, then in return insist that your supervisor show how to do that in a way that's consistent with the expectations in your field of study. Perhaps there are accepted ways in that field to choose one of the infinite possible solutions in a situation like this, but be sure that you and your supervisor know exactly what you are doing if you go down that route.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/531368', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/326038/']}
jdg_77369
stackexchange
llm_judgeable_groundtruth_similarity
4202288
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 $a$ and $b$ are real and satisfy the relation $4a^2 + 3b^2 - 4ab - 4b + 2 \le 0$ then calculate the determinant of $$\begin{pmatrix} 4 & 4 & 4 \\ a & b & 2 \\ a^2 & b^2& 4\end{pmatrix}$$ $2$ $3$ $-3$ $0$ My attempt: I first calculated the determinant in terms of $a$ and $b$ : $$\Delta = 4(b-a)(2-a)(2-b)$$ But I don't know how to use the relation given in the question to find a numerical value for $\Delta$ . Any hints would be appreciated. Now provide the response and nothing else.
One way of viewing them is as one-forms. See Help understanding expression for Derivative of a function for the multivariable situation. The idea is that (in single variable) given a differentiable function $f:\Bbb{R}\to\Bbb{R}$ , and a point $a\in\Bbb{R}$ , the quantity $f'(a)\in\Bbb{R}$ is what we geometrically think of as the slope at the point $(a,f(a))$ of the graph of $f$ (in fact logically speaking, this ought to be a definition for the term "slope at a point"). Now, what I'm suggesting to you is rather than thinking of the single number $f'(a)$ , we consider the linear transformation $L_{f,a}:\Bbb{R}\to\Bbb{R}$ defined as \begin{align}L_{f,a}(h):=f'(a)\cdot h\end{align} What is the significance of this linear transformation? By rewriting the definition of the derivative $f'(a)=\lim\limits_{h\to 0}\frac{f(a+h)-f(a)}{h}$ , we get \begin{align}f(a+h)-f(a)&=L_{f,a}(h)+R_a(h)\end{align} where $R_a(h)$ is the "remainder" term which is "small" in the sense that $\lim\limits_{h\to 0}\frac{R_a(h)}{h}=0$ . Now, traditional notation demands that the LHS be denoted as $\Delta f_a(h)$ and $L_{f,a}$ be denoted as $Df_a(h)$ or $df_a(h)$ . Therefore, we get the very memorable equation \begin{align}\Delta f_a(h)&=df_a(h)+R_a(h)\end{align} "actual change in function at a point equals a linear term plus a small error term". Note that this is nothing but a simple algebraic rewriting of the definition of a derivative, but it is very powerful because the same idea can be used in higher dimensions: we're shifting our primary perspective from slopes to linear approximation simply because linear algebra is a very well-studied and powerful tool for systematically organizing all this information (in one dimension, linear algebra is almost trivial which is why we don't emphasize this perspective). So, now for a differentiable function $f:\Bbb{R}\to\Bbb{R}$ , rather than considering the derivative $f':\Bbb{R}\to\Bbb{R}$ , we instead consider the object $df$ , which for every point $a\in\Bbb{R}$ gives a linear transformation $df_a:\Bbb{R}\to\Bbb{R}$ , where the interpretation is that for a "displacement vector from the point $a$ " $h\in\Bbb{R}$ , $df_a(h)$ is the linear approximation of the actual error $\Delta f_a(h)$ . That's all there is to the definition of $df$ ; it's just a simple re-interpretation of the function $f'$ . Next, what does $dx$ mean? Well, now we understand that $d$ acts on differentiable functions, so what function is $x$ ? Well, it is tradition to use $x:\Bbb{R}\to\Bbb{R}$ to mean the identity function, i.e for any point $a\in\Bbb{R}$ , we set $x(a):=\text{id}_{\Bbb{R}}(a):=a$ . Now, it is easily verified that $dx_a=\text{id}_{\Bbb{R}}$ (all this is saying is that $x'(a)=1$ for all $a$ ). Therefore, \begin{align}df_a(h)&=f'(a)\cdot h=f'(a)\cdot dx_a(h)= (f'dx)_a(h)\end{align} This is why if we don't write the displacement $h$ anywhere, nor the point of evaluation of derivative $a$ , we end up with $df=f'\,dx$ , where now both sides have a proper definition. Note: Throughout this answer, since we're only dealing with functions defined on vector spaces such as $\Bbb{R}$ (or in my other linked answer, $\Bbb{R}^n$ ), I have avoided a careful distinction between the vector space and its tangent space at a point. But hopefully, with this introduction, future encounters with $df_a$ being defined at the tangent space at $a$ wouldn't seem so random.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4202288', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/794439/']}
jdg_77370
stackexchange
llm_judgeable_groundtruth_similarity
13446842
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 build a Java application that allows users to use Git based repositories. I was able to do this from the command-line, using the following commands: git init<create some files>git add .git commitgit remote add <remote repository name> <remote repository URI>git push -u <remote repository name> master This allowed me to create, add and commit content to my local repository and push contents to the remote repository. I am now trying to do the same thing in my Java code, using JGit. I was able to easily do git init, add and commit using JGit API. Repository localRepo = new FileRepository(localPath);this.git = new Git(localRepo); localRepo.create(); git.add().addFilePattern(".").call();git.commit().setMessage("test message").call(); Again, all of this works fine. I couldn't find any example or equivalent code for git remote add and git push . I did look at this SO question . testPush() fails with the error message TransportException: origin not found . In the other examples I've seen https://gist.github.com/2487157 do git clone before git push and I don't understand why that's necessary. Any pointers to how I can do this will be appreciated. Now provide the response and nothing else.
You will find in org.eclipse.jgit.test all the example you need: RemoteconfigTest.java uses Config : config.setString("remote", "origin", "pushurl", "short:project.git");config.setString("url", "https://server/repos/", "name", "short:");RemoteConfig rc = new RemoteConfig(config, "origin");assertFalse(rc.getPushURIs().isEmpty());assertEquals("short:project.git", rc.getPushURIs().get(0).toASCIIString()); PushCommandTest.java illustrates various push scenario, using RemoteConfig . See testTrackingUpdate() for a complete example pushing an tracking a remote branch. Extracts: String trackingBranch = "refs/remotes/" + remote + "/master";RefUpdate trackingBranchRefUpdate = db.updateRef(trackingBranch);trackingBranchRefUpdate.setNewObjectId(commit1.getId());trackingBranchRefUpdate.update();URIish uri = new URIish(db2.getDirectory().toURI().toURL());remoteConfig.addURI(uri);remoteConfig.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/" + remote + "/*"));remoteConfig.update(config);config.save();RevCommit commit2 = git.commit().setMessage("Commit to push").call();RefSpec spec = new RefSpec(branch + ":" + branch);Iterable<PushResult> resultIterable = git.push().setRemote(remote) .setRefSpecs(spec).call();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13446842', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/476077/']}
jdg_77371
stackexchange
llm_judgeable_groundtruth_similarity
1241639
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How do I prove that $\lim_{(x,y)\to (0,0)} \frac{x^2 y }{x^2 + y^2} = 0$? I can prove this by notifying $x=rcos\theta$ and $y=rsin\theta$, but I remember that it could also be proven by squeeze theorem. How do I prove this using squeeze theorem? Now provide the response and nothing else.
$$0\le\left|\frac{x^2y}{x^2+y^2}\right|\le \left|\frac{x^2y}{x^2}\right|=|y|\xrightarrow[(x,y)\to (0,0)]{}0$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1241639', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/116887/']}
jdg_77372
stackexchange
llm_judgeable_groundtruth_similarity
390600
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 want to believe that this has an easy answer, but I’ve never considered it before and can’t seem to answer it now either. Does every infinite-dimensional Banach space admit a locally convex vector topology that is strictly coarser than the norm topology and strictly finer than the weak topology? If this is non-trivial and constructive, I’d be much obliged if an explicit example (or reference) is provided. Now provide the response and nothing else.
In a normed space, every weak neighborhood of zero contains a finite codimensional subspace. Consequently, if you have a weak to norm continuous linear operator between normed spaces, then the operator has finite rank. Suppose that $X$ is an infinite dimensional Banach space. Take a closed subspace $Y$ that has infinite dimension and infinite codimension, and let $Q:X\to X/Y$ be the quotient map. Let $\tau$ be the topology on $X$ generated by $X^*$ and the seminorm $|x| = \|Qx\|$ . Obviously $\tau$ is a locally convex topology between the norm and weak topologies on $X$ . On $Y$ , the topology $\tau$ is the weak topology, so $\tau$ is not the norm topology on $X$ . OTOH, $Q$ is $\tau $ to norm continuous, so by my opening remark, $\tau$ cannot be the weak topology on $X$ .
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/390600', 'https://mathoverflow.net', 'https://mathoverflow.net/users/166628/']}
jdg_77373
stackexchange
llm_judgeable_groundtruth_similarity
21237907
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 downloading JSON data from a very slow server. It takes about a minute to get a resoonse from the server. I use AFNetworking library and my code throws "The request timed out" error: NSString *urlString = [NSString stringWithFormat:@"%@/account.do?JSON&sysparm_action=getRecords",baseUrlString]; NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"]; NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"]; [manager setRequestSerializer:[AFHTTPRequestSerializer serializer]]; [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password]; [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); [self parseJsonWithAccountsData:responseObject]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", operation.responseString); [self performSelectorOnMainThread:@selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES]; }]; Didn't find a way to set a timeout for AFHTTPRequestOperationManager . How can I do it? Now provide the response and nothing else.
Method 1. I think the best way is to subclass AFHTTPRequestSerializer and override - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters like this: - (NSMutableURLRequest *)requestWithMethod:(NSString *)method URLString:(NSString *)URLString parameters:(NSDictionary *)parameters{ NSMutableURLRequest *request = [super requestWithMethod:method URLString:URLString parameters:parameters]; [request setTimeoutInterval:YOUR_TIMEOUT_INTERVAL_HERE]; return request;} and then NSString *urlString = [NSString stringWithFormat:@"%@/account.do?JSON&sysparm_action=getRecords",baseUrlString]; NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"]; NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"]; [manager setRequestSerializer:YOUR_NEW_REQUEST_SERIALIZER_HERE]; [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password]; [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); [self parseJsonWithAccountsData:responseObject]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", operation.responseString); [self performSelectorOnMainThread:@selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES]; }]; Method 2 NSString *urlString = [NSString stringWithFormat:@"%@/account.do?JSON&sysparm_action=getRecords",baseUrlString];NSString *login = [[NSUserDefaults standardUserDefaults] objectForKey:@"login"];NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];[manager setRequestSerializer:[AFHTTPRequestSerializer serializer]];[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:login password:password];NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:urlString relativeToURL:manager.baseURL] absoluteString] parameters:nil];[request setTimeoutInterval:YOUR_TIMEOUT_INTERVAL_HERE];AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"JSON: %@", responseObject); [self parseJsonWithAccountsData:responseObject];} failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", operation.responseString); [self performSelectorOnMainThread:@selector(failedWithContactsDownload) withObject:nil waitUntilDone:YES];}];[manager.operationQueue addOperation:operation];
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21237907', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/952671/']}
jdg_77374
stackexchange
llm_judgeable_groundtruth_similarity
52859515
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 simple demo has an error https://docs.nestjs.com/techniques/http-module import { Get, Controller, HttpService } from '@nestjs/common';import { AxiosResponse } from 'axios'import { Observable } from 'rxjs'@Controller()export class AppController { constructor(private readonly http: HttpService) {} @Get() root(): Observable<AxiosResponse<any>> { return this.http.get('https://api.github.com/users/januwA'); }} What should I do? [Nest] 7356 - 2018-10-18 00:08:59 [ExceptionsHandler] Converting circular structure to JSON +9852msTypeError: Converting circular structure to JSON at JSON.stringify (<anonymous>) nest icommon version : 5.1.0core version : 5.1.0 Now provide the response and nothing else.
You cannot just return the whole AxiosResponse object because it cannot be serialized to JSON. You most likely want to get the response data like this: @Get()root() { return this.http.get('https://api.github.com/users/januwA').pipe( map(response => response.data) );} or alternatively using Promises : @Get()async root() { const response = await this.http.get('https://api.github.com/users/januwA').toPromise(); return response.data;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/52859515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9874407/']}
jdg_77375
stackexchange
llm_judgeable_groundtruth_similarity
66996319
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 building a simple .NET Core console application that will read in basic options from the command line, then execute and terminate without user interaction. I'd like to take advantage of DI, so that lead me to using the .NET Core generic host. All of the examples I've found that build a console app create a class that either implements IHostedService or extends BackgroundService. That class then gets added to the service container via AddHostedService and starts the application's work via StartAsync or ExecuteAsync. However, it seems that in all of these examples, they are implemementing a background service or some other application that runs in a loop or waits for requests until it gets shut down by the OS or receives some request to terminate. What if I just want an app that starts, does its thing, then exits? For example: Program.cs: namespace MyApp{ using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; public static class Program { public static async Task Main(string[] args) { await CreateHostBuilder(args).RunConsoleAsync(); } private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseConsoleLifetime() .ConfigureLogging(builder => builder.SetMinimumLevel(LogLevel.Warning)) .ConfigureServices((hostContext, services) => { services.Configure<MyServiceOptions>(hostContext.Configuration); services.AddHostedService<MyService>(); services.AddSingleton(Console.Out); }); }} MyServiceOptions.cs: namespace MyApp{ public class MyServiceOptions { public int OpCode { get; set; } public int Operand { get; set; } }} MyService.cs: namespace MyApp{ using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; public class MyService : IHostedService { private readonly MyServiceOptions _options; private readonly TextWriter _outputWriter; public MyService(TextWriter outputWriter, IOptions<MyServiceOptions> options) { _options = options.Value; _outputWriter = outputWriter; } public async Task StartAsync(CancellationToken cancellationToken) { _outputWriter.WriteLine("Starting work"); DoOperation(_options.OpCode, _options.Operand); _outputWriter.WriteLine("Work complete"); } public async Task StopAsync(CancellationToken cancellationToken) { _outputWriter.WriteLine("StopAsync"); } protected void DoOperation(int opCode, int operand) { _outputWriter.WriteLine("Doing {0} to {1}...", opCode, operand); // Do work that might take awhile } }} This code compiles and runs just fine, producing the following output: Starting workDoing 1 to 2...Work complete However, after that, the application will just sit there waiting until I press Ctrl+C. I know I could force the application to shutdown after the work is complete, but at this point, I feel like I'm not using IHostedService correctly. It seems as though it's designed for recurring background processes, and not simple console applications like this. However, in an actual application where DoOperation might take 20-30 minutes, I would like to take advantage of the StopAsync method to do cleanup before terminating. I also know I could create the service container myself and all that, but the .NET Core generic host already does a lot of stuff I would want to do anyway. It seems to be the right way to write console applications, but without adding a hosted service that kicks off the actual work, how do I get the app to actually do anything? Now provide the response and nothing else.
Instead of a hosted service, I would recommend the following; using (var host = CreateHostBuilder(args).Build()){ await host.StartAsync(); var lifetime = host.Services.GetRequiredService<IHostApplicationLifetime>(); // do work here / get your work service ... lifetime.StopApplication(); await host.WaitForShutdownAsync();}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/66996319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2820102/']}
jdg_77376
stackexchange
llm_judgeable_groundtruth_similarity
16920700
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 generate dynamically a geoJSON with a variable number of polygons. Example for 2 polygons: { "type": "FeatureCollection", "features": [ {"geometry": { "type": "GeometryCollection", "geometries": [ { "type": "Polygon", "coordinates": [[11.0878902207, 45.1602390564], [0.8251953125, 41.0986328125], [7.63671875, 48.96484375], [15.01953125, 48.1298828125]] }, { "type": "Polygon", "coordinates": [[11.0878902207, 45.1602390564], [14.931640625, 40.9228515625], [11.0878902207, 45.1602390564]] } ] }, "type": "Feature", "properties": {}} ]} I have a function which gives me the list of coordinates for each polygon, so I can create a list of polygons, so I am able to build the geoJSON iterating it with a for loop. The problem is that I don't see how to do it easily (I thought for example in returning the list as a string, but building the geoJSON as a string looks like a bad idea). I have been suggested this very pythonic idea: geo_json = [ {"type": "Feature",, "geometry": { "type": "Point", "coordinates": [lon, lat] }} for lon, lat in zip(ListOfLong,ListOfLat) ] But since I am adding a variable number of Polygons instead of a list of points, this solutions does not seem suitable. Or at least I don't know how to adapt it. I could build it as a string, but I'd like to do it in a smarter way. Any idea? Now provide the response and nothing else.
If you can get the libraries installed, django has some good tools for dealing with geometry objects, and these objects have a geojson attribute, giving you access to the GeoJSON representation of the object: https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/ >>> from django.contrib.gis.geos import Polygon, Point, MultiPoint, GeometryCollection>>>>>> poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )>>> gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly)>>> gc.geojsonu'{ "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [ 0.0, 0.0 ] }, { "type": "MultiPoint", "coordinates": [ [ 0.0, 0.0 ], [ 1.0, 1.0 ] ] }, { "type": "Polygon", "coordinates": [ [ [ 0.0, 0.0 ], [ 0.0, 1.0 ], [ 1.0, 1.0 ], [ 0.0, 0.0 ] ] ] } ] }' GeometryCollection can also accept a list of geometry objects: >>> polys = []>>> for i in range(5):... poly = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )... polys.append(poly)...>>> gc = GeometryCollection(polys) Update 2019 : shapely with shapely-geojson is now available can may be more easily to introduce as it doesn't required django.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16920700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/808091/']}
jdg_77377
stackexchange
llm_judgeable_groundtruth_similarity
5587264
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 coworker who is actively trying to convince me that I should not use do..end and instead use curly braces for defining multiline blocks in Ruby. I'm firmly in the camp of only using curly braces for short one-liners and do..end for everything else. But I thought I would reach out to the greater community to get some resolution. So which is it, and why? (Example of some shoulda code) context do setup { do_some_setup() } should "do somthing" do # some more code... endend or context { setup { do_some_setup() } should("do somthing") { # some more code... }} Personally, just looking at the above answers the question for me, but I wanted to open this up to the greater community. Now provide the response and nothing else.
The general convention is to use do..end for multi-line blocks and curly braces for single line blocks, but there is also a difference between the two that can be illustrated with this example: puts [1,2,3].map{ |k| k+1 }234=> nilputs [1,2,3].map do |k| k+1; end#<Enumerator:0x0000010a06d140>=> nil This means that {} has a higher precedence than do..end, so keep that in mind when deciding what you want to use. One more example to keep in mind while you develop your preferences. The following code: task :rake => pre_rake_task do somethingend really means: task(:rake => pre_rake_task){ something } And this code: task :rake => pre_rake_task { something} really means: task :rake => (pre_rake_task { something }) So to get the actual definition that you want, with curly braces, you must do: task(:rake => pre_rake_task) { something} Maybe using braces for parameters is something you want to do anyways, but if you don't it's probably best to use do..end in these cases to avoid this confusion.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5587264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32384/']}
jdg_77378
stackexchange
llm_judgeable_groundtruth_similarity
2371178
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If we have a class that inherits from multiple interfaces, and the interfaces have methods with the same name, how can we implement these methods in my class? How can we specify which method of which interface is implemented? Now provide the response and nothing else.
By implementing the interface explicitly, like this: public interface ITest { void Test();}public interface ITest2 { void Test();}public class Dual : ITest, ITest2{ void ITest.Test() { Console.WriteLine("ITest.Test"); } void ITest2.Test() { Console.WriteLine("ITest2.Test"); }} When using explicit interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type. var dual = new Dual();// Call the ITest.Test() function by first assigning to an explicitly typed variableITest test = dual;test.Test();// Call the ITest2.Test() function by using a type cast.((ITest2)dual).Test();
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2371178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191997/']}
jdg_77379
stackexchange
llm_judgeable_groundtruth_similarity
15792855
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create a 300px by 300 px div box that moves a few pixels when the user has their mouse on the box. The only thing is when the div hits the end of the browser size I want it to to start moving the other way and not make the window scroll. Any help would be greatly appreciated. <div style="left:300px; top:300px; width:300px; height:300px; background:blue;></div> This is oleg's code that I am having trouble running in firefox, am i doing something wrong? <html><head><script>window.onload = function () {var speed = 10, // the box will move by 10 pixels on every stepdirection = 1, // 1 = move right; -1 = move leftboxElement = document.getElementById('theIdOfTheBox');if (boxElement) { boxElement.addEventListener('mouseover', function () { // Calculate and store some of the box coordinates: var boxLeftPos = boxElement.offsetLeft, boxRightPos = boxLeftPos + boxElement.offsetWidth; // When right side of the box goes too far - change direction: if (boxRightPos > document.body.offsetWidth) { direction = -1; } // When left side of the box goes too far - change direction: if (boxLeftPos < 0) { direction = 1; } // Recalculate position: boxElement.style.left = (boxLeftPos + speed * direction) + 'px'; }); }};</script><style>#theIdOfTheBox {position: absolute;left:100px;top:100px;width:300px;height:300px;background:blue;}</style></head><body><div id="theIdOfTheBox">box</div></body></html> Now provide the response and nothing else.
Start by creating a couple of variable that keep track of speed and direction: var speed = 10, // the box will move by 10 pixels on every step direction = 1; // 1 moves in the positive direction; -1 vice versa Then grab a reference to your box and attach an event handler to its "mouseover" event: var boxElement = document.getElementById('theIdOfTheBox');if (boxElement) { boxElement.addEventListener('mouseover', function () { // Calculate and store some of the box coordinates: var boxLeftPos = boxElement.offsetLeft, boxRightPos = boxLeftPos + boxElement.offsetWidth; // When right side of the box goes too far - change direction: if (boxRightPos > document.body.offsetWidth) { direction = -1; } // When left side of the box goes too far - change direction: if (boxLeftPos < 0) { direction = 1; } // Recalculate position: boxElement.style.left = (boxLeftPos + speed * direction) + 'px'; });} All done, here's a jsfiddle for you to play around with. Mind, however, the position: absolute; in the CSS and the fact that you need to wait for the DOM to load to be able to safely perform the getElementById operation. If you want to avoid usage of offsets, you may want to parse and manipulate margins or padding of the box instead. Animation If you want to animate the movement of your box, you can try CSS animations. Just add the following to the style declaration of your box in the CSS: -webkit-transition: left 0.3s 0.1s ease-out; The above code will animate any changes in left property in webkit browsers. You can add other vendor prefixes (and none for compatibility with future releases) to enable animation in other browsers that support it. EDIT Regarding your comment with running the script on browser launch: First of all make sure to wrap the JavaScript code in <script></script> tags if you are embedding it in an HTML page. You can run a validator (e.g. validator.w3.org ) to ensure you have a correct document structure. Secondly, place the code inside those tags as close as possible to the end of the body of your document, i.e. </body> . You can also wrap the entire JavaScript code in a function that will be executed once the document is fully loaded. This way the code can be placed (or remotely required) from the document head (but why would you want that?). Here's how it's done: window.addEventListener('load', function () { // ... the code goes here}); A (non-recommended) alternative is: window.onload = function () { // ... the code goes here}; Or (please avoid this, it's just an example) in HTML: <body onload="someFunction();"> So, the resulting code might look like: <!DOCTYPE html><html><head> <style> /* ... the CSS goes here */ </style></head><body> <div id="box">I'm a box.</div> <script> // ... the JavaScript code goes here </script></body></html> Special note regarding Internet Explorer There's no support for addEventListener in Internet Explorer below version 9. You should use attachEvent instead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15792855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2230364/']}
jdg_77380
stackexchange
llm_judgeable_groundtruth_similarity
148398
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 SQL Server 2005, are there any disadvantages to making all character fields nvarchar(MAX) rather than specifying a length explicitly, e.g. nvarchar(255)? (Apart from the obvious one that you aren't able to limit the field length at the database level) Now provide the response and nothing else.
Same question was asked on MSDN Forums: Varchar(max) vs Varchar(255) From the original post (much more information there): When you store data to a VARCHAR(N) column, the values are physically stored in the same way. But when you store it to a VARCHAR(MAX) column, behind the screen the data is handled as a TEXT value. So there is some additional processing needed when dealing with a VARCHAR(MAX) value. (only if the size exceeds 8000) VARCHAR(MAX) or NVARCHAR(MAX) is considered as a 'large value type'. Large value types are usually stored 'out of row'. It means that the data row will have a pointer to another location where the 'large value' is stored...
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/148398', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21379/']}
jdg_77381
stackexchange
llm_judgeable_groundtruth_similarity
18158094
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 three classes structured like this: #include <iostream>using namespace std;class Keyword{ public: virtual float GetValue() = 0;};class CharacterKeyword : public Keyword{ public: virtual float GetValue(){return _value;} private: float _value;};class MeasurementKeyword : public Keyword{ public: virtual float GetValue(){return _value;} private: float _value;};class AddressType : public CharacterKeyword, public MeasurementKeyword{ private: float address; float addresExt;};int main(){ AddressType *a = new AddressType(); a->GetValue(); return 0;} I am getting the following: In function ‘int main()’: error: request for member ‘GetValue’ is ambiguous error: candidates are: virtual float Keyword::GetValue() error: virtual float MeasurementKeyword::GetValue() error: virtual float CharacterKeyword::GetValue() I have done some reading into multiple inheritance and I know that it has a lot of pitfalls - this being one of them. I need my class structure to be like this so I was wondering if there was a way that I could fix this using templates? Update After reading your comments, my original thought was that maybe I can just delineate between an AddressType that is a CharacterKeyword and an AddressType that is a MeasurementKeyword by templating the AddressType . And using it as such in the updated code. OR I can just specify the namespace of the member that I would like. Since the templated way has not been mentioned yet as an answer, is it a bad fix? Should I just specify the namespace of the member I want? template <class T>class AddressType : public T{ private: float address; float addresExt;};int main(){ AddressType<MeasurementKeyword> *a = new AddressType<MeasurementKeyword>(); a->GetValue(); return 0;} Now provide the response and nothing else.
This is because of a diamond inheritance pattern , to resolve the error you can specify the specific namespace you want the member from like. paddressType->MeasurementKeyword::GetValue() or paddressType->CharacterKeyword::GetValue() Basically your AddressType class has access to the GetValue members from both the classes it inherits from and can't choose one (call is ambiguous). The scope resolution operator ( :: ) helps specify which one you actually want. You haven't said what you actually want this code to do so I'll just say that generally complex inheritance patterns are not conducive to creating readable code, rethink what you actually want.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18158094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1052906/']}
jdg_77382
stackexchange
llm_judgeable_groundtruth_similarity
20066858
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my current project I've run into the need to turn various monads into their transformer counterparts e.g. stateT :: Monad m => State s a -> StateT s m astateT stf = StateT $ return . runState stf It's trivial to write these utility functions for the monads I need, but I was wondering if there already exists a library that contains this functionality for the standard monads and maybe a typeclass that abstracts this sort of transformation. Something like class (Monad f, MonadTrans t) => LiftTrans f t | f -> t where liftT :: Monad m => f a -> t m a ("lift" is probably the wrong term to use here, but I wasn't sure what else to call it.) Now provide the response and nothing else.
Check out function hoist from the mmorph package. Its signature is hoist :: Monad m => (forall a. m a -> n a) -> t m b -> t n b Meaning that it can change the base monad underlying a transformer. Now, in the trasformers package, many "basic" monads are implemented as transformers applied to the Identity monad, like this: type State s = StateT s Identity Therefore, we can define the following function (taken form the Generalizing base monads section of the mmorph documentation): import Data.Functor.Identitygeneralize :: (Monad m) => Identity a -> m ageneralize m = return (runIdentity m) and combine it with hoist: hoist generalize :: (Monad m, MFunctor t) => t Identity b -> t m b This method won't work for simple monads which are not defined as transformers applied to Identity , like the Maybe and Either monads. You are stuck with hoistMaybe and hoistEither for these.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20066858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/572606/']}
jdg_77383
stackexchange
llm_judgeable_groundtruth_similarity
370310
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 JPanel full of JTextFields... for (int i=0; i<maxPoints; i++) { JTextField textField = new JTextField(); points.add(textField);} How do I later get the JTextFields in that JPanel? Like if I want their values with TextField.getText(); Thanks Now provide the response and nothing else.
Well bear in mind they didn't get there by them selves ( I think a read some questions about dynamically creating these panels at runtime ) In the answers posted there, someone said you should kept reference to those textfields in an array. That's exactly what you need here: List<JTextField> list = new ArrayLists<JTextField>();// your code...for (int i=0; i<maxPoints; i++) { JTextField textField = new JTextField(); points.add(textField); list.add( textField ); // keep a reference to those fields.} // Later for( JTextField f : list ) { System.out.println( f.getText() ) ;} Wasn't that easy? Just remember to keep these kinds of artifacts ( list ) as private as possible. They are for your control only, I don't think they belong to the interface. Let's say you want to get the array of texts, instead of public List<JTextField> getFields(); You should consider: public List<String> getTexts(); // get them from the textfields ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/370310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/51518/']}
jdg_77384
stackexchange
llm_judgeable_groundtruth_similarity
13773
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a command that will output a list of values that correspond to the current parameter values manually set on a particular Manipulate interface. For example, lets say I create an interactive interface using this code: Manipulate[ Plot[ A*Sin[f*t + p], {t, 0, 2 Pi}, PlotRange -> {{0, 2 Pi}, {-1, 1}}], {A, 0, 1}, {f, 1, 10}, {p, 0, 2 Pi}] Then suppose I use the Manipulate interface to set the parameters to some values I like as in the instance shown in the this screen cap: What I would like to do now is input some command that will output these parameter values that the interface is currently set to (in this case, A = .5, f = 6, p = 1.4). Ideally, I would like a List in a new cell of the form {0.5, 6, 1.4} Perhaps some kind of Dynamic automatic updating feature would be nice too. This will allow me to continue being lazy and not have to enter these values individually when I refer to them in later code. Thanks to anyone who helps! Now provide the response and nothing else.
Perhaps the simplest way is to introduce a global variable storing the Manipulate variables: Manipulate[ global = {A, f, p}; Plot[A*Sin[f*t + p], {t, 0, 2 Pi}, PlotRange -> {{0, 2 Pi}, {-1, 1}}], {A, 0, 1}, {f, 1, 10}, {p, 0, 2 Pi}] From now on, we can query global in a different cell any time. If wrapped into Dynamic , it will be updated as the Manipulate is manipulated. Dynamic@global
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/13773', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/874/']}
jdg_77385
stackexchange
llm_judgeable_groundtruth_similarity
22383345
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Should ng-click work with img tag ? <img ng-src="img" ng-click="openNewWindow(url)/> myFunction is defined in controller and is $scope available … Nothing gets called; any ideas? (I would like to open a new tab/window when image is clicked, but I don't even get into my function) Thanks for any info EDIT I probably rushed myself when first asking this question. I know now why it doesn't work in my case: I am manipulating images with jQuery for some kind a 'gallery' effect … (if anyone has an idea how to do that in AngularJS please bring it on). This is the html I am talking about: <div class="commercial-container"> <img class="commercial" ng-src="pathToImageOrImageVar" ng-click="openNewWindow(urlToOpen)" /> <img class="commercial" ng-src="pathToImageOrImageVar" ng-click="openNewWindow(urlToOpen2)" /> <img class="commercial" ng-src="pathToImageOrImageVar" ng-click="openNewWindow(urlToOpen3)" /> <img class="commercial" ng-src="pathToImageOrImageVar" ng-click="openNewWindow(urlToOpen4)" /></div> And here the jQuery with which I create fade-in/fade-out effect (showing one image, then the next and so on indefinitely) function fadeInLastImg(){ var backImg = $('.commercial-container img:first'); backImg.hide(); backImg.remove(); $('.commercial-container' ).append( backImg ); backImg.fadeIn();}; So my real question is this: How can I get the same behaviour as with my jQuery so that images will be ng-clickable? You can of course provide a better solution (perhaps AngularJS one) for changing images like this if you know one … Thank you Now provide the response and nothing else.
Yes, ng-click works on images. Without further code I can't tell you why yours isn't working, but the code you have pasted will call myFunction in the scope of the controller governing that element. EDIT You definitely don't need to use jQuery for this, and it's not really thinking about it in an "angular" mindset if you do. My suggestion is to make a directive to do this. I've created a plunker with a simple example of what it could look like. Here's a summary: Note: Because animation is important to you, make sure you include the ng-animate src and include it as a dependency in your app module definition. Use the same version of animate as base angular. HTML <script src="http://code.angularjs.org/1.2.13/angular.js"></script> <script src="http://code.angularjs.org/1.2.13/angular-animate.js"></script> Javascript angular.module("gallery", ['ngAnimate']) Now Define a template for your directive: galleryPartial.html <div class="container"> <img ng-src="{{image.url}}" alt="{{image.name}}" ng-repeat="image in images" class="gallery-image fade-animation" ng-click="openInNewWindow($index)" ng-show="nowShowing==$index"></div> This template simply says "I want one image for every item listed in the 'images' array from the scope. The src is should be the url property of the image, and the alt text should be the name. When I click an image, run the openInNewWindow function passing the index of that image in the array. Finally, hide images unless the nowShowing variable is set to their index." Also note the class fade-animation . This could be called anything, but this is the class we'll use to define the animation in CSS later. Next we write the directive itself. It's pretty simple - it just has to use this template, and then define the openInNewWindow function, as well as iterate nowShowing through the array indexes: .directive('galleryExample', function($interval, $window){ return { restrict: 'A', templateUrl: 'galleryPartial.html', scope: { images: '=' }, link: function(scope, element, attributes){ // Initialise the nowshowing variable to show the first image. scope.nowShowing = 0; // Set an interval to show the next image every couple of seconds. $interval(function showNext(){ // Make sure we loop back to the start. if(scope.nowShowing != scope.images.length - 1){ scope.nowShowing ++; } else{ scope.nowShowing = 0; } }, 2000); // Image click behaviour scope.openInNewWindow = function(index){ $window.open(scope.images[index].url); } } };}) You will see I have used an isolate scope to make this directive reusable and to keep things separated nicely. You don't have to do this, but it's good practice. The html for the directive must therefore also pass the images you want to put in the gallery, like so: index.html <body ng-controller="AppController"> <div gallery-example="" images="imageList"></div> </body> So the last bit of javascript we need to write is to populate that images array in the AppController scope. Normally you'd use a service to get a list of images from a server or something, but in this case we'll hard code it: .controller('AppController', function($scope){ $scope.imageList = [ { url: 'http://placekitten.com/200/200', name: 'Kitten 1' }, { url: 'http://placekitten.com/201/201', name: 'Kitten 2' }, { url: 'http://placekitten.com/201/202', name: 'Kitten 3' }, { url: 'http://placekitten.com/201/203', name: 'Kitten 4' } ]}) Finally, styling. This will also define the animation (note the use of ng-hide classes etc). I strongly recommend you read up on this here as it is too big a subject to cover in this (already long!) answer: .fade-animation.ng-hide-add,.fade-animation.ng-hide-remove { -webkit-transition:0.5s linear all; -moz-transition: 0.5s linear all; -o-transition: 0.5s linear all; transition:0.5s linear all; display:block !important; opacity:1;} This is your end result
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22383345', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1524316/']}
jdg_77386
stackexchange
llm_judgeable_groundtruth_similarity
434985
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 am thinking of using pfsense on my ubuntu server box. I'd virtualise pfsense with virtualbox, and have it route and firewall all traffic both on and destined to my server as well as the the rest of the LAN. However, I've heard that using pfsense on anything but a dedicated box poses a security risk. Why is this, and is this really an issue? Now provide the response and nothing else.
Theo and others can make claims along those lines, but history suggests it's not a significant concern. Security researchers have been looking for vulnerabilities in hypervisors for years, and by and large they've escaped unscathed from at least major repeated vulnerabilities. Not entirely, you'll have to patch your hypervisor as needed where you generally never have to patch physical hardware for security reasons, but there really hasn't proven to be a significant difference in practice. It's beyond a home networking question in general. There are numerous critical production pfSense installs running in hypervisors, largely ESX. We have 4 colo datacenters on the *.pfsense.org hosting infrastructure that strictly run virtual firewalls. I like it because we can scale way up on CPU power, RAM, etc. as needed without dedicating expensive servers to firewalls, and based on history I'm not concerned about the security of the hypervisor (but keep an eye on new developments). You do need to take care to ensure the host OS of your hypervisor cannot bind IPs to the NIC that goes to your unfiltered Internet connectivity. That's the significant risk in running your edge firewalls as VMs, it's easier to screw up the networking on a hypervisor than it is to plug physical cables into the wrong place.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/434985', 'https://serverfault.com', 'https://serverfault.com/users/-1/']}
jdg_77387
stackexchange
llm_judgeable_groundtruth_similarity
49515325
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to open dev menu or reload app without shaking the app? AndroidWireless over wifi so no usb cableWindows 10 Hot reload or Live reload is not good enough and my arm hurts :) Now provide the response and nothing else.
for android :in your package.json add following lines in scripts "reload":"adb shell input keyevent 82 && adb shell input keyevent 66 && adb shell input keyevent 66", "devmenu":"adb shell input keyevent 82", "debug":"adb shell input keyevent 82 && adb shell input keyevent 61 && adb shell input keyevent 66 && adb shell input keyevent 66" now you can run npm run devmenu to open shake menu in android,and reload to reload the app, and debug to connect to remote debugger. for ios : you can make a button for it somewhere in app, and let this thing only be shown when app is in dev mode. import {NativeModules,Platform} from "react-native"renderDevMenuTouchable = () => { if(__DEV__ && Platform.OS == "ios" ){ return ( <TouchableOpacity style={styles.touchableDebug} onPress={()=>{ NativeModules.DevMenu.reload(); }} onLongPress={()=>{ NativeModules.DevMenu.show(); }} > <View style={{backgroundColor:"red",width:23,height:25}}/> </TouchableOpacity> ) } else { return null; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49515325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4741711/']}
jdg_77388
stackexchange
llm_judgeable_groundtruth_similarity
12641658
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Has anyone else, who's using maps in their iOS 6 apps, noticing extremely high memory use to the point of receiving memory warnings over and over to the point of crashing the app? I've ran the app through instruments and I'm not seeing any leaks and until the map view is created the app consistently runs at around ~3mb Live Bytes. Once the map is created and the tiles are downloaded the Live Bytes jumps up to ~13mb Live Bytes. Then as I move the map around and zoom in and out the Live Bytes continuos to climb until the app crashes at around ~40mb Live Bytes. This is on an iPhone 4 by the way. On an iPod touch it crashes even earlier. I am reusing annotation views properly and nothing is leaking. Is anyone else seeing this same high memory usage with the new iOS 6 maps? Also, does anyone have a solution? Now provide the response and nothing else.
After a lot of playing around and testing different ideas, some of which were mentioned here, the final solution that worked for me was as follows. Instead of creating new MKMapView's as needed in the app, I added an mkMapView property to my AppDelegate and only created it when needed. Once it has been created, it lives in the AppDelegate forever and I reuse that single instance everywhere needed. This really helped in reducing the amount of memory being used as I was previously instantiating a couple different MKMapView's and both were burning through memory pretty quickly. I also found that iOS 6 Maps handles releasing memory very well once a Memory Warning has been received. Yes, it does use up more memory while zooming and panning, but seems to be responding to Memory Warnings appropriately. The last thing I had to do was work on reducing my overall initial memory footprint. I noticed I was starting off way higher than I expected so that was also contributing to the crashes I was receiving related to memory. Once I got the initial footprint down, let MKMapView handle releasing it's memory during Memory Warnings, and made sure I only had 1 instance of MKMapView that I could reuse throughout the app, everything is running fine.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12641658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1050170/']}
jdg_77389
stackexchange
llm_judgeable_groundtruth_similarity
55109497
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: 1. To build a next.js app using styled components it's really easy. You just have to use their _document.js snippet to enable SSR and prevent styles flickering on page load: https://github.com/zeit/next.js/blob/canary/examples/with-styled-components/pages/_document.js 2. To build a next.js app using material-ui is almost as simple. You just have to start with ther project base: https://github.com/mui-org/material-ui/tree/master/examples/nextjs , which has its own implementation on _document.js : https://github.com/mui-org/material-ui/blob/master/examples/nextjs/pages/_document.js 3. Sadly, I couldn't figure out how to "merge" both implementations and get a next app where both styled-components and material-ui components can coexist, SSR and do not flicker on page load. Can you help me?Is there someone on the internet with better abilities than mine whom already solved that problem but I do not know about? Thanks in advance. Now provide the response and nothing else.
Give this a try _document.js import React from 'react';import Document, { Head, Main, NextScript } from 'next/document';import { ServerStyleSheet } from 'styled-components'import { ServerStyleSheets } from '@material-ui/styles';import theme from '../src/theme';class MyDocument extends Document { static async getInitialProps (ctx) { const styledComponentsSheet = new ServerStyleSheet() const materialSheets = new ServerStyleSheets() const originalRenderPage = ctx.renderPage; try { ctx.renderPage = () => originalRenderPage({ enhanceApp: App => props => styledComponentsSheet.collectStyles(materialSheets.collect(<App {...props} />)) }) const initialProps = await Document.getInitialProps(ctx) return { ...initialProps, styles: ( <React.Fragment> {initialProps.styles} {materialSheets.getStyleElement()} {styledComponentsSheet.getStyleElement()} </React.Fragment> ) } } finally { styledComponentsSheet.seal() } } render() { return ( <html lang="en" dir="ltr"> <Head> <meta charSet="utf-8" /> {/* Use minimum-scale=1 to enable GPU rasterization */} <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no" /> {/* PWA primary color */} <meta name="theme-color" content={theme.palette.primary.main} /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> </Head> <body> <Main /> <NextScript /> </body> </html> ); }}export default MyDocument; .babelrc { "presets": ["next/babel"], "plugins": [["styled-components", { "ssr": true }]]} For update check https://github.com/nblthree/nextjs-with-material-ui-and-styled-components
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55109497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1093222/']}
jdg_77390
stackexchange
llm_judgeable_groundtruth_similarity
44149098
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 run a Rails application on AWS/EB that creates a TempFile. Code works correctly when I run in Development, but in Production it fails. Here is the code that is executed: v_index_file_save = Tempfile.new(['index','.lst']) I get the following error message: Errno::EACCES: Permission denied @ dir_s_mkdir - /var/app/current/tmp/1495598860-11267-0001-8597 I found an entry that suggests creating a pre-compile script to change the permissions on my /tmp directory. Here is the scipt: commands: 01_set_tmp_permissions: command: "chmod 0777 /var/app/current/tmp" Deploy seemingly works correctly, but the permissions are not updated on the /tmp/ directory. Any suggestions?? Now provide the response and nothing else.
I was facing the same issue, @MFAL's link in comment helped. I am expanding upon it. When there is an error/incorrect assertion an error is raised inside the promise. This leads to promise rejection. Once rejected done is never called and mocha reports time out.I solved this by writing a .catch block and chaining it with the promise: it('resolves', (done) => { fooAsyncPromise(arg1, arg2).then((res, body) => { expect(res.statusCode).equal(incorrectValue); done(); }).catch(done); }); Other ways as mentioned in the Wietse's blog are: To chain a then(done, done) which handles both resolve and reject of the promise. it('resolves', (done) => { resolvingPromise.then( (result) => { expect(result).to.equal('promise resolved'); }).then(done, done); }); Return a promise: it('resolves', () => { return resolvingPromise.then( (result) => { expect(result).to.equal('promise resolved'); }); }); Use async/wait: it('assertion success', async () => { const result = await resolvingPromise; expect(result).to.equal('promise resolved'); });
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44149098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4259749/']}
jdg_77391
stackexchange
llm_judgeable_groundtruth_similarity
34724320
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a school project, I've to code the C function printf. Things are going pretty well, but there is one question I can't find a good answer to, so here I am. printf("PRINTF(d) \t: %d\n", -2147483648); tells me ( gcc -Werror -Wextra -Wall ): error: format specifies type 'int' but the argument has type 'long' [-Werror,-Wformat] printf("PRINTF(d) \t: %d\n", -2147483648); ~~ ^~~~~~~~~~~ %ld But if I use an int variable, everything is going well: int i;i = -2147483648;printf("%d", i); Why? EDIT: I understood many points, and they were very interesting. Anyway, I guess printf is using the <stdarg.h> librairy and so, va_arg(va_list ap, type) should also return the right type. For %d and %i , obviously the type returned is an int . Does it change anything? Now provide the response and nothing else.
In C, -2147483648 is not an integer constant. 2147483648 is an integer constant, and - is just a unary operator applied to it, yielding a constant expression. The value of 2147483648 does not fit in an int (it's one too large, 2147483647 is typically the largest integer) and thus the integer constant has type long , which causes the problem you observe. If you want to mention the lower limit for an int , either use the macro INT_MIN from <limits.h> (the portable approach) or carefully avoid mentioning 2147483648 : printf("PRINTF(d) \t: %d\n", -1 - 2147483647);
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/34724320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5774090/']}
jdg_77392
stackexchange
llm_judgeable_groundtruth_similarity
1558642
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently, I have upgraded my iPhone SDK OS from version 2.2.1 to 3.0 version. After that, while building my application, I get an error that the provisioning profile has expired. So I created a new provisioning profile. Then I made the distribution of my application with the provisioning profile. But I get an error in iTunes while synchronising my application into an iPhone device. The error message is "The application 'iGVA' was not installed on the iPhone because the entitlements are not valid." I checked the code signing Entitlements contains the correct entitlement plist file. How can this be solved? Now provide the response and nothing else.
Michael's answer above is spot on (or the link he points to is). Here are the steps I had to take to get it to work: Have an ad-hoc certificate for which the device UDID is checked. Install that cert by dragging it onto the XCode icon. On the project, create a distribution configuration and set your build params to the appropriate device | distribution. Right now, we build for Device 3.0 | Distribution. My project did not include an Entitlements.plist file - I had to add it by selecting from the menu File | Add File | IPhone OS | Entitlements, and call the new file Entitlements.plist The new plist file has only one row - set the value of that row to unchecked. In the project build configuration, in the line for Code Signing Entitlements, enter the Entitlements.plist filename as the value. In the Code Signing Identity, select the ad-hoc certificate identity (though I have found that you can also use your distribution certificate identity) NOW BUILD :) Deliver the resulting app file plus the ad-hoc cert to the person who gave you their UDID. Should work :).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1558642', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/174162/']}
jdg_77393
stackexchange
llm_judgeable_groundtruth_similarity
419389
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We currently have 27 open bug reports for markdown rendering and most of those are of the type: The preview shows X, after posting it shows Y where X and Y can be any markdown/html that you can dream-up. One of the latest incarnations was Stack Overflow URLs in double quotes in answers are not replaced by the name of the question where I decided it might be better to lump similar bugs together so after some research I duplicate voted against Editor preview disagrees on link title . After the community review was complete the post was indeed closed as a duplicate. One user voted to leave open, 3 others voted to close. In the comments I was pinged for selecting a not fitting duplicate and the alternative of leaving the bug report simply open might be a better option. I'm not sure now what is better. Do we help the poor SE developer that has to fix all these bugs by linking but not closing such reports or do we start closing against a reasonable duplicate target? In that case which target would that be? Now provide the response and nothing else.
Close as a duplicate if you reasonably believe it's the same bug In general, we should close bug reports as duplicates, if and only if we reasonably believe they are caused by the same bug, not the same class of bugs. The goal with such reports is to get bug reports into the hands of Stack Exchange developers. If we end up closing something that's actually a different bug as a duplicate of some other bug, then it's likely that SE developers will never be informed about the bug, until the developers are all done with fixing that area of the code and someone re-posts a bug report, or otherwise indicates that the original bug report, which was closed as a duplicate, wasn't actually fixed. We don't need to be paranoid about being sure it's the same bug for the duplicate, just use our best judgement. Put yourself in the position of being the developer receiving the bug reports. What would you want to see, assuming the only things which you actually see are questions which are not marked as duplicates and which at some point had a status-review tag? Handling reports of actual CommonMark Markdown rendering differences between preview and server-side It is frustrating that there are so many issues and bug report questions regarding the differences between the two implementations of Markdown conversion which Stack Overflow uses. While it would be nice to have all of these issues organized into one place, that's really the job of tags. For these bugs, we have the markdown-rendering tag. Stack Exchange has consistently stated that they want bugs in separate questions, not rolled up into a single question. The only times they've temporarily wanted organization other than that has been when their developers are actively working on some area of the site and specifically ask for bugs/issues to be included as answers to a question they post for that purpose. When the developers are done, Stack Exchange typically asks for reports to return to the one question per bug format, even that unresolved bugs which were initially reported as an answer each be reposted as a new question, because bug reports as questions is what ties into their ticketing system. The specific example linked in this question appears to be two different bugs, IMO While the two linked questions are related with respect to being issues that deal with URLs, Markdown, and double-quotes, my expectation is that these are actually two separate bugs, because: The two reports show opposite issues with respect to if it's properly rendered in the preview or on the server. The recently closed question is about what happens in the SE specific rendering of SE post/question titles from just a URL, while the duplicate target is about straight CommonMark Markdown conversion to HTML. The parsing for those two things are almost certainly separate, with the URL➞SE post title conversion likely a pre-processing step. I've reopened that question, verified the bug exists , and added the status-review tag to get it into Stack Exchange's ticketing system. However, I believe I've seen a question about that bug in the past, either on MSO or MSE, so it's likely an actual duplicate, or at least a cross-site duplicate. Obviously, if an actual duplicate on MSO is found, then it should be re-closed.
{}
{'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/419389', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/578411/']}
jdg_77394
stackexchange
llm_judgeable_groundtruth_similarity
21572
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: How many bits does a pH or conductivity sensor have? I need a Analog-to-Digital-Converter for these sensors. Thus I need to know how many bits are required in order to purchase the right ADC.I am not sure if 8, 12 or 16 Bit. Can anyone help me out here? EDIT: For now we have HACH sensors connected to the SC100 controller, but I am searching other sensor which do not require a controller. Yes 4-20 mA is the output of the sensors I am looking for as well as the controller from HACH SC100. I don't know the voltage ouput yet. I want to connect the ADC to a Simatic S7-1200. Now provide the response and nothing else.
A circuit that will do what is wanted, or as much as what is wanted as has been revealed, is shown below. This circuit is much simpler than it sounded like it was going to need to be, due to the revelation that the USB power feed could easily accomodate a Schottky "blocking dioe" and still meet the Vout requirement. If this diode had had too high a voltage drop to be acceptable then a circuit withtime delays and current flow direction detection would hav ebeen needed. It can be surprising how much difference a little more information can make to the solution of a problem. Battery feed at top. USB power feed at bottom. USB power is fed to load via Schottky diode D1. Power may be fed via Ja and the LDO regulator or via JB as desired. If feed via JB is used the LDO must survive with external voltage on its output when it has no input. If necessary (depends on LDO) adding another Schottky diode across Ja "pointing upwards" would apply the same voltage across either side of the LDO and minimise quiescent current (in most cases) when USB power is in use.If absolutely necessary another FET could be used to block USB feed from LDO but should not be needed. LDO could be put above Q3 BUT then battery supplies LDO quiescent current at all times = poor. When USB voltage is absent Q3 = P Channel MOSFET is turned on by R4, feeding battery voltage to LDO and thence to Vout. When USB voltage is present Q1 is trurned on by R2/R3 and this turns on Q2 (usually held off by R1) which clamps Q3 gate high turning it off, thus disabling battery feed. USB power feeds via D1 either via Ja and LDo or Jb as above. Battery current when USB connected: Changed R1, R4, R5 to nominal 1 megohm each to reduce battery load when USB in use. A small MOSFET for Q2 and/or some more thinking will reduce required standby current. USB on, Q1 on, About 5 uA via R5 to turn Q2 on. About 5 uA via R4 to turn Q3 off. R4 can probably be 10M if slow response OK. ( At R4 = 10 megohm if gate capcitance on Q3 is say 10 nF then time constant for turn on = RC = 1E7 x 10E-9 =~ 0.1 second. Depending on =FET gate threshold it MAY take a few 10ths of a secind for battery to turn on when USB is unplugged. This could dropout powered cct unless a large enough output cap was provided. At R4 = 1m the time constant is about 10 milliseconds and a "usual" sort of cap on output rail would suffice. Can be "tuned". Q1 on removes voltage from R1. 10 uA quiescent when USB is on =~ 90 mAh/year. This is about 3% of battery pack capacity. Small but annoying. Q1, Q2 = almost any jellybean bipolar. Q3 = P Channel MOSFET. Vthreshold << Vbattery. D1 = Schottky eg 1N5817. LDO to suit. Roll your own LDO with MOSFET and eg TLV431 can have about 100 uA quiescent when running and essentially zero dropout voltage. Can be much lower with lower Iq ref diode. BUT When you can get eg Microchip's VERY nice TC2104 LDO for under 50 cents in 1's, making your own makes less sense. ASdded Oct-2001: The TC2104 seems to have vanished. The LM293x series is widely avail;able - see eg Digikeys listings here Or, here are LDOs with 0.1V or less dropout voltage - Digikey listings quantity 1. Added 9/2015 Kar asked ... why are the BJTs needed? Why not just have a MOSFET and a diode, and that's it? @Kar Good question. The MOSFET solution is a good one but it is slightly more design-demanding than may be apparent, whereas the bipolar solution uses a few more components but is easier to ensure operation ioj all conditions. Tpo use the MOSFET as shown the FET's Vgsth must be chosen to suit. Battery max voltage (assuming his AA cells are Alkaline) is 1.65V (new cells) x 4 = 6.6V. In a few cases even maybe 1.655V so say 6.8V for 4. USB is say 5.3V max when on and 0V when off after any capacitors discharge. But critical here is not USB Vmax but USB_on_min USB_on_min = say 4.8V. Under that condition FET must be off, so FET Vgs = (6.8-4.8) =~~~~ 2V worst case. The FET MUST NOT turn on at Vgs = 2V. Battery min is say 4V and USB low falls to 0V "after a while" so FET must turn on at Vgs = 4V. That puts the FET Vgs_off_max and Vgs_on_min in a fairly narrow 2 to 4V range. That's certainly doable by correct choice of FET - but datasheet must be chacked to ensure that worst case spread lies in the desired range. The designer needs to be aware that design is needed! In the bipolar case the USB Von_min is very easily accommodated by Q1 and if desired full turnoff can occur when V_USB is say 2V so changeover to battery is better defined. So overall, the bipolar addition adds 2 x Q and 4 x R (small but non trivial) for the sake of better flexibility and designability. BUT the MOSFET only solution is a good one as long as the complexity that goes along with the simplicity is properly understood.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/21572', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/6347/']}
jdg_77395
stackexchange
llm_judgeable_groundtruth_similarity
545624
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I make and sell low voltage, mostly digital, retrocomputing expansion boards as a hobby/hustle. I use all through-hole components partly because of the retro aesthetic and partly because I find soldering through-hole relaxing and fun to do. I'm selling enough boards now that I'm feeling like my assembly and soldering process should be optimized. One of the boards has about 30 components on it and if I'm making 10 of them, it can take up a whole Saturday afternoon. Currently I place a part, flip the board in my hand while holding the part, tack one of its pins with the iron while making sure the part is fully inserted and aligned if necessary, lay the board down and solder the rest of the pins, then move on to the next part. I am pretty sure this isn't the best way to do this. Do you have any tips or tool recommendations to help me optimize my board assembly / through-hole soldering process? Thanks! Now provide the response and nothing else.
Insert all the components of the same height. Maybe you have a holder to hold the board steady and off the bench. Put a piece of material (wood, heavy cardboard, foamcore) on the top of the board and flip it. Solder all the parts in and trim the leads. Repeat for taller parts. If you have a 3D printer or a milling machine you can easily make a jig that will hold all the parts in one go. It helps to have the leads bent so that they don't slop around too much. For parts that need to be located very accurately for functional or aesthetic reasons (for example, LEDs or terminal blocks), a more precise jig may be beneficial. If your boards are reasonably small, you can save a lot of work by panelizing them in the design stage. The reduction in handling makes a significant difference. Even having a small number such as 4 in an array helps. Try to keep them together as long as possible, even as far as testing. You will pay more for the boards but everything else is cheaper.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/545624', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/33138/']}
jdg_77396
stackexchange
llm_judgeable_groundtruth_similarity
510213
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What kinds of activities will trigger reflow of web page with DOM? It seems there are different points of view. According to http://www.nczonline.net/blog/2009/02/03/speed-up-your-javascript-part-4/ , it happens When you add or remove a DOM node. When you apply a style dynamically (such as element.style.width="10px"). When you retrieve a measurement that must be calculated, such as accessing offsetWidth, clientHeight, or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE). However, according to http://dev.opera.com/articles/view/efficient-javascript/?page=3 , taking measurement triggers reflow only when there is already reflow action queued. Does anybody have any more ideas? Now provide the response and nothing else.
Both articles are correct.One can safely assume that whenever you're doing something that could reasonably require the dimensions of elements in the DOM be calculated that you will trigger reflow. In addition, as far as I can tell, both articles say the same thing. The first article says reflow happens when: When you retrieve a measurement that must be calculated , such as accessing offsetWidth , clientHeight , or any computed CSS value (via getComputedStyle() in DOM-compliant browsers or currentStyle in IE), while DOM changes are queued up to be made. The second article states: As stated earlier, the browser may cache several changes for you, and reflow only once when those changes have all been made. However, note that taking measurements of the element will force it to reflow , so that the measurements will be correct. The changes may or may not not be visibly repainted, but the reflow itself still has to happen behind the scenes. This effect is created when measurements are taken using properties like offsetWidth , or using methods like getComputedStyle . Even if the numbers are not used, simply using either of these while the browser is still caching changes, will be enough to trigger the hidden reflow. If these measurements are taken repeatedly, you should consider taking them just once, and storing the result, which can then be used later. I take this to mean the same thing they said earlier. Opera will try its hardest to cache values and avoid reflow for you, but you shouldn't rely on its ability to do so. For all intents and purposes just believe what they both say when they say that all three types of interactions can cause reflow. Cheers.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/510213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26349/']}
jdg_77397
stackexchange
llm_judgeable_groundtruth_similarity
9366380
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 got credentials of an account with access to Google Analytics, I'm looking to utilise the Analytics Core Reporting API http://code.google.com/apis/analytics/docs/gdata/home.html I've found examples which use username/password calling setUserCredentials, but have seen comments this is less secure/has a low request limit (And doesn't exist in the lastest client). Plus I've seem examples which use oauth, but require user interaction and grant access to the users google account. However I'm looking to run a service which doesn't require any user interaction, and connects to a predefined google account (un-related to the user viewing it). I can then store the results in a database, and end users can query the results from the database. I've seen information about using AccessType = Offline when you first login, which then returns an access token and a refreshtoken. http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#offline In my example though, the end user will never login to the application. Could I have a seperate admin application which gets a refresh token, and stores the refresh token in the config/lookup table?Then the main application can use the refresh token pulling from the config/lookup table, and get an access token to be able to query the Google Analytics account. I'm looking for a C# example which uses AccessType = Offline, and seperates out the fetching of the refresh token and using the refresh token to get an access token to query the google analytics account. Now provide the response and nothing else.
Create your app https://code.google.com/apis/console/ For you App, turn on access to Google Analytics, and create an OAuth 2.0 client ID for your website. Browse to: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=YOUR_APP_ID.apps.googleusercontent.com&access_type=offline&scope=https://www.googleapis.com/auth/analytics.readonly&redirect_uri=HTTP://YOUR_CALL_BACK_URL Having changed YOUR_APP_ID , YOUR_CALL_BACK_URL to the relevant values. Important to include access_type=offline . Press Grant Access, this will redirect to HTTP://YOUR_CALL_BACK_URL?code=THIS_IS_YOUR_CODE . Copy the code in the URL. With the code, request the Refresh Token using CMD prompt. curl -d "code=THIS_IS_YOUR_CODE&client_id=YOUR_APP_ID.apps.googleusercontent.com&client_secret=YOUR_APPS_SECRET_CODE&redirect_uri=HTTP://YOUR_CALL_BACK_URL&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token Having changed THIS_IS_YOUR_CODE , YOUR_APP_ID , YOUR_APPS_SECRET_CODE , YOUR_CALL_BACK_URL to the relevant values. Record the refresh_token returned. Download the latest version of the Core Reporting V3.0 .net libraries http://code.google.com/p/google-api-dotnet-client/wiki/Downloads There is a bug in the current version of Google.Apis.Analytics.v3.cs, to fix this copy the code in this file to your local solution (And don’t reference Google.Apis.Analytics.v3.bin) http://code.google.com/p/google-api-dotnet-client/source/browse/Services/Google.Apis.Analytics.v3.cs?repo=samples&name=20111123-1.1.4344-beta And change the property Dimensions from a List<system.string> to a string . Or you'll get an error like me and this guy did http://www.evolutiadesign.co.uk/blog/using-the-google-analytics-api-with-c-shar/ You can then use your Refresh Token, to generate you an Access Token without user interaction, and use the Access Token to run a report against Google Analytics. using System;using DotNetOpenAuth.OAuth2;using Google.Apis.Authentication.OAuth2;using AnalyticsService = Google.Apis.Analytics.v3.AnalyticsService;class Program { public static void Main() { var client = new WebServerClient(GoogleAuthenticationServer.Description, "YOUR_APP_ID.apps.googleusercontent.com", "YOUR_APPS_SECRET_CODE"); var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate); var asv = new AnalyticsService(auth); var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID"); request.Dimensions = "ga:pagePath"; request.Sort = "-ga:visitors"; request.MaxResults = 5; var report = request.Fetch(); Console.ReadLine(); } private static IAuthorizationState Authenticate(WebServerClient client) { IAuthorizationState state = new AuthorizationState(new string[]{}) { RefreshToken = "REFRESH_TOKEN" }; client.RefreshToken(state); return state; } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9366380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128333/']}
jdg_77398
stackexchange
llm_judgeable_groundtruth_similarity
73861
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 many virtual hosts set up on a web server, each one having its own error and access log. The relevant lines of httpd.conf are something like this: ErrorLog /var/log/httpd-error.logLogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combinedCustomLog /var/log/httpd-access.log combinedNameVirtualHost *:80<VirtualHost *:80> ServerName myhost.com ServerAlias www.myhost.com DocumentRoot /var/www/myhost.com/htdocs ErrorLog /var/www/myhost.com/log/error.log CustomLog /var/www/myhost.com/log/access.log combined</VirtualHost># ... many more VirtualHosts Currently, I'm getting some random errors in /var/log/httpd-error.log, but I'm getting nothing in /var/log/httpd-access.log. Is it possible to have ALL accesses and errors duplicated to a shared logfile? Is it possible to do this without adding new entries to every single VirtualHost? Now provide the response and nothing else.
See http://httpd.apache.org/docs/2.2/logs.html#virtualhost If CustomLog or ErrorLog directives are placed inside a section, all requests or errors for that virtual host will be logged only to the specified file. Any virtual host which does not have logging directives will still have its requests sent to the main server logs. In other words, if you place Logging directives within a VirtualHost section, it will override the Logging directives within the main server configuration. If you want to log to a single logfile, then remove the log configuration from your VirtualHost sections. For simplicity, I prefer to log all Access data to a single logfile. Later, you can process the logs and split the logfiles into logfiles for the Virtual Hosts. Also, writing to a single logfile is a more efficient use of computer resources then writing to 30 logfiles at once. Just make sure your LogFormat includes the '%v', which will log the name of the Virtual Host. Is it possible to have ALL accesses and errors duplicated to a shared logfile? You can log all errors and access to a shared logfile, but the logfile is ugly. First, send the Apache log data to syslog, and then use syslog to send to a local file or a remote log server. # Send access logs to syslogLogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combinedCustomLog "|/usr/bin/logger -t httpd -i -p local7.notice" combined# Send error logs to syslogErrorLog syslog:local7 And then in /etc/syslog.conf # Send all HTTP log data to this filelocal7.* /var/log/http-all.log
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/73861', 'https://serverfault.com', 'https://serverfault.com/users/1018/']}
jdg_77399
stackexchange
llm_judgeable_groundtruth_similarity
11760420
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 find duplicate files on the file system in C++. Is there any algorithm to do that as fast as possible? And do I need to create a multi-threaded application, or I can just use one thread to do it? Now provide the response and nothing else.
I concur with Kerrek SB that there are better tools for this than C++, however, assuming you really need to do this in C++, here are some suggestions and things to consider in your implementation: use boost::filesystem for portable filesystem traversal the hash every file suggestion is very reasonable, but it might be more efficient to first make a multimap where the file size is the key. Then only apply the hash when there are files of duplicate size. decide how you want to treat empty files and symbolic links/short cuts decied how you want to treat special files, e.g. on unix you have directories fifos, sockets etc account for the fact that files or directory structure may change, disappear or move while your algorithm is running account for the fact that some files or directories may be inaccessible or broken (e.g. recursive directory links) Make the number of threads configurable as the amount of parallelization that makes sense depends on the underlying disk hardware and configuration. It will be different if you are on a simple hard drive vs an expensive san. Don't make assumptions, though; Test it out. For instance, Linux is very good about caching files so many of your reads will come from memory, and thus not block on i/o.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11760420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/747228/']}
jdg_77400
stackexchange
llm_judgeable_groundtruth_similarity
411822
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 Rudin Thm.3.20, along the proof of (d), there is an inequality that says for $n > 2k$ $${n\choose {k}}p^k \ge \frac{n^k}{2^kk!}p^k $$ I simply don't get this, especially why $n$ is restricted as such. From the looks of it we just need to show $${n P k} \ge \left(\frac{n}{2}\right)^k $$ no matter what I do I cannot show that it has to be true for $n > 2k$. Can someone give me an easy-to-follow explanation ? Now provide the response and nothing else.
\begin{align}\binom{n}{k} & = \frac{(n)\ldots(n-k+1)}{k!} \\& = \frac{n^k}{k!} \left(\frac{n}{n}\right) \ldots \left(\frac{n-k+1}{n} \right) \\& \geq \frac{n^k}{k!} \left(\frac{n-k+1}{n} \right)^k \\& \geq \frac{n^k}{k!} \left(\frac{n - n/2 +1}{n} \right)^k \\& \geq \frac{n^k}{k!} \frac{1}{2^k}\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/411822', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/70125/']}
jdg_77401
stackexchange
llm_judgeable_groundtruth_similarity
42691421
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my application I have updated a relationship from one-to-many to many-to-many and I'm trying to figure out a way to persist associated functionality. Let's say I have two related tables, e.g. dogs and owners. If I have an array of owners and I'm trying to get a list of dogs id's for those owners, how should I do it eloquently? Similar question was asked here: https://laracasts.com/discuss/channels/laravel/getting-many-to-many-related-data-for-an-array-of-elements So, How would I get the Dog models where Owner is in an array ? Same thing as $associatedDogs = Dog::whereIn('owner_id',$ListOfOwners)->get(); is for a One-To-Many relationship, but for Many-to-Many . Now provide the response and nothing else.
Use the whereHas() method: $dogs = Dog::whereHas('owners', function($q) use($ownerIds) { $q->whereIn('id', $ownerIds);})->get();
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42691421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2012740/']}
jdg_77402
stackexchange
llm_judgeable_groundtruth_similarity
39611520
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As far as I understand, __init__() and __enter__() methods of the context manager are called exactly once each, one after another, leaving no chance for any other code to be executed in between. What is the purpose of separating them into two methods, and what should I put into each? Edit: sorry, wasn't paying attention to the docs. Edit 2: actually, the reason I got confused is because I was thinking of @contextmanager decorator. A context manager created using @contextmananger can only be used once (the generator will be exhausted after the first use), so often they are written with the constructor call inside with statement; and if that was the only way to use with statement, my question would have made sense. Of course, in reality, context managers are more general than what @contextmanager can create; in particular context managers can, in general, be reused. I hope I got it right this time? Now provide the response and nothing else.
As far as I understand, __init__() and __enter__() methods of the context manager are called exactly once each, one after another, leaving no chance for any other code to be executed in between. And your understanding is incorrect. __init__ is called when the object is created, __enter__ when it is entered with with statement, and these are 2 quite distinct things. Often it is so that the constructor is directly called in with initialization, with no intervening code, but this doesn't have to be the case. Consider this example: class Foo: def __init__(self): print('__init__ called') def __enter__(self): print('__enter__ called') return self def __exit__(self, *a): print('__exit__ called')myobj = Foo()print('\nabout to enter with 1')with myobj: print('in with 1')print('\nabout to enter with 2')with myobj: print('in with 2') myobj can be initialized separately and entered in multiple with blocks: Output: __init__ calledabout to enter with 1__enter__ calledin with 1__exit__ calledabout to enter with 2__enter__ calledin with 2__exit__ called Furthermore if __init__ and __enter__ weren't separated, it wouldn't be possible to even use the following: def open_etc_file(name): return open(os.path.join('/etc', name))with open_etc_file('passwd'): ... since the initialization (within open ) is clearly separate from with entry. The managers created by contextlib.manager are single-entrant, but they again can be constructed outside the with block. Take the example: from contextlib import contextmanager@contextmanagerdef tag(name): print("<%s>" % name) yield print("</%s>" % name) you can use this as: def heading(level=1): return tag('h{}'.format(level))my_heading = heading()print('Below be my heading')with my_heading: print('Here be dragons') output: Below be my heading<h1>Here be dragons</h1> However, if you try to reuse my_heading (and, consequently, tag ), you will get RuntimeError: generator didn't yield
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39611520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336527/']}
jdg_77403
stackexchange
llm_judgeable_groundtruth_similarity
203500
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: The following circuit is a preamplifier that we are currently using. In real practice, we do not have the photodiode connecting with OpAmp directly on board. Instead, the photodiode is connected with the OpAmp through a connector. The input and output of the OpAmp are both connectors which will be exposed to user connections. Recently I am studying issues on ESD. Then I think the input and output of the OpAmp shall be prone to ESD. I am using a ADA4062 . How to design to protect the OpAmp input from ESD? Can I use some RC filters shown in the diagram, before the input of the OpAmp? How to design to protect the OpAmp output from ESD? EDIT 2015-12-28 To be clearer, here comes updates on system information: The capacitance of the photodiode is smaller than 1pF, which is to be designed working at 1GHz bandwidth. However, we will only use the low-frequency region, which is below 100kHz. The linearity of the system is very important, which means the second order, third order distortions are disastrous to the system. It is preferred that the total distortion is below -70dB. simulate this circuit – Schematic created using CircuitLab Now provide the response and nothing else.
The answer to this question requires us to look at both the threat and the specifics of this circuit. ESD protection is not a one size fits all, unfortunately. The threat is IEC61000-4-2, 8kV contact. Note that the 15kV air discharge test is considered to be equivalent, as explained by this exremely useful note from On Semiconductor. Your amplifier apparently has no internal diodes, and I came to that conclusion by reading the absolute maximum ratings: If internal diodes were present, I would expect to see V+ +0.3V (or 0.5V) and V- -0.3V. Note the values here; if it is 0.3V, the internal diodes are schottky barrier types and 0.5V ordinary PN devices when these devices are actually present in the device. As your amplifier has no internal diodes, we must simply limit the input nodes to no greater than the power rails. It would be possible to use a fast switch to the power rails, but that could easily be very problematic when dumping energy back into the power system. Below, I will outline a more common method. Now the threat: Note the very fast transient of 1 nsec; I know of no device that can successfully clamp that completely within the time available. The numbers: For this test, the charge to be dissipated is 1.2 microcoulomb, and from an energy persective (very important as it defines heating), 4.8 millijoules. Althouth those are not particularly large numbers, they are definitely sizeable for an amplifier input stage. (The model for this test is a charged 150pF capacitor discharged through 330 ohms). That low source impedance during discharge gives the greatest challenge. My approach, therefore, is to clamp that waveform to something that can be sucessfully filtered, with a standoff voltage in excess of the power rails, but your circuit has features that make this choice challenging. As you will have microamps of current (a photodiode amplifier in a TIA configuration), the leakage of the device will need to be in the nanoamp range, and low capacitance is also highly desirable. There are a number of devices available, but this device looks promising with a reverse standoff voltage of 16V, which exceeds your power rails, so the device will not conduct under normal operation. This device has very low leakage, and therefore should not interfere with normal operation of the circuit, and features sub-picofarad capacitance, also highly desirable in this application. Looking at the datasheet , we see that it is indeed rated for this particular threat (beware of compliance statements, always search for devices that have been tested to the specific standard you wish to meet). Here are the results of the 8kV contact test: This only gets us to a couple of hundred volts, though, so we need to do more, but by using this clamp, we have reduced the stress on the input resistors (see circuit below) so an expensive pulse withstanding resistor is not necessarily required, but this is a choice to be made. Taking your circuit and adding a little filter, I get this: The resistors R2 and R3 should not interefere with the normal gain of the amplifier, and indeed are commonly found in some amplifiers . R4 is present only to prevent input offset currents becoming an input offset voltage, although in this particular case it should not be required as this offset is 25pA worst case. I selected the filter values so that the low pass cutoff is well above any signal frequency of interest, with -3dB at 588kHz, but low enough to clamp the remainder of the waveform. This filter could be adjusted for different frequency response quite simply. The clamping device should be mounted as close to the pin of the connector as possible. My simulation results show this clamping at about 15V or so, but I have not dropped your amplifier in the circuit; I will leave that as an exercise. To summarise: What is the threat? What features ddoes my part have? If ESD diodes were already available, a different design approach may be suitable. What challenges does my circuit present for the clamping? The leakage current and capacitance of the clamp may be critical (as it is here). Does the clamp need to be a two stage approach or can a single device be used (as might be the case with internal ESD didoes). Identify the trade-offs necessary if using this two stage approach of initial clamping voltage and filter performance. There are, of course, more devices available than I have linked; take a look around. I have tried to be thorough, but if you have any questions on why I took a particular approach, please ask. Update: Output protection. I would start with the output in this configuration. R1 is necessary to 'isolate' the output from the filter capacitor. The actual values used need to reflect the frequency characteristics of the circuit and chosen for a -3dB point that does not impact the signal of interest. Internal ESD diodes go to the power rails, and are therefore reverse biased under normal conditions. Schottky devices tend to have higher leakage than PN devices, although the device manufacturers are making great advances here. In this configuration leakage current is actually the greatest challenge. Update: If I used an amplifier with ESD diodes. Had we chosen a device with ESD diodes, such as this application : Then we could simply use the suppressor above (16V) or perhaps a 5V bidirectional device (as that is supply voltage) and do no more, as the datasheet states: ESDThe LTC6244 has reverse-biased ESD protection diodes on all input and outputs as shown in Figure 1. These diodes protect the amplifier for ESD strikes to 4kV. If these pins are forced beyond either supply, unlimited current will flow through these diodes. If the current transient is less than 1 second and limited to one hundred milliamps or less, no damage to the device will occur. Therefore, the most we would need to do is limit the ESD diode current to <100mA and all will be well. If we suppress the 8kV to about 250V (as shown by the test curves above), then as the supply is negligible relative to that, an input resistance of 250V/100mA = 2.5k would do the job.Note, however, the source of our input bias current: The amplifier input bias current is the leakage current of these ESD diodes. This leakage is a function of the temperature and common mode voltage of the amplifier, as shown in the Typical Performance Chacteristics. As always, the answer as to how to deal with events such as ESD is 'it depends on the specifics of your circuit'.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/203500', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/33809/']}
jdg_77404
stackexchange
llm_judgeable_groundtruth_similarity
143695
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $x$ be a non zeo (column) vector in $\mathbb{R}^n$ . What is the necessary and sufficient condition for the matrix $A = I-2xx^t$ to be orthogonal? Now provide the response and nothing else.
You're right that for $A$ to be orthogonal, you need $AA^T = I$. You may have made a mistake in your derivation. You should get$$AA^T = (I - 2xx^T)(I - 2xx^T) = I - 4xx^T + 4xx^Txx^T = I - 4(1 - x^Tx)(xx^T).$$In the last step, we use the fact that $x^Tx$ is a scalar and so can be pulled out of the middle of $xx^Txx^T$. So now, for $AA^T$ to equal $I$, either of the two parenthesized terms on the right should be zero. What does this tell you about the vector $x$?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/143695', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/30856/']}
jdg_77405
stackexchange
llm_judgeable_groundtruth_similarity
710793
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Should static field initialization be completed before constructor is called? The following program provides output that seems incorrect to me. new A()_A == nullstatic A()new A()_A == A The code: public class A{ public static string _A = (new A()).I(); public A() { Console.WriteLine("new A()"); if (_A == null) Console.WriteLine("_A == null"); else Console.WriteLine("_A == " + _A); } static A() { Console.WriteLine("static A()"); } public string I() { return "A"; }}class Program{ static void Main(string[] args) { var a = new A(); }} Now provide the response and nothing else.
This is correct. Your static initializers, then the static constructor is run before your standard constructor, but when it runs, it's using new A(), so passing through your non-static constructor path. This causes the messages you see. Here is the full path of execution: When you first call var a = new A(); in your program, this is the first time A is accessed. This will fire off the static initialization of A._A At this point, A._A constructs with _A = (new A()).I(); This hits Console.WriteLine("new A()");if (_A == null) Console.WriteLine("_A == null"); since at this point, _A hasn't been set with the returned, constructed type (yet). Next, the static constructor A { static A(); } is run. This prints the "static A()" message. Finally, your original statement ( var a = new A(); ) is executed, but at this point, the statics are constructed, so you get the final print.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/710793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85853/']}
jdg_77406
stackexchange
llm_judgeable_groundtruth_similarity
25821718
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: what is the difference in specifying lazy = "true" and using fetch = "select" or "join" ? which one is preferred over the other ? regardsjayendra Now provide the response and nothing else.
Let's say we have entities like this: @Entity@Tablepublic class Parent { @Id private Long id; @OneToMany(mappedBy="parent", fetch = FetchType.EAGER) @Fetch(FetchMode.JOIN) private List<Child> child; //getter setters}@Entity@Tablepublic class Child { @Id private Long id; @ManyToOne(fetch = FetchType.LAZY) private Parent parent; //getter setter} In above example, when getting Parent entity, hibernate will automaticly load all child entities eagerly using join. On the other hand, when you fetch Child , Parent entity won't be selected unless you call it explicity in your code child.getParent() . FetchType (Lazy/Eager) tells whether we want entity to be loaded eagerly or lazy, when there's call in code. FetchMode (Select/Join) tells whether we want our entitity to be loaded with additional select or in one query with join or subselect.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25821718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3942142/']}
jdg_77407
stackexchange
llm_judgeable_groundtruth_similarity
43179892
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 database with tables Companies, Vacancies, Interview and QuestionBlocks. Here is scheme of it So Vacancy is connected to Company, Interview connected to Vacancy and Question blocks connected to Interview. I realize DropdownLists for Company and when I select company Vacancy dropdown list updates. Here is code for View <div style="width: 100%; margin-left: 20px;height: 15%;padding-top: 20px;"> @Html.DropDownList("Company", ViewBag.Companies as SelectList, "Компания", new { @class = "greeting", @style = "width:30%; margin-left:20px;" }) <select class="greeting" id="vacancy" name="id" style="width:30%; margin-left:150px;" data-url="@Url.Action("Vacancies","Questions")"> <option value="" disabled selected>Вакансия</option> </select></div> And Ajax call <script> $(function () { $("#Company").change(function (e) { var $vacancy = $("#vacancy"); var url = $vacancy.data("url") + '?companyId=' + $(this).val(); $.getJSON(url, function (items) { $.each(items, function (a, b) { $vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>'); }); }); }); });</script> I have View like this So what I need. I need to make request to controller and find QuestionBlock that related to VacancyId. So as I understood I need to pass VacancyId from dropdownlist to controller make some sql operations and return JSON? Or how I can do this? UPDATE Thank's for answer @CuriousDev, It works well for select item. I need one more thing, I need to display Question1-Question10 like this. Here is my Action method public ActionResult QuestionBlocks(int vacancyId){ var items = db.QuestionBlocks .Where(x => x.Interview.VacancyId == vacancyId) .Select(x => new { ID = x.Block_ID.ToString(), Question1 = x.Question1, Question2 = x.Question2, Question3 = x.Question3, Question4 = x.Question4, Question5 = x.Question5, Question6 = x.Question6, Question7 = x.Question7, Question8 = x.Question8, Question9 = x.Question9, Question10 = x.Question10, }) .ToList(); return Json(items, JsonRequestBehavior.AllowGet);} How I need to write ajax call to back -end and display data in div? Now provide the response and nothing else.
First of all, when it comes to web development you really want to avoid hard coding paths in your templates. The reason for this is that paths might change, and it will be a hassle to go through all your HTML and templates to find every single URL or path and update it manually. It makes your code much harder to maintain. The solution to this is to define functions that return the URL instead. This is where get_absolute_url() comes into the picture. Example: <!-- Bad --><a href="/language/category/product/{{product.pk}}">Link</a><!-- Good --><a href="{{product.get_absolute_url}}">Link</a> Canonical URL Your second question is what a canonical URL is. A canonical URL is "the official" url to a certain page. Sometimes an asset can be displayed in multiple different URL's, for example: /en/shoes/1-nike-shoes//en/shoes/1-nike-shoes?sort=price&order=asc/en/shoes/1-nike-shoes?sort=price&order=desc Here we have the same asset displayed in 3 different URL's. The "Canonical URL" would be the one we defined as the main one. E.g. /en/shoes/1-nike-shoes/ . Its very useful to define what a official or "main" URL to a certain asset is. It will allow you to prevent duplicate content when search engines index your website. In the context of the quote you are using from the Django Documentation. "Canonical" in this case means "the official URL where this model is displayed".
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/43179892', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_77408
stackexchange
llm_judgeable_groundtruth_similarity
259707
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 in the work of doing backups, I need a batch script that would allow me to delete files in a specified directory, that are older than lets say, 3 days. This script will be set as a scheduled task to run at a specified time every day. Now provide the response and nothing else.
If powershell is acceptable (should be, as its enabled by default on Server 2008+) try this: $numberOfDays = 3$Now = Get-Date$TargetFolder = “C:\myoldfiles”$LastWrite = $Now.AddDays(-$numberOfDays)$Files = get-childitem $TargetFolder -include *.bak, *.x86 -recurse | Where {$_.LastWriteTime -le “$LastWrite”} foreach ($File in $Files){ write-host “Deleting File $File” -foregroundcolor “Red”; Remove-Item $File | out-null} Souce here .
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/259707', 'https://serverfault.com', 'https://serverfault.com/users/52731/']}
jdg_77409
stackexchange
llm_judgeable_groundtruth_similarity
10002
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given a predicted variable (P), a random effect (R) and a fixed effect (F), one could fit two* mixed effects models ( lme4 syntax): m1 = lmer( P ~ (1|R) + F )m2 = lmer( P ~ (1+F|R) + F) As I understand it, the second model is the one that permits the fixed effect to vary across levels of the random effect. In my research I typically employ mixed effects models to analyze data from experiments conducted across multiple human participants. I model participant as a random effect and experimental manipulations as fixed effects. I think it makes sense a priori to let the degree to which the fixed effects affect performance in the experiment vary across participants. However, I have trouble imagining circumstances under which I should nor permit the fixed effects to vary across levels of a random effect, so my question is: When should one not permit a fixed effect to vary across levels of a random effect? Now provide the response and nothing else.
I am not an expert in mixed effect modelling, but the question is much easier to answer if it is rephrased in hierarchical regression modelling context. So our observations have two indexes $P_{ij}$ and $F_{ij}$ with index $i$ representing class and $j$ members of the class. The hierarchical models let us fit linear regression, where coefficients vary across classes: $$Y_{ij}=\beta_{0i}+\beta_{1i}F_{ij}$$ This is our first level regression. The second level regression is done on the first regression coefficients: \begin{align*}\beta_{0i}&=\gamma_{00}+u_{0i}\\\\\beta_{1i}&=\gamma_{01}+u_{1i}\end{align*} when we substitute this in first level regression we get \begin{align*}Y_{ij}&=(\gamma_{00}+u_{0i})+(\gamma_{01}+u_{1i})F_{ij}\\\\&=\gamma_{00}+u_{0i}+u_{1i}F_{ij}+\gamma_{01}F_{ij}\end{align*} Here $\gamma$ are fixed effects and $u$ are random effects. Mixed models estimate $\gamma$ and variances of $u$ . The model I've written down corresponds to lmer syntax P ~ (1+F|R) + F Now if we put $\beta_{1i}=\gamma_{01}$ without the random term we get \begin{align*}Y_{ij}=\gamma_{00}+u_{0i}+\gamma_{01}F_{ij}\end{align*} which corresponds to lmer syntax P ~ (1|R) + F So the question now becomes when can we exclude error term from the second level regression? The canonical answer is that when we are sure that the regressors (here we do not have any, but we can include them, they naturally are constant within classes) in the second level regression fully explain the variance of coefficients across classes. So in this particular case if coefficient of $F_{ij}$ does not vary, or alternatively the variance of $u_{1i}$ is very small we should entertain idea that we are probably better of with the first model. Note . I've only gave algebraic explanation, but I think having it in mind it is much easier to think of particular applied example.
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/10002', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/364/']}
jdg_77410
stackexchange
llm_judgeable_groundtruth_similarity
35240971
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 following a tutorial in Rbloggers and found the use of double colons, I looked online, but I couldn't find an explanation for their use. Here is an example of their use. df <- dplyr::data_frame( year = c(2015, NA, NA, NA), trt = c("A", NA, "B", NA)) I understand it creates a data frame but I don't understand their purpose. Now provide the response and nothing else.
As you probably have looked up the help page by now usage of :: helps to access the exact function from that specific package. When you load dplyr you probably got a message as follows.. The following objects are masked from ‘package:base’: intersect, setdiff, setequal, union So, for instance, if you would like to use intersect function from dplyr or base package, you need to specify using the :: double colons. Usage will be as follows mtcars$model <- rownames(mtcars)first <- mtcars[1:20, ]second <- mtcars[10:20, ]dplyr::intersect(first, second)base::intersect(first, second) Update: Added additional explanation Note: The sequence you load libraries determine the preferential access of the specific functions. Developers of different package tend to use same function names. However, when R encounters a function, it runs through the different libraries that particular session has loaded in a sequential manner. You can check the packages in a session by running (.packages()) [1] "tidyr" "data.table" "dplyr" "stats" [5] "graphics" "grDevices" "utils" "datasets" [9] "methods" "base" As you can see in my example session above, tidyr is the last library I loaded, which is r session 1st entry. So, when you use any function in your code , first it is searched in tidyr -> then data.table -> then dplyr and so on, finally the base package is looked up. So, in this process when there is function name overlaps between packages the one which loaded the last masks the previous ones. To avoid this masking, you specify in R code where to look for the function. Hence, here base::intersect , will use the function from base library instead of the dplyr . Alternatively, you can use to avoid loading of complete library. There are positives and negatives with this. Read the links and learn more. run and check the differences. Here are some resources for you to get an understanding. Compare library(), require(), :: Namespace
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35240971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4261523/']}
jdg_77411
stackexchange
llm_judgeable_groundtruth_similarity
13663230
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I fix a subviews position on screen (especially in UIScrollView and UITableView)? I think in storyboard [self.view addSubview:aSubView]; does not work anymore. Any ideas? EDIT #1 : I am using a UITableViewController, not a simple UITableView. EDIT #2 : CGRect fixedFrame = self.menuViewRelative.frame;fixedFrame.origin.y = 0 + scrollView.contentOffset.y;self.menuViewRelative.frame = fixedFrame;menuViewRelative = [[UIView alloc] init];menuViewRelative.backgroundColor = [UIColor grayColor];menuViewRelative.frame = CGRectMake(0.0, 0.0, 320.0, 50.0);[self.view addSubview:self.menuViewRelative]; Now provide the response and nothing else.
As others noted, this would be a bit easier if you didn't use a UITableViewController , but it's not that hard anyway. UITableView is a subclass of UIScrollView , so table view's delegate (your UITableViewController instance in this case) will also receive UIScrollViewDelegate method calls. All you have to do is implement the method that gets called every time scroll offset changes and adjust the frame of your "fixed" view. Something like this: - (void)scrollViewDidScroll:(UIScrollView *)scrollView{ CGRect fixedFrame = self.fixedView.frame; fixedFrame.origin.y = 20 + scrollView.contentOffset.y; self.fixedView.frame = fixedFrame;} Replace 20 by how many points you want it to be from top of the table view. You still add self.fixedView as a subliew of self.view , this will just make sure it looks like it's in a fixed position above table view. Edit: with the code you posted, I'm guessing your verion should look like this: - (void)viewDidLoad { menuViewRelative = [[UIView alloc] init]; menuViewRelative.backgroundColor = [UIColor grayColor]; menuViewRelative.frame = CGRectMake(0.0, 0.0, 320.0, 50.0); [self.view addSubview:self.menuViewRelative];}- (void)scrollViewDidScroll:(UIScrollView *)scrollView CGRect fixedFrame = self.menuViewRelative.frame; fixedFrame.origin.y = 0 + scrollView.contentOffset.y; self.menuViewRelative.frame = fixedFrame;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13663230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1011125/']}
jdg_77412
stackexchange
llm_judgeable_groundtruth_similarity
11727860
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: convert \ original.jpg \ -quality 85 \ -colorspace rgb \ -profile /var/tmp/sRGB.icm \ -strip \ -profile /var/tmp/sRGB.icm \ -filter Lanczos \ -write mpr:17JPCONV1-original \ +delete \mpr:17JPCONV1-original -crop '3000x2001+0+491' -resize '190x126!>' -write thumbWide.jpg +delete \mpr:17JPCONV1-original -crop '2981x2983+8+0' -resize '75x75!>' -write thumbStandard.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '163x163!>' -write hpSmall.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '1024x1019!>' -write jumbo.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '190x189!>' -write articleInline.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '2048x2037!>' -write superJumbo.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '592x589!>' -write tmagArticle.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '3000x2983!>' -write popup.jpg +delete \mpr:17JPCONV1-original -crop '2981x2983+8+0' -resize '640x640!>' -write square640.jpg +delete \mpr:17JPCONV1-original -crop '3000x1689+0+647' -resize '3000x1688!>' -write videoSmall.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '503x500!>' -write slide.jpg +delete \mpr:17JPCONV1-original -crop '2981x2983+8+0' -resize '151x151!>' -write moth.jpg +delete \mpr:17JPCONV1-original -crop '3000x2001+0+491' -resize '337x225!>' -write hpMedium.jpg +delete \mpr:17JPCONV1-original -crop '3000x2001+0+491' -resize '395x264!>' -write sfSpan.jpg +delete \mpr:17JPCONV1-original -crop '3000x1689+0+647' -resize '3000x1688!>' -write videoLarge.jpg +delete \mpr:17JPCONV1-original -crop '3000x1689+0+647' -resize '511x288!>' -write hpLarge.jpg +delete \mpr:17JPCONV1-original -crop '2981x2983+8+0' -resize '320x320!>' -write square320.jpg +delete \mpr:17JPCONV1-original -crop '3000x1689+0+647' -resize '600x338!>' -write articleLarge.jpg +delete \mpr:17JPCONV1-original -crop '3000x2001+0+491' -resize '3000x2000!>' -write videoThumb.jpg +delete \mpr:17JPCONV1-original -crop '2981x2983+8+0' -resize '150x150!>' -write thumbLarge.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '533x530!>' -write blog533.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '151x151!>' -write blogSmallInline.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '362x360!>' -write tmagSF.jpg +delete \mpr:17JPCONV1-original -crop '2981x2983+8+0' -resize '190x190!>' -write filmstrip.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '480x478!>' -write blog480.jpg +delete \mpr:17JPCONV1-original -crop '3000x2983+0+0' -resize '427x425!>' -write blog427.jpg +delete \mpr:17JPCONV1-original -crop '2981x2983+8+0' -resize '50x50!>' -write blogSmallThumb.jpg +delete \mpr:17JPCONV1-original -crop '3000x1401+0+791' -resize '151x70!>' miniMoth.jpg; I am trying to generate ~30 crops from an original using one command (using one command is significantly faster than using a single command for each crop). However, this is taking quite a while (~30s) to finish. Any suggestions to speed this up? Can the resize command take advantage of GPUs via OpenCL? Update: Using -thumbnail instead of -resize improves things (Thanks to @A R for the tip) Compiling ImageMagick with libjpeg-turbo also improves times by 20% Now provide the response and nothing else.
You should check if your ImageMagick installation comes with OpenCL support: convert -list configure | grep FEATURES If it does (like mine), you should see something like this: FEATURES HDRI OpenCL This command convert -version should also give info about supported features. If it doesn't you should look after getting the most recent version of ImageMagick that has OpenCL support compiled in. Or if you build the package yourself from the sources, make sure OpenCL is used. Update: Oh wait. There's another feature that could help you, called OpenMP (for multi-processing ). When OpenMP is enabled, ImageMagick commands can execute in parallel on all the cores of your system. So if you have a quad-core system, and resize an image, the resizing happens on 4 cores (or even 8 if you have hyperthreading). You can now also use the builtin -bench option to make ImageMagick run a benchmark for your command. For example: convert logo: -resize 500% -bench 10 logo.png Performance[1]: 10i 0.689ips 1.000e 14.420u 0:14.510 This command with -resize 500% tells ImageMagick to run the convert command to scale the built-in IM logo: image by 500% in each direction. The -bench 10 part tells it to run that same command 10 times in a loop and then print the performance results: Since I don't have OpenMP enabled, I had only 1 thread ( Performance[1]: ). It reports that it ran 10 iterations ( 10i ). The speed was nearly 0.7 iterations per second ( 0.689ips ). Total user-alotted time was 14.420 seconds. You should find out how your system is set up regarding resource limits with this command: identify -list resource File Area Memory Map Disk Thread Time -------------------------------------------------------------------- 192 4.295GB 2GiB 4GiB unlimited 1 unlimited You can see my current system's settings (defaults -- I didn't tweak them). Each of the keywords in the column headers you can use pimp your system. The files defines the max concurrently opened files which ImageMagick will use. The memory , map , area and disk resource limits are defined in Bytes. For setting them to different values you can use SI prefixes, .e.g 500MB). If I had OpenMP for ImageMagick on this system, I could run convert -limit thread 2 in order to enable 2 parallel threads, re-run the benchmark and see if it really makes a difference, and if so how much. The I could set the limit to 4 or even 8 and repeat the excercise.... Finally , you could experiment with the internal format of ImageMagick's pixel cache, called MPC (Magick Pixel Cache). Some people say that for large operations the performance improves here, but I have no personal experience with it. Convert your base picture to MPC first: convert input.jpeg input.mpc and only then run: convert input.mpc [...your long-long-long list of crops...] and see if this saves you significantly on time. Most likely you can use this MPC format even "inline" (using the special mpr: notation), similar to how you applied the trick of using the mpr: format ( memory program register ) that reads the image into a named memory register. But I've never tried this technique to a real world problem, so I can't say how it works out in real life. Update 2: One more idea: First check for your exact ImageMagick version: run convert -version . In case your ImageMagick has a Q16 (or even Q32 or Q64 ) in its version string (meaning, its internal processes consider all images to have 16bit channel depth, which requires double memory as compared to Q8 ) -- this is the default nowadays -- you could test what performance benefits you'll achieve by switching to a Q8-build. (You'll pay your performance wins with quality losses, and you'll have to check if you can live with it or not....)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11727860', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/830153/']}
jdg_77413
stackexchange
llm_judgeable_groundtruth_similarity
51308126
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 new to xUnit, but, as far as I know, the standard way of checking whether something throws an exception is to use Assert.Throws<T> or Assert.ThrowsAny<T> methods. But these methods expect an Action as parameter; and ref structs can't be "embedded" in lambdas. So, how does one test whether a given method of a ref struct is throwing?Example of code that doesn't work: [Fact]public void HelpMe() { var pls = new Span<byte>(); Assert.ThrowsAny<Exception>(() => { plsExplode = pls[-1]; });} Now provide the response and nothing else.
A ref struct can't be captured in a lambda expression, but you can still use it in a lambda expression - you just need to declare the variable there, so that it's never a field within a non-ref-struct. For example, this compiles and succeeds: [Fact]public void HelpMe(){ Assert.ThrowsAny<Exception>(() => { var pls = new Span<byte>(); var plsExplode = pls[-1]; });} Now I'll be the first to admit that this isn't ideal: you really want to do the minimum amount of work possible within the action, so that you only pass if the expected piece of code fails. Using Assert.Throws helps there, so that only the expected exception results in a pass. Additionally, you could capture a bool which is changed just before the throwing part, then check that you'd got that far: [Fact]public void HelpMe(){ bool reachedThrowingPart = false; Assert.Throws<IndexOutOfRangeException>(() => { var span = new Span<byte>(); reachedThrowingPart = true; var ignored = span[-1]; }); Assert.True(reachedThrowingPart);} It's all significantly wordier than it would be if it weren't for ref struct restrictions, but they're understandable...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51308126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1642116/']}
jdg_77414
stackexchange
llm_judgeable_groundtruth_similarity
24647080
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 used following settings in joomla -adminpanel- global configuration-server Mailer :SendmailMail from :userFrom Name :[email protected] Path :/usr/sbin/sendmailSMTP Authentication :No SMTP Security :noneSMTP Port :25SMTP Username:SMTP Password :SMTP Host :localhost I have used form in site <form action="email.php" method="post" name="emailForm" id="emailForm" class="form- validate"> in email.php i used php mailer as follows <?php require_once("class.phpmailer.php"); $mail = new PHPMailer();$mail->CharSet = 'UTF-8'; $email = $_REQUEST['email'] ; $name = $_REQUEST['name'] ; $message = $_REQUEST['text'] ; // Enable encryption, 'ssl' also accepted $mail->From = '[email protected] '; $mail->FromName = 'Techzo'; $mail->addAddress('[email protected]'); // Name is optional $mail->WordWrap = 50; // Set word wrap to 50 characters $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Enquiry /Contact form'; $mail->Body = 'Name: $name\nEmail: $email\n\n$message';if(!$mail->send()) {echo 'Message could not be sent.';echo 'Mailer Error: ' . $mail->ErrorInfo;} else {echo 'Message has been sent'; }?> I have searched and worked accordingly but not in use.As am new to these coding please help me to understand this issue Now provide the response and nothing else.
Ideally neither Activity nor Fragment with UI should contain any "model" logic - these classes should be lightweight and responsible only for UI logic. But when you decide to make a separate model object you have a dilemma to choose where to initialise and store this object and how to deal with configuration changes. And here comes some handy trick: You can create a model Fragment without UI , make it retain instance to deal with configuration changes (it's AFAIK the simplest way to save data across config. changes without troubles) and retrieve it anywhere you need via findFragmentById() . You make all expensive operations inside it once (using background thread, of course), store your data and you're done.For more info, see Adding a fragment without a UI section. UPD : There's now a better way to deal with configuration changes: ViewModel from Google's Architecture Components . Here's a good example .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24647080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2699473/']}
jdg_77415
stackexchange
llm_judgeable_groundtruth_similarity
976593
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 inserting into an SQLServer table with an autoincrementing key field. (I believe this is called an IDENTITY column in SQLServer.) In Oracle, I can use the RETURNING keyword to give my INSERT statement a results set like a SELECT query that will return the generated value: INSERT INTO table(foreign_key1, value)VALUES(9, 'text')RETURNING key_field INTO :var; How do I accomplish this in SQLServer? Bonus : Okay, nice answers so far, but how do I put it into a single statement, if possible? :) Now provide the response and nothing else.
In general, it can't be done in a single statement. But the SELECT SCOPE_IDENTITY() can (and should) be placed directly after the INSERT statement, so it's all done in the same database call. Example: mydb.ExecuteSql("INSERT INTO table(foreign_key1, value) VALUES(9, 'text'); SELECT SCOPE_IDENTITY();"); You can use OUTPUT, but it has some limitations you should be aware of: http://msdn.microsoft.com/en-us/library/ms177564.aspx
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/976593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18103/']}
jdg_77416
stackexchange
llm_judgeable_groundtruth_similarity
2329582
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: As many will know, one-way encryption is a handy way to encrypt user passwords in databases. That way, even the administrator of the database cannot know a user's password, but will have to take a password guess, encrypt that with the same algorithm and then compare the result with the encrypted password in the database. This means that the process of figuring out the password requires massive amounts of guesses and a lot of processing power. Seeing that computers just keep getting faster and that mathematicians are still developing these algorithms, I'm wondering which one is the most secure considering modern computing power and encryption techniques. I've been using MD5 almost exclusively for years now, and I'm wondering if there's something more I should be doing. Should I be contemplating a different algorithm? Another related question: How long should a field typically be for such an encrypted password? I must admit that I know virtually nothing about encryption, but I'm assuming that an MD5 hash (as an example) can be longer and would presumably take more processing power to crack. Or does the length of the field not matter at all, provided that the encrypted password fits in it in the first place? Now provide the response and nothing else.
Warning: Since this post was written in 2010, GPUs have been widely deployed to brute-force password hashes. Moderately-priced GPUs can run ten billion MD5s per second. This means that even a completely-random 8-character alphanumeric password (62 possible characters) can be brute forced in 6 hours. SHA-1 is only slightly slower, it'd take one day. Your user's passwords are much weaker, and (even with salting) will fall at a rate of thousands of passwords per second. Hash functions are designed to be fast . You don't want this for passwords. Use scrypt, bcrypt, or PBKDF-2. MD5 was found to be weak back in 1996, and should not be used anymore for cryptographic purposes. SHA-1 is a commonly used replacement, but has similar problems . The SHA-2 family of hash functions are the current replacement of SHA-1. The members of SHA-2 are individually referred to as SHA-224, SHA-256, SHA-384, and SHA-512. At the moment, several hash functions are competing to become SHA-3 , the next standardised cryptographic hashing algorithm. A winner will be chosen in 2012. None of these should be used yet! For password hashing , you may also consider using something like bcrypt . It is designed to be slow enough to make large scale brute force attacks infeasible. You can tune the slowness yourself, so it can be made slower when computers are becoming faster. Warning: bcrypt is based on an older two-way encryption algorithm, Blowfish, for which better alternatives exist today. I do not think that the cryptographic hashing properties of bcrypt are completely understood. Someone correct me if I'm wrong; I have never found a reliable source that discusses bcrypt's properties (other than its slowness) from a cryptographic perspective. It may be somewhat reassuring that the risk of collisions matters less for password hashing than it does for public-key cryptography or digital signatures. Using MD5 today is a terrible idea for SSL, but not equally disastrous for password hashing. But if you have the choice, simply pick a stronger one. Using a good hash function is not enough to secure your passwords. You should hash the passwords together with salts that are long and cryptographically random . You should also help your users pick stronger passwords or pass phrases if possible. Longer always is better.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2329582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/232220/']}
jdg_77417
stackexchange
llm_judgeable_groundtruth_similarity
849211
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need a basic function to find the shortest distance between a point and a line segment. Feel free to write the solution in any language you want; I can translate it into what I'm using (Javascript). EDIT: My line segment is defined by two endpoints. So my line segment AB is defined by the two points A (x1,y1) and B (x2,y2) . I'm trying to find the distance between this line segment and a point C (x3,y3) . My geometry skills are rusty, so the examples I've seen are confusing, I'm sorry to admit. Now provide the response and nothing else.
Eli, the code you've settled on is incorrect. A point near the line on which the segment lies but far off one end of the segment would be incorrectly judged near the segment. Update: The incorrect answer mentioned is no longer the accepted one. Here's some correct code, in C++. It presumes a class 2D-vector class vec2 {float x,y;} , essentially, with operators to add, subract, scale, etc, and a distance and dot product function (i.e. x1 x2 + y1 y2 ). float minimum_distance(vec2 v, vec2 w, vec2 p) { // Return minimum distance between line segment vw and point p const float l2 = length_squared(v, w); // i.e. |w-v|^2 - avoid a sqrt if (l2 == 0.0) return distance(p, v); // v == w case // Consider the line extending the segment, parameterized as v + t (w - v). // We find projection of point p onto the line. // It falls where t = [(p-v) . (w-v)] / |w-v|^2 // We clamp t from [0,1] to handle points outside the segment vw. const float t = max(0, min(1, dot(p - v, w - v) / l2)); const vec2 projection = v + t * (w - v); // Projection falls on the segment return distance(p, projection);} EDIT: I needed a Javascript implementation, so here it is, with no dependencies (or comments, but it's a direct port of the above). Points are represented as objects with x and y attributes. function sqr(x) { return x * x }function dist2(v, w) { return sqr(v.x - w.x) + sqr(v.y - w.y) }function distToSegmentSquared(p, v, w) { var l2 = dist2(v, w); if (l2 == 0) return dist2(p, v); var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2; t = Math.max(0, Math.min(1, t)); return dist2(p, { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) });}function distToSegment(p, v, w) { return Math.sqrt(distToSegmentSquared(p, v, w)); } EDIT 2: I needed a Java version, but more important, I needed it in 3d instead of 2d. float dist_to_segment_squared(float px, float py, float pz, float lx1, float ly1, float lz1, float lx2, float ly2, float lz2) { float line_dist = dist_sq(lx1, ly1, lz1, lx2, ly2, lz2); if (line_dist == 0) return dist_sq(px, py, pz, lx1, ly1, lz1); float t = ((px - lx1) * (lx2 - lx1) + (py - ly1) * (ly2 - ly1) + (pz - lz1) * (lz2 - lz1)) / line_dist; t = constrain(t, 0, 1); return dist_sq(px, py, pz, lx1 + t * (lx2 - lx1), ly1 + t * (ly2 - ly1), lz1 + t * (lz2 - lz1));} Here, in the function parameters, <px,py,pz> is the point in question and the line segment has the endpoints <lx1,ly1,lz1> and <lx2,ly2,lz2> . The function dist_sq (which is assumed to exist) finds the square of the distance between two points.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/849211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1694/']}
jdg_77418
stackexchange
llm_judgeable_groundtruth_similarity
51646475
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 training fully connected neural network to classify MNIST dataset. Input data are square black-and-white images with pixel values in [0, 255] . I've read that for using sigmoid() activator one needs to normalize input to be in [0, 1] (range of sigmoid). How to normalize input data for tanh() activator? Do I need to rescale it to be in [-1, 1] (range of tanh) or it can still be in [0, 1] . Which approach is better and why? What is the general guidance? Now provide the response and nothing else.
You don't have to use a different normalization for a different activation function. In fact you don't have to normalize the input to be in [0, 1] for sigmoid. The range of sigmoid [0, 1] is the range of its output. Its range for input (domain) is in fact from minus infinity to positive infinity. What's more is that your input does not go directly into the sigmoid function so the range of your image input is not the same as the range of input that sigmoid would get. There will be some linear layers in between which change the data range. The general guidance is to normalize your input to be in [-1, 1] . This has nothing to be with the activation function but a general effective measure for back propagation. See Effective BackProp .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51646475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/309852/']}
jdg_77419
stackexchange
llm_judgeable_groundtruth_similarity
67618
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: Since Shannon's paper Mathematical theory of communications , probability theory has played an important role on communications (digital and analog). I've been checking some course descriptions on my college and noted that for almost every course related with communications an important prerequisite is probability. Why is that? What is the role of probability in communications? Is it a practical approach or just theoretical? Now provide the response and nothing else.
In analog communications, you are trying to recover a message signal from a received signal containing noise. Noise is a random fluctuation of the signal variable. So with out some theory of what random means, we can't even understand what noise is. Furthermore when we talk about recovering the message signal, we're basically talking about estimating the original signal from the received signal (corrupted by noise). Again, estimation is a fundamental of probability theory. In digital communications, at the most basic level, we talk about receiving bits of a message after they pass through a channel with some probability of error. Again, this description doesn't even have meaning until we have a theory of probability.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/67618', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/11324/']}
jdg_77420
stackexchange
llm_judgeable_groundtruth_similarity
6922050
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 just starting to work on an database application when I realized I should implement MVC pattern as the application is quite complex and involves a number of database operations. In regards to this, I have decided to create a separate model class for handling database operations. This class will have all methods which will return me the data after executing Sqlite command(Select for instance) OR will simply execute the SQLite command(Delete for instance). But what I want is to separate this class from Database Adapter class, where I open, create and close my database. Let me put my concept into code : public class DataModel{/*Private members*/// Method to Select data from Student tablepublic ArrayList<String> FetchStudents (parameter 1){private ArrayList<String> arrStudent;DatabaseAdapter objDB= new DatabaseAdapter();objDB.open(); /*Some code*/objDB.close();return arrStudent}//Method to delete record from Student tablepublic DeleteStudent(parameter 1){DatabaseAdapter objDB= new DatabaseAdapter();objDB.open();//Some codeobjDB.close();}/*Rest of methods*/} //DatabaseAdapterClass private static class DatabaseHelper extends SQLiteOpenHelper {DatabaseHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}/*** onCreate method is called for the 1st time when database doesn't exists.*/@Overridepublic void onCreate(SQLiteDatabase db) {Log.i(TAG, "Creating DataBase: " + CREATE_STUDENT_TABLE);db.execSQL(CREATE_STUDENT_TABLE);}/*** onUpgrade method is called when database version changes.*/@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);}} Question : What I want to ask is this the correct approach of implementation? Is it fine if create separate class for database methods ? What limitations or issues you guys think might trouble me later on? Also, is there a better way to implement the above concept? Thanks Stone Now provide the response and nothing else.
What you are referring to as a 'model class' is more commonly known as a data access object (DAO). Your model would usually be a set of classes that hold your data and business logic. In you case, probably a Student class having an ID, name, GPA, etc. properties. If you want to separate data access from your model, you would have your data access class ( DatabaseHelper ) query the database and use the data it gets to return Student objects or a List<Student> . There is really not much point in separating the data access class from the database helper, it is better to have all of your database-related code in one place. Using model classes (only), however, may not always be practical on Android, because it has native support for getting and displaying data from a Cursor ( CursorAdapter , etc.). If you want to use any of that, you would have to expose your data not as model objects but as Cursor 's. As for content providers, have a look at those too, but if you don't need to expose your data to other applications, writing a ContentProvider might be overkill. On another note, you don't want to be opening and closing the database on each query. It is actually safe to leave it open, it will be automatically closed when your app's process dies.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6922050', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_77421
stackexchange
llm_judgeable_groundtruth_similarity
9028118
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 svnX. When importing project, I check "no ignore" option. (for importing libOAuth.a, ...) But one file is causing a small problem. UserInterfaceState.xcuserstate What is this file? Can I ignore this file? Is it important? Should I commit this file? Now provide the response and nothing else.
What is this file? You can open it in property list editor and have a look -- It stores things like your workspace/project document layouts, nothing you would lose sleep over if lost. Can I ignore this file? You would ignore it in all but exceptional cases. It's easily reconstructed, and should be considered local to your system's user account. To stretch imagination or reason to track it: If you worked by yourself and mirrored your user accounts, then you might want this information synchronized among your machines. Sure, you could track it, but it would produce a lot of unnecessary revision control noise.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9028118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/833182/']}
jdg_77422
stackexchange
llm_judgeable_groundtruth_similarity
687789
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a reason why passing a reference to a std::map as const causes the [] operator to break? I get this compiler error (gcc 4.2) when I use const: error: no match for ‘operator[]’ in ‘map[name]’ Here's the function prototype: void func(const char ch, std::string &str, const std::map<std::string, std::string> &map); And, I should mention that there is no problem when I remove the const keyword in front of std::map . If I've been instructed correctly, the [] operator will actually insert a new pair into the map if it doesn't find the key, which would of course explain why this happens, but I can't imagine that this would ever be acceptable behavior. If there is a better method, like using find instead of [], I'd appreciate it. I can't seem to get find to work either though... I receive const mismatched iterator errors. Now provide the response and nothing else.
Yes you can't use operator[] . Use find , but note it returns const_iterator instead of iterator : std::map<std::string, std::string>::const_iterator it;it = map.find(name);if(it != map.end()) { std::string const& data = it->second; // ...} It's like with pointers. You can't assign int const* to int* . Likewise, you can't assign const_iterator to iterator .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/687789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83369/']}
jdg_77423
stackexchange
llm_judgeable_groundtruth_similarity
2680163
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 noticed that after I use AssemblyDelaySignAttribute to indicate that an assembly is in development and does not need to be signed now, I'll have to use sn -Vr foolib.dll to register for strong name verification to be turned off for this assembly. What's the point of doing this circle ? Why not just leave the assembly unsigned until it's fully done? Isn't that less bothering? Now provide the response and nothing else.
A couple reasons... Assemblies without a strong name cannot be added to the GAC Related to #1, assemblies not in the GAC do not benefit much from NGEN Strong named assemblies exhibit different behavior when it comes to assembly probing and loading with partial names. Assemblies without a strong name cannot be referenced by a strong named assembly So in organizations where the signing process is tightly controlled, it helps to be able to fake it out for development.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2680163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264052/']}
jdg_77424
stackexchange
llm_judgeable_groundtruth_similarity
15780717
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Script <a href="#?cat=MT&typ=1" data-reveal-id="reveal_popup" onclick="pop();" data-closeonbackgroundclick="false" data-dismissmodalclass="close-reveal-modal">due today</a> <a href="#?cat=MT&typ=2" data-reveal-id="reveal_popup" onclick="pop();" data-closeonbackgroundclick="false" data-dismissmodalclass="close-reveal-modal">due in 2 days</a> <div id="reveal_popup" class="reveal-modal"> <div id="popup"></div> <a class="close-reveal-modal">&#215;</a> </div>function pop() { var cat=**value of cat parameter in href** var type=**value of typ parameter in href** $.ajax({ type:'post', url:site_url()+'/event/deleteEventSingle', data:{'cat':cat,'type':typ}, async:false, success:function(result){} });} In this when the user clicks a href same popup appears with different data. there are more than 10 hrefs actually and i am trying to show a calender with user inputted data in the popup. This depends on two parameters cat and typ as shown in href. Requirement Every href has its own cat and typ values. When a href is clicked I want the cat and typ values of the clicked href to be get using jquery so that i can pass these variables in ajax. var cat=**value of cat parameter in href**var type=**value of typ parameter in href** Tried How to get the parameters of an href attribute of a link from the click event object Now provide the response and nothing else.
You can do as soeme thing as below $('a').bind('click',function(){ var url = ($(this).attr('href')); var cat = getURLParameter(url, 'cat'); var typ = getURLParameter(url, 'typ'); //calling the ajax function pop(cat, typ)});function getURLParameter(url, name) { return (RegExp(name + '=' + '(.+?)(&|$)').exec(url)||[,null])[1];}function pop(cat, typ) { $.ajax({ type:'post', url:site_url()+'/event/deleteEventSingle', data:{'cat':cat,'type':typ}, async:false, success:function(result){} });} Check out the the example at Live fiddle http://jsfiddle.net/mayooresan/aY9vy/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15780717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1500524/']}
jdg_77425
stackexchange
llm_judgeable_groundtruth_similarity
51518133
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 found an examle which can do "select all": https://ng-select.github.io/ng-select#/multiselect-checkbox But, I get an error: Cannot read property 'selected' of undefined. I am wondering why I got this error, and how to implement "select all" using ng-select in Angular 5. Thank you Now provide the response and nothing else.
Using ng-select in Angular 5 limits you to using v1.6.3 of ng-select (or < v2.x), but you can accomplish this using the ng-select header template. I included the code below, but this is a working Stackblitz I put together as an example: <ng-select [items]="listOfItems" bindValue="id" bindLabel="name" [multiple]="true" placeholder="Select City" formControlName="example"> <ng-template ng-header-tmp> <div> <button class="btn btn-link" (click)="onSelectAll()">Select All</button> <button class="btn btn-link" (click)="onClearAll()">Clear All</button> </div> </ng-template></ng-select> Then in your controller you would patch the form control with an array of values mapped to only include the bound values you provided to ng-select , which are the bindValue key values. public onSelectAll() { const selected = this.listOfItems.map(item => item.id); this.form.get('example').patchValue(selected);}public onClearAll() { this.form.get('example').patchValue([]);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51518133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9577259/']}
jdg_77426
stackexchange
llm_judgeable_groundtruth_similarity
365008
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: For example, I want to show a list of buttons from 0,0.5,... 5, which jumps for each 0.5. I use a for loop to do that, and have different color at button STANDARD_LINE: var MAX=5.0;var DIFF=0.5var STANDARD_LINE=1.5;for(var i=0;i<=MAX;i=i+DIFF){ button.text=i+''; if(i==STANDARD_LINE){ button.color='red'; }} At this case there should be no rounding errors as each value is exact in IEEE 754.But I'm struggling if I should change it to avoid floating point equality comparison: var MAX=10;var STANDARD_LINE=3;for(var i=0;i<=MAX;i++){ button.text=i/2.0+''; if(i==STANDARD_LINE/2.0){ button.color='red'; }} On one hand, the original code is more simple and forward to me. But there is one thing I'm considering : is i==STANDARD_LINE misleads junior teammates? Does it hide the fact that floating point numbers may have rounding errors? After reading comments from this post: https://stackoverflow.com/questions/33646148/is-hardcode-float-precise-if-it-can-be-represented-by-binary-format-in-ieee-754 it seems there are many developers don't know some float numbers are exact. Should I avoid float number equality comparisons even if it is valid in my case? Or am I over thinking about this? Now provide the response and nothing else.
I would always avoid successive floating-point operations unless the model I'm computing requires them. Floating-point arithmetic is unintuitive to most and a major source of errors. And telling the cases in which it causes errors from those where it doesn't is an even more subtle distinction! Therefore, using floats as loop counters is a defect waiting to happen and would require at the very least a fat background comment explaining why it's okay to use 0.5 here, and that this depends on the specific numeric value. At that point, rewriting the code to avoid float counters will probably be the more readable option. And readability is next to correctness in the hierarchy of professional requirements.
{}
{'log_upvote_score': 8, 'links': ['https://softwareengineering.stackexchange.com/questions/365008', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/248528/']}
jdg_77427
stackexchange
llm_judgeable_groundtruth_similarity
354173
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a Labview program which sends 4-20ma current signal through a ni usb device to control the speed of a motor by controlling a sew eurodrive MOVIDRIVE ® MDX60B / 61B. Here is the data sheet of MOVIDRIVE: https://download.sew-eurodrive.com/download/pdf/16837614.pdf . PAGE 60 shows the layout of signal terminals. On the actual device, the input terminals are just two normal terminals,nothing special. Originally, this motor is controlled by manually pushing some physical buttons on a device. The device is just some kind of signal generator that generats 4-20ma current signal. The MOVIDRIVE ® MDX60B / 61B is set to accept 4-20ma current signal as control input. So how can I switch between the two control signals (1.from labview, 2. from the device) so that there won't be any gap between the switch? I want to accomplish this because if the control signal drops to 0 at some point, the driver may get damaged. Since these equipment (both the movidrive and the motor) is really expensive and important, I can't risk damaging them by placing a switch in the circuit and just switch between the signals. Any advice is much appreciated! Now provide the response and nothing else.
MOSFETs with a diode in their symbol are power MOSFETs , i.e. a class of MOSFETs whose structure has the channel between source and drain oriented "vertically" in the planar structure of the chip. They are sometimes also called vertical MOSFETs for this reason, and they are designated also by the acronyms DMOS, VMOS or VDMOS (these acronyms refer to the shape of the structure viewed in the cross-section of the chip or to the fact that the structure is vertical). This allows greater power dissipation and handling of higher power, compared to "older" lateral MOSFETs, whose channel "lies flat" on the chip surface, like the following image shows: The vertical structure implies that a parasitic diode is formed across source and drain, that's why that diode is almost always depicted in the symbol. Power MOSFETs comprise a large array of specific technologies, developed by individual manufacturer, which go under a plethora of trademark names, such as: HEXFET, TRENCHMOS, etc.. They are all power MOSFETs and they share the same symbol. HEXFET is just the trade mark name of a power MOSFET by International Rectifier, so there is no difference between a power MOSFET and an HEXFET in the sense that an HEXFET is just a power MOSFET produced using a specific proprietary technology. Note that, in reality, a power MOSFET (intended as a discrete device in a package) is made up of several individual MOSFETs (called cells) connected in parallel inside the chip . This is done to optimize efficiency and power handling capability of the device. Keep in mind that "power MOSFET" doesn't necessarily mean "high power". The term was coined when the only MOSFETs available where tiny devices that could handle only milliwatts of power, therefore when the new technology became available they were dubbed "power MOSFETs" because they could handle much more power. Taking as an example jellybean devices common nowadays, the 2N7000 is still a power MOSFET even if it can handle only 350mW max, whereas the IRFZ44N can handle 94W! Nowadays "older" lateral MOSFETs are very specialized devices, rarely used as discrete components. Instead, they are used heavily in digital logic: the ubiquitous CMOS technology, which probably covers 99% of modern digital technology, makes use of complementary MOSFET (P-channel and N-channel) transistors as basic building blocks. Note that I keep saying "older" lateral MOSFET , this is to avoid confusion with a more modern technology used to make power MOSFET, which employs a lateral (i.e. non-vertical) structure. These are devices optimized for power linear applications (i.e. where the transistor works as an amplifier and not as a switch), whereas the classic vertical power MOSFET is more suited for switching applications. EDIT (to answer a doubt expressed in comments and clarify some points) The choice of the symbol of the diode, rectifier vs. Zener, is somewhat arbitrary. The Zener symbol is chosen, most probably, to highlight the fact that, even when the MOSFET is OFF, there is a limitation on max Vds because of that diode entering breakdown. Many devices are characterized in that sense. See for example the 2N7000 datasheet I linked above (yellow emphasis mine): As with any diode, bringing the device into breakdown put you at risk of damaging it. Entering breakdown is not in itself harmful, but in that region the current increases very quickly and the dissipated power consequently, too. Actual Zener diodes are well characterized and their breakdown voltage is specified with a well defined range, therefore you can always control and limit the current so that the power doesn't exceed the max ratings of the device. In a MOSFET, or other non-Zener diodes, the BD voltage is usually given as a minimum value, i.e. they give you that value so as to guarantee a maximum safe value for Vds. They don't specify a max BD-voltage value. This means that, taking that 2N7000G as an example, you may enter breakdown at (say) 60V , 70V or even at 80V. Therefore you have no means, reading the datasheet, to guarantee that the power dissipation is under control: if you apply 65V, for example, you could have barely entered BD, so that the VI product is smallish and can be handled by the device, or you can be in full BD, where the current is huge and the VI product exceed the device ratings.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/354173', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/149141/']}
jdg_77428
stackexchange
llm_judgeable_groundtruth_similarity
1678457
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array of around 200 colours in RGB format. I want to write a program that takes any RGB colour and tries to match a colour from the array that is most "similar". I need a good definition for "similar", which is as close as possible to human perception. I also want to show some information about matching accuracy. For example black-white: 100% and for a similar colour with a slightly different hue: -4%. Do I need to use neural networks? Is there an easier alternative? Now provide the response and nothing else.
Convert all of the colors to the CIE Lab color space and compute the distance in that space deltaE = sqrt(deltaL^2 + deltaA^2 + deltaB^2) Colors with the lowest deltaE are the most perceptually similar to each other.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1678457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/201306/']}
jdg_77429
stackexchange
llm_judgeable_groundtruth_similarity
34965147
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 recyclerview in my app, that contains two textviews, one is rankTextView and other is nameTextview. Something like this; What I want to do is sort this recyclerview, firstly in lowest number order and if there is two same numbers then I want it to be sorted out by Strings. In the above screenshot I have for example, two people rank 1, firstly I want the recyclerview to put these to the top and then sort it out by String. I have searched online to see how can I go about doing this but being new to android I haven't been able to play around/adapt the findings into my project. For example; How to sort Strings on an Android RecyclerView? What is the SortedList<T> working with RecyclerView.Adapter? I have created a custom adapter that contains a textview called rankTextview and another textview called nameTextview, like this; rankTextview = (TextView) itemView.findViewById(R.id.ranktextview); nameTextview = (TextView) itemView.findViewById(R.id.nametextview); then I have a method that takes what value to put in these textview as parameter, like this; public addPerson(String rankTextview, String personTextview,) { this.rankTextview = rankTextview; this.personTextview = personTextview; } and then I call this method in my main class to add data, like this; person.add(new addPerson ("1\nrank", "James Kub"));person.add(new addPerson ("2\nrank", "Peter Hanly"));person.add(new addPerson ("3\nrank", "Josh Penny"));person.add(new addPerson ("1\nrank", "Danny Jackson"));person.add(new addPerson ("3\nrank", "Brad Black")); Now what I want to do is sort out this data firstly by rank lowest number order e.g 1, 2,3... and if there are two same numbers then I want to sort out by name alphabetical order. Also, in future my app will contain points in stead of ranks which will be decimal numbers like this. 1.1, 1.5, 1.1, 2.1, 2.5 and so on, so would it possible to take in count decimal numbers when sorting out by rank. Also, since I had so many lines of code, I wasn't sure which section to provide and which not to provide, please let me know if there is any code I am missing that I should have included. EDITED: public void animateTo(List<ExampleModel> models) { applyAndAnimateRemovals(models); applyAndAnimateAdditions(models); applyAndAnimateMovedItems(models); } private void applyAndAnimateRemovals(List<ExampleModel> newModels) { for (int i = mModels.size() - 1; i >= 0; i--) { final ExampleModel model = mModels.get(i); if (!newModels.contains(model)) { removeItem(i); } } } private void applyAndAnimateAdditions(List<ExampleModel> newModels) { for (int i = 0, count = newModels.size(); i < count; i++) { final ExampleModel model = newModels.get(i); if (!mModels.contains(model)) { // error here, saying cannot resolve method contains addItem(i, model); } } } private void applyAndAnimateMovedItems(List<ExampleModel> newModels) { for (int toPosition = newModels.size() - 1; toPosition >= 0; toPosition--) { final ExampleModel model = newModels.get(toPosition); final int fromPosition = mModels.indexOf(model); if (fromPosition >= 0 && fromPosition != toPosition) { moveItem(fromPosition, toPosition); } } } public ExampleModel removeItem(int position) { final ExampleModel model = mModels.remove(position); // Error here, saying in sortedlist cannot be applied to (int) notifyItemRemoved(position); return model; } public void addItem(int position, ExampleModel model) { mModels.add(position, model); // Error here, saying add has private access in 'android.support.v7.util.SortedList' notifyItemInserted(position); } public void moveItem(int fromPosition, int toPosition) { final ExampleModel model = mModels.remove(fromPosition); // Error here, saying in sortedlist cannot be applied to (int) mModels.add(toPosition, model); // Error here, saying add has private access in 'android.support.v7.util.SortedList' notifyItemMoved(fromPosition, toPosition); } Now provide the response and nothing else.
There are some options for implementing sorting in a RecyclerView . Of course it is possible to rely on Comparable<T> and Comparator<T> interfaces but, as you mentioned, it is also possible to exploit SortedList<T> class defined in Android SDK. Purpose of SortedList<T> is simplifying sorting of elements in a RecyclerView , allowing you to intercept significant events like "new item added", "item removed" and so on. In your case you can proceed as follows: Define a Person class for wrapping rank and name. Please notice that in this version I'm assuming to have integer values for rank, but it's quite easy to move to decimal value. class Person { private String rank; private String name; public Person(String rank, String name) { this.rank = rank; this.name = name; } // getters and setters here} Define an Activity where to build RecyclerView and corresponding adapter. In this example I've included a FloatingActionButton for inserting new random Persons. As you can see, when creating a new Person , method addPerson is invoked on the adapter. Its effect will be to update the RecyclerView , sorting it according to criteria defined within the adapter itself (see point 3). public class SortPersonsActivity extends AppCompatActivity { private List<Person> mPersons; private SortPersonsAdapter mPersonsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_persons_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mPersons = new ArrayList<>(); mPersons.add(new Person("1\nrank", "James Kub")); mPersons.add(new Person("2\nrank", "Peter Hanly")); mPersons.add(new Person("3\nrank", "Josh Penny")); mPersons.add(new Person("1\nrank", "Danny Jackson")); mPersons.add(new Person("3\nrank", "Brad Black")); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.lst_items); recyclerView.setLayoutManager(getLayoutManager()); mPersonsAdapter = new SortPersonsAdapter(this, mPersons); recyclerView.setAdapter(mPersonsAdapter); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // building new fake person Person person = new Person( buildRandomInt(10) + "\nrank", buildRandomName(5) + " " + buildRandomName(5)); // let's keep also basic list updated mPersons.add(person); // let's update adapter mPersonsAdapter.addPerson(person); } }); } private RecyclerView.LayoutManager getLayoutManager() { LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); return llm; } // support method for random names and ranks here} Implement a RecyclerView Adapter relying on SortedList<Person> . Here it's important to notice that all Persons are inserted into a SortedList<Person> . Creating a SortedList<T> requires a Callback to be defined for intercepting events as well as for defining sorting criteria. In our case, as you can see, compare method defines criteria for sorting Persons while onInserted method defines what to do when a new Person is inserted (notify a data set change for updating RecyclerView in this case). Please notice also implementation of addPerson method described at point 2. It just adds a Person to the SortedList , because the logic for updating RecyclerView is embedded into the Callback method onInserted mentioned before. class SortPersonsAdapter extends RecyclerView.Adapter<SortPersonsAdapter.PersonViewHolder> { protected static class PersonViewHolder extends RecyclerView.ViewHolder { View layout; TextView txt_rank; TextView txt_full_name; public PersonViewHolder(View itemView) { super(itemView); layout = itemView; txt_rank = (TextView) itemView.findViewById(R.id.txt_rank); txt_full_name = (TextView) itemView.findViewById(R.id.txt_full_name); } } private Context mContext; private LayoutInflater mLayoutInflater; private SortedList<Person> mPersons; public SortPersonsAdapter(Context context, List<Person> persons) { mContext = context; mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mPersons = new SortedList<>(Person.class, new PersonListCallback()); mPersons.addAll(persons); } public void addPerson(Person person) { mPersons.add(person); } @Override public int getItemCount() { return mPersons.size(); } @Override public SortPersonsAdapter.PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = mLayoutInflater.inflate(R.layout.view_person_item, parent, false); return new PersonViewHolder(itemView); } @Override public void onBindViewHolder(final PersonViewHolder viewHolder, final int position) { Person person = mPersons.get(position); viewHolder.txt_rank.setText(person.getRank()); viewHolder.txt_full_name.setText(person.getName()); } /** * Implementation of callback for getting updates on person list changes. */ private class PersonListCallback extends SortedList.Callback<Person> { @Override public int compare(Person p1, Person p2) { String[] rank1 = p1.getStringRank().split("\n"); String[] rank2 = p2.getStringRank().split("\n"); int diff = Integer.parseInt(rank1[0]) - Integer.parseInt(rank2[0]); return (diff == 0) ? p1.getName().compareTo(p2.getName()) : diff; } @Override public void onInserted(int position, int count) { notifyItemInserted(position); } @Override public void onRemoved(int position, int count) { notifyItemRemoved(position); } @Override public void onMoved(int fromPosition, int toPosition) { } @Override public void onChanged(int position, int count) { } @Override public boolean areContentsTheSame(Person oldItem, Person newItem) { return false; } @Override public boolean areItemsTheSame(Person item1, Person item2) { return false; } }} Hope this could help. Here I've put an implementation for your RecyclerView , in case you need more details on code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34965147', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4408769/']}
jdg_77430
stackexchange
llm_judgeable_groundtruth_similarity
32247643
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 lot of dataframes created as part of preprocessing. Since I have limited 6GB ram, I want to delete all the unnecessary dataframes from RAM to avoid running out of memory when running GRIDSEARCHCV in scikit-learn. 1) Is there a function to list only, all the dataframes currently loaded in memory? I tried dir() but it gives lot of other object other than dataframes. 2) I created a list of dataframes to delete del_df=[Gender_dummies, capsule_trans, col, concat_df_list, coup_CAPSULE_dummies] & ran for i in del_df: del (i) But its not deleting the dataframes. But deleting dataframes individiallylike below is deleting dataframe from memory. del Gender_dummiesdel col Now provide the response and nothing else.
del statement does not delete an instance, it merely deletes a name. When you do del i , you are deleting just the name i - but the instance is still bound to some other name, so it won't be Garbage-Collected. If you want to release memory, your dataframes has to be Garbage-Collected , i.e. delete all references to them. If you created your dateframes dynamically to list, then removing that list will trigger Garbage Collection. >>> lst = [pd.DataFrame(), pd.DataFrame(), pd.DataFrame()]>>> del lst # memory is released If you created some variables, you have to delete them all. >>> a, b, c = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()>>> lst = [a, b, c]>>> del a, b, c # dfs still in list>>> del lst # memory release now
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32247643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3424990/']}
jdg_77431
stackexchange
llm_judgeable_groundtruth_similarity
1575286
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How can I get the list of opened files by an application, using Delphi?For example what files are opened by winword.exe Now provide the response and nothing else.
Using the Native API function NtQuerySystemInformation you can list all open handles from all processes. try this example program ListAllHandles;{$APPTYPE CONSOLE}uses PSApi, Windows, SysUtils;constSystemHandleInformation = $10;STATUS_SUCCESS = $00000000;STATUS_BUFFER_OVERFLOW = $80000005;STATUS_INFO_LENGTH_MISMATCH = $C0000004;DefaulBUFFERSIZE = $100000;type OBJECT_INFORMATION_CLASS = (ObjectBasicInformation,ObjectNameInformation,ObjectTypeInformation,ObjectAllTypesInformation,ObjectHandleInformation ); SYSTEM_HANDLE=packed record uIdProcess:ULONG; ObjectType:UCHAR; Flags :UCHAR; Handle :Word; pObject :Pointer; GrantedAccess:ACCESS_MASK; end; PSYSTEM_HANDLE = ^SYSTEM_HANDLE; SYSTEM_HANDLE_ARRAY = Array[0..0] of SYSTEM_HANDLE; PSYSTEM_HANDLE_ARRAY= ^SYSTEM_HANDLE_ARRAY; SYSTEM_HANDLE_INFORMATION=packed record uCount:ULONG; Handles:SYSTEM_HANDLE_ARRAY; end; PSYSTEM_HANDLE_INFORMATION=^SYSTEM_HANDLE_INFORMATION; TNtQuerySystemInformation=function (SystemInformationClass:DWORD; SystemInformation:pointer; SystemInformationLength:DWORD; ReturnLength:PDWORD):THandle; stdcall; TNtQueryObject =function (ObjectHandle:cardinal; ObjectInformationClass:OBJECT_INFORMATION_CLASS; ObjectInformation:pointer; Length:ULONG;ResultLength:PDWORD):THandle;stdcall; UNICODE_STRING=packed record Length :Word; MaximumLength:Word; Buffer :PWideChar; end; OBJECT_NAME_INFORMATION=UNICODE_STRING; POBJECT_NAME_INFORMATION=^OBJECT_NAME_INFORMATION;Var NTQueryObject :TNtQueryObject; NTQuerySystemInformation:TNTQuerySystemInformation;function GetObjectInfo(hObject:cardinal; objInfoClass:OBJECT_INFORMATION_CLASS):LPWSTR;var pObjectInfo:POBJECT_NAME_INFORMATION; HDummy :THandle; dwSize :DWORD;begin Result:=nil; dwSize := sizeof(OBJECT_NAME_INFORMATION); pObjectInfo := AllocMem(dwSize); HDummy := NTQueryObject(hObject, objInfoClass, pObjectInfo,dwSize, @dwSize); if((HDummy = STATUS_BUFFER_OVERFLOW) or (HDummy = STATUS_INFO_LENGTH_MISMATCH)) then begin FreeMem(pObjectInfo); pObjectInfo := AllocMem(dwSize); HDummy := NTQueryObject(hObject, objInfoClass, pObjectInfo,dwSize, @dwSize); end; if((HDummy >= STATUS_SUCCESS) and (pObjectInfo.Buffer <> nil)) then begin Result := AllocMem(pObjectInfo.Length + sizeof(WCHAR)); CopyMemory(result, pObjectInfo.Buffer, pObjectInfo.Length); end; FreeMem(pObjectInfo);end;Procedure EnumerateOpenFiles();var sDummy : string; hProcess : THandle; hObject : THandle; ResultLength: DWORD; aBufferSize : DWORD; aIndex : Integer; pHandleInfo : PSYSTEM_HANDLE_INFORMATION; HDummy : THandle; lpwsName : PWideChar; lpwsType : PWideChar; lpszProcess : PAnsiChar;begin AbufferSize := DefaulBUFFERSIZE; pHandleInfo := AllocMem(AbufferSize); HDummy := NTQuerySystemInformation(DWORD(SystemHandleInformation), pHandleInfo,AbufferSize, @ResultLength); //Get the list of handles if(HDummy = STATUS_SUCCESS) then //If no error continue begin for aIndex:=0 to pHandleInfo^.uCount-1 do //iterate the list begin hProcess := OpenProcess(PROCESS_DUP_HANDLE or PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, FALSE, pHandleInfo.Handles[aIndex].uIdProcess); //open the process to get aditional info if(hProcess <> INVALID_HANDLE_VALUE) then //Check valid handle begin hObject := 0; if DuplicateHandle(hProcess, pHandleInfo.Handles[aIndex].Handle,GetCurrentProcess(), @hObject, STANDARD_RIGHTS_REQUIRED,FALSE, 0) then //Get a copy of the original handle begin lpwsName := GetObjectInfo(hObject, ObjectNameInformation); //Get the filename linked to the handle if (lpwsName <> nil) then begin lpwsType := GetObjectInfo(hObject, ObjectTypeInformation); lpszProcess := AllocMem(MAX_PATH); if GetModuleFileNameEx(hProcess, 0,lpszProcess, MAX_PATH)<>0 then //get the name of the process sDummy:=ExtractFileName(lpszProcess) else sDummy:= 'System Process'; Writeln('PID ',pHandleInfo.Handles[aIndex].uIdProcess); Writeln('Handle ',pHandleInfo.Handles[aIndex].Handle); Writeln('Process ',sDummy); Writeln('FileName ',string(lpwsName)); Writeln; FreeMem(lpwsName); FreeMem(lpwsType); FreeMem(lpszProcess); end; CloseHandle(hObject); end; CloseHandle(hProcess); end; end; end; FreeMem(pHandleInfo);end;begin try NTQueryObject := GetProcAddress(GetModuleHandle('NTDLL.DLL'), 'NtQueryObject'); NTQuerySystemInformation := GetProcAddress(GetModuleHandle('NTDLL.DLL'), 'NtQuerySystemInformation'); if (@NTQuerySystemInformation<>nil) and (@NTQuerySystemInformation<>nil) then EnumerateOpenFiles(); Readln; except on E:Exception do Writeln(E.Classname, ': ', E.Message); end;end.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1575286', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168946/']}
jdg_77432
stackexchange
llm_judgeable_groundtruth_similarity
4084720
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 this question, I am asked to express $\sum_{n=1}^{\infty}\frac{nx^n}{(n+1)!}$ as elementary functions (for example, $\log x, x^2, \sqrt{x}$ , etc) List of elementary functions v https://en.wikipedia.org/wiki/Elementary_function#Examples How would I break down an infinite sum into such functions? Well, first thing I thought about is using integration techniques. We can write the infinite sum as $\sum_{n=1}^{\infty}\frac{n}{(n+1)!}x^n$ . Let $a_n = \frac{n}{(n+1)!}$ , then $\sum_{n=0}^{\infty}\int a_n x^ndx = \sum_{n=1}^{\infty}\frac{a_n}{n+1} x^{n+1}+C$ , and C is a constant. Is this approach correct? If so, how would it work? Now provide the response and nothing else.
Notice \begin{align*}\sum^\infty_{n=1} \frac{nx^n}{(n+1)!} &= \sum^\infty_{n=1} \frac{(n+1)x^n}{(n+1)!} - \sum^\infty_{n=1} \frac{x^n}{(n+1)!}\\&= \sum^\infty_{n=1} \frac{x^n}{n!} - \frac1{x}\sum^\infty_{n=1} \frac{x^{n+1}}{(n+1)!}\\&= (e^x - 1) - \frac 1 x(e^x - 1 - x).\end{align*}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4084720', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/893042/']}
jdg_77433
stackexchange
llm_judgeable_groundtruth_similarity
7582485
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 running a long query from PHP, [how] can I kill the query if the user presses stop in their browser? Take into consideration that I cannot call any other PHP functions because PHP is blocked while waiting for MySQL. Also I cannot make any more requests to the server (via Ajax) because of session locking. So one solution could be: ignore user abort run the long query in the back ground and have PHP check every 100ms if it has finished get the pid from the query if the user aborts, kill the pid else return the result when finished The 2 thing that I dont know how to do in that is: run a non blocking (background) query get the pid of a query Now provide the response and nothing else.
For those who are interested, here is what I used: <?php// Connection to query on$query_con = mysqli_connect($host, $user, $password, $name, $port);// Connection to kill on$kill_con = mysqli_connect($host, $user, $password, $name, $port);// Start the query$query_con->query($slow_query, MYSQLI_ASYNC);// Get the PID$thread_id = $query_con->thread_id;// Ignore user abort so we can kill the queryignore_user_abort(true);do { // Poll MySQL $links = $errors = $reject = array($mysqli->mysqli); $poll = mysqli_poll($links, $errors, $reject, 0, 500000); // Check if the connection is aborted and the query was killed if (connection_aborted() && mysqli_kill($kill_con, $thread_id)) { die(); }} while (!$poll);// Not aborted, so do stuff with the result$result = $link->reap_async_query();if (is_object($result)) { // Select while ($row = $result->fetch_object()) { var_dump($row); }} else { // Insert/update/delete var_dump($result);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7582485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/268074/']}
jdg_77434
stackexchange
llm_judgeable_groundtruth_similarity
37185361
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the following command to import a third-party jar, which is not available online, into my local Maven repository for purposes of building my project: mvn install:install-file -Dfile=C:\Users\MNXE\plugins\myArtifactTest-generate\myArtifactTest-generate-plugin\lib\autoitx4java.jar -DgroupId=com.autoit.code -DartifactId=autoitx4java -Dversion=1.0.0 -Dpackaging=jar -DgeneratePom=true The dependency in my pom file for this jar looks like: <dependency> <groupId>com.autoit.code</groupId> <artifactId>autoitx4java</artifactId> <version>1.0.0</version> </dependency> The following is the full stack trace of my error while attempting to install the Maven project. Regardless of my attempt to install the jar, or include the jar in my build path in Eclipse, nothing seems to work. I continue to get a compilation error: C:\Users\MNXE\plugins\myArtifactTest-generate>mvn install -e[INFO] Error stacktraces are turned on.[INFO] Scanning for projects...[INFO] ------------------------------------------------------------------------[INFO] Reactor Build Order:[INFO][INFO] OO sample content project[INFO] myArtifactTest-generate-plugin[INFO] myArtifactTest-generate-cp[INFO][INFO] ------------------------------------------------------------------------[INFO] Building OO sample content project 1.0.0[INFO] ------------------------------------------------------------------------[INFO][INFO] --- maven-install-plugin:2.3.1:install (default-install) @ myArtifactTest-generate ---[INFO] Installing C:\Users\MNXE\plugins\myArtifactTest-generate\pom.xml to C:\Users\MNXE\.m2\repository\myGroupTest-generate\myArtifactTest-generate\1.0.0\myArtifactTest-generate-1.0.0.pom[INFO][INFO] ------------------------------------------------------------------------[INFO] Building myArtifactTest-generate-plugin 1.0.0[INFO] ------------------------------------------------------------------------[INFO][INFO] --- oo-action-plugin-maven-plugin:10.20.8:generate-action-plugin (generate-contentpack-plugin) @ myArtifactTest-generate-plugin ---[INFO][INFO] --- maven-plugin-plugin:2.9:descriptor (default-descriptor) @ myArtifactTest-generate-plugin ---[WARNING] Using platform encoding (Cp1250 actually) to read mojo metadata, i.e.build is platform dependent![INFO] Applying mojo extractor for language: java[INFO] Mojo extractor for language: java found 4 mojo descriptors.[INFO] Applying mojo extractor for language: bsh[INFO] Mojo extractor for language: bsh found 0 mojo descriptors.[INFO][INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ myArtifactTest-generate-plugin ---[debug] execute contextualize[WARNING] Using platform encoding (Cp1250 actually) to copy filtered resources,i.e. build is platform dependent![INFO] skip non existing resourceDirectory C:\Users\MNXE\plugins\myArtifactTest-generate\myArtifactTest-generate-plugin\src\main\resources[INFO][INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ myArtifactTest-generate-plugin ---[INFO] Changes detected - recompiling the module![WARNING] File encoding has not been set, using platform encoding Cp1250, i.e. build is platform dependent![INFO] Compiling 5 source files to C:\Users\MNXE\plugins\myArtifactTest-generate\myArtifactTest-generate-plugin\target\classes[INFO] -------------------------------------------------------------[ERROR] COMPILATION ERROR :[INFO] -------------------------------------------------------------[ERROR] /C:/Users/MNXE/plugins/myArtifactTest-generate/myArtifactTest-generate-plugin/src/main/java/SampleActions.java:[9,20] package autoitx4java does not exist[ERROR] /C:/Users/MNXE/plugins/myArtifactTest-generate/myArtifactTest-generate-plugin/src/main/java/SampleActions.java:[123,38] cannot find symbol symbol: class AutoItX location: class SampleActions[ERROR] /C:/Users/MNXE/plugins/myArtifactTest-generate/myArtifactTest-generate-plugin/src/main/java/SampleActions.java:[128,41] cannot find symbol symbol: class AutoItX location: class SampleActions[ERROR] /C:/Users/MNXE/plugins/myArtifactTest-generate/myArtifactTest-generate-plugin/src/main/java/SampleActions.java:[133,39] cannot find symbol symbol: class AutoItX location: class SampleActions[INFO] 4 errors[INFO] -------------------------------------------------------------[INFO] ------------------------------------------------------------------------[INFO] Reactor Summary:[INFO][INFO] OO sample content project ......................... SUCCESS [0.817s][INFO] myArtifactTest-generate-plugin .................... FAILURE [6.999s][INFO] myArtifactTest-generate-cp ........................ SKIPPED[INFO] ------------------------------------------------------------------------[INFO] BUILD FAILURE[INFO] ------------------------------------------------------------------------[INFO] Total time: 7.994s[INFO] Finished at: Thu May 12 11:33:43 CEST 2016[INFO] Final Memory: 17M/213M[INFO] ------------------------------------------------------------------------[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project myArtifactTest-generate-plugin: Compilation failure: Compilation failure:[ERROR] /C:/Users/MNXE/plugins/myArtifactTest-generate/myArtifactTest-generate-plugin/src/main/java/SampleActions.java:[9,20] package autoitx4java does not exist[ERROR] /C:/Users/MNXE/plugins/myArtifactTest-generate/myArtifactTest-generate-plugin/src/main/java/SampleActions.java:[123,38] cannot find symbol[ERROR] symbol: class AutoItX[ERROR] location: class SampleActions[ERROR] /C:/Users/MNXE/plugins/myArtifactTest-generate/myArtifactTest-generate-plugin/src/main/java/SampleActions.java:[128,41] cannot find symbol[ERROR] symbol: class AutoItX[ERROR] location: class SampleActions[ERROR] /C:/Users/MNXE/plugins/myArtifactTest-generate/myArtifactTest-generate-plugin/src/main/java/SampleActions.java:[133,39] cannot find symbol[ERROR] symbol: class AutoItX[ERROR] location: class SampleActions[ERROR] -> [Help 1]org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project myArtifactTest-generate-plugin: Compilation failure at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59) at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161) at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320) at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156) at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537) at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196) at org.apache.maven.cli.MavenCli.main(MavenCli.java:141) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290) at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409) at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)Caused by: org.apache.maven.plugin.compiler.CompilationFailureException: Compilation failure at org.apache.maven.plugin.compiler.AbstractCompilerMojo.execute(AbstractCompilerMojo.java:858) at org.apache.maven.plugin.compiler.CompilerMojo.execute(CompilerMojo.java:129) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101) at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209) ... 19 more[ERROR][ERROR] Re-run Maven using the -X switch to enable full debug logging.[ERROR][ERROR] For more information about the errors and possible solutions, please read the following articles:[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException[ERROR][ERROR] After correcting the problems, you can resume the build with the command[ERROR] mvn <goals> -rf :myArtifactTest-generate-pluginC:\Users\MNXE\plugins\myArtifactTest-generate> Now provide the response and nothing else.
As far as I can see, the code is designed to check if all the items of the myArray are in the myExists the implementation: isValid = myArray .All(item => myList.Exists(x => x.Value == item)); if you want to refactor for performace as well as for readability , have a look for bottlenecks. Say, is it myList.Exists that slows down? In that case think of HashSet<T> where T is a type of x.Value etc.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37185361', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4077513/']}
jdg_77435
stackexchange
llm_judgeable_groundtruth_similarity
1195095
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm practicing with Winding Numbers , and encountered an interesting example. You might be familiar with this liantong symbol, the logo of China Unicom: Suppose we make this into a fully closed and connected curve, and try to determine the Winding Numbers of the various points in the symbol. For instance: Find the winding numbers of the closed curve shown below at $z_1,z_2,z_3,z_4,z_5$ It seems to me that for each $z$, the winding number $W(z)$ is: $W(z_1)=0$ (since it is outside the curve) $W(z_2)=1$ (since it falls to the left of the curve in one loop) $W(z_3)=-2$ (since it falls to the right of the curve in two loops) $W(z_4)=0$ (since it falls to the right and to the left of the curve twice each, cancelling out) $W(z_5)=-1$ (since it falls to the right of the curve in one loop) Would you agree with these winding numbers (and given reasoning)? Thank you for your help! Now provide the response and nothing else.
If a curve crosses your path from left to right, the winding number increases. If a curve crosses your path from right to left, the winding number decreases. Going from $z_1$ to $z_2$, the curve crosses our path from left to right. Therefore, $\mathrm{W}(z_2)=1$. Going from $z_1$ to $z_3$, the curve crosses our path from right to left. Therefore, $\mathrm{W}(z_3)=-1$. Going from $z_3$ to $z_4$, the curve crosses our path from left to right. Therefore, $\mathrm{W}(z_4)=0$. Going from $z_4$ to $z_5$, the curve crosses our path from right to left. Therefore, $\mathrm{W}(z_5)=-1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1195095', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/100167/']}
jdg_77436
stackexchange
llm_judgeable_groundtruth_similarity
18219779
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 read this: Importing a CSV file into a sqlite3 database table using Python and it seems that everyone suggests using line-by-line reading instead of using bulk .import from SQLite. However, that will make the insertion really slow if you have millions of rows of data. Is there any other way to circumvent this? Update: I tried the following code to insert line by line but the speed is not as good as I expected. Is there anyway to improve it for logFileName in allLogFilesName: logFile = codecs.open(logFileName, 'rb', encoding='utf-8') for logLine in logFile: logLineAsList = logLine.split('\t') output.execute('''INSERT INTO log VALUES(?, ?, ?, ?)''', logLineAsList) logFile.close()connection.commit()connection.close() Now provide the response and nothing else.
Divide your data into chunks on the fly using generator expressions, make inserts inside the transaction. Here's a quote from sqlite optimization FAQ : Unless already in a transaction, each SQL statement has a new transaction started for it. This is very expensive, since it requires reopening, writing to, and closing the journal file for each statement. This can be avoided by wrapping sequences of SQL statements with BEGIN TRANSACTION; and END TRANSACTION; statements. This speedup is also obtained for statements which don't alter the database. Here's how your code may look like. Also, sqlite has an ability to import CSV files .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18219779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2521066/']}
jdg_77437
stackexchange
llm_judgeable_groundtruth_similarity
9904653
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: CSS Select Selector What is the CSS equivalent to the following when dealing with select lists? input[type="text"]input[type="submit"] Now provide the response and nothing else.
The input[type="text"] CSS selector can be broken down into; input ; find all elements that are input elements. [type="text"] ; filter those elements by those which have the type attribute of text . Because a select box is a <select> element rather than a <input type="select" /> , you can just use the select selector as follows; select { /* blah blah blah*/}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9904653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1073117/']}
jdg_77438
stackexchange
llm_judgeable_groundtruth_similarity
8012462
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: (Note, I'm not looking for the answer git rebase -i ) In mercurial, I can "reopen" a commit by importing it into my patch queue: hg qimport tip The commit is "open" in the sense that it's just like before I had committed it, I can revert, do hg diff , hg status , etc. How do I do this in git? (Everything I've found on the web suggests git rebase -i and then choose edit , but that's different, because the commit is not "open" in the same way.) Now provide the response and nothing else.
You just need to move your HEAD pointer up without making any changes to your working copy: git reset --soft HEAD^ Reset moves the pointer, and the soft option specifies that it shouldn't change any of your files. The default is mixed, which will reset your index, and the hard option will actually remove the changes since that commit in your working copy. HEAD is a "magic" git pointer that is always pointing to the current ref (i.e. the parent of your working copy). The caret (^) indicates the parent. You can use this repeatedly, e.g. HEAD^^ refers to the parent of the last commit.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8012462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/104021/']}
jdg_77439
stackexchange
llm_judgeable_groundtruth_similarity
7548480
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following this excellent tutorial for futures , promises and packaged tasks I got to the the point where I wanted to prepare my own task #include <iostream>#include <future>using namespace std;int ackermann(int m, int n) { // might take a while if(m==0) return n+1; if(n==0) return ackermann(m-1,1); return ackermann(m-1, ackermann(m, n-1));}int main () { packaged_task<int(int,int)> task1 { &ackermann, 3, 11 }; // <- error auto f1 = task1.get_future(); thread th1 { move(task1) }; // call cout << " ack(3,11):" << f1.get() << endl; th1.join();} As far as I can decipher the gcc-4.7.0 error message it expects the arguments differently? But how? I try to shorten the error message: error: no matching function for call to 'std::packaged_task<int(int, int)>::packaged_task(<brace-enclosed initializer list>)'note: candidates are: std::packaged_task<_Res(_ArgTypes ...)>::---<_Res(_ArgTypes ...)>&&) ---note: candidate expects 1 argument, 3 provided ...note: cannot convert 'ackermann' (type 'int (*)(int, int)') to type 'std::allocator_arg_t' Is my variant how I provide the parameters for ackermann wrong? Or is it the wrong template parameter? I do not give the parameters 3,11 to the creation of thread, right? Update other unsuccessful variants: packaged_task<int()> task1 ( []{return ackermann(3,11);} );thread th1 { move(task1) };packaged_task<int()> task1 ( bind(&ackermann,3,11) );thread th1 { move(task1) };packaged_task<int(int,int)> task1 ( &ackermann );thread th1 { move(task1), 3,11 }; hmm... is it me, or is it the beta-gcc? Now provide the response and nothing else.
Firstly, if you declare std::packaged_task to take arguments, then you must pass them to operator() , not the constructor. In a single thread you can thus do: std::packaged_task<int(int,int)> task(&ackermann);auto f=task.get_future();task(3,11);std::cout<<f.get()<<std::endl; To do the same with a thread, you must move the task into the thread, and pass the arguments too: std::packaged_task<int(int,int)> task(&ackermann);auto f=task.get_future();std::thread t(std::move(task),3,11);t.join();std::cout<<f.get()<<std::endl; Alternatively, you can bind the arguments directly before you construct the task, in which case the task itself now has a signature that takes no arguments: std::packaged_task<int()> task(std::bind(&ackermann,3,11));auto f=task.get_future();task();std::cout<<f.get()<<std::endl; Again, you can do this and pass it to a thread: std::packaged_task<int()> task(std::bind(&ackermann,3,11));auto f=task.get_future();std::thread t(std::move(task));t.join();std::cout<<f.get()<<std::endl; All of these examples should work (and do, with both g++ 4.6 and MSVC2010 and my just::thread implementation of the thread library). If any do not then there is a bug in the compiler or library you are using. For example, the library shipped with g++ 4.6 cannot handle passing move-only objects such as a std::packaged_task to std::thread (and thus fails to handle the 2nd and 4th examples), since it uses std::bind as an implementation detail, and that implementation of std::bind incorrectly requires that the arguments are copyable.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7548480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/472245/']}
jdg_77440