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 | 2118755 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was going through Questions every good .Net developer should be able to answer and was highly impressed with the content and approach of this question and so in the same spirit, I am asking this question for PHP Developer. What questions do you think should a good PHP programmer be able to respond to? EDIT : I am marking this question as community wiki as it is not user specific and it aims to serve programming community at large. Looking forward for some amazing responses. NOTE : Please answer questions too as suggested in the comments so that people could learn something new too regarding the language.
Now provide the response and nothing else.
| Admittedly, I stole this question from somewhere else (can't remember where I read it any more) but thought it was funny: Q: What is T_PAAMAYIM_NEKUDOTAYIM ? A: Its the scope resolution operator (double colon) An experienced PHP'er immediately knows what it means.Less experienced (and not Hebrew) developers may want to read this . But more serious questions now: Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it? A: Cause: body data was sent, causing headers to be sent too. Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters. Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]" ? A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements ( PDO ) 2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future. Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ... ? A: strpos returns the index position of where it first found the $needle, which could be 0 . Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )... Q: What is the preferred way to write this if statement, and why? if( 5 == $someVar ) or if( $someVar == 5 ) A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ( $someVar = 5 ), and will cause an error, the latter won't. Q: Given this code: function doSomething( &$arg ){ $return = $arg; $arg += 1; return $return;}$a = 3;$b = doSomething( $a ); ...what is the value of $a and $b after the function call and why? A: $a is 4 and $b is 3 . The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument. OOP specific Q: What is the difference between public , protected and private in a class definition? A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself. Q: What is wrong with this code: class SomeClass{ protected $_someMember; public function __construct() { $this->_someMember = 1; } public static function getSomethingStatic() { return $this->_someMember * 5; // here's the catch }} A: Static methods don't have access to $this, because static methods can be executed without instantiating a class. Q: What is the difference between an interface and an abstract class? A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist. Q: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour? A: This might be a code smell since the object acts as an ennobled array, without much other use. Q: Why is PHP's implementation of the use of interfaces sub-optimal? A: PHP doesn't allow you to define the expected return type of the method's, which essentially renders interfaces pretty useless. :-P | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2118755', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164299/']} | jdg_78241 |
stackexchange | llm_judgeable_groundtruth_similarity | 12508653 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Near the beginning of this clip from C++ And Beyond, I heard something about problems with std::async . I have two questions: For a junior developer, is there a set of rules for what to do and what to avoid when using std::async ? What are the problems presented in this video? Are they related to this article ?
Now provide the response and nothing else.
| There are several issues: std::async without a launch policy lets the runtime library choose whether to start a new thread or run the task in the thread that called get() or wait() on the future. As Herb says, this is the case you most likely want to use. The problem is that this leaves it open to the QoI of the runtime library to get the number of threads right, and you don't know whether the task will have a thread to itself, so using thread-local variables can be problematic. This is what Scott is concerned about, as I understand it. Using a policy of std::launch::deferred doesn't actually run the task until you explicitly call get() or wait() . This is almost never what you want, so don't do that. Using a policy of std::launch::async starts a new thread. If you don't keep track of how many threads you've got, this can lead to too many threads running. Herb is concerned about the behaviour of the std::future destructor, which is supposed to wait for the task to complete, though MSVC2012 has a bug in that it doesn't wait. For a junior developer, I would suggest: Use std::async with the default launch policy. Make sure you explicitly wait for all your futures. Don't use thread-local storage in the async tasks. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12508653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/700825/']} | jdg_78242 |
stackexchange | llm_judgeable_groundtruth_similarity | 2684 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that we get half of our genes from each parent, but does it necessarily mean we get 1/4 of our genes from each grandparent? Or is it possible that we might get say 30% from one grandparent, 20% from other, 15% from another, 35% from another?
Now provide the response and nothing else.
| I have answered a similar question before: " How many genes do we share with our mother? ". It is not that you "get half your genes" from each parent, and thus a quarter from each grandparent, it is that you inherit the versions of the genes (we all have the 'same' genes). The method that determines which traits are inherited from each parent by the offspring is known as homologous recombination , and this process is (essentially) random, and thus you end with ~50% of your traits (the alleles of the genes) from each parent, and ~25% from each grandparent, so you are right in this respect. This is, however, a generalization; due to the chance nature of the recombination it is entirely plausible that you may inherit more traits from one grandparent in comparison to another, but this is unique to each individual (with the exception of course of genetically identical twins). | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/2684', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/1041/']} | jdg_78243 |
stackexchange | llm_judgeable_groundtruth_similarity | 21498991 |
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 recurring problem when starting the terminal in OSX 10.9.1. Every time I start the terminal I get the following repeated at least 30 times Unknown option: 1Usage: head [-options] <url>...-m <method> use method for the request (default is 'HEAD')-f make request even if head believes method is illegal-b <base> Use the specified URL as base-t <timeout> Set timeout value-i <time> Set the If-Modified-Since header on the request-c <conttype> use this content-type for POST, PUT, CHECKIN-a Use text mode for content I/O-p <proxyurl> use this as a proxy-P don't load proxy settings from environment-H <header> send this HTTP header (you can specify several)-u Display method and URL before any response-U Display request headers (implies -u)-s Display response status code-S Display response status chain-e Display response headers-d Do not display content-o <format> Process HTML content in various ways-v Show program version-h Print this message-x Extra debugging output followed finally by /usr/local/bin/rbenv: fork: Resource temporarily unavailable/usr/local/bin/rbenv: line 63: rbenv---version: command not found/usr/local/bin/rbenv: line 63: rbenv-help: command not found and this repeated 50ish times /usr/local/bin/rbenv: line 63: rbenv---version: command not found/usr/local/bin/rbenv: line 63: rbenv-help: command not found Figuring it's Ruby related, I tried rvm get stable and curl -sSL https://get.rvm.io | bash -s stable but then get the error: SSL certificate problem: self signed certificate in certificate chain I've also tried repairing permissions (as usual) with no solution (as usual) This isn't an area I'm familiar with so I not sure which tree to bark up now. Can anyone help? Here are the .bashrc and .bash_profile contents as requested .bashrc contents: PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting .bash_profile contents: # Setting PATH for Python 2.7# The orginal version is saved in .bash_profile.pysavePATH="/Library/Frameworks/Python.framework/Versions/2.7/bin:${PATH}"export PATHexport PATH=$PATH:/usr/local/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/stevekirkby/.rvm/binexport PATH=$PATH:/usr/local/bin:/usr/local/bin:/Library/Frameworks/Python.framework/Versions/2.7/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/stevekirkby/.rvm/binexport PATH=$PATH:/usr/local/bin:/usr/local/sbin:/usr/local/mysql/binexport PATH=$PATH:$HOME/.rvm/binexport PATH="/Applications/XAMPP/xamppfiles/bin:$PATH"eval "$(rbenv init -)"[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*alias htdocs='cd /Applications/XAMPP/xamppfiles/htdocs'alias home='cd /Users/stevekirkby' Thanks, Steve
Now provide the response and nothing else.
| I had exactly the same problem. It stems from rbenv trying to use head -1 in one of it's scripts, but failing. The problem is that your (and my for that matter) .bash_profile contains: export PATH="/Applications/XAMPP/xamppfiles/bin:$PATH" And the /Applications/XAMPP/xamppfiles/bin folder contains a script named HEAD (named after the HTTP method) and a case-insensitive file system in conjunction with bash (as ZSH did not have this problem) gets head and HEAD mixed up and serves whichever comes first in $PATH b. As a solution: either remove /Applications/XAMPP/xamppfiles/bin from your $PATH (or move it last) Or, as I did, mv HEAD HTTP_HEAD in that folder. PS. the latter option might break some XAMPP scripts but I still need correct XAMPP php version in my path. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21498991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1168863/']} | jdg_78244 |
stackexchange | llm_judgeable_groundtruth_similarity | 2311237 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This thing is confusing me for a long time and hence I am asking it here. We have a given set of numbers $$ X = \{1,2,3,4,5\} $$and we want to form a $4$- digit number of the form $aaac$(this is just symbolic; I want all the arrangements of this form for e.g. $aaca$ etc). (I know that such questions' answers do exist on MSE, but my doubt/ confusion is pertinent to something extraneous to such questions.) To make such a number the first approach that we can induce in our solution is that of using simple combination technique and choose two numbers out of the set of $5$ numbers. This can be done in the following way: $$\binom{5}{2} \cdot \frac {4!}{3!}=40 $$ That seems fine as far as the combination formula is confirmed. Let us now take a naive approach and pretend as if we don't know the combination formula. Here we use the gap method:Let us make one of our configuration as:$$\fbox{a} \fbox{a} \fbox{a} \fbox{c}$$Here $a$ can be chosed in $5$ ways and $c$ can be chosen in $4$ waysTotal ways to make $aaac$ configuration $=5 \cdot 1\cdot 1\cdot 4 = 20$ ways Every such configuration now needs to be permuted since we want $aaca$ etc. also. To permute such a configuration, we can write:$$ \frac {4!}{3!} \cdot 20 = 80$$ which is exactly double that of the answer obtained from the combination formula (which makes be believe that either I have double counted things or I have snubbed some of the arrangements). Now let us try to think about some cases manually: Case $1$: When $a=1$The cases are: $$\{1112\}, \{1121\},\{1211\},\{2111\},\{1113\},\{1131\},\{1311\},\{3111\},\{1114\},\{1141\},\{1411\},\{4111\},\{1115\},\{1151\},\{1511\},\{5111\}$$Thus there are $16$ configurations regarding $1$ only which means that for all the whole set, there are $16 \cdot 5 =80$ configurations. This proves that the problem is with my usage of the combination formula. Can anybody tell me how my usage of combination formula comes out to be fallacious?
Now provide the response and nothing else.
| The problem here is that $a$ and $c$ have two different roles. Therefore simply using $\binom{5}{2}$ will not work, as it denotes the number of ways of picking two elements out of five, but without distinguishing between them. What you can do is$$\binom{5}{2}\cdot2\cdot4 = 80\ ,$$where we piked two numbers in $\{1,2,3,4,5\}$ using $\binom{5}{2}$, then we choose which one to assign to $a$ and which one to $c$ (whence the factor $2$), and finally we choose where to put the $c$ (the factor $4$). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2311237', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/335582/']} | jdg_78245 |
stackexchange | llm_judgeable_groundtruth_similarity | 10966879 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to show one html file. Then fade to another one. Here's my code and it works, except the first time, it waits 10 seconds to switch. Then after the switch, it waits 5 seconds in between switches. I'm a little confused as to how to jquery's handles timeouts and waits. I'd like to wait 5 seconds per switch, beginning with the first one. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script><script>$(document).ready(function() { $("#responsecontainer3").load("ad1.html"); var refreshId = setInterval(function() { $("#responsecontainer3").fadeTo("slow").load('ad1.html?randval='+ Math.random());setTimeout(function() { $("#responsecontainer3").fadeTo("slow").load('ad2.html?randval='+ Math.random()); }, 5000); }, 10000);});</script><div id="responsecontainer3"></div>
Now provide the response and nothing else.
| I think the problem is that when jQuery Mobile initializes the page, the header image is not loaded and the header is much smaller so jQuery Mobile puts a padding on the .ui-page element that is too small once the image loads. A simple fix for this is to manually set the size of the header image so that it takes-up it's required space even before its source loads. You could also do this, although it seems pretty hacky to me, force a redraw by triggering the resize event on document.ready or maybe window.load : $(window).on('load', function () { $(this).trigger('resize');}); I pasted this code into the console while on your page and it re-positioned the title element as expected. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10966879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/710624/']} | jdg_78246 |
stackexchange | llm_judgeable_groundtruth_similarity | 122144 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
There is now a canonical answer for this question over on here that outlines each and every type of RAID in use today, when you should and shouldn't use each one, and how to calculate usable RAW capacity of each RAID type. I administer the hardware that runs a website that receives 10,000 daily visitors. What variables should I consider when deciding which RAID type to choose for our web application? The server is a HP-DL380 G6 Server with 6 146GB (SCSI) HDDs.
Now provide the response and nothing else.
| I know that machine and those disks very well but you've not told us what the application does and how much space you need - this is important because you have a few choices, let's go through them. RAID 0 - You'd have 6 x 146GB (actually you only get about 95% of that 146GB, take this into consideration throughout) available to you application - this gets you the most space but is a bad idea as when one disk fails it kills your whole data - avoid this. RAID 1 - you could theoretically setup 3 x (2 x 146GB) RAID 1 arrays - there may be a good reason to do this, you could have your OS on one pair, your database on another pair and your logs on another pair - if your application is a write-heavy database this isn't the worst way to go if your data would fit in that little space - ignore this if your application isn't a database. Ignore RAID 3 and 4 - they're old-school (unless you're NetApp of course :) ) RAID 5 - this would give you 5 x 146GB of space and could survive a single disk failure - RAID 5 is kind-of hated by quite a lot of us geeks for dull, but valid, statistical reasons - if your application is something that does mostly reads against an easily restorable or transient data set then RAID 5 can gives you a pretty good balance. RAID 6 - this would give you 4 x 146GB but allow you to survive two concurrent disk failures - I would avoid this mode given your setup as it gives you a write performance penalty and only gives you a single disk of extra space over... RAID 10 - this splits your 6 disks into two piles of three disks - so you only get 3 x 146GB of space - BUT it can survive up to three disks failing without performance hits, in fact it's often the fastest mode for both reads and writes - if you can live with only 3 disks-worth of space then this mode would be great for most applications. RAID 50 - well you've only just about got enough disks for this and you'd only get 2 x 146GB of space for zero benefit in your situation and you don't have enough disks for RAID 60. So you can see how your application requirements will drive your disk layout - let us know what you're doing and we'll point you to one mode over another ok. Now one other thing to consider is that you have 2 spare drive slots left on that model - I'd urge you to fill them now. The reason is that if you've got a database system you can have a RAID 1 pair for your OS and apps, a pair of 2 disks for data and a pair of disks for database logs - this will be pretty fast and give you 2 x 146GB of database space instead of just 1 x 146GB - does that make sense? If you have a more 'read-only' type of setup then having 8 disks will allow you to have a much larger and/or much faster RAID 5/6 or 10 setup and these are best created like this on day one that added to later. I hope this helps and come back with more information please, oh and p.s. good choice on the server, they're great - have you got iLO working yet, it's a life-saver :) | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/122144', 'https://serverfault.com', 'https://serverfault.com/users/-1/']} | jdg_78247 |
stackexchange | llm_judgeable_groundtruth_similarity | 215800 |
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 $Y$ be an orientable, smooth 3-manifold and let $X=Y\times S^{1}$. My question is that: when does $X$ admits a Riemannian metric with positive scalar curvature? An obvious case is when $Y$ itself admits a psc metric. Are there any other case? It was proved by Gromov and Lawson that any 3-manifold which contains a $K(\pi,1)$ prime factor does not admits a psc metric (another result in the paper implies that $Y$ should not be hyperbolic if $Y\times S^{1}$ admits psc), which, together with the Geometrization conjecture classifies all the 3-manifold admits psc metric. Does their proof works for $Y\times S^{1}$? (I am most interested in the special case that $Y$ is an irreducible integer homology sphere)
Now provide the response and nothing else.
| It is a theorem of Schoen and Yau (see Jonathan Rosenberg's survey , theorem 1.10) that no closed aspherical 4-manifold is psc. That means that the three-manifold should be non-aspherical, which narrows it down to a very small list (especially if you insist on integer homology spheres). | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/215800', 'https://mathoverflow.net', 'https://mathoverflow.net/users/44651/']} | jdg_78248 |
stackexchange | llm_judgeable_groundtruth_similarity | 35544693 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Trying to read json Data and I can't get it to work correctly with the following code: $apiurl = "https://api.hasoffers.com/Apiv3/json?NetworkId=REDACTED&Target=Affiliate_Report&Method=getStats&api_key=REDACTED&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.unique_clicks&fields%5B%5D=Stat.payout&filters%5BStat.date%5D%5Bconditional%5D=LESS_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21&filters%5BStat.date%5D%5Bconditional%5D=GREATER_THAN&filters%5BStat.date%5D%5Bvalues%5D=2016-02-21";$data = json_decode(file_get_contents($apiurl), true);foreach($data['response']['data'] as $dataline) { echo "Conversions: {$dataline['Stat']['conversions']} Payout: {$dataline['Stat']['payout']}";} The query is generating the following json return, I just can't figure out how to read the stats correctly (it's also looping through 7 lines in the foreach which also makes no sense to me): {"request":{"Target":"Affiliate_Report","Format":"json","Service":"HasOffers","Version":"2","NetworkId":"REDACTED","Method":"getStats","api_key":"REDACTED","fields":["Stat.conversions","Stat.unique_clicks","Stat.payout"],"filters":{"Stat.date":{"conditional":"GREATER_THAN","values":"2016-02-21"}},"__gaTune":"GA1.2.1289716345.1455904273","__utma":"267117079.1377304869.1455903853.1455904273.1455904273.1","__utmc":"267117079","__utmz":"267117079.1455904273.1.1.utmcsr=developers.hasoffers.com|utmccn=(referral)|utmcmd=referral|utmcct=/","_biz_uid":"1742fd1f613440a4cfbb5a510d1d7def","_biz_nA":"1","_biz_pendingA":"[]","_hp2_id_1318563364":"5257773084071598.0276720083.0714677778","_ga":"GA1.2.1377304869.1455903853"},"response":{"status":1,"httpStatus":200,"data":{"page":1,"current":50,"count":1,"pageCount":1,"data":[{"Stat":{"conversions":"1000","unique_clicks":"1000","payout":"1000.000000"}}],"dbSource":"branddb"},"errors":[],"errorMessage":null}}
Now provide the response and nothing else.
| The one you want to call is a function template: template<class charT, class Traits, class Alloc>bool operator<(std::basic_string<charT, Traits, Alloc> const& lhs, std::basic_string<charT, Traits, Alloc> const& rhs); Deduction fails for the second argument because a HasConversionToString is not a std::basic_string - template argument deduction doesn't look through implicit conversions. As a result, that function template is removed from overload resolution. std::experimental::basic_string_view has a similar problem, which was solved by a "sufficient additional overloads" rule (the library must add enough overloads so that comparison between a basic_string_view and something convertible to one works). You don't really want such a thing for basic_string , though - having < possibly silently causing a trip to the heap is not really a good idea. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35544693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5960663/']} | jdg_78249 |
stackexchange | llm_judgeable_groundtruth_similarity | 170477 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am testing web application for which business actions are done by sending JSON requests like for example: POST /dataRequest HTTP/1.1Host: test.comUser-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0Accept: */*Accept-Language: pl,en-US;q=0.7,en;q=0.3Content-Type: application/json; charset=utf-8Content-Length: 99Cookie: SESSIONID=7jtyutuytu1aConnection: close{"F":"test.AppRequestFactory","I":[{"O":"5vhghgjhgjE0="}]} I made the HTML auto-submit page like this <html><head></head><body onload=document.getElementById('xsrf').submit()> <form id="xsrf" action="https://test.com/dataRequest" method=post enctype="text/plain"> <input name='{"F":"test.AppRequestFactory","I":[{"O":""O":"5vhghgjhgjE0' value='"}]}' type='hidden'> </form></body></html> The problem is that it will be send with header Content-Type: text/plain , but the server only accepts Content-Type: application/json; charset=utf-8 . I've read the discussion CSRF with JSON POST where one of the comments states: Use something like this: var blob= new Blob([JSON.stringify(YOUR JSON)], {type : 'application/json; charset=UTF-8'}); to generate a JSON blob and it'll send perfectly. CSRF in seconds! But I have no idea how to use this approach. Is this application vulnerable to CSRF attack?
Now provide the response and nothing else.
| Is this application vulnerable to CSRF attack? Yes, it's vulnerable. The prerequisite, however, here is Flash . With the help of Flash, it's possible to forge a Content-type header with any arbitrary value. What you need to do is POST a request to your own domain, and then issue a 307 redirect. Please refer to below screenshot: For more information, please refer to this cm2.pw article . Use something like this: var blob= new Blob([JSON.stringify(YOUR JSON)], {type : 'application/json; charset=UTF-8'}); to generate a JSON blob and it'll send perfectly. CSRF in seconds! This, afaik, is already fixed in modern browsers. However, it still works in IE with file URI. Update : Since it's still getting a lot of views lately, I'm adding links to fixes; https://bugzilla.mozilla.org/show_bug.cgi?id=1436241 https://bugs.chromium.org/p/chromium/issues/detail?id=332023 For some reason, chromium fix does not work and still allow sending POST request with custom Content-type headers. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/170477', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/156661/']} | jdg_78250 |
stackexchange | llm_judgeable_groundtruth_similarity | 2117557 |
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 map like this, Map<Integer,ArrayList<Object>> myMap = new LinkedHashMap<Integer,ArrayList<Object>>(); Now I have to iterate this Map and then the ArrayList inside the map. How can I do this using JSTL?
Now provide the response and nothing else.
| You can use JSTL <c:forEach> tag to iterate over arrays, collections and maps. In case of arrays and collections, every iteration the var will give you just the currently iterated item right away. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:forEach items="${collectionOrArray}" var="item"> Item = ${item}<br></c:forEach> In case of maps, every iteration the var will give you a Map.Entry object which in turn has getKey() and getValue() methods. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:forEach items="${map}" var="entry"> Key = ${entry.key}, value = ${entry.value}<br></c:forEach> In your particular case, the ${entry.value} is actually a List , thus you need to iterate over it as well: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><c:forEach items="${map}" var="entry"> Key = ${entry.key}, values = <c:forEach items="${entry.value}" var="item" varStatus="loop"> ${item} ${!loop.last ? ', ' : ''} </c:forEach><br></c:forEach> The varStatus is there just for convenience ;) To understand better what's all going on here, here's a plain Java translation: for (Entry<String, List<Object>> entry : map.entrySet()) { out.print("Key = " + entry.getKey() + ", values = "); for (Iterator<Object> iter = entry.getValue().iterator(); iter.hasNext();) { Object item = iter.next(); out.print(item + (iter.hasNext() ? ", " : "")); } out.println();} See also: How to loop through a HashMap in JSP? Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern How to loop over something a specified number of times in JSTL? | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2117557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/94813/']} | jdg_78251 |
stackexchange | llm_judgeable_groundtruth_similarity | 18620 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to install version 1.4 of Subversion on a Suse 10.1 (64 bit) box. I can't change either of these two versions and there isn't an RPM for this distro. After looking around I assume that I'll have to create an RPM myself. Is there a better way than this? If not does anyone have any tips on the process? I don't need a step-by-step tutorial, just a basic outline of the process.
Now provide the response and nothing else.
| Rebuilding an existing src.rpm is probably the easiest. I would definitely not go the way of configure, make, make install because (a) that doesn't scale, (b) doesn't provide for easy removal / upgrading of the package and (c) is not atomic. Building an RPM is not so hard. There used to be a pretty good beginners tutorial at Linux.com, before they destroyed the site. You can try this one , but it's a lot of text, not easy to digest. Still, it's better than nothing. I'll give you a few pointers, out of the back of my head: setup an .rpmmacros file in ~ create ~/rpmbuild/{RPMS,SRPMS,SPECS,BUILD,BUILDROOT,SOURCES} drop the source tarball in ~/rpmbuild/SOURCES drop the the spec file(s) in ~/rpmbuild/SPECS run rpmbuild -bp YOURSPEC in ~/rpmbuild/SPECS (runs prepare phase) run rpmbuild -bc YOURSPEC in ~/rpmbuild/SPECS (above and runs compile phase) run rpmbuild -bb YOURSPEC in ~/rpmbuild/SPECS (above and builds actual package) If everything worked out, your RPM will have appeared in ~/rpmbuild/RPMS/${arch}. I tend to use 5, 6 and 7 separately when creating new RPM's, because I like to inspect the ouput in detail. You might want to go for 7 immediately if you have a vendor provided specfile. I usually have something like this in my .rpmmacros. %_topdir /home/YOURNAME/rpmbuild%packager YOUR NAME <[email protected]>%_tmppath /tmp As for the syntax of the specfile: it is not that hard. There exists a very detailed, be it very old, reference work called ' Maximum RPM '. Everything you want to know is in there. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/18620', 'https://serverfault.com', 'https://serverfault.com/users/7787/']} | jdg_78252 |
stackexchange | llm_judgeable_groundtruth_similarity | 10128950 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two images that need to kept inline; I want to write a caption under each image. <center> <a href="http://example.com/hello"> <img src="hello.png" width="100px" height="100px"> </a> <a href="http://example.com/hi"> <img src="hi.png" width="100px" height="100px"> </a></center> How can I implement?
Now provide the response and nothing else.
| Figure and Figcaption tags: <figure> <img src='image.jpg' alt='missing' /> <figcaption>Caption goes here</figcaption></figure> Gotta love HTML5. See sample #container { text-align: center;}a, figure { display: inline-block;}figcaption { margin: 10px 0 0 0; font-variant: small-caps; font-family: Arial; font-weight: bold; color: #bb3333;}figure { padding: 5px;}img:hover { transform: scale(1.1); -ms-transform: scale(1.1); -webkit-transform: scale(1.1); -moz-transform: scale(1.1); -o-transform: scale(1.1);}img { transition: transform 0.2s; -webkit-transition: -webkit-transform 0.2s; -moz-transition: -moz-transform 0.2s; -o-transition: -o-transform 0.2s;} <div id="container"> <a href="#"> <figure> <img src="http://lorempixel.com/100/100/nature/1/" width="100px" height="100px" /> <figcaption>First image</figcaption> </figure> </a> <a href="#"> <figure> <img src="http://lorempixel.com/100/100/nature/2/" width="100px" height="100px" /> <figcaption>Second image</figcaption> </figure> </a></div> | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10128950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689557/']} | jdg_78253 |
stackexchange | llm_judgeable_groundtruth_similarity | 343606 |
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 am dealing with being Bayesian and looking for a closed form for a posterior for the scale parameter $\tau$ of a Laplace distribution, such that I can derive a full conditional in my Gibbs sampler. I do not think I could exploit conjugacy for the Laplace, but any closed-form computation for the posterior would be useful. Any ideas on how to choose the prior and obtain a closed form posterior from which it is known how to sample from?
Now provide the response and nothing else.
| The likelihood for $n$ iid observations looks like: $ f(x_1,...x_n|\lambda,\mu) \propto \frac{1}{\lambda^n} exp(-\frac{1}{\lambda}\sum_{i=1}^n|x_i-\mu|)$ Hence a conjugate prior for $\lambda$ with $\mu, x$ known must (thinking only about the algebra) look like: $ f(\lambda) \propto \frac{1}{\lambda^a} exp(-\frac{b}{\lambda})$ As suggested by marmle, this is an Inverse Gamma, although to be nice we'd need to change $a\rightarrow a-1$ and let $a>0, b>0$. EDIT: To get the updated parameters for $\lambda$: $ f(\lambda|x_1,...x_n, \mu) \propto f(\lambda)f(x_1,...x_n|\lambda,\mu) $ $ \propto \frac{1}{\lambda^{a-1}} exp(-\frac{b}{\lambda}) \frac{1}{\lambda^n} exp(-\frac{1}{\lambda}\sum_{i=1}^n|x_i-\mu|)$ $ \propto \frac{1}{\lambda^{n+a-1}} exp(-\frac{1}{\lambda}(b+\sum_{i=1}^n|x_i-\mu|)) $ | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/343606', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/14101/']} | jdg_78254 |
stackexchange | llm_judgeable_groundtruth_similarity | 50722824 |
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 happen? http://coliru.stacked-crooked.com/a/e1376beff0c157a1 class Base{private: virtual void do_run() = 0;public: void run(){ do_run(); }};class A : public Base {public: // uplift ?? virtual void do_run() override {}};int main(){ A a; a.do_run();} Why can I override a PRIVATE virtual method as public?
Now provide the response and nothing else.
| According to https://en.cppreference.com/w/cpp/language/virtual#In_detail overriding a base's virtual member function only care about the function name, parameters, const/volatile-ness and ref qualifier. It doesn't care about return type, access modifier or other things you might expect it to care about. The linked reference also specifically notes that : Base::vf does not need to be visible (can be declared private, or inherited using private inheritance) to be overridden. Nothing that I can find explicitly gives permission to do this, but the rules of overriding do not prevent it. It's allowed by virtue of virtual functions and function overriding existing and not disallowing this case. If you are asking why this is how the language is, you may have to ask the standardization committee. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50722824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1559666/']} | jdg_78255 |
stackexchange | llm_judgeable_groundtruth_similarity | 2855392 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When i access joomla article manager or module manager then i had faced the bellow output:500 - An error has occurred! DB function failed with error number 1Can't create/write to file '/tmp/#sql_57c0_0.MYD' (Errcode: 17) SQL=SELECT c.*, g.name AS groupname, cc.title AS name, u.name AS editor, f.content_id AS frontpage, s.title AS section_name, v.name AS author FROM jos_content AS c LEFT JOIN jos_categories AS cc ON cc.id = c.catid LEFT JOIN jos_sections AS s ON s.id = c.sectionid LEFT JOIN jos_groups AS g ON g.id = c.access LEFT JOIN jos_users AS u ON u.id = c.checked_out LEFT JOIN jos_users AS v ON v.id = c.created_by LEFT JOIN jos_content_frontpage AS f ON f.content_id = c.id WHERE c.state != -2 ORDER BY section_name , section_name, cc.title, c.ordering LIMIT 0, 20
Now provide the response and nothing else.
| Well, you first need to select your project root folder. Quite simply, this is the folder at the top level of your project, or the current folder if you're dealing with a single file. Once you've selected the root folder, then other options will work, such as code assist, showing documentation, jumping to other symbols, etc. For full benefit of ropemacs, I suggest getting autocomplete.el , putting it in ~/.emacs.d, and then adding this to your .emacs (add-to-list 'load-path "~/.emacs.d/")(add-to-list 'load-path "~/.emacs.d/auto-complete-1.2")(autoload 'python-mode "python-mode" "Python Mode." t)(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))(add-to-list 'interpreter-mode-alist '("python" . python-mode))(require 'python-mode)(autoload 'pymacs-apply "pymacs")(autoload 'pymacs-call "pymacs")(autoload 'pymacs-eval "pymacs" nil t)(autoload 'pymacs-exec "pymacs" nil t)(autoload 'pymacs-load "pymacs" nil t)(pymacs-load "ropemacs" "rope-")(setq ropemacs-enable-autoimport t)(require 'auto-complete)(global-auto-complete-mode t) This assumes you install autocomplete in ~/.emacs.d/auto-complete-1.2. After you do this, you will get autocomplete automatically after typing a few characters of a word or symbol. You can modify your ROOT/.ropeproject/config.py file to add more directories to the rope lookup path, in order to provide better autocomplete. EDIT: Two of the most important functions for me are looking up documentation and jumping directly to a function definition. This is dependent on setting the rope lookup path correctly for your project as mentioned above. Documentation : Put the cursor over a symbol (function name, class name, etc), and do: C-c d This will show you the docstring for the symbol in question. Jumping to definition :Put the cursor over a symbol (function name, class name, etc), and do: C-c g This will immediately open the file where the symbol resides and jump to the beginning of the definition. This is great for times when the documentation is sparse and you want to see the actual code. Also, it's really nice for navigating around inside your own code. Find occurrences : C-c f Smart search in your entire project for the symbol at the cursor. Code assist : M-/ Just type the first characters of a function, class, etc, and this will show a list of possible completions. Note that due to python's nature, it will not always be a complete list. Refactorings :There are quite a few options under Rope->Refactor. These are to organize your code better. How to use them should be mostly self-explanatory; in general, select the region of code you want to refactor, then choose the command. Edit :In response to a comment below, here's exactly how to add other paths to your python path so autocomplete will look for those symbols as well. prefs.add('python_path', '~/path/to/virtualenv/lib/python2.6/site-packages') This goes in .ropeproject/config.py | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2855392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297150/']} | jdg_78256 |
stackexchange | llm_judgeable_groundtruth_similarity | 105910 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to get boundaries of grains from a microphotograph. I have tried using different methods but because of the texture of background I am not able to get smooth boundaries. Codes that I've tried are: 1) EdgeDetect[ DeleteSmallComponents[ FillingTransform[ MorphologicalBinarize[Import["http://imgur.com/o7OF9jG.jpg"], .5]]]] This gives output as: 2) EdgeDetect[ FillingTransform[ DeleteSmallComponents[ ColorNegate[ ChanVeseBinarize[Import["http://imgur.com/o7OF9jG.jpg"]]], 2000]]] This gives output as: However, I am not satisfied with either of the results. Can I use any other way/function to determine a more accurate grain boundaries from this image?
Now provide the response and nothing else.
| One approach is to smooth the image (here I've used the curvature flow filter, which is a nonlinear edge-preserving smoothing filter) and then binarize before doing the edge detection. img = Import["http://i.stack.imgur.com/TIiTZ.jpg"] curve = CurvatureFlowFilter[img, 40];EdgeDetect[FillingTransform[DeleteSmallComponents[Binarize[curve]]]] Dilating makes it look a bit smoother, but you may (or may not) want to do that, depending on what you are doing with the images. Dilation[EdgeDetect[FillingTransform[DeleteSmallComponents[Binarize[curve]]]], 1] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/105910', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/13777/']} | jdg_78257 |
stackexchange | llm_judgeable_groundtruth_similarity | 119319 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to print the word before the last word in line (with ksh or awk or sed or perl one liner) Example 1: echo one two three will print "two" Example 2: echo 1 2 3 4 5 6 will print "5"
Now provide the response and nothing else.
| With awk: awk '{ print $(NF-1) }' NF is the number of fields -- all that happens here is that one is subtracted from the total field length to get the penultimate field. With perl: perl -lane 'print $F[-2]' An array containing the fields is created as @F (that's what -a does), and we get the value of the second last field (with index -2 ). Using sed is slightly less palatable, since it doesn't have any concept of fields. I'd recommend using one of the above, instead. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/119319', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']} | jdg_78258 |
stackexchange | llm_judgeable_groundtruth_similarity | 1064159 |
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 somewhat new to Ruby and although I find it to be a very intuitive language I am having some difficulty understanding how implicit return values behave. I am working on a small program to grep Tomcat logs and generate pipe-delimited CSV files from the pertinent data. Here is a simplified example that I'm using to generate the lines from a log entry. class LineMatcher class << self def match(line, regex) output = "" line.scan(regex).each do |matched| output << matched.join("|") << "\n" end return output end endendputs LineMatcher.match("00:00:13,207 06/18 INFO stateLogger - TerminationRequest[accountId=AccountId@66679198[accountNumber=0951714636005,srNumber=20]", /^(\d{2}:\d{2}:\d{2},\d{3}).*?(\d{2}\/\d{2}).*?\[accountNumber=(\d*?),srNumber=(\d*?)\]/) When I run this code I get back the following, which is what is expected when explicitly returning the value of output. 00:00:13,207|06/18|0951714636005|20 However, if I change LineMatcher to the following and don't explicitly return output: class LineMatcher class << self def match(line, regex) output = "" line.scan(regex).each do |matched| output << matched.join("|") << "\n" end end end end Then I get the following result: 00:00:13,20706/18095171463600520 Obviously, this is not the desired outcome. It feels like I should be able to get rid of the output variable, but it's unclear where the return value is coming from. Also, any other suggestions/improvements for readability are welcome.
Now provide the response and nothing else.
| Any statement in ruby returns the value of the last evaluated expression.You need to know the implementation and the behavior of the most used method in order to exactly know how your program will act. #each returns the collection you iterated on. That said, the following code will return the value of line.scan(regexp). line.scan(regex).each do |matched| output << matched.join("|") << "\n"end If you want to return the result of the execution, you can use map , which works as each but returns the modified collection. class LineMatcher class << self def match(line, regex) line.scan(regex).map do |matched| matched.join("|") end.join("\n") # remember the final join end endend There are several useful methods you can use depending on your very specific case. In this one you might want to use inject unless the number of results returned by scan is high (working on arrays then merging them is more efficient than working on a single string). class LineMatcher class << self def match(line, regex) line.scan(regex).inject("") do |output, matched| output << matched.join("|") << "\n" end end endend | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1064159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131105/']} | jdg_78259 |
stackexchange | llm_judgeable_groundtruth_similarity | 283030 |
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:
Java documentation says it's " strongly recommended " to have them behaving consistently. But are there legitimate cases of java/c#/python/etc Object.equals() method behaving inconsistently with the method Comparable.compareTo() ?
Now provide the response and nothing else.
| The reason you have two different methods is that they do two different things. The .equals method returns a boolean value indicating whether the object on which you call the method is equal to the object passed in as a parameter (for some definition of "is equal to" that is consistent with the nature of the object being compared). The .compareTo method returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. That makes it a useful method for sorting; it allows you to compare one instance with another for purposes of ordering. When the Java documentation says that these two methods must behave consistently, what they mean is that the .equals method must return true in exactly the same situations where the .compareTo method returns zero, and must return false in exactly the same situations where the .compareTo method returns a nonzero number. Is there any good reason to violate these rules? Generally no, for the same reasons that #define TRUE FALSE is a really bad idea. The only legitimate reason for inconsistent behavior is hinted at in the Java documentation itself: "[if the] class has a natural ordering that is inconsistent with equals." To drive home the point, you can actually define .equals() in terms of compareTo() , thus guaranteeing consistent behavior. Consider this .equals() method from a Rational class which, after a few sanity checks, simply defines .equals as compareTo() == 0 : public boolean equals(Object y) { if (y == null) return false; if (y.getClass() != this.getClass()) return false; Rational b = (Rational) y; return compareTo(b) == 0;} | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/283030', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/165064/']} | jdg_78260 |
stackexchange | llm_judgeable_groundtruth_similarity | 44100477 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am creating a python module with a function to display a pandas DataFrame ( my_df ). If the user imports the module into a Jupyter notebook, I would want to deliver "pretty" formatting for the DataFrame by using something like: from IPython.display import display, HTMLdisplay(my_df) If the user is not in a Jupyter notebook, I would want to display the text form of the DataFrame: print(my_df) How can I check if the code is being run from a Jupyter notebook? Or, how can I display the DataFrame in text form from the commandline, vs display the HTML form if it is imported into a Jupyter notebook? from IPython.display import display, HTMLdef my_func(my_df): if [... code to check for Jupyter notebook here ...]: display(my_df) else: print(my_df)
Now provide the response and nothing else.
| You don't need to check if the code is being run from a Notebook; display() prints text when called from the command line. test.py : from IPython.display import displayimport pandas as pd my_df = pd.DataFrame({'foo':[1,2,3],'bar':[7,8,9]})display(my_df) From the command line: $ python test.py bar foo0 7 11 8 22 9 3 From a Jupyter Notebook: UPDATE To check whether you're running inside an interactive Ipython shell (command-line or browser-based), check for get_ipython . (Adapted from the Ipython docs) Modified test.py : from IPython.display import display, HTMLimport pandas as pd my_df = pd.DataFrame({'foo':[1,2,3],'bar':[7,8,9]})try: get_ipython display(my_df)except: print(my_df) This approach will: - pretty-print in a browser Jupyter notebook - print text when run as a script from the command line (e.g. python test.py ) - if run line-by-line in a Python shell, it will not turn into an interactive Ipython shell after printing | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44100477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2636317/']} | jdg_78261 |
stackexchange | llm_judgeable_groundtruth_similarity | 33786662 |
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 Eigen::MatrixXd and I would like to modify all its elements by applying a function component-wise. For example: MatrixXd m = ...;for each m[i][j]: m[i][j] = exp(m[i][j]); Is there a way to achieve this result?
Now provide the response and nothing else.
| Yes, use the Eigen::MatrixBase<>::unaryExpr() member function. Example: #include <cmath>#include <iostream>#include <Eigen/Core>double Exp(double x) // the functor we want to apply{ return std::exp(x);}int main(){ Eigen::MatrixXd m(2, 2); m << 0, 1, 2, 3; std::cout << m << std::endl << "becomes: "; std::cout << std::endl << m.unaryExpr(&Exp) << std::endl;} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33786662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1395740/']} | jdg_78262 |
stackexchange | llm_judgeable_groundtruth_similarity | 71952 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Background Take 2 convex sets in $\mathbb{R}^2$, or 3 convex sets in $\mathbb{R}^3$, or generally, $n$ convex sets in $\mathbb{R}^n$. "Mixed volume" assigns to such a family $A_1, \ldots, A_n$ a real number $V(A_1, \ldots, A_n)$, measured in $\mathrm{metres}^n$. As I understand it, mixed volume is a kind of cousin of the determinant. I'll give the definition in a moment, but first here are some examples. $V(A, \ldots, A) = \mathrm{Vol}(A)$, for any convex set $A$. More generally, suppose that $A_1, \ldots, A_n$ are all scalings of a single convex set (so that $A = r_i B$ for some convex $B$ and $r_i \geq 0$). Then $V(A_1, \ldots, A_n)$ is the geometric mean of $\mathrm{Vol}(A_1), \ldots, \mathrm{Vol}(A_n)$. The previous examples don't show how mixed volume typically depends on the interplay between the sets. So, taking $n = 2$, let $A_1$ be an $a \times b$ rectangle and $A_2$ a $c \times d$ rectangle in $\mathbb{R}^2$, with their edges parallel to the coordinate axes. Then $$V(A_1, A_2) = \frac{1}{2}(ad + bc).$$(Compare and contrast the determinant formula $ad - bc$.) More generally, take axis-parallel parallelepipeds $A_1, \ldots, A_n$ in $\mathbb{R}^n$. Write $m_{i1}, \ldots, m_{in}$ for the edge-lengths of $A_i$. Then$$V(A_1, \ldots, A_n) = \frac{1}{n!} \sum_{\sigma \in S_n} m_{1, \sigma(1)} \cdots m_{n, \sigma(n)}.$$(Again, compare and contrast the determinant formula.) The definition of mixed volume depends on a theorem of Minkowski: for any compact convex sets $A_1, \ldots, A_m$ in $\mathbb{R}^n$, the function$$(\lambda_1, \ldots, \lambda_m) \mapsto \mathrm{Vol}(\lambda_1 A_1 + \cdots + \lambda_m A_m)$$(where $\lambda_i \geq 0$ and $+$ means Minkowski sum) is a polynomial, homogeneous of degree $n$. For $m = n$, the mixed volume $V(A_1, \ldots, A_n)$ is defined as the coefficient of $\lambda_1 \lambda_2 \cdots \lambda_n$ in this polynomial, divided by $n!$. Why pick out this particular coefficient? Because it turns out to tell you everything, in the following sense: for any convex sets $A_1, \ldots, A_m$ in $\mathbb{R}^n$,$$\mathrm{Vol}(\lambda_1 A_1 + \cdots + \lambda_m A_m) = \sum_{i_1, \ldots, i_n = 1}^m V(A_{i_1}, \ldots, A_{i_n}) \lambda_{i_1} \cdots \lambda_{i_n}.$$ Properties of mixed volume Formally, let $\mathscr{K}_n$ be the set of nonempty compact convex subsets of $\mathbb{R}^n$. Then mixed volume is a function$$V: (\mathscr{K}_n)^n \to [0, \infty),$$and has the following properties: Volume: $V(A, \ldots, A) = \mathrm{Vol}(A)$. (Here and below, the letters $A$, $A_i$ etc. will be understood to range over $\mathscr{K}_n$, and $\lambda$, $\lambda_i$ etc. will be nonnegative reals.) Symmetry: $V$ is symmetric in its arguments. Multilinearity: $$V(\lambda A_1 + \lambda' A'_1, A_2, \ldots, A_n) = \lambda V(A_1, A_2, \ldots, A_n) + \lambda' V(A'_1, A_2, \ldots, A_n).$$(These first three properties closely resemble a standard characterization of determinants.) Continuity: $V$ is continuous with respect to the Hausdorff metric on $\mathscr{K}_n$. Invariance: $V(gA_1, \ldots, gA_n) = V(A_1, \ldots, A_n)$ for any isometry $g$ of Euclidean space $\mathbb{R}^n$ onto itself. Multivaluation: $$V(A_1 \cup A'_1, A_2, \ldots, A_n) = V(A_1, A_2, \ldots) + V(A'_1, A_2, \ldots) - V(A_1 \cap A'_1, A_2, \ldots)$$whenever $A_1, A'_1, A_1 \cup A'_1 \in \mathscr{K}_n$. Monotonicity: $V(A_1, A_2, \ldots, A_n) \leq V(A'_1, A_2, \ldots, A_n)$ whenever $A_1 \subseteq A'_1$. There are other basic properties, but I'll stop there. Questions Is $V$ the unique function $(\mathscr{K}_n)^n \to [0, \infty)$ satisfying properties 1--7? If so, does some subset of these properties suffice? In particular, do properties 1--3 suffice? If not, is there a similar characterization involving different properties? (Partway through writing this question, I found a recent paper of Vitali Milman and Rolf Schneider: Characterizing the mixed volume . I don't think it answers my question, though it does give me the impression that the answer might be unknown.)
Now provide the response and nothing else.
| Sorry to answer my own question, but asking this in public seems to have spurred me into thought. As auniket suspected, the answer is "yes" in the strongest sense I'd hoped: properties 1-3 do characterize mixed volume. In fact, something slightly stronger is true: $V$ is the unique function $(\mathscr{K}_n)^n \to \mathbb{R}$ satisfying $V(A, \ldots, A) = Vol(A)$ $V$ is symmetric $V(A_1 + A'_1, A_2, \ldots, A_n) = V(A_1, A_2, \ldots, A_n) + V(A'_1, A_2, \ldots, A_n)$. In other words, we don't need multilinearity, just multiadditivity. The proof is along the lines suggested by auniket. Fix $n$ and $A_1, \ldots, A_n \in \mathscr{K}_n$. Write $\mathbf{n} = \{1, \ldots, n\}$, and for sets $R$ and $S$, write $\mathrm{Surj}(R, S)$ for the set of surjections $R \to S$. I claim that for all subsets $S$ of $\mathbf{n}$,$$\sum_{f \in \mathrm{Surj}(\mathbf{n}, S)} V(A_{f(1)}, \ldots, A_{f(n)})$$is uniquely determined by the properties above. The proof will be by induction on the cardinality of $S$. When $S = \mathbf{n}$, this sum is$$n! V(A_1, \ldots, A_n),$$so this claim will imply the characterization theorem. To prove the claim, take $S \subseteq \mathbf{n}$. Then$$Vol(\sum_{i \in S} A_i) = \sum_{f: \mathbf{n} \to S} V(A_{f(1)}, \ldots, A_{f(n)})$$by the three properties. This in turn is equal to$$\sum_{R \subseteq S} \sum_{f \in \mathrm{Surj}(\mathbf{n}, R)} V(A_{f(1)}, \ldots, A_{f(n)}).$$By the inductive assumption, all but one of the summands in the first summation - namely, $R = S$ - is uniquely determined. Hence the $S$-summand is uniquely determined too. This completes the induction, and so completes the proof. The proof makes it clear that $V(A_1, \ldots, A_n)$ is some rational linear combination of ordinary volumes of Minkowski sums of some of the $A_i$s. It must be possible to unwind this proof and get an explicit expression; and that expression must be the one auniket gave (which also appears in Lemma 5.1.3 of Schneider's book Convex Bodies: The Brunn-Minkowski Theory ). This all seems rather easy, and must be well-known, though I'm a bit surprised that this characterization isn't mentioned in some of the things I've read. Incidentally, I now understand why it doesn't appear in the paper of Milman and Schneider mentioned in my question: they explicitly state that they want to avoid assuming property 1. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/71952', 'https://mathoverflow.net', 'https://mathoverflow.net/users/586/']} | jdg_78263 |
stackexchange | llm_judgeable_groundtruth_similarity | 1425221 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Java, if I create a Hashtable<K, V> and put N elements in it, how much memory will it occupy? If it's implementation dependent, what would be a good "guess"?
Now provide the response and nothing else.
| Edit; Oh geez, I'm an idiot, I gave info for HashMap, not HashTable. However, after checking, the implementations are identical for memory purposes. This is dependent on your VM's internal memory setup (packing of items, 32 bit or 64 bit pointers, and word alignment/size) and is not specified by java. Basic info on estimating memory use can be found here . You can estimate it like so: On 32-bit VMs, a pointer is 4 bytes, on 64-bit VMs, it is 8 bytes. Object overhead is 8 bytes of memory (for an empty object, containing nothing) Objects are padded to a size that is a multiple of 8 bytes (ugh). There is a small, constant overhead for each hashmap: one float, 3 ints, plus object overhead. There is an array of slots, some of which will have entries, some of which will be reserved for new ones. The ratio of filled slots to total slots is NO MORE THAN the specified load factor in the constructor. The slot array requires one object overhead, plus one int for size, plus one pointer for every slot, to indicate the object stored. The number of slots is generally 1.3 to 2 times more than the number of stored mappings, at default load factor of 0.75, but may be less than this, depending on hash collisions. Every stored mapping requires an entry object. This requires one object overhead, 3 pointers, plus the stored key and value objects, plus an integer. So, putting it together (for 32/64 bit Sun HotSpot JVM):HashMap needs 24 bytes (itself, primtive fields) + 12 bytes (slot array constant) + 4 or 8 bytes per slot + 24/40 bytes per entry + key object size + value object size + padding each object to multiple of 8 bytes OR, roughly (at most default settings, not guaranteed to be precise): On 32-bit JVM: 36 bytes + 32 bytes/mapping + keys & values On 64-bit JVM: 36 bytes + 56 bytes/mapping + keys & values Note: this needs more checking, it might need 12 bytes for object overhead on 64-bit VM.I'm not sure about nulls -- pointers for nulls may be compressed somehow. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1425221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/81108/']} | jdg_78264 |
stackexchange | llm_judgeable_groundtruth_similarity | 1564478 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In any graph G=(V,E) [the hand shaking lemma] $$\sum_{v \in V} \deg(v) = 2 |E|$$ (original at http://i.stack.imgur.com/af4en.png ) where |E| donetes the number of edges I alredy tried to count to edges.For a more normal argument i used the induction on the number of edges but i came croos a problem.I could not keep doing the inductiun
Now provide the response and nothing else.
| Here's one argument you could make. Let $p=(0,0,0)$, let $S_n$ be the sphere centered at $(1/n,0,0)$, and let $H_n=\bigcup_{k\geq n} S_k$. You want to show that $\pi_1(H_1,p)$ is trivial. Given a loop in $H_1$ based at $p$, use van Kampen to show that it can be homotoped into $H_2$ (split $H_1$ as the union of a small open neighborhood $U$ of $H_2$ and a contractible open set $V$ containing most of $S_1$, and then use the fact that $U$ deformation-retracts to $H_2$). Similarly, show that for each $n$, a loop in $H_n$ based at $p$ can be homotoped into $H_{n+1}$ without leaving $H_n$. Now given a loop in $H_1$ based at $p$, construct a homotopy as follows. From $t=0$ to $t=1/2$, homotope your loop into $H_2$. From $t=1/2$ to $t=2/3$, homotope your loop into $H_3$ without leaving $H_2$. From $t=2/3$ to $t=3/4$, homotope your loop into $H_4$ without leaving $H_3$. And so on. Finally, at $t=1$, take the constant loop at $p$. This homotopy is continuous at $t=1$ since for $t>(n-1)/n$, the image of the homotopy is contained in $H_n$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1564478', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/292415/']} | jdg_78265 |
stackexchange | llm_judgeable_groundtruth_similarity | 34663173 |
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 master folder on my disk drive which contains 50 other folders. Now, I want to hide those 50 folders. I can simply right click and select "hide" attribute checkbox but I am looking for a faster way of doing this. Any recommendations? Windows 8.
Now provide the response and nothing else.
| The accepted answer presents a potential security issue. By overwriting the whole Attributes bit field, please be aware that any other attribute previously defined on your file or folder (read-only, encryption , ...) will be silently removed. Use a binary OR to prevent this behavior: Get-Item .\your_folder -Force | foreach { $_.Attributes = $_.Attributes -bor "Hidden" } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34663173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/810815/']} | jdg_78266 |
stackexchange | llm_judgeable_groundtruth_similarity | 40473609 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Problem While trying to generate sphinx documentation for a re-usable Django application I struck upon the following snafoo. When sphinx parses the model.py code it is thwarted by the code therein trying to access the Django project settings. As this is a standalone/reusable application there is not a primary project providing these settings i.e. there is no ROOT/PROJECT/PROJECT/settings.py file. Setup In the interest of clarity here is what I've done. Traverse to what would be the usual project folder cd ROOT/PROJECT and create an application django-admin startapp APPLICATION which produces the following structure /ROOT/ /PROJECT/ /APPLICATION/ admin.py apps.py models.py tests.py views.py Note : There are no /ROOT/PROJECT/PROJECT/*.py files because I did not navigate to the root folder cd root and create a project using django-admin createproject as one normally might. Next one creates the sphinx documentation spinx-quickstart docs producing the following additional structure. /ROOT/ /PROJECT/ /docs/ /source/ ... conf.py make.bat That is the docs are built next to the APPLICATION . Question What do I place within conf.py to properly load the application without there being a settings.py file ? Homework In trying to resolve this I have perused a number of SO Questions, Blogs and the Django Docs and not found a succinct solution. As this has been asked a few times before on SO I'd like to motivate that it not be closed as a duplicate, if the answer in the proposed duplicate uses one of these snippets as it's solution. Fails with AppRegistryNotReady from django.conf import settingssettings.configure() Similar to the first method of failure i.e. emits AppRegistryNotReady from django.conf import settingssettings.configure()settings.INSTALLED_APPS += ['fintech'] Fails with ImproperlyConfigured import djangodjango.setup() There is a really old solution mentioning the deprecated setup_environ from django.core.management import setup_environfrom django.conf import settingssettings.configure()setup_environ(settings) This is also a favourite answer but fails if there is no settings.py file. import djangoos.environ['DJANGO_SETTINGS_MODULE'] = 'PROJECT.settings'django.setup() I've also made this question rather verbose as the related questions on SO are rather terse and not especially helpful. If it's any help I'm using Django 1.10. Update I have since found that if one imports their setup function from setuptools versus distutils.core that one may invoke the setup script to compile their documentation as in python setup.py build_sphinx -b BUILDER It's probably best to re-ask this when invoking setup.py over docs/conf.py via either the make.bat or the MakeFile provided by Sphinx. I suspect the outcome would be similar though, namely include the provided answers within docs/conf.py or alternatively within setup.py , both must be called within the same Python session after all.
Now provide the response and nothing else.
| If you don't want to make your documentation dependent on a "demo" project, then you can manually build the settings in your conf.py . In the path setup section: import djangofrom django.conf import settingsimport osimport sys# add path to sys.path (this might be different in your project)sys.path.insert(0, os.path.abspath('..'))# pass settings into configuresettings.configure( INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_reusable_app', 'any_other_dependencies', ])# call django.setup to load installed apps and other stuffdjango.setup()# ... continue with rest of conf.py Now Sphinx can import the app modules without having a project settings.py . Other settings can be passed to settings.configure() . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40473609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/958580/']} | jdg_78267 |
stackexchange | llm_judgeable_groundtruth_similarity | 92511 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Take $n\geq 1$, and $m_{ij}\in [0,1], 1\leq i,j \leq n$. Under what conditions is it possible to find measurable subsets $X_1,...,X_n$ of, say, $[0,1]$, such that $leb(X_i\cap X_j)=m_{ij}$? Some relations are necessary, like $m_{ii}\geq m_{ij}$, or the fact that the matrix $(m_{ij})$ must be semi-definite positive, but it does not appear to be sufficient. The same question holds with $m_{ij}\in \mathbb{R}_+, X_i \subset \mathbb{R}$.
Now provide the response and nothing else.
| Here's a counterexample with $n=d=3$. Let $C$ be the rational curve $\lbrace (x,y,z) = (t,t^4,t^6) \rbrace$.Then the space $S$ of cubics that vanish on $C$ is the span of$\lbrace x^2 y - z, x^2 z - y^2, y^3 - z^2 \rbrace$.But all such cubics vanish also on the line $y=z=0$. Thereforewe can take $V$ to be the zero-locus of any two-dimensionalsubspace of $S$, and $C$ will not be cut out by the space $S$of cubics vanishing on $C$ (even though for this example we defined$V$ by a proper subspace of $S$). | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/92511', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16934/']} | jdg_78268 |
stackexchange | llm_judgeable_groundtruth_similarity | 35978797 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an object called student, with two properties, name and score. I am trying to perform calculations using the score property but am having trouble accessing the property from the array of students. Currently, I'm trying to get the sum of the scores with the following code: var sum = students.reduce(function(a, b) { return {sum: a.score + b.score} }) This returns an undefined value and causes display weirdness in firefox. I can't seem to find the error. Is there no way to just access parameters simply, (i.e. var myVar = myArray. myObject.myProperty; )?
Now provide the response and nothing else.
| I think you have a misunderstanding about how reduce works. For each element in the array, it executes the provided function. The first argument is an "accumulator"; something that's passed along as each element is visited (actually, it's the return value of the function from the last element, but it's usually used as an accumulator). The second argument is the element being visited. So what I think you want is this: var sum = students.reduce(function(a, s) { a.sum += s.score; return a;}, { sum: 0 }); When you invoke reduce , you can provide the initial value of the accumulator (otherwise it takes on the value of the first element, and the visitation starts with the second element). Here, we provide an object with a sum property set to zero. If all you want is the sum (not an object with a sum property), it can be even simpler: var sum = students.reduce(function(a, s) { return a += s.score;}, 0); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35978797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5927799/']} | jdg_78269 |
stackexchange | llm_judgeable_groundtruth_similarity | 418042 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Okay, I'm trying to ask a question which hasn't been asked before, it may be futile, but let's see. So let's take a square, this will be our shape A. We can tile a 2x1 rectangle by using shapes congruent to A. So we take 2 squares to build a 2x1 rectangle. But... now we need to go back too. Can we do so? Sure we can. So now we take the 2x1 rectangle as our shape B, and we tile shapes congruent to shape B to make shape A. Hope it's clear enough whan I'm getting at. Now, we have 2 members in this family, but in fact, this family is infinite. It also includes the 3x1 rectangle, 4x1 rectangle, and so forth. It also includes several polyominoes, like the L-tetromino and the T-tetromino. They can all be transformed into a square, and into each other. Another infinite family is composed of parallellograms. (If one would consider that as a different family) (And I suppose you could also make a distinction between rectangles and squares, since not all rectangles can be tiled into a square, since one of its sides could be an irrational number) But aside from all this, there's another, perhaps finite, family, which has the equilateral triangle as a member.This trapezium is also a member, they can be coverted into one another. https://math.stackexchange.com/questions/603586/can-you-make-an-equilateral-triangle-from-3identical-trapezoids The sphinx, made up by 6 equilateral triangles, is also a member: https://math.stackexchange.com/questions/3953136/which-equilateral-triangles-does-the-p-hexiamond-the-sphinx-tile And then there's this one, a longer sphinx, made up by 8 equilateral triangles, from a book by Karl Scherer: http://www.recmath.com/PolyPages/PolyPages/index.htm?Polyiamonds.htm So now we have a family of 4 members. Are there any other? It seems to be unknown. But what about other families? Can you find another family? I don't know any. I'm assuming that a family has to have at least 2 members.
Now provide the response and nothing else.
| Any member of a nontrivial family like this has to be a rep-tile ; looking among those will give you many examples. Some specific examples: The family of all rectifiable polyominoes, which includes all rectangles with rational ratios but also many other polyominoes, like the T-tetromino (though classifying them is a hard problem in general). While it's not inconceivable to have a set of polyominoes which mutually tile one another that aren't rectifiable, to my knowledge every known reptilic polyomino is rectifiable, so no examples are known at least. The family of all polyiamonds that can tile an equilateral triangle, which again includes those you list but also many more. Let $S$ be the set of polyominoes which tile a rectangle via only translations and $180^\circ$ rotations - this includes all rectangles of rational ratios, the L tromino, the P pentomino, and many others (though certainly not all rectifiable polyominoes). Applying any affine transformation to the members of this set preserves their ability to tile one another. The Sierpinski carpet , a domino formed from two Sierpinski carpets, and an L-tetromino formed from four Sierpinski carpets all mutually tile one another, to use one of the more fractally rep-tiles. (Many more examples in this vein are possible by subdividing the fractal at smaller scales.) The Sierpinski triangle is a member of a family along with a row of three Sierpinski triangles; here’s a diagram. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/418042', 'https://mathoverflow.net', 'https://mathoverflow.net/users/478668/']} | jdg_78270 |
stackexchange | llm_judgeable_groundtruth_similarity | 218451 |
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:
People are making a big fuss about how you absolutely have to disable SSLv3 because TLS can be downgraded to SSLv3 and there is barely a server left on the internet that speaks SSLv3. At the same time, almost every mail server out there will happily support STARTTLS, which can be trivially (like: 3 lines of code or so) downgraded to plain text . What am I missing?
Now provide the response and nothing else.
| The problem you describe is not the use of STARTTLS by itself but the optional use of STARTTLS. Mail systems can be setup so that TLS is required in which case the mail will not be delivered if STARTTLS will fail or if the peer does not offer support for STARTTLS in EHLO. Required STARTTLS is is as safe as required TLS from start. The reason STARTTLS is not mandatory in most setups is because there are still enough systems out there which don't support TLS. The current transparency report from Google shows only 90% of all mails delivered from Google by TLS, which means that 10% of the mails are delivered to an MTA which does not support TLS. Apart from that even with mandatory TLS the mail is not delivered in a sufficiently secure way. TLS is only used between the various hops during mail delivery and does not provide the end-to-end security which TLS provides in HTTPS. This means every mail server on the path has access to the plain text of the mail and can read and modify it, unless the mail is additionally protected with end-to-end protections like PGP or S/MIME. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/218451', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/81149/']} | jdg_78271 |
stackexchange | llm_judgeable_groundtruth_similarity | 30571875 |
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 is it important to pass props to super() , and why? class MyComponent extends React.Component { constructor(props) { super(); // or super(props) ? }}
Now provide the response and nothing else.
| There is only one reason when one needs to pass props to super() : When you want to access this.props in constructor. Passing: class MyComponent extends React.Component { constructor(props) { super(props) console.log(this.props) // -> { icon: 'home', … } }} Not passing: class MyComponent extends React.Component { constructor(props) { super() console.log(this.props) // -> undefined // Props parameter is still available console.log(props) // -> { icon: 'home', … } } render() { // No difference outside constructor console.log(this.props) // -> { icon: 'home', … } }} Note that passing or not passing props to super has no effect on later uses of this.props outside constructor . That is render , shouldComponentUpdate , or event handlers always have access to it. This is explicitly said in one Sophie Alpert's answer to a similar question. The documentation— State and Lifecycle, Adding Local State to a Class, point 2 —recommends: Class components should always call the base constructor with props . However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility. (Thanks @MattBrowne for the link) | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/30571875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247243/']} | jdg_78272 |
stackexchange | llm_judgeable_groundtruth_similarity | 35606551 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to format my Java 8 LocalDateTime object in "dd.MM.yyyy " pattern. Is there any library to format? I tried code below but got conversion exception. <fmt:parseDate value="${date}" pattern="yyyy-MM-dd" var="parsedDate" type="date" /> Is there any tag or converter for LocalDateTime class in JSTL?
Now provide the response and nothing else.
| It doesn't exist in the 14-year old JSTL. Your best bet is creating a custom EL function. First create an utility method. package com.example;public final class Dates { private Dates() {} public static String formatLocalDateTime(LocalDateTime localDateTime, String pattern) { return localDateTime.format(DateTimeFormatter.ofPattern(pattern)); }} Then create a /WEB-INF/functions.tld wherein you register the utility method as an EL function: <?xml version="1.0" encoding="UTF-8" ?><taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <tlib-version>1.0</tlib-version> <short-name>Custom_Functions</short-name> <uri>http://example.com/functions</uri> <function> <name>formatLocalDateTime</name> <function-class>com.example.Dates</function-class> <function-signature>java.lang.String formatLocalDateTime(java.time.LocalDateTime, java.lang.String)</function-signature> </function></taglib> Finally use it as below: <%@taglib uri="http://example.com/functions" prefix="f" %><p>Date is: ${f:formatLocalDateTime(date, 'dd.MM.yyyy')}</p> Extend if necessary the method to take a Locale argument. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35606551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1243350/']} | jdg_78273 |
stackexchange | llm_judgeable_groundtruth_similarity | 241414 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For example I'm in my directory: /home/myname and then I want to CD into a different directory. /home/pulsar/... Since I need to go pretty deep into the other directory, how can I go about this without having to type the whole line? I tried cd */thedirectoryiwanttogointo but that doesn't work. I have to type the whole line.
Now provide the response and nothing else.
| Probably your wildcard does not work because: there were no matches for the wildcard from the location you gave, or there was more than one match. The usual approach (in a shell) to moving frequently among subdirectories is to use the CDPATH feature, as well as pushd and popd . The CDPATH feature (perhaps first seen in tcsh) is a colon-separated list of directories. If the parent of your thedirectoryiwanttogointo name is reasonably unique, then you could add the parent to the list. For further reading (your shell's manual page should be first): What is CDPATH ? 3.4. Changing Directories with cd (Red Hat Enterprise Linux Step By Step Guide) How to change the CDPATH for the C shells: csh and tcsh pushd and popd are newer than CDPATH , but still dating from the mid-1990s. They allow you to save your current directory ("pushing" onto a stack) and restore it ("popping" from a stack) during their respective cd commands. For further reading: How do I use pushd and popd commands? Using pushd and popd in Linux Other people use shell aliases or symbolic links. Those are most useful when going to well-known locations. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/241414', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/142064/']} | jdg_78274 |
stackexchange | llm_judgeable_groundtruth_similarity | 462796 |
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 heard and read unclear mentions of links between projective planes and finite fields. Is it possible to construct a projective plane (or a Steiner system) starting out with a field? Could you, for example, construct the Fano plane with help of a finite field?
Now provide the response and nothing else.
| There is a difference between the projective plane as an object of algebraic geometry and as a combinatorial construction (=Steiner system) that has not been adequately explained. The former makes sense over any field - the latter only over a finite field (together with the speculations that no field may be necessary for the required construction to exist). Given any field $F$ we can construct the set $\mathbb{P}^2(F)$ in the usual way: it is the set of equivalence classes $S/\sim$ of $F^3\setminus\{(0,0,0)\}$, where two non-zero vectors $x=(x_1,x_2,x_3)$ and $y=(y_1,y_2,y_3)$ of $F^3$ are called equivalent, denoted $x\sim y$, if there is a scalar $\lambda\in F^*$ such that $y_i=\lambda x_i$ for all $i=1,2,3.$ The "points" of $\mathbb{P}^2(F)$ are equivalence classes, but to identify them we need to use coordinates. To that end we need a set of representatives - one from each equivalence class. A popular way of achieving that is to select $\lambda$ in such a way that the last non-zero coordinate is equal to $1$. After all, if $x_3\neq0$, we have (with $\lambda=1/x_3$)$$(x_1,x_2,x_3)\sim (\frac{x_1}{x_3},\frac{x_2}{x_3},1).$$We can equally well choose to scale the first non-zero coordinate to be equal to one, if so desired. If $F$ is finite, say $|F|=q$, this means that there are $q^2+q+1$ elements in $\mathbb{P}^2(F)$: $q^2$ equivalence classes with representatives $(x,y,1)$, $x,y\in F$ arbitrary. $q$ equivalence classes with representatives $(x,1,0)$, $x\in F$ arbitrary. A single equivalence class with representative $(1,0,0)$. So in a way $\mathbb{P}^2(F)$ is the union of a "usual" (affine) plane, a line and a point. If $F=\{0,1,2\}=\mathbb{Z}/3\mathbb{Z}$, then the $9+3+1=13$ elements are (the classes of) $P_1=(0,0,1)$, $P_2=(0,1,1)$, $P_3=(0,2,1)$, $P_4=(1,0,1)$,$P_5=(1,1,1)$, $P_6=(1,2,1)$, $P_7=(2,0,1)$, $P_8=(2,1,1)$, $P_9=(2,2,1)$, $P_{10}=(0,1,0)$, $P_{11}=(1,1,0)$$P_{12}=(2,1,0)$ and $P_{13}=(1,0,0)$. The equivalence relation means that we equate, for example, the point $(2,1,2)$ with $2(2,1,2)=(1,2,1)=P_6$ and the point $(1,2,0)$ with the poin $2(1,2,0)=(2,1,0)=P_{12}$. In the field of $q$ elements there are $q-1$ non-zero constants, so in general $q-1$ points of $F^3$ form a single equivalence class. These are the non-zero points of a 1-dimensional subspace of $F^3$, and a useful point of view is to think of points of $\mathbb{P}^2(F)$ as lines through the origin in $F^3$. To get the combinatorial design called the projective plane we need to also specify certain subsets of $\mathbb{P}^2(F)$, called "lines". These are constructed with the following recipe. Let $U\subset F^3$ be any 2-dimensional subspace. Then the line $L_U$ consists of the equivalence classes of the non-zero points of $U$. As $U$ is a subspace, it is closed under scalar multiplication. Therefore $U$ is a union of equivalence classes. If $|F|=q$, there are $q^2-1$ non-zero vectors in $U$, and these are divided into $(q^2-1)/(q-1)=q+1$ equivalence classes. Thus the line $L_U$ will have $q+1$ "points". Continuing the example with $F=\mathbb{Z}/3\mathbb{Z}$ we see that, if $U$ is the span of the two (linearly independent) vectors $x=(1,2,1)$ and $y=(0,1,2)$ then the non-zero points in $U$ are $x,2x=(2,1,2)$ (both in $P_6$), $y,2y=(0,2,1)$ (both in $P_3$),$x+y=(1,0,0)$, $2x+2y=(2,0,0)$ (in $P_{13}$), $x+2y=(1,1,2)$ and $2x+y=(2,2,1)$ (in $P_9$). As promised, these fell into four equivalence classes, and thus$$ L_U=\{P_6,P_3,P_{13},P_9\}.$$ You can do the same construction for all the $13$ 2-dimensional subspaces of $F^3$, and end up with $13$ lines, four points on each. Work out a few of those by hand to gain some fluidity. The characteristic combinatorial properties of this construction are: 1) any pair of lines intersects at exactly one point, 2) given any two points there is a unique line containing them. These then follow from results of linear algebra: 1) any two 2-dimensional subspaces of $F^3$ intersect in a 1-dimensional subspace, 2) any two 1-dimensional subspaces of $F^3$ span a unique 2-dimensional subspace. Hopefully this clears up some of the fog. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/462796', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43535/']} | jdg_78275 |
stackexchange | llm_judgeable_groundtruth_similarity | 245078 |
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:
My code replaces each repeated element by "X". ReplaceRepeated[{1, 2, 3, 2, 5, 2, 1, 5, 5, 2, 3, 3, 7}, {a1___, y_ /; y != #, a2___, y_, a3___} :> {a1, y, a2, #, a3}] &@"X"(*{1, 2, 3, "X", 5, "X", "X", "X", "X", "X", "X", "X", 7}*) What is the most elegant code to do this?
Now provide the response and nothing else.
| ClearAll[replaceDuplicates]replaceDuplicates[rep_: "X"] := Module[{f}, f[y_] := (f[y] = rep; y); f /@ #] & Examples: replaceDuplicates[] @ {1, 2, 3, 2, 5, 2, 1, 5, 5, 2, 3, 3, 7} {1, 2, 3, "X", 5, "X", "X", "X", "X", "X", "X", "X", 7} replaceDuplicates[Nothing] @ {1, 2, 3, 2, 5, 2, 1, 5, 5, 2, 3, 3, 7} {1, 2, 3, 5, 7} Alternatively: ClearAll[replaceDuplicates2]replaceDuplicates2[rep_: "X"] := Module[{y = #}, y[[Join @@ (Rest /@ Values @ PositionIndex[y])]] = rep; y] & Examples: replaceDuplicates2[] @ {1, 2, 3, 2, 5, 2, 1, 5, 5, 2, 3, 3, 7} {1, 2, 3, "X", 5, "X", "X", "X", "X", "X", "X", "X", 7} replaceDuplicates2[Nothing] @ {1, 2, 3, 2, 5, 2, 1, 5, 5, 2, 3, 3, 7} {1, 2, 3, 5, 7} | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/245078', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/53172/']} | jdg_78276 |
stackexchange | llm_judgeable_groundtruth_similarity | 423147 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is a picture of a circuit I built. I'm a novice in building amplifiers, but I'm interested in building a simple circuit that picks up music using a condenser microphone and transmits it across some distance using cable with headphones attached to the other end. The output is taken from the emitter of the Q3 transistor. There is a simple audio pre-amplifier that I found online, connected through C2 capacitor to a common emitter amplifier of my design, which in turn is connected to transistor Q3 serving as a current buffer. Again, I have little to no experience in building audio circuits, so I just put together what I thought would work. The circuit does work: When I play music from a phone near the mic, the music can be heard from the headphones in another room (I connected a long wire to the output, across R8 resistor). There is a lot of noise though. The sound is clear enough so that I can hear the lyrics, but quite barely. I would like to hear suggestions on how to improve this circuit. The sound quality does not have to be good at all, but I'm would very much like to hear what I'm doing wrong. The CE amp has quite a high gain which I thought might lead to clipping so I've tried to limit its gain by inserting an additional resistor in series with C1 capacitor and it has helped a little, but not much. Rather than pointing me to another, more advanced circuit, I would like to hear what is wrong with this one and how to possibly improve it. I've tried finding information on Google, but most sources deal with reducing noise on professional, bought audio amplifiers instead of simple electrical circuits. EDIT: There was a mistake in my circuit schematic. EDIT: Here is a picture of the headphones.
Now provide the response and nothing else.
| It depends what sort of noise you're talking about. I suspect, given the configuration of Q3, that you're getting a very distorted output because Q3 is not biased to work in its linear region. Imagine something like a 2V p-p sinewave coming through C4. Q3 won't begin to conduct until that signal goes above 0.6V or so, and it won't conduct at all below that - including throughout the negative half of the cycle. What you'll end up with going into your headphones is a sort of square wave with a round top - a massively distorted version of your original signal. The base of Q3 would need to be biased to at least 1.6V in order to achieve the desired output. Obviously that will introduce a DC component to the output, so as stated in the comments you will need a coupling capacitor in series with your headphones to remove that. You might want to consider a push-pull output stage - read up on class AB amplifiers. You might also want to investigate some of the free online circuit simulators: you can feed your circuit with a test waveform and look at points around it with a virtual oscilloscope. It'll become painfully obvious where the problems lie. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/423147', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/142915/']} | jdg_78277 |
stackexchange | llm_judgeable_groundtruth_similarity | 40501780 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been trying to learn how delegation with protocols work. I understood everything, but I can't think of when to use delegation other than when using table views and possibly scroll views. In general, when is delegation used?
Now provide the response and nothing else.
| What is Delegation? First of all, you should know that Delegation Pattern is not exclusive for iOS world: In software engineering, the delegation pattern is a design pattern in object-oriented programming that allows object composition to achieve the same code reuse as inheritance. But working with delegation in the iOS world is so common, I assume that you can see many of classes that provide a delegation/datasource for giving the ability to provide properties or behaviors for the used instance. It is one of main mechanisms of how objects talk to each other in CocoaTouch. Alternatives: However, delegation is not the only way to let objects talk to each other in iOS, you might want to know that there are: NotificationCenter . KVO (Key-Value Observing) . Completion handlers/Callbacks (using closures) . Target-Action . Remark : in case if you are interested in comparing between them, you might want to check the following articles: Communication Patterns. When to Use Delegation, Notification, or Observation in iOS. Delegates vs Observers. When to use Delegation? So, the question is: "So why should I use delegation instead of those options?" I will try to make it simple; I would suggest the use of delegation when you have one to one relationship between two objects. Just to make it clearer, the goal of talking a little bit about the NotificationCenter is to try to make sense when delegations are used: NotificationCenter represents one to many relationship; Simply, it works as: posting (notifying) a notification on a specific event and observing (get notified about) this notification -- it could be observed anywhere else; Logically, that's what one to many relationship means. It is a representation of the Observer Pattern . How to Apply Delegation? For the purpose of simplifying, I would mention it as steps: Knowing the requirements: Each delegate has its own rules , listed in the delegate protocol which is a set of method signatures that you should implement for conforming this delegation. Conforming for the delegation: it is simply letting your class to be a delegate, by marking it. For instance: class ViewController: UIViewController, UITableViewDelegate {} . Connecting the delegate object: Marking your class to be a delegate is not enough, you need to make sure that the object you want to be confirmed by your class to give the required job to your class. Implementing the requirements: Finally, your class have to implement all required methods listed in the delegate protocol. For Example Does it sounds a little confusing? What about a real-world example? Consider the following scenario: Imagine that you are building an application related to playing audios. Some of the viewControllers should have a view of an audio player . In the simplest case, we assume that it should have a play/pause button and another button for, let's say, showing a playlist somehow, regardless of how it may look like. So far so good, the audio player view has its separated UIView class and .xib file; it should be added as a subview in any desired viewController. Now, how can you add functionality to both of the buttons for each viewController? You might think: "Simply, I will add an IBAction in the view class and that's it", at first look, it might sound ok, but after re-thinking a little bit, you will realize that it will not be applicable if you are trying to handle the event of tapping the button at the controller layer; To make it clear, what if each viewController implemented different functionality when tapping the buttons in the audio player view? For example: tapping the playlist in "A" viewController will display a tableView, but tapping it in the "B" viewController will display a picker. Well, let's apply Delegation to this issue: The "#" comments represents the steps of "How to Apply Delegation?" section. Audio Player View: // # 1: here is the protocol for creating the delegationprotocol AudioPlayerDelegate: class { func playPauseDidTap() func playlistDidTap()}class AudioPlayerView: UIView { //MARK:- IBOutlets @IBOutlet weak private var btnPlayPause: UIButton! @IBOutlet weak private var btnPlaylist: UIButton! // MARK:- Delegate weak var delegate: AudioPlayerDelegate? // IBActions @IBAction private func playPauseTapped(_ sender: AnyObject) { delegate?.playPauseDidTap() } @IBAction private func playlistTapped(_ sender: AnyObject) { delegate?.playlistDidTap() }} View Controller: class ViewController: UIViewController { var audioPlayer: AudioPlayerView? // MARK:- Life Cycle override func viewDidLoad() { super.viewDidLoad() audioPlayer = AudioPlayerView() // # 3: the "AudioPlayerView" instance delegate will implemented by my class "ViewController" audioPlayer?.delegate = self }}// # 2: "ViewController" will implement "AudioPlayerDelegate":extension ViewController: AudioPlayerDelegate { // # 4: "ViewController" implements "AudioPlayerDelegate" requirments: func playPauseDidTap() { print("play/pause tapped!!") } func playlistDidTap() { // note that is should do a different behavior in each viewController... print("list tapped!!") }} Quick Tip: As one of the most popular examples of using delegation is Passing Data Back between View Controllers. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40501780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6616619/']} | jdg_78278 |
stackexchange | llm_judgeable_groundtruth_similarity | 1962980 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to select only certain rows from a NumPy array based on the value in the second column. For example, this test array has integers from 1 to 10 in the second column. >>> test = numpy.array([numpy.arange(100), numpy.random.randint(1, 11, 100)]).transpose()>>> test[:10, :]array([[ 0, 6], [ 1, 7], [ 2, 10], [ 3, 4], [ 4, 1], [ 5, 10], [ 6, 6], [ 7, 4], [ 8, 6], [ 9, 7]]) If I wanted only rows where the second value is 4, it is easy: >>> test[test[:, 1] == 4]array([[ 3, 4], [ 7, 4], [16, 4], ... [81, 4], [83, 4], [88, 4]]) But how do I achieve the same result when there is more than one wanted value? The wanted list can be of arbitrary length. For example, I may want all rows where the second column is either 2, 4 or 6: >>> wanted = [2, 4, 6] The only way I have come up with is to use list comprehension and then convert this back into an array and seems too convoluted, although it works: >>> test[numpy.array([test[x, 1] in wanted for x in range(len(test))])]array([[ 0, 6], [ 3, 4], [ 6, 6], ... [90, 2], [91, 6], [92, 2]]) Is there a better way to do this in NumPy itself that I am missing?
Now provide the response and nothing else.
| test[numpy.logical_or.reduce([test[:,1] == x for x in wanted])] The result should be faster than the original version since NumPy's doing the inner loops instead of Python. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1962980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422778/']} | jdg_78279 |
stackexchange | llm_judgeable_groundtruth_similarity | 70587978 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to delete it.But it won't be deleted.If you click the delete text in the modal, it should be deleted, but it doesn't work.What should I do to delete it?There's an error saying that onRemove is not a function.Please help me. I want to delete it.But it won't be deleted.If you click the delete text in the modal, it should be deleted, but it doesn't work.What should I do to delete it?There's an error saying that onRemove is not a function.Please help me. export default function Modal({ onRemove, id }) { return ( <OptionModalWrap> <ModalWrapper> <TitleWrap>Edit</TitleWrap> <TitleWrap>Duplicate</TitleWrap> <DeleteText onClick={() => onRemove(id)}>Delete</DeleteText> </ModalWrapper> </OptionModalWrap> );} export default function GroupList({ title, onRemove }) { const [showModal, setShowModal] = useState(false); const optionModal = () => { setShowModal(prev => !prev); }; return ( <AdGroups> <Header> <Container> <ActiveWrap> <ActiveIcon src={Active} /> <SubTitle>Active</SubTitle> </ActiveWrap> <Alaram> <Bell src={bell} /> <Text className="alarmCount">10</Text> </Alaram> </Container> <EtcIconWrap> <EtcIcon src={plus} onClick={optionModal} /> {showModal && ( <OptionModal showModal={showModal} onRemove={onRemove} /> )} </EtcIconWrap> </Header> <GroupTitle>{title}</GroupTitle> </AdGroups> );} export default function GroupPage() { const [Groupdata, setGroupData] = useState([]); const onRemove = item => { setGroupData(Groupdata.filter(item => item.id !== item)); }; useEffect(() => { fetch('./data/AdsGroup/AdsGroupList.json') .then(res => res.json()) .then(res => setGroupData(res)); }, []); return ( <GroupPages> {Groupdata.map(item => { return ( <GroupList key={item.id} title={item.title} onRemove={onRemove} /> ); })} </GroupPages> );}
Now provide the response and nothing else.
| The official doc to use brew install. $ brew install hdf5 If the above command gives you rosetta 2 issue, then run:- arch -arm64 brew install hdf5 Once, the h5py installation is done, run following 2 commands:- $ export HDF5_DIR=/opt/homebrew/Cellar/hdf5/1.12.0_4 OR export HDF5_DIR=/opt/homebrew/opt/hdf5 (if hdf5 is installed in the "/opt/homebrew/opt/hdf5" location, you have to check it out first)$ pip install --no-binary=h5py h5py Note:- in the first command "1.12.0_4" is the version of hdfc installed in my system, you have to change it according to yours. If you are getting the aforementioned error implies you must be using poetry. Finally run:- poetry install We are running the above command, In case poetry wants to update anything. Once we run poetry install , it might update existing libraries or download new libraries. So we have to update poetry.lock file as well. poetry lock | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70587978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17635677/']} | jdg_78280 |
stackexchange | llm_judgeable_groundtruth_similarity | 7916834 |
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 created an RSS reader that lists items in a listview. I also want a date below each item, but I have no idea how to do that. I need someone's help to make the Sub Item text display the pubDate that was retrieved from the RSS feed. This is the code I have for my class: public class RSSReader extends Activity implements OnItemClickListener{ public final String RSSFEEDOFCHOICE = "http://app.calvaryccm.com/mobile/android/v1/devos"; public final String tag = "RSSReader"; private RSSFeed feed = null; /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); // go get our feed! feed = getFeed(RSSFEEDOFCHOICE); // display UI UpdateDisplay(); } private RSSFeed getFeed(String urlToRssFeed) { try { // setup the url URL url = new URL(urlToRssFeed); // create the factory SAXParserFactory factory = SAXParserFactory.newInstance(); // create a parser SAXParser parser = factory.newSAXParser(); // create the reader (scanner) XMLReader xmlreader = parser.getXMLReader(); // instantiate our handler RSSHandler theRssHandler = new RSSHandler(); // assign our handler xmlreader.setContentHandler(theRssHandler); // get our data via the url class InputSource is = new InputSource(url.openStream()); // perform the synchronous parse xmlreader.parse(is); // get the results - should be a fully populated RSSFeed instance, or null on error return theRssHandler.getFeed(); } catch (Exception ee) { // if we have a problem, simply return null System.out.println(ee.getMessage()); System.out.println(ee.getStackTrace()); System.out.println(ee.getCause()); return null; } } public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, 0, 0, "Refresh"); Log.i(tag,"onCreateOptionsMenu"); return true; } public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { case 0: Log.i(tag,"Set RSS Feed"); return true; case 1: Log.i(tag,"Refreshing RSS Feed"); return true; } return false; } private void UpdateDisplay() { TextView feedtitle = (TextView) findViewById(R.id.feedtitle); TextView feedpubdate = (TextView) findViewById(R.id.feedpubdate); ListView itemlist = (ListView) findViewById(R.id.itemlist); if (feed == null) { feedtitle.setText("No RSS Feed Available"); return; } if(feedtitle != null) feedtitle.setText(feed.getTitle()); if(feedpubdate != null) feedpubdate.setText(feed.getPubDate()); ArrayAdapter<RSSItem> adapter = new ArrayAdapter<RSSItem>(this,android.R.layout.simple_list_item_1,feed.getAllItems()); itemlist.setAdapter(adapter); itemlist.setOnItemClickListener(this); itemlist.setSelection(0); } @Override public void onItemClick(AdapterView parent, View v, int position, long id) { //Log.i(tag,"item clicked! [" + feed.getItem(position).getTitle() + "]"); Intent itemintent = new Intent(this,ShowDescription.class); Bundle b = new Bundle(); b.putString("title", feed.getItem(position).getTitle()); b.putString("description", feed.getItem(position).getDescription()); b.putString("link", feed.getItem(position).getLink()); b.putString("pubdate", feed.getItem(position).getPubDate()); itemintent.putExtra("android.intent.extra.INTENT", b); startActivity(itemintent); }} This is my XML: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Android RSSReader"android:id="@+id/feedtitle"/><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text=""android:id="@+id/feedpubdate"/><ListViewandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:id="@+id/itemlist"android:fastScrollEnabled="true"/> </LinearLayout> This is what it looks like now in Eclipse: This is what it looks like running: How to make the Sub Item text display the pubDate that was retrieved from the RSS feed?
Now provide the response and nothing else.
| The simplest solution is probably to substitute the ArrayAdapter and the android.R.layout.simple_list_item_1 that you are using with a SimpleAdapter and the android.R.layout.simple_list_item_2 predefined layout. This layout is composed by two TextView s, with an id of android.R.id.text1 (the "item") and android.R.id.text2 (the "sub item") respectively, which you will need as a reference for the SimpleAdapter to work. By looking at the constructor for SimpleAdapter you will notice that, apart from a Context instance and the id of a layout resource, it takes three parameters that may be new to you: a List<? extends Map<String, ?>> instance where you put the elements you want the ListView to show. Elements are in the form of a Map , i.e. something akin to a struct composed by properties in form of name/value pairs. For example, you may use "title" and "date" as keys for the title and date of each RSS item, respectively. an array of strings, where to put the names of the keys in each map that you want to show on the ListView . an array of integers where you need to put the ids of the parts in the list item view where you want the single elements referenced by the keys in the preceding array of strings to be shown. For example, if you want to show the title and date of a RSS item in the "item" and "sub item" views respectively, you use new String[] { "title", "date" } as the array of strings argument, and new int[] { android.R.id.text1, android.R.id.text2 } as this argument. A rough code example, just to give you the idea: List<Map<String, String>> data = new ArrayList<Map<String, String>>();for (RSSItem item : feed.getAllItems()) { Map<String, String> datum = new HashMap<String, String>(2); datum.put("title", item.getTitle()); datum.put("date", item.getDate().toString()); data.add(datum);}SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"title", "date"}, new int[] {android.R.id.text1, android.R.id.text2});itemList.setAdapter(adapter); The documentation states that "the maps contain the data for each row, and should include all the entries specified in the from parameter", so both title and date should always be present. Please note that this is all off the top of my head. I haven't actually tested all the code, so you may very well encounter some quirk or bug that you need to adjust or fix on your way up. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7916834', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/616454/']} | jdg_78281 |
stackexchange | llm_judgeable_groundtruth_similarity | 443187 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that $\frac{1}{\sqrt{\mu_0\varepsilon_0}}$ is equal to the speed of light but is this prediction accurate? I mean is it 100 percent accurate?
Now provide the response and nothing else.
| I'm not sure exactly what question you are asking, but it seems to me that the answers that referred to units and definitions of distance and time (e.g. in the SI system) may be missing what the question is. In the back-up question mentioned as a comment, you ask "does it agree with experiment 100%?" Well no experiment gets 100% precision. The most one can ever say is "it is consistent with all experiments that have been performed, and the best precision attained so far is ...". If your question is: "is it the case that electromagnetic waves are fully and correctly described by classical electromagnetism?" then the answer is no, because classical electromagnetism is not quite the same as our best understanding of these fields. Our best understanding is offered by quantum field theory and general relativity, and even those are probably not the whole story. Let me flesh this out a little. In classical electromagnetism, we can measure $\epsilon_0$ by doing static experiments with things like capacitors, and we can measure $\mu_0$ by doing experiments with things like electrical inductors. If someone says those constants have defined values, then such experiments serve as a way of relating field measurements to other properties such as current and charge. Having done all that, we can then measure the speed of electromagnetic waves in vacuum. Within the theoretical model offered by classical electromagnetism , the answer to your question is that, yes, electromagnetic waves in empty space do propagate at exactly $1/\sqrt{\epsilon_0 \mu_0}$ , and you can, if you like, regard this as a good way to define $\epsilon_0$ once $c$ and $\mu_0$ have been given their defined values. However, the physical world does not behave exactly as this theoretical model suggests. Among other effects that complicate the picture are that bright enough light waves will interact with one another in complex ways, owing to their interaction with the Dirac field which describes electrons and positrons. Also, they will cause spacetime curvature. Even the field between the plates of a static capacitor is not nearly as simple as the classical theory suggests (though the corrections are very small in ordinary circumstances). In the modern understanding based on quantum field theory and general relativity, light in otherwise empty space does move at the special maximum speed, but the fields are no longer fully specified by equations involving just $\epsilon_0$ and $\mu_0$ (in addition to the fields themselves), so the answer to your question is something like "well, $\epsilon_0$ and $\mu_0$ don't exactly capture the physics of these fields, so the answer has to be 'no'". | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/443187', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/210956/']} | jdg_78282 |
stackexchange | llm_judgeable_groundtruth_similarity | 16678929 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Inline blocks have this weird space in-between them. I could live with it, up to a point where, if I load more content with an AJAX call, the tiny space goes away. I know I'm missing something here. div { width: 100px; height: auto; border: 1px solid red; outline: 1px solid blue; margin: 0; padding: 0; display: inline-block;} http://jsfiddle.net/AWMMT/ How to make the spacing consistent in Inline blocks?
Now provide the response and nothing else.
| The space is in the HTML. There are several possible solutions. From best to worst: Remove the actual space in the HTML (ideally your server could do this for you when the file is served, or at least your input template could be spaced appropriately) http://jsfiddle.net/AWMMT/2/ Use float: left instead of display: inline-block , but this has undesirable effects on t he height: http://jsfiddle.net/AWMMT/3/ Set the container's font-size to 0 and set an appropriate font-size for the internal elements: http://jsfiddle.net/AWMMT/4/ -- this is pretty simple, but then you can't take advantage of relative font size rules on the internal elements (percentages, em) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16678929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/853685/']} | jdg_78283 |
stackexchange | llm_judgeable_groundtruth_similarity | 402067 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm talking about Banksy's "Girl with balloon" painting that shredded itself at auction. I think the general consensus is that he didn't, and that it was set up before the auction (or a couple years ago, not 12 years). But lets say he did, how could he have made it keep its power for that long? What sorts of RF receivers run on such low power? What batteries can withstand a 12 year low-but-constant-load life?
Now provide the response and nothing else.
| A relatively large lithium primary cell would be my choice. They are specified for something like 10 or 20 year life running water meters, including periodic radio communication. And maybe a second cell to run the motor so it stays relatively fresh. The Israeli company Tadiran makes such products. As long as the temperature does not get too high the shelf-ish life of such Lithium cells is in the decades (they claim 40 year operating life). You can bet that an expensive piece of art will be kept in carefully controlled temperature and humidity conditions. Given that power source, power management would be important but not crazy critical. You would want to keep the average draw in the << 100uA range most likely. Doing the sums, their 19AH TL-4930 works out to 54uA (average) for 40 years. So even if it turned on a receiver once per 10 minutes for a second it could draw tens of mA, provided the sleep mode power was inconsequential. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/402067', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/116803/']} | jdg_78284 |
stackexchange | llm_judgeable_groundtruth_similarity | 52921 |
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 continuing to work through permutations and combinations and my book has the following question: A box contains 9 red, 4 blue, and 6 yellow chips. In how many ways can 6 chips be chosen if: a) all 6 chips are red b) all 6 chips are yellow c) 2 chips are blue I had no problem answering a) and b); however c) is stumping me. The answer, according to the text, is 8,190 however I can't figure out how they're arriving at that number. I thought it would be:$$(19\cdot 18\cdot 17\cdot 16/4!)/2! = \frac{19\cdot 18\cdot 17\cdot 16}{4!\cdot 2!}$$but that returns $1938$, not $8,190$. At this point in the text we've only covered the Permutation and Combination formulas: nPr and nCr. Help?
Now provide the response and nothing else.
| The number of ways of choosing 2 blue out of 4 is $\binom{4}{2}.$ After that you have 4 chips remaining which can be chosen from either 9 red or 6 yellow or both. So you are choosing 4 chips from $9 + 6 =15$ chips.Putting all together, you get $$\binom{4}{2}\binom{15}{4}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/52921', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13439/']} | jdg_78285 |
stackexchange | llm_judgeable_groundtruth_similarity | 26613459 |
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 related to this question converting to declarative method and column property , which has never been answered. We are trying to set up a Flask-SQLAlchemy project on an existing schema (one we cannot change), and decided on the declarative syntax so that we can organize the classes into multiple files in a sane way for maintenance. This works for most of our relationships except for something that we call, for lack of a better term, attribute tables. These are one-to-one leaf tables off some primary object, and typically contain some kind of controlled vocabulary for the attribute. The goal in the ORM is to map all of these (of which there are many) types of tables as if they were properties of the primary table. Here is an SQA example with two tables: class MarkerType(db.Model): __tablename__="mrk_types" _marker_type_key = db.Column(db.Integer,primary_key=True) name = db.Column(db.String())class Marker(db.Model): __tablename__="mrk_marker" _marker_key=db.Column(db.Integer,primary_key=True) _marker_type_key=db.Column(db.Integer()) We want to access MarkerType.name as if we were saying Marker.markertype, or in a query as Marker.markertype=='thing'. The only way I could manage that is with a column_property in the Marker class, like so: markertype = db.column_property( db.select([MarkerType.name]). where(MarkerType._marker_type_key==_marker_type_key) ) However, I cannot seem to find how to do this in a declarative way, and maybe that way does not exist. Is there a sane way I can achieve this without having to worry about my imports, or even worse the order of my classes? Since we have hundreds of tables to map, I can see this being a maintenance nightmare if we have to worry about class and import order. If all of this is totally impossible, wishful thinking, what is a better approach to mapping these tables?
Now provide the response and nothing else.
| This sounds like an excellent use case for the Association Proxy . This proxies a field of a related model. In this case the implementation would be: from sqlalchemy.orm import relationshipfrom sqlalchemy.ext.associationproxy import association_proxyclass MarkerType(db.Model): __tablename__="mrk_types" _marker_type_key = db.Column(db.Integer, primary_key=True) name = db.Column(db.String())class Marker(db.Model): __tablename__="mrk_marker" _marker_key=db.Column(db.Integer,primary_key=True) _marker_type_key=db.Column(db.Integer, ForeignKey('mrk_types._marker_type_key') mt = relationship(MarkerType, uselist=False) marker_type = association_proxy('mt', 'name') This allows querying like session.query(Marker).filter_by(marker_type='my_marker_type') The marker_type field is a proxy of the name field on the MarkerType object. That object can be referenced by the mt field (the relationship field) Note the uselist=False . This indicates that each Marker has 1 marker type. The relationship automatically detects the ForeignKey and uses it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26613459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3677281/']} | jdg_78286 |
stackexchange | llm_judgeable_groundtruth_similarity | 20034415 |
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 lot of daily backup archives. To manage disk usage, I need a bash script that will delete all files older than 1 month, but keep all files created on Mondays, even if they are older than 1 month. For example, this will delete all files last modified more than 30 days ago: find /path/to/files* -type f -mtime +30 -delete But I don't really know how to keep files created on Mondays.
Now provide the response and nothing else.
| Slightly simpler and more cautious version of @JoSo's answer: find /path/to/files -type f -mtime +30 \ -exec sh -c 'test $(date +%a -r "$1") = Mon || echo rm "$1"' -- {} \; The differences: Using date -r to get the last modification date of a file directly Using %a to work with more comprehensible weekday names Just echo the rm "$1" first to review what will be deleted. If looks good, then either stick | sh at the end to really execute, or remove the echo However, @JoSo is right to point out that date +%a is locale dependent, so these versions would be indeed safer: find /path/to/files -type f -mtime +30 \ -exec sh -c 'test $(date +%u -r "$1") = 1 || echo rm "$1"' -- {} \;find /path/to/files -type f -mtime +30 \ -exec sh -c 'test $(LC_TIME=C date +%a -r "$1") = Mon || echo rm "$1"' -- {} \; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20034415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1650332/']} | jdg_78287 |
stackexchange | llm_judgeable_groundtruth_similarity | 23665056 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
here is my code : angular.module('option') .factory('optionListService', ['$resource', function($resource) { return $resource(HOST+'option/action/:id', {}, { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} }); }]); and this work for GET requests and not for POST ! I'm using Apache as a server and configured it with : <Limit GET HEAD POST PUT DELETE OPTIONS> Order Allow,Deny Allow from all </Limit>Header set Access-Control-Allow-Origin "*" and in my angularjs I include in config of module app: delete $httpProvider.defaults.headers.common['X-Requested-With'];delete $httpProvider.defaults.headers.post['Content-type']; but the request POST still not working !! I hope that someone can give any idea.
Now provide the response and nothing else.
| Add those headers on the server side: Access-Control-Request-Headers: X-Requested-With, accept, content-typeAccess-Control-Allow-Methods: GET, POST If still not working post the details of the preflight OPTIONS request which the browser is sending. Why is this required? If it is not a simple request (e.g. GET or POST of form data) the browser sends a preflight HTTP OPTIONS request to the server to check if CORS is allowed. This request contains some Access-Control-Request headers (can differ based on the specific request): Access-Control-Request-Headers: accept, content-typeAccess-Control-Request-Method: POST Now it is important that the server references the same Access-Control-Allow header in the response: Access-Control-Allow-Headers: accept, content-typeAccess-Control-Allow-Methods: POSTAccess-Control-Allow-Origin: * Otherwise the request is rejected by the browser. @ilyas : finaly after 3hours of reseach I sovelved this problem //Part added by ilyas : if (isset($_SERVER['HTTP_ORIGIN'])) { header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day }//End of part. I hope this help others. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23665056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2822643/']} | jdg_78288 |
stackexchange | llm_judgeable_groundtruth_similarity | 63304115 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i have 3 table in my database CREATE TABLE IF NOT EXISTS depances ( id SERIAL PRIMARY KEY UNIQUE NOT NULL, type VARCHAR NOT NULL, nom VARCHAR, montant DECIMAL(100,2) NOT NULL, date DATE, temp TIME)CREATE TABLE IF NOT EXISTS transactions ( id SERIAL PRIMARY KEY UNIQUE NOT NULL, montant DECIMAL(100,2), medecin VARCHAR, patient VARCHAR, acte VARCHAR, date_d DATE, time_d TIME, users_id INTEGER) CREATE TABLE IF NOT EXISTS total_jr ( id SERIAL PRIMARY KEY UNIQUE NOT NULL, total_revenu DECIMAL(100,2), total_depance DECIMAL(100,2), total_différence DECIMAL(100,2), date DATE) my idea is to insert defrent value in table depances and transaction using a GUI interface.and after that adding the SUM of montant.depances in total_depance.total_jrand the SUM of montant.transactions in total_revenu.total_jr where all rows have the same timethat's the easy part using this code self.cur.execute( '''SELECT SUM(montant) AS totalsum FROM depances WHERE date = %s''',(date,)) result = self.cur.fetchall() for i in result: o = i[0] self.cur_t = self.connection.cursor() self.cur_t.execute( '''INSERT INTO total_jr(total_depance) VALUES (%s)''' , (o,)) self.connection.commit() self.cur.execute( '''UPDATE total_jr SET total_depance = %s WHERE date = %s''',(o, date)) self.connection.commit() But every time it adds a new row to the table of total_jr How can i add thos value of SUM(montant) to the table where the date is the same every time its only put the value of sum in one row not every time it add a new rowThe result should will be like this id|total_revenu|total_depance|total_différence|date--+------------+-------------+----------------+----1 sum(montant1) value value 08/07/20202 sum(montant2) value value 08/09/20203 sum(montant3) value value 08/10/2020 but it only give me this result id|total_revenu|total_depance|total_différence|date--+------------+-------------+----------------+----1 1 value value 08/07/20202 2 value value 08/07/20203 3 value value 08/7/2020 if there is any idea or any hit that will be hulpefull
Now provide the response and nothing else.
| I added a demo of what you are trying to get (I followed the Image you posted): NOTE : I had to make few changes to the way you arranged your widget tree. class profilePage extends StatefulWidget { @override profilePageState createState() => profilePageState();}class profilePageState extends State<profilePage> { @override Widget build(BuildContext context) { return DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( title: Text( 'My Profile', ), centerTitle: true, backgroundColor: Colors.grey[700].withOpacity(0.4), elevation: 0, // give the app bar rounded corners shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(20.0), bottomRight: Radius.circular(20.0), ), ), leading: Icon( Icons.menu, ), ), body: Column( children: <Widget>[ // construct the profile details widget here SizedBox( height: 180, child: Center( child: Text( 'Profile Details Goes here', ), ), ), // the tab bar with two items SizedBox( height: 50, child: AppBar( bottom: TabBar( tabs: [ Tab( icon: Icon(Icons.directions_bike), ), Tab( icon: Icon( Icons.directions_car, ), ), ], ), ), ), // create widgets for each tab bar here Expanded( child: TabBarView( children: [ // first tab bar view widget Container( color: Colors.red, child: Center( child: Text( 'Bike', ), ), ), // second tab bar viiew widget Container( color: Colors.pink, child: Center( child: Text( 'Car', ), ), ), ], ), ), ], ), ), ); }} OUTPUT: | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/63304115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13491580/']} | jdg_78289 |
stackexchange | llm_judgeable_groundtruth_similarity | 253868 |
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:
If so, is trying to exploit through a time-based injection enough to prove there's a vulnerability in said site?
Now provide the response and nothing else.
| As stated, the answer to the question is "certainly not", HTTP 500 Internal Server Error is used by pretty much every web server in the world for any uncaught exception, which could be anything from a divide-by-zero to a null pointer dereference to an out-of-memory. It could even be from a database connection without meaning there's a SQLi vulnerability; maybe the developer has a typo in their procedure name or a function sometimes tries to insert a null in a non-optional column. In the specific case that you were attempting SQLi against the server, it's certainly evidence. You'd still want to verify it in a few ways (do queries without any SQL metacharacters always work? Do those with metacharacters always either fail or "work" in a way consistent with the injection?) but it's probably worth trying a few more things, including time-based attacks. However, if a time-based attack attempt just returns a 500 without actually delaying or anything, then you haven't succeeded in an attack, you've just sent a request the developer didn't anticipate and handle correctly by sending a 400 instead. If you want to prove there's a vulnerability, you have to actually exploit it. Get an actual delay, or return an extra value, or log in as the wrong user, or insert spurious data, or whatever. HTTP 500 is literally just "an unspecified error occurred" and doesn't prove anything at all (maybe a passing cosmic ray flipped a bit that caused the exception and it didn't have anything to do with your request at all...). EDIT: Since apparently this isn't clear: a server can also return 500 Internal Server Error (or anything else) in response to any request, at the whim of its programmer. It's just bits on a wire, data sent by a program to a network socket. The spec says it's a catch-all for errors where something went wrong while processing the request and it wasn't a recognized client error, and it's the default response when there's an uncaught exception (though that too can be overridden), but web developers sometimes send it for other situations too. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/253868', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/264122/']} | jdg_78290 |
stackexchange | llm_judgeable_groundtruth_similarity | 13221504 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need vbscript to iterate files through files and find all files which are created today. DateDiff("d",RFile.DateLastModified ,Date)=0 I can see there are 40 files in the folder for today but when the script scans though all files, it lists files less than 40. Maybe it is also looking at the time portion. Can anyone tell me exactly how to use the datediff function so that I can achieve the desired. I want it to get all files whose DATE portion is today's date portion without any consideration for the time portion.
Now provide the response and nothing else.
| Yeah. Ive got a nifty trick for you. Instead of having your red outlined view a scrollview make it a normal UIView that fills the screen. In that view lay out your scroll view (table view) and image view as they are in your illustration. Place a scrollview that fills the bounds of the root view (i.e. also fills the screen) above all the other scrollview and image views. Set the content size of this view to be the total content height of all the views you want to scroll through. In otherwords there is an invisible scrollview sitting on top of all your other views and its content size height is inner scrollview (tableview) content size height + image view size height. The heierarchy should look like this: Then this scrollview on top that you have made with the really tall content size make its delegate be your view controller. Implement scrollViewDidScroll and we'll work some magic. Scrollviews basically scroll by adjusting the bounds origin with funky formulas for momentum and stuff. So in our scrollviewDidScroll method we will simply adjust the bounds of the underlying views: -(void)scrollViewDidScroll:(UIScrollView *)scrollView{ //the scroll view underneath (in the container view) will have a max content offset equal to the content height //but minus the bounds height CGFloat maxYOffsetForUnderScrollView = self.underScrollView.contentSize.height - self.underScrollView.bounds.size.height; CGRect scrolledBoundsForContainerView = self.view.bounds; if (scrollView.contentOffset.y <= maxYOffsetForUnderScrollView) { //in this scenario we are still within the content for the underScrollView //so we make sure the container view is scrolled to the top and set the offset for the contained scrollview self.containerView.bounds = scrolledBoundsForContainerView; self.underScrollview.contentOffset = scrollView.contentOffset; return; } //in this scenario we have scrolled throug the entirety of the contained scrollview //set its offset to the max and change the bounds of the container view to scroll everything else. self.underScrollView.contentOffset = CGPointMake(0, maxYOffsetForUnderScrollView); scrolledBoundsForContainerView.origin.y = scrollView.contentOffset.y - maxYOffsetForUnderScrollView; self.containerView.bounds = scrolledBoundsForContainerView;} You will find that as scrollViewDidScroll is called every frame of animation that this faux scrolling of the contained views looks really natural. But wait! I hear you say. That scroll view on top now intercepts ALL touches, and the views underneath it need to be touched as well. I have an interesting solution for that as well. Set the scrollview on top to be off screen somewhere (i.e. set its frame off screen, but still the same size.) and then in your viewDidLoad method you add the scrollview's panGestureRecogniser to the main view. This will mean that you get all the iOS natural scrolling momentum and stuff without actually having the view on the screen. The contained scroll view will now probably go juddery as its pan gesture recognizer will get called as well (they work differently to UIEvent handling) so you will need to remove it. - (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self.view addGestureRecognizer:self.scrollview.panGestureRecognizer]; [self.underScrollview removeGestureRecognizer:self.underScrollView.panGestureRecognizer]; //further code to set up content sizes and stuff} I had fun making this so heres a link to the sample project on github: https://github.com/joelparsons/multipleScrollers EDIT: To show the scrollbar for the top scrollview when its off the screen no matter where you put it you can set the scrollIndicatorInsets to an inset created like this: CGPoint scrollviewOrigin = self.scrollview.frame.origin;self.scrollview.scrollIndicatorInsets = UIEdgeInsetsMake(-scrollviewOrigin.y,0,scrollviewOrigin.y,scrollviewOrigin.x); *caveat that the scrollview still has to be the right height but I'm sure you get the idea. And then to make the bar draw outside the scrollview's visible bounds you have to turn off clips to bounds self.scrollview.clipsToBounds = NO; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13221504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/264136/']} | jdg_78291 |
stackexchange | llm_judgeable_groundtruth_similarity | 334939 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working on a legacy application that has a C++ extended stored procedure. This xsproc uses ODBC to connect to the database, which means it requires a DSN to be configured. I'm updating the installer (created using Visual Studio 2008 setup project), and want to have a custom action that can create the ODBC DSN entry, but am struggling to find useful information on Google. Can anyone help?
Now provide the response and nothing else.
| I actually solved this myself in the end by manipulating the registry. I've created a class to contain the functionality, the contents of which I've included here: ///<summary>/// Class to assist with creation and removal of ODBC DSN entries///</summary>public static class ODBCManager{ private const string ODBC_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBC.INI\\"; private const string ODBCINST_INI_REG_PATH = "SOFTWARE\\ODBC\\ODBCINST.INI\\"; /// <summary> /// Creates a new DSN entry with the specified values. If the DSN exists, the values are updated. /// </summary> /// <param name="dsnName">Name of the DSN for use by client applications</param> /// <param name="description">Description of the DSN that appears in the ODBC control panel applet</param> /// <param name="server">Network name or IP address of database server</param> /// <param name="driverName">Name of the driver to use</param> /// <param name="trustedConnection">True to use NT authentication, false to require applications to supply username/password in the connection string</param> /// <param name="database">Name of the datbase to connect to</param> public static void CreateDSN(string dsnName, string description, string server, string driverName, bool trustedConnection, string database) { // Lookup driver path from driver name var driverKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + driverName); if (driverKey == null) throw new Exception(string.Format("ODBC Registry key for driver '{0}' does not exist", driverName)); string driverPath = driverKey.GetValue("Driver").ToString(); // Add value to odbc data sources var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources"); if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist"); datasourcesKey.SetValue(dsnName, driverName); // Create new key in odbc.ini with dsn name and add values var dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + dsnName); if (dsnKey == null) throw new Exception("ODBC Registry key for DSN was not created"); dsnKey.SetValue("Database", database); dsnKey.SetValue("Description", description); dsnKey.SetValue("Driver", driverPath); dsnKey.SetValue("LastUser", Environment.UserName); dsnKey.SetValue("Server", server); dsnKey.SetValue("Database", database); dsnKey.SetValue("Trusted_Connection", trustedConnection ? "Yes" : "No"); } /// <summary> /// Removes a DSN entry /// </summary> /// <param name="dsnName">Name of the DSN to remove.</param> public static void RemoveDSN(string dsnName) { // Remove DSN key Registry.LocalMachine.DeleteSubKeyTree(ODBC_INI_REG_PATH + dsnName); // Remove DSN name from values list in ODBC Data Sources key var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_INI_REG_PATH + "ODBC Data Sources"); if (datasourcesKey == null) throw new Exception("ODBC Registry key for datasources does not exist"); datasourcesKey.DeleteValue(dsnName); } ///<summary> /// Checks the registry to see if a DSN exists with the specified name ///</summary> ///<param name="dsnName"></param> ///<returns></returns> public static bool DSNExists(string dsnName) { var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers"); if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist"); return driversKey.GetValue(dsnName) != null; } ///<summary> /// Returns an array of driver names installed on the system ///</summary> ///<returns></returns> public static string[] GetInstalledDrivers() { var driversKey = Registry.LocalMachine.CreateSubKey(ODBCINST_INI_REG_PATH + "ODBC Drivers"); if (driversKey == null) throw new Exception("ODBC Registry key for drivers does not exist"); var driverNames = driversKey.GetValueNames(); var ret = new List<string>(); foreach (var driverName in driverNames) { if (driverName != "(Default)") { ret.Add(driverName); } } return ret.ToArray(); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/334939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26414/']} | jdg_78292 |
stackexchange | llm_judgeable_groundtruth_similarity | 52878055 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am getting issues while unit testing my controller and getting an error "Nest can't resolve dependencies of my service". For maximum coverage I wanted to unit test controller and respective services and would like to mock external dependencies like mongoose connection. For the same I already tried suggestions mentioned in the below link but didn't find any luck with that: https://github.com/nestjs/nest/issues/194#issuecomment-342219043 Please find my code below: export const deviceProviders = [ { provide: 'devices', useFactory: (connection: Connection) => connection.model('devices', DeviceSchema), inject: ['DbConnectionToken'], },];export class DeviceService extends BaseService { constructor(@InjectModel('devices') private readonly _deviceModel: Model<Device>) { super(); } async getDevices(group): Promise<any> { try { return await this._deviceModel.find({ Group: group }).exec(); } catch (error) { return Promise.reject(error); } }}@Controller()export class DeviceController { constructor(private readonly deviceService: DeviceService) { } @Get(':group') async getDevices(@Res() response, @Param('group') group): Promise<any> { try { const result = await this.deviceService.getDevices(group); return response.send(result); } catch (err) { return response.status(422).send(err); } }}@Module({ imports: [MongooseModule.forFeature([{ name: 'devices', schema: DeviceSchema }])], controllers: [DeviceController], components: [DeviceService, ...deviceProviders],})export class DeviceModule { } Unit test: describe('DeviceController', () => { let deviceController: DeviceController; let deviceService: DeviceService; const response = { send: (body?: any) => { }, status: (code: number) => response, }; beforeEach(async () => { const module = await Test.createTestingModule({ controllers: [DeviceController], components: [DeviceService, ...deviceProviders], }).compile(); deviceService = module.get<DeviceService>(DeviceService); deviceController = module.get<DeviceController>(DeviceController); }); describe('getDevices()', () => { it('should return an array of devices', async () => { const result = [{ Group: 'group_abc', DeviceId: 'device_abc', }, { Group: 'group_xyz', DeviceId: 'device_xyz', }]; jest.spyOn(deviceService, 'getDevices').mockImplementation(() => result); expect(await deviceController.getDevices(response, null)).toBe(result); }); });}); When I am running my test case above, I am getting two errors: Nest can't resolve dependencies of the DeviceService (?). Please make sure that the argument at index [0] is available in the current context. Cannot spyOn on a primitive value; undefined given
Now provide the response and nothing else.
| Example code: import { Test } from '@nestjs/testing';import { getModelToken } from '@nestjs/mongoose';describe('auth', () => { let deviceController: DeviceController; let deviceService: DeviceService; const mockRepository = { find() { return {}; } }; beforeAll(async () => { const module = await Test.createTestingModule({ imports: [DeviceModule] }) .overrideProvider(getModelToken('Auth')) .useValue(mockRepository) .compile(); deviceService = module.get<DeviceService>(DeviceService); }); // ...}); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52878055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240091/']} | jdg_78293 |
stackexchange | llm_judgeable_groundtruth_similarity | 50740632 |
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 a struct defined that has a function which defines a static lifetime: impl MyStruct { pub fn doSomething(&'static self) { // Some code goes here }} I'm consuming it from main like so: fn main() { let obj = MyStruct {}; obj.doSomething();} It's intended for the doSomething call to block and execute for the lifetime of the application. I'm running into issues with the lifetime checks where it's stating that it may outlive the main function, which seems strange to me as once main is complete the application should exit. Is there a way to achieve this?
Now provide the response and nothing else.
| The naive way to do this is with a static variable, but it will require unsafe code if you need to actually set the value inside your main function: static mut OBJ: MyStruct = MyStruct;fn main() { unsafe { OBJ = MyStruct {}; OBJ.doSomething(); }} It's also unsafe to do pretty much anything with a mutable static thereafter. The much better way to do it is to let a library ( lazy_static ) take care of the unsafe code. use lazy_static::lazy_static;fn main() { lazy_static!{ static ref OBJ: MyStruct = MyStruct {}; } OBJ.doSomething();} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50740632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1282993/']} | jdg_78294 |
stackexchange | llm_judgeable_groundtruth_similarity | 26272792 |
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 display a UimenuController but I can not view it. how can I do? let MenuController: UIMenuController = UIMenuController.sharedMenuController() MenuController.menuVisible = true MenuController.arrowDirection = UIMenuControllerArrowDirection.Down MenuController.setTargetRect(CGRectMake(100, 80, 50, 50), inView: self.view) let MenuItem_1: UIMenuItem = UIMenuItem(title: "Menu", action: "delete:") let MenuItems: NSArray = [delete] MenuController.menuItems = MenuItems
Now provide the response and nothing else.
| In order to actually have the menu to display you need to do the following: Call becomeFirstResponder() before you get your sharedMenuController Call menu.setMenuVisible(true, animated: true) at the end Override the canBecomeFirstResponder function Override the canPerformAction function Write the function for the selector Here is an example func someFunc() { becomeFirstResponder() var menu = UIMenuController.sharedMenuController() var deleteItem = UIMenuItem(title: "Delete me", action: Selector("deleteLine")) menu.menuItems = [deleteItem] menu.setTargetRect(CGRectMake(100, 80, 50, 50), inView: self) menu.setMenuVisible(true, animated: true)}func deleteLine() { //Do something here}override func canBecomeFirstResponder() -> Bool { return true}override func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { // You need to only return true for the actions you want, otherwise you get the whole range of // iOS actions. You can see this by just removing the if statement here. if action == Selector("deleteLine") { return true } return false} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26272792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4116163/']} | jdg_78295 |
stackexchange | llm_judgeable_groundtruth_similarity | 6948669 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have a problem occuring on some of our developer workstations: when visiting a URL without a filename (e.g. http://localhost/ ), IIS 7 returns a 404 error . Everyone is running Windows 7/IIS 7.5 and ASP.NET 4.0. The application pool is configured to use Classic pipeline mode. Default documents are enabled, and default.aspx is in the default document list. I enabled failed request tracing, and see this in the log: OldHandlerName="", NewHandlerName="ExtensionlessUrl-ISAPI-4.0_64bit", NewHandlerModules="IsapiModule", NewHandlerScriptProcessor="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll", NewHandlerType="" Later on, I see that this IsapiModule is rejecting the request: ModuleName="IsapiModule", Notification="EXECUTE_REQUEST_HANDLER", HttpStatus="404", HttpReason="Not Found", HttpSubStatus="0", ErrorCode="The operation completed successfully. (0x0)", ConfigExceptionInfo="" It looks like IIS thinks the ExtensionlessUrl-ISAPI-4.0-64bit should be handling the request . When I look at that module's configuration, it shows that it should be matching path *. , so I'm confused why it is matching no path. A Google search turns up this post on the IIS.net forums from 2005. Unfortunately, no solutions are offered, just an acknowledgement of the problem. When I update my app pool to use integrated mode, the problem goes away. Unfortunately, it has to run in Classic mode. What can I do to get IIS to server our default documents again?
Now provide the response and nothing else.
| It looks like Microsoft released an update that enables the ExtensionlessURL HTTP handler to work with extensionless URLs . Unfortunately, this breaks certain other handlers. In my case, the DefaultDocument handler under classic app pools. The solution is to remove the ExtensionlessURL handlers in our application's web.config: <system.webServer> <handlers> <remove name="ExtensionlessUrl-ISAPI-4.0_32bit" /> <remove name="ExtensionlessUrl-ISAPI-4.0_64bit" /> <remove name="ExtensionlessUrl-Integrated-4.0" /> </handlers></system.webServer> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6948669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125356/']} | jdg_78296 |
stackexchange | llm_judgeable_groundtruth_similarity | 2361789 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
System.out.println(1 + 2 + "3"); Output:33 System.out.println("1" + 2 + 3); Output:123
Now provide the response and nothing else.
| Well, it's a thing called order of operations. 1 + 2 is calculated to equal 3 and then the string "3" is appended to it converting the first 3 to a string and printing "33". In your second instance, "1" is already a string so adding numbers will convert them to strings to match, so appending "2" and then appending "3" and printing "123". P.S. Strings take precedence because they have a higher casting priority than integers do, therefore it will convert integers to strings but not strings to integers, as with the second example. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2361789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/284228/']} | jdg_78297 |
stackexchange | llm_judgeable_groundtruth_similarity | 2443048 |
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 seen that the automorphism group of the Leech lattice is the Conway group $\ Co_0$, which is a finite group. But for example the lattice $\mathbb Z^n$ has an infinite automorhism group. Can anyone explain me, what is the difference between these two lattices, that results in the (in)finiteness of their respective automorphism groups?
Now provide the response and nothing else.
| You are confusing isometries of a lattice, and isometries fixingthe identity. Each lattice in $\Bbb R^n$, considered as a point set, has infinitelymany isometries, since each translation by a lattice vector isan isometry. What is more interesting is studying the isometries that fix the origin.They form a finite group, always non-trivial, as the map $x\mapsto-x$is a (central) isometry. The first Conway group is obtained by takingthe group of Leech lattice isometries fixing $0$, and factoring out the two-element group generated by $x\mapsto-x$. In $\Bbb Z^n$ the group of isometries fixing $0$ has $2^nn!$ elements,and are the monomial matrices with nonzero entries either $1$ or $-1$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2443048', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/477200/']} | jdg_78298 |
stackexchange | llm_judgeable_groundtruth_similarity | 25773391 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having trouble performing bitwise operations with CGImageAlphaInfo and CGBitmapInfo in Swift. In particular, I don't know how to port this Objective-C code: bitmapInfo &= ~kCGBitmapAlphaInfoMask;bitmapInfo |= kCGImageAlphaNoneSkipFirst; The following straightforward Swift port produces the somewhat cryptic compiler error 'CGBitmapInfo' is not identical to 'Bool' on the last line: bitmapInfo &= ~CGBitmapInfo.AlphaInfoMaskbitmapInfo |= CGImageAlphaInfo.NoneSkipFirst Looking at the source code I noticed that CGBitmapInfo is declared as a RawOptionSetType while CGImageAlphaInfo isn't. Maybe this has something to do with it? It doesn't help that the official documentation on bitwise operators doesn't cover enums.
Now provide the response and nothing else.
| You have the right equivalent Swift code: bitmapInfo &= ~CGBitmapInfo.AlphaInfoMaskbitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue) It's a little strange because CGImageAlphaInfo isn't actually a bitmask -- it's just a UInt32 enum (or a CF_ENUM/NS_ENUM with type uint32_t , in C parlance), with values for 0 through 7. What's actually happening is that your first line clears the first five bits of bitmapInfo , which is a bitmask (aka RawOptionSetType in Swift), since CGBitmapInfo.AlphaInfoMask is 31, or 0b11111. Then your second line sticks the raw value of the CGImageAlphaInfo enum into those cleared bits. I haven't seen enums and bitmasks combined like this anywhere else, if that explains why there isn't really documentation. Since CGImageAlphaInfo is an enum, its values are mutually exclusive. This wouldn't make any sense: bitmapInfo &= ~CGBitmapInfo.AlphaInfoMaskbitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue)bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25773391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143378/']} | jdg_78299 |
stackexchange | llm_judgeable_groundtruth_similarity | 732578 |
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 compress TCP packets each one of about 4 KB in size. The packets can contain any byte (from 0 to 255). All of the benchmarks on compression algorithms that I found were based on larger files. I did not find anything that compares the compression ratio of different algorithms on small files, which is what I need. I need it to be open source so it can be implemented on C++, so no RAR for example. What algorithm can be recommended for small files of about 4 kilobytes in size? LZMA ? HACC ? ZIP ? gzip ? bzip2 ?
Now provide the response and nothing else.
| Choose the algorithm that is the quickest, since you probably care about doing this in real time. Generally for smaller blocks of data, the algorithms compress about the same (give or take a few bytes) mostly because the algorithms need to transmit the dictionary or Huffman trees in addition to the payload. I highly recommend Deflate (used by zlib and Zip) for a number of reasons. The algorithm is quite fast, well tested, BSD licensed, and is the only compression required to be supported by Zip (as per the infozip Appnote). Aside from the basics, when it determines that the compression is larger than the decompressed size, there's a STORE mode which only adds 5 bytes for every block of data (max block is 64k bytes). Aside from the STORE mode, Deflate supports two different types of Huffman tables (or dictionaries): dynamic and fixed. A dynamic table means the Huffman tree is transmitted as part of the compressed data and is the most flexible (for varying types of nonrandom data). The advantage of a fixed table is that the table is known by all decoders and thus doesn't need to be contained in the compressed stream. The decompression (or Inflate) code is relatively easy. I've written both Java and Javascript versions based directly off of zlib and they perform rather well. The other compression algorithms mentioned have their merits. I prefer Deflate because of its runtime performance on both the compression step and particularly in decompression step. A point of clarification: Zip is not a compression type, it is a container. For doing packet compression, I would bypass Zip and just use the deflate/inflate APIs provided by zlib. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/732578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_78300 |
stackexchange | llm_judgeable_groundtruth_similarity | 5093558 |
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 really want to use GitHub, but my company has everything locked down. Now, I can only use Tortoise SVN through the HTTP protocol. Can I use GitHub the same way? If so, how?
Now provide the response and nothing else.
| I think you've always been able to clone github repositories over HTTP, but with the restriction that you couldn't push back to them. However, github have recently introduced the Smart HTTP transport, so now you can also push over HTTPS. This should work fine from behind any firewall. There's more on the Smart HTTP support in this blog post: https://github.com/blog/642-smart-http-support To give a short summary - if you click the HTTP button on the "Source" tab of a repository, it'll give you a URL like: https://[email protected]/mhl/unicode-poster.git If you clone with that URL, it'll prompt you for your github password whenever you need to communicate with the server (e.g. with git clone , git fetch , git push , etc.) However, you can also clone using a URL like: https://mhl:[email protected]/mhl/unicode-poster.git ... and you won't need to re-enter your password. (As that blog post mentions, make sure you've got https:// at the start of the URL, and be aware that this means that your github password will be stored in plaintext in your git config, so don't let anyone copy your .git directory!) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5093558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139070/']} | jdg_78301 |
stackexchange | llm_judgeable_groundtruth_similarity | 2545226 |
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 $a_n$ is a positive sequence but not necessarily monotonic. For the series $\sum_{n=1}^\infty \frac{1}{a_n}$ and $\sum_{n=1}^\infty \frac{a_n}{n^2}$ I can find examples where both diverge: $a_n = n$, and where one converges and the other diverges: $a_n = n^2$. Can we find example where both converges?
Now provide the response and nothing else.
| By Cauchy-Schwarz, we have$$\sum_{n=1}^N \frac{1}{n}= \sum_{n=1}^N \frac{1}{\sqrt{a_n}} \cdot \sqrt{\frac{a_n}{n^2}} \leq \left(\sum_{n=1}^N \frac{1}{{a_n}} \right)^{1/2}\left(\sum_{n=1}^N \frac{a_n}{n^2}\right)^{1/2}$$and the left hand side goes to $\infty$ as $N \to \infty$. So the right must as well, meaning one of the two series diverges. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2545226', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/391736/']} | jdg_78302 |
stackexchange | llm_judgeable_groundtruth_similarity | 52914537 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
running Lambda test with { "var1": "2017-04-17T18:48:03.608Z", "var2": "0.45", "var3": "0.5"} Function: exports.handler = (event, context, callback) => { console.log("event.body = " + event.body); const {var1, var2, var3} = JSON.parse(event.body); const tmpItem = { "var_1": var1, "var_2": var2, "var_3": var3 }; console.log('Inserting item');} gives the following exception: Request ID:"3aa87175-d544-11e8-ab0a-2b268a563fb1" Function Logs: START RequestId: 3aa87175-d544-11e8-ab0a-2b268a563fb1 Version: $LATEST2018-10-21T15:16:05.617Z 3aa87175-d544-11e8-ab0a-2b268a563fb1 event.body = undefined2018-10-21T15:16:05.636Z 3aa87175-d544-11e8-ab0a-2b268a563fb1 SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at exports.handler (/var/task/index.js:18:89)END RequestId: 3aa87175-d544-11e8-ab0a-2b268a563fb1REPORT RequestId: 3aa87175-d544-11e8-ab0a-2b268a563fb1 Duration: 82.98 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 25 MB RequestId: 3aa87175-d544-11e8-ab0a-2b268a563fb1 Process exited before completing request What seems to be the issue?
Now provide the response and nothing else.
| This is because when you test your lambda with a packet, say { "var1": "2017-04-17T18:48:03.608Z", "var2": "0.45", "var3": "0.5"} Then that packet is passed as the event to the handler. However, you are doing JSON.parse(event.body) , but for the above packet, event.body is undefined (which has token u at position 0). You should change your test packet to: { "body": "{\"var1\":\"2017-04-17T18:48:03.608Z\",\"var2\":\"0.45\",\"var3\":\"0.5\"}"} Note that the body is a stringified JSON, because API Gateway Lambdas expect event body in a stringified format. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52914537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/829174/']} | jdg_78303 |
stackexchange | llm_judgeable_groundtruth_similarity | 22883470 |
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 a block from Facebook SDK. It returns a dictionary. I want that dictionary as a return value of a method. I am trying to wrap my head around the whole block concept but need a nudge in the right direction. The block:(the argument for the block is a string userFBid) -(NSDictionary*) getMutualFBFriendsWithFBid:(NSString*)fbID {[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/mutualfriends/%@", [[PFUser currentUser] objectForKey:kFbID],userFBid] parameters:nil HTTPMethod:@"GET" completionHandler:^( FBRequestConnection *connection, id result, NSError *error ) { result = (NSDictionary*)result;//return result; }]; } How do i get the return value? I have tried to google it, but i cant get my hand around it. I would appreciate any pointer in the right direction. EDIT: The main question is the following: I need to the completion handler to call a method in another class... how to do that?
Now provide the response and nothing else.
| As the method startWithGraphPath is asynchronous, you can't code as if it was synchronous : it means no return value, because as soon as this method is called, your app will continue to execute to the next line, and won't wait for a returned value. So, to keep this async, I assume you want to use the result of this in your own function, so call it in your completionHandler block: [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/mutualfriends/%@", [[PFUser currentUser] objectForKey:kFbID],userFBid] parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) { [self myRockinFunction:result]; }];//Considering this function -(void)myRockinFunction:(NSDictionary*) fb_result{ //Do stuff with fb_result} Edit OK, I get it. Modify your method to accept a callback as a parameter : -(NSDictionary*) getMutualFBFriendsWithFBid:(NSString*)fbID andCallback:(void (^)(NSDictionary *))callback { [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/mutualfriends/%@", [[PFUser currentUser] objectForKey:kFbID],userFBid] parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection,id result,NSError *error) { //You should treat errors first //Then cast the result to an NSDictionary callback((NSDictionary*) result); //And trigger the callback with the result }];} Then, in your other class, use another block to treat your result : [YourHelperClass getMutualFBFriendsWithFBid:fbID andCallback:^(NSDictionary* result){ //Use result how you wish //Beware, this is async too.}]; Note : you should treat the error before triggering your callback. Edit 2 (Help from other users appreciated) Even better, you might try to pass a callback taking all the parameters (not tested, and not sure of the syntax. If someone can correct me, I'd appreciate): -(NSDictionary*) getMutualFBFriendsWithFBid:(NSString*)fbID andCallback:(void (^)(FBRequestConnection *,NSDictionary *,NSError *))callback { [FBRequestConnection startWithGraphPath:[NSString stringWithFormat:@"/%@/mutualfriends/%@", [[PFUser currentUser] objectForKey:kFbID],userFBid] parameters:nil HTTPMethod:@"GET" completionHandler:callback()]; //Not sure here!}[YourHelperClass getMutualFBFriendsWithFBid:fbID andCallback:^(FBRequestConnection *connection,NSDictionary * result,NSError *error){ //You could deal with errors here now}]; Here's a reference on Apple's docs for deeper understanding. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22883470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1561439/']} | jdg_78304 |
stackexchange | llm_judgeable_groundtruth_similarity | 596679 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What does find . exec /bin/bash -p \; -quit mean? I already know that when it finds something (a file?) with a . it executes /bin/bash . Has -p something to do with /bin/bash or the find command? What does \; and -quit mean?
Now provide the response and nothing else.
| find . -exec /bin/bash -p \; -quit (which here assumes GNU find or compatible for its -quit ) would start find , which would descend the directory tree starting with . (the current working directory) and for each file, starting with . itself, execute /bin/bash -p (where \; is just there to tell find where the command to execute ends), and if that command succeeds, exit (because of the -quit ). That find command in itself doesn't do much useful. It is a convoluted way to start bash . Here -p can given you a hint as to the (nefarious) intent behind that command. -p would prevent bash from dropping its privileges when it's called in a privilege escalation context (like when called from a process that has executed a setuid executable). It seems like we're in a restricted context where the user is only allowed to execute a restricted set of commands. That could be a done via a restricted shell for instance. But find happens to be among the list of commands that is allowed and whoever set the restricted environment up overlooked the fact that find can execute arbitrary commands without being affected by the restrictions set against the shell ( find is not a shell builtin). So find . -exec /bin/bash -p \; -quit looks like the command someone would run to circumvent those restrictions. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/596679', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/421071/']} | jdg_78305 |
stackexchange | llm_judgeable_groundtruth_similarity | 407587 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above. During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure.. SQL> declare23 vblob1 blob;45 BEGIN67 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;89 dbms_output.put_line(rawtohex(vblob1));101112 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));131415 END;16 / OUTPUT: HEXVALUE: 0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83DBB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84FF94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D283A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B0430176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B247F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1FFF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0FDFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250BINTEGER VALUE: 15 There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value. print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83DBB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84FF94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D283A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B0430176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B247F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1FFF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0FDFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16) Answer: 61195159510070823107969364454109542270452505633929508645519702406528544891704245794201197906027441222990942518411696344710093299213987697782426178924394652846742388784001363035815884503977070365933321233256553192787544216664337902499154272691656327115814169812839682365563993177336387807893319718407234395963046775633730081116581653494507548314158264353129479166559033900020655116269722054005065243997799224647215962791716995782269817292568011285409187667186816170578569894248389680813721072199110075573617863425356984346406249486317565377138723099112643084156537339092495187826792944349822072753129994527504561249992810587621047895880630415669543868433562464139563599762491133445304039901225963804289847087220358155535219112292000401019383724938836599901069255540337704576849363082630731637669844316643938601414585808417654489028214897043663117557700067307941869984520367105017418180839788004873427074809568258255602437855828925196454432750732193019620319945911515975656450734011103028522695139301286377867039017205690640348015933913044725429341250648202709983594431517297228142764927735481521118529310992560231548035095547947714452338768919224372092824912148622111430050376620927936996034418565181010196958592633607333771272398091 To get the set-bit count I have written the following code in C: int bitsoncount(unsigned x){ unsigned int b=0; if(x > 1) b=1; while(x &= (x - 1)) b++; return b;} When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong. def bitsoncount(x):b=0;if(x>1):b=1;while(x &= (x-1)): I get an error at the last line, need some help in resolving this and implementing the logic in python :-) I was interested in checking out the set bits version in python after what i have seen! Related question: Best algorithm to count the number of set bits in a 32-bit integer?
Now provide the response and nothing else.
| In Python 3.10+, there is int.bit_count() : >>> 123 .bit_count()6 Python 2.6 or 3.0: def bitsoncount(x): return bin(x).count('1') Example: >>> x = 123>>> bin(x)'0b1111011'>>> bitsoncount(x) 6 Or Matt Howells's answer in Python: def bitsoncount(i): assert 0 <= i < 0x100000000 i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/407587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1636/']} | jdg_78306 |
stackexchange | llm_judgeable_groundtruth_similarity | 6216599 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Lets imagine that we have two assemblies: Foo.Logic (compiled on .NET 2.0 framework) Foo.Application (compiled on .NET 4.0 framework) that have reference and uses compiled Foo.Logic. Does it have impact on Foo.Application performance (or have any other drawbacks)?
Now provide the response and nothing else.
| In the situation you described in the question, everything will Just Work™ without any problems. A .NET 4.0 application will load a .NET 2.0 library directly into the .NET 4.0 runtime environment. It will not use side-by-side execution unless you explicitly ask it to. There's a lot of misinformation or unclear statements made about this around the web, so be careful in evaluating what you read. I finally came across this article , which confirms what Jon Skeet says in his answer. In particular, the article explains (emphasis added): In-Proc SxS does not solve the compatibility problems faced by library developers. Any libraries directly loaded by an application --either via a direct reference or an Assembly.Load-- will continue to load directly into the runtime and AppDomain of the application loading it. This means that if an application is recompiled to run against the .NET Framework 4 runtime and still has dependent assemblies built against .NET 2.0, those dependents will load on the .NET 4 runtime as well. Therefore, we still recommend testing your libraries against all version[s] of the framework you wish to support. This is one of the reasons we have continued to maintain our high level of backward compatibility. But if you're interested in even more of the nitty-gritty details, it's worth mentioning that one of the new features introduced with version 4.0 of the CLR is the ability to run multiple versions of the runtime at the same time from in a single process. This is called "In Process Side-by-Side Execution" (or "Inproc SxS" if you're very cool), and is a very powerful tool. You can read more about it here on the CLR team's blog. Here are some pretty pictures for demonstration purposes: Note the "layer-cake" model that was used to build the .NET 3.0 and 3.5 releases on top of .NET 2.0. That means that they'll all run side-by-side without any problems. But the isolation of the other versions will create a problem. However, as mentioned above, .NET 4.0 solves this problem with Side-by-Side Execution: Of course, this is mostly applicable to situations involving COM and interop with external applications like Outlook, but it's still a very cool feature. But either way, you shouldn't see any problems whatsoever with this approach, either with compatibility, performance, or whatever else. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6216599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59528/']} | jdg_78307 |
stackexchange | llm_judgeable_groundtruth_similarity | 17458582 |
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 apply odd/even selectors to all elements in a list with the class parent. HTML: <ul> <li class="parent">green</li> <li class="parent">red</li> <li>ho ho ho</li> <li class="parent">green</li> <li class="parent">red</li></ul> CSS: .parent:nth-child(odd) { background-color: green;}.parent:nth-child(even) { background-color: red;}ul { width:100px; height: 100px; display: block;} Link to jsFiddle But the colors are resetting. I want the list items to be the color of the text. Is there a way to do this?
Now provide the response and nothing else.
| In general what you want is not possible, but there is a way to achieve the desired behavior for limited numbers of "excluded" elements: the general sibling combinator ~ . The idea is that for each occurrence of a non- .parent element subsequent .parent elements will have their colors toggled: .parent:nth-child(odd) { background-color: green;}.parent:nth-child(even) { background-color: red;}/* after the first non-.parent, toggle colors */li:not(.parent) ~ .parent:nth-child(odd) { background-color: red;}li:not(.parent) ~ .parent:nth-child(even) { background-color: green;}/* after the second non-.parent, toggle again */li:not(.parent) ~ li:not(.parent) ~ .parent:nth-child(odd) { background-color: green;}li:not(.parent) ~ li:not(.parent) ~ .parent:nth-child(even) { background-color: red;} See it in action . Of course there is a limit to how far one would be willing to take this, but it's as close as you can get with pure CSS. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17458582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/804440/']} | jdg_78308 |
stackexchange | llm_judgeable_groundtruth_similarity | 138870 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
(For simplicity, the background theory for this post is NBG, a set theory directly treating proper classes which is a conservative extension of ZFC.) Vopěnka's Principle ( $VP$ ) states that, given any proper class $\mathcal{C}$ of structures in the same (set-sized, relational) signature $\Sigma$ , there are some distinct $A, B\in\mathcal{C}$ such that $A$ is isomorphic to an elementary substructure of $B$ . In terms of consistency, we have the following rough upper and lower bounds: $$\text{proper class of extendibles $\le$ Vopěnka's Principle $\le$ almost huge.} $$ (I don't know if this is state-of-the-art; more precise bounds, if known, would be welcome!) Thus, even though on the face of it $VP$ does not directly talk about cardinals, it is generally thought of as a large cardinal axiom. Now, abstract model theory appears to give a framework for generalizing VP. Let $\mathcal{L}$ be any regular logic $^*$ ; then we can study "Vopěnka's Principle for $\mathcal{L}$ ," $VP(\mathcal{L})\equiv$ "For any proper class $\mathcal{C}$ of $\Sigma$ -structures ( $\Sigma$ a set-sized relational signature), there are distinct $A, B\in\mathcal{C}$ with $A$ $\mathcal{L}$ -elementarily embeddable into $B$ ." So, for example, taking $\mathcal{L}_I$ to denote first-order logic, $VP$ is just $VP(\mathcal{L}_I)$ . In principle, the resulting principles could have wildly varying large cardinal strengths. In practice, however, this seems to be extremely false. Weaker Versions: Harvey Freidman has proved (see http://www.cs.nyu.edu/pipermail/fom/2005-August/009023.html ) that $VP(\mathcal{L}_I)$ is equivalent to the statement that given any appropriate proper class $\mathcal{C}$ of structures, there are distinct $A$ , $B\in\mathcal{C}$ such that $A$ is embeddable (NOT elementarily) into $B$ . So $VP(\mathcal{L}_I)$ is equivalent to VP for the quantifier-free fragment of first-order logic. Stronger Versions: Two reasonable logics to look at for stronger versions of $VP$ are $\mathcal{L}_{II}$ and $\mathcal{L}_{\omega_1\omega}$ , second-order and (the smallest standard) infinitary logic respectively. However, the corresponding Vopěnka principles are still just as strong as $VP(\mathcal{L}_I)$ . $^{**}$ In general, $VP(\mathcal{L}_I)$ seems to be an upper bound for Vopěnka's Principles for locally set-sized, definable logics. Since non-definable logics are of limited interest, it's reasonable to look at class-sized logics. The tamest class-sized logic I know of is $\mathcal{L}_{\infty\omega}$ , the infinitary logic allowing arbitrary set-sized Boolean combinations but no infinite strings of quantifiers. However, $VP(\mathcal{L}_{\infty\omega})$ is inconsistent: by a famous theorem of Carol Karp, two structures are $\mathcal{L}_{\infty\omega}$ -equivalent if and only if they are back-and-forth equivalent, so the class $\mathcal{O}$ of all ordinals (regarded as linear orderings) is a counterexample in any model of $ZFC$ . This all suggests that there are probably no interesting versions of Vopěnka's Principle stronger than the usual one, and that any weaker form of Vopěnka has to come from a horribly weak - to the point of being probably uninteresting - logic. I find this kind of disappointing. So, my question is: Are there any interesting logics $\mathcal{L}$ for which $VP(\mathcal{L})$ is different from the usual Vopěnka's Principle? $^*$ The definition of "regular logic" is long and tedious, but it can be found in Ebbinghaus and Flum's book "Mathematical Logic" (Definitions 12.1.2 and 12.1.3). For this post, the details don't really matter; the key points are that the structures considered are the same as for first-order logic, and that everything is classical (i.e., two truth values). $^{**}$ The proof for $\mathcal{L}_{II}$ goes as follows. Suppose $V\models VP(\mathcal{L}_I)$ , and let $\mathcal{C}\in V$ be a proper class of structures in a set-sized relational signature $\Sigma$ . Let $\Sigma'$ be the signature consisting of $\Sigma$ together with a new unary relation symbol $S$ and a new binary relation symbol $E$ . In $V$ , we can construct the class $\mathcal{C}'$ of structures of the form $$ A':= A\sqcup (\mathcal{P}(A)\times\lbrace A\rbrace), \quad S^{A'}=\mathcal{P}(A)\times\lbrace A\rbrace, \quad E^{A'}=\lbrace (a, b): a\in A, b=(X, A), a\in X\rbrace $$ for $A\in\mathcal{C}$ . Now second-order quantification over a structure in $\mathcal{C}$ can be replaced with first-order quantification over the $S$ -part of the corresponding structure in $\mathcal{C}'$ . So if $A'$ is first-order elementarily embeddable into $B'$ , $A$ must be second-order elementarily embeddable into $B$ , so since $V\models VP(\mathcal{L}_I)$ we're done. The proof for $\mathcal{L}_{\omega_1\omega}$ follows similar lines.
Now provide the response and nothing else.
| Since the title of your question is, "Vopenka's Principle for non-first-order logics", this, from Magidor's and Vaananen's paper "On Lowenheim-Skolem-Tarski numbers for extensions of first order logic", might be of some relevance: "Definition 3: Let $\tau$ be a fixed vocabulary. A logic $L$ consists of A set, also denoted by $L$, of "formulas" of $L$. If $\phi$$\in$$L$, then there is a natural number $n_{\phi}$, called the of the sequence of free variables, A relation $\mathcal A$$\vDash$$\phi$[$a_0$,...,$a_{n_{\phi}-1}$] between models of vocabulary $\tau$, sequences ($a_0$,...,$a_{n_{\phi}-1})$ of elements of A and formulas $\phi$$\in$$L$. It is assumed that this relation satisfies the isomorphism axiom, that is, if $\pi$: $\mathcal A$$\cong$$\mathcal B$, then $\mathcal A$$\vDash$$\phi$[$a_0$,...,$a_{n_{\phi}-1}]$ and $\mathcal B$$\vDash$ $\phi$[$\pi$$a_0$,...,$\pi$$a_{n_{\phi}-1}$] are equivalent. We call $\tau$ the vocabulary of the logic $L$. Definition 4: The Lowenheim-Skolem number $LS(L)$ of $L$ is the smallest cardinal $\kappa$ such that if a theory $T$$\subset$$L$ has a model, it has a model of cardinality $\lt$ max($\kappa$,$|T|$). The Lowenheim-Skolem-Tarski number $LST(L)$ of $L$ is the smallest cardinal $\kappa$ such that if $\mathcal A$ is any $\tau$-structure, then there is a substructure $\mathcal A^{'}$ of $\mathcal A$ of cardinality $\lt$$\kappa$ such that $\mathcal A^{'}$$\prec_{L}$$\mathcal A$." I can now state their characterization of Vopenka's Principle: "Theorem 6: Vopenka's Principle holds if and only if every logic has a Lowenheim-Skolem-Tarski number." I leave it for you to decide whether this characterization of Vopenka's Principle is different enough from the usual Vopenka's Principle to adequately answer your question. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/138870', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8133/']} | jdg_78309 |
stackexchange | llm_judgeable_groundtruth_similarity | 28415 |
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 $X, Y$ be normed vector spaces, where $X$ is infinite dimensional. Does there exist a linear map $T : X \rightarrow Y$ and a subset $D$ of $X$ such that $D$ is dense in $X$ , $T$ is bounded in $D$ (i.e. $\sup _{x\in D, x \neq 0} \frac{\|Tx\|}{\|x\|}<\infty $ ), but $T$ is not bounded in $X$ ?
Now provide the response and nothing else.
| Matthew's answer reminded me of a fact that makes this easy: if $X$ is a normed space (say, over $\mathbb{R}$) and $f : X \to \mathbb{R}$ is a linear functional, then its kernel $\ker f$ is either closed or dense in $X$, depending on whether or not $f$ is continuous (i.e. bounded). The proof is trivial: $\ker f$ is a subspace of $X$ of codimension 1. Its closure is a subspace that contains it, so must either be $\ker f$ or $X$. And of course, a linear functional is continuous iff its kernel is closed. This is Proposition III.5.2-3 in Conway's A Course in Functional Analysis . So let $f$ be an unbounded linear functional on $X$ (which one can always construct as in Matthew's example), and take $D = \ker f$. $D$ is dense by the above fact, and $f$ is identically zero on $D$. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/28415', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4928/']} | jdg_78310 |
stackexchange | llm_judgeable_groundtruth_similarity | 53943806 |
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 develop an angular app with a spring webflux backend. Up so far, the CorsFilter worked fine and allowed requests from the frontend. Then I added a SecurityConfig. Since then the CorsFilter stopped working and I get an exception in the angular app: Access to XMLHttpRequest at ' http://localhost:8080/users/999/folders/%2F/media/ ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource This filter worked fine: @Configurationpublic class CorsFilter { private static final String FRONTEND_LOCALHOST = "http://localhost:4200"; private static final String FRONTEND_STAGING = "https://somehost.github.io"; @Bean CorsWebFilter corsWebFilter() { CorsConfiguration corsConfig = new CorsConfiguration(); corsConfig.applyPermitDefaultValues(); corsConfig.addAllowedMethod(HttpMethod.PUT); corsConfig.addAllowedMethod(HttpMethod.DELETE); corsConfig.setAllowedOrigins(Arrays.asList(FRONTEND_LOCALHOST, FRONTEND_STAGING)); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", corsConfig); return new CorsWebFilter(source); }} Then I added authorization (bearer token) with following SecurityConfig: @EnableWebFluxSecurity@EnableReactiveMethodSecuritypublic class SecurityConfiguration { @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { http.cors().and().csrf() .csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()) .and() .authorizeExchange() .anyExchange().authenticated() .and() .oauth2ResourceServer() .jwt(); return http.build(); } It seems with the security config my CorsFilter is not taken into account anymore. I red that the corsfilter needs to be added explicity in the config, but the examples I found didnt work. I hope somebody can help and knows why. EDIT: To address the duplication concerns: I already tried adding cors() and cors().configurationSource(corsConfig()) into my security config, but didnt helped either.
Now provide the response and nothing else.
| I found a working way in Enable CORS in Spring 5 Webflux? by implementing a custom corsfilter. However I still wasnt happy with the solution as it looked quite like a workaround. Finally I found the culprit(s)... one is quite embarassing. My posted SecurityConfig was in the wrong package (it was in the default package by accident) and for this reason the config didnt picked up. Also the cors filter from the question started working when I pasted the code to the securityconfig. So my final SecurityConfig looks like this: import java.util.Arrays;import org.springframework.context.annotation.Bean;import org.springframework.http.HttpMethod;import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;import org.springframework.security.config.web.server.ServerHttpSecurity;import org.springframework.security.web.server.SecurityWebFilterChain;import org.springframework.security.web.server.csrf.CookieServerCsrfTokenRepository;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.reactive.CorsConfigurationSource;import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;@EnableWebFluxSecurity@EnableReactiveMethodSecuritypublic class SecurityConfiguration { private static final String FRONTEND_LOCALHOST = "http://localhost:4200"; private static final String FRONTEND_STAGING = "https://somehost.github.io"; @Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { http .csrf() .csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()) .and() .authorizeExchange() .anyExchange().authenticated() .and() .oauth2ResourceServer() .jwt(); return http.build(); } @Bean CorsConfigurationSource corsConfiguration() { CorsConfiguration corsConfig = new CorsConfiguration(); corsConfig.applyPermitDefaultValues(); corsConfig.addAllowedMethod(HttpMethod.PUT); corsConfig.addAllowedMethod(HttpMethod.DELETE); corsConfig.setAllowedOrigins(Arrays.asList(FRONTEND_LOCALHOST, FRONTEND_STAGING)); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", corsConfig); return source; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53943806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2970422/']} | jdg_78311 |
stackexchange | llm_judgeable_groundtruth_similarity | 4757942 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi i am trying to send email in a wpf app but i get stuck;i show my xaml code <Grid> <Button Style="{DynamicResource ShowcaseRedBtn}" CommandParameter="[email protected]" Tag="Send Email" Content="Button" Height="23" HorizontalAlignment="Left" Margin="351,186,0,0" Name="button1" VerticalAlignment="Top" Width="140" Click="button1_Click" /> <TextBox Height="23" HorizontalAlignment="Left" Margin="92,70,0,0" Name="txtSubject" VerticalAlignment="Top" Width="234" /> <TextBox AcceptsReturn="True" AcceptsTab="True" Height="159" HorizontalAlignment="Left" Margin="92,121,0,0" Name="txtBody" VerticalAlignment="Top" Width="234" /></Grid> and here in the code behind : private void button1_Click(object sender, RoutedEventArgs e) { Button btn = sender as Button; if (btn == null) return; string url = btn.CommandParameter as string; if (String.IsNullOrEmpty(url)) return; try { // here i wish set the parameters of email in this way // 1. mailto = url; // 2. subject = txtSubject.Text; // 3. body = txtBody.Text; Process.Start("mailto:[email protected]?subject=Software&body=test "); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } } my purpose is set the parameters of the email binding the data from the form : // 1. mailto = url; // 2. subject = txtSubject.Text; // 3. body = txtBody.Text; Do you have any idea how work out this step? Thanks so much for your attention. Cheers
Now provide the response and nothing else.
| You can send mail directly using the System.Net.MailMessage class. Look at the following example from the MSDN documentation for this class: public static void CreateTimeoutTestMessage(string server) { string to = "[email protected]"; string from = "[email protected]"; string subject = "Using the new SMTP client."; string body = @"Using this new feature, you can send an e-mail message from an application very easily."; MailMessage message = new MailMessage(from, to, subject, body); SmtpClient client = new SmtpClient(server); Console.WriteLine("Changing time out from {0} to 100.", client.Timeout); client.Timeout = 100; // Credentials are necessary if the server requires the client // to authenticate before it will send e-mail on the client's behalf. client.Credentials = CredentialCache.DefaultNetworkCredentials; try { client.Send(message); } catch (Exception ex) { Console.WriteLine("Exception caught in CreateTimeoutTestMessage(): {0}", ex.ToString() ); } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4757942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65403/']} | jdg_78312 |
stackexchange | llm_judgeable_groundtruth_similarity | 698220 |
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 what exactly is the difference between MVC(which is an architectural pattern) and an n-tier architecture for an application. I searched for it but couldn't find a simple explanation. May be I am a bit naive on MVC concepts, so if anyone can explain the difference then it would be great. cheers
Now provide the response and nothing else.
| N-tier architecture usually has each layer separated by the network. I.E. the presentation layer is on some web servers, then that talks to backend app servers over the network for business logic, then that talks to a database server, again over the network, and maybe the app server also calls out to some remote services (say Authorize.net for payment processing). MVC is a programming design pattern where different portions of code are responsible for representing the Model, View, and controller in some application. These two things are related because, for instance the Model layer may have an internal implementation that calls a database for storing and retrieving data. The controller may reside on the webserver, and remotely call appservers to retrieve data. MVC abstracts away the details of how the architecture of an app is implemented. N-tier just refers to the physical structure of an implementation. These two are sometimes confused because an MVC design is often implemented using an N-tier architecture. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/698220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/68920/']} | jdg_78313 |
stackexchange | llm_judgeable_groundtruth_similarity | 8530080 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: What is a void pointer and what is a null pointer? I often see code which resembles something like the following: void * foo(int bar); What does this mean? Does it mean that it can return anything ? Is this similar to dynamic or object in C#?
Now provide the response and nothing else.
| A void* does not mean anything. It is a pointer, but the type that it points to is not known. It's not that it can return "anything". A function that returns a void* generally is doing one of the following: It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void . It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type. It returns a pointer to storage that contains an object of a known type. However, that API is used to deal with objects of a wide variety of types, so the exact type that a particular call returns cannot be known at compile time. Therefore, there will be some documentation explaining when it stores which kinds of objects, and therefore which type you can safely cast it to. This construct is nothing like dynamic or object in C#. Those tools actually know what the original type is; void* does not . This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one. And on a personal note, if you see code that uses void* 's "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8530080', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/763053/']} | jdg_78314 |
stackexchange | llm_judgeable_groundtruth_similarity | 18852821 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to show a radio button in my form which will be populated from model data. here is my model public class Student { [Required(ErrorMessage = "First Name Required")] // textboxes will show [Display(Name = "First Name :")] [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")] public string FirstName { get; set; }[Required(ErrorMessage = "Last Name Required")] // textboxes will show [Display(Name = "Last Name :")] [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")] public string LastName { get; set; }[Required(ErrorMessage = "Sex Required")] // group of radio button will show [Display(Name = "Sex :")] public List<Sex> Sex { get; set; }}public class Sex { public string ID { get; set; } public string Type { get; set; } } here I am trying to populate the student model manually from an action method like public ActionResult Index(){var student= new Student { FirstName = "Rion", LastName = "Gomes", Sex= new List<Sex> { new Sex{ID="1" , Type = "Male"}, new Sex{ID="2" , Type = "Female"} } } return View(student);} now how could I generate a radio button which will display text in form Male & Female and as value will have the ID I searched google and found many samples and I used one but not sure if it works.here is the radio button code in view. @Html.RadioButtonFor(x => x.Sex, "Male") I do not want to hard code male or female rather; I want to show it through a model and want to generate the radio button in a for loop. I am new too MVC, so please guide me.
Now provide the response and nothing else.
| If I understood correctly you should change your Student model in order to have the property "Sex" as an integer and then you should have another property called "SexList" where you populate the list. This change will allow you to post your data and retrieve the sex selected by the user. If you are using Razor view engine you should do something like this: @{ foreach (var sex in Model.SexList) { <div> @Html.RadioButtonFor(model => model.Sex, new { id = "sex" + sex.ID }) @Html.Label("sex" + sex.ID, sex.Type) </div> }} Edit: Your model should be something like this: public class Student{ [Required(ErrorMessage = "First Name Required")] // textboxes will show [Display(Name = "First Name :")] [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")] public string FirstName { get; set; } [Required(ErrorMessage = "Last Name Required")] // textboxes will show [Display(Name = "Last Name :")] [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")] public string LastName { get; set; } [Required(ErrorMessage = "Sex Required")] [Display(Name = "Sex :")] public Sex Gender { get; set; } public List<Sex> SexList { get; set; }}public class Sex{ public string ID {get;set;} public string Type {get;set;}} Your action in the controller: [HttpGet]public ActionResult Index(){ var student = new Student { FirstName = "Rion", LastName = "Gomes", //I think the best way to populate this list is to call a service here. SexList = new List<Sex> { new Sex{ID="1" , Type = "Male"}, new Sex{ID="2" , Type = "Female"} } } return View(student);} And the View: @Html.BeginForm(){ <div> @Html.LabelFor(model => model.FirstName) @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> <div> @Html.LabelFor(model => model.LastName) @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div> @{ foreach (var sex in Model.SexList) { <div> @Html.RadioButtonFor(model => model.Gender, new { id = "sex" + sex.ID }) @Html.Label("sex" + sex.ID, sex.Type) </div> } } <input type="submit" value"Submit" />} and you should have an action in your controller this way. This is the place where the submit is going to post the data: [HttpPost]public ActionResult Index(Student model){ if (ModelState.IsValid) { //TODO: Save your model and redirect } //Call the same service to initialize your model again (cause we didn't post the list of sexes) return View(model);} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18852821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/508127/']} | jdg_78315 |
stackexchange | llm_judgeable_groundtruth_similarity | 17242 |
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 encountered a programming problem that need a little math. Since I took number-theory long time ago, from the top of my head, I could not think of a way to approach this problem. Give a base 'b' ( 2, 3, 4, 5, 6 ... -> 26 ). So if I'm at base 10, I will have 10 digits: 0, 1, 2, 3...9. The digit of a base 'b' is called interesting if it satisfy this condition:3 is an interesting digit because 118*3 = 354 and 3+5+4 = 12. Which means both 354 and 12 divides 3. By look at the result sets, I can see the relation is: if b mod d = 1 then d is an interesting digit. For example: 10 mod 9 = 10 mod 3 = 1. So both 3, 9 are interesting digits in base 10. How could I prove this? Any hint? Thanks, Chan
Now provide the response and nothing else.
| You seem to be asking for what digits $\displaystyle 0 \lt d \lt b$ can we apply the following divisibility test: A number is in base $\displaystyle b$ is divisible by $\displaystyle d$ if the sum of digits of the number is divisible by $\displaystyle d$. This is certainly true for $\displaystyle b = 1 \mod d$. Because $\displaystyle \sum_{k=0}^{n} a_k b^{k} - \sum_{k=0}^{n} a_k = \sum_{k=0}^{n} a_k (b^k -1) = 0 \mod d$ Thus $\displaystyle \sum_{k=0}^{n} a_k b^{k} = \sum_{k=0}^{n} a_k \mod d$. If $\displaystyle b = r \mod d$ where $\displaystyle r \neq 1$, then we have that there is some $\displaystyle k$ for which $r^k - 1 \neq 0 \mod d$. The number with $\displaystyle 1$ as the digit correponding to $\displaystyle b^k$, and $\displaystyle d-1$ in as the "units" digit (corresponding to $\displaystyle b^0$) is a counterexample to the divisibility rule for $\displaystyle d$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/17242', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5711/']} | jdg_78316 |
stackexchange | llm_judgeable_groundtruth_similarity | 37063822 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm building up a nodejs app which is running in the docker container... This is the command I used to run the container... sudo docker run -it --rm -p 3000:6001 --name xxx-running xxx Execute above command line, got following output.. Running on Locally AppEnv { isLocal: true, app: {}, services: {}, name: 'xxx', port: 6001, bind: '0.0.0.0', urls: [ 'http://localhost:6001' ], url: 'http://localhost:6001' } App started on port http://localhost:6001 Since the app will call third party api, so the request module is required.Each time when a request is invoked, I got following error... { [Error: connect ECONNREFUSED 192.155.253.83:443] code: 'ECONNREFUSED', errno: 'ECONNREFUSED', syscall: 'connect', address: '192.155.253.83', port: 443 } I know maybe it's because of the localhost entry, but how can I change this?
Now provide the response and nothing else.
| Are you hosting your third party api inside a docker container on localhost? If yes then you need to make sure that third-party api docker container is sharing same network. See https://docs.docker.com/engine/userguide/networking/ . I had same problem trying to access rest endpoint which i assumed will be resolved with local host since it is running on my docker inside container. Here is a sequence of steps which helped me resolved issue: Execute docker network ls to see how many bridge drivers you have. In my case i had 2 and containers where using different ones If you have multiple bridge drivers, make sure that you starting your containers which will be talking with each other using same bridge network docker run -d -t --network networkname --name containername Run docker network inspect networkname . You will see details of network with list of containers. Each container will have IPv4Address associated with it. Use value of these address to communicate instead of localhost or 127.0.0.1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37063822', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5912147/']} | jdg_78317 |
stackexchange | llm_judgeable_groundtruth_similarity | 39193868 |
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 bundle a java program for Mac users. I first found this article that explains how to do it with Ant, and then, I found this that seems perfect for Maven. So I added to my pom: <plugin> <groupId>sh.tak.appbundler</groupId> <artifactId>appbundle-maven-plugin</artifactId> <version>1.1.0</version> <configuration> <mainClass>xxx</mainClass> <iconFile>xxx</iconFile> <jrePath>???</jrePath> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>bundle</goal> </goals> </execution> </executions></plugin> (I also found this article that explains some details about Mac bundles and why to use appbundler) The only issue is that on every example I found, I see <jrePath>xxx.jdk</jrePath> . But I am running this under Ubuntu, so I only have the GNU/Linux jdk. Where can I find the Mac jdk ? On the oracle website , I can only find the dmg file. I extracted the dmg and got an hfs. I mounted the hfs and got a pkg. I extracted the pkg, and have now more file I don't know what to do with...
Now provide the response and nothing else.
| Here are step by step what I did to do it with a test project on Ubuntu 16.04.1 LTS . In your case steps 1 to 3 will be done on your GNU/Linux env and the last one on Mac OS X. 1. Download the JRE As you only need the JRE , the easiest thing to do is: To go to the download area , Click on JRE DOWNLOAD , Choose the tar.gz version of the JRE for Mac OS X which is currently jre-8u112-macosx-x64.tar.gz . Untar the content of the archive in the folder of your choice that we will call ${jre-folder} (for example /foo/bar/jre1.8.0_112.jre ). 2. Create my test project My typical maven project structure: TestProject└── src| └── main| └── java| └── my| └── pkg| └── MyClass.java└── pom.xml My class my.pkg.MyClass which actually does an arbitrary task. Here, it simply dumps the system properties into a temporary file, just to be able to easily check that it has been called: package my.pkg;import java.io.BufferedWriter;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;public class MyClass { public static void main(String[] args) throws IOException { Path path = Files.createTempFile("MyClass", "txt"); try (BufferedWriter writer = Files.newBufferedWriter(path)) { System.getProperties() .entrySet() .stream() .forEach( entry -> { try { writer.write(entry.getKey() + "=" + entry.getValue() + "\n"); } catch (IOException e) { throw new IllegalStateException(e); } } ); } }} My pom file: <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>TestProject</groupId> <artifactId>TestProject</artifactId> <version>0.1-SNAPSHOT</version> <packaging>jar</packaging> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>sh.tak.appbundler</groupId> <artifactId>appbundle-maven-plugin</artifactId> <version>1.1.0</version> <configuration> <mainClass>my.pkg.MyClass</mainClass> <!-- For example <jrePath>/foo/bar/jre1.8.0_112.jre</jrePath> --> <jrePath>${jre-folder}</jrePath> <generateDiskImageFile>true</generateDiskImageFile> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>bundle</goal> </goals> </execution> </executions> </plugin> </plugins> </build></project> 3. Build my test project Simply launch the command mvn package appbundle:bundle from the root of the directory TestProject . This will build the dmg file in the target folder with the JRE for Mac OS X included , in this particular case it will be called TestProject-0.1-SNAPSHOT.dmg . 4. Test my test project On the target Mac OS X : Double click on the dmg file , it will automatically mount the image, Then you will be able to double click on TestProject.app , you will see an icon appear and quickly disappear as the test program is rather short You can check that it worked properly by launching cat $TMPDIR/MyClass* from a terminal, you will then see the content of the temporary file that has been created by the test application. 5. Add resources to the dmg file To add resources to the generated dmg file , you can use additionalResources with a fileSet . <plugin> <groupId>sh.tak.appbundler</groupId> <artifactId>appbundle-maven-plugin</artifactId> <version>1.1.0</version> <configuration> ... <additionalResources> <fileSet> <directory>/path/to/my/resources/folder</directory> <includes> <include>*.pdf</include> </includes> </fileSet> </additionalResources> </configuration> ...</plugin> This example will add all the pdf files from /path/to/my/resources/folder into the generated dmg file . 6. Add resources to the app file To add resources to the generated app file , you can use additionalResources with a fileSet . <plugin> <groupId>sh.tak.appbundler</groupId> <artifactId>appbundle-maven-plugin</artifactId> <version>1.1.0</version> <configuration> ... <additionalBundledClasspathResources> <fileSet> <directory>/path/to/my/resources/folder</directory> <includes> <include>*.pdf</include> </includes> </fileSet> </additionalBundledClasspathResources> </configuration> ...</plugin> This example will add all the pdf files from /path/to/my/resources/folder to the generated app file into /Contents/Java/lib , they will be automatically included to the classpath of your application such that you will be able to access them easily. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39193868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1967800/']} | jdg_78318 |
stackexchange | llm_judgeable_groundtruth_similarity | 540 |
Below is a question asked on the forum bioinformatics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
When you look at all the genome files available from Ensembl. You are presented with a bunch of options. Which one is the best to use/download? You have a combination of choices. First part options: dna_sm - Repeats soft-masked (converts repeat nucleotides to lowercase) dna_rm - Repeats masked (converts repeats to to N's) dna - No masking Second part options: .toplevel - Includes haplotype information (not sure how aligners deal with this) .primary_assembly - Single reference base per position Right now I usually use a non-masked primary assembly for analysis, so in the case of humans: Homo_sapiens.GRCh38.dna.primary_assembly.fa.gz Does this make sense for standard RNA-Seq, ChIP-Seq, ATAC-Seq, CLIP-Seq, scRNA-Seq, etc... ? In what cases would I prefer other genomes? Which tools/aligners take into account softmasked repeat regions?
Now provide the response and nothing else.
| There's rarely a good reason to use a hard-masked genome (sometimes for blast, but that's it). For that reason, we use soft-masked genomes, which only have the benefit of showing roughly where repeats are (we never make use of this for our *-seq experiments, but it's there in case we ever want to). For primary vs. toplevel, very few aligners can properly handle additional haplotypes. If you happen to be using BWA, then the toplevel assembly would benefit you. For STAR/hisat2/bowtie2/BBmap/etc. the haplotypes will just cause you problems due to increasing multimapper rates incorrectly. Note that none of these actually use soft-masking. | {} | {'log_upvote_score': 4, 'links': ['https://bioinformatics.stackexchange.com/questions/540', 'https://bioinformatics.stackexchange.com', 'https://bioinformatics.stackexchange.com/users/383/']} | jdg_78319 |
stackexchange | llm_judgeable_groundtruth_similarity | 28882130 |
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 code to test to stress test the memory management of Linux and Windows OS. Just for further tests I went ahead and checked what values are present in the memory returned by malloc(). The values that are being return are all 0 (zero). I have read the man page of malloc, checked on both Windows and Linux, but I am not able to find the reason for this behavior . According to the manpage the The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. To clear the memory segment, one has to manually use memset(). #include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <stdbool.h>int eat(long total,int chunk){ long i; for(i=0;i<total;i+=chunk){ short *buffer=malloc(sizeof(char)*chunk); if(buffer==NULL){ return -1; } printf("\nDATA=%d",*buffer); memset(buffer,0,chunk); } return 0;}int main(int argc, char *argv[]){ int i,chunk=1024; long size=10000; printf("Got %ld bytes in chunks of %d...\n",size,chunk); if(eat(size,chunk)==0){ printf("Done, press any key to free the memory\n"); getchar(); }else{ printf("ERROR: Could not allocate the memory"); } } Maybe I am missing something.The code is adapted from here EDIT: The problem has been been answered here for the GCC specific output. I believe Windows operating system would be also following the same procedures.
Now provide the response and nothing else.
| The memory returned by malloc() is not initialized, which means it may be anything. It may be zero, and it may not be; 'not initialized' means it could be anything (zero included). To get a guaranteed zeroed page use calloc() . The reason you are seeing zeroed pages (on Linux anyway) is that if an application requests new pages, these pages are zeroed by the OS (or more precisely they are copy-on-write images of a fixed page of zeroes known as the 'global zero page'). But if malloc() happens to use memory already allocated to the application which has since been freed (rather than expanding the heap) you may well see non-zero data. Note the zeroing of pages provided by the OS is an OS specific trait (primarily there for security so that one process doesn't end up with pages that happen to have data from another process), and is not mandated by the C standard. You asked for a source for get_free_page zeroing the page: that says ' get_free_page() takes one parameter, a priority. ... It takes a page off of the free_page_list , updates mem_map , zeroes the page and returns the physical address of the page.' Here 's another post that explains it well, and also explains why using calloc() is better than malloc() + memset() . Note that you aren't checking the entire allocated chunk for zero. You want something like this (untested): int n;char nonzero=0;char *buffer=malloc(sizeof(char)*chunk); if(buffer==NULL){ return -1;}for (n = 0; n<chunk; n++) nonzero = nonzero || buffer[n]; printf("\nDATA=%s\n",nonzero?"nonzero":"zero"); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28882130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1111696/']} | jdg_78320 |
stackexchange | llm_judgeable_groundtruth_similarity | 506590 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The circuit shown below consists of two resistors connected in series that form a closed loop. No electrical sources are in that loop.Let’s assume that the resistance of the wires that connect the resistors and form the loop is zero.Inside the loop is an external changing magnetic field that induces inside that loop a constant EMF of 1 V. The current inside the loop is calculated using Ohm’s Law : The problem was introduced by former MIT professor Walter Lewin. The problem was introduced in this video (starting at 35th min of the video): 8.02x - Lect 16 - Electromagnetic Induction, Faraday's Law, Lenz Law, SUPER DEMO In the video is shown that two voltmeters connected to the same terminals show different values. Can two voltmeters connected to the same terminals show different values? My solution to this problem would be: To measure the voltage between points D and A, the circuit has to be divided into two halves, the left half of the loop and the right half of the loop. If the induced EMF is considered to be equally distributed through the loop then in every half of the loop there is an induced EMF of 0.5 V: The polarity of the the induced EMFs is according to Lenz law. The voltage between points D and A by writing the equation trough the left half of the loop is: The voltage between points D and A by writing the equation trough the right half of the loop is: The conclusion is that there is a unique voltage value between points D and A, and the measured value should be 0.4 V . Now let’s connect to the circuit between points D and A two voltmeters. The two connected voltmeters together with the wires that connect them to the main circuit form a second loop. Let’s assume that the resistance of the wire that connects the voltmeters and forms the second loop is zero. The left half of the second loop is connected to the voltmeter between points C and B, the right half of the second loop is connected to the voltmeter between points F and E. There is also an induced EMF of 1V inside the second loop. If the induced EMF is considered to be equally distributed through the second loop then the final circuit can be represented with the model shown on below. The voltage between points C and B is defined with the following equations: The voltage between points F and E is defined with the following equations: The calculations above match the measurement performed by professor Walter Lewin. My main question is : What is the theoretical potential difference between points D and A?
Now provide the response and nothing else.
| YES , two voltmeters connected to the very same couple of terminals can simultaneously show two different values.The reason is that, since the circuit path is enclosing a variable magnetic flux region, the 'theoretical potential difference' between point D and A is not (uniquely) defined. Actually, that's all there is to it . Because if your circuit sits in a variable magnetic field region, then all the paths between nodes sit in a dB/dt region, and since the line integral of the electric field along any closed path will not always be zero (this is basic physics), it is not possible to define a potential function such that the line integral of E from D to A only depends on the values in D and A . It will depend on the path.(This is basic calculus) Since this notion usually encounters a certain resistance to be accepted, it is worth to have a deeper look at where it comes from and what it entails in detail. Answering to all the doubts that emerged from the numerous internet interactions after Walter Lewin made his 'superdemo' accessible to the masses, requires a lot of space. For the TL;DR people, the rest of this post is structured in this way: A definition of potential difference Where we define what is usually meant for voltage in circuit theory and why you can reduce it to a potential difference (hint: the irrotationality of the electric field makes voltage a function of the endpoints only) Lumped Circuit Theory I : Kirchhoff rulez Where we see what physical condition makes it possible to have an irrotational E field and make use of the concept of voltage as potential difference. (Hint: it's the absence of a varying magnetic flux: Kirchhoff's Voltage Law is just Faraday's law when dphi/dt = 0) Lumped circuit theory II : Limited regions of non-conservativeness outside the circuit's path Where we try to save KVL by hiding circumscribed regions of variable magnetic flux inside the magnetic components (note: this is what Lewin refers as the stinky physics of 'taking the right hand side on the left side' and what I call 'new KVL' or 'amended KVL': if the circuit path does not enclose a variable magnetic field, we can pretend there is a unique voltage expressible as potential difference by simply not looking inside the magnetic components) The Romer-Lewin ring, or: the unlumpable circuit Where we see that when the circuit path encloses a variable magnetic flux KVL is no longer salvageable, and voltage in your circuit becomes path dependent (which means: it is no longer possible to express it as potential difference) Scalar and Vector Potentials Where we take a look at an alternative definition of voltage that admit a scalar potential. (hint: this is what I call the McDonald maneuver, and it entails separating the total electric field into two constituents parts, one conservative that is caused by coulombian interaction, one rotational that is caused by magnetic induction) The role of surface charges Where we look at what makes the total field in the conductor and the resistors the way it is. The concept of partial inductance Where we take a look at how trying to model the induced voltage with partial lumped 'secondary' coils corresponds to a different physical situation and how partial inductances can be used (with due caution) as a tool in the field of electromagnetic compatibility . 1 - A definition of potential difference When you define voltage as the potential difference between two points VBA = VB - VA = Vab (going from a to b) you are implicitly assuming that - apart from an additive constant - the potential function is uniquely determined, that is the (negative of the) path integral of the electric field from a to b does not depend on the particular integration path chosen integration. This situation requires that the electric field E be conservative or, and this name is telling, irrotational . If the electric field is made rotational, as it happens in the presence of a variable magnetic field, then you can get different results at once for Vab, depending on the particular path you choose to compute the integral: you go along the path that passes through R1, you get 0.9V; you go along the path that passes through R2 you get -0.1V; you go along an arbitrary path that follows Snoopy's profile in and out of the conductor and resistors, you get 0.741V, you name it. (Note that I am not mentioning probes at all.) The endpoints alone are no longer sufficient to uniquely determine the voltage. Here's the disambiguation between the two conventions I am going to use. Since it would be too much to use a different letter to denote path-dependent and path-independent voltage, I will use V for both, leaving it to the smalltext to tell them apart. So, Vab stands for and it's the energy per unit charge required to go from point A to point B along the path gamma(a->b). l will denote this, generally path-dependent , voltage with Vab, with lower case letters from start point to endpoint.When the electric field is irrotational, there is a potential function V such that so that the line integral becomes path-independent and only the endpoints A and B needs to be specified, not the path gamma joining them (any path will do). I will call this voltage 'potential difference' and will denote it with VBA, with capital letters ordered from endpoint to start point. Note: the endpoint comes first, since I adopt the convention VBA = VB - VA (graphically represented with an arrow going from A to B). This will further help in differentiate between the two. A little digression There really is nothing strange in having line integrals dependent on path, in fact it's conservative fields that are almost magically special. In the real world it is normal to consider a function computed by integration along a path to depend on the particular path itself and not on its endpoints alone. Consider the energy spent to reach the top of a mountain in your car from the same parking lot and let's measure it in gallons of gasoline: if you choose a straight path you need 10 gallons, if you choose a loose spiral you need 20 gallon, a loose spiral against the wind and it's 25 gallons, but if it's along with the wind it's 18 gallon; a wobbly path with backs and forth and it's 35 gallons. (It's a very high mountain, mind you).Would you find it strange if the answer to "what is the theoretical gasoline consumption for going from A to B?" was "it depends"? Of course not, you would be surprised of the contrary. (And yet you could think of a minimum consumption that could be thought of as 'unique', I get back to that later, when I introduce the vector potential). Also, would you expect your gas tank to refill itself by simply going down to the parking lot? I believe you would be very much surprised if that happened. And yet, that's what happens with conservative fields: going full circle will give you a zero line integral. They are the counterintuitive stuff, not the other way around. 2 - Lumped Circuit Theory I : Kirchhoff rulez Lumped circuit theory is so easy because it is based on this special, almost magical, kind of fields. The theory is so simple and beautiful that many engineers cannot let go of it and try to use it even when it is not applicable.The fundamental assumption of lumped circuit theory is that you must be able to define voltage between two points independently of the path. Considered the definition of voltage given above this means that and in particular, if we choose a closed path of integration, i.e. a=b, the circulation of E must be zero It turns out that having zero circulation for the electric field along any closed path is a necessary and sufficient condition for the existence of a potential function. Now, since one of the fundamentals laws of physics, Faraday's law, states that it follows that if we want to be able to express voltage as a path independent potential difference, we must avoid regions of changing magnetic flux. Feynman is very clear about this in his Lectures: Volume II, Ch. 22, "AC Circuits" (emphasis mine.) Suppose we have a circuit consisting of a generator and severalimpedances connected together, as shown in Fig. 22–9. According to ourapproximations there is no magnetic field in the region outside theindividual circuit elements . Therefore the line integral of E around any curve which does not passthrough any of the elements is zero. Consider then the curve Γ shownby the broken line which goes all the way around the circuit inFig. 22–9. The line integral of E around this curve is made up ofseveral pieces. Each piece is the line integral from one terminal of acircuit element to the other. This line integral we have called thevoltage drop across the circuit element. The complete line integral isthen just the sum of the voltage drops across all of the elements inthe circuit: Since the line integral is zero, we have that the sum of the potentialdifferences around a complete loop of a circuit is equal to zero: This result follows from one of Maxwell’s equations—that in a regionwhere there are no magnetic fields the line integral of E around anycomplete loop is zero. So, KVL is just a particular special case of Faraday's law, when the electric field behaves in that magical way that will refill your gas tank when you go from the top of the mountain back to the parking lot.If your circuit path encloses a varying magnetic field then you are out of luck: the voltages in your circuit will not have unique values for the same endpoints but will also depend on the particular path along which you compute the line integral.But notice that Feynman says: "According to our approximations there is no magnetic field in the region outside the individual circuit elements ." So, there is room for some magnetic field madness, it seems. Well, within reason. 3 - Lumped circuit theory II : Limited regions of nonconservativeness outside the circuit's path If we were to completely avoid regions of varying magnetic (and displacement) field, we would be stuck with simply resistive circuits. Let's see if we can work out a solution that allows for dynamic elements such as inductors (and capacitors) into the picture without giving up the simple tools represented by KVL (and KCL). Turns out we can, if we add the extra proviso that all the variable field craziness be left outside of the circuit path by confining it inside lumped components. Leaving the variable magnetic region outside the circuit's path will allow us to define voltages in the circuit in an unique manner and use Kirchhoff laws to compute voltages and currents as we did with resistive circuits. By hiding the complexity of variable magnetic (and electric fields) inside the dynamic components, we can pretend that the voltage across them and the current through them still obey Kirchhoff rules, while in fact, deep inside, they are determined by the more general laws of Faraday-Neumann and Ampere-Maxwell. Let's consider the following circuit, with a generator, a resistor, an inductor, and a capacitor along the path that connects all their terminals together: The variable magnetic field regions are indicated by shaded regions and are relegated inside the magnetic element. The closed path can be decomposed into the following segments: Now, if - as it happens in this picture - the circuit's path does not enclose a variable magnetic field region, we can write the path integral of the electric field across the closed loop a-b-c-d-a and rest assured it is zero. This is the condition required to consider voltages function of the endpoints only, and for KVL to work (sum of voltages along a closed circuit is zero).KVL works because, by not enclosing any variable magnetic field in our circuit path Gamma, all voltages can be considered path-independent and it does not matter how we integrate from one terminal to the other. But are all voltages in this circuit really all path-independent? Well, no . We just pretend they are by turning a blind eye at those that are not. It turns out that when we come across the magnetic component, we can choose paths that go from one terminal to the other by entering or encircling the variable magnetic flux region. The voltage computed as a line integral along those paths will in general be path-dependent. Not all paths going from one terminal to the other give the same result, if we go inside the component We can have paths from C to D crossing the region of variable magnetic field so that there are closed loops passing from C and D whose line integral is not zero. This means that we can have multiple values for the voltage between C and D. In particular there are different values for the line integral going from point C to point D in the space between terminal (say a voltage V) and another, different, value for the line integral along the path that follow the coil inside the conductor (and that value is zero). There is hope, though. Among the infinite number of paths to choose from, those that do not go inside or around the forbidden region (like those indicated by \$\gamma_1\$ , \$\gamma_2\$ , and \$\gamma_3\$ ) all give the same result (in fact, by choosing them we always end up with an overall circuit path that will not enclose the magnetic variable region.) So, if when we consider a path connecting the terminals we are smart enough to stay clear of the variable magnetic flux region, our circuit path will be in the clear, and - if we can delude ourselves that the coil voltage only depends on the endpoints (it does not!) - we will be able to use a mock-up version of KVL (much in the same way that jumping at the capacitor's terminals we can use a mock-up version of KCL) Now, the problem is to find what is that one value of the path integral along any 'safe' path that goes from one terminal to the other without going inside or around the forbidden zone of the magnetic element. It turns out we can easily compute it by using - you guessed it - Faraday's law. The fake 'potential difference' across a coil We are going to consider this part of the circuit where we the value of \$B(t)\$ or \$\Phi(t)\$ is determined by the effects of a nuclear explosion, a falling magnet, another coil or even elven magic (but note that I am not considering the case of a moving coil - meaning we are in a frame of reference where the coil CD is at rest) We are interested in the line integral along one of the 'safe' paths from C to D, that we will call \$\gamma_{term}\$ . We can easily compute it considering it as part of a closed loop that encircles the variable flux region by going through the copper (so that the electric field has a known or easy to compute value and direction) We can split the closed loop line integral into its constituent parts i.e. the path that connects the terminals from C to D ( \$\gamma_{term}\$ ), and the path that goes through copper from D to C ( \$\gamma_{copper}\$ ): what we are interested in is the fist integral on the right hand side, that corresponds to the mock-up 'potential difference' at the coil terminals. We can find it right away considering that the circulation of the electric field across the closed loop has a value given by Faraday's law, and that the line integral going through the copper is zero because the electric field inside a stationary perfect conductor - even under the effect of induction - is zero: and here is the result for our mock-up 'potential difference': I put "VDC" in quotes because it is not a real potential difference, since in general this voltage depends on the path and not only on the endpoints C and D. But if we can make sure that we refer it to paths that do not get into or around the inductor's guts, we can pretend it is single-valued. The voltage you see at the terminals of the inductor is the time derivative of the magnetic flux phi. The sign of the voltage depends on the orientation of the magnetic field and on how it is changing (decreasing, increasing) If you want, add that \$\Phi = L * i\$ (and in that case, since the magnetic flux is produced by the current in the loop itself, the sign of the voltage will follow from Lenz's law) or \$\Phi = M * i\$ (here the sign also depend on how you orient the coils) and you get the well known relations for self and mutual inductance. But this result is also valid for magnetic field changes caused by a falling magnet or a nuclear explosion. Zero field in the conductor means no voltage build up inside the coil Now, what it most interesting to us is that, despite the voltage presented at the terminals, the (total) electric field inside the copper conductor the coil is made of is zero. There is no 'incremental voltage build up' so to speak. All voltage appears at the terminals. This is how Ramo, Whinnery, and VanDuzer put it (p. 171 in the 2nd edition, emphasis mine) "The voltage at the terminals of the magnetic element comes from thetime rate of change of magnetic flux within the inductor, shown in thefigure as coil. Assuming first that resistance of the conductor of thecoil is negligible, let us take a closed line integral of electricfield along the conductor of the coil, returning by the path acrossthe terminals, fig. 4.2b. Since the contribution along the part of thepath that follows the conductor is zero , all the voltage appearsacross the terminals." How is it possible to have the path integral of the (total, see later expansion) electric field E be zero inside the coil's conductor, when we can measure a voltage at its terminals? Well, much like in the case of electrostatic induction, the charge that produces the field outside the copper is the very same charge responsible for making it zero inside the copper. In the electrostatic case the path integral is zero both inside and outside the conductor; in the quasi-static case of induction in a stationary conductor, the path integral is zero inside but non-zero outside. If you compute the line integral of the electric field jumping along a safe path from one terminal to the other, you get nonzero values (corresponding to the voltage that is given by the time derivative of the magnetic flux) because there is an overall non-conservative electric field in the space between the terminals, but if you compute the line integral from the same two endpoints by going inside the conductor, you get zero because inside the perfect conductor in these quasi-static conditions there is no electric field. So, there you have it: multiple values for the voltage between the same two points in all your circuits using any form of inductor. The trick we use in circuit theory is just to pretend not to see the infinitely many values the line integral can have if we choose paths inside the component's forbidden region, and only look at the nice paths outside of it that consistently give the same value. By forgetting that it is only one value among many, we call that voltage a 'potential difference' even if there is no potential function . Now, if you were to make voltage measurements in your circuit you would get consistent results, no matter the path you choose as long as you stay out and do not go around the forbidden region inside the magnetic component . It is with this proviso that we can pretend we can still talk about path-independent voltages and potential differences. The working of your circuit is based on that illusory 'unique' voltage at the inductor's terminals.But if you put your probes around or inside the magnetic component, you will commit a probing error, because messing with the forbidden region will destroy that illusion. Sneak preview: Why can't the 'amended KVL' work in the Romer-Lewin ring? The Romer-Lewin ring has some points in common with the above lumped circuit, but also some striking differences.Similarly to the circuit with an inductor, there is no total electric field inside the conductor, and all the E field end up between the resistors (or non-magnetic components) terminals.The really big difference is that now it's the circuit path that encircles a variable magnetic flux region, hence we are always inside the 'forbidden region' where KVL does not work and we cannot 'stay out' of it like we did in the case of the isolated magnetic component. Since in general the line integral of the total electric field along any closed loop will not be zero but equal to minus the time derivative of the magnetic flux enclosed by the path, we cannot have a potential function. Voltages in the circuit will in general be path-dependent , and we have to expect multiple values for the voltage between two points. This multivaluedness of voltage is not the result of a measurement error, it is just a consequence of the fact that all the circuit sits in (encircles) the forbidden zone, and thus KVL, not even the 'amended' one, cannot work there. You cannot take two terminals out and put them in a 'safe' circuit path the does not go around the forbidden zone, as we did for the lumped inductor in the previous circuit.Moreover, if you were to subtract the effects of induction thinking this is what good probing is about, you would commit a probing error. You will end up measuring a voltage that does not correspond to the actual configuration of electric field in the circuit but correspond instead to only a part of it (this is shown in part 5 where the induced field is subtracted the total field). What is the "5 + 3 = 8 is not 5 + 3 - 8 = 0" all about? Had we chosen to go from one terminal of the inductor to the other following the conductor, we would have had to abandon KVL and resort to the more general Faraday's law, because the new overall circuit path would be enclosing a variable magnetic field: And this is the right way to treat problems with changing magnetic flux: 5 + 3 = 8. It does not pretend that the voltage be path-independent (it isn't) and makes the contribution of the magnetic flux explicit in the right hand side of the equation. But if we are desperate to see our beloved KVL again, we can take the right hand side term to the left hand side, and we end up with 5 + 3 - 8 = 0, the 'amended version' of KVL, where the mock-up inductor voltage is the time derivative of the magnetic flux. This is convenient, because we can pretend KVL still works, but it is also misleading because it makes it seem that the voltage is path-independent when in fact it isn't. 4 - The Romer-Lewin ring In the Romer-Lewin ring two (lumped) resistors are placed inside a coil enclosing a variable flux region so that the circuit's path encloses a dB/dt region. Feynman is adamant: you cannot use lumped circuit theory. Lewin is also adamant: you cannot use Kirchhoff's law (it's for the birds!), so we need to go back to the more general relation: Faraday's Law. If you accept that the variable B field will generate a rotational E field, things can be explained by looking at how charges in the circuit react to the induced field, change their configuration and produce a different resulting electric field inside and nearby the ring. If you were to magically make the ring made of copper conductor and two resistors appear inside this circulating field, the charges inside and on the surface of its parts would almost instantaneously redistribute themselves in such a way as to obey Ohm's law. We can get a glimpse of what drives the charge redistribution by considering the continuity equation.Charge displacement - gradients in charge density \$\rho\$ - happens on the surface also in the longitudinal direction, anywhere there be gradients in the values of conductivity and permeability. If we assume \$\frac{\partial \rho}{\partial t}=0\$ , then the continuity equation becomes div j = 0 and by adding compliance to Ohm's law we get if \$\sigma\$ depends on the coordinates, we can expand the above as Charge density is linked to electric displacement, and in a medium of relative permeability \$\epsilon_r\$ we can express this in terms of electric field by Let's get rid of div E = -1/sigma . grad sigma And now let us express E in terms of \$j = \sigma E\$ . We find that charge density in the circuit goes like and we see that charge density, for a given current density, changes according to gradients in conductivity and permeability. Good luck in solving that. But when you do it you see that charge will be displaced producing an additional electric field that will almost completely cancel out the tangential part of the electric field in the conductor. In a perfect conductor with infinite conductivity, the tangential field would be zero inside it. With a finite value for sigma, we get a resulting tangential E field, compatible with the constitutive equation \$j = \sigma E\$ . (Tiny field in copper, large field in resistive materials.) Charges will distribute themselves around the conductor in order to produce a very small, usually negligible electric field directed axially along the copper conductor, and they will also accumulate at the discontinuity in conductivity at the extremes of the resistors, basically producing a voltage that is coherent with Ohm's law for the resulting current. Summarizing: if we consider the current density j to be the same along the whole circuit (by taking the conductor and the resistor of the same diameter, only differing in material), we will see a very small electric field inside the highly conductive copper (hence no distribution of imaginary partial coils voltages inside the conductor), a big electric field inside the the small resistor (responsible for the 0.1V 'voltage' along the path going through it, the sign depends on the direction) and a much bigger electric field inside the bigger resistor (responsible for the 0.9V 'voltage' along the path going through it). The sum of all voltages along the loop (note that they have definite values because I am specifying a path) is not zero , but it's 1V, as predicted by Faraday's law. Note that there are no probes in the drawing above.All voltages shown are single-valued because we are computing them specifying a path along the circuit (again, we have to specify the path because in non-conservative fields such integrals are path dependent).The fact that we find two different values of the voltage between A and B (namely 0.9V and -0.1V) is an expected consequence of the fact that the whole circuit path is enclosing a variable magnetic field region, and thus ordinary circuit theory is not applicable. So the answer to your question "what is the theoretical voltage between points A and B?" is " it depends , along which path do you want it computed?". (I had to remove the rest, post too long) | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/506590', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/214320/']} | jdg_78321 |
stackexchange | llm_judgeable_groundtruth_similarity | 306327 |
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:
On high school, I was taught that I could obtain any sine value with some basic arithmetic on the values of the following image: But I never really understood where these values where coming from, some days ago I started to explore it but I couldn't discover it. After reading for a while, I remembered that the sine function is: $$\sin=\frac{\text{opposite}}{\text{hypotenuse}}$$ Then I thought that I just needed to calculate $\frac{1}{x}$ where $0 \leq x \leq 1$ but it gave me no good results, then I thought that perhaps I could express not as a proportion of the opposite and hypotenuse, I thought I could express it as the ratio between slices of the circumference, for example: circumference $=\pi$, then divided it by $4$ (to obtain the slice from $0$ to $90$ degrees) then I came with: $x/ \frac{\pi}{4}$ where $0\leq x \leq \frac{\pi}{4} $ but it also didn't work, the best guess I could make was $\sqrt{x/ \frac{\pi}{4}}$, the result is in the following plot: The last guess I made seems to be (at least visually) very similar to the original sine function, it seems it needs only to be rotated but from here, I'm out of ideas. Can you help me?
Now provide the response and nothing else.
| All of the values in your picture can be deduced from two theorems: The Pythagorean theorem: If a right triangle has sides $a,b,c$ where $c$ is the hypotenuse, then $a^2+b^2=c^2$ If a right triangle has an angle of $\frac{\pi}{6} = 30^\circ$, then the length of the side opposite to that angle is half the length of the hypotenuse. Both can be proven with elementary high school geometry. Let's see how this works for Quadrant I (angles between $0$ and $90^\circ$), as the rest follows from identities. $\sin 0 = 0$; this is clear from the definition. $\sin 90^\circ = 1$; less intuitive because it breaks the triangle, but $\sin 90^\circ =\cos0$, and $\cos 0 = 1$ because the adjacent side and the hypotenuse coincide when the angle is $0$. $\sin 45^\circ = \frac{1}{\sqrt{2}}$; this corresponds to an isosceles triangle, and if we set the sides to be $1$, then by the Pythagorean theorem, the hypotenuse is $\sqrt{2}$. $\sin30^\circ = \frac{1}{2}$; this follows immediately from theorem 2 above. $\sin60^\circ = \frac{\sqrt{3}}{2}$; if we take a $30^\circ-60^\circ-90^\circ$ triangle, and set the side opposite to the $30^\circ$ angle to be $1$, then the hypotenuse is $2$ and the side opposite to the $60^\circ$ angle satisfies $x^2 + 1 = 2^2$, so its length is $\sqrt{3}$ - and thus $\sin 60^\circ = \frac{\sqrt{3}}{2}$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/306327', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/25805/']} | jdg_78322 |
stackexchange | llm_judgeable_groundtruth_similarity | 18189874 |
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 break some rock by developing a website on my own, and I'm starting by creating some registry pages and listing database records. I'm getting bugged with the fact that __unicode__ method doesn't print the username of my records and __str__ does! I know that using __unicode__ is the best practice to have, but I can only print my object username with __str__ . Can anybody explain why this happens? My Model: from django.db import modelsclass User(models.Model): username = models.CharField(max_length=200) reg_date = models.DateTimeField('registry date') def __unicode__(self): return self.username My admin.py: from django.contrib import adminfrom registo.models import Useradmin.site.register(User) My __unicode__(self) output: User User object My __str__(self) output: User Teste Thanks for your cooperation in advance!
Now provide the response and nothing else.
| it looks like you are using Python3.x and here is the relevant documentation on Str and Unicode methods In Python 2, the object model specifies __str__() and __unicode__() methods. If these methods exist, they must return str (bytes) and unicode (text) respectively. The print statement and the str() built-in call __str__() to determine the human-readable representation of an object. The unicode() built-in calls __unicode__() if it exists, and otherwise falls back to __str__() and decodes the result with the system encoding. Conversely, the Model base class automatically derives __str__() from __unicode__() by encoding to UTF-8. In Python 3, there’s simply __str__() , which must return str (text). So On Python 3, the decorator is a no-op. On Python 2, it defines appropriate __unicode__() and __str__() methods (replacing the original __str__() method in the process). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18189874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1729416/']} | jdg_78323 |
stackexchange | llm_judgeable_groundtruth_similarity | 27703138 |
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 followed http://aparnaank.blogspot.in/2014/03/how-to-configure-wso2-bps-workermanager.html link for clustering WSO2 BPS. When all servers started and ELB showing that two members has joined. When i click (Try It) for a web service i am getting following error [2014-12-30 15:30:38,237] ERROR {org.apache.catalina.core.StandardWrapperValve} - Servlet.service() for servlet [bridgeservlet] in context with path [/] threworg.apache.axis2.AxisFault at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430) at org.wso2.carbon.core.transports.CarbonServlet.doGet(CarbonServlet.java:155) at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61) at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128) at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68) at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter.doFilter(CharacterSetFilter.java:61) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178) at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:49) at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141) at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936) at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619)Caused by: java.lang.NullPointerException at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:768) at org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils.getTenantConfigurationContext(TenantAxisUtils.java:120) at org.wso2.carbon.core.multitenancy.utils.TenantAxisUtils.getTenantAxisConfiguration(TenantAxisUtils.java:104) at org.wso2.carbon.wsdl2form.WSDL2FormGenerator.getAxisService(WSDL2FormGenerator.java:702) at org.wso2.carbon.wsdl2form.WSDL2FormGenerator.getInternalTryit(WSDL2FormGenerator.java:112) at org.wso2.carbon.tryit.TryitRequestProcessor.process(TryitRequestProcessor.java:49) at org.wso2.carbon.core.transports.CarbonServlet.processWithGetProcessor(CarbonServlet.java:182) at org.wso2.carbon.core.transports.CarbonServlet.doGet(CarbonServlet.java:145) ... 31 more What to i do now Thanks in advance....
Now provide the response and nothing else.
| You want a Map<String, Code> , but how to populate it neatly? Enums don't allow you to initialize a static fields before the enum instances are initialized, but there's a neat little trick, called the Initialization-on-demand holder idiom , that makes using a statically initialized map needed for this functionality easy to implement: public enum Code { CODE_1("string1"), CODE_2("string2"), CODE_3("string3"), // etc ; private static class Holder { static Map<String, Code> CODE_MAP = new HashMap<>(); } private final String code; private Code(String code) { this.code = code; Holder.CODE_MAP.put(code, this); } public String getCode() { return this.code; } public Code convertFromString(String code) { return Holder.CODE_MAP.get(code); }} This works because the class loader initializes inner static classes before initializing the enum class, so the map is assigned ready to load during enum instance initialization. No loops. No special code to load the map (done in constructor). Minimal code. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27703138', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3978130/']} | jdg_78324 |
stackexchange | llm_judgeable_groundtruth_similarity | 6063347 |
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 a best practice? To use try or use rescue ? user.try(:email) VS user.email rescue nil post.try(:comments).try(:first).try(:author) VS post.comments.first.author rescue nil Is there any difference in using any of these?
Now provide the response and nothing else.
| Try and rescue serve different purposes. The purpose of try is to save you from having to do: if user && user.email Or any situation where the parent object can possibly be nil, which would cause a NoMethodError on NilClass. The purpose of rescue is to handle exceptions that get thrown by your method invocation. If you expect an exception from calling user.email , then you can rescue nil it to prevent the exception from bubbling up. In general, I'd say avoid using rescue nil unless you know explicitly what exceptions you are rescuing because you could be rescuing a different exception, and you would never know it because rescue nil would prevent you from seeing it. At the very least maybe you could log it: begin ...some code...rescue => ex logger.error ex.messageend | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6063347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/512433/']} | jdg_78325 |
stackexchange | llm_judgeable_groundtruth_similarity | 15408156 |
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 'cookbook' way of resampling a DataFrame with (semi)irregular periods? I have a dataset at a daily interval and want it to resample to what sometimes (in scientific literature) is named dekad's. I dont think there is a proper English term for it but its basically chopping a month in three ~ten-day parts where the third is a remainder of anything between 8 and 11 days. I came up with two solutions myself, a specific one for this case and a more general one for any irregular periods. But both arent really good, so im curiuous how others handle these type of situations. Lets start with creating some sample data: import pandas as pdbegin = pd.datetime(2013,1,1)end = pd.datetime(2013,2,20)dtrange = pd.date_range(begin, end)p1 = np.random.rand(len(dtrange)) + 5p2 = np.random.rand(len(dtrange)) + 10df = pd.DataFrame({'p1': p1, 'p2': p2}, index=dtrange) The first thing i came up with is grouping by individual months (YYYYMM) and then slicing it manually. Like: def to_dec1(data, func): # create the indexes, start of the ~10day period idx1 = pd.datetime(data.index[0].year, data.index[0].month, 1) idx2 = idx1 + datetime.timedelta(days=10) idx3 = idx2 + datetime.timedelta(days=10) # slice the period and perform function oneday = datetime.timedelta(days=1) fir = func(data.ix[:idx2 - oneday].values, axis=0) sec = func(data.ix[idx2:idx3 - oneday].values, axis=0) thi = func(data.ix[idx3:].values, axis=0) return pd.DataFrame([fir,sec,thi], index=[idx1,idx2,idx3], columns=data.columns)dfmean = df.groupby(lambda x: x.strftime('%Y%m'), group_keys=False).apply(to_dec1, np.mean) Which results in: print dfmean p1 p22013-01-01 5.436778 10.4098452013-01-11 5.534509 10.4822312013-01-21 5.449058 10.4547772013-02-01 5.685700 10.4226972013-02-11 5.578137 10.5321802013-02-21 NaN NaN Note that you always get a full month of 'dekads' in return, its not a problem and easy to remove if needed. The other solution works by providing a range of dates at which you chop up the DataFrame and perform a function on each segment. Its more flexible in terms of the periods you want. def to_dec2(data, dts, func): chucks = [] for n,start in enumerate(dts[:-1]): end = dts[n+1] - datetime.timedelta(days=1) chucks.append(func(data.ix[start:end].values, axis=0)) return pd.DataFrame(chucks, index=dts[:-1], columns=data.columns)dfmean2 = to_dec2(df, dfmean.index, np.mean) Note that im using the index of the previous result as the range of dates to save some time 'building' it myself. What would be the best way of handling these cases? Is there perhaps a bit more build-in method in Pandas?
Now provide the response and nothing else.
| If you use numpy 1.7, you can use datetime64 & timedelta64 arrays to do the calculation: create the sample data: import pandas as pdimport numpy as npbegin = pd.datetime(2013,1,1)end = pd.datetime(2013,2,20)dtrange = pd.date_range(begin, end)p1 = np.random.rand(len(dtrange)) + 5p2 = np.random.rand(len(dtrange)) + 10df = pd.DataFrame({'p1': p1, 'p2': p2}, index=dtrange) calculate the dekad's date: d = df.index.day - np.clip((df.index.day-1) // 10, 0, 2)*10 - 1date = df.index.values - np.array(d, dtype="timedelta64[D]")df.groupby(date).mean() The output is: p1 p22013-01-01 5.413795 10.4456402013-01-11 5.516063 10.4913392013-01-21 5.539676 10.5287452013-02-01 5.783467 10.4780012013-02-11 5.358787 10.579149 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15408156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1755432/']} | jdg_78326 |
stackexchange | llm_judgeable_groundtruth_similarity | 25329302 |
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 connect with PostgreSQL database through Laravel in order to do a php artisan migrate but doesn't seem to be directed since it's reading the database name of MySQL. Here are the commands from database.php: 'connections' => array( 'sqlite' => array( 'driver' => 'sqlite', 'database' => __DIR__.'/../database/production.sqlite', 'prefix' => '', ), 'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), 'pgsql' => array( 'driver' => 'pgsql', 'host' => 'localhost', 'database' => 'postgres', 'username' => 'postgres', 'password' => 'root', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ), 'sqlsrv' => array( 'driver' => 'sqlsrv', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'prefix' => '', ),), If I remove the MySQL paths I'll get: [InvalidArgumentException]Database [mysql] not configured. EDIT: When trying to do php artisan migrate I get a 'PDOException: could not find driver'. I'm using WAMP and I'm in Win8.1. Using PostgreSQL as database. EDIT: Have experimented a series of alternative solutions but I'm still ought to get this solved.The php.ini file was checked in Apache, WAMP (from php folder) and PostgreSQL. The extension_dir is correct as it being -> extension_dir = "c:/wamp/bin/php/php5.5.12/ext/" The extension=pdo_pgsql.dll and extension=pgsql.dll are uncommented. Done the PATH trick in the 'System Variables' and rebooted. No chance. Thanks for the help so far. These are my drivers php_pdo_driver.h & php_pdo.h from C:\Program Files (x86)\PostgreSQL\EnterpriseDB-ApachePHP\php\SDK\include\ext\pdo Information from phpinfo: PHP Version 5.5.12 Compiler MSVC11 (Visual C++ 2012) Configure Command cscript /nologo configure.js "--enable-snapshot-build" "--disable-isapi" "--enable-debug-pack" "--without-mssql" "--without-pdo-mssql" "--without-pi3web" "--with-pdo-oci=C:\php-sdk\oracle\x64\instantclient10\sdk,shared" "--with-oci8=C:\php-sdk\oracle\x64\instantclient10\sdk,shared" "--with-oci8-11g=C:\php-sdk\oracle\x64\instantclient11\sdk,shared" "--enable-object-out-dir=../obj/" "--enable-com-dotnet=shared" "--with-mcrypt=static" "--disable-static-analyze" "--with-pgo"
Now provide the response and nothing else.
| Be sure to configure the 'default' key in app/config/database.php For postgres, this would be 'default' => 'postgres', If you are receiving a [PDOException] could not find driver error, check to see if you have the correct PHP extensions installed. You need pdo_pgsql.so and pgsql.so installed and enabled. Instructions on how to do this vary between operating systems. For Windows, the pgsql extensions should come pre-downloaded with the official PHP distribution. Just edit your php.ini and uncomment the lines extension=pdo_pgsql.so and extension=pgsql.so Also, in php.ini , make sure extension_dir is set to the proper directory. It should be a folder called extensions or ext or similar inside your PHP install directory. Finally, copy libpq.dll from C:\wamp\bin\php\php5.*\ into C:\wamp\bin\apache*\bin and restart all services through the WampServer interface. If you still get the exception, you may need to add the postgres \bin directory to your PATH : System Properties -> Advanced tab -> Environment Variables In 'System variables' group on lower half of window, scroll through and find the PATH entry. Select it and click Edit At the end of the existing entry, put the full path to your postgres bin directory. The bin folder should be located in the root of your postgres installation directory. Restart any open command prompts, or to be certain, restart your computer. This should hopefully resolve any problems. For more information see: http://php.net/manual/en/install.pecl.windows.php http://webcheatsheet.com/php/install_and_configure.php#extsetup | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25329302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3944643/']} | jdg_78327 |
stackexchange | llm_judgeable_groundtruth_similarity | 42834529 |
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 a series of elements, as shown in the image below: They are rotated 45 degrees to one side (the content inside -45 degrees, to remain upright). Now I'd like to rotate each element around a vertical axis, going through the element's center. RotateY doesn't work, as it is at a 45-degree angle. How would you go about doing this?
Now provide the response and nothing else.
| The trick is to set this rotation before the 45 degrees rotation: Notice also that to make the rotation behave really as expect, you need to set it to 0 in the base state .container { width: 200px; height: 200px; margin: 100px; border: solid 1px; transform: rotateY(0deg) rotate(45deg); /* needs Y at 0 deg to behave properly*/ transition: transform 2s;}.container:hover { transform: rotateY(180deg) rotate(45deg); /* notice the order */}.inner { margin: 50px; transform: rotate(-45deg);} <div class="container"><div class="inner">INNER</div></div> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42834529', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6502862/']} | jdg_78328 |
stackexchange | llm_judgeable_groundtruth_similarity | 2158636 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to find the value of $$\sum_{k=1}^{\infty}{\frac{1}{(k+2)(k+3)}}$$ I do not believe it is geometric, it cannot be divided into two fractions that both converge, but it definitely does converge, and, according to WolframAlpha, to $\frac{1}{3}$. Any way I can easily show this with no more than basic calculus? Thank you.
Now provide the response and nothing else.
| Note that $$\frac{1}{k+2}-\frac{1}{k+3}=\frac{(k+3)-(k+2)}{(k+2)(k+3)}=\frac{1}{(k+2)(k+3)}$$ so $$\begin{align}\sum_{k=1}^n \frac{1}{(k+2)(k+3)}&=\vphantom{\cfrac1{\cfrac11}}\sum_{k=1}^n \left(\frac{1}{k+2}-\frac{1}{k+3}\right)\\&=\left(\frac{1}{3}-\color{#4488dd}{\frac{1}{4}}\right)+\left(\color{#4488dd}{\frac{1}{4}}-\color{#ff4444}{\frac{1}{5}}\right)+\bigg(\color{#ff4444}{\frac{1}{5}}+\underbrace{\frac16\bigg)+\cdots+\bigg(\frac{1}{n+2}}_{\text{cancellations}}-\frac{1}{n+3}\bigg)\\&=\frac13-\frac{1}{n+3}\end{align}$$ (as the middle terms are cancelling each other) Now, what's the value of $\sum_{k=1}^\infty \frac{1}{(k+2)(k+3)}$? | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2158636', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/170240/']} | jdg_78329 |
stackexchange | llm_judgeable_groundtruth_similarity | 4310469 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A "Brain Teaser" with Trigonometry: If $$\begin{align}\tan^3 (\alpha) +2\tan^3 (\beta)&=\phantom{0}6 \\\tan^4 (\alpha) +2\tan^4 (\beta)&=18 \\\tan^5 (\alpha) +2\tan^5 (\beta)&=30 \\\tan^6 (\alpha) +2\tan^6 (\beta)&=66\end{align}$$ Then find $\cot(\alpha+\beta)$ . Answer is $3$ . I have tried to form terms of $\tan(\alpha+\beta)$ by multiplying 1st term with $\tan(\alpha) +\tan(\beta)$ and again 1st term with $\tan^2(\alpha) +\tan^2(\beta)$ to get relationship with different terms hoping to extract $\tan(\alpha) \tan(\beta)$ and cancel out terms but no use. Any suggestions???
Now provide the response and nothing else.
| Something of a trick here. If you render $6=8-2,18=16+2,30=32-2,66=64+2$ you discover that the equations are satisfied by rendering $\tan\alpha=2,\tan\beta=-1$ . Then apply the identity $\tan(\alpha+\beta)=\dfrac{\tan\alpha+\tan\beta}{1-\tan\alpha\tan\beta}$ and proceed from there. There is also a way to extract $\tan\alpha$ and $\tan\beta$ without "inspection". Let these parameters be $a$ and $b$ respectively and consider first the two equations $a^3+2b^3=6$ $a^6+2b^6=66$ From the first equation render $a^3=6-2b^3$ , thus substitute $(6-2b^3)^2$ for $a^6$ into the second equation. This leads to $b^6-4b^3-5=0$ which can be solved as a quadratic equation for $b^3$ . Thus $b^3\in\{-1,5\}$ and $a^3=6-2b^3$ , from which we then obtain the two candidate solutions $a=\tan\alpha=2, b=\tan\beta=-1$ $a=\tan\alpha=-\sqrt[3]4, b=\tan\beta=\sqrt[3]5$ The second candidate, with its cube-root surds, cannot give the required whole number sums for $a^4+2b^4$ and $a^5+2b^5$ , so only the first one checks with all four equations. We then proceed with the tangent formula as above. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4310469', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/935130/']} | jdg_78330 |
stackexchange | llm_judgeable_groundtruth_similarity | 65713 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a set of observations, independent of time. I am wondering whether I should run any autocorrelation tests? It seems to me that it makes no sense, since there's no time component in my data. However, I actually tried serial correlation LM test, and it indicates strong autocorrelation of residuals. Does it make any sense? What I'm thinking is that I can actually rearrange observations in my dataset in any possible order, and this would change the autocorrelation in residuals. So the question is - should I care at all about autocorrelation in this case? And should I use Newey-West to adjust SE for it in case test indicates so? Thanks!
Now provide the response and nothing else.
| The true distinction between data, is whether there exists, or not, a natural ordering of them that corresponds to real-world structures, and is relevant to the issue at hand. Of course, the clearest (and indisputable) "natural ordering" is that of time, and hence the usual dichotomy "cross-sectional / time series". But as pointed out in the comments, we may have non-time series data that nevertheless possess a natural spatial ordering. In such a case all the concepts and tools developed in the context of time-series analysis apply here equally well, since you are supposed to realize that a meaningful spatial ordering exists, and not only preserve it, but also examine what it may imply for the series of the error term, among other things related to the whole model (like the existence of a trend, that would make the data non-stationarity for example). For a (crude) example, assume that you collect data on number of cars that has stopped in various stop-in establishments along a highway, on a particular day (that's the dependent variable). Your regressors measure the various facilities/services each stop-in offers, and perhaps other things like distance from highway exits/entrances. These establishments are naturally ordered along the highway... But does this matter? Should we maintain the ordering, and even wonder whether the error term is auto-correlated? Certainly : assume that some facilities/services on establishment No 1 are in reality non-functional during this particular day (this event would be captured by the error term). Cars intending to use these particular facilities/services will nevertheless stop-in, because they do not know about the problem. But they will find out about the problem, and so, because of the problem , they will also stop in the next establishment, No 2, where, if what they want is on offer, they will receive the services and they won't stop in establishment No 3 - but there is a possibility that establishment No 2 will appear expensive, and so they will, after all, try also establishment No 3: This means that the dependent variables of the three establishments may not be independent, which is equivalent to say that there is the possibility of correlation of the three corresponding error terms, and not "equally", but depending on their respective positions. So the spatial ordering is to be preserved, and tests for autocorrelation must be executed -and they will be meaningful. If on the other hand no such "natural" and meaningful ordering appears to be present for a specific data set, then the possible correlation between observations should not be designated as "autocorrelation" because it would be misleading, and the tools specifically developed for ordered data are inapplicable. But correlation may very well exist, although in such case, it is rather more difficult to detect and estimate it. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/65713', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/28479/']} | jdg_78331 |
stackexchange | llm_judgeable_groundtruth_similarity | 270627 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider: MoleculePlot[Molecule[Entity["Chemical", "Theobromine"]]] How can I rotate and reflect it? This is my current method: img=Image[MoleculePlot[Molecule[Entity["Chemical", "Theobromine"]]]];ImageRotate[ImageReflect[img]] I would like two improvements on my current method: The result is no longer a Graphics object. Instead I would like to retain the same Head (i.e., Graphics ). I want to retain the orientation of the atom labels as they were in the first plot, i.e., the "right way up".
Now provide the response and nothing else.
| MoleculeValue [m1, "AtomDiagramCoordinates"] If the idea is to change the MoleculePlot (2D diagram) as described in the question after the edit , then one can use: Block[ { chem=Entity["Chemical", "Theobromine"], tr = ReflectionTransform[{1, -1}], coords, m1,m2 }, m1 = Molecule[chem]; coords= MoleculeValue[m1, "AtomDiagramCoordinates"]; m2 = Molecule[chem , AtomDiagramCoordinates->tr@coords ]; MoleculePlot/@{m1,m2}] Credit goes to @J.M for inspiring this answer, and for the much more compact alternative offered in the comments {mol,coords} = EntityValue[Entity["Chemical","Theobromine"] ,{"Molecule","VertexCoordinates"} ];MoleculePlot[ Molecule[ mol ,AtomDiagramCoordinates->ReflectionTransform[{1,-1}][coords] ]] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/270627', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/21532/']} | jdg_78332 |
stackexchange | llm_judgeable_groundtruth_similarity | 18889941 |
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 print the entire stack trace using java.util.Logger? (without annoying Netbeans). The question should've originally specified staying within Java SE. Omitting that requirment was an error on my part. -do-compile: [mkdir] Created dir: /home/thufir/NetBeansProjects/rainmaker/build/empty [mkdir] Created dir: /home/thufir/NetBeansProjects/rainmaker/build/generated-sources/ap-source-output [javac] Compiling 13 source files to /home/thufir/NetBeansProjects/rainmaker/build/classes [javac] /home/thufir/NetBeansProjects/rainmaker/src/model/TelnetEventProcessor.java:44: error: 'void' type not allowed here [javac] log.severe(npe.printStackTrace(System.out)); [javac] ^ [javac] 1 errorBUILD FAILED code with the error: package model;import java.util.Observable;import java.util.logging.Logger;import java.util.regex.Matcher;import java.util.regex.Pattern;public class TelnetEventProcessor extends Observable { private static Logger log = Logger.getLogger(TelnetEventProcessor.class.getName()); private String string = null; public TelnetEventProcessor() { } private void stripAnsiColors() { Pattern regex = Pattern.compile("\\e\\[[0-9;]*m"); Matcher regexMatcher = regex.matcher(string); string = regexMatcher.replaceAll(""); // *3 ?? } public void parse(String string) { this.string = string; ifs(); } // [\w]+(?=\.) private void ifs() { log.fine("checking.."); if (string.contains("confusing the hell out of")) { Pattern pattern = Pattern.compile("[\\w]+(?=\\.)"); //(\w+)\. Matcher matcher = pattern.matcher(string); String enemy = null; GameData data = null; while (matcher.find()) { enemy = matcher.group(); } try { data = new GameData.Builder().enemy(enemy).build(); log.fine("new data object\t\t" + data.getEnemy()); setChanged(); notifyObservers(data); } catch (NullPointerException npe) { log.severe(npe.printStackTrace(System.out)); } } else if (string.contains("Enter 3-letter city code:")) { log.fine("found enter city code"); } else { } }} see also: https://stackoverflow.com/a/7100975/262852
Now provide the response and nothing else.
| The severe method is only used to log severe messages without associated throwable information. If you need to log throwable information then you should use the log method instead: try { data = new GameData.Builder().enemy(enemy).build(); log.fine("new data object\t\t" + data.getEnemy()); setChanged(); notifyObservers(data);} catch (NullPointerException npe) { log.log(Level.SEVERE, npe.getMessage(), npe);} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18889941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262852/']} | jdg_78333 |
stackexchange | llm_judgeable_groundtruth_similarity | 30016868 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am following this link: http://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#_client_side_usage I tested this again and again and not seeing Spring cloud client is loading configuration from cloud server, please help to see where is the error: POM: <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency></dependencies> Application: @Configuration@EnableAutoConfiguration@RestControllerpublic class ConfigclientApplication { @Value("${spring.cloud.config.uri}") String url; @Value("${production.host}") String host; @RequestMapping("/") public String home() { return "Host is => " + this.host ; } public static void main(String[] args) { SpringApplication.run(ConfigclientApplication.class, args); }} bootstrap.properties:spring.cloud.config.uri=http://localhost:8888 The config server is good:http://localhost:8888/spirent/default { "name": "spirent", "profiles": [ "default" ], "label": "master", "propertySources": [ { "name": "classpath:/spirent.yml", "source": { "production.host": "server1", "production.port": 9999, "production.value1": 12345, "test.host": "server2.com", "test.port": 4444, "test.value": "hello123" } } ]} now http://localhost:8080/ can not be started at all. Error creating bean with name 'configclientApplication'It seemed the auto inject of @Value can not find the production.host environment value. How can I read the configuration in client once loaded from config server? Thanks for your help.
Now provide the response and nothing else.
| For those getting here after using the default Maven Spring Cloud dependency version related to Spring Boot to 2.4.0 or 2.4.1 (e.g., 2020.0.0-M5 for Spring Boot 2.4.0), besides following RubesMN's good advice, be aware that bootstrapping is not enabled by default in such Spring Cloud dependency. According to the Spring Cloud 2020.0 Release Notes : Bootstrap, provided by spring-cloud-commons, is no longer enabled by default. If your project requires it, it can be re-enabled by properties or by a new starter. To re-enable by properties set spring.cloud.bootstrap.enabled=true or spring.config.use-legacy-processing=true. These need to be set as an environment variable, java system property or a command line argument. The other option is to include the new spring-cloud-starter-bootstrap (in your POM file). I used the second option and worked just fine. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30016868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3006967/']} | jdg_78334 |
stackexchange | llm_judgeable_groundtruth_similarity | 5511274 |
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 edit my project file to enable me to have a project that builds multiple build configs at once. I've done this using a batching approach and using the MSBuild task (see below). If I run the script, I get an this error: Error 103 The OutputPath property is not set for project "ThisMSBuildProjectFile.csproj". Please check to make sure that you have specified a valid combination of Configuration and Platform for this project. Configuration='Debug' Platform='AnyCPU'. I get this if I add or omit the OutputPath from the MSBuild task. If used the VS2010 debugger to step through the script and the MSBuild Task is called - the debugger steps into the file again and then steps into OutputPath, so afaik, it should pick that value up, no? Any help for this would be greatly appreciated - it's driving me crazy. Thanks, Paul. ThisMSBuildProjectFile.csproj (surplus stuff taken out): <?xml version="1.0" encoding="utf-8"?><Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build"> <!-- Only Import normal targets if not building multiple projects --> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" Condition="'$(Configuration)|$(Platform)' != 'AllBuild|AnyCPU' "/> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == '' "> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>C:\Folder\Etc\Output\$(Configuration)\</OutputPath> <OutDir>C:\Folder\Etc\Output\$(Configuration)\</OutDir> <BaseOutputPath>C:\Folder\Etc\Output\$(Configuration)\</BaseOutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <!-- Common --> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <Platform>AnyCPU</Platform> <!-- Repeated properties from above here (including, of course, OutputPath) --> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <!-- Repeated properties from above here (including, of course, OutputPath) --> </PropertyGroup> <ItemGroup> <Projects Include="C:\Folder\Etc\ThisMSBuildProjectFile.csproj" /> </ItemGroup> <!-- Call this project file again, but with a different configuration - if this was working, this would call multiple build configs --> <Target Name="Build" Condition="'$(Configuration)|$(Platform)' == 'AllBuild|AnyCPU' "> <Message Text="hm!"/> <!-- Tried thiswith and without the OutputPath property - makes no difference. --> <MSBuild Projects="@(Projects)" Properties="Configuration=Debug;OutputPath=C:\Folder\Etc\Output\" ToolsVersion="4.0" Condition="'$(Configuration)|$(Platform)' == 'AllBuild|AnyCPU' "/> </Target> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'AllBuild|AnyCPU' "> <!-- Repeated properties from above here (including, of course, OutputPath) --> </PropertyGroup> <!-- Project files --> <ItemGroup> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="Blah\Blah.cs" /> </ItemGroup>
Now provide the response and nothing else.
| It is important to realize that when you use a "MSBuild" task, a new child MSBuild process will be started. The implication of this is that any items and properties you define in the parent MSBuild process will not be automatically passed to/visible from the child MSBuild process unless you explicitely pass them via Properties attribute on MSBuild element (as in <MSbuild Properties="..." /> ). To answer your question, I wrote the following self-contained example that runs a child MSBuild project for all the specified configurations: First, create a directory for your MSBuild experiment (for example I used C:\temp\msbuildtest ) In this directory, create the first file, main.proj : <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0"> <ItemGroup> <ConfigList Condition=" '@(ConfigList)' == '' and $(Config) != '' " Include="$(Config.Split('+'))" /><!-- parse all requested configurations into a list --> <ConfigList Condition=" '@(ConfigList)' == '' " Include="Debug" /><!-- if no configurations were specified, default to Debug --> </ItemGroup> <!-- Build the child project for each requested configuration. --> <Target Name="Build"> <MSBuild Projects="$(MSBuildProjectDirectory)\child.proj" Properties="Configuration=%(ConfigList.Identity);OutputPath=$(MSBuildProjectDirectory)\bin\%(ConfigList.Identity)" Targets="Build" /> </Target></Project> In the same directory, create the second file, child.proj (in your case this would be the actual C# project you're trying to build, but because I'm trying to illustrate my point, I am using a simple child project that instead of running C# compiler just prints values of properties :-) ) <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0"> <Target Name="Build"> <Message Text="Building configuration $(Configuration) with output path $(OutputPath)" Importance="High" /> </Target></Project> Now you can run the example. First the default, if you don't explicitly specify configurations to build: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\msbuild main.proj> (cut the noise)> Build:> Building configuration Debug with output path C:\temp_c\d\bin\Debug And then explicitly specified multiple configurations: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\msbuild main.proj /property:Config=Debug+Release+Staging+Production> (cut the noise)> Build:> Building configuration Debug with output path C:\temp_c\d\bin\Debug> Build:> Building configuration Release with output path C:\temp_c\d\bin\Release> Build:> Building configuration Staging with output path C:\temp_c\d\bin\Staging> Build:> Building configuration Production with output path C:\temp_c\d\bin\Production You should be able to adapt this technique to your situation. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5511274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541894/']} | jdg_78335 |
stackexchange | llm_judgeable_groundtruth_similarity | 42907285 |
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 source files in my project change, django server reloads. I want to extend this to non-Python source files. I use native SQL queries, which are stored in separate files (eg. big_select.sql ), and I want the server to reload when these files change. I use django on Windows. I have tried adding .py extension, which didn't work.
Now provide the response and nothing else.
| Django>=2.2 The autoreloading was given a major overhaul (thanks to @Glenn who notified about the incoming changes in this comment !), so one doesn't have to use the undocumented Django features and append files to _cached_filenames anymore. Instead, register custom signal listener, listening to autoreloading start: # apps.pyfrom django.apps import AppConfigfrom django.utils.autoreload import autoreload_starteddef my_watchdog(sender, **kwargs): sender.watch_file('/tmp/foo.bar') # to listen to multiple files, use watch_dir, e.g. # sender.watch_dir('/tmp/', '*.bar')class EggsConfig(AppConfig): name = 'eggs' def ready(self): autoreload_started.connect(my_watchdog) Django<2.2 Django stores the watched filepaths in the django.utils.autoreload._cached_filenames list, so adding to or removing items from it will force django to start or stop watching files. As for your problem, this is the (kind of a hacky) solution. For the demo purpose, I adapted the apps.py so the file starts being watched right after django initializes, but feel free to put the code wherever you want to. First of all, create the file as django can watch only files that already exist: $ touch /tmp/foo.bar In your django app: # apps.pyfrom django.apps import AppConfig...import django.utils.autoreloadclass MyAppConfig(AppConfig): name = 'myapp' def ready(self): ... django.utils.autoreload._cached_filenames.append('/tmp/foo.bar') Now start the server, in another console modify the watched file: $ echo baz >> /tmp/foo.bar The server should trigger an autoreload now. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42907285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6362349/']} | jdg_78336 |
stackexchange | llm_judgeable_groundtruth_similarity | 24512712 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According the MDN documentation calling array.slice() will create a shallow copy of the array. See this MDN link for slice() . However, if I run a simple test as such in the console: var test = [[1,2,3],7,8,9];var shallow_copy = test.slice(); and inspect shallow_copy, I can see that the entire 2 dimensional array appears to be copied over. What is the difference between a shallow copy and a deep copy? If I were to guess, I would have called this a deep copy.
Now provide the response and nothing else.
| To see the difference, try: shallow_copy[0][2] = 4;console.dir(test); You'll see that test has been modified! This is because while you may have copied the values to the new array, the nested array is still the same one. A deep copy would recursively perform shallow copies until everything is a new copy of the original. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24512712', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_78337 |
stackexchange | llm_judgeable_groundtruth_similarity | 408177 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I prove $\sqrt{x + y} \le \sqrt{x} + \sqrt{y}$? for $x, y$ positive? This should be easy, but I'm not seeing how. A hint would be appreciated.
Now provide the response and nothing else.
| For positive $x, y$ , we have: $$\sqrt{x + y} \leq \sqrt{x} + \sqrt{y} \iff \left(\sqrt{x + y}\right)^2 \leq \left(\sqrt x + \sqrt y\right)^2 \iff \color{blue}{\bf x + y \leq x + y + 2\sqrt{xy}}$$ What can you conclude about the leftmost "inequality", given its equivalence to the $\color{blue}{\bf rightmost\;inequality}$ ? | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/408177', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80492/']} | jdg_78338 |
stackexchange | llm_judgeable_groundtruth_similarity | 2388932 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone know why I get undefined method `my_method' for #<MyController:0x1043a7410> when I call my_method("string") from within my ApplicationController subclass? My controller looks like class MyController < ApplicationController def show @value = my_method(params[:string]) endend and my helper module ApplicationHelper def my_method(string) return string endend and finally, ApplicationController class ApplicationController < ActionController::Base after_filter :set_content_type helper :all helper_method :current_user_session, :current_user filter_parameter_logging :password protect_from_forgery # See ActionController::RequestForgeryProtection for details
Now provide the response and nothing else.
| You cannot call helpers from controllers. Your best bet is to create the method in ApplicationController if it needs to be used in multiple controllers. EDIT : to be clear, I think a lot of the confusion (correct me if I'm wrong) stems from the helper :all call. helper :all really just includes all of your helpers for use under any controller on the view side. In much earlier versions of Rails, the namespacing of the helpers determined which controllers' views could use the helpers. I hope this helps. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2388932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83897/']} | jdg_78339 |
stackexchange | llm_judgeable_groundtruth_similarity | 51004506 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given the following pandas data frame: ColA ColB ColC0 a1 t 11 a2 t 22 a3 d 33 a4 d 4 I want to get a dictionary of dictionary. But I managed to create the following only: d = {t : [1, 2], d : [3, 4]} by: d = {k: list(v) for k,v in duplicated.groupby("ColB")["ColC"]} How could I obtain the dict of dict: dd = {t : {a1:1, a2:2}, d : {a3:3, a4:4}}
Now provide the response and nothing else.
| You can do this with a groupby + apply step beforehand. dd = df.set_index('ColA').groupby('ColB').apply( lambda x: x.ColC.to_dict()).to_dict() Or, with a dict comprehension: dd = {k : g.ColC.to_dict() for k, g in df.set_index('ColA').groupby('ColB')} print(dd){'d': {'a3': 3, 'a4': 4}, 't': {'a1': 1, 'a2': 2}} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51004506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1945881/']} | jdg_78340 |
Subsets and Splits