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
|
276078
|
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:
Please change the requirement that allows an answer to make it into the Late Answers Review Queue (LARQ) here on Stack Overflow. According to here , the answer must be posted 30 days after the question was asked or later for it to be a late answer. Please change that to 14 or 10 or 7 days instead. There's a lack of reviews that users can do in that queue, so please lower this to help people be able to review more late answers. It will also help find unwanted spammish posts, low-quality posts, answers that aren't answers, users posting comments or questions as an answer, etc. faster than we can find these now. Lastly, it will give more attention to answers that happen in this time period, so people can upvote or downvote as they see fit. Posting an answer 14 days after the question was asked is considered late for most questions on Stack Overflow. Most questions get answered within the first two days. The LARQ can handle a big increase in the number of posts that end up there, so that won't be a problem. Please Note: This feature request is definitely not about the fact that I really would like to add a Gold Badge for that queue sometime this century. I ran some queries to get a general idea of how many extra reviews this would mean for the late answers queue. Since I'm using SEDE , this only counts non -deleted answers, since deleted answers don't show up there. There have been about 26,751,487 answers posted so far. Deleted or un-deleted. Found this by looking at the id of one of the newest answers on the site. According to this query there are currently about 14,070,167 answers that have not been deleted. Meaning about 12.6 million answers have been deleted. 12,121,030 query non-deleted answers have been posted < 7 days after the question was asked 1,525,719 query non-deleted answers have been posted >= 30 days after the question was asked 423,418 query non-deleted answers have been posted >= 7 days but < 30 days after the question was asked 192,132 query non-deleted answers have been posted >= 14 days but < 30 days after the question was asked More than 86% of non-deleted answers have been answered within one week of the question being asked. There are very few non-deleted answers that were asked between 14 and 30 days.. so few that I may as well change my request of a late answer being 14 days old, to that of seven days. Or we could meet towards the middle at 10 days old as a compromise. This data, although not exact since I can't query the deleted answers themselves , shows that it would be no problem for the community to handle late answers of two weeks after the question was asked and possibly even a week after. I'd be fine starting out at 14 days and seeing how it goes.
Now provide the response and nothing else.
|
The reason late answers are considered suspicious is not just because most questions are answered quickly. It's also because most questions are old . Consider a spammer, picking a question at random (or, more likely, based on a google search). The minor pagerank bump for recently updated pages notwithstanding, it is extremely unlikely that he'll end up at a question that's less than a month old, let alone less than a week old. Now consider if he's picking off the "new questions" list. The questions he posts on will be a few minutes or hours old. Now, consider a non-spammer user. True, most of his answers will be for recently asked questions... and some will be for very old questions, because he got there through google. But some will be based on watched tags, or questions he read a while ago but never went back to, or... etc. Both of these groups have a question-age falloff, but it's much steeper for spammers. So I highly doubt that dropping the threshold age would result in anything except more false positives, further diluting an already diluted review queue.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/276078', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/3041194/']}
|
jdg_378641
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6913512
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From this original question , how would I apply a sort on multiple fields? Using this slightly adapted structure, how would I sort city (ascending) & then price (descending)? var homes = [ {"h_id":"3", "city":"Dallas", "state":"TX", "zip":"75201", "price":"162500"}, {"h_id":"4", "city":"Bevery Hills", "state":"CA", "zip":"90210", "price":"319250"}, {"h_id":"6", "city":"Dallas", "state":"TX", "zip":"75000", "price":"556699"}, {"h_id":"5", "city":"New York", "state":"NY", "zip":"00010", "price":"962500"} ]; I liked the fact than an answer was given which provided a general approach. Where I plan to use this code, I will have to sort dates as well as other things. The ability to "prime" the object seemed handy, if not a little cumbersome. I've tried to build this answer into a nice generic example, but I'm not having much luck.
Now provide the response and nothing else.
|
You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero. var data = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500" }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250" }, { h_id: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];data.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price;});console.log(data); .as-console-wrapper { max-height: 100% !important; top: 0; } Or, using es6, simply: data.sort((a, b) => a.city.localeCompare(b.city) || b.price - a.price);
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6913512', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178383/']}
|
jdg_378642
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8444570
|
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 use an IF statement in a MySQL select query. I am getting an error after the AND statement where the first IF . SELECT J.JOB_ID,E.COMPANY_NAME,J.JOB_DESC,JT.JOBTYPE_NAME,J.COMPENSATION,ST.STATE_NAME,MC.METRO_CITY_NAME,I.INDUSTRY_NAME, J.JOB_CONTACT_PERSON,J.DT_INSRT,J.JOB_TITLE,J.JOB_EXP_DATE,J.SKILLS FROM JOBS J JOIN EMPLOYER E ON J.COMPANY_ID=E.COMPANY_ID JOIN LOOKUP_JOBTYPE JT ON J.JOB_TYPE=JT.JOBTYPE_ID JOIN LOOKUP_STATE ST ON J.STATE_ID=ST.STATE_ID JOIN JOBS_LOCATION JL ON J.JOB_ID=JL.JOB_ID JOIN LOOKUP_METRO_CITY MC ON JL.METRO_CITY_ID=MC.METRO_CITY_ID JOIN LOOKUP_INDUSTRY I ON J.INDUSTRY_ID=I.INDUSTRY_ID JOIN JOBS_QUALIFICATION JQ ON J.JOB_ID=JQ.JOB_ID JOIN LOOKUP_DEGREE_QUALIFICATION LDQ ON LDQ.QUALIFICATION_ID = JQ.QUALIFICATION_ID WHERE J.ACTIVE='Y' AND J.DT_INSRT > COALESCE(pEmailSntDt,DATE_SUB(SYSDATE(),INTERVAL 4 DAY)) ANDIF(JQ.COURSE_ID=0) THENIF(JQ.DEGREE_ID=0)THEN J.SKILLS LIKE CONCAT('%', pSkills,'%')ELSEJQ.DEGREE_ID=pDegreeId OR J.SKILLS LIKE CONCAT('%', pSkills,'%')END IFELSEJQ.COURSE_ID=pCourseId OR IF(JQ.DEGREE_ID=0) THEN J.SKILLS LIKE CONCAT('%', pSkills,'%') ELSE JQ.DEGREE_ID=pDegreeId OR J.SKILLS LIKE CONCAT('%', pSkills,'%') END IFEND IF GROUP BY J.JOB_ID ORDER BY J.DT_INSRT DESC; Why doesn't this work and what is the proper way to do an IF statement in a MySQL query?
Now provide the response and nothing else.
|
The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this. The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query: SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNSFROM ...WHERE ...
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8444570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838893/']}
|
jdg_378643
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20767745
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Introduction In every textbook on C/C++, you'll find an operator precedence and associativity table such as the following: http://en.cppreference.com/w/cpp/language/operator_precedence One of the questions on StackOverflow asked something like this: What order do the following functions execute: f1() * f2() + f3(); f1() + f2() * f3(); Referring to the previous chart I confidently replied that functions have left-to-right associativity so in the previous statements the are evaluated like this in both cases: f1() -> f2() -> f3() After the functions are evaluated you finish the evaluation like this: (a1 * a2) + a3 a1 + (a2 * a3) To my surprise, many people told me I was flat out wrong. Determined to prove them wrong, I decided to turn to the ANSI C11 standard. I was once again surprised to find out that very little is mentioned on operator precedence and associativity. Questions If my belief that functions are always evaluated from left-to-right is wrong, what does the table referring to function precedence and associativity really mean? Who defines operator precedence and associativity if it's not ANSI? If it is ANSI who makes the definition, why is little mentioned about operator precedence and associativity? Is operator precedence and associativity inferred from the ANSI C standard or is it defined in Mathematics?
Now provide the response and nothing else.
|
Operator precedence is defined in the appropriate standard. The standards for C and C++ are the One True Definition of what exactly C and C++ are. So if you look closely, the details are there. In fact, the details are in the grammar of the language. For example, take a look at the grammar production rule for + and - in C++ (collectively, additive-expressions ): additive-expression: multiplicative-expression additive-expression + multiplicative-expression additive-expression - multiplicative-expression As you can see, a multiplicative-expression is a subrule of an additive-expression . This means that if you have something like x + y * z , the y * z expression is a subexpression of x + y * z . This defines the precedence between these two operators. We can also see that the left operand of an additive-expression expands to another additive-expression , which means that with x + y + z , x + y is a subexpression of it. This defines the associativity . Associativity determines how adjacent uses of the same operator will be grouped. For example, + is left-to-right associative, which means that x + y + z will be grouped like so: (x + y) + z . Don't mistake this for order of evaluation . There is absolutely no reason why the value of z could not be computed before x + y is. What matters is that it is x + y that is computed and not y + z . For the function call operator, left-to-right associativity means that f()() (which could happen if f returned a function pointer, for example) is grouped like so: (f())() (of course, the other direction wouldn't make any sense). Now let's consider the example you were looking at: f1() + f2() * f3() The * operator has higher precedence than the + operator, so the expressions are grouped like so: f1() + (f2() * f3()) We don't even have to consider associativity here, because we don't have any of the same operator adjacent to each other. Evaluation of the functions call expressions is, however, completely unsequenced. There's no reason f3 couldn't be called first, then f1 , and then f2 . The only requirement in this case is that operands of an operator are evaluated before the operator is. So that would mean f2 and f3 have to be called before the * is evaluated and the * must be evaluated and f1 must be called before the + is evaluated. Some operators do, however, impose a sequencing on the evaluation of their operands. For example, in x || y , x is always evaluated before y . This allows for short-circuiting, where y does not need to be evaluated if x is known already to be true . The order of evaluation was previously defined in C and C++ with the use of sequence points , and both have changed terminology to define things in terms of a sequenced before relationship. For more information, see Undefined Behaviour and Sequence Points .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20767745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2993960/']}
|
jdg_378644
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50138100
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
const params = { entity: 'musicTrack', term: 'Muzzy New Age', limit: 1};searchitunes(params).then(console.log); I want searchitunes(params).then(console.log) to be a variable instead of being logged.
Now provide the response and nothing else.
|
You have two options: Option 1 - With guide Nuxt.js is recommended add .js in folder plugin https://nuxtjs.org/guide/plugins Example: Add new file in plugins/example.js Then, add the file inside the plugins key of nuxt.config.js : module.exports = { plugins: ['~/plugins/example']} Option 2 - Use in metadata with body: true <script>export default { head: { script: [ { src: '/head.js' }, // Supported since Nuxt 1.0 { src: '/body.js', body: true }, { src: '/defer.js', defer: '' } ] }}</script> More info: https://github.com/nuxt/nuxt.js/issues/2000#issuecomment-341380762
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50138100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9676885/']}
|
jdg_378645
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40246937
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With the latest Aurora update (1.8), the command LOAD DATA FROM S3 was introduced. Has anyone gotten this to work? After upgrading to 1.8, I followed the setup guide Here to create the Role to allow access from RDS to S3. After rebooting the server and trying to run the command LOAD DATA FROM S3 PREFIX 's3://<bucket_name>/prefix' INTO TABLE table_name in SQL Workbench/J, I get the errors: Warnings:S3 API returned error: Missing Credentials: Cannot instantiate S3 ClientS3 API returned error: Failed to instantiate S3 ClientInternal error: Unable to initialize S3Stream Are there any additional steps required? Can I only run this from the SDK? I don't see that mentioned anywhere in the documents
Now provide the response and nothing else.
|
I had the same issue. I tried adding AmazonS3FullAccess to the IAM role that my RDS instances were using...no joy. After poking around, I went into the RDS console, to Clusters. Selected my Aurora cluster and clicked Manage IAM Roles. It gave me a drop-down, I selected the IAM role (same one that the individual instances were using). Once I did that, all was well and data load was nice and fast. So, there are (for us) 5 steps/components: 1) The S3 bucket and bucket policy to allow a user to upload the object { "Version": "2012-10-17", "Id": "Policy1453918146601", "Statement": [ { "Sid": "Stmt1453917898368", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::<account id>:<user/group/role>/<IAM User/Group/Role>" }, "Action": [ "s3:DeleteObject", "s3:GetObject", "s3:PutObject" ], "Resource": "arn:aws:s3:::<bucket name>/*" } ]} The "Principal" would be whatever IAM user, group or role will be uploading the data files to the bucket so that the RDS instance can import the data. 2) The IAM policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1486490368000", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:GetObjectVersion", "s3:ListBucket" ], "Resource": [ "arn:aws:s3:::<bucket name>/*" ] } ]} This is pretty simple with the Policy Generator. 3) Create the IAM Role: This role should be assigned the IAM policy above. You can probably do an inline policy, too, if you're not going to use this policy for other roles down the line, but I like the idea of having a defined policy that I can reference later if I have a need. 4) Configure a Parameter Group that your cluster/instances will use to set the aws_default_s3_role value to the ARN of the role from #3 above. 5) Configure the Aurora Cluster by going to Clusters, selecting your cluster, selecting Manage IAM Roles and setting the IAM Role for your DB Cluster At least for me, these steps worked like a charm. Hope that helps!
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40246937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1596770/']}
|
jdg_378646
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22288271
|
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 used this script for years on my VPS. And it's still working. DBLIST=`mysql -uroot -pROOT_PASSWORD -ANe"SELECT GROUP_CONCAT(schema_name) FROM information_schema.schemata WHERE schema_name NOT IN ('information_schema','performance_schema')" | sed 's/,/ /g'`MYSQLDUMP_OPTIONS="-uroot -pROOT_PASSWORD --single-transaction --routines --triggers"BACKUP_DEST="/home/backup/db/"for DB in `echo "${DBLIST}"`do mysqldump ${MYSQLDUMP_OPTIONS} ${DB} | gzip > ${BACKUP_DEST}/${DB}.sql.gz &donewaittar -czvf /home/backup/db2/`date +\%G-\%m-\%d`_db.tar.gz ${BACKUP_DEST} Now I'm moving to another hosting. I 'm trying to use the same script (of course I changed ROOT_PASSWORD with the new credentials) but I don't know why I get this: mysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on writemysqldump: Got errno 32 on write
Now provide the response and nothing else.
|
20:47:59 0 ~] $ perror 32OS error code 32: Broken pipe So errno 32 is "broken pipe". You're piping the mysqldump output to gzip , so this means gzip terminated prior to mysqldump finished. Could e.g. be because your disk is full, or gzip surpassed any max CPU time/usage your host has in place.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22288271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1342772/']}
|
jdg_378647
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5095407
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can somebody provide me a link or pseudocode of a function for finding all combinations of k elements out of n? possibly in STL. I don't need to compute n choose k, I need to list all vectors of numbers of size k. Thanks
Now provide the response and nothing else.
|
In C++ given the following routine: template <typename Iterator>inline bool next_combination(const Iterator first, Iterator k, const Iterator last){ /* Credits: Thomas Draper */ if ((first == last) || (first == k) || (last == k)) return false; Iterator itr1 = first; Iterator itr2 = last; ++itr1; if (last == itr1) return false; itr1 = last; --itr1; itr1 = k; --itr2; while (first != itr1) { if (*--itr1 < *itr2) { Iterator j = k; while (!(*itr1 < *j)) ++j; std::iter_swap(itr1,j); ++itr1; ++j; itr2 = k; std::rotate(itr1,j,last); while (last != j) { ++j; ++itr2; } std::rotate(k,itr2,last); return true; } } std::rotate(first,k,last); return false;} You can then proceed to do the following: // 9-choose-3 std::string s = "123456789";std::size_t k = 3;do{ std::cout << std::string(s.begin(),s.begin() + k) << std::endl;}while(next_combination(s.begin(),s.begin() + k,s.end())); Or for a std::vector of int's: // 5-choose-3 std::size_t n = 5;std::size_t k = 3;std::vector<int> ints;for (int i = 0; i < n; ints.push_back(i++));do{ for (int i = 0; i < k; ++i) { std::cout << ints[i]; } std::cout << "\n";}while(next_combination(ints.begin(),ints.begin() + k,ints.end()));
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5095407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/464277/']}
|
jdg_378648
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14530492
|
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 shell script that does the following mysql -uuser -ppass -e "DROP DATABASE IF EXISTS database" However, this brings up a prompt if you're sure you want to do that [Y/N]. I need this in a script so is there a way to force it execute? --force option in documentation talks about not stopping for errors. EDIT: mysql client in fact does not generate prompt. It turns out I had mysqladmin client call that was generating the prompt.
Now provide the response and nothing else.
|
It is evident that the shell script is waiting for the Y/N response and not the MySQL client. You should be able to execute the line directly by just copying/pasting mysql -uuser -ppass -e "DROP DATABASE IF EXISTS database" at the Linux command prompt. If you prefer, where this command appears, simply comment out the Y/N response from the shell script. My next suggestion would be for you look into your my.cnf. See if there is a [mysql] or [client] section with the following: [mysql]i-am-a-dummysafe-updates or [client]i-am-a-dummysafe-updates Those are real options: See safe-updates and i-am-a-dummy in the MySQL Documentation UPDATE 2013-01-25 16:48 EDT My next guess would be the Operating System. Why ??? If you are logged into Linux as root or you executed sudo , you have unquestioned rights to doing a DROP DATABASE IF EXISTS . At the OS level, mysqld would attempt to discard the folder for the database. For example, if datadir is /var/lib/mysql and you execute DROp DATABASE IF EXISTS rolando; , mysqld will attempt to run rm -rf /var/lib/mysql/rolando . if you are not root or sudo 'd as root , I would expect the OS to echo that message. In fact, I have seen a message from the OS ask to delete a PID file when I was not logged in as root and attempted service mysql stop . UPDATE 2013-01-25 16:54 EDT mysqladmin does not cause prompting either, except for passwords. Here are all its options: [root@***]# mysqladmin --helpmysqladmin Ver 8.42 Distrib 5.1.47, for redhat-linux-gnu on x86_64Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.This software comes with ABSOLUTELY NO WARRANTY. This is free software,and you are welcome to modify and redistribute it under the GPL licenseAdministration program for the mysqld daemon.Usage: mysqladmin [OPTIONS] command command.... -c, --count=# Number of iterations to make. This works with -i (--sleep) only. --debug-check Check memory and open file usage at exit. --debug-info Print some debug info at exit. -f, --force Don't ask for confirmation on drop database; with multiple commands, continue even if an error occurs. -C, --compress Use compression in server/client protocol. --character-sets-dir=name Directory for character set files. --default-character-set=name Set the default character set. -?, --help Display this help and exit. -h, --host=name Connect to host. -b, --no-beep Turn off beep on error. -p, --password[=name] Password to use when connecting to server. If password is not given it's asked from the tty. -P, --port=# Port number to use for connection or 0 for default to, in order of preference, my.cnf, $MYSQL_TCP_PORT, /etc/services, built-in default (3306). --protocol=name The protocol to use for connection (tcp, socket, pipe, memory). -r, --relative Show difference between current and previous values when used with -i. Currently only works with extended-status. -O, --set-variable=name Change the value of a variable. Please note that this option is deprecated; you can set variables directly with --variable-name=value. -s, --silent Silently exit if one can't connect to server. -S, --socket=name The socket file to use for connection. -i, --sleep=# Execute commands repeatedly with a sleep between. --ssl Enable SSL for connection (automatically enabled with other flags). Disable with --skip-ssl. --ssl-ca=name CA file in PEM format (check OpenSSL docs, implies --ssl). --ssl-capath=name CA directory (check OpenSSL docs, implies --ssl). --ssl-cert=name X509 cert in PEM format (implies --ssl). --ssl-cipher=name SSL cipher to use (implies --ssl). --ssl-key=name X509 key in PEM format (implies --ssl). --ssl-verify-server-cert Verify server's "Common Name" in its cert against hostname used when connecting. This option is disabled by default. -u, --user=name User for login if not current user. -v, --verbose Write more information. -V, --version Output version information and exit. -E, --vertical Print output vertically. Is similar to --relative, but prints output vertically. -w, --wait[=#] Wait and retry if connection is down. --connect_timeout=# --shutdown_timeout=# HEY, I STAND CORRECTED --force does prompt for DROP DATABASE OK I guess you located the culprit. I learned something today because I do not use mysqladmin to drop databases.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14530492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1541619/']}
|
jdg_378649
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14918020
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
try { MessageDigest digest = MessageDigest.getInstance("SHA-512"); byte[] output = digest.digest(password); digest.update(salt); digest.update(output); return new BigInteger(1, digest.digest()); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } But I got Exception in thread "main" java.security.NoSuchAlgorithmException: SHA_512 MessageDigest not available error
Now provide the response and nothing else.
|
I would say that the most likely explanation is that your REAL code has "SHA_512" rather than "SHA-512" . Certainly, that would explain why there is an underscore in the exception message. The other possibility is that you have a JVM with the "military strength" crypto algorithms removed because of US export restrictions. However, I think that is pretty unlikely ... (And in fact, my reading of this is that SHA-512 was included in all versions of the default "Sun" provider anyway.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14918020', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/236501/']}
|
jdg_378650
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
746111
|
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:
Say I have a commutative ring $R$ with a maximal ideal $m$. Then $m/m^k$ is a maximal ideal in $R/m^k$ for any $k$. Is it the only maximal ideal, i.e. is $R/m^k$ a local ring? This is a well known result for $k = 1$, as $R/m$ is a field. It seems to be true in other cases, e.g. $p\mathbb{Z}\subset \mathbb{Z}$ for prime $p$ and for $(x,y) \subset \mathbb{F}[x,y]$, the maximal ideal generated by $x$ and $y$ in a polynomial ring over the field $\mathbb{F}$. Equivalently, if an element $x\notin m$, is $x + m^k$ an invertible element in $R/m^k$?
Now provide the response and nothing else.
|
The ideals of a quotient ring $R/I$ are of the form $J/I$ with $I\subseteq J\subseteq R$, $J$ ideal of $R$. In particular, the prime ideals are of the form $P/I$ with $I\subseteq P$, $P$ prime ideal of $R$. Now let $I=M^k$ with $M$ maximal. A prime ideal $P$ of $R$ containing $M^k$ contains $M$ (by the definition of prime ideals), so equals $M$. Conclusion: $R/M^k$ is not only local, it has only one prime ideal, namely $M/M^k$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/746111', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/132617/']}
|
jdg_378651
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19654578
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why python 2.7 doesn't include Z character (Zulu or zero offset) at the end of UTC datetime object's isoformat string unlike JavaScript? >>> datetime.datetime.utcnow().isoformat()'2013-10-29T09:14:03.895210' Whereas in javascript >>> console.log(new Date().toISOString()); 2013-10-29T09:38:41.341Z
Now provide the response and nothing else.
|
Python datetime objects don't have time zone info by default, and without it, Python actually violates the ISO 8601 specification ( if no time zone info is given, assumed to be local time ). You can use the pytz package to get some default time zones, or directly subclass tzinfo yourself: from datetime import datetime, tzinfo, timedeltaclass simple_utc(tzinfo): def tzname(self,**kwargs): return "UTC" def utcoffset(self, dt): return timedelta(0) Then you can manually add the time zone info to utcnow() : >>> datetime.utcnow().replace(tzinfo=simple_utc()).isoformat()'2014-05-16T22:51:53.015001+00:00' Note that this DOES conform to the ISO 8601 format, which allows for either Z or +00:00 as the suffix for UTC. Note that the latter actually conforms to the standard better, with how time zones are represented in general (UTC is a special case.)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19654578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1328978/']}
|
jdg_378652
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20861
|
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
everybody knows there exist many decision problems which are NP-hard on general graphs, but I'm interested in problems that are even NP-hard when the underlying graph is a path. So, can you help me to collect such problems? I've already found a related question about NP-hard problems on trees .
Now provide the response and nothing else.
|
A rainbow matching in an edge-colored graph is a matching whose edges have distinct colors. The problem is: given an edge-colored graph $G$ and an integer $k$, does $G$ have a rainbow matching with at least $k$ edges? This is known as rainbow matching problem , and its NP -complete even for properly edge-colored paths. The authors even note that prior to this result, no unweighted graph problem is known to be NP -hard for simple paths to the best of their knowledge. See Le, Van Bang, and Florian Pfender. "Complexity results for rainbow matchings." Theoretical Computer Science (2013) , or the arXiv version .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/20861', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/21430/']}
|
jdg_378653
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4519127
|
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 setuptools to distribute my python package. Now I need to distribute additional datafiles. From what I've gathered fromt the setuptools documentation, I need to have my data files inside the package directory. However, I would rather have my datafiles inside a subdirectory in the root directory. What I would like to avoid: / #root|- src/| |- mypackage/| | |- data/| | | |- resource1| | | |- [...]| | |- __init__.py| | |- [...]|- setup.py What I would like to have instead: / #root|- data/| |- resource1| |- [...]|- src/| |- mypackage/| | |- __init__.py| | |- [...]|- setup.py I just don't feel comfortable with having so many subdirectories, if it's not essential. I fail to find a reason, why I /have/ to put the files inside the package directory. It is also cumbersome to work with so many nested subdirectories IMHO. Or is there any good reason that would justify this restriction?
Now provide the response and nothing else.
|
Option 1: Install as package data The main advantage of placing data files inside the root of your Python packageis that it lets you avoid worrying about where the files will live on a user'ssystem, which may be Windows, Mac, Linux, some mobile platform, or inside an Egg. You canalways find the directory data relative to your Python package root, no matter where or how it is installed. For example, if I have a project layout like so: project/ foo/ __init__.py data/ resource1/ foo.txt You can add a function to __init__.py to locate an absolute path to a data file: import os_ROOT = os.path.abspath(os.path.dirname(__file__))def get_data(path): return os.path.join(_ROOT, 'data', path)print get_data('resource1/foo.txt') Outputs: /Users/pat/project/foo/data/resource1/foo.txt After the project is installed as an Egg the path to data will change, but the code doesn't need to change: /Users/pat/virtenv/foo/lib/python2.6/site-packages/foo-0.0.0-py2.6.egg/foo/data/resource1/foo.txt Option 2: Install to fixed location The alternative would be to place your data outside the Python package and theneither: Have the location of data passed in via a configuration file, command line arguments or Embed the location into your Python code. This is far less desirable if you plan to distribute your project. If you really want to do this, you can install your data wherever you like on the target system by specifying the destination for each group of files by passing in a list of tuples: from setuptools import setupsetup( ... data_files=[ ('/var/data1', ['data/foo.txt']), ('/var/data2', ['data/bar.txt']) ] ) Updated : Example of a shell function to recursively grep Python files: atlas% function grep_py { find . -name '*.py' -exec grep -Hn $* {} \; }atlas% grep_py ": \["./setup.py:9: package_data={'foo': ['data/resource1/foo.txt']}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4519127', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/383124/']}
|
jdg_378654
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24499624
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know the difference between range and xrange . But I was surprised to see that xrange wasn't a generator but a sequence object . What's the difference then, how to create a sequence object and when used it over a generator ?
Now provide the response and nothing else.
|
The reason that xrange is a sequence object is because it supports the sequence methods interface . For example you can index it (which is something you can't do with a vanilla generator): print xrange(30)[5] # No Error In other words, something is a sequence if it supports all of the methods defined in that link. If it's a generator, it probably only supports a couple methods ( .next or .__next__ are the most important) 1 . there's also an in-between land which is "iterable" -- "iterables" have a typically 2 defined __iter__ method which returns "generator" (something with a well defined .next or .__next__ 3 method) just to be complete, you'll often see people say "iterators" which are very similar to generators (implement __iter__ which returns the object itself and has a well defined next and/or __next__ method). More formal definitions can be found in the documentation glossary 1 generators also support __iter__ and simply return themselves. so techincally, all generators are also iterables (and iterators!), but not all iterables (iterators) are generators. 2 __len__ + __getitem__ is enough to create an iterable as pointed out in the comments. 3 __next__ is the method name for python3.x
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24499624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/676973/']}
|
jdg_378655
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24238820
|
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 the for-loop to be parallel using go routines. i tried using channels but that didnt work. My main problem is, that i want to wait for all iterations to be finished before continuing. That's why simply writing go before it doesn't work. I tried to using channels (i think the wrong way) but that made my code even slower func createPopulation(populationSize int, individualSize int) []Individual { population := make([]Individual, populationSize) //i want this loop to be work parallel for i := 0; i < len(population); i++ { population[i] = createIndividual(individualSize) } return population}func createIndividual(size int) Individual { var individual = Individual{make([]bool, size), 0} for i := 0; i < len(individual.gene); i++ { if rand.Intn(2)%2 == 1 { individual.gene[i] = true } else { individual.gene[i] = false } } return individual} My struct looks like this: type Individual struct { gene []bool fitness int}
Now provide the response and nothing else.
|
So basically the goroutine should not return a value but push it down a channel. If you want to wait for all goroutines to finish you can just count to the number of goroutines, or use a WaitGroup. In this example it's an overkill because the size is known, but it's good practice anyway. Here's a modified example: package mainimport ( "math/rand" "sync")type Individual struct { gene []bool fitness int}func createPopulation(populationSize int, individualSize int) []Individual { // we create a slice with a capacity of populationSize but 0 size // so we'll avoid extra unneeded allocations population := make([]Individual, 0, populationSize) // we create a buffered channel so writing to it won't block while we wait for the waitgroup to finish ch := make(chan Individual, populationSize) // we create a waitgroup - basically block until N tasks say they are done wg := sync.WaitGroup{} for i := 0; i < populationSize; i++ { //we add 1 to the wait group - each worker will decrease it back wg.Add(1) //now we spawn a goroutine go createIndividual(individualSize, ch, &wg) } // now we wait for everyone to finish - again, not a must. // you can just receive from the channel N times, and use a timeout or something for safety wg.Wait() // we need to close the channel or the following loop will get stuck close(ch) // we iterate over the closed channel and receive all data from it for individual := range ch { population = append(population, individual) } return population} func createIndividual(size int, ch chan Individual, wg *sync.WaitGroup) { var individual = Individual{make([]bool, size), 0} for i := 0; i < len(individual.gene); i++ { if rand.Intn(2)%2 == 1 { individual.gene[i] = true } else { individual.gene[i] = false } } // push the population object down the channel ch <- individual // let the wait group know we finished wg.Done()}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24238820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2316112/']}
|
jdg_378656
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2718150
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am studying for my graduate qualifying exam and unfortunately for me I have spent the last two years studying commutative algebra and algebraic geometry, and the qualifying exam is entirely 'fundamental / core' material - tricky multivariable calculus and linear algebra questions, eek! Here is the question from an old exam I am working on. Please note, how to solve the problem is not my specific question. After I introduce the problem, I will ask my specific questions about the problem below. No Calculators. Let $$M = \begin{bmatrix} 2 & 0 & 0 \\ 1 & 4 & 2 \\ 0 & -2 & -1\\ \end{bmatrix}$$ 1) Find the determinant of $M$ , Find the eigenvalues and associated eigenvectors of $M$ , Calculate $$M^{2013} \cdot \begin{bmatrix}1\\1\\1\\\end{bmatrix}.$$ My issue is that with computational problems on an exam where calculators aren't allowed I always expect that either: there will be a trick to sidestep nasty calculations by hand, the problem will be contrived in such a way that the computation goes very easily. This seems to be the case in part 1 and part 2 of the problem since: The determinant of $M$ can very easily be found by cofactor across row 1 to get $\mathrm{det}(M) = 2(-4+4) = 0$ , or by inspection we see column 2 is quite visibly a scalar multiple of column 3 so that $\mathrm{det}(M) = 0$ . Since $\mathrm{det}(M) = 0$ we know 0 is an eigenvalue. Noting the dependence relation between column 2 and column 3 allows us to easily read off an eigenvector for $\lambda = 0$ . Further, manually computing $\mathrm{det}(M - \lambda I)$ is again computationally easy because of the 0's across row 1. We get $p_{M}(t) = \lambda(2-\lambda)(\lambda - 3)$ . Solving for the corresponding eigenvectors is also fairly fast. Now - part 3 starts off fine. Considering part 2 it is practically implied from context clues that we are intended to diagonalize this matrix $M$ , as the only thing needed at this point is the inverse of the matrix of eigenvectors. The computation is when I go into a whirlwind because it does not flow as easily as the previous computations. In part 2 we had a degree three polynomial we wanted roots of, and of course it split into linear factors. Now I am inverting a 3x3 matrix by hand and getting all entries as ratios? On the exam, this will panic me. Time is definitely an issue and I need to learn how to not waste it. I immediately start restudying the problem trying to see if there is some way around computing a 3 x 3 inverse by hand. One other approach I took, since I am just studying right now and not worried about time, was trying to express the vector $(1,1,1)^T$ as a linear combination of eigenvectors, say $$(1,1,1)^T = a_1v_1 + a_2v_2 + a_3v_3$$ with suitably chosen eigenvectors $v_1, v_2, v_3$ , since then $$M^{2013}(a_1 v_1 + a_2 v_2 + a_3 v_3) = a_2 \lambda_2^{2013}v_2 + a_3 \lambda_3^{2013} v_3.$$ Finding the linear combinations of eigenvectors seems to be no more or less easy than inverting the matrix of eigenvectors. Although I took a graduate abstract linear algebra course, I also worked in a tutoring center for years where I tutored problems like this without advanced methods - thus when I see questions like this, the method that immediately comes to mind is the classic one - diagonalize. Does anyone see any tricks to avoid nasty computation by hand in the problem above? More generally (I am sure lots of other users have taken graduate qual exams, and might have feedback here) does anyone have exam advice, perhaps a systematic way to decide if I should simply commit to doing the computation, and try to do it carefully yet as fast as possible, or halt myself in my tracks and say "they wouldn't expect me to do this computation by hand, I should study the problem and see if there is a way around this." Thank you. Edit: I suppose I may slightly be misusing this site since I know how to solve my problem, and my question is more geared towards exam skills? Part of my question even borders psychology... This is a bit of a philosophical conundrum whether my question is appropriate for the site. But, my exam is tomorrow so I will risk it! If it gets closed, so be it :)
Now provide the response and nothing else.
|
This answer is a more detailed walk through of the method outlined by @yixing in the comments. I present it more verbosely than I would on the exam for the aid of anyone else who reads it. From part 2 of the problem we have already discovered that $M$ has 3 distinct eigenvalues (thus diagonalizable) and also have found the characteristic polynomial $p_m(t) = x(2-x)(3-x).$ Since $k[t]$ is a Euclidean domain, we know that for the polynomials $t^{2013}$ and $p_m(t)$, there exists $q(t)$ and $r(t)$ such that $$t^{2013} = p_m(t)q(t) + r(t), \hspace{5mm}(1)$$ where $\mathrm{deg}(r(t)) < \mathrm{deg}(p_m(t)).$ Note that since the degree of the characteristic polynomial is 3, $r(t)$ is at most a quadratic, $r(t) = at^2 + bt + c.$ The degree of $r(t)$ being at most two will ultimately be the crux of why this method is computationally superior to diagonalizing the matrix $M$, for evaluating both sides of (1) at the matrix M yields $$M^{2013} = p_m(M)q(M) + r(M),$$ thus $$M^{2013} = r(M) = aM^2 + bM + cI.$$ This final line can be justified either by invoking the Cayley-Hamilton theorem, or by noting that since the matrix is diagonalizable with 3 distinct eigenvalues, the characteristic polynomial and minimal polynomial are equivalent and by definition the minimal polynomial vanishes on $M$. Thus if we solve for the coefficients of $r(t)$, the desired matrix / vector multiplication can be computed easily. By evaluating line (1) at t = 0,2,3 we discover that $c = 0$, then get an 'easy to solve' 2x2 system for $a,b$ yielding $a = 3^{2012} - 2^{2012}$, $b = 2^{2012} + 2^{2013} - 2\cdot 3^{2012}$. Now let $v = (1,1,1)^{T}$, then it is easily computed mentally that $Mv = (2,7,-3)^T$ and $M^2v = (4,24,-11)^T$. So we have \begin{align*}M^{2013}\cdot v &= aM^2v + bMv\\&= a(2,7,-3)^T + b(4,-24,-11)^T.\\\end{align*} Since the values for $a,b$ were found above, I see no reason to simplify further. A huge thanks to @yixing for the suggestion of this method. The method is considerably faster than computing an inverse by hand, and is actually quite robust.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2718150', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/249419/']}
|
jdg_378657
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24831476
|
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 learning Python (coming from other languages like JavaScript and Ruby). I am very used to chaining a bunch of transformations / filters, but I'm pretty sure that's not the right way to do it in Python: filter takes a lambda before the enumerable, so writing a long / multi-line function looks really weird and chaining them means putting them in reverse order which isn't readable. What would be the "Python way" of writing the maps and filters in this JavaScript function? let is_in_stock = function() /* ... */let as_item = function() /* ... */let low_weight_items = shop.inventory .map(as_item) .filter(is_in_stock) .filter(item => item.weight < 1000) .map(item => { if (item.type == "cake") { let catalog_item = retrieve_catalog_item(item.id); return { id: item.id, weight: item.weight, barcode: catalog_item.barcode }; } else { return default_transformer(item); } }); I understand that I might use a list comprehension for the first map and the next two filters, but I am not sure how to do the last map and how to put everything together. Thank you!
Now provide the response and nothing else.
|
If you don't mind using a package, this is another way to do it using https://github.com/EntilZha/PyFunctional from functional import seqdef as_item(x): # Implementation here return xdef is_in_stock(x): # Implementation return Truedef transform(item): if item.type == "cake": catalog_item = retrieve_catalog_item(item.id); return { 'id': item.id, 'weight': item.weight, 'barcode': catalog_item.barcode } else: return default_transformer(item)low_weight_items = seq(inventory)\ .map(as_item)\ .filter(is_in_stock)\ .filter(lambda item: item.weight < 1000)\ .map(transform) As mentioned earlier, python lets you use lamdba expressions, but they aren't flexible as clojures in javascript since they can't have more than one statement. Another annoying python thing are the need for backslashes. That being said, I think the above most closely mirrors what you originally posted. Disclaimer: I am the author of the above package
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24831476', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3854095/']}
|
jdg_378658
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10734746
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My problem is that when the chart drawing area of is smaller than a highchart tooltip, a part of the tooltip is hidden where it overflows the chart drawing area. I want the tooltip to be visible all the time, no matter the size of the chart drawing area. No CSS setting helped and no higher z-index setting helped either. Here is my example... http://twitpic.com/9omgg5 Any help will be mostly apreciated. Thank you.
Now provide the response and nothing else.
|
OK, sorry for the delay. I could not find a better solution, but I found a workaround. Here is what I did and what I suggest everyone to try: Set the tooltip.useHTML property to true (now you can have more control with html and CSS). Like this: tooltip: { useHTML: true } Unset all the default tooltip peoperties that may have something to do with the default tooltip functionalities. Here is what I did... tooltip: { shared: false, borderRadius: 0, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none'} Make sure that your chart container's css property "overflow" is set to visible. Also make sure that all DOM elements (div, section, etc....) that hold your chart container also have the css "overflow" property set to "visible". In this way you will make sure that your tooltip will be visibile at all times as it overflows his parent and his other "ancestors" (Is this a correct term? :)). Customize your tooltip formatter as you wish, using standard CSS styling. Here is what I did: tooltip.formatter: { < div class ="tooltipContainer"> Tooltip content here < /div >} This is how it all looks like: tooltip: { tooltip.formatter: { < div class ="tooltipContainer"> Tooltip content here < /div > }, useHTML: true, shared: false, borderRadius: 0, borderWidth: 0, shadow: false, enabled: true, backgroundColor: 'none'} If you have a better solution, please post.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10734746', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1016115/']}
|
jdg_378659
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39182494
|
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 calling a dialog box through an activity , when alarm goes of.The dialog box appears when alarm goes of. When back button is pressed there is another Dialog box , which diaplays the app name. the dialog that appears when alarm goes of The Dialog that appears with app name when back button is pressed, after the first dialog appears This is the intent for alarm : Intent intent = new Intent(this, HydrateNotifier.class);PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); This is the Dialog definition inside OnCreate() within HydrateNotifier.class : AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setTitle("Hydrate Time"); alertDialogBuilder.setMessage("Enter the amount of water"); alertDialogBuilder.setPositiveButton("Update", this); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show();} Need Solution for : The dialog box that appears when alarm goes of , disappears when touched outside its boundary. Please provide a logic to make the dialog box remain. 2.On pressing the back button , when the dialog box appears , the dialog box closes and another dialog box is visible with the app name ,as shown in image.How do i make it not appear? I have set android:theme="@android:style/Theme.Holo.Dialog" in the Manifest for the class in which the dialog is defined.
Now provide the response and nothing else.
|
Windows bash does not support X Server. However, using a Windows X Server port such as MobaXTerm, XMing or vcXsrv in conjunction with Windows bash works. Some things work out of the box (gvim did,) emacs requires more effort. Here's how I've made it work: Install MobaXterm . Most probably you can make it work with XMing as well, but I have tested only with MobaXterm. Update: Tested with vcXsrv and XMing (paid version.) Works essentially the same, I will probably stick with MobaXTerm. Install emacs 25.1 snapshot. The reason: Ubuntu 14.04 comes with emacs 24.3, which doesn't work with Windows bash and MobaXTerm X server (no idea why, and it's too old anyway.) Install the snapshot using the following commands: sudo add-apt-repository ppa:ubuntu-elisp/ppasudo apt-get updatesudo apt-get install emacs-snapshot Then run sudo update-alternatives --config emacs and select emacs-snapshot Make sure you set the DISPLAY export DISPLAY=localhost:0.0 Run MobaXTerm (you don't need anything to do in it, just start it - it will start X Server when needed.) Run emacs in bash and enjoy. One problem remains, and it persists across all three packages I've tested (MobaXTerm, XMing and vcXsrv). Emacs sticks to the initial frame size, and doesn't resize its frame when the window is resized. Same problem with the menu bar - when menu bar is disabled, emacs doesn't reclaim its space, it remains as a grey rectangle. This problem seems to be peculiar to emacs on Windows bash - gvim and other GUI programs seem to work fine. Also, running emacs 25.1 on Linux using any X Server on Windows works fine. I have tried to build emacs with different GUI settings (GTK 2.0 etc.) but emacs make on Windows bash gets stuck. If I find a workaround for this I will post an update. Update 09/24/2017 According to Jarett the following in your init.el should fix the frame resizing problem: (setq frame-resize-pixelwise t) I don't have Windows with bash active anymore, so I can't test it.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39182494', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6739824/']}
|
jdg_378660
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27256629
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is not identical to this question , but it's very similar. I'm using ASP.Net and need to more or less do the same thing, but was hoping it can be done on the ASP side. My relevant code is such: <td style="line-height: 230%;"> <asp:TextBox ID="txtePro" runat="server" CssClass="textbox" Font-Size="Small" Height="18px" Width="100px" Visible="False" Wrap="False" OnTextChanged="txtEPro_OnLeave" AutoPostBack="true"></asp:TextBox> <asp:MaskedEditExtender ID="MeeePro" runat="server" Mask="9999999" MaskType="None" TargetControlID="txtePro" PromptCharacter="_" /> <asp:MaskedEditExtender ID="MeePRD" runat="server" Mask="999999" MaskType="None" TargetControlID="txtePro" PromptCharacter="_" /> <asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtePro" ID="RevePro" ValidationExpression="^[\s\S]{7,7}$" runat="server" ErrorMessage="7 Digits required." ForeColor="White" Font-Size="X-Small"></asp:RegularExpressionValidator> <asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtePro" ID="RevPRD" ValidationExpression="^[\s\S]{6,}$" runat="server" ErrorMessage="6 Digits required." ForeColor="White" Font-Size="X-Small"></asp:RegularExpressionValidator> <asp:TextBox ID="hdntxtePro" runat="server" CssClass="textbox" Font-Size="Small" Height="18px" Width="100px" Visible="False" Wrap="False"></asp:TextBox> <asp:DropDownList ID="ddlCIT" runat="server" AutoPostBack="True" CssClass="textbox" Visible="false" Height="20px" OnSelectedIndexChanged="ddlCIT_SelectedIndexChanged" Width="100px"></asp:DropDownList> <asp:TextBox ID="txtCIT" runat="server" CssClass="textbox" Height="18px" Width="100px" Visible="False" Font-Size="Small" Wrap="False"></asp:TextBox> <asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtCIT" ID="RevCIT" ValidationExpression="^[\s\S]{4,}$" runat="server" ErrorMessage="4 Digits required." ForeColor="White" Font-Size="X-Small"></asp:RegularExpressionValidator> <asp:MaskedEditExtender ID="meeCIT" runat="server" MaskType="Number" Mask="99.99" TargetControlID="txtCIT" PromptCharacter="_" InputDirection="LeftToRight" /> <asp:TextBox ID="txtClientID" runat="server" CssClass="textbox" Height="18px" Width="100px" Visible="False" Font-Size="Small" Wrap="False" OnTextChanged="txtClientID_OnLeave" AutoPostBack="true" MaxLength="5"></asp:TextBox> <asp:MaskedEditExtender ID="meeClientID" runat="server" MaskType="Number" Mask="99999" TargetControlID="txtClientID" PromptCharacter="_" InputDirection="LeftToRight" AutoComplete="False" UserTimeFormat="TwentyFourHour"/> <asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtClientID" ID="RevClientID" ValidationExpression="^[\s\S]{5,5}$" runat="server" ErrorMessage="5 Digits required." ForeColor="White" Font-Size="X-Small"></asp:RegularExpressionValidator> <asp:TextBox ID="hdntxtClientID" runat="server" CssClass="textbox" Height="18px" Width="100px" Visible="False" Font-Size="Small" Wrap="False"></asp:TextBox> <asp:TextBox ID="txtElasID" runat="server" CssClass="textbox" Height="18px" Width="100px" Wrap="False" Visible="False" Font-Size="Small"></asp:TextBox> <asp:MaskedEditExtender ID="meeElas" runat="server" MaskType="None" Mask="99999999" TargetControlID="txtElasID" PromptCharacter="_" /> <asp:RegularExpressionValidator Display="Dynamic" ControlToValidate="txtElasID" ID="RevElasID" ValidationExpression="^[\s\S]{8,}$" runat="server" ErrorMessage="8 Digits required." ForeColor="White"></asp:RegularExpressionValidator> <asp:TextBox ID="txtEffDate" runat="server" CssClass="textbox" Height="18px" Width="100px" Visible="False" Font-Size="Small" TextMode="Date" Wrap="False"></asp:TextBox> <asp:RangeValidator ID="rvDate" runat="server" ControlToValidate="txtEffDate" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic" ForeColor="White"></asp:RangeValidator> <asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtEffDate" Format="MM/dd/yyyy"></asp:CalendarExtender></td> As in the linked question, my problem is that when a user clicks inside the text box, they're sometimes starting in the middle and I need the cursor to be forced all the way to the left. Is there a way to force the cursor all the way to the left from within ASP, or is this something that can only be done in the code-behind?
Now provide the response and nothing else.
|
You can achieve that using javascript and jQuery by setting the SelectionRange to 0,0 on the mouseup event: $(document).ready(function(){ $(".resetCursor").mouseup(function () { this.setSelectionRange(0,0); });}); http://jsfiddle.net/6m8stbo7/1/ Then add the class resetCursor to the TextBox Controls you want to extend with this behavior. <asp:TextBox ID="txtePro" runat="server" CssClass="textbox resetCursor" Font-Size="Small" Height="18px" Width="100px" Visible="False" Wrap="False" OnTextChanged="txtEPro_OnLeave" AutoPostBack="true"></asp:TextBox> Explanation: resetCursor is a css stylesheet class that is used by jQuery to select the specific DOM-Elements. It is common practice to use css classes to "declare" certain behavior on a set of DOM-Elements and then use jquery to "activate" that behavior in one go. Edit : Note that resetCursor is an arbitrary name, you could have chosen another name as you please. Here is a good introduction to the basic jQuery selectors (I'm using the Class-Selector in this example): http://api.jquery.com/category/selectors/basic-css-selectors/
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27256629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2174085/']}
|
jdg_378661
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3744337
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am currently reading Lectures in Logic and Set Theory: Volume 2, Set Theory by Tourlakis. In the book, he formally introduces the power set notation, $\mathcal{P}(A)$ , as well as union, $\bigcup A$ , into the formal, first-order theory of sets as unary function symbols by extending the theory through definition . This process is described in the linked Wikipedia article and also here but, in summary, to introduce a function symbol into our theory, we must first find a defining formula for the function, \begin{equation}\forall x_1\ldots\forall x_n\phi(f(x_1,\ldots, x_n), x_1,\ldots x_n),\tag{Defining Axiom}\end{equation} where $\phi(y,x_1,\ldots,x_n)$ is a first-order formula with free variables $y,x_1,\ldots,x_n$ , then take this defining axiom and add it to our formal theory as a non-logical axiom. However, this is provided that we first have a proof of the existence and uniqueness of such an object for every possible term: $$\forall x_1\ldots\forall x_n\exists ! y\phi(y,x_1,\ldots x_n)\tag{Existential Formula}.$$ My question is how is this done for the intersection symbol, $\bigcap$ ? Tourlakis avoids the issue since $\bigcap\varnothing$ is not a set and thus "violates" the existential formula. Specifically, he writes, "We do not feel inclined to perform acrobatics just to get around the fact that $\bigcap\varnothing$ cannot be a formal term: it is not a set." I would like to know how this issue is resolved and, if the "acrobatics" required to get around this issue is too extreme, how I can be assured that leaving this as a loose end will not cause too many issues in the theory.
Now provide the response and nothing else.
|
I dont think Feynman's trick would work best here, following your path: $$\int _0^1\frac{\ln \left(x^2+x+1\right)}{x\left(x+1\right)}\:dx=\int _0^1\frac{\ln \left(x^2+x+1\right)}{x}\:dx-\underbrace{\int _0^1\frac{\ln \left(x^2+x+1\right)}{x+1}\:dx}_{x=\frac{1-t}{1+t}}\:$$ $$=\int _0^1\frac{\ln \left(x^3-1\right)}{x}\:dx-\int _0^1\frac{\ln \left(x-1\right)}{x}\:dx-\int _0^1\frac{\ln \left(x^2+3\right)}{x+1}\:dx+2\int _0^1\frac{\ln \left(x+1\right)}{x+1}\:dx$$ $$-\sum _{k=1}^{\infty }\frac{1}{k}\int _0^1x^{3k-1}\:dx\:+\sum _{k=1}^{\infty }\frac{1}{k}\:\int _0^1x^{k-1}\:dx-\int _0^1\frac{\ln \left(x^2+3\right)}{x+1}\:dx+\ln ^2\left(2\right)$$ To solve that remaining integral you can use the identity i derived here So, $$=\frac{2\zeta \left(2\right)}{3}-(-\frac{\ln ^2\left(3\right)}{4}-\frac{\text{Li}_2\left(-\frac{1}{3}\right)}{2}-\frac{\ln ^2\left(4\right)}{4}+\frac{\ln \left(3\right)\ln \left(4\right)}{2}-\arctan ^2\left(\sqrt{\frac{1}{3}}\right)+\ln \left(2\right)\ln \left(4\right))+\ln ^2\left(2\right)$$ $$\frac{\pi ^2}{9}+\frac{\ln ^2\left(3\right)}{4}+\frac{\text{Li}_2\left(-\frac{1}{3}\right)}{2}+\ln ^2\left(2\right)-\ln \left(3\right)\ln \left(2\right)+\frac{\pi ^2}{36}-2\ln ^2\left(2\right)+\ln ^2\left(2\right)$$ So your integral's solution is, $$\boxed{\int _0^1\frac{\ln \left(x^2+x+1\right)}{x\left(x+1\right)}\:dx=\frac{5\pi ^2}{36}+\frac{\ln ^2\left(3\right)}{4}+\frac{\text{Li}_2\left(-\frac{1}{3}\right)}{2}-\ln \left(3\right)\ln \left(2\right)}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3744337', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/564773/']}
|
jdg_378662
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
56417134
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I wrote a simple piece of code to compare random array difference and found something ... that I don't quite understand. I generate 2 arrays filled with random numbers Add up the differences between the random numbers Print out the average difference I would have expected the result to be random number close to 0.5 but in practice, it is 0.3333. Why does the random number array home in on 0.3 and not 0.5? const result = document.getElementById('result');const generateRandomNrArray = (nrNumbers) => { let i; let result = []; for (i = 0; i < nrNumbers; i++) { result.push(Math.random()); } return result;}const getArrayDiff = (arr1, arr2) => { var diff = 0; arr1.forEach(function (v1, index) { diff += Math.abs(v1 - arr2[index]); }); return diff;}const run = (nr) => { const arr1 = generateRandomNrArray(nr); const arr2 = generateRandomNrArray(nr); const totalDiff = getArrayDiff(arr1, arr2); result.innerHTML = "Average difference:" + (totalDiff / nr);} button {font-size: 2em;} <div id="result"></div><button id="run" onclick="run(1500)">Click Me</button>
Now provide the response and nothing else.
|
This basically boils down to a limit and it makes sense. Consider the combinations of numbers between 0 and 10 and count the various differences you can make. For example, there is one combination with a difference of 9 — (0, 9). There are 5 with a difference of 5: [0, 5], [1, 6], [2, 7], [3, 8], [4, 9] But there are nine combinations with a difference of 1: [1, 2], [2, 3], ... [8, 9] With 0 - 10 the counts are: {1: 9, 2: 8, 3: 7, 4: 6, 5: 5, 6: 4, 7: 3, 8: 2, 9: 1} There are 45 combinations and the average difference of the those combinations is 3.6666 not 5 because there are more smaller differences than larger ones. When you increase the granularity from 0 - 10 to 0 - 100 the same pattern holds. There are 99 combinations that result in a difference 1 and only 50 with a difference of 50 for an average of 33.6666 . As you increase the number of significant digits the opposite directions the opposite direction with finer and finer divisions between 0 and 1, you find the same process as the limit approaches 1/3 . There are many more smaller difference than larger ones pulling the average difference down. For 0-1 in 0.1 intervals you'll see 9 with a difference of 0.1 and 5 with a difference of 0.5, at 0.01 there will be 99 with a difference 0.01, and 50 with a difference of 0.5. As the interval approaches 0 the average of the differences approaches 1/3 .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56417134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1932379/']}
|
jdg_378663
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19772284
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following activity screens Activity A - contains a button that links to Activity B Activity B - contains a confirmation of order and then a Next button that opens up a Activity C (to capture signature) Activity C - a dialog box that pops up for the user to enter their signature and a complete button. Activity A - contains intent start to start Activity B and implements onActivityForResult Intent intent = new Intent( this, ConfirmLines.class );startActivityForResult( intent, GET_SIGNATURE );protected void onActivityResult( int requestCode, int resultCode, Intent intent ) { super.onActivityResult( requestCode, resultCode, intent ); switch ( requestCode ) { case GET_SIGNATURE: if ( resultCode == RESULT_OK ) { getIntent().putExtra( SIGNATURE_DATA, intent.getStringExtra( SignatureCapture.SIGNATURE_RESULT ) ); getIntent().putExtra( SIGNATURE_TIME, "34552655544" ); // todo - remove hardcoded signature time showDialog( PRINT_NAME ); } else { //reset data after a cancel/back from signature screen getIntent().putExtra( SignatureCapture.SIGNATURE_RESULT, "" ); } break; } } Activity B - contains code to start intent for signature capture and also onActivityForResult which goes back to Activity A. final Intent intent = new Intent( this, SignatureCapture.class ); startActivityForResult( intent, GET_SIGNATURE ); @Override protected void onActivityResult( int requestCode, int resultCode, Intent intent ) { super.onActivityResult( requestCode, resultCode, intent ); switch ( requestCode ) { case GET_SIGNATURE: if ( resultCode == RESULT_OK ) { finish(); } } } Activity C - contains the code for signature capture and a complete button public void onClick( View view ) { switch ( view.getId() ) { case R.id.button_cancel: dismiss(); nameValue.setText( "" ); notesValue.setText( "" ); imageView_button.setImageBitmap( null ); break; case R.id.button_confirm: final String printedText = String.valueOf( nameValue.getText() ); if ( printedText.isEmpty() ) { Toast.makeText( getContext(), "Please enter a name", Toast.LENGTH_SHORT ).show(); } else { if ( mDialogResult != null ) { mDialogResult.finish( String.valueOf( nameValue.getText() ), String.valueOf( notesValue.getText() ) ); } nameValue.setText( "" ); notesValue.setText( "" ); dismiss(); } break; } } I am getting stuck when I get returned back to Activity A, the resultCode equals 0, which is defined as the result being cancelled. It is picking up the correct requestCode as started originally from Activity A but it's just this resultCode that seems to be the problem, if anyone can see why? Could it possibly be to do with calling finish() from Activity B when it is returned from Activity C? Also, I am needing to pass Intent data from Activity C to A. Where I have finish() in Activity B if I startActivity for Activity A it then does not drop into onActivityForResult. Thanks for help in advanced :]
Now provide the response and nothing else.
|
If you would like to get the result from Activity C passed back to Activity A: Start Activity B from Activity A: Intent showB = new Intent(ActivityA, ActivityB); startActivityForResult(showB, RequestCode); In Activity B call C: Intent showC = new Intent(ActivityC);showC.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);startActivity(showC); finish(); //Close Activity B In C: //set the result code and close the activityIntent result = new Intent();setResult(resultCode, result);//like RESULT_OKfinish(); In A: public void onActivityResult(int requestCode, int resultCode, Intent data) { ...... handle RequestCode here}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19772284', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2661511/']}
|
jdg_378664
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1726254
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was looking at the implementation of compare(double, double) in the Java standard library (6). It reads: public static int compare(double d1, double d2) { if (d1 < d2) return -1; // Neither val is NaN, thisVal is smaller if (d1 > d2) return 1; // Neither val is NaN, thisVal is larger long thisBits = Double.doubleToLongBits(d1); long anotherBits = Double.doubleToLongBits(d2); return (thisBits == anotherBits ? 0 : // Values are equal (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 1)); // (0.0, -0.0) or (NaN, !NaN)} What are the merits of this implementation? edit: "Merits" was a (very) bad choice of words. I wanted to know how this works.
Now provide the response and nothing else.
|
The explanation is in the comments in the code. Java has double values for both 0.0 and -0.0 , as well as "not a number" ( NaN ). You can't use simple == operator for these values. Take a peek into the doubleToLongBits() source and at the Javadoc for the Double.equals() method : Note that in most cases, for two instances of class Double , d1 and d2 , the value of d1.equals(d2) is true if and only if d1.doubleValue() == d2.doubleValue() also has the value true . However, there are two exceptions: If d1 and d2 both represent Double.NaN , then the equals method returns true , even though Double.NaN == Double.NaN has the value false . If d1 represents +0.0 while d2 represents -0.0 , or vice versa, the equal test has the value false , even though +0.0 == -0.0 has the value true . This definition allows hash tables to operate properly.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1726254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/201891/']}
|
jdg_378665
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10527983
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I'm trying to move a "close" button to the left side when the user is on Mac and the right side when the user is on PC. Now I'm doing it by examining the user agent, but it can be too easily spoofed for reliable OS detection. Is there a surefire way to detect whether the OS on which the browser is running is Mac OS X or Windows? If not, what's better than user agent sniffing?
Now provide the response and nothing else.
|
The window.navigator.platform property is not spoofed when the userAgent string is changed.I tested on my Mac if I change the userAgent to iPhone or Chrome Windows, navigator.platform remains MacIntel. The property is also read-only I could came up with the following table Mac Computers Mac68K Macintosh 68K system. MacPPC Macintosh PowerPC system. MacIntel Macintosh Intel system. MacIntel Apple Silicon (ARM) iOS Devices iPhone iPhone. iPod iPod Touch. iPad iPad. Modern macs returns navigator.platform == "MacIntel" but to give some "future proof" don't use exact matching, hopefully they will change to something like MacARM or MacQuantum in future. var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0; To include iOS that also use the "left side" var isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);var isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform); var is_OSX = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);var is_iOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);var is_Mac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;var is_iPhone = navigator.platform == "iPhone";var is_iPod = navigator.platform == "iPod";var is_iPad = navigator.platform == "iPad";/* Output */var out = document.getElementById('out');if (!is_OSX) out.innerHTML += "This NOT a Mac or an iOS Device!";if (is_Mac) out.innerHTML += "This is a Mac Computer!\n";if (is_iOS) out.innerHTML += "You're using an iOS Device!\n";if (is_iPhone) out.innerHTML += "This is an iPhone!";if (is_iPod) out.innerHTML += "This is an iPod Touch!";if (is_iPad) out.innerHTML += "This is an iPad!";out.innerHTML += "\nPlatform: " + navigator.platform; <pre id="out"></pre> Since most O.S. use the close button on the right, you can just move the close button to the left when the user is on a MacLike O.S., otherwise isn't a problem if you put it on the most common side, the right. setTimeout(test, 1000); //delay for demonstrationfunction test() { var mac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform); if (mac) { document.getElementById('close').classList.add("left"); }} #window { position: absolute; margin: 1em; width: 300px; padding: 10px; border: 1px solid gray; background-color: #DDD; text-align: center; box-shadow: 0px 1px 3px #000;}#close { position: absolute; top: 0px; right: 0px; width: 22px; height: 22px; margin: -12px; box-shadow: 0px 1px 3px #000; background-color: #000; border: 2px solid #FFF; border-radius: 22px; color: #FFF; text-align: center; font: 14px"Comic Sans MS", Monaco;}#close.left{ left: 0px;} <div id="window"> <div id="close">x</div> <p>Hello!</p> <p>If the "close button" change to the left side</p> <p>you're on a Mac like system!</p></div> http://www.nczonline.net/blog/2007/12/17/don-t-forget-navigator-platform/
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/10527983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/743561/']}
|
jdg_378666
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
535246
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have read that for a ring $ R $ in general, right $ R $-modules are not the same things as left $ R $-modules. Why do we say that a right $ R $-module is equivalent to a left $ R $-module only when $ R $ is commutative? I feel that the commutativity of $ R $ is strictly an internal property of $ R $, so how can the commutativity of $ R $ affect scalar multiplication on an $ R $-module $ M $, which is an external operation?
Now provide the response and nothing else.
|
Intro a right R-module is equivalent to a left R-module only when R is commutative This statement has a pair of serious problems to resolve. Because "equivalent" is undefined, it's unclear what the statement means. (Discussed briefly below.) It uses "only when," but that is the wrong logical direction: it should use just when . There are in fact not-commutative rings where left and right modules are pretty much the same, so "only when" is not really appropriate. I think a better version of the statement is: A right $R$ module structure can be used as a left $R$ module structure when $R$ is commutative Modules over commutative rings Suppose you've defined a right $R$ module for a commutative ring so that $mr$ makes sense for $m\in M$ and $r\in R$. Then naively one might say "oh, well that must be the same thing as $rm$." Actually, it's not immediately clear that that is a legitimate thing to do, but yes, using commutativity of $R$, you can verify that the new action $rm:=mr$ satisfies all the module axioms. After that is done, we would have used the right $R$ module structure as a left $R$ module structure. Symmetrically, left module structures can be used as right module structures, and in fact if you switch sides twice, you wind up with the original module you started with. That's why we say when $R$ is commutative, right and left modules are "the same." Modules over rings in general It turns out that a left $R$ module structure on an abelian group $M$ amounts to a ring homomorphism of $R\to End(M)$, where $End(M)$ is the set of group endomorphisms of $M$. On the other hand, a right $R$ module structure on $M$ amounts to a ring homomorphism from $R\to End(M)^{op}$, where $End(M)^{op}$ is the opposite ring of $End(M)$. (Equivalently, you could use a ring homomorphism from $R^{op}\to End(M)$.) This whole "opposite ring" business is what makes it necessary to keep track of module sides: the homomorphisms of $R$ into $End(R)$ might be completely different from those into $End(R)^{op}$. That's just the way things are. Finally, if $R\cong R^{op}$, then something nice happens! Since $R$ and $R^{op}$ can't be distinguished, you can in fact use a left $R$ module structure as a right $R$ module structure. Formally, if you had the homomorphism $R\to End(M)$, you could simply compose it with the isomorphism $R^{op}\to R\to End(M)$ obtaining $R^{op}\to End(M)$, a right $R$ module structure. This is obviously the case for commutative rings, since the identity map is an isomorphism of a commutative ring with its opposite ring. But this applies more generally, since there are not-commutative rings isomorphic with their opposite rings. Your second question Your question is based on good observations :) The previous paragraph supplies a partial explanation of why the internal property of commutative rings can influence the two categories of modules. The reason is that since commutativity makes the ring "symmetric," its right modules and left modules are going to look alike. If you want to deepen your understanding of how the properties of a ring and its two module categories interact, then you will have a good time studying module theory because that is one of module theory's main topics.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/535246', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/102426/']}
|
jdg_378667
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6509298
|
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 lots of large (around 5000 x 5000) matrices that I need to invert in Matlab. I actually need the inverse, so I can't use mldivide instead, which is a lot faster for solving Ax=b for just one b. My matrices are coming from a problem that means they have some nice properties. First off, their determinant is 1 so they're definitely invertible. They aren't diagonalizable, though, or I would try to diagonlize them, invert them, and then put them back. Their entries are all real numbers (actually rational). I'm using Matlab for getting these matrices and for this stuff I need to do with their inverses, so I would prefer a way to speed Matlab up. But if there is another language I can use that'll be faster, then please let me know. I don't know a lot of other languages (a little but of C and a little but of Java), so if it's really complicated in some other language, then I might not be able to use it. Please go ahead and suggest it, though, in case.
Now provide the response and nothing else.
|
I actually need the inverse, so I can't use mldivide instead,... That's not true, because you can still use mldivide to get the inverse. Note that A -1 = A -1 * I . In MATLAB, this is equivalent to invA = A\speye(size(A)); On my machine, this takes about 10.5 seconds for a 5000x5000 matrix. Note that MATLAB does have an inv function to compute the inverse of a matrix. Although this will take about the same amount of time, it is less efficient in terms of numerical accuracy (more info in the link). First off, their determinant is 1 so they're definitely invertible Rather than det(A)=1 , it is the condition number of your matrix that dictates how accurate or stable the inverse will be. Note that det(A)=∏ i=1:n λ i . So just setting λ 1 =M , λ n =1/M and λ i≠1,n =1 will give you det(A)=1 . However, as M → ∞ , cond(A) = M 2 → ∞ and λ n → 0 , meaning your matrix is approaching singularity and there will be large numerical errors in computing the inverse. My matrices are coming from a problem that means they have some nice properties. Of course, there are other more efficient algorithms that can be employed if your matrix is sparse or has other favorable properties. But without any additional info on your specific problem, there is nothing more that can be said. I would prefer a way to speed Matlab up MATLAB uses Gauss elimination to compute the inverse of a general matrix (full rank, non-sparse, without any special properties) using mldivide and this is Θ(n 3 ) , where n is the size of the matrix. So, in your case, n=5000 and there are 1.25 x 10 11 floating point operations. So on a reasonable machine with about 10 Gflops of computational power, you're going to require at least 12.5 seconds to compute the inverse and there is no way out of this, unless you exploit the "special properties" (if they're exploitable)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6509298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/661284/']}
|
jdg_378668
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10753881
|
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 change the language of the error message in the html5 form field. I have this code: <input type="text" name="company_name" oninvalid="setCustomValidity('Lütfen işaretli yerleri doldurunuz')" required /> but on submit, even the field is not blank, I still get the error message. I tried with <input type="text" name="company_name" setCustomValidity('Lütfen işaretli yerleri doldurunuz') required /> but then the english message is displayed. Anyone know how can I display the error message on other language? Regards,Zoran
Now provide the response and nothing else.
|
setCustomValidity 's purpose is not just to set the validation message, it itself marks the field as invalid. It allows you to write custom validation checks which aren't natively supported. You have two possible ways to set a custom message, an easy one that does not involve Javascript and one that does. The easiest way is to simply use the title attribute on the input element - its content is displayed together with the standard browser message. <input type="text" required title="Lütfen işaretli yerleri doldurunuz" /> If you want only your custom message to be displayed, a bit of Javascript is required. I have provided both examples for you in this fiddle .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10753881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1004754/']}
|
jdg_378669
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
896704
|
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 just curious but will the convolution operation be any sort of group operation? A motivating example would be to see that the natural exponential family of distribution functions are closed under convolution (although I'm not sure about the inverse). I know the irreducible unitary representation is a possible link of convolution to groups, but its just a hunch. If not, could it relate to any weaker structure? like a monoid, semigroup?
Now provide the response and nothing else.
|
Let $X$ be any set and $F$ a field. The space of functions $\hom(X,F)$ is a vector space over $F$; given any function $f:X\to F$ and scalar $a\in F$, we have $(af)(x):=af(x)$, and given any other function $g$ we have $(f+g)(x):=f(x)+f(x)$, for all $x\in X$. These are called pointwise operations, because you act on the function by acting on its value at each individual argument. If $M$ is any monoid, we can equip $\hom(M,F)$ with a convolution operation $$(f*g)(x):=\sum_{ab=x}f(a)g(b).$$ This operation is commutative if $M$ is commutative, but otherwise not necessarily. This is because the tuples $(a,b)$ for which $ab=x$ may not be the same tuples for which $ba=x$. But the operation is associative. And the function $f$ defined by $f(e_M)=1_F$ and $f(x)=0$ for $x\ne e_M$ is a two-sided identity element with respect to this operation. Moreover, convolution distributes over addition! This means that $\hom(M,F)$ forms a unital, associative algebra over a field when equipped with pointwise addition and convolution. One can also restrict to certain subspaces of $\hom(M,F)$ (for instance, if $M$ and $F$ are topological, then we can take compactly supported continuous maps). Example: if we take the subspace of functions with finite support, we get the monoid algebra denoted $F[M]$. This is usually presented as the space of formal $F$-linear combinations of elements of $M$ (with the obvious multiplication extended using the distributive property). Such a formal sum of the form $\sum_{x\in M} a_xx$ corresponds to the function $x\mapsto a_x$. Check for yourself that multiplication of formal sums corresponds to convolution of functions. Example: if $M=(\Bbb N,+)$ is the naturals (containing $0$) under addition, then $F[M]\cong F[x]$ is the polynomial ring in one variable. (Can you figure out what the isomorphism is?)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/896704', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74973/']}
|
jdg_378670
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26155523
|
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 assign multiple variables in one line using Swift? var blah = 0 var blah2 = 2 blah = blah2 = 3 // Doesn't work???
Now provide the response and nothing else.
|
You don't. This is a language feature to prevent the standard unwanted side-effect of assignment returning a value, as described in the Swift book : Unlike the assignment operator in C and Objective-C, the assignment operator in Swift does not itself return a value. The following statement is not valid: if x = y { // this is not valid, because x = y does not return a value } This feature prevents the assignment operator ( = ) from being used by accident when the equal to operator ( == ) is actually intended. By making if x = y invalid, Swift helps you to avoid these kinds of errors in your code. So, this helps prevent this extremely common error. While this kind of mistake can be mitigated for in other languages—for example, by using Yoda conditions —the Swift designers apparently decided that it was better to make certain at the language level that you couldn't shoot yourself in the foot. But it does mean that you can't use: blah = blah2 = 3 If you're desperate to do the assignment on one line, you could use tuple syntax, but you'd still have to specifically assign each value: (blah, blah2) = (3, 3) ...and I wouldn't recommend it. While it may feel inconvenient at first, just typing the whole thing out is the best way to go, in my opinion: blah = 3blah2 = 3
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26155523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015571/']}
|
jdg_378671
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28314
|
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the newest episode of Q&A (which was broadcast on Monday, 29 June 2015), a theoretical physicist and cosmologist named Lawrence Krauss from America, made this statement/comment. There's been a study in America that being an atheist is viewed on the level as being a rapist. It's the same thing. The quote is taken from this video: Radicalisation, Religion & Recognition between 54:50 and 55:10. The context was whether it's possible for someone who is running for political office in America to admit to being a atheist. What is this study?
Now provide the response and nothing else.
|
Was there a study finding that being an atheist is viewed on the level of being a rapist in the US? Everything I have been able to find points to a single study. Restricting the search to before the study was published results in nothing interesting. Similarly restricting the search to about a year after the study was published results in a few late comers. Everything seems to point to one paper. The paper is composed of 6 studies. The first of which surveyed US citizens, comparing how they reported their feelings about gay men in contrast to atheists. The remaining five studies used a sample from a pool of psychology students from University of British Columbia (Canadian). Of these studies the only one that used the group "rapist" was study 2. So already, our answer seems to be no. (though, of course you can't prove a negative) But let's go ahead and take a look at the study anyway. Study 2 One hundred five UBC undergraduates (Age 18-25, M = 19.95; 71% Female) participated for extra credit. Participants read the following description of an untrustworthy man who is willing to behave selfishly (and criminally) when other people will not find out: " Richard is 31 years old. On his way to work one day, he accidentally backed his car into a parked van. Because pedestrians were watching, he got out of his car. He pretended to write down his insurance information. He then tucked the blank note into the van's window before getting back into his car and driving away. Later the same day, Richard found a wallet on the sidewalk. Nobody was looking, so he took all of the money out of the wallet. He then threw the wallet in a trash can. " Next, participants chose whether they thought it more probable that Richard was either 1) a teacher, or 2) a teacher and XXXX. We manipulated XXXX between subjects. XXXX was either a Christian (N = 26) a Muslim (N = 26) a rapist (N = 26) an atheist (someone who does not believe in God) (N = 27) The only difference in descriptions across targets was that the Muslim target was called "a man" rather than "Richard". So the conclusions were drawn based on how often the conjunction fallacy was committed with a 31 year-old teacher named Richard who committed insurance fraud and stole the money from a found wallet, since no one was looking (and threw the wallet away). In sum, participants frequently committed the conjunction fallacy when given a description of an untrustworthy person and a target who could be an atheist or a rapist, but not for targets who could be a Christian or a Muslim. It's not mentioned how the authors think Richard being a teacher would have affected the likelihood of the conjunction fallacy with atheist among these college students; or what affect him sharing his name with one of, if not the , most prominent atheist might have. As hypothesized, participants were significantly more likely to commit the conjunction error for an atheist target than for either a Christian target or a Muslim target, odds ratio = 22.29 (95% C.I.: 3.82, 427.10), b = 3.10, p = .004 and odds ratio = 5.11 (95% C.I.: 1.48, 21.13), b = 1.63, p = .01, respectively. The atheist target did not significantly differ from the rapist target, odds ratio = 1.27 (95% C.I.: .43, 3.79), b = .24, p = .67. You can see the proportion of individuals committing the conjunction fallacy above this can be multiplied by 26 (the number of individuals in each group, 27 in atheist) to get the approximate number of individuals committing the fallacy in each group. The pool the students were drawn from was a bit interesting as well. Christian (34%), None (16%), Nonreligious (12%), Agnostic (11%), Atheist (9%), Other (7%), Buddhist (7%), Muslim (3%), and Jewish (1%) East Asian (49%), Caucasian/White (30%), Other/mixed (7%), South Asian (6%), Southeast Asian (4%), Middle Eastern (2%), Hispanic/Latino (1%), and African (< 1%) One last thing of interest: In an additional analysis, we examined whether atheists distrust other atheists. We isolated a subsample of 49 individuals from the total sample who indicated that they do not believe in God (based on the binary Yes/No belief question). Atheists Distrust within this subsample did not significantly differ from zero, t(48)= -.08, p= .94, indicating that whereas religious people strongly distrust atheists, atheists neither trust nor distrust atheists, relative to people in general.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://skeptics.stackexchange.com/questions/28314', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/26923/']}
|
jdg_378672
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21469270
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
(new to WPF) I am looking over the WPF example: <Window x:Class="Attempt_XAML.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <Label HorizontalAlignment="Center">A Button Stack</Label> <Button HorizontalAlignment="Left">Button 1</Button> <Button HorizontalAlignment="Right">Button 2</Button> <Button Background="#FFA29494">Button 3</Button> <Button>Button 4</Button> </StackPanel></Window> Remark in MS notes that: The default value is stretch for both HorizontalAlignment and VerticalAlignment of content that is contained in a StackPanel. However, result looks different from what I am expecting. Button and Label are not stretched out vertically, but only horizontally(i.e they don't fill the entire space of Window in both directions) Why ?
Now provide the response and nothing else.
|
Button and Label are not stretched out vertically, but only horizontally(i.e they don't fill the entire space of Window in both directions) Why ? To understand the reason, you really need at least a basic understanding of Panels . Any Panel such as a StackPanel uses a measure-arrange cycle to decide on a layout for its child elements: in the "measure" cycle, it assigns a size to each child in the "arrange" cycle, it positions each child in its view The key feature of a StackPanel is that it has infinite space -- infinite horizontal space if its orientation is Horizontal , and infinite vertical space if Vertical . In other words, it does not actually pay attention to the size available to it (in the direction of its orientation), but claims an infinite space. So therefore, coming back to your example, even though the VerticalAlignment of the children may be Stretch , they cannot actually be stretched out to an infinite size. If you need a panel that stretches out its children to fill the available space, then Grid is a good example (by default the Grid will assign an equal share of the total height to each child -- or you can use the star sizing to adjust the proportions). You could also consider creating your own custom Panel, if you need a specialized layout behavior. Edit To clarify "infinite space": what I mean is that the StackPanel tells its children that there is infinite space available. What do you do if you are a Button, Label, etc, and there is infinite space available? You probably just take up the minimum space you need, even if your VerticalAlignment is "Stretch", right? That's what happens. Contrast to a Grid, which tells the child controls that they have x (finite) amount of space -- in that case, a Button, Label, etc, will fill up all that space (if their VerticalAlignment is "Stretch"). To illustrate the above, take this custom control as an example: public class TestControl : ContentControl{ public string Description { get; set; } protected override Size MeasureOverride(Size availableSize) { System.Diagnostics.Debug.WriteLine("Size available for '" + Description + "': " + availableSize.Height); return base.MeasureOverride(availableSize); }} This doesn't actually do anything, just reports how much space has been allocated to it. Now, place the test control in a Grid and a StackPanel , and compare: <Grid Height="50"> <Grid.RowDefinition /> <Grid.RowDefinition /> <local:TestControl Description="in Grid" /> <StackPanel Grid.Row="1" Height="10"> <local:TestControl Description="in StackPanel" /> </StackPanel></Grid> You'll see that the Grid assigns its CustomPanel (the first one above) a height of 25 (half its height). The StackPanel , though, assigns its CustomPanel a height of Infinity.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21469270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465292/']}
|
jdg_378673
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
188730
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I thought that if you repeated a sequence of characters in your password, the password would get easier to crack. I tried one of those websites which gives you an estimate of how much time it would take it to crack a password with a force brute attack (websites of dubious reliability, but anyway) and it doesnt seem to show any sign of weakness by repeating a sequence of 20 characters several times (the password gets increased by 30 orders of magnitude) Then my question is, if a password repeats a sequence of characters, does it become easier to crack?
Now provide the response and nothing else.
|
Not exactly. More precisely: For any given human-generated password (based on a known word or character sequence), repeating character sequences from that base word to create a longer password makes that specific password just a tiny bit harder to crack than the underlying base word ... ... but the resulting longer password will be inherently weaker than other passwords of the same length that were created using a stronger length-extension method ... ... and it's hard for a password-strength meter to tell the difference. To understand why, we need an understanding both of human password memorization strategies - and of the limitations of password strength meters. A human password strategy like duplicating letters is a common way to meet password length requirements because the incremental cognitive burden for the user is low (only requiring the user to remember a little bit more information.) For example, if the minimum password length requirement was 12, then a password paaaaassword meets that requirement, with the user only having to remember two things: My password starts with the word password as a base. I then just repeat the a four more times. Increasing password length with a "trick" only marginally improves attack resistance. While the raw Shannon entropy of the new password is higher, the effective entropy of the new password is only very slightly higher than the base word itself - because it's really only one more piece of additional information - which means that it can be easily used by attackers. Many password-lengthening strategies (adding digits, adding a couple of common special characters, doubling the word, etc.) are very well-known to password crackers. Most cracking software can try these strategies at very high speeds. So strategies like adding repeating characters to a human-generated password are easy to implement in a password attack ... but they are much more difficult to implement in a password-strength meter. This is why password-strength meters are notoriously inaccurate. A meter can use broad general measurements of strength (complexity, composition rules), and approximate some of the basic attacks (masks, simple wordlists, etc.) ... but it is impossible for a meter to mimic the millions of combinations of base words and human password-generation rules ... without starting to behave more and more like a password cracking engine. And such meters need to be much faster than that, in order to give real-time feedback to the user. So the strategy of repeating characters only marginally increases the effective entropy, which will fall to high-speed attacks ... but the password-strength meter can't use the same attack strategies to tell the difference.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/188730', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/103379/']}
|
jdg_378674
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6860893
|
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 git branch checked out named foo . > git status# On branch foonothing to commit (working directory clean) It was originally checked out using this command: > git checkout origin/foo -b foo --track I want to get updates to this branch from the remote repository. I know that either of these commands will suffice: > git fetch origin foo # ignore the lack of merging> git pull origin foo If I omit the arguments to fetch or pull , will git default to fetching (or pulling) the branch that I currently have checked out? That is, are the following pairs of commands equivalent? > git checkout foo> git pull and > git checkout foo> git pull origin foo
Now provide the response and nothing else.
|
Unfortunately, whether they are equivalent or not in general depends on which branch you are on, your configuration, phase of the moon, etc. You can figure this out from the git pull man page, as I've described below, but I would generally try to avoid having to work that out by doing: git fetch origin and then git merge origin/foo . (I wrote a somewhat rambling blog post about this .) However, your question is really about the default behaviour of git pull when you don't specify a remote or a refspec. We can figure this out from the git pull man page , and in particular the DEFAULT BEHAVIOUR section . This is somewhat tough to figure out, so I've put in bold the only parts that really apply to your question given that (a) you are on branch foo , (b) you created that branch as you described in the question, and (c) you haven't been changing your configuration. Often people use git pull without giving any parameter. Traditionally, this has been equivalent to saying git pull origin . However, when configuration branch.<name>.remote is present while on branch <name> , that value is used instead of origin . In order to determine what URL to use to fetch from, the value of the configuration remote.<origin>.url is consulted and if there is not any such variable, the value on URL: line in $GIT_DIR/remotes/<origin> file is used. In order to determine what remote branches to fetch (and optionally store in the remote-tracking branches) when the command is run without any refspec parameters on the command line, values of the configuration variable remote.<origin>.fetch are consulted, and if there aren’t any, $GIT_DIR/remotes/<origin> file is consulted and its Pull: lines are used. In addition to the refspec formats described in the OPTIONS section, you can have a globbing refspec that looks like this: refs/heads/*:refs/remotes/origin/* A globbing refspec must have a non-empty RHS (i.e. must store what were fetched in remote-tracking branches), and its LHS and RHS must end with /* . The above specifies that all remote branches are tracked using remote-tracking branches in refs/remotes/origin/ hierarchy under the same name. The rule to determine which remote branch to merge after fetching is a bit involved, in order not to break backward compatibility. If explicit refspecs were given on the command line of git pull, they are all merged. When no refspec was given on the command line, then git pull uses the refspec from the configuration or $GIT_DIR/remotes/<origin> . In such cases, the following rules apply: If branch.<name>.merge configuration for the current branch exists, that is the name of the branch at the remote site that is merged. If the refspec is a globbing one, nothing is merged. Otherwise the remote branch of the first refspec is merged. When you created the branch foo with: git checkout origin/foo -b foo --track ... it will have set the following config options, which associate your branch foo with refs/heads/foo in the origin repository: branch.foo.remote=originbranch.foo.merge=refs/heads/foo So, if you put that together with the emboldened sentences above, the answer is "Yes, in this situation you describe, when you're on branch foo , the commands git pull and git pull origin foo are equivalent."
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6860893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139010/']}
|
jdg_378675
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21982118
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A generator is simply a function which returns an object on which you can call next, such that for every call it returns some value, until it raises a StopIteration exception, signaling that all values have been generated. Such an object is called an iterator. >>> def myGen(n):... yield n... yield n + 1... >>> g = myGen(6) I quoted this from Understanding Generators in Python? Here is what I am trying to figure out: Which is the generator? myGen or myGen(6) ? According to the quote mentioned above, I think the generator should be myGen . And myGen(6) is the returned iterator object. But I am really not sure about it. When I tried this: >>> type(myGen)<type 'function'>>>> type(g) # <1>this is confusing me.<type 'generator'> >>> callable(g) # <2> g is not callable. False >>> callable(myGen)True>>> g is iter(g) # <3> so g should an iterable and an iterator True # at the same time. And it will be passed as an argument>>> for i in g: # to built-in function `next()` in a "for...in..." loop. print i # (is that correct?)67 So, according to <1> and <2> , g 's type is 'generator' and it is not callable.But generators are callable, and calling a generator gets you an iterator object What's going on here? When I was searching for answers, I run into Every time you define a function python creates a callable object. So, can I say something like this? when the function myGen is defined, myGen is a name referring to a callable object which is an instance of a class that has a __call__ method . In this case, myGen is a generator, and myGen(6) is the returned iterator when myGen is called. But why does type(g) return <type 'generator'> at all?And this returned iterator thing also looks suspicious to me since there is no return statement in the function. Isn't it that Functions always return something (at least None , when no return-statement was reached during execution and the end of the function is reached) ?
Now provide the response and nothing else.
|
The terminology is unfortunately confusing, as "generator" is so commonly used to refer to either the function or the returned iterator that it's hard to say one usage is more correct. The documentation of the yield statement says The yield statement is only used when defining a generator function , and is only used in the body of the generator function. Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. When a generator function is called, it returns an iterator known as a generator iterator , or more commonly, a generator . The original PEP introducing the concept says Note that when the intent is clear from context, the unqualified name "generator" may be used to refer either to a generator-function or a generator-iterator . If you want to make a clear distinction, use "generator function" for the function and "generator iterator" for the iterator.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21982118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2961429/']}
|
jdg_378676
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35430
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $G$ be a (simple) graph. Given $k \ge \chi(G)$, define $Cor(G,k,u,v)$ to be the proportion among all $k$-colorings of $G$ for which the vertices $u$ and $v$ have the same color. Questions: Question 1. Given a graph $G$ and a positive integer $k \ge \chi(G)$, is there a better-than-greedy way to calculate $Cor(G,k,u,v)$? I suspect the answer to this question is "Yes, but not really."; for is there was an efficient way to calculate $Cor$, we would probably get $P=NP$. Question 2. If not, is there a ``good'' way to estimate it? Question 3. Is there any other information (e.g., the chromatic polynomial, etc.) that would yield an efficient way to calculate $Cor$?
Now provide the response and nothing else.
|
A few opposite-looking remarks, and the case of (minimal) surfaces. If a variety $X$ admits a non-constant morphism to a curve, then it admits a non-constant morphism to $\mathbb{P}^1$ (just compose the given morphism with a morphism of the curve to $\mathbb{P}^1$). Thus, if you only care about existence of a non-constant morphism to a curve, you may as well restrict your attention to the question of existence of a non-constant morphism to $\mathbb{P}^1$. On the other hand, the existence of a morphism to a curve of genus at least one is a birational property: any such morphism factors through the Albanese variety of $X$, and the Albanese variety of $X$ is a birational invariant. The property of admitting a morphism to $\mathbb{P}^1$ is clearly not a birational invariant property, as any non-constant rational function determines a rational map to $\mathbb{P}^1$ (see Charles Matthews' answer). Both questions appear quite hard, though. An equivalent formulation of the question is the following: does $X$ admit two disjoint effective non-zero nef divisors? The equivalence of the statements is almost tautological. An easy implication is that the rank of the Neron-Severi group of $X$ is at least two, and that there are effective non-zero nef divisors that are not big. For minimal surfaces, the situation is as follows. A surface of negative Kodaira dimension (i.e. a ruled surface or $\mathbb{P}^2$, here we do not need the surface to be minimal) admits a morphism to $\mathbb{P}^1$ if and only if it is not isomorphic to $\mathbb{P}^2$. A surface of Kodaira dimension zero (i.e. a K3, Enriques, Abelian of bielliptic surface) not admitting a morphism to $\mathbb{P}^1$ is a non-elliptic K3 surface. Every surface of Kodaira dimension one (a properly elliptic surface) admits a morphism to $\mathbb{P}^1$ (and in fact a canonical morphism to a curve). EDIT: Among surfaces of Kodaira dimension zero, also simple abelian surfaces (i.e. abelian surfaces that are not isogenous to a product of two elliptic curves) admit no morphism to a curve. For all surfaces (including the surfaces of Kodaira dimension two), one thing you can say is that there is a Theorem of Castelnuovo and de Franchis characterizing surfaces with a morphism to a curve of genus at least two. Thus, in conclusion, it seems that for minimal surfaces of special type, the only surfaces not admitting a morphism to a curve are $\mathbb{P}^2$ and non-elliptic K3 surfaces and simple abelian surfaces (which does not look so bad, after all!). Note that every irreducible component of the moduli space of polarized K3 surfaces contains elliptic surfaces and non-elliptic ones.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/35430', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8437/']}
|
jdg_378677
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29184358
|
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 implement a generic function in Rust where the only requirement for the argument is that the multiplication operation should be defined. I'm trying to implement a generic "power", but will go with a simpler cube function to illustrate the problem: use std::ops::Mul;fn cube<T: Mul>(x: T) -> T { x * x * x}fn main() { println!("5^3 = {}", cube(5));} When compiling I get this error: error[E0369]: binary operation `*` cannot be applied to type `<T as std::ops::Mul>::Output` --> src/main.rs:4:5 |4 | x * x * x | ^^^^^^^^^ | = note: an implementation of `std::ops::Mul` might be missing for `<T as std::ops::Mul>::Output` What does this mean? Did I choose the wrong trait? How can I resolve this?
Now provide the response and nothing else.
|
Let's break down your example a bit: fn cube<T: Mul>(x: T) -> T { let a = x * x; let b = a * x; b} What are the types of a and b ? In this case, the type of a is <T as std::ops::Mul>::Output — sound familiar from the error message? Then, we are trying to multiply that type by x again, but there's no guarantee that Output is able to be multiplied by anything! Let's do the simplest thing and say that T * T needs to result in a T : fn cube<T: Mul<Output = T>>(x: T) -> T { x * x * x} Unfortunately, this gives two similar errors: error[E0382]: use of moved value: `x` --> src/lib.rs:6:9 |6 | x * x * x | - ^ value used here after move | | | value moved here | = note: move occurs because `x` has type `T`, which does not implement the `Copy` trait Which is because the Mul trait takes arguments by value , so we add the Copy so we can duplicate the values. I also switched to the where clause as I like it better and it is unwieldy to have that much inline: fn cube<T>(x: T) -> Twhere T: Mul<Output = T> + Copy{ x * x * x} See also: How do I implement the Add trait for a reference to a struct? How to write a trait bound for adding two references of a generic type?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29184358', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/141906/']}
|
jdg_378678
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25857
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
2 samuel 6:23 (KJV) 23 Therefore Michal the daughter of Saul had no child unto the day of her death. 2 samuel 21:7-9 (KJV) 7 But the king spared Mephibosheth, the son of Jonathan the son of Saul, because of the LORD'S oath that was between them, between David and Jonathan the son of Saul. 8 But the king took the two sons of Rizpah the daughter of Aiah, whom she bare unto Saul, Armoni and Mephibosheth; and the five sons of Michal the daughter of Saul, whom she brought up for Adriel the son of Barzillai the Meholathite: 9 And he delivered them into the hands of the Gibeonites, and they hanged them in the hill before the LORD: and they fell all seven together, and were put to death in the days of harvest, in the first days, in the beginning of barley harvest. It would seem in 2 samuel 6 Michal the the daughter of King Saul died without conceiving but later the same Michal is mentioned as having five sons,or is that Saul had another daughter named Michal as well?
Now provide the response and nothing else.
|
As a commenter notes , there is a text-critical issue here. The Masoretic Text of the Hebrew Bible plainly reads "Michal" at this point. However, as the textual notes to the Biblia Hebraica Stuttargtensia indicate, there are two Hebrew manuscripts that read "Merob", and there is some support for this among Septuagint manuscripts, too: P. Kyle McCarter comments on this textual situation in his II Samuel Anchor Bible commentary (p. 439) this way: For this reason, almost all modern versions read "Merab" here, in light of 1 Sam 18:19, as well as the tradition of Michal's childessness. There are dissenting voices: see, e.g., J. J. Glück, " Merab or Michal ", Zeitschrift für die Alttestamentliche Wissenschaft 77/1 (1965), 72–81, who argues for the retention of Michal. This is where the vast majority of modern scholars, translators, and commentators are content to leave it: that 2 Sam 21:8 contains a "slip" (S.R. Driver calls it a " lapsus calami ") confusing the names of Michal and Merab which is then corrected. The KJV's "whom she brought up for Adriel" may itself represent an attempt to deal with the perceived problem, since that is a dodgy translation, to put it bluntly. The Hebrew here, אֲשֶׁ֥ר יָלְדָ֛ה לְעַדְרִיאֵ֥ל, plainly means "whom she had borne to Adriel" (cf. BDB sub ילד ). Older commentators spotted the problem, but got round it -- in the case of both Rashi and Matthew Henry , from very different times and traditions -- by supposing that although the five sons must have been born to Merab, they were raised by her sister, the childless Michal, thus following the same line of reasoning which gives rise to the KJV's mistranslation.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/25857', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/16527/']}
|
jdg_378679
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3503345
|
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:
My problem: Suppose $x_n > 0$ and the infinite series $\sum x_n y_n$ converges for all nonnegative sequences $\{ y_n\}$ such that $\sum {y_n}^3$ converges. Show that $\sum x_n^{3/2}$ is convergent. Since $\frac{1}{3} + \frac{1}{3/2} = 1$ , I thought of the Holder inequality: $$\sum_{n=1}^\infty x_n y_n \leq \left(\sum_{n=1}^\infty x_n^{3/2} \right)^{2/3}\left(\sum_{n=1}^\infty y_n^{3}\right)^{1/3}$$ but the direction of the inequality is not going to help with a comparison test for convergence of $\sum x_n^{3/2}$ .
Now provide the response and nothing else.
|
Obtain a contradiction by assuming $S_n = \sum_{k=1}^n x_k^{3/2} \to \infty$ and taking $y_n = \frac{x_n^{1/2}}{S_n}$ . Note that $ \sum_{n=1}^\infty y_n^3 < \infty ,$ since $$\sum_{n=2}^m \frac{x_n^{3/2}}{S_n^3} = \sum_{n=2}^m \frac{S_n - S_{n-1}}{S_n^3}\leqslant \sum_{n=2}^m \int_{S_{n-1}}^{S_n} \frac{dx}{x^3} = \frac{1}{2S_1^2} - \frac{1}{2S_m^2} \underset{m \to \infty}\longrightarrow \frac{1}{2S_1^2}$$ However, contrary to the hypothesis, $$\sum_{n=1}^\infty x_n y_n = \sum_{n=1}^\infty x_n \frac{x_n^{1/2}}{S_n} = \sum_{n=1}^\infty \frac{x_n^{3/2}}{S_n} = \infty,$$ using a well-known result that divergence of a positive seres $\sum_{n \geqslant 1} a_n$ implies divergence of $\sum_{n \geqslant 1} \frac{a_n}{\sum_{k=1}^n a_k}$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3503345', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/318852/']}
|
jdg_378680
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7618121
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the sentence "I would like 50 of those, please" in cell A1. I want to make any numeric characters red text (just the numeric characters). How do I do this? Here's the frame of what I have... Sub RedText()Dim i As IntegerFor i = 1 To Len(Cells(1, 1).Value) If IsNumeric(Mid(Cells(1, 1).Value, i, 1)) = True Then 'make the character red text End IfNextEnd Sub Any help would be greatly appreciated.
Now provide the response and nothing else.
|
You can use the characters( start, length ) property to do this. You can also store the text in a string and loop on that, which will be faster when you work with many cells. Here is an example: Sub RedText()Dim i As LongDim text As Stringtext = Cells(1, 1).ValueFor i = 1 To Len(text) If IsNumeric(Mid$(text, i, 1)) = True Then Cells(1, 1).Characters(i, 1).Font.Color = vbRed End IfNextEnd Sub
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7618121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/974051/']}
|
jdg_378681
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24947198
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using Java 8 stream what is the best way to map a List<Integer> when you have no output for the input Integer ? Simply return null? But now my output list size will be smaller than my input size... List<Integer> input = Arrays.asList(0,1,2,3); List<Integer> output = input.stream() .map(i -> { Integer out = crazyFunction(i); if(out == null || out.equals(0)) return null; return Optional.of(out); }) .collect(Collectors.toList());
Now provide the response and nothing else.
|
I don’t get why you (and all answers) make it so complicated. You have a mapping operation and a filtering operation. So the easiest way is to just apply these operation one after another. And unless your method already returns an Optional , there is no need to deal with Optional . input.stream().map(i -> crazyFunction(i)) .filter(out -> out!=null && !out.equals(0)) .collect(Collectors.toList()); It may be simplified to input.stream().map(context::crazyFunction) .filter(out -> out!=null && !out.equals(0)) .collect(Collectors.toList()); But you seem to have a more theoretical question about what kind of List to generate, one with placeholders for absent values or one with a different size than the input list. The simple answer is: don’t generate a list . A List is not an end in itself so you should consider for what kind of operation you need this list (or its contents) and apply the operation right as the terminal operation of the stream. Then you have your answer as the operation dictates whether absent values should be filtered out or represented by a special value (and what value that has to be). It might be a different answer for different operations…
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24947198', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/119333/']}
|
jdg_378682
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55307489
|
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 implement a struct person, and I need to hide some fields or make them constant. A trick for create private fields. Header: #pragma once#define NAME_MAX_LEN 20typedef struct _person { float wage; int groupid;} Person;const char const *getName (Person *p);int getId (Person *p);/// OTHER FUNCTIONS Source #include "person.h"struct _person{ int id; float wage; int groupid; char name[NAME_MAX_LEN];};/// FUNCTIONS GCC says that person.c:7:8: error: redefinition a 'struct _person' struct _person I can write this in a header, but after it, I can't use fields of a struct. typedef struct _person Person;
Now provide the response and nothing else.
|
A struct cannot have multiple conflicting definitions. As such, you can't create a struct that hides some of the fields. What you can do however it declare that the struct exists in the header without defining it. Then the caller is restricted to using only a pointer to the struct and using functions in your implementation to modify it. For example, you could define your header as follows: typedef struct _person Person;Person *init(const char *name, int id, float wage, int groupid);const char *getName (const Person *p);int getId (const Person *p);float getWage (const Person *p);int getGroupid (const Person *p); And your implementation would contain: #include "person.h"struct _person{ int id; float wage; int groupid; char name[NAME_MAX_LEN];};Person *init(const char *name, int id, float wage, int groupid){ Person *p = malloc(sizeof *p); strcpy(p->name, name); p->id = id; p->wage= wage; p->groupid= groupid; return p;}...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55307489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9855653/']}
|
jdg_378683
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
98971
|
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:
After centering, the two measurements x and −x can be assumed to be independent observations from a Cauchy distribution with probability density function: $f(x :\theta) = $ $1\over\pi (1+(x-\theta)^2) $ $, -∞ < x < ∞$ Show that if $x^2≤ 1$ the MLE of $\theta$ is 0, but if $x^2>1$ there are two MLE's of $\theta$, equal to ±$\sqrt {x^2-1}$ I think to find the MLE I have to differentiate the log likelihood: $dl\over d\theta$ $=\sum $$2(x_i-\theta)\over 1+(x_i-\theta)^2 $ $=$ $2(-x-\theta)\over 1+(-x-\theta)^2 $ + $2(x-\theta)\over 1+(x-\theta)^2 $ $=0$ So, $2(x-\theta)\over 1+(x-\theta)^2 $ $=$ $2(x+\theta)\over 1+(x-\theta)^2 $ which I then simplified down to $5x^2 = 3\theta^2+2\theta x+3$ Now I've hit a wall. I've probably gone wrong at some point, but either way I'm not sure how to answer the question. Can anyone help?
Now provide the response and nothing else.
|
There is a math typo in your calculations. The first order condition for a maximum is: \begin{align}\frac {\partial L}{\partial \theta}= 0 &\Rightarrow \frac {2(x+\theta)}{ 1+(x+\theta)^2} - \frac{2(x-\theta)}{ 1+(x-\theta)^2}&=0 \\[5pt]&\Rightarrow (x+\theta)+(x+\theta)(x-\theta)^2 - (x-\theta)-(x-\theta)(x+\theta)^2&=0 \\[3pt]&\Rightarrow 2\theta +(x+\theta)(x-\theta)\left[x-\theta-(x+\theta\right]&=0 \\[3pt]&\Rightarrow2\theta -2\theta(x+\theta)(x-\theta) =0\Rightarrow 2\theta -2\theta(x^2-\theta^2)&=0 \\[3pt]&\Rightarrow2\theta(1-x^2+\theta^2)=0 \Rightarrow 2\theta\big(\theta^2+(1-x^2)\big)&=0\end{align} If $x^2\leq 1$ then the term in the parenthesis cannot be zero (for real solutions of course), so you are left only with the solution $\hat \theta =0$. If $x^2 >1$ you have $2\theta\big[\theta^2-(x^2-1)\big]=0$ so, apart from the candidate point $\theta =0$ you also get $$\frac {\partial L}{\partial \theta}= 0,\;\; \text{for}\;\;\hat \theta = \pm\sqrt {x^2-1}$$ You also have to justify why in this case $\hat \theta =0$ is no longer an MLE. ADDENDUM For $x =\pm 0.5$ the graph of the log-likelihood is while for $x =\pm 1.5$ the graph of the log-likelihood is, Now all you have to do is to prove it algebraically and then wonder "fine -now which of the two should I choose?"
|
{}
|
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/98971', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/40378/']}
|
jdg_378684
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1520458
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The depressed cubic equation $y^3 +py + q = 0$ can be solved with Vieta's transformation (or Vieta's substitution ) $y = z - \frac{p}{3 \cdot z}.$ This reduces the cubic equation to a quadratic equation (in $z^3$). Is there any geometric or algebraic motivation for this transformation? I am not asking why this transformations works - this is just an easy calculation. I would rather like to know how to come up with it. Perhaps even how and when Vieta came up with it. I haven't found anything about the history of this transformation, except that it probably wasn't invented by Vieta . Notice that the Ansatz $y = z + \frac{c}{z}$ for a constant $c$ will eventually lead to $c = -\frac{p}{3}$, but what motivates this Ansatz - except for that it works in the end? Here is what I guess (but this is not convincing yet): Polynomial transformations do not work, so let's try rational transformations. Try to keep the degree low. I am aware of Galois theory and how it helps to understand the cubic from a highly conceptual point of view, but I would like to avoid Galois theory here. Any information about the history of this transformation will also be appreciated.
Now provide the response and nothing else.
|
Viète's motivation came from the solution of the following problem: Find two numbers when their sum and the sum of their cubes are given, i.e., find $x$ and $y$ such that $$x+y=a, \qquad x^3+y^3=d$$ A simple solution is to factor the last expression: $$\begin{align}x^3+y^3&=(x+y)(x^2-xy+y^2) \\ &=(x+y)((x+y)^2-3xy) \\ &=a(a^2-3xy)=d\end{align}$$ We can now find $$xy={a^3-d \over 3a}$$ and the problem is reduced to the much simpler one of solving the equations $x+y=a$ and $xy=b$ , which Viète had already considered. Viète now realized that he had a very nice relation between the sum of two numbers, the product of the two numbers, and the sum of their cubes, given by $$a^3 - 3ba = d$$ Hence, if he had an equation on this form, where $a$ was the unknown, he could solve it by finding $x$ and $y$ such that $a=x+y$ and $b=xy$ . This leads to the substitution $$a = x + {b\over x}$$ The equation then becomes $$x^3+{b^3\over x^3}=d$$ which gives $d$ as the sum of the cubes, and which is a quadratic in $x^3$ . Edit: The Analytic Art by Viète is available online. The motivating example is on p. 110, and this solution of the cubic equation is on p. 289. Viète's methods are also explained in Victor Katz: A History of Mathematics. An Introduction .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1520458', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1650/']}
|
jdg_378685
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31307584
|
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 learning how to build apps and working with Swift for this project. I had a buddy help me pull data in from a website and it looks like he created classes with variables and mapped them to certain extensions (IE "Username") so when I call the variable data such as profile I would call it. The below uses luck_30 able to store "Stats.luck_30" luck_30.text = profile.luck_30 So inside one of my variables that is in this "Profile" class is setup into an array. I can pull the array out of the class, but I can't seem to do for while statement replacing the [#] with a variable from the for command. func aliveWorkers(profile: Profile) -> NSNumber{ var myworkers : Array = profile.workers! //this test works and returns the proper value var testworker: NSNumber = myworkers[0].alive! println("The satus of the test worker is " + testworker.description) /* This code is giving error "Could not find member alive" it does not ifor var for ifor in myworkers{ var thisworker: NSNumber = myworkers[ifor].alive! as NSNumber } */ return 42}
Now provide the response and nothing else.
|
There are two approaches you can use: Approach 1: Use a background script. in manifest.json : "browser_action": { "default_icon": "icon.png"},"permissions": [ "activeTab", "clipboardWrite"],"background": { "persistent": false, "scripts": ["background.js"]} (You can also use "page": "background.html" instead of "scripts" .) in background.js : chrome.browserAction.onClicked.addListener(function(tab) { alert('working?');}); Approach 2: Use a popup. manifest.json: "browser_action": { "default_icon": "icon.png", "default_popup": "popup.html"},"permissions": [ "activeTab", "clipboardWrite"] in popup.html : <html> <head> <script src="popup.js"></script> </head></html> in popup.js : alert('working?'); Your problem was that you were mixing the two. If you use a browser_action.default_popup , then chrome.browserAction.onClicked is never triggered . (And you wouldn’t want a background page named popup.html , since that would cause all sorts of confusion.)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31307584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5096558/']}
|
jdg_378686
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48441356
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does this code work? I expected this to fail because of breaking of one of the basic C++ rules: #include <iostream>using namespace std;struct A { A() { cout << "ctor A" << endl; } void doSth() { cout << "a doing sth" << endl; }};struct B { B(A& a) : a(a) { cout << "ctor B" << endl; } void doSth() { a.doSth(); } A& a;};struct C { C() : b(a) { cout << "ctor C" << endl; } void doSth() { b.doSth(); } B b; A a;};int main(){ C c; c.doSth();} https://wandbox.org/permlink/aoJsYkbhDO6pNrg0 I expected this to fail since in C's constructor, B is given a reference to object of A when this A object has not yet been created. Am I missing something? Does the rule of order of initialization being the same as the order of fields not apply for references? EDIT:What surprises me even more is that I can add a call to "a.doSth();" inside B constructor and this will also work. Why? At this moment the A object should not exist!
Now provide the response and nothing else.
|
Your code is fine so long as the constructor of B doesn't use that reference it gets for anything other than binding its member. The storage for a has already been allocated when the c'tor of C starts, and like Sneftel says, it's in scope. As such, you may take its reference, as [basic.life]/7 explicitly allows: Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see [class.cdtor]. Otherwise, such a glvalue refers to allocated storage ([basic.stc.dynamic.deallocation]), and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if: the glvalue is used to access the object, or the glvalue is used to call a non-static member function of the object, or the glvalue is bound to a reference to a virtual base class ([dcl.init.ref]), or the glvalue is used as the operand of a dynamic_cast or as the operand of typeid. Regarding your edit: What surprises me even more is that I can add a call to "a.doSth();" inside B constructor and this will also work. Why? At this moment the A object should not exist! Undefined behavior is undefined. The second bullet in the paragraph I linked to pretty much says it. A compiler may be clever enough to catch it, but it doesn't have to be.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48441356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7174778/']}
|
jdg_378687
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1632412
|
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 $F$ is a field. Suppose we have $a,b \in F $ and relatively prime integers $m,n \geq 1$ such that $a^m = b^n$. Can I conclude that there is some $c \in F $ such that $c^{mn} = a^m = b^n$?
Now provide the response and nothing else.
|
Write $xm+yn=1$ with $x,y$ integers. Then $c=a^yb^x$ satisfies $c^{mn} = a^{ymn}b^{xmn} = (a^m)^{yn}(b^n)^{xm}=(b^n)^{yn+xm}=b^n$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1632412', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/99428/']}
|
jdg_378688
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
448693
|
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 currently trying to better understand the fundamental notions of statistics. Navigating through multiple sites, I've found this formula for joint probability.P(A ∩ B) = P(A)*P(B) Namely, if we want to know what is the probability of A and B to co-occur, we just multiply their individual (marginal) probabilities. As for the conditional probability, the formula stands like this:P(A | B) = P(A∩B) / P(B) So, if we want to know the probability of A when we already know B, we divide the joint probability of A and B by the probability of B. If we develop this formula, we will get:P(A | B) = P(A)*P(B)/P(B) Further, we can simplify the fraction by dividing it by P(B), and we are left withP(A | B) = P(A) Suppose we want to estimate the probability of drawing from a deck of cards a red colored card of 4 (hearts or diamonds), while already knowing it's colored red. Individual (marginal) probabilities P(red) = 1/2 = 0.5P(4) = 4/52 = 1/13 Joint Probability (to draw a red 4) P(4 ∩ red) = P(A)*P(B) = 1/2 * 1/13 = 1/26 Conditional probability (prob to draw a 4 already knowing it is red) P(4 | red) = P(4 ∩ red) / P(red) = P(4)*P(red)/P(red)P(4 | red) = 1/13*0.5/0.5 = 1/13 If we know that the card we are about to draw is red, the probability of it being a red 4 is 1/13 (or 7.6%), which is just the probability of drawing a 4 from the deck. This makes sense because we have eliminated half of the possibilities (black cards), and we are actually drawing from a set of 26 cards that has 2 fours in it. So, 2 out of 26 (or 1 of 13) of the drawn cards will be a red 4. The results look fine, but it really seems that I am missing something, because in the relationship P(A | B) = P(A) doesn't take into account the probability of B. I will be highly grateful is someone could look into my question and give a response. Thanks in advance!
Now provide the response and nothing else.
|
$P(A\cap B)=P(A)P(B)$ is true if and only if $A$ and $B$ are independent. So, $P(A|B)\neq P(A)$ in general. In your example, it holds because the events are fortunately independent. You already informally found it in your reasoning paragraph, by thinking about the sample space. For a simple counter example, consider the case where $A=B$ . $P(A|B)=1$ clearly, because if you know that $B=A$ happened, the probability of $A$ happening is $1$ .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/448693', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/273263/']}
|
jdg_378689
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11489255
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Sometimes, my script cannot read output by a server and the following error occurs: PHP Fatal error: Call to a member function somefun() on a non-object This is not something that can't be fixed on my end but this causes my script to crash. Is there a way I can create a function that gets run when this particular error occurs? I don't think it's practical to make a try-catch or similar because I would have to find every instance where a member function gets called and test whether the object exists or not (several thousand).
Now provide the response and nothing else.
|
In PHP 7 Yes, catch an "Error" throwable, see http://php.net/manual/en/language.errors.php7.php Demo: https://3v4l.org/Be26l <?php$x = "not an object";try { $x->foo();} catch (\Throwable $t) { echo "caught";} In PHP 5 Is there a way I can create a function that gets run when this particular error occurs? Yes, you can use " register_shutdown_function " to get PHP to call a function just before it dies after encountering this error. PHP: catching a fatal error (call to member function on a non-object) It is not possible to recover from this error, if that is what you mean by "catch", as PHP has defined "Call to a member function on a non-object" as a "fatal" error. See PHP turn "Call to a member function on a non-object" into exception for some discussion on why this might be.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11489255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255439/']}
|
jdg_378690
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14175514
|
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 tampering with Expressions and I got confused at some points We can assign same LamdaExpression to both Expression and/or Func. But we cannot assign a Func to an Expression (or an Expression to Func). Why cannot we do that? I looked for if a conversion operator between Expression and Func is defined but I could not found any. Func<int, int> sumFunc = i => i + i;Expression<Func<int, int>> sumExp = i => i + i;// sumExp = sumFunc; // Cannot convert source type 'System.Func<int,int>' to target type 'System.Linq.Expressions.Expression<System.Func<int,int>>'// sumFunc = sumExp; // Cannot convert source type 'System.Linq.Expressions.Expression<System.Func<int,int>>' to target type 'System.Func<int,int>' Even we cannot assign a LambdaExpression to an object. Again, why cannot we do that? // object o = i => i + i; // Cannot convert source type 'lambda expression' to target type 'object' I think there is something about compiler. If so, can we write our custom types those behave in this (confusing) manner and take advantage of something.
Now provide the response and nothing else.
|
Regarding to the C# Language Specification a lambda expression like i => i + i is an anonymous function. An expression with this classification can be implicitly converted to a compatible delegate type or expression tree type. This is why you can write both Func<int, int> sumFunc = i => i + i;Expression<Func<int, int>> sumExp = i => i + i; The first is a delegate type, the second an expression tree type. Because there is no implicit converting between those types, you cannot assign sumFunc = sumExp or vice versa. But since the expression tree sumExp represents a lambda expression, you can compile that expression to an executable delegate and assign it to sumFunc , because this is such a compatible delegate: sumFunc = sumExp.Compile(); The other direction is not possible, because a delegate cannot easily be "decompiled" into an expression tree. The reason why you cannot write object o = i => i + i; is, that an anonymous function does not have a value or type in and of itself, it is just convertible to a delegate or expression tree type. You have to tell the compiler which of both you want, so you can convert it at first and then assign the result to a variable of type object : object sumFuncObject = (Func<int, int>) (i => i + i);object sumExpObject = (Expression<Func<int, int>>) (i => i + i); Regarding your last question: You can create custom implicit or explicit conversions between complex types, so that this "magic" can be applied to assignments. See the Conversion Operations Programming Guide for more information.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14175514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/554397/']}
|
jdg_378691
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3049175
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am (just for fun) trying to implement a High Score web-service. I would like it be compatible with REST principles. I want to be able to add a new highscore using url parameters like this http://mydomain.com/hs/add&name=John&score=987 . According to REST this must be done using a POST request. Which leads to empty POST request with all data contained in the URL parameters. Would this be considered a bad practice? Update Security is currently not a big concern.
Now provide the response and nothing else.
|
The common way to do it would be to send a POST to http://mydomain.com/hs/add with the content: name=John&score=987 (for simple urlencoded data, would be different for e.g. multipart encoded data; the format of the POST request body is arbitrary and outside of the scope of REST recommendations – it could even be arbitrary encrypted data, as others have suggested). A GET request for adding a new highscore would not only be a violation of REST principles, but also a violation of RFC 2616 , which requires GET requests to be idempotent. EDIT Is it bad practice to pass data in the query string and post an empty body? Yes. The URL should describe the resource that's being subjected to the action described by the HTTP method. Hence, probably the best option would be to have http://mydomain.com/hs as an URL and let the body completely describe the action. The query string could possibly be used to further qualify requests without a body, e.g.: http://mydomain.com/hs?period=lastmonth (GET)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3049175', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/75889/']}
|
jdg_378692
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24453
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This is a foundational doubt I have. How does singular homology H_n capture the number of n-dimensional holes in a space? We disregard the case of $H_0$ as it has the very satisfactory explanation that it is the direction sum of $\mathbb Z$ over the path-connected components of the space. Now, handwaving aside, we consider the most important example of this "detecting hole" phenomenon, viz,, the fact that for $i \geq 1$ $H_i(S^n) = \mathbb(Z)$ if and only if $i = n$. For this we use Mayer-Vietoris and a decomposition of $S_n$ into a union of two open sets which are the complements of the north pole and south pole. And the intersection deformation retracts to $S^{n -1}$ and from the long exact sequence we get the isomorphisms $H_i \cong H_{i -1}$. Now, by the above computation, it seems that the "hole detection" is achieved via Mayer-Vietoris and going up from the dimension below, using the long exact sequence. Mayer-Vietoris on the other hand depends on the snake lemma, which is very un-geometric and difficult to visualize. So I would be most grateful for a more intuitive explanation of this hole capturing phenomenon. I can see that it is very natural that boundaries should be cancelled out as the solid simplices can be contracted to the central point. I can also "feel" that a hollow $n$-simplex, there should be a nontrivial $n$-chain which is not a boundary of an $n+1$-chain. But I am still left with a feeling of partial understanding. I hope this fundamental vagueness of understanding of mine can be cleared here.
Now provide the response and nothing else.
|
The "hole detection" is rather in the very definition of homology. Consider, for example, $H_2$: it is morally the set of closed surfaces in you space modulo those that bound a $3$-dimensional body, and if a surface is not the boundary of any $3$-dimensional body then surely there must be a hole entrapped in it, no? (Morally because when you want to actually implement this, you get a slightly different thing... Although I'd be thrilled to be informed that, in the case of a manifold at least, say, one can somehow construct a free abelian group on the set of maps $\Sigma\to M$ from $k$-manifolds $\Sigma$ to $M$ which, when one mods out the subgroup of those maps that extend to a manifold-with-boundary $N$ such that $\partial N=\Sigma$, gets you $H_k(M)$ or something close)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/24453', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6031/']}
|
jdg_378693
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27580938
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following list comprehension that only works in Python 2 due to use of iteritems() : foo = [key for key, value in some_dict.iteritems() if value['marked']] I can't import any libraries. Is there a clean way of making this compatible on both Python 2 and 3?
Now provide the response and nothing else.
|
You can simply use dict.items() in both Python 2 and 3, foo = [key for key, value in some_dict.items() if value['marked']] Or you can simply roll your own version of items generator, like this def get_items(dict_object): for key in dict_object: yield key, dict_object[key] And then use it like this for key, value in get_items({1: 2, 3: 4}): print key, value
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27580938', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/804495/']}
|
jdg_378694
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3316244
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using gVim 7.2 on Windows 7. I can set the gui font as Consolas 10 (font size) from the menu. I am trying to set this in .vimrc file like below: set guifont=Consolas\ 10 But it doesn't work. Does anyone know how to set this?
Now provide the response and nothing else.
|
I use the following (Uses Consolas size 11 on Windows, Menlo Regular size 14 on Mac OS X and Inconsolata size 12 everywhere else): if has("gui_running") if has("gui_gtk2") set guifont=Inconsolata\ 12 elseif has("gui_macvim") set guifont=Menlo\ Regular:h14 elseif has("gui_win32") set guifont=Consolas:h11:cANSI endifendif Edit: And while you're at it, you could take a look at Coding Horror's Programming Fonts blog post . Edit²: Added MacVim.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3316244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/169477/']}
|
jdg_378695
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33734640
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this trait and simple structure: use std::path::{Path, PathBuf};trait Foo { type Item: AsRef<Path>; type Iter: Iterator<Item = Self::Item>; fn get(&self) -> Self::Iter;}struct Bar { v: Vec<PathBuf>,} I would like to implement the Foo trait for Bar : impl Foo for Bar { type Item = PathBuf; type Iter = std::slice::Iter<PathBuf>; fn get(&self) -> Self::Iter { self.v.iter() }} However I'm getting this error: error[E0106]: missing lifetime specifier --> src/main.rs:16:17 |16 | type Iter = std::slice::Iter<PathBuf>; | ^^^^^^^^^^^^^^^^^^^^^^^^^ expected lifetime parameter I found no way to specify lifetimes inside that associated type. In particular I want to express that the iterator cannot outlive the self lifetime. How do I have to modify the Foo trait, or the Bar trait implementation, to make this work? Rust playground
Now provide the response and nothing else.
|
There are a two solutions to your problem. Let's start with the simplest one: Add a lifetime to your trait trait Foo<'a> { type Item: AsRef<Path>; type Iter: Iterator<Item = Self::Item>; fn get(&'a self) -> Self::Iter;} This requires you to annotate the lifetime everywhere you use the trait. When you implement the trait, you need to do a generic implementation: impl<'a> Foo<'a> for Bar { type Item = &'a PathBuf; type Iter = std::slice::Iter<'a, PathBuf>; fn get(&'a self) -> Self::Iter { self.v.iter() }} When you require the trait for a generic argument, you also need to make sure that any references to your trait object have the same lifetime: fn fooget<'a, T: Foo<'a>>(foo: &'a T) {} Implement the trait for a reference to your type Instead of implementing the trait for your type, implement it for a reference to your type. The trait never needs to know anything about lifetimes this way. The trait function then must take its argument by value. In your case you will implement the trait for a reference: trait Foo { type Item: AsRef<Path>; type Iter: Iterator<Item = Self::Item>; fn get(self) -> Self::Iter;}impl<'a> Foo for &'a Bar { type Item = &'a PathBuf; type Iter = std::slice::Iter<'a, PathBuf>; fn get(self) -> Self::Iter { self.v.iter() }} Your fooget function now simply becomes fn fooget<T: Foo>(foo: T) {} The problem with this is that the fooget function doesn't know T is in reality a &Bar . When you call the get function, you are actually moving out of the foo variable. You don't move out of the object, you just move the reference. If your fooget function tries to call get twice, the function won't compile. If you want your fooget function to only accept arguments where the Foo trait is implemented for references, you need to explicitly state this bound: fn fooget_twice<'a, T>(foo: &'a T)where &'a T: Foo,{} The where clause makes sure that you only call this function for references where Foo was implemented for the reference instead of the type. It may also be implemented for both. Technically, the compiler could automatically infer the lifetime in fooget_twice so you could write it as fn fooget_twice<T>(foo: &T)where &T: Foo,{} but it's not smart enough yet . For more complicated cases, you can use a Rust feature which is not yet implemented: Generic Associated Types (GATs). Work for that is being tracked in issue 44265 .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33734640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1667955/']}
|
jdg_378696
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
267387
|
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:
There are so many false calculations out there that working with Quantity und units—at least initially—should be mandatory in many applications. Alas, implementation in the Wolfram Language sometimes seems to be in the way. I will give a simple calculation of compound interest as example: r = Quantity[ 5, "Percent"/"Years" ]; (* a continuously compounding rate *)t = Quantity[ 10, "Years" ]; (* time for interest to accrue *)initialCapital = Quantity[ 1000, "USDollars" ]; initialCapital Exp[ r t ] While in this special case using Normal and N come to the rescue, it seems that the treatment of units that are compatible to "DimensionlessUnit" like Percent is not consistent accross WL functions. Note the following: Log[ 1. + 5 Quantity["Percent"] ](* 0.0487902 *)Log[ 1. + Quantity[ 5, "Percent"] ](* 0.0487902 *)Exp[ 5. Quantity["Percent"] ](* E^Quantity[5., "Percent"] *) Is there some principle here? How to best work with units in these cases? A support case with the identification [CASE:4935014] was created. Please include this ID in any future correspondence with Wolfram Technical Support regarding this issue.
Now provide the response and nothing else.
|
While the approaches in the comments (thanks a lot!) solve the issue, the question triggered me to try to "have my cake and eat it as well" , i.e., enter quantities but decide globally whether they are used and what will happen if I just want magnitudes—after all using Quantity slows down things. A Litte Package For Conditional Quantities The use of quantities with appropriate units should be mandatory for any mathematical model of reality, so that we may have a chance to validate equations. While using Quantity is the way to go, there is a price to pay with regard to performance—likely a reason that using Quantity may be avoided and mere comments are used for units, which have the downside, that we can't let Mathematica help us. So a nice thing to have may actually be to allow the verbose use of Quantity so that users can enter 10 Quantity["Percent"] instead of 0.1 (don't laugh, it happens). But at the same time, we may use ConditionalQuantity as a wrapper to guide conversion with regard to the use in our models. The following package thus has two main functions: Allow to use On["Quantities"] and Off["Quantities"] to switch between UnitConvert and QuantityMagnitude for quanties as appropriate. Tell Mathematica how we would like to have our verbose units be interpreted either for UnitConvert or QuantityMagnitude . We can achieve (2) by using: ConditionalQuantity[quantity] to use QuantityMagnitude as is or to keep quantity as is, i.e., no target units are provided. ConditionalQuantity[quantity, "Canonical" ] to try to go for the canonical unit, if it exists. ConditionalQuantity[quantity, "Normal" ] to get rid of all units that are compatible to "DimensionlessUnit" (i.e., replace those units by 1 ), but leave the other units unchanged. ConditionalQuantity[quantity, unit] to tell QuantityMagnitude and UnitConvert that unit is the target unit. (Instead of unit we also provide a reference Quantity .) Code BeginPackage[ "ConditionalQuantities`" ]Quantity::inuse = "Quantities in use."QuantitiesOffQ::usage = "\QuantitiesOffQ[] returns True, if messages related to Quantities have been switched off using Off[\"Quantities\"].\The function will by default be used by ConditionalQuantity to decide whether a magnitude or a quantity is to be returned." $numericalUnitRules = "\$ numericalUnitRules is a list of replacement rules for numerical units like Percent, BasisPoints, Thousand etc."ConditionalQuantity::usage = "\ConditionalQuantity[quantity] will return QuantityMagnitude[quantity] if QuantitiesOffQ[] is True and quantity, if this is not the case.\n\ConditionalQuantity[quantity, \"Canonical\" ] will call ConditionalQuantity[quantity, unit], where unit is the canonical unit.\n\ConditionalQuantity[quantity, \"Normal\" ] will call ConditionalQuantity[quantity, unit], where unit is QuantityUnit[quantity] where all parts\ compatible to \"DimensionlessUnit\" have been replaced by 1.\n\ConditionalQuantity[quantity, refQuantity] will call ConditionalQuantity[quantity, QuantityUnit[refQuantity]].\n\ConditionalQuantity[quantity, unit] will return QuantityMagnitude[quantity,unit] or UnitConversion[quantity, unit] depending on QuantitiesOffQ[].\ If units is are not compatible, unit input is disregarded and ConditionalQuantity[quantity] is called."Begin["`Private`"]$numericalUnitRules = Map[ Rule[ #, 1 ]&, { "Percent", "BasisPoints", "Dozen", "Hundred", "Thousand", "HundredThousand", "Million", "Billion", "Trillion" }] $MessageGroups = Join[ $ MessageGroups, { "Quantities" :> { Quantity::inuse } } ]QuantitiesOffQ[] := HoldPattern[ Quantity::inuse ] /. Messages[ Quantity ] // Not @* FreeQ[ $Off ]ConditionalQuantity[ q_Quantity ] := If[ QuantitiesOffQ[], QuantityMagnitude @ q, q ]ConditionalQuantity[ q_Quantity, refq_Quantity ] := ConditionalQuantity[ q, QuantityUnit @ refq ]ConditionalQuantity[ q_Quantity, "Canonical" ] := Enclose[ With[ { canonicalUnit = ConfirmQuiet[ QuantityVariableCanonicalUnit @ QuantityVariable @ UnitDimensions @ q ] } , ConditionalQuantity[ q, canonicalUnit ] ]]ConditionalQuantity[ q_Quantity, "Normal" ] := With[ { normalUnit = QuantityUnit[ q ] /. $numericalUnitRules } , If[ normalUnit === 1, (* then *) ConditionalQuantity[ q, "DimensionlessUnit" ], (* else *) ConditionalQuantity[ q, normalUnit ] ]]ConditionalQuantity[ q_Quantity, unit_ ] /; CompatibleUnitQ[ q, unit ] unit := If[ QuantitiesOffQ[], (* then *) QuantityMagnitude[ q, unit ], (* else *) UnitConvert[ q, unit ]]ConditionalQuantity[ q_Quantity, unit_ ] /; Not @ CompatibleUnitQ[ q, unit ] := ConditionalQuantity[q]End[]EndPackage[] Examples Assuming that we loaded the package with <<ConditionalQuantities` or Needs , we can now do the following: On["Quantities"] (* Not really necessary since it is default *)r := ConditionalQuantity[ Quantity[5., "Percent"/"Years"], "Normal" ];t := ConditionalQuantity[ Quantity[10, "Years"] ]; initialCapital := ConditionalQuantity[ Quantity[1000, "USDollars"] ];initialCapital Exp[r t](* $1648.72 *)r(* 0.05 per year *)Do[ initialCapital Exp[r t], 1000] // RepeatedTiming{0.957131, Null}Off["Quantities"]initialCapital Exp[ r t ](* 1648.72 *)r(* 0.05 *)Do[ initialCapital Exp[r t], 1000] // RepeatedTiming{0.413421, Null}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/267387', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/764/']}
|
jdg_378697
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1962283
|
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 avoid circular dependencies, other than mixing modules, in a arrangement like this(it is a chess application) Long description: There is the Gui module which imports a ChessWidget module; ChessWidget just wraps the ChessWorld module and imports CellButton ; The CellButton module imports the module Cell ; The ChessWorld module imports Board (to represent it) and Players (to notify them and fetch their moves); The Board module imports module Piece ; The Piece module imports module Player ; AND HERE IS THE PROBLEM: The Player module needs to know about other players and the board, thus importing ChessWorld ! Short description: The World module needs to know about the Player module (even indirectly by Board / Piece ) and Player need to know about World . Help is very appreciated. PS: Is not because I cant use circular dependencies, but because they are evil.
Now provide the response and nothing else.
|
Follow the Dependency inversion principle : introduce an interface, which ChessWorld implements, and on which Player depends -- and/or one which Player implements and on which Piece depends (either or both may be appropriate depending on details on the nature of the dependency). This often goes together with Dependency Injection , and, if the dependant needs to dynamically instantiate a number of instance of the dependees, with Factory DPs.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1962283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95600/']}
|
jdg_378698
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49320810
|
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 good about using [[maybe_unused]] ?Consider int winmain(int instance, int /*prevInstance*/, const char */*cmdline*/, int show);int winmain(int instance, [[maybe_unused]] int prevInstance, [[maybe_unused]] const char *cmdline, int show); Some might insist that using comments is ugly, because this keyword was made and intended to be used under these circumstances, and I totally agree with it, but the maybe_unused keywords seems a bit too long to me, making the code slightly harder to read. I would like to follow the standard as "strictly" as I can, but is it worth using?
Now provide the response and nothing else.
|
If the parameter is definitely unused, [[maybe_unused]] is not particularly useful, unnamed parameters and comments work just fine for that. [[maybe_unused]] is mostly useful for things that are potentially unused, like in void fun(int i, int j) { assert(i < j); // j not used here anymore} This can't be handled with unnamed parameters, but if NDEBUG is defined, will produce a warning because j is unused. Similar situations can occur when a parameter is only used for (potentially disabled) logging.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/49320810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7609476/']}
|
jdg_378699
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
204099
|
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 am under the impression that an encrypted string cannot be decrypted so the original value is lost forever. However, if the following string always equals "dominic" (my name), then can't there be some logical way to reverse it; being as it's not random nor is it based on the date/time, but there is a logical method to it? 0WrtCkg6IdaV/l4hDaYq3seMIWMbW+X/g36fvt8uYkE= No matter what or how many times I encrypt "dominic" (string), it always equals as above. So, shouldn't there be some way to decrypt a string like that? Example of what I'm talking about: public string EncryptPassword(string password){ return Convert.ToBase64String( System.Security.Cryptography.SHA256.Create() .ComputeHash(Encoding.UTF8.GetBytes(password)));}
Now provide the response and nothing else.
|
Encryption can always be reversed. The point of encryption is to take a message and encode it with a secret key so that only another person who has the key can reverse the encryption and read the message. What you're looking at here is hashing , which is not the same as encryption, though cryptographic techniques are often used in implementing hashes. The idea of a hash is that it uses complicated mathematical techniques to build a new value that maps to an old value, which is repeatable. There's no key, and it's not meant to be reversed. A cryptographically strong hash is created with the mathematical property that, if you have value A whose hash is value B , it's very, very difficult to intentionally create another value C that also hashes to B . Hashes don't need to be reversible, because they're used for authentication. If you give me a username and a password, you really don't want me storing that password in my database, because if someone hacks in and gains access to my database, they could get ahold of your password! So instead, I'd store the hash of your password in the database. Then when you log in, I check to see if there's a username that matches yours, with a password entry that matches the hash of the password you sent, and if so you're authenticated, because it's very difficult to create a hash collision (two values that hash to the same value) with a good hash, so I'm almost perfectly certain that the password you used is the right one. The other property of a strong cryptographic hash is that it's very difficult to reverse. You know that the value 0WrtCkg6IdaV/l4hDaYq3seMIWMbW+X/g36fvt8uYkE= is the hash for "dominic" because you just worked it out, but if you didn't know that, and didn't know where to start looking, and all you had was 0WrtCkg6IdaV/l4hDaYq3seMIWMbW+X/g36fvt8uYkE= , it could literally take you billions of years to figure out that the original was "dominic", if the hash is a good one. Again, this is useful to prevent collateral damage in case a password list gets stolen.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/204099', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/61753/']}
|
jdg_378700
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
464510
|
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 the following function be defined as such:$$F_x: \Bbb R \to \Bbb C, x \mapsto x^{1/x}, \forall x \ne 0$$ What I want to know is $$\max_{x<0}\Re\left(F_x\right)=\,?$$and$$\max_{x<0}\Im\left(F_x\right)=\,?$$ Additional Questions Why does $F$ act weird when approaching $0$ form the left? For example $$\lim_{x\to0^-}F_x=\infty \text{ and }\lim_{x\to0^+}F_x=0$$ What is with the oscillation when approaching? How are $\Re(F_x)$ and $\Im(F_x)$ related during the left approach? Are there any other functions with similar behaviors?
Now provide the response and nothing else.
|
For $x\gt0$, we have$$x^{1/x}=e^{\log(x)/x}$$As $x\to0^+$, $\log(x)/x\to-\infty$. As $x\to+\infty$, $\log(x)/x\to0$. In between, $\log(x)/x$ has a maximum of $1/e$ at $x=e$. We get this by looking at its derivative, which is $\frac{1-\log(x)}{x^2}$. Therefore, for $x\gt0$, we have an infimum of $0$ as $x\to0^+$ and a maximum of $e^{1/e}$ at $x=e$. For $x\lt0$, let $x=-t$. Then, taking $\log(x)=\log(-t)=\log(t)+i\pi$, we get$$\begin{align}x^{1/x}&=e^{-(\log(t)+i\pi)/t}\\&=(\cos(\pi/t)-i\sin(\pi/t))e^{-\log(t)/t}\end{align}$$As $t\to0^+$ (that is, $x\to0^-$), $-\log(t)/t\to+\infty$. As $t\to+\infty$ (that is $x\to-\infty$), $-\log(t)/t\to0$. In between, $-\log(t)/t$ has a minimum of $-1/e$ at $t=e$. Therefore, for $t>0$, $e^{-\log(t)/t}$ have a minimum of $e^{-1/e}$ at $t=e$ and a supremum of $+\infty$ as $t\to0^+$. However, since$$\begin{align}\mathrm{Re}\left(x^{1/x}\right)&=\hphantom{-}\cos(\pi/t)e^{-\log(t)/t}\\\mathrm{Im}\left(x^{1/x}\right)&=-\sin(\pi/t)e^{-\log(t)/t}\end{align}$$the fact that $e^{-\log(t)/t}$ grows without bound and the $\sin(\pi/t)$ and $\cos(\pi/t)$ oscillate faster and faster between $+1$ and $-1$ as $t\to0^+$ means that$$\begin{align}\limsup_{x\to0^-}\mathrm{Re}\left(x^{1/x}\right)&=\limsup_{x\to0^-}\mathrm{Im}\left(x^{1/x}\right)=+\infty\\\liminf_{x\to0^-}\mathrm{Re}\left(x^{1/x}\right)&=\liminf_{x\to0^-}\mathrm{Im}\left(x^{1/x}\right)=-\infty\\\end{align}$$which in turn imply$$\bbox[5px, border: 1px solid #C00000]{\begin{align}\sup_{x\lt0}\mathrm{Re}\left(x^{1/x}\right)&=\sup_{x\lt0}\mathrm{Im}\left(x^{1/x}\right)=+\infty\\\inf_{x\lt0}\mathrm{Re}\left(x^{1/x}\right)&=\inf_{x\lt0}\mathrm{Im}\left(x^{1/x}\right)=-\infty\\\end{align}}$$ Plots of $\mathrm{Re}\left(x^{1/x}\right)$ and $\mathrm{Im}\left(x^{1/x}\right)$: $\hspace{3.2cm}$ $\hspace{3.2cm}$ Additional Answers $\ \small\bullet$ The weird behavior when approaching $0$ from the left is two-fold: First, for $x\lt0$, $\log(|x|)/x\to+\infty$ as $x\to0^-$; therefore, $\left|\,x^{1/x}\,\right|=e^{\log(|x|)/x}\to+\infty$. Second, due to the $\pi i$ in $\log(x)$ for $x\lt0$, $\arg\left(x^{1/x}\right)=\pi/x$ forces both real and imaginary parts to oscillate positive and negative. $\ \small\bullet$ For $x\lt0$, $\mathrm{Re}\left(x^{1/x}\right)^2+\mathrm{Im}\left(x^{1/x}\right)^2=e^{\log(|x|)/x}$ and $\frac{\displaystyle\mathrm{Im}\left(x^{1/x}\right)}{\displaystyle\mathrm{Re}\left(x^{1/x}\right)}=\tan(\pi/x)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/464510', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87191/']}
|
jdg_378701
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43519690
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can someone explain the purpose of this two in csproj file (VS2017): <TargetFramework>netstandard1.6</TargetFramework><RuntimeIdentifier>win7</RuntimeIdentifier> I just migrated from VS2015 and now can't publish my web api because it looks I should use only one target framework. In addition I can't specify multiple RIDs. All these changed things make me frustrated. Nothing works from scratch, should overcome something over and over. I just want developing my web-api on windows, run xUnit tests here and then deploy web-api to run on linux (ubuntu) server. What I should put in both parameters in csproj ? Links with good explanation is highly appreciated. Update1 I have web api with referenced .net core libraries. Everything where migrated from VS2015. Now in root project I have <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> . When I publish via VS2017 I got error: C:\Program Files\dotnet\sdk\1.0.3\Sdks\Microsoft.NET.Sdk\buildCrossTargeting\Microsoft.NET.Sdk.targets(31,5): error : The 'Publish' target is not supported without specifying a target framework. The current project targets multiple frameworks, please specify the framework for the published application. But I have specified target framework in publish as netcoreapp1.1 . OK. Then I updated my csproj with <PropertyGroup Condition="$(TargetFramework)'=='netcoreapp1.1'"> <RuntimeIdentifier>ubuntu.16.10-x64</RuntimeIdentifier></PropertyGroup> as suggested below. But now I even can't build app, get error: 5>C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.targets(92,5): error : Assets file '\obj\project.assets.json' doesn't have a target for '.NETCoreApp,Version=v1.1/ubuntu.16.10-x64'. Ensure you have restored this project for TargetFramework='netcoreapp1.1' and RuntimeIdentifier='ubuntu.16.10-x64'. I just want develop with VS2017 at windows 8.1/windows7 and deploy to ubuntu 16.10. What I'm doing wrong ? Update2 I have 8 projects in solution. 3 of them are xUnit tests. Thus we have 5 projects. 4 of these 5 are class libraries and 1 is my web-app.All 4 class libraries have this: <TargetFrameworks>netstandard1.6;net461</TargetFrameworks> <ItemGroup Condition=" '$(TargetFramework)' == 'net461' "> <Reference Include="System" /> <Reference Include="Microsoft.CSharp" /></ItemGroup> My web app: <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks><ItemGroup Condition=" '$(TargetFramework)' == 'net461' "> <Reference Include="System" /> <Reference Include="Microsoft.CSharp" /> </ItemGroup> How to publish my web-app ?
Now provide the response and nothing else.
|
The <TargetFramework> (or <TargetFrameworks> when you want have multiple targets, such as net451 , one or multiple netstandard1.x etc). Per <TargetFramework> / <TargetFrameworks> entry one set of assemblies will be created and located inside bin\Debug\<targetframeworkid> ). This is useful, when you want to use a different library in .NET Core (because the library you used only works with full .NET Framework such as 4.5.1) or remove this feature from i.e. .NET Core because it's unsupported. It is used for both, building and NuGet restore. i.e. you can't use a net451 only library in a .NET Core project ( netstandard 1.1 for example - but you can use netstandard1.1 in a net451 project). <RuntimeIdentifier> / <RuntimeIdentifiers> on the other side is used for NuGet mainly. It tells NuGet which packages you need. For example if you want to target Linux, Mac and Windows, certain assemblies require native libraries (such as encryption. On windows CryptoAPI will be used, but on Linux and Mac you need OpenSSL). This includes non-managed dlls and *.so (Linux) files. i.e. <RuntimeIdentifiers>win7-x64;win7-x86;ubuntu.16.10-x64</RuntimeIdentifiers> will make nuget restore packages for win7 (both x64 and x86) versions and x64 only for ubuntu. This is required, because when you work on windows you need to download these native libraries too so you deploy/package them with dotnet publish . Here's a little catch though: When you have a full .NET Framework reference in <TargetFramework> or <TargetFrameworks> , then you must specify a single <RuntimeIdentifier> (singular, not plural <RuntimeIdentifiers> ), otherwise you will get an error. For example: <PropertyGroup> <TargetFrameworks>netstandard1.0;net451</TargetFrameworks> <RuntimeIdentifiers>win7-x64;win7-x86;ubuntu.16.10-x64</RuntimeIdentifiers> </PropertyGroup><!-- This entry will only be used for the .NET Framework 4.5.1 output --><PropertyGroup Condition="'$(TargetFramework)' == 'net451'"> <RuntimeIdentifier>win7-x64</RuntimeIdentifier></PropertyGroup>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43519690', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/665550/']}
|
jdg_378702
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7241936
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My app uses an NSOperationQueue to cache thumbnail images in a background thread. On the iPad2 I can push the concurrent task count limit up to 5 or 6, but on single core devices like the iPad 1 this brings the UI to a grinding halt. So, I'd like to detect a dual core device (currently only iPad 2) and adapt the concurrent limit appropriately. I know I'm not supposed to check model numbers, rather device features. So what device feature should I be looking for that would tell me whether the cpu is dual core?
Now provide the response and nothing else.
|
Method 1 [[NSProcessInfo processInfo] activeProcessorCount]; NSProcessInfo also has a processorCount property. Learn the difference here . Method 2 #include <mach/mach_host.h>unsigned int countCores(){ host_basic_info_data_t hostInfo; mach_msg_type_number_t infoCount; infoCount = HOST_BASIC_INFO_COUNT; host_info( mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount ) ; return (unsigned int)(hostInfo.max_cpus);} Method 3 #include <sys/sysctl.h>unsigned int countCores(){ size_t len; unsigned int ncpu; len = sizeof(ncpu); sysctlbyname ("hw.ncpu",&ncpu,&len,NULL,0); return ncpu;}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7241936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42961/']}
|
jdg_378703
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5874118
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Coming from Rails 2 to Rails 3 I've never worked so hard to understand something (side editorial). Anyway, In a Rails 3 app i have the following models... User: has_many :answers Answer: belongs_to :userbelongs_to :questionscope :user_answers, where (:user_id => current_user.id) Question: has_many :answersscope :qs_w_user_ans, joins(:questions) & (:user_answers) The current error i am getting is "undefined method `includes_values' for :user_answers:Symbol" There is a Question id and a User id. Each answer has question_id and user_id. I need the questions with a user's answers linked appropriately via the ids. Can you show me where my models are wrong? Thank you.
Now provide the response and nothing else.
|
The & operator (which I believe is recently deprecated) is an alias for merge , which allows you to essentially merge scopes. :user_answers isn't a scope, so you can't use this method. As Dinatih pointed out, you can call joins multiple times. In this case, creating different scopes for each join won't buy you much, so his method suits your case. More info on scopes: http://archives.edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html Update Sorry for my misunderstanding. :user_answers is a scope, but you're not calling it correctly in this case. You want the following: scope :qs_w_user_ans, joins(:questions) & Answer.user_answers When merging scopes, you call the merged scopes like class methods. In the article I linked, the scope :published on Post is merged with the scope :published on User : scope :published, lambda { joins(:posts).group("users.id") & Post.published}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5874118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/488856/']}
|
jdg_378704
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47854623
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I know what setFlags does is replacing the old flags with the new ones. And addFlags is appending more flag. I'm just confused why are the arguments in setFlags method that I've seen usually the same?For example: getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//orgetWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); After taking a look at android.view.Window class, I'm not clear that why they must do many binary operators (NOT, AND, OR). What is the purpose of this? public void setFlags(int flags, int mask) { final WindowManager.LayoutParams attrs = getAttributes(); attrs.flags = (attrs.flags & ~mask) | (flags & mask); mForcedWindowFlags |= mask; dispatchWindowAttributesChanged(attrs); } One more question, what is the difference between //argument is a flaggetWindow().addFlags(flag1); and //argument is the result of OR operator of 2 identical flagsgetWindow().addFlags(flag1 | flag1); and //argument is the result of OR operator of 2 different flagsgetWindow().addFlags(flag1 | flag2); and //argument is the result of AND operator of 2 identical flagsgetWindow().addFlags(flag1 & flag1); and //argument is the result of AND operator of 2 different flagsgetWindow().addFlags(flag1 & flag2); Any help would be appreciated.
Now provide the response and nothing else.
|
The binary operators are because the field is a bitfield. They use a single integer to hold a lot of settings, and each settings are assigned to different bits. You then use binary operations to combine them and set the bits correctly. This is a common hardware technique, its very space efficient. Generally you'll turn on a bit (a setting) by using OR on it, and remove it by ANDing its inverse. Both of these operations leave the rest of the settings unchanged. You would never see setFlags(FOO | FOO), because its redundant. All that happens is FOO would be set. You would see setFlags(FOO | BAR), which would set both FOO and BAR. When you see setFlags(FOO, FOO)- the second parameter is a mask. It allows you to turn fields on and off at the same time, and only the bits in the mask will change. SO any other setting will be kept as it was. The math is basically ((getFlags &~mask) | (value & mask)). You'll see the same thing in both values if you only want to change certain settings, and you want to turn them all on. setFlags(x,x) is equivalent to addFlags(x)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47854623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5157066/']}
|
jdg_378705
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15817881
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using data tables jquery plugin...In that search box comes up...Right now my label is on left side and search box on right side...How to move the search text box on left side and label on right side...I have put my code in fiddle...If I put js plug in code separately in JS panel it does not work....so i have combined the code and put it in one panel.... http://jsfiddle.net/bz2C4/37/ my related code starts from line 2121 #moveLabel { border: 1px solid black;}.dataTables_filter label { border: 1px solid red; background: lemonchiffon;}.dataTables_filter { position: static; text-align: center;} providing my code below /** * Generate the node required for filtering text * @returns {node} Filter control element * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnFeatureHtmlFilter ( oSettings ) { var oPreviousSearch = oSettings.oPreviousSearch; var sSearchStr = oSettings.oLanguage.sSearch; sSearchStr = (sSearchStr.indexOf('_INPUT_') !== -1) ? sSearchStr.replace('_INPUT_', '<input type="text" />') : sSearchStr==="" ? '<input type="text" />' : sSearchStr+' <input type="text" />'; var nFilter = document.createElement( 'div' ); nFilter.className = oSettings.oClasses.sFilter; nFilter.innerHTML = '<label id="moveLabel">'+sSearchStr+'</label>'; if ( !oSettings.aanFeatures.f ) { nFilter.id = oSettings.sTableId+'_filter'; } var jqFilter = $('input[type="text"]', nFilter); // Store a reference to the input element, so other input elements could be // added to the filter wrapper if needed (submit button for example) nFilter._DT_Input = jqFilter[0]; jqFilter.val( oPreviousSearch.sSearch.replace('"','"') ); jqFilter.bind( 'keyup.DT', function(e) { /* Update all other filter input elements for the new display */ var n = oSettings.aanFeatures.f; var val = this.value==="" ? "" : this.value; // mental IE8 fix :-( for ( var i=0, iLen=n.length ; i<iLen ; i++ ) { if ( n[i] != $(this).parents('div.dataTables_filter')[0] ) { $(n[i]._DT_Input).val( val ); } } /* Now do the filter */ if ( val != oPreviousSearch.sSearch ) { _fnFilterComplete( oSettings, { "sSearch": val, "bRegex": oPreviousSearch.bRegex, "bSmart": oPreviousSearch.bSmart , "bCaseInsensitive": oPreviousSearch.bCaseInsensitive } ); } } ); jqFilter .attr('aria-controls', oSettings.sTableId) .bind( 'keypress.DT', function(e) { /* Prevent form submission */ if ( e.keyCode == 13 ) { return false; } } ); return nFilter; }
Now provide the response and nothing else.
|
Your solution is fine. If the dates are literals, I'd prefer, though: WHERE datefield >= '2010-01-01 00:00:00' AND datefield < '2012-01-01 00:00:00' This performs exactly the same, but is more maintenable, because it makes clear the point of each literal "date" being a timestamp, not a date. For example, suppose sometime someone changes your query to the following AND datefield <= '2012-01-01' ... expecting (and failing) to include the full day "2012-01-01" in the query. With the later syntax, the intention is more clear and this confusion is prevented. To make it even more clear (perhaps too verbose), you can do the explicit cast: WHERE datefield >= '2010-01-01 00:00:00'::timestamp AND datefield < '2012-01-01 00:00:00'::timestamp I wouldn't use to_date() here for similar reasons (potential datatype confusion), nor to_timestamp() (it returns a timestamptz ). BTW, I've modified the case to comply with recommended practice (keywords in uppercase, identifiers in lowercase)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15817881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_378706
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9240188
|
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 custom binary resources (animated cursors) that would like to store as resources in a static lib in Visual Studio C++. It turns out that custom binary resources will not get loaded by ::LoadCursor() or found by ::FindResource() if it is a custom resource and in a static library. This question gives some work around. Following its advice, if I add the *.res file to an exe as a "Configuration Property->Linker->Additional Dependency" then the static library will be able to find the resource. BUT if the static library is part of a dll and I link it in as an Additional Dependency it is not found again! How can I link the resources in a dll? Or just make the binary be found in the static lib? The methods in the question are pretty cumbersome.
Now provide the response and nothing else.
|
In Add Resource dialog click Import, select "All Files ( . )" so that it allows you to import file of any type, and then just select the file you want there. When Custom Resource Type dialog pops up, type RCDATA into "Resource type" field. If you open .rc file, you will see something like this: ///////////////////////////////////////////////////////////////////////////////// RCDATA//IDR_RCDATA1 RCDATA "myfile.whatever" and it will generate resource.h with following line: #define IDR_RCDATA1 101 In code you access it like this: #include "resource.h"#include <windows.h>int main(int argc, char* argv[]){ HRSRC myResource = ::FindResource(NULL, MAKEINTRESOURCE(IDR_RCDATA1), RT_RCDATA); HGLOBAL myResourceData = ::LoadResource(NULL, myResource); void* pMyBinaryData = ::LockResource(myResourceData); return 0;} where pMyBinaryData is pointer to first byte of this executable. For more information visit Resource Functions Here's an example how you would save binary resource like this on disk: #include "resource.h"#include <windows.h>#include <fstream>int main(int argc, char* argv[]){ HRSRC myResource = ::FindResource(NULL, MAKEINTRESOURCE(IDR_RCDATA1), RT_RCDATA); unsigned int myResourceSize = ::SizeofResource(NULL, myResource); HGLOBAL myResourceData = ::LoadResource(NULL, myResource); void* pMyBinaryData = ::LockResource(myResourceData); std::ofstream f("C:\\x.bin", std::ios::out | std::ios::binary); f.write((char*)pMyBinaryData, myResourceSize); f.close(); return 0;} When you build project with resource like that, this resource will become part of your program (dll).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9240188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/110838/']}
|
jdg_378707
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30194919
|
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 ASP.NET MVC 6 (beta-4) app. public void ConfigureServices(IServiceCollection services){ // Logging services.AddLogging(); // ...}public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory){ // Add the console logger. loggerfactory.AddConsole(minLevel: LogLevel.Warning); // ...} And I have a controller... public class HomeController : Controller{ ILogger _logger; public HomeController(ILogger logger) { _logger = logger; } // ...} But when I'm not getting the service registered correctly somehow: InvalidOperationException: Unable to resolve service for type 'Microsoft.Framework.Logging.ILogger' while attempting to activate 'HomeController'. . What am I doing wrong with the registering the logger?
Now provide the response and nothing else.
|
I assumed that services.AddLogging(); was doing the right thing and registering ILogger . After looking at the source ( https://github.com/aspnet/Logging/blob/d874c5726e713d3eb34938f85faf7be61aae0f2a/src/Microsoft.Framework.Logging/LoggingServiceCollectionExtensions.cs ) I found that it's actually registering ILogger<> . Changing the signature of ILogger to ILogger<HomeController> makes the above example work. public class HomeController : Controller{ ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } // ...} Thanks to @Steve for setting me on the right track to find this.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30194919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/396746/']}
|
jdg_378708
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7020966
|
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 model with managed = False. class SampleModel(models.Model): apple = models.CharField(max_length=30) orange = models.CharField(max_length=30) class Meta: managed = False I have a unit test which creates a SampleModel, however when I run the test I get: DatabaseError: no such table: SAMPLE_SAMPLE_MODEL The django docs - https://docs.djangoproject.com/en/dev/ref/models/options/#managed documents the following: For tests involving models with managed=False, it's up to you to ensure the correct tables are created as part of the test setup. How can I actually "create" the tables during the test setup? Or alternatively, how can I make it so that when I am running tests, this model has "managed = True" for the duration of the test? In the real application, this model is actually backed by a view in the database. However for the during of the test, I would like to treat this as a table and be able to insert test data in there.
Now provide the response and nothing else.
|
Check out this blog post: http://www.caktusgroup.com/blog/2010/09/24/simplifying-the-testing-of-unmanaged-database-models-in-django/ It describes in detail the creation of a test runner for unmanaged models. from django.test.simple import DjangoTestSuiteRunnerclass ManagedModelTestRunner(DjangoTestSuiteRunner): """ Test runner that automatically makes all unmanaged models in your Django project managed for the duration of the test run, so that one doesn't need to execute the SQL manually to create them. """ def setup_test_environment(self, *args, **kwargs): from django.db.models.loading import get_models self.unmanaged_models = [m for m in get_models() if not m._meta.managed] for m in self.unmanaged_models: m._meta.managed = True super(ManagedModelTestRunner, self).setup_test_environment(*args, **kwargs) def teardown_test_environment(self, *args, **kwargs): super(ManagedModelTestRunner, self).teardown_test_environment(*args, **kwargs) # reset unmanaged models for m in self.unmanaged_models: m._meta.managed = False
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7020966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/386221/']}
|
jdg_378709
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10778741
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When doing a json_encode a multidimensional array in PHP, I'm noticing a different output simply by naming one of the arrays, as opposed to not naming them. For Example: $arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));json_encode($arrytest) gives a single array of multiple json objects [{"a":1,"b":2},{"c":3},{"d":4}]; whereas simply assigning a name to the middle array $arrytest = array(array('a'=>1, 'b'=>2),"secondarray"=>array('c'=>3),array('d'=>4));json_encode($arrytest) creates a single json object with multiple json objects inside {"0":{"a":1,"b":2},"secondarray":{"c":3},"1":{"d":4}}; why would the 1st option not return the same reasults as the 2nd execpt with "1" in place of "secondarray"
Now provide the response and nothing else.
|
In JSON, arrays [] only every have numeric keys, whereas objects {} have string properties. The inclusion of a array key in your second example forces the entire outer structure to be an object by necessity. The inner objects of both examples are made as objects because of the inclusion of string keys a,b,c,d . If you were to use the JSON_FORCE_OBJECT option on the first example, you should get back a similar structure to the second, with the outer structure an object rather than an array. Without specifying that you want it as an object, the absence of string keys in the outer array causes PHP to assume it is to be encoded as the equivalent array structure in JSON. $arrytest = array(array('a'=>1, 'b'=>2),array('c'=>3),array('d'=>4));// Force the outer structure into an object rather than arrayecho json_encode($arrytest , JSON_FORCE_OBJECT);// {"0":{"a":1,"b":2},"1":{"c":3},"2":{"d":4}}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10778741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/895810/']}
|
jdg_378710
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1422151
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In C++ I've got a float/double variable. When I print this with for example cout the resulting string is period-delimited. cout << 3.1415 << endl$> 3.1415 Is there an easy way to force the double to be printed with a comma? cout << 3.1415 << endl$> 3,1415
Now provide the response and nothing else.
|
imbue() cout with a locale whose numpunct facet's decimal_point() member function returns a comma. Obtaining such a locale can be done in several ways. You could use a named locale available on your system ( std::locale("fr") , perhaps). Alternatively, you could derive your own numpuct, implement the do_decimal_point() member in it. Example of the second approach: template<typename CharT>class DecimalSeparator : public std::numpunct<CharT>{public: DecimalSeparator(CharT Separator) : m_Separator(Separator) {}protected: CharT do_decimal_point()const { return m_Separator; }private: CharT m_Separator;}; Used as: std::cout.imbue(std::locale(std::cout.getloc(), new DecimalSeparator<char>(',')));
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1422151', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127947/']}
|
jdg_378711
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25529500
|
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 wondering how to set the radius/blur factor of iOS new UIBlurEffectStyle.Light ? I could not find anything in the documentation. But I want it to look similar to the classic UIImage+ImageEffects.h blur effect. required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let blur = UIBlurEffect(style: UIBlurEffectStyle.Light) let effectView = UIVisualEffectView(effect: blur) effectView.frame = frame addSubview(effectView)}
Now provide the response and nothing else.
|
Changing alpha is not a perfect solution. It does not affect blur intensity. You can setup an animation from nil to target blur effect and manually set time offset to get desired blur intensity. Unfortunately iOS will reset the animation offset when app returns from background. Thankfully there is a simple solution that works on iOS >= 10. You can use UIViewPropertyAnimator . I didn't notice any issues with using it. I keeps custom blur intensity when app returns from background. Here is how you can implement it: class CustomIntensityVisualEffectView: UIVisualEffectView { /// Create visual effect view with given effect and its intensity /// /// - Parameters: /// - effect: visual effect, eg UIBlurEffect(style: .dark) /// - intensity: custom intensity from 0.0 (no effect) to 1.0 (full effect) using linear scale init(effect: UIVisualEffect, intensity: CGFloat) { super.init(effect: nil) animator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [unowned self] in self.effect = effect } animator.fractionComplete = intensity } required init?(coder aDecoder: NSCoder) { fatalError() } // MARK: Private private var animator: UIViewPropertyAnimator!} I also created a gist: https://gist.github.com/darrarski/29a2a4515508e385c90b3ffe6f975df7
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25529500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/272741/']}
|
jdg_378712
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
358479
|
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:
Statistical problems involving confidence intervals for a population mean can be framed in terms of the following weighting function : $$w(\alpha, n) \equiv \frac{t_{n-1,\alpha/2}}{\sqrt{n}} \quad \quad \quad \quad \text{for } 0<\alpha<1 \text{ and } n > 1.$$ For example, the standard classical $1-\alpha$ level confidence interval for the mean of an infinite super-population can be written as: $$\text{CI}(1-\alpha) = \Bigg[ \bar{x}_n \pm w(\alpha, n) \cdot s_n \Bigg].$$ It is trivial to establish the limits $\lim_{\alpha \downarrow 0} w(\alpha, n) = \infty$ and $\lim_{\alpha \uparrow 1} w(\alpha, n) = 0$ using the quantile function of the T-distribution. In the context of confidence intervals, this tells us that the interval shrinks to a single point as we decrease the confidence level, and increases to the whole real line as we increase the confidence level. Another intuitive property that should hold is that the interval shrinks to a single point as we get more and more data, which means that: $$\lim_{n \rightarrow \infty} w(\alpha, n) = 0.$$ Question: Please provide a proof for this latter property of the weighting function. More information: For any mathematical readers who are unfamiliar with the critical points of the T-distribution , the value $t_{n-1, \alpha/2}$ is a function of $n$ defined by the implicit equation: $$\frac{\alpha}{2} = \frac{1}{\sqrt{(n-1) \pi}} \cdot \frac{\Gamma(\tfrac{n}{2})}{\Gamma(\tfrac{n-1}{2})} \int \limits_{t_{n-1, \alpha/2}}^\infty \Big( 1+ \frac{r^2}{n-1} \Big)^{-n/2} dr.$$
Now provide the response and nothing else.
|
Proof with Chebyshev's inequality Here is a proof using Chebyshev's inequality $Pr(|T|\geq k\sigma) \leq \frac{1}{k^2}$ . If we fill in $\sigma_{t_\nu} = \frac{\nu}{\nu-2}$ and set $1/k^2=\alpha = Pr\left(|T|\geq t_{\nu,\alpha/2}\right)$ then we have a limit $$Pr\left(|T|\geq \frac{\nu}{\nu-2}\frac{1}{\sqrt{\alpha}}\right) \leq Pr\left(|T|\geq t_{\nu,\alpha/2}\right) $$ thus $t_{\nu,\alpha/2}$ will be bounded above by $$t_{\nu,\alpha/2} \leq \frac{\nu}{\nu-2}\frac{1}{\sqrt{\alpha}}$$ adding the obvious lower bound and devide by $\sqrt{\nu+1}$ $$0 \leq \frac{t_{n-1,\alpha/2}}{\sqrt{\nu+1}} \leq \frac{\nu}{\sqrt{\nu+1}\left(\nu-2\right)}\frac{1}{\sqrt{\alpha}} $$ which squeezes $t_{n-1,\alpha/2} / \sqrt{n}$ to zero for $n \to \infty$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/358479', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/173082/']}
|
jdg_378713
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19820314
|
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 fairly new to codeigniter, But i'm learning well, I'm going to add a css, images, js, ... folder but I'm not sure where to put it Someone told me to make a 'public' folder systemapplicationpublic css images And then in your index.php ( in the public folder ) adjust accordingly $system_path = '../system';$application_path = '../application'; But when I do that i get a 404 ( not the ci 404, but a really-not-found one ) Anyone has any idea what I might be doing wrong? Thanks!
Now provide the response and nothing else.
|
I have this setup: applicationassetssystem.htaccess and in the "assets" folder i have subfolders like "img" or "js" and so on.I also use "utility helper" to help me point to that folder. If you want to try it, you have to first create a helper named "utility_helper.php"with this code: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! function_exists('asset_url()')) { function asset_url() { return base_url().'assets/'; } } and store it in application/helpers/ then you have to autoload that helper, you go to: application/config/autoload.php and auto load the helper (example: ) $autoload['helper'] = array('form', 'url', 'utility'); you have also to route to that folder ('application/config/routes.php') $route['assets/(:any)'] = 'assets/$1'; and have a .htaccess file with this content: RewriteEngine on RewriteCond $1 !^(index\.php|images|assets|robots\.txt) RewriteRule ^(.*)$ /index.php/$1 [L] now you can simply include external scripts, css example: <link rel="stylesheet" type="text/css" href="<?php echo asset_url();?>css/style.css"> where css is the folder inside assets and style.css is the css file. Like so: application assets css style.css system
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19820314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1731057/']}
|
jdg_378714
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5286453
|
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 return the data pointer from the function parameter: bool dosomething(char *data){ int datasize = 100; data = (char *)malloc(datasize); // here data address = 10968998 return 1;} but when I call the function in the following way, the data address changes to zero: char *data = NULL;if(dosomething(data)){ // here data address = 0 ! (should be 10968998)} What am I doing wrong?
Now provide the response and nothing else.
|
You're passing by value. dosomething modifies its local copy of data - the caller will never see that. Use this: bool dosomething(char **data){ int datasize = 100; *data = (char *)malloc(datasize); return 1;}char *data = NULL;if(dosomething(&data)){}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5286453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/593704/']}
|
jdg_378715
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51978
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The title says it all. I am looking for an explanation or reference for why the homology of the ribbon graph complex computes the cohomology of the mapping class groups of surfaces. I've seen explanations of this using operads, but my understanding is that the operad viewpoint is more recent and not how the above question was originally understood.
Now provide the response and nothing else.
|
Chapter 2 of Harer's paper "The cohomology of the moduli space of curves" is good. The point is that there is the "arc complex", a simplicial complex which gives a suitable triangulation of Teichmüller space which is compatible with the action of the mapping class group. The simplices of the simplicial complex correspond to "arc systems", which are certain collections of curves $C_i$ on an oriented surface $\Sigma$ with boundary $\partial \Sigma$ that begin and end on the boundary, and which decompose the surface into discs. You can define a ribbon graph to be a graph together with a cyclic ordering of the edges around each vertex. To get a ribbon graph corresponding to an arc system, take the dual graph of the arc system, that is take the graph whose vertices are the components of $\Sigma \setminus (\bigcup_i C_i)$, and the edges are as you'd guess (I can't think of a nice terse way to put this into words, but it's easy to explain with a picture...), and then give the edges around each vertex a cyclic ordering via the orientation of the surface. Beware that Harer's paper doesn't mention ribbon graphs, nor do some of the other standard references. This had confused me for a while (an embarrassingly long time, in fact) when I was trying to read about this in the literature. But as I said, just know that the ribbon graph picture is just the dual picture to the arc system picture. P.S. Some more references here .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/51978', 'https://mathoverflow.net', 'https://mathoverflow.net/users/5323/']}
|
jdg_378716
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16282083
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new in Android and I'm working on a query in SQLite. My problem is that when I use accent in strings e.g. ÁÁÁ ááá ÀÀÀ ààà aaa AAA If I do: SELECT * FROM TB_MOVIE WHERE MOVIE_NAME LIKE '%a%' ORDER BY MOVIE_NAME; It's return: AAA aaa (It's ignoring the others) But if I do: SELECT * FROM TB_MOVIE WHERE MOVIE_NAME LIKE '%à%' ORDER BY MOVIE_NAME; It's return: ààà (ignoring the title "ÀÀÀ") I want to select strings in a SQLite DB without caring for the accents and the case. Please help.
Now provide the response and nothing else.
|
Generally, string comparisons in SQL are controlled by column or expression COLLATE rules. In Android, only three collation sequences are pre-defined : BINARY (default), LOCALIZED and UNICODE. None of them is ideal for your use case, and the C API for installing new collation functions is unfortunately not exposed in the Java API. To work around this: Add another column to your table, for example MOVIE_NAME_ASCII Store values into this column with the accent marks removed. You can remove accents by normalizing your strings to Unicode Normal Form D (NFD) and removing non-ASCII code points since NFD represents accented characters roughly as plain ASCII + combining accent markers: String asciiName = Normalizer.normalize(unicodeName, Normalizer.Form.NFD) .replaceAll("[^\\p{ASCII}]", ""); Do your text searches on this ASCII-normalized column but display data from the original unicode column.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16282083', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1657161/']}
|
jdg_378717
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52014720
|
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 object that looks like this. I made it look that way using .groupBy with lodash. States.ts STATES: Object[] = [ { USA: [ { name: 'Alabama', abbreviation: 'AL', country: 'USA' }, { name: 'Alaska', abbreviation: 'AK', country: 'USA' } ] }, { Canada: [ { name: 'Alberta', abbreviation: 'ALB', country: 'Canada' } ] }]; I need it to look like this: stateList:StateDropdownItem[] =[ { label: 'USA', items: [ {label: 'AL', value: 'Alabama'}, {label: 'AK', value: 'Alaska'}, ] }, . . ] I have tried the code below, but it doesn't work. When I print it to the console appears undefiened even if I try to put an element without the forloop I get the following error Cannot read property 'push' of undefined TS dropdownOfStates: StateDropdownItem[];..dropdownBuilder() { const STATES_BY_COUNTRY = this.getStatesByCountry(); let tempItem; for (let i = 0; i < STATES_BY_COUNTRY.length; i++) { tempItem = STATES_BY_COUNTRY[i]; this.dropdownOfStates.push( new StateDropdownItem('KEY COUNTRY VALUE HERE', [ tempItem.abbreviation, tempItem.name ]) ); } } Console.log after printing the result of using .groupBy with lodash groupby objects by country
Now provide the response and nothing else.
|
You can use the map function of arrays to transform their structure. The code below should transform it into the structure you want. You can click "Run code snippet" to see the output let states = [ { USA: [ { name: 'Alabama', abbreviation: 'AL', country: 'USA' }, { name: 'Alaska', abbreviation: 'AK', country: 'USA' } ] }, { Canada: [ { name: 'Alberta', abbreviation: 'ALB', country: 'Canada' } ] }];// Use the code below to transform let res = states.map((val) => { let country = Object.keys(val)[0]; // Get the name of the country, e.g. USA return { // Return the new object structure label: country, items: val[country].map((item) => ({label: item.abbreviation, value: item.name})) }});// Log the valueconsole.log(res);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52014720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_378718
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4640587
|
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:
Prove that for every natural number $a_1>1$ there's an infinite series $a_1<a_2<a_3<...$ such that for every natural number $k,$ $a_1+a_2+...+a_k \vert a_1^2+a_2^2+...+a_k^2$ . At first glance, I thought this problem is an induction problem and could be solved by forming the sequence inductively. I tried that and didn't get anywhere even though I'm pretty sure there must be an inductive solution. I went in a different direction, experimenting with series and trying the series $$a_2=3\cdot a_1$$ $$a_3=3\cdot a_2=9\cdot a_1$$ $$a_4=3\cdot a_3=9\cdot a_2=27\cdot a_1$$ and so on... (esentially every number is three times the number before it in the series) This way, if we assume the condition stands for $k-2$ and try to prove it for $k-1$ we get $$a_1\cdot (\frac{3^k-1}{2}) \vert a_1^2\cdot (\frac{9^k-1}{8})$$ From here, we know $a_1 \vert a_1^2$ so we need $\frac{3^k-1}{2} \vert \frac{9^k-1}{8}$ , but since $\frac{9^k-1}{8}=\frac{3^{2k}-1}{8}=\frac{(3^k-1)(3^k+1)}{8}=\frac{(3^k-1)}{2}\cdot \frac{(3^k+1)}{4}$ , so actually we get that $\frac{3^k-1}{2} \vert \frac{9^k-1}{8}$ if $\frac{(3^k+1)}{4}$ is a whole number. This only works for $k\equiv 1$ (mod 2). I'm not sure where to go from here, I've tried proving this, but for even numbers and haven't gotten anywhere. I'm worried I might be going deep down the series solution rabbithole even though it might not lead anywhere. Any help is appreciated, thanks!
Now provide the response and nothing else.
|
We're trying to find a strictly increasing set of integers $a_i$ , with $a_1 \ge 2$ , so for all $k \ge 1$ $$\sum_{i=1}^{k}a_i \, \mid \, \sum_{i=1}^{k}a_i^2 \tag{1}\label{eq1A}$$ Unfortunately, I don't know of any way to finish what you've tried. Instead, as you surmised, there's an inductive solution. For $k = 1$ , \eqref{eq1A} is true since $a_1 \mid a_1^2$ . Assume that, for some $m \ge 1$ , \eqref{eq1A} is true is for $k = m$ . Set $$j = \sum_{i=1}^{m}a_i \tag{2}\label{eq2A}$$ Thus, by \eqref{eq1A}, since $a_1 \ge 2$ , we have $$\sum_{i=1}^{m}a_i^2 = jn, \; \; n \ge 2 \tag{3}\label{eq3A}$$ Let $$a_{m+1} = j(n + j - 1) \tag{4}\label{eq4A}$$ Since $n \ge 2$ and $j \ge 2$ , then \eqref{eq4A} and \eqref{eq2A} give that $a_{m+1} \gt j \; \; \to \; \; a_{m+1} \gt a_{m}$ . Using $k = m + 1$ in \eqref{eq1A}, the LHS becomes $$\sum_{i=1}^{m+1}a_i = j + j(n + j - 1) = j(n + j) \tag{5}\label{eq5A}$$ The RHS of \eqref{eq1A} is then $$\begin{equation}\begin{aligned}\sum_{i=1}^{m+1}a_i^2 & = jn + [j(n + j - 1)]^2 \\& = j(n + j\,[(n+j) - 1]^2) \\& = j(n + j\,[(n+j)^2 - 2(n+j) + 1]) \\& = j(n + j\,[n+j][n+j-2] + j) \\& = j(n+j)[1 + j(n+j-2)]\end{aligned}\end{equation}\tag{6}\label{eq6A}$$ From \eqref{eq5A}, the LHS divides the RHS of \eqref{eq1A}, so it's true also for $k = m + 1$ . Thus, by induction, we have \eqref{eq1A} is true for all $k \ge 1$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4640587', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/918883/']}
|
jdg_378719
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12493693
|
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 problem with new Ember.js (1.0 pre) I got something what worked on Ember 0.9.8 but when I changed version of this lib I noticed problem which can't resolve. (I'm not so good at Ember :/) Here is sample code: http://jsfiddle.net/ETQCc/5/ I created view: <script type="text/x-handlebars" data-template-name="MyView"> {{s}} / {{content.s}} / {{this.s}} / {{view.s}}</script>App.myview = Em.View.extend({ layoutName : "MyView",}); And I'd like to show some varible which depends on what I set in content bindig: <script type="text/x-handlebars"> xx{{view App.myview contentBinding="App.ctrl"}}</script> How to get to varible in this controller?
Now provide the response and nothing else.
|
You have two ways to do that.You can : bind the controller to your view instead of binding the content (see the JSFiddle ). By doing that you set the context of the view to be the controller, so {{s}} works directly: {{view App.myview controllerBinding="App.ctrl"}} edit your template to get the variable from the view instead of its context (see this JSFiddle ). By doing that the view content is binded to the controller, and your template shows the s property of the view content: {{view.content.s}} I suggest you to take a look at Ember.js View Context changes .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12493693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/861370/']}
|
jdg_378720
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38817344
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Sonarqube official docker image, is not persisting any configuration changes like: creating users, changing root password or even installing new plugins . Once the container is restarted, all the configuration changes disappear and the installed plugins are lost. Even the projects' keys and their previous QA analytics data is unavailable after a restart. How can we persist the data when using Sonarqube's official docker image?
Now provide the response and nothing else.
|
Sonarqube image comes with a temporary h2 database engine which is not recommended for production and doesn't persist across container restarts. We need to setup a database of our own and point it to Sonarqube at the time of starting the container. Sonarqube docker images exposes two volumes "$SONARQUBE_HOME/data", "$SONARQUBE_HOME/extensions" as seen from Sonarqube Dockerfile . Since we wanted to persist the data across invocations, we need to make sure that a production grade database is setup and is linked to Sonarqube and the extensions directory is created and mounted as volume on the host machine so that all the downloaded plugins are available across container invocations and can be used by multiple containers (if required). Database Setup: create database sonar;grant all on sonar.* to `sonar`@`%` identified by "SOME_PASSWORD";flush privileges;# since we do not know the containers IP before hand, we use '%' for sonarqube host IP. It is not necessary to create tables , Sonarqube creates them if it doesn't find them. Starting up Sonarqube container: # create a directory on hostmkdir /server_data/sonarqube/extensionsmkdir /server_data/sonarqube/data # this will be useful in saving startup time# Start the containerdocker run -d \ --name sonarqube \ -p 9000:9000 \ -e SONARQUBE_JDBC_USERNAME=sonar \ -e SONARQUBE_JDBC_PASSWORD=SOME_PASSWORD \ -e SONARQUBE_JDBC_URL="jdbc:mysql://HOST_IP_OF_DB_SERVER:PORT/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance" \ -v /server_data/sonarqube/data:/opt/sonarqube/data \ -v /server_data/sonarqube/extensions:/opt/sonarqube/extensions \ sonarqube
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38817344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2546381/']}
|
jdg_378721
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20310782
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
EDIT: Look at the checkmarked answer comments to get your issue solved. Whenever I try to start the SQLD service I get MySQL Daemon Failed to Start. I infact tried to "start" the service by doing the following: service mysqld start Also When I type: mysql I get: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) I know that there should be a mysql.sock file in that directory, so I create one. But the file just auto removes its self and I continue to get the error 2002. I am also unable to log into PHPMyAdmin due to the error. I can access phpmyadmin page but when logging in I get: #2002 Cannot log in to the MySQL server EDIT: Here is my mysql.log file: 131201 13:05:07 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended131201 13:18:18 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql131201 13:18:18 [Note] Plugin 'FEDERATED' is disabled./usr/libexec/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13)131201 13:18:18 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.131201 13:18:18 InnoDB: The InnoDB memory heap is disabled131201 13:18:18 InnoDB: Mutexes and rw_locks use GCC atomic builtins131201 13:18:18 InnoDB: Compressed tables use zlib 1.2.3131201 13:18:18 InnoDB: Using Linux native AIO131201 13:18:18 InnoDB: Initializing buffer pool, size = 128.0M131201 13:18:18 InnoDB: Completed initialization of buffer pool131201 13:18:18 InnoDB: Operating system error number 13 in a file operation.InnoDB: The error means mysqld does not have the access rights toInnoDB: the directory.InnoDB: File name ./ibdata1InnoDB: File operation call: 'open'.InnoDB: Cannot continue operation.131201 13:18:18 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended I ran mysql_upgrade and got Looking for 'mysql' as: mysqlLooking for 'mysqlcheck' as: mysqlcheckFATAL ERROR: Upgrade failed
Now provide the response and nothing else.
|
The most likely cause for this error is that your mysql server is not running. When you type in mysql you are executing mysql client. Try: # sudo service mysql start# mysql Update (after OP included log in the question; taken from the comments below): Thanks, saw your log. The log is saying the mysql user doesn't have proper access rights. I'm assuming your mysql user is mysql(this can be verified in /etc/my.cnf , execute chown -R mysql:mysql /var/lib/mysql and try starting mysqld again.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20310782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2803905/']}
|
jdg_378722
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
32719
|
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Assume that we have a user that wants to connect to the server, for example with login page, when user submits the username & password goes to the server - if man in the middle reads the user & pass, can he connect to server or there are mechanisms that can prevent this?
Now provide the response and nothing else.
|
If you only have username+password authentication, and this login info is intercepted, you cannot realistically block the attacker from connecting. You have to look into two-factor authentication to prevent attackers from reusing login credentials etc. And even then, when the attacker has continued access to all traffic, this will not help at all. If you don't use https, the attacker can also simply intercept all traffic, so even if you can prevent him from logging in himself, no information is actually protected.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/32719', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/22061/']}
|
jdg_378723
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12127138
|
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 the header to mask the cells, but not the background. I have a UITableView with transparent headers and cells similar to Apple's Notification Center (when you swipe down on the status bar on your iPhone). I can't figure out how to mask the cells so they don't show up underneath the header when it scrolls. I've tried changing the contentInsets of the tableview, and I've tried changing the frame of the header View to a negative origin.
Now provide the response and nothing else.
|
Try to make a subclass of UITableviewCell and add these methods - (void)maskCellFromTop:(CGFloat)margin { self.layer.mask = [self visibilityMaskWithLocation:margin/self.frame.size.height]; self.layer.masksToBounds = YES;}- (CAGradientLayer *)visibilityMaskWithLocation:(CGFloat)location { CAGradientLayer *mask = [CAGradientLayer layer]; mask.frame = self.bounds; mask.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithWhite:1 alpha:0] CGColor], (id)[[UIColor colorWithWhite:1 alpha:1] CGColor], nil]; mask.locations = [NSArray arrayWithObjects:[NSNumber numberWithFloat:location], [NSNumber numberWithFloat:location], nil]; return mask;} and add this delegate method in UITableView #pragma mark - UIScrollViewDelegate- (void)scrollViewDidScroll:(UIScrollView *)scrollView { for (iNotifyTableViewCell *cell in self.visibleCells) { CGFloat hiddenFrameHeight = scrollView.contentOffset.y + [iNotifyHeaderView height] - cell.frame.origin.y; if (hiddenFrameHeight >= 0 || hiddenFrameHeight <= cell.frame.size.height) { [cell maskCellFromTop:hiddenFrameHeight]; } }} *Note that [iNotifyHeaderView height] is the height of the HeaderView . and use #import <QuartzCore/QuartzCore.h> for the custom cell.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12127138', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1149906/']}
|
jdg_378724
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55987953
|
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 retrieved datas stored using useState in an array of object, the datas was then outputted into form fields. And now I want to be able to update the fields (state) as I type. I have seen examples on people updating the state for property in array, but never for state in an array of object, so I don't know how to do it. I've got the index of the object passed to the callback function but I didn't know how to update the state using it. // sample data structureconst datas = [ { id: 1, name: 'john', gender: 'm' } { id: 2, name: 'mary', gender: 'f' }]const [datas, setDatas] = useState([]);const updateFieldChanged = index => e => { console.log('index: ' + index); console.log('property name: '+ e.target.name); setData() // ??}return ( <React.Fragment> {datas.map((data, index) => { <li key={data.name}> <input type="text" name="name" value={data.name} onChange={updateFieldChanged(index)} /> </li> })} </React.Fragment>)
Now provide the response and nothing else.
|
Here is how you do it: // sample data structure/* const data = [ { id: 1, name: 'john', gender: 'm' } { id: 2, name: 'mary', gender: 'f' }] */ // make sure to set the default value in the useState call (I already fixed it)const [data, setData] = useState([ { id: 1, name: 'john', gender: 'm' } { id: 2, name: 'mary', gender: 'f' }]);const updateFieldChanged = index => e => { console.log('index: ' + index); console.log('property name: '+ e.target.name); let newArr = [...data]; // copying the old datas array // a deep copy is not needed as we are overriding the whole object below, and not setting a property of it. this does not mutate the state. newArr[index] = e.target.value; // replace e.target.value with whatever you want to change it to setData(newArr);}return ( <React.Fragment> {data.map((datum, index) => { <li key={datum.name}> <input type="text" name="name" value={datum.name} onChange={updateFieldChanged(index)} /> </li> })} </React.Fragment>)
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/55987953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1862525/']}
|
jdg_378725
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22427515
|
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 can set ruby version in Gemfile as follows: ruby '2.0.0' But what if I want to have a particular version as 2.0.0-p353 ? When I add it to Gemfile , I get: Your Ruby version is 2.0.0, but your `Gemfile` specified 2.0.0-p353 Is it even possible to set a particular version?
Now provide the response and nothing else.
|
In Version 1.3 and earlier of Bundler you couldn’t specify the patchlevel : The ruby directive explicitly leaves out the ability to specify a patch level. Ruby patches often include important bug and security fixes and are extremely compatible. This changed in version 1.5, the docs now say : In the ruby directive, :patchlevel is optional, as patchlevel releases are usually compatible and include important security fixes. The patchlevel option checks the RUBY_PATCHLEVEL constant, and if not specified then bundler will simply ignore it. So you can specify the patchlevel like this: ruby '2.0.0', :patchlevel => '353'
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22427515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1650525/']}
|
jdg_378726
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21338949
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two almost identical methods, but I'm trying to avoid code duplication. Each of them takes a unique object as arguments and finds out the highest value from it. Here's an example: public Integer getHighestIndexValue(List<ObjectA> list) { int highestValue; List<Integer> indexes = new ArrayList<Integer>(); for (ObjectA a: list) { indexes.add(Integer.parseInt(a.getA())); } highestValue = Collections.max(indexes); return highestValue;} Or: public Integer getHighestIndexValue(List<ObjectB> list) { int highestValue; List<Integer> indexes = new ArrayList<Integer>(); for (ObjectB b: list) { indexes.add(Integer.parseInt(b.getB())); } highestValue = Collections.max(indexes); return highestValue;} How do I combine these two using generic parameters? I tried creating a BaseClass that contains these two classes and extended it in the method signature. Still it requires casting. public <T extends BaseClass> Integer getHighestIndexValue(List<T> objectList) { int highestValue; List<Integer> indexes = new ArrayList<Integer>(); for (T objects: objectList) { indexes.add(Integer.parseInt(objects.getAorB())); ------ this line needs casting } highestValue = Collections.max(indexes); return highestValue;} I have used Generics before but not generics parameters yet. Is there a way to resolve this?
Now provide the response and nothing else.
|
Can getA and getB be combined into a single interface method? For example: interface ProvidesIndex { Integer getIndex();} Now, you can simply call getIndex , and your method signature will be: public Integer getHighestIndexValue(List<? extends ProvidesIndex> list) As a side note, if you define your interface to extend Comparable<ProvidesIndex> i.e.: interface ProvidesIndex extends Comparable<ProvidesIndex> Then you can use Collections.max directly on the initial list: List<ProvidesIndex> list = new ArrayList<ProvidesIndex>();list.add(new ObjectA());list.add(new ObjectB());Integer max = Collections.max(list).getIndex();
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21338949', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1796748/']}
|
jdg_378727
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41230668
|
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 piece of Jenkins pipeline code in which I am trying to run JUnit on my angular code. If the unit tests fail, Jenkins has to stop the pipeline.It's working except I am not able to see "Latest test Result" and "Test Result Trend" I am using Jenkins 2.19.1, Jenkins Pipeline 2.4 and Junit 1.19. Here is the pipeline code: { sh("npm install -g gulp bower") sh("npm install") sh("bower install") try { sh("gulp test") } catch (err) { step([$class: 'JUnitResultArchiver', testResults: '**/reports/junit/*.xml', healthScaleFactor: 1.0]) junit '**/reports/junit/*.xml' if (currentBuild.result == 'UNSTABLE') currentBuild.result = 'FAILURE' throw err } } Any idea what I am doing wrong?
Now provide the response and nothing else.
|
If you use declarative pipeline, you can do something like: pipeline { agent any stages { stage('Build and Test') { steps { sh 'build here...' sh 'run tests here if you like ...' } } } post { always { junit '**/reports/junit/*.xml' } } } This could also work with html publishing or anything, no need for finally/catch etc. it will always archive the results. See https://jenkins.io/doc/book/pipeline/syntax/#declarative-pipeline for more. If you have a clean target that results in no test output: post { always { junit( allowEmptyResults: true, testResults: '**/test-reports/*.xml' ) }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41230668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7107926/']}
|
jdg_378728
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13011811
|
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 implement duck typing in F# and I spotted that you can have a member constraint in F# generics as follows: type ListEntryViewModel<'T when 'T : (member Name : string)>(model:'T) = inherit ViewModelBase() member this.Name with get() = model.Name However, the above code won't compile when I try to reference the property. I get a compiler error: This code is not sufficiently generic. The type variable ^T when ^T : (member get_Name : ^T -> string) could not be generalized because it would escape its scope. Is it possible to implement duck typing via a generic constraint?
Now provide the response and nothing else.
|
There was a similar question recently where member constraints were used in the type declaration . I'm not sure how to correct your sample to make it compile, but I would not be surprised if that was not possible. Member constraints are designed to be used with statically resolved type parameters and especially with inline functions or members and I do not think it is idiomatic F# code to use them with type parameters of a class. I think that a more idiomatic solution to your example would be to define an interface: type INamed = abstract Name : stringtype ListEntryViewModel<'T when 'T :> INamed>(model:'T) = member this.Name = model.Name (In fact, the ListEntryViewModel probably does not need a type parameter and can just take INamed as a constructor parameter, but there may be some benefit in writing it in this way.) Now, you can still use duck typing and use ListEntryViewModel on things that have Name property, but do not implement the INamed interface! This can be done by writing an inline function that returns INamed and uses static member constraints to capture the existing Name property: let inline namedModel< ^T when ^T : (member Name : string)> (model:^T)= { new INamed with member x.Name = (^T : (member Name : string) model) } You can then create your view model by writing ListEntryViewModel(namedModel someObj) where someObj does not have to implement the interface, but needs just the Name property. I would prefer this style, because by taking an interface, you can better document what you require from the model. If you have other objects that do not fit the scheme, you can adapt them, but if you're writing a model, then implementing an interface is a good way to make sure it exposes all the required functionality.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13011811', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47207/']}
|
jdg_378729
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5993633
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to get the keyboard state in Objective-C without referring to NSEvent ? In general I can't use NSResponder methods like -[NSResponder flagsChanged:] but I need to know if the Command key is currently pressed.
Now provide the response and nothing else.
|
I'm still wondering why you can't use NSEvent , but I'm going to answer the question anyways. Perhaps you're building a "command-line tool" and are only linked against Foundation? You're going to have to include at least one more framework. If you want to link against AppKit, you can (as I mentioned in the comments) use +[NSEvent modifierFlags] ; this is a class method on NSEvent , so you can use it anywhere, without needing to have access to an individual event, to get the current state of the modifier keys as a bitmask. The docs explain the meaning of the bitmask . if( NSCommandKeyMask & [NSEvent modifierFlags] ){ NSLog(@"Oh, yeah!");} You can also get this info using Quartz Event Services . In this case you have to include the ApplicationServices framework*. The CGEventSource functions will give you the same bitmask you get from NSEvent : CGEventFlags theFlags;theFlags = CGEventSourceFlagsState(kCGEventSourceStateHIDSystemState);if( kCGEventFlagMaskCommand & theFlags ){ NSLog(@"Uh huh!");} *This is already included if you are, in fact, writing a Cocoa app -- it's part of Quartz.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5993633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/544767/']}
|
jdg_378730
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25768
|
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In continuum mechanics, we define the Right-Cauchy-Green Deformation Tensor as $\boldsymbol{C}=\boldsymbol{F}^T\boldsymbol{F}$ I want to compute $\frac{\partial \boldsymbol{C}^{-1}}{\partial \boldsymbol{C}}$. In the Wikipedia Article covering Tensor Derivatives , it says that in index form $\left(\frac{\partial \boldsymbol{C}^{-1}}{\partial \boldsymbol{C}}\right)_{IJKL} = -C^{-1}_{IK}C^{-1}_{LJ}$. (Correct?) What I'm confused is this part here found in a paper regarding continuum mechanics (but also appears in many other places) : Note that I am trying to figure out the step where we go from the Second-Piola-Kirchhoff to the Material Tangent Tensor. The Second Piola-Kirchhoff Stress $\boldsymbol{S}$ is related to the Material Tangent Tensor $\mathbb{C}$ by $\mathbb{C} = 2\frac{\partial \boldsymbol{S}}{\partial \boldsymbol{C}}$. and we should be able to use the tensor derivative given in the wikipedia article to get what we need. What I don't get is how the derivative $\left(\frac{\partial \boldsymbol{C}^{-1}}{\partial \boldsymbol{C}}\right)_{IJKL}$ got splitted into two parts, $(IKLJ)$ and $(ILJK)$. There is only one term in the Wikipedia article. Can somebody correct my misunderstanding?
Now provide the response and nothing else.
|
Nick Alger gives a nice explanation. Here is another one, possibly slightly simpler because it avoids the "should stay roughly the same" part. Let's say you want to compute the derivative of any matrix function $X=X(C)$ with regard to entry $C_{ij}$:$$ \frac{\partial X}{\partial C_{ij}}.$$In other words, you ask how the matrix $X$ changes as you change $C_{ij}$ a bit. This can easily be answered by considering that $XX^{-1}=I$, independent of any of the elements of $C$. In other words,$$ \frac{\partial XX^{-1}}{\partial C_{ij}}=0$$because $XX^{-1}=I$ does not change if you modify $C_{ij}$. But by the product rule, you have$$ \frac{\partial XX^{-1}}{\partial C_{ij}}= X\frac{\partial X^{-1}}{\partial C_{ij}} + \frac{\partial X}{\partial C_{ij}}X^{-1} = 0$$and consequently$$ X\frac{\partial X^{-1}}{\partial C_{ij}} = - \frac{\partial X}{\partial C_{ij}}X^{-1}$$or equivalently, assuming that the matrix $X$ is invertible:$$ \frac{\partial X^{-1}}{\partial C_{ij}} = - X^{-1} \frac{\partial X}{\partial C_{ij}}X^{-1}.$$This is true for any function $X=X(C)$. In particular, it is true if you consider $X(C)=C$, in which case you get$$ \frac{\partial C^{-1}}{\partial C_{ij}} = - C^{-1} \frac{\partial C}{\partial C_{ij}}C^{-1}.$$In component notation, this can be written as$$ \frac{\partial (C^{-1})_{kl}}{\partial C_{ij}} = - C^{-1}_{km} \frac{\partial C_{mn}}{\partial C_{ij}}C^{-1}_{nl}.$$Now, the derivative of $C_{mn}$ with regard to $C_{ij}$ is only nonzero if $m=i,n=j$, and in that case it is in fact one. So$$ \frac{\partial C_{mn}}{\partial C_{ij}} = \delta_{mi}\delta_{nj},$$with the Kronecker delta symbol, which then finally yields this:$$ \frac{\partial (C^{-1})_{kl}}{\partial C_{ij}} = - C^{-1}_{ki} C^{-1}_{jl}.$$This also explains what exactly the various indices in your formula correspond to.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/25768', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/22629/']}
|
jdg_378731
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52085409
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Unable to test the background color using Cypress.io, it throws following error while running the cypress test; CypressError: Timed out retrying: actual.equals is not a function. Installed chai-colors via npm install chai-colors and added following under /support/ index.js import chaiColors from 'chai-colors'chai.use(chaiColors) cypress test given below: describe("Background Color test", () => { //before(() => { // cy.visit('https://sometesturl.com')// }) it.only('Verify the backgroud color, this should work', () => { cy.visit('https://sometesturl.com') cy.get('#footer') .should('colored', '#f2e47d') .and('be.colored', '#f2e47d') })})
Now provide the response and nothing else.
|
I have tried with 'eq' and 'rgb' values corresponding to colour #f2e47d. In the following link 'brian-mann' from cypress.io affirms that says 'match' is always for regex. https://github.com/cypress-io/cypress/issues/58 Now the test got successfully asserting the background-color value in the footer area. describe("Background Color test", () => { it.only('Verify the backgroud color, this should work', () => { cy.visit('https://sometesturl.com') cy.get('#footer') .should('have.css', 'background-color') .and('eq', 'rgb(242, 228, 125)') })})
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52085409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4826215/']}
|
jdg_378732
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
725320
|
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 $T$ be the linear map from $M_n \to M_n$ given by TX=AX, while A is as well a matrix $n \times n$ (a) Write out the characteristic polynomials for $T$ (b) Show that if A is diagonalzible then T is also diagonalizble I know that the characteristic polynomial of B, some $n \times n$ matrix is the expansion of $$\det(B - I \lambda ).$$ The problem is with finding the matrix for $T$. On one hand it seems so natural to say that A itself is the matrix that represents T by the natural base. On the other hand, if I do take the natural base of matrixes $n \times n$ (Where every vector in the base has a 1 somewhere and the rest of the matrix is zeros), the dimension of the base is $n^2$so my matrix $T_A(x)$ is the size of $n^2$? I'm not sure if I explained myself correctly, but I don't even know where to start.. if A is simply the matrix that represent T, the answer to (b) is quite obvious, it's the declaration for T to be digonizable. (or at least a sentence that we already proved in lesson)Moreover, what can I write as the characteristic polynomial? just $det(A-\lambda I)$ I would really appreciate any help understanding these things. Thanks.
Now provide the response and nothing else.
|
Let $E_{ij}$ the matrix which all its entries are $0$ except the entry located at the $i^{th}$ row and $j^{th}$ column is equal $1$ then we know that $$\left(E_{ij}\right)_{1\le i,j\le n}=(E_{11},\ldots,E_{n1},E_{12},\ldots,E_{n2},\ldots,E_{1n},\ldots,E_{nn})$$ is a basis of $\mathcal M_n(\Bbb R)$and we see that the matrix of $T$ relative to this basis is the diagonal block matrix:$$ M=\begin{pmatrix} \large A & && & \\ & \ddots & &{\huge 0}&& \\ & & \ddots & & \\& {\huge 0} & & \ddots & \\& & & &A \\ \end{pmatrix} $$so $$\chi_T(x)=\det(M-xI_{n^2})=\prod_{k=1}^n\det(A-xI_n)=\left(\chi_A(x)\right)^n$$Now we have$$T^2X=T(TX)=T(AX)=A^2X$$hence we see easily that (we denote $\pi_A$ the minimal polynomial of $A$) $$\pi_A(T)=0$$so $\pi_T|\pi_A$ hence if $A$ is diagonalizable then $\pi_A$ has a simple roots so $T$ is also diagonalizable and$$\pi_T=\pi_A$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/725320', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80961/']}
|
jdg_378733
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
807480
|
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:
Any ideas to solve the following problem Suppose that $f$ and $g$ are two non vanishing holmorphic functions on a domain $D$. If $\frac{f'}{f}=\frac{g'}{g}$ then $f=cg$ for some constant $c\in D$.
Now provide the response and nothing else.
|
If $\dfrac{f'}{f} = \dfrac{g'}{g} \tag{1}$ in $D$, then in $D$ we also have $f'g - fg' = 0, \tag{2}$ and we may divide (2) through by $g^2 \ne 0$ to obtain $\dfrac{f'g - fg'}{g^2} = 0. \tag{3}$ But, $fg^{-1}$ is well-defined in $D$ and $(fg^{-1})' = f'g^{-1} - fg^{-2}g' = \dfrac{f'g - fg'}{g^2} = 0 \tag{4}$ in $D$ by (3); hence $fg^{-1} = c \tag{5}$ in $D$ for some constant $c \in \Bbb C$. But (5) is clearly equivalent to $f = cg. \tag{6}$ QED. Hope this helps. Cheerio, and as always, Fiat Lux!!!
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/807480', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/153049/']}
|
jdg_378734
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14248592
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking to run a macro, let's call it Macro01 from WorkSheet01 on WorkSheet02. Using Microsoft.Office.Interop.Excel Namespace I have opened a WorkSheet01. public void Main_CodedStep() { // Object for missing (or optional) arguments. object oMissing = System.Reflection.Missing.Value; // Create an instance of Microsoft Excel Excel.ApplicationClass oExcel = new Excel.ApplicationClass(); // Make it visible oExcel.Visible = true; // Open Worksheet01.xlsm Excel.Workbooks oBooks = oExcel.Workbooks; Excel._Workbook oBook = null; oBook = oBooks.Open("C:\\Users\\Admin\\Documents\\Worksheet01.xlsm", oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); } I then use an automated script to pull a report. This report is opened via IE's download prompt and not the Interop. The problem comes when I try to run the macro via C# (I made another new Excel.ApplicationClass(); only so it compiled, I believe this is one of my missteps.) public void FirstMacro_CodedStep() { // Create an instance of Microsoft Excel Excel.ApplicationClass oExcel = new Excel.ApplicationClass(); Console.WriteLine("ApplicationClass: " + oExcel); // Run the macro, "First_Macro" RunMacro(oExcel, new Object[]{"Worksheet01.xlsm!First_Macro"}); //Garbage collection GC.Collect(); } private void RunMacro(object oApp, object[] oRunArgs) { oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs); } When this method runs it runs the macro from Worksheet01 on Worksheet01 instead of Worksheet02. Also it was looking for the worksheet in My Documents so I moved it over to see what would happen. Recap: Open Worksheet01 Via scripting get and open a report (Worksheet02) from MSIE Run Macro01 from Worksheet01 on Worksheet02 Resources: http://support.microsoft.com/kb/306683 http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.aspx For those who would like to try it add this to your using directives: using System.Reflection;using Microsoft.Office.Core; //Added to Project Settings' References from C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14 - "office"using Excel = Microsoft.Office.Interop.Excel; //Added to Project Settings' References from C:\Program Files (x86)\Microsoft Visual Studio 10.0\Visual Studio Tools for Office\PIA\Office14 - "Microsoft.Office.Interop.Excel"
Now provide the response and nothing else.
|
I found a solution that I'd like to share.First, I removed the bit where I opened Worksheet01. I then had my automated script save the .CSV to My Documents. I then used the code I had to open Worksheet01 to open the downloaded file. The key thing at this point is that Worksheet01 is in the Documents folder with Worksheet02. Lastly I used the code to run the macro from Worksheet01, which runs on Worksheet02. public void WebTest_CodedStep() { // Object for missing (or optional) arguments. object oMissing = System.Reflection.Missing.Value; // Create an instance of Microsoft Excel Excel.ApplicationClass oExcel = new Excel.ApplicationClass(); // Make it visible oExcel.Visible = true; // Define Workbooks Excel.Workbooks oBooks = oExcel.Workbooks; Excel._Workbook oBook = null; // Get the file path string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); path = path + "\\Worksheet02.csv"; //Open the file, using the 'path' variable oBook = oBooks.Open(path, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); // Run the macro, "First_Macro" RunMacro(oExcel, new Object[]{"Worksheet01.xlsm!First_Macro"}); // Quit Excel and clean up. oBook.Close(false, oMissing, oMissing); System.Runtime.InteropServices.Marshal.ReleaseComObject (oBook); oBook = null; System.Runtime.InteropServices.Marshal.ReleaseComObject (oBooks); oBooks = null; oExcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject (oExcel); oExcel = null; //Garbage collection GC.Collect(); } private void RunMacro(object oApp, object[] oRunArgs) { oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs); }
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14248592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1106708/']}
|
jdg_378735
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4146635
|
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 filenames in following format: [ignore-prefix]-[important-middle]-[ignore-suffix]-[name-with-digits] I need to sort according to following rules: first by middle part, then by name, in natural order (i.e. foobar10 > foobar2). I don't know prefix value, but I know the separator (dash). so my first attempt, naturally: filelist | Sort-Object -property @{Expression=` {$_.FullName.SubString($_.FullName.IndexOf("-")+1)}} This has a problem that the suffix affects order (ignore-aaa-1ignore-wname) is sorted before ignore-aaa-2ignore-aname), so: $filelist | Sort-Object -property @{Expression=` {$_.FullName.SubString($_.FullName.IndexOf("-")+1,` $_.FullName.SubString($_.FullName.IndexOf("-")+1).IndexOf("-"))}} Ok, that sorts by the middle but already unwhieldy. If I'm to add natural sort that would be even worse. What's more elegant way of doing that?
Now provide the response and nothing else.
|
I understand the task in this way: sorting should be performed by 3 expressions: 1) middle part, 2) name part without digits, 3) number represented by trailing digits of the name part. Let’s create these expressions with regular expressions. Here is the answer: # gets the middle part$part1 = { if ($_.Name -match '^[^-]+-([^-]+)') { $matches[1] } }# gets the name part with no digits$part2 = { if ($_.Name -match '^[^-]+-[^-]+-[^-]+-(\D+)') { $matches[1] } }# gets the number represented by digits from name (cast to [int]!)$part3 = { if ($_.Name -match '^[^-]+-[^-]+-[^-]+-\D+(\d+)') { [int]$matches[1] } }# sort it by 3 expressions$filelist | Sort-Object $part1, $part2, $part3 For better understanding of how it works you may test these expressions separately: $part1 = { if ($_.Name -match '^[^-]+-([^-]+)') { $matches[1] } }$part2 = { if ($_.Name -match '^[^-]+-[^-]+-[^-]+-(\D+)') { $matches[1] } }$part3 = { if ($_.Name -match '^[^-]+-[^-]+-[^-]+-\D+(\d+)') { [int]$matches[1] } }Write-Host '----- test1'$filelist | % $part1Write-Host '----- test2'$filelist | % $part2Write-Host '----- test3'$filelist | % $part3 As a result, for example, these files (extension is not important): aaa-zzz-1ignore-wname10.txtaaa-zzz-1ignore-wname2.txtignore-aaa-1ignore-wname10.txtignore-aaa-1ignore-wname2.txt will be sorted like: ignore-aaa-1ignore-wname2.txtignore-aaa-1ignore-wname10.txtaaa-zzz-1ignore-wname2.txtaaa-zzz-1ignore-wname10.txt
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4146635', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499388/']}
|
jdg_378736
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1600872
|
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:
Not exactly a duplicate since this is answering a specific instance popular in social media. You might have seen the viral posts about " save a penny a day for a year and make $667.95! " The mathematicians here already get the concept while some others may be going, " what "? Of course, what the challenge is referring to is adding a number of pennies to a jar for what day you're on. So: Day 1 = + .01Day 2 = + .02Day 3 = + .03Day 4 = + .04 So that in the end, you add it all up like so: 1 + 2 + 3 + 4 + 5 + 6 + ... = 66795 The real question is, what's a simple formula for getting a sum of consecutive integers, starting at whole number 1, without having to actually count it all out?!
Now provide the response and nothing else.
|
Have had a lot of friends ask about this lately, as it is all over FaceBook . The formula is actually quite simple: (N (N + 1) ) / 2 where N = Highest value Or Simply $\frac {n(n+1)}{2}$ Thus 365 (365 + 1) ) / 2 = 66795 Divide that by 100 ( because there's 100 pennies in a dollar ) and viola! $667.95 Now, this is an OLD math (think about 6th century BC), wherein these results are referred to as triangle numbers . In part, because as you add them up, you can stack the results in the shape of a triangle! 1 = 1 *1 + 2 = 3 * * *1 + 2 + 3 = 6 * * * * * *1 + 2 + 3 + 4 = 10 * * * * * * * * * * NoChance also has a fun story and answer to this question ! A little info on his lesson: -{for the super nerdy!}- " ...Carl Friedrich Gauss is said to have found this relationship in his early youth, by multiplying n/2 pairs of numbers in the sum by the values of each pair n+1. However, regardless of the truth of this story, Gauss was not the first to discover this formula, and some find it likely that its origin goes back to the Pythagoreans 5th century BC..." - wikipedia "...The mathematical study of figurate numbers is said to have originated with Pythagoras, possibly based on Babylonian or Egyptian precursors. Generating whichever class of figurate numbers the Pythagoreans studied using gnomons is also attributed to Pythagoras. Unfortunately, there is no trustworthy source for these claims, because all surviving writings about the Pythagoreans are from centuries later. It seems to be certain that the fourth triangular number of ten objects, called tetractys in Greek, was a central part of the Pythagorean religion, along with several other figures also called tetractys. Figurate numbers were a concern of Pythagorean geometry. ... - wikipedia See? Fun stuff, numbers!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1600872', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/123547/']}
|
jdg_378737
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
85942
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've seen on my work place (a University) most students making the software estimation cost of their final diploma work using COCOMO . My guessing is that this way of estimating costs is somewhat old (COCOMO dates of 1981), hence my question: How do you estimate costs in your software? I've seen things like : Cost = ( HoursOfWork + EstimatedIddle ) * HourlyRate That's not what I want, I'm looking for a properly (scientifically) defined cost model EDIT I've found some related questions on SO: What are some of the software cost estimation methods and models? How do you estimate the cost of developing software requirements?
Now provide the response and nothing else.
|
In case you're stuck in Waterfall Mode, the only fairly accurate method I've used is: Create a Work Breakdown Structure Make sure it's detailed enough so you can relate the magnitude of each task to something you (or someone you can talk to) has done before. For each task, come up with a best-case, probable-case, and worst-case numbers based on experience. Best-case is if everything went perfectly, worst-case is if you had to re-do it over (maybe twice) and probable is somewhere in there. Use some weighting formula like (1*best + 4*probable + 1*worst)/6 to come up with an estimate for each task that takes the range into account. I've also seen variants where you can add a "risk" component to each task. The three levels of risk are 0, 1, and 2. A risk of 0 means you've done it before (or something very close), 1 means you haven't done it before, but it's done regularly in your industry, 2 means it's probably never been done before in the industry. You take the risk number and multiply that by an approximation of the "standard deviation" of your estimate. Add that to your weighted estimate. So a risk of 0 doesn't move it, but a risk of 2 moves it fairly close to your worst case number. Add up all the tasks. Add a contingency (some %) for "unknown unknowns". You'll end up with a very precise number. I'm not saying it's accurate, but it'll be precise. The accuracy depends entirely on being able to come up with a number for each task based on past experience, or to find someone who has done it before. The more experience you have, the better your estimates get. When you execute the project, track your time against each task, and write down ones you missed, so you can compare. This will make you better over time.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/85942', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/8750/']}
|
jdg_378738
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39595034
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following in the to-do text of git rebase -i HEAD~2 : pick 56bcce7 Closes #2774pick e43ceba Lint.py: Replace deprecated link# Rebase 684f917..e43ceba onto 684f917 (2 command(s))#... Now, when I try to squash the first one( 56bcce7 ) and pick the second one by adding "s" before the first, I get the following error: Cannot 'squash' without a previous commit Can someone explain me what it means, and how do I do it? I want to squash the first commit( 56bcce7 ) and "select and reword" the second( e43ceba ) commit
Now provide the response and nothing else.
|
Interactive rebase presents commits in the reverse order of what you are used to when using git log . git rebase -i replays the selected commits in the exact (top-down) order they are listed in the saved rebase instructions file. When squashing, the commit selected for squashing is combined with the commit that precedes it in the (edited) list, i.e. the commit from the previous line. In your case - there is no previous commit for 56bcce7 . You have to do one of the following git rebase -i HEAD~3 (if you want to squash 56bcce7 into 684f917 ) If you mean to combine 56bcce7 with e43ceba , and e43ceba doesn't depend on 56bcce7 , then simply reorder them: r e43ceba Lint.py: Replace deprecated links 56bcce7 Closes #2774 UPDATE : Gus's answer below suggests a better way of doing the same, without reordering the two commits: r 56bcce7 Closes #2774s e43ceba Lint.py: Replace deprecated link This will squash/merge the two commits into one. When the interactive rebase asks for a reworded commit message for 56bcce7 , provide the commit message that describes the union of 56bcce7 and e43ceba .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/39595034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4993513/']}
|
jdg_378739
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9461880
|
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 not sure what the difference is between specifying Unit as the return type of my scala method or leaving out the return type altogether. What is the difference? Can anyone please advise?
Now provide the response and nothing else.
|
Implicit Unit return type: def f() {println("ABC")} Explicit Unit return type: def g(): Unit = {println("ABC")} Return type inferred from the last method expression, still Unit because this is the type of println , but confusing: def h() = println("ABC") All the methods above are equivalent. I would prefer f() because the lack of = operator after method signature alone is enough for me. Use explicit : Unit when you want to extra document the method. The last form is confusing and actually treated as a warning in intellij-idea . The = operator is crucial. If it is present it means: " please return whatever the last statement returns " in method body. Obviously you cannot use this syntax for abstract methods. If it is not, Unit is assumed.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9461880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/536299/']}
|
jdg_378740
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.