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
16000282
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 reading the answer mentioned to the question" Do we ever need to use Iterators on ArrayList? ". In the answer, the user stated something like this: "A big use case of iterators with ArrayLists is when you want to remove elements while iterating". This could be achieved even using remove method of ArrayList in Java. My question is why we need iterator in ArrayList? Consider the code: import java.util.*;public class ocajp66 { public static void main(String[] args) { ArrayList a = new ArrayList(); for (int i = 0; i < 10; i++) { a.add(i); } System.out.printf("BEFORE ITERATOR\n"); for (int i = 0; i < a.size(); i++) { System.out.printf("I:%d\n", a.get(i)); } System.out.printf("AFTER ITERATOR\n"); Iterator i = a.iterator(); while (i.hasNext()) { System.out.printf("I:%d\n", i.next()); } }} Can anybody explain the significance of the iterator? It would be wonderful if you could explain me with code. Now provide the response and nothing else.
As you have stated iterator is used when you want to remove stuff whilst you iterate over the array contents. If you don't use an iterator but simply have a for loop and inside it use the remove method you will get exceptions because the contents of the array changes while you iterate through. e.g: you might think array size is 10 at the start of the for loop but it wont be the case once you remove stuff.. so when u reach the last loops probably there will be IndexOutofBoundsException etc.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16000282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1985975/']}
jdg_375241
stackexchange
llm_judgeable_groundtruth_similarity
44098385
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 Subscription model which contain start_date and end_date attributes in my Laravel app. I have created two query scopes, scopeActive and scopeFuture to find active and future subscriptions (respectively). I would like to know how I can build a query using both scopes in OR context, so that I can find any active or future subscriptions. Subscription Model /** * Scope a query to only include active subscriptions. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */public function scopeActive($query){ return $query->where('start_date', '<', Carbon::now()) ->where('end_date', '>', Carbon::now());}/** * Scope a query to only include future subscriptions. * * @param \Illuminate\Database\Eloquent\Builder $query * @return \Illuminate\Database\Eloquent\Builder */public function scopeFuture($query){ return $query->where('start_date', '>', Carbon::now());}public function business(){ return $this->belongsTo('App\Business');} Business Model .....public function subscriptions(){ return $this->hasMany('App\Subscription');} User Model public function business(){ return $this->hasOne('App\Business');} Controller Subscription::active()->get(); Now provide the response and nothing else.
For static-context try: $subscriptions = Subscription::query() ->active() ->orWhere(function ($query) { $query->future(); }) ->get(); First call query() to prevent errors (because we may have a non-static method with " active " as name). Relation query (as requested in the comment) $subscriptions = auth()->user() ->business() ->subscriptions() ->active() ->orWhere(function ($query) { $query->future(); }) ->get(); Note that above we don't need to call query() (because it's not from static-context).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44098385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180837/']}
jdg_375242
stackexchange
llm_judgeable_groundtruth_similarity
20012533
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 trying to create a django form and one of my field contain a ModelChoiceField class FooForm(forms.Form): person = forms.ModelChoiceField(queryset=Person.objects.filter(is_active=True).order_by('id'), required=False) age = forms.IntegerField(min_value=18, max_value=99, required=False) When I try the code above what it return as an html ouput is <option value="1">Person object</option> on my Person Model I have the fields "id, fname, lname, is_active" . Is it possible to specify that my dropdown option will use "id" as the value and "lname" as the label? The expected htmlshould be <option value="1">My Last Name</option> Thanks in advance! Now provide the response and nothing else.
You can just add a call to label_from_instance in the init of Form ie by adding something like class TestForm(ModelForm): def __init__(self, *args, **kwargs): super(TestForm, self).__init__(*args, **kwargs) self.fields['field_name'].label_from_instance = self.label_from_instance @staticmethod def label_from_instance(obj): return "My Field name %s" % obj.name
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20012533', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2192691/']}
jdg_375243
stackexchange
llm_judgeable_groundtruth_similarity
5944747
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 making a date matching regex, and it's all going pretty well, I've got this so far: "/(?:[0-3])?[0-9]-(?:[0-1])?[0-9]-(?:20)[0-1][0-9]/" It will (hopefully) match single or double digit days and months, and double or quadruple digit years in the 21st century. A few trials and errors have gotten me this far. But, I've got two simple questions regarding these results: (?: ) what is a simple explanation for this? Apparently it's a non-matching group. But then... What is the trailing ? for? e.g. (? )? Now provide the response and nothing else.
[Edited (again) to improve formatting and fix the intro.] This is a comment and an answer. The answer part... I do agree with alex' earlier answer. (?: ) , in contrast to ( ) , is used to avoid capturing text, generally so as to have fewer back references thrown in with those you do want or to improve speed performance. The ? following the (?: ) -- or when following anything except * + ? or {} -- means that the preceding item may or may not be found within a legitimate match. Eg, /z34?/ will match z3 as well as z34 but it won't match z35 or z etc. The comment part... I made what might considered to be improvements to the regex you were working on: (?:^|\s)(0?[1-9]|[1-2][0-9]|30|31)-(0?[1-9]|10|11|12)-((?:20)?[0-9][0-9])(?:\s|$) -- First, it avoids things like 0-0-2011 -- Second, it avoids things like 233443-4-201154564 -- Third, it includes things like 1-1-2022 -- Forth, it includes things like 1-1-11 -- Fifth, it avoids things like 34-4-11 -- Sixth, it allows you to capture the day, month, and year so you can refer to these more easily in code.. code that would, for example, do a further check (is the second captured group 2 and is either the first captured group 29 and this a leap year or else the first captured group is <29) in order to see if a feb 29 date qualified or not. Finally, note that you'll still get dates that won't exist, eg, 31-6-11. If you want to avoid these, then try: (?:^|\s)(?:(?:(0?[1-9]|[1-2][0-9]|30|31)-(0?[13578]|10|12))|(?:(0?[1-9]|[1-2][0-9]|30)-(0?[469]|11))|(?:(0?[1-9]|[1-2][0-9])-(0?2)))-((?:20)?[0-9][0-9])(?:\s|$) Also, I assumed the dates would be preceded and followed by a space (or beg/end of line), but you may want ot adjust that (eg, to allow punctuations). A commenter elsewhere referenced this resource which you might find useful: http://rubular.com/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5944747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/385273/']}
jdg_375244
stackexchange
llm_judgeable_groundtruth_similarity
348609
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Can't seem to find an answer to this question on AWS' forum, not in the Route53 manual, nor on Stackoverflow/Serverfault in a way that makes sense...and GoDaddy's support sure as heck ain't got an answer: How do I set an MX record in Route53 for a GoDaddy domain? My apex record and all CNAME records on Route53 are working correctly, pointing to my app on EC2. But I would love to be able to login to http://login.secureserver.net to check my web-based e-mail for this domain. In case it's pertinent, GoDaddy's "Email Info Center" for the domain returns... Domain settings can be invalid if the system cannot verify your email address or if the MX records are incorrect. For additional information, see Managing DNS for your domain names. Type Host IP Address Nameserver ns-AAA.awsdns-47.com XXX.XXX.XX3.X22Nameserver ns-BBB.awsdns-55.net XXX.XXX.XX5.X86Nameserver ns-CCCC.awsdns-24.org XXX.XXX.XX6.X97Nameserver ns-DDDD.awsdns-11.co.uk XXX.XXX.XX8.92 GoDaddy e-mail server settings listed as... Server Standard Ports Your Open Ports Incoming server (POP3): pop.secureserver.net 110, 995 (SSL) 110, 995 (SSL) Outgoing server (SMTP): smtpout.secureserver.net 80, 3535, 25, 465 (SSL) 80, 3535, 25, 465 (SSL) In the AWS console for Route53, is it just a matter of creating a MX record set with... Name = mail.mydomain.comValue = 10 pop.secureserver.net 20 smtpout.secureserver.net ...??? Now provide the response and nothing else.
To make things nice and clear, as some of the GoDaddy help articles are dead wrong: You just need to paste the two records from the server settings into your Route 53 control panel as a new record. The possible deception here is the the GD email panel will tell you you're wrong, but not what is right so you can make it right. Further, their help article tells you do look for the proper MX record settings under the Domains manager, where you'll not find them. Finally, AWS is a tad confusing since they'll only let you enter a single apex domain MX entry. You can't have two as GD wants and some other zone managers allow, hence the need to double them up. Hope this helps others! :)
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/348609', 'https://serverfault.com', 'https://serverfault.com/users/105110/']}
jdg_375245
stackexchange
llm_judgeable_groundtruth_similarity
29361801
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The linker from the LLVM project lld is currently developed with new features added week by week. Its developers promise that lld is faster than ld . How does it compete compared to gold ? Is lld a drop-in replacement for ld ? With gold there are some hoops to jump through . Now provide the response and nothing else.
One of the LLD developers, Rui Ueyama, looks back at the progress LLD did in 2016, see http://lists.llvm.org/pipermail/llvm-dev/2016-December/107981.html . "Now I'm pretty sure that that [LLD] is going to be a serious (and better, in my opinion) alternative to the existing GNU linkers [..]." "LLD is now able to link most x86-64 userland programs." "The FreeBSD project and we are trying to make LLD the system default linker of the operating system, and except a few tricky programs such as the kernel or a bootloader, the linker works mostly fine." Already achieved! "LLD supports x86, x86-64, x32, AArch64, AMDGPU, ARM, PPC64 and MIPS32/64,though completeness varies." "[T]here are already a few systems that are using LLD as systemlinkers, such as CloudABI or Fuchsia. Chromium and Clang/LLVM itself hasbuild options to use LLD to build them." And, as a bonus: "LLD got faster [..] At the beginning of this year,LLD took about 16 seconds to produce a 1.5 GB clang (debug build)executable. Now, it takes about 14.5 seconds on single core and 8.5 secondson 20 cores. ld.gold takes about 25 seconds and 20 seconds,respectively. [..] If you have a problem of too long link time, I'd recommend to try LLD." Update spring 2017 According to one of the developers "LLD/ELF is now ready for production use at least for x86-64 (and probably for AArch64 and MIPS).", see http://lists.llvm.org/pipermail/llvm-dev/2017-March/111083.html It also contains a brief description on how to make use of LLD.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29361801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2799037/']}
jdg_375246
stackexchange
llm_judgeable_groundtruth_similarity
55892917
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 ionic installed in my system. When i run ionic run app tabs it installs all the npm packages but then the prompt falls to Downloading binary from https://github.com/sass/node-sass/releases/download/v4.11.0/linux-x64-72_binding.nodeCannot download "https://github.com/sass/node-sass/releases/download/v4.11.0/linux-x64-72_binding.node":HTTP error 404 Not Found Then it fails with the prompt showing gyp ERR! build error gyp ERR! stack Error: `make` failed with exit code: 2gyp ERR! stack at ChildProcess.onExit (/home/l3g0b0y/code/greenlink/node_modules/node-gyp/lib/build.js:262:23)gyp ERR! stack at ChildProcess.emit (events.js:196:13)gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:256:12)gyp ERR! System Linux 4.15.0-47-genericgyp ERR! command "/home/l3g0b0y/.nvm/versions/node/v12.0.0/bin/node" "/home/l3g0b0y/code/greenlink/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="gyp ERR! cwd /home/l3g0b0y/code/greenlink/node_modules/node-sassgyp ERR! node -v v12.0.0gyp ERR! node-gyp -v v3.8.0gyp ERR! not ok Build failed with error code: 1npm notice created a lockfile as package-lock.json. You should commit this file.npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.8 (node_modules/fsevents):npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.8: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})npm WARN optional SKIPPING OPTIONAL DEPENDENCY: node-sass@4.11.0 (node_modules/node-sass):npm WARN optional SKIPPING OPTIONAL DEPENDENCY: node-sass@4.11.0 postinstall: `node scripts/build.js`npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1 I have already tried removing node_modules and reinstall the packages. I tried reinstalling ionic-cli as well. Which doesn't work. I'm using node v12.0.0 npm v6.9.0 ionic v4.12.0 Now provide the response and nothing else.
Indeed, the version https://github.com/sass/node-sass/releases/download/v4.11.0/linux-x64-72_binding.node is not available because you are using node v12 and try to get unsupported version of node-sass for node v12. The solution is to downgrade your node version to v11 or upgrade your node-sass dependency to the latest. If you (for visitors having the same issue w/ another library. Here, it is ionic ) are using node-sass as a vendor library, downgrade to node v11 and notify the library developer team to the need for an update.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55892917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_375247
stackexchange
llm_judgeable_groundtruth_similarity
15904896
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There is a range-based for loop with the syntax: for(auto& i : array) It works with constant arrays but not with pointer based dynamic ones, like int *array = new int[size];for(auto& i : array) cout<< i << endl; It gives errors and warnings about failure of substitution, for instance: Error] C:\Users\Siegfred\Documents\C-Free\Temp\Untitled2.cpp:16:16: error: no matching function for call to 'begin(int*&)' How do I use this new syntax with dynamic arrays? Now provide the response and nothing else.
To make use of the range-based for-loop you have to provide either begin() and end() member functions or overload the non-member begin() and end() functions.In the latter case, you can wrap your range in a std::pair and overload begin() and end() for those: namespace std { template <typename T> T* begin(std::pair<T*, T*> const& p) { return p.first; } template <typename T> T* end(std::pair<T*, T*> const& p) { return p.second; } } Now you can use the for-loop like this: for (auto&& i : std::make_pair(array, array + size)) cout << i << endl; Note, that the non-member begin() and end() functions have to be overloaded in the std namespace here, because pair also resides in namespace std . If you don't feel like tampering with the standard namespace, you can simply create your own tiny pair class and overload begin() and end() in your namespace. Or, create a thin wrapper around your dynamically allocated array and provide begin() and end() member functions: template <typename T> struct wrapped_array { wrapped_array(T* first, T* last) : begin_ {first}, end_ {last} {} wrapped_array(T* first, std::ptrdiff_t size) : wrapped_array {first, first + size} {} T* begin() const noexcept { return begin_; } T* end() const noexcept { return end_; } T* begin_; T* end_; }; template <typename T> wrapped_array<T> wrap_array(T* first, std::ptrdiff_t size) noexcept { return {first, size}; } And your call site looks like this: for (auto&& i : wrap_array(array, size)) std::cout << i << std::endl; Example
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15904896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2223424/']}
jdg_375248
stackexchange
llm_judgeable_groundtruth_similarity
110966
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 W be the Weyl a group of a semisimple simply connected group over C. Let I={1,...,r} the set of simple roots. For $w\in W$, I denote by supp(w) the subset of I corresponding to the simple reflexions that appear in a reduced decomposition of w. Let w an element such that supp(w)=I and length(w)>r+1, is it true that there exist an element w' such that 1/ $w'\leq w$ 2/length (w')=r+1 3/supp(w')=I ? Now provide the response and nothing else.
Some added observations on what is likely to be a very complicated problem: The 2010 Selecta Math. paper by Fresse and Melnikov which you mention was posted here , but the published version is somewhat longer. I haven't checked the precise differences, but this is always a hazard when consulting arXiv preprints. The joint work of Melnikov with various people has uncovered many of the known results about singularities of irreducible components of Springer fibers. This builds on work of Francis Fung in type $A$ , for example, and mostly deals with aspects that can be formulated combinatorially. As far as I can see, the geometry of Springer fibers is little understood, beyond the older work of Spaltenstein which determined in general the dimensions of the fibers and proved the equidimensionality of their components. So the refined study of singularities (or normality) is likely to require some new ideas. While I agree with what Alexander Woo says in his first paragraph, I don't agree with his reading of the 1979 Kazhdan-Lusztig paper. As their introduction indicates, they were motivated by several different-looking problems including Springer's representations of Weyl groups (on cohomology of fibers in the Springer desingularization of the unipotent variety), the indirectly related problem of working out singularities of Schubert varieties, and the even more indirectly related problem of understanding algebraic work on Verma modules and primitive ideals in enveloping algebras. While those subjects do have connections, they are rather subtle, as Geordie's comment indicates. One aspect which remains mysterious to me is the rough analogy between two pictures: Schubert varieties in the flag variety and their partial ordering (corresponding to the Chevalley-Bruhat ordering in the Weyl group); unipotent classes or nilpotent orbits and their closure ordering. In each case you have varieties which are sometimes not smooth, and might or might not even be normal. Moreover, the two pictures are connected indirectly by the fact that the Springer fibers live in the cotangent bundle of the flag variety. All of this requires unpacking, even in type $A$ where the combinatorics is better-behaved. Concerning Springer fibers and their irreducible components, the cohomology of a fiber turns out to be important in representation theory of different flavors. On the other hand, Slodowy's work on slices to nilpotent orbits leads to smooth varieties in the cotangent bundle which have twice the dimension of the corresponding Springer fiber but lead to the same equivariant K-theory in Lusztig's further work. He has studied these equivariant cohomology groups and their canonical bases extensively. In some ways this may be a more fruitful aspect of Springer fibers than the nonsingularity of their components, but there are many unknowns.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/110966', 'https://mathoverflow.net', 'https://mathoverflow.net/users/27398/']}
jdg_375249
stackexchange
llm_judgeable_groundtruth_similarity
70917
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 $\mu$ be a probability measure on a set of $n$ elements and let $p_i$ be the measure of the $i$-th element. Its Shannon entropy is defined by $$E(\mu)=-\sum_{i=1}^np_i\log(p_i)$$ with the usual convention that $0\cdot(-\infty)=0$. The following are two fundamental properties: Property 1: $E(\mu)$ takes its minimum on the Dirac measures. Property 2: $E(\mu)$ takes its maximum on the uniform probability measure. Now, for some application, I am really interested in a possible generalization when $\mu$ is a finitely additive probability measure on the natural numbers. Question: Is it possible to define a notion of entropy of a finitely additive probability measure on the natural numbers in such a way that it verifies the following properties: it takes its minimum on the Dirac measures it takes its maximum on the finitely additive translation invariant probability measures Any reference? Idea? Thanks in advance, Valerio Now provide the response and nothing else.
I don't know if someone has already defined such entropy and I am not an expert on these things, but (depending what is wanted) I would start with something like$$E(\mu)=\sup\left\{-\sum_{i=1}^n\mu(A_i)\log(\mu(A_i)) : \mathbb{N} = \bigcup_{i=1}^n A_i, A_i \text{ pairwise disjoint}\right\}.$$ Some properties this entropy would have are It equals the Shannon entropy for measures that are concentrated on finitely many numbers. It gives value $+\infty$ for finitely additive translation invariant probability measures. A related definition for arbitrary measure spaces $(X,m)$ is the relative Shannon entropy (a.k.a. the Kullback–Leibler divergence )$$E(\mu) = \int_X \frac{d\mu}{dm} \log\left(\frac{d\mu}{dm}\right)dm,$$where $\frac{d\mu}{dm}$ is the Radon-Nikodym derivative of $\mu$ w.r.t. $m$. One could fix a finitely additive measure $m$ and try to work with that.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/70917', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13809/']}
jdg_375250
stackexchange
llm_judgeable_groundtruth_similarity
42854598
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I reset the index of my pandas DataFrame with "inplace=True" (following the documentation ) it returns a class 'NoneType'. If I reset the index with "inplace=False" it returns the DataFrame with the new index. Why? print(type(testDataframe))print(testDataframe.head()) returns: <class 'pandas.core.frame.DataFrame'> ALandbouwBosbouwEnVisserij AantalInkomensontvangers AantalInwoners \0 73780.0 None 16979120 1 290.0 None 25243 2 20.0 None 3555 Set_index returns a new index: testDataframe = testDataframe.set_index(['Codering']) print(type(testDataframe)) print(testDataframe.head()) returns <class 'pandas.core.frame.DataFrame'> ALandbouwBosbouwEnVisserij AantalInkomensontvangers \Codering NL00 73780.0 None GM1680 290.0 None WK168000 20.0 None BU16800000 15.0 None But the same set_index with "inplace=True": testDataframe = testDataframe.set_index(['Codering'], inplace=True)print(type(testDataframe))print(testDataframe.head()) returns <class 'NoneType'>---------------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-50-0d6304ebaae1> in <module>() Version info: python: 3.4.4.final.0python-bits: 64pandas: 0.18.1numpy: 1.11.1IPython: 5.2.2 Now provide the response and nothing else.
Ok, now I understand, thanks for the comments! So inplace=True should return None and make the change in the original object. It seemed that on listing the dataframe again, no changes were present. But of course I should not have assigned the return value to the dataframe, i.e. testDataframe = testDataframe.set_index(['Codering'], inplace=True) should just be testDataframe.set_index(['Codering'], inplace=True) or testDataframe = testDataframe.set_index(['Codering'], inplace=False) otherwise the return value of the inplace index change (None) is the new content of the dataframe which is of course not the intend. I am sure this is obvious to many and now it is to me as well but it wasn't without your help, thanks!!!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/42854598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6421290/']}
jdg_375251
stackexchange
llm_judgeable_groundtruth_similarity
5620758
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 don't seem to be having much luck on this site, still forever the optimist, I will keep trying.I have two tables, Journals and ArticleCategories that are joined using the this query: SELECT Journals.JournalId, Journals.Year, Journals.Title, ArticleCategories.ItemTextFROM Journals LEFT OUTER JOIN ArticleCategories ON Journals.ArticleCategoryId = ArticleCategories.ArticleCategoryId Can anyone tell me how I can re-write this make it into a Skip, Take query.In other words, I want to it skip the first n records and then take the next n.I think ROW_NUMBER is involved somewhere but I cannot work out how to use it in this case. I suspect the reason why don't have much luck is that I find it difficult to explain what I am trying to do.If my question is not clear, please do not hesitate to tell me where I am going wrong and I will gladly try again.Perhaps I should also mention that I am trying to put this in a stored procedure.Many Thanks.Many thanks, Now provide the response and nothing else.
For 2005 / 2008 / 2008 R2 ;WITH cte AS( SELECT Journals.JournalId, Journals.Year, Journals.Title, ArticleCategories.ItemText, ROW_NUMBER() OVER (ORDER BY Journals.JournalId,ArticleCategories.ItemText) AS RN FROM Journals LEFT OUTER JOIN ArticleCategories ON Journals.ArticleCategoryId = ArticleCategories.ArticleCategoryId) SELECT JournalId, Year, Title, ItemTextFROM cteWHERE RN BETWEEN 11 AND 20 For 2012 this is simpler SELECT Journals.JournalId, Journals.Year, Journals.Title, ArticleCategories.ItemTextFROM Journals LEFT OUTER JOIN ArticleCategories ON Journals.ArticleCategoryId = ArticleCategories.ArticleCategoryIdORDER BY Journals.JournalId, ArticleCategories.ItemText OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5620758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/685555/']}
jdg_375252
stackexchange
llm_judgeable_groundtruth_similarity
468791
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way of setting culture for a whole application? All current threads and new threads? We have the name of the culture stored in a database, and when our application starts, we do CultureInfo ci = new CultureInfo(theCultureString);Thread.CurrentThread.CurrentCulture = ci;Thread.CurrentThread.CurrentUICulture = ci; But, of course, this gets "lost" when we want to do something in a new thread. Is there a way of setting that CurrentCulture and CurrentUICulture for the whole application? So that new threads also gets that culture? Or is it some event fired whenever a new thread is created that I can hook up to? Now provide the response and nothing else.
In .NET 4.5, you can use the CultureInfo.DefaultThreadCurrentCulture property to change the culture of an AppDomain. For versions prior to 4.5 you have to use reflection to manipulate the culture of an AppDomain. There is a private static field on CultureInfo ( m_userDefaultCulture in .NET 2.0 mscorlib, s_userDefaultCulture in .NET 4.0 mscorlib) that controls what CurrentCulture returns if a thread has not set that property on itself. This does not change the native thread locale and it is probably not a good idea to ship code that changes the culture this way. It may be useful for testing though.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/468791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39321/']}
jdg_375253
stackexchange
llm_judgeable_groundtruth_similarity
9119614
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 a WinForm on witch I've a DataGridView that display a list of sites. bellow that grid i've a TextBox and a Combobox, using DataBinding the textbox show the current value "Code" grid column and the combobox show the province. The combobox is filled with a list for provinceThe weird thing is this:When I change the combobox selected province for another one, at the time when the focus leave the combobox, the original value of the of the combobox return. I can't find a way for the combobox to keep the changed value. what am I doing wrong? Here my the code of my workbench project; private void Form1_Load(object sender, EventArgs e) { context = new GMR_DEVEntities(); lSite = from t in context.tblSites where t.Actif == true select t; this.dataGridView1.DataSource = lSite; this.dataGridView1.AutoGenerateColumns = true; Guid ProvinceId = Guid.Parse("00000000-0001-0000-0008-000000000001"); IQueryable<tblDomVal> provinces = from prov in context.tblDomVals where prov.pTypeDomValID == ProvinceId select prov; comboBox1.DataSource = provinces; comboBox1.ValueMember = "ID"; comboBox1.DisplayMember = "DescrFr"; textBox1.DataBindings.Add(new Binding("Text", lSite, "Code")); comboBox1.DataBindings.Add(new Binding("SelectedValue", lSite, "pProvinceID", false, DataSourceUpdateMode.OnPropertyChanged)); } Any help would be welcome :) Hugo Now provide the response and nothing else.
Based on your prior use of mobile detection middleware, I'd recommend the following: Pick up the Python port of MobileESP ( source code here ) and drop it into a folder named mobileesp in the base of your project (where manage.py is). Throw in a blank __init__.py file so that Python will see it as a package. Go ahead and create a new file, middleware.py , in that directory, and fill it with: import refrom mobileesp import mdetectclass MobileDetectionMiddleware(object): """ Useful middleware to detect if the user is on a mobile device. """ def process_request(self, request): is_mobile = False is_tablet = False is_phone = False user_agent = request.META.get("HTTP_USER_AGENT") http_accept = request.META.get("HTTP_ACCEPT") if user_agent and http_accept: agent = mdetect.UAgentInfo(userAgent=user_agent, httpAccept=http_accept) is_tablet = agent.detectTierTablet() is_phone = agent.detectTierIphone() is_mobile = is_tablet or is_phone or agent.detectMobileQuick() request.is_mobile = is_mobile request.is_tablet = is_tablet request.is_phone = is_phone Lastly, make sure to include 'mobileesp.middleware.MobileDetectionMiddleware', in MIDDLEWARE_CLASSES in your settings file. With that in place, in your views (or anywhere that you have a request object) you can check for is_phone (for any modern smartphones), is_tablet (for modern tablets) or is_mobile (for any mobile devices whatsoever).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9119614', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1186073/']}
jdg_375254
stackexchange
llm_judgeable_groundtruth_similarity
29273498
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How Can I get the date time in unix time as byte array which should fill 4 bytes space in Java? Something like that: byte[] productionDate = new byte[] { (byte) 0xC8, (byte) 0x34, (byte) 0x94, 0x54 }; Now provide the response and nothing else.
First: Unix time is a number of seconds since 01-01-1970 00:00:00 UTC. Java's System.currentTimeMillis() returns milliseconds since 01-01-1970 00:00:00 UTC. So you will have to divide by 1000 to get Unix time: int unixTime = (int)(System.currentTimeMillis() / 1000); Then you'll have to get the four bytes in the int out. You can do that with the bit shift operator >> (shift right). I'll assume you want them in big endian order: byte[] productionDate = new byte[]{ (byte) (unixTime >> 24), (byte) (unixTime >> 16), (byte) (unixTime >> 8), (byte) unixTime};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29273498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1463542/']}
jdg_375255
stackexchange
llm_judgeable_groundtruth_similarity
25498274
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It isn't clear to me what the benefits are. If I have: Foo* foo = nullptr;std::unique_ptr<Foo> unique_foo(foo); Is the nullptr_t constructor called in that situation? Or only if you do: std::unique_ptr<Foo> unique_foo(nullptr); Thanks! There is some discussion here which is to allow you to passing in nullptr_t, otherwise it won't compile since it won't cast to type pointer. So my question may be why it doesn't cast? Now provide the response and nothing else.
A possible reason is that the unique_ptr constructor that takes a unique_ptr::pointer argument is explicit . This means that in the absence of the unique_ptr(nullptr_t) constructor, the following code would not compile. std::unique_ptr<int> intp = nullptr; Since a unique_ptr is intended to be a lightweight smart pointer that closely imitates raw pointer semantics, it is desirable to have the above code compile. In your first example the nullptr_t constructor is not called because the type of the argument is Foo* , even though its value is nullptr .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25498274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/922839/']}
jdg_375256
stackexchange
llm_judgeable_groundtruth_similarity
5661544
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 a web application, I want to be able to define some mapping using a config section like this: <configuration> <configSections> <sectionGroup name="MyCustomer"> <section name="CatalogMappings" type="MyCustom.MyConfigSection" /> </sectionGroup> </configSections> <MyCustomer> <catalogMappings> <catalog name="toto"> <mapping value="1" displayText="titi" /> <mapping value="2" displayText="tata" /> </catalog> <catalog name="toto2"> <mapping value="1" displayText="titi2" /> <mapping value="2" displayText="tata2" /> </catalog> </catalogMappings> </MyCustomer></configuration> I'm struggling to achieve this goal, especially when defining my collection of collections. What are the classes that I need to implement to achieve this? Currently, I have: public class CatalogMappingSection : System.Configuration.ConfigurationSection{ public class Mapping : ConfigurationElement { [ConfigurationProperty("externalKey")] public string ExternalKey { get; set; } [ConfigurationProperty("displayText", IsRequired=true)] public string DisplayText { get; set; } [ConfigurationProperty("value", IsRequired=true, IsKey=true)] public int Value { get; set; } } public class Catalog : ConfigurationElementCollection { [ConfigurationProperty("name", IsRequired=true, IsKey=true)] public string Name { get; set; } protected override ConfigurationElement CreateNewElement() { return new Mapping(); } protected override object GetElementKey(ConfigurationElement element) { return ((Mapping)element).Value; } } public class CatalogCollection : ConfigurationElementCollection { [ConfigurationProperty("catalog")] [ConfigurationCollection(typeof(Catalog))] public Catalog CatalogMappingCollection { get { return (Catalog)base["catalog"]; } } protected override ConfigurationElement CreateNewElement() { return new Catalog(); } protected override object GetElementKey(ConfigurationElement element) { return ((Catalog)element).Name; } } [ConfigurationProperty("catalogMappings")] [ConfigurationCollection(typeof(CatalogCollection))] public CatalogCollection CatalogMappings { get { return (CatalogCollection)base["catalogMappings"]; } }} But, this is not working as expected. Now provide the response and nothing else.
I finally found this guy's example. It was coded and worked right out of the box. http://manyrootsofallevilrants.blogspot.com/2011/07/nested-custom-configuration-collections.html I am going to paste the code here......only because I cannot stand it when someone says "Your answer is here", and the link is dead. Please try his website first, and leave a "thank you" if it works. using System;using System.Configuration;namespace SSHTunnelWF{ public class TunnelSection : ConfigurationSection { [ConfigurationProperty("", IsDefaultCollection = true)] public HostCollection Tunnels { get { HostCollection hostCollection = (HostCollection)base[""]; return hostCollection; } } } public class HostCollection : ConfigurationElementCollection { public HostCollection() { HostConfigElement details = (HostConfigElement)CreateNewElement(); if (details.SSHServerHostname != "") { Add(details); } } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override ConfigurationElement CreateNewElement() { return new HostConfigElement(); } protected override Object GetElementKey(ConfigurationElement element) { return ((HostConfigElement)element).SSHServerHostname; } public HostConfigElement this[int index] { get { return (HostConfigElement)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } new public HostConfigElement this[string name] { get { return (HostConfigElement)BaseGet(name); } } public int IndexOf(HostConfigElement details) { return BaseIndexOf(details); } public void Add(HostConfigElement details) { BaseAdd(details); } protected override void BaseAdd(ConfigurationElement element) { BaseAdd(element, false); } public void Remove(HostConfigElement details) { if (BaseIndexOf(details) >= 0) BaseRemove(details.SSHServerHostname); } public void RemoveAt(int index) { BaseRemoveAt(index); } public void Remove(string name) { BaseRemove(name); } public void Clear() { BaseClear(); } protected override string ElementName { get { return "host"; } } } public class HostConfigElement:ConfigurationElement { [ConfigurationProperty("SSHServerHostname", IsRequired = true, IsKey = true)] [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\")] public string SSHServerHostname { get { return (string)this["SSHServerHostname"]; } set { this["SSHServerHostname"] = value; } } [ConfigurationProperty("username", IsRequired = true)] [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\")] public string Username { get { return (string)this["username"]; } set { this["username"] = value; } } [ConfigurationProperty("SSHport", IsRequired = true, DefaultValue = 22)] [IntegerValidator(MinValue = 1, MaxValue = 65536)] public int SSHPort { get { return (int)this["SSHport"]; } set { this["SSHport"] = value; } } [ConfigurationProperty("password", IsRequired = false)] public string Password { get { return (string)this["password"]; } set { this["password"] = value; } } [ConfigurationProperty("privatekey", IsRequired = false)] public string Privatekey { get { return (string)this["privatekey"]; } set { this["privatekey"] = value; } } [ConfigurationProperty("privatekeypassphrase", IsRequired = false)] public string Privatekeypassphrase { get { return (string)this["privatekeypassphrase"]; } set { this["privatekeypassphrase"] = value; } } [ConfigurationProperty("tunnels", IsDefaultCollection = false)] public TunnelCollection Tunnels { get { return (TunnelCollection)base["tunnels"]; } } } public class TunnelCollection : ConfigurationElementCollection { public new TunnelConfigElement this[string name] { get { if (IndexOf(name) < 0) return null; return (TunnelConfigElement)BaseGet(name); } } public TunnelConfigElement this[int index] { get { return (TunnelConfigElement)BaseGet(index); } } public int IndexOf(string name) { name = name.ToLower(); for (int idx = 0; idx < base.Count; idx++) { if (this[idx].Name.ToLower() == name) return idx; } return -1; } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMap; } } protected override ConfigurationElement CreateNewElement() { return new TunnelConfigElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((TunnelConfigElement)element).Name; } protected override string ElementName { get { return "tunnel"; } } } public class TunnelConfigElement : ConfigurationElement { public TunnelConfigElement() { } public TunnelConfigElement(string name, int localport, int remoteport, string destinationserver) { this.DestinationServer = destinationserver; this.RemotePort = remoteport; this.LocalPort = localport; this.Name = name; } [ConfigurationProperty("name", IsRequired = true, IsKey = true, DefaultValue = "")] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("localport", IsRequired = true, DefaultValue =1)] [IntegerValidator(MinValue = 1, MaxValue = 65536)] public int LocalPort { get { return (int)this["localport"]; } set { this["localport"] = value; } } [ConfigurationProperty("remoteport", IsRequired = true, DefaultValue =1)] [IntegerValidator(MinValue = 1, MaxValue = 65536)] public int RemotePort { get { return (int)this["remoteport"]; } set { this["remoteport"] = value; } } [ConfigurationProperty("destinationserver", IsRequired = true)] [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\")] public string DestinationServer { get { return (string)this["destinationserver"]; } set { this["destinationserver"] = value; } } }} And the configuration code <?xml version="1.0"?> <configuration> <configSections> <section name="TunnelSection" type="SSHTunnelWF.TunnelSection,SSHTunnelWF" /> </configSections> <TunnelSection> <host SSHServerHostname="tsg.edssdn.net" username="user" SSHport="22" password="pass" privatekey="" privatekeypassphrase=""> <tunnels> <tunnel name="tfs" localport="8081" remoteport="8080" destinationserver="tfs2010.dev.com" /> <tunnel name="sql" localport="14331" remoteport="1433" destinationserver="sql2008.dev.com" /> <tunnel name="crm2011app" localport="81" remoteport="80" destinationserver="crm2011betaapp.dev.com" /> </tunnels> </host> <host SSHServerHostname="blade16" username="root" SSHport="22" password="pass" privatekey="" privatekeypassphrase=""> <tunnels> <tunnel name="vnc" localport="5902" remoteport="5902" destinationserver="blade1.dev.com" /> </tunnels> </host> </TunnelSection> </configuration> And then the "call" TunnelSection tunnels = ConfigurationManager.GetSection("TunnelSection") as TunnelSection
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5661544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588868/']}
jdg_375257
stackexchange
llm_judgeable_groundtruth_similarity
16566552
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The documentation on PowerShell here has the following interesting comment in it: PowerShell powershell = PowerShell.Create();using (powershell){ //...}// Even after disposing of the PowerShell object, we still // need to set the powershell variable to null so that the // garbage collector can clean it up.powershell = null; Why does powershell need to be set to null after being disposed? Now provide the response and nothing else.
It's not directly a PowerShell issue. When a using block terminates, the specified object(s) have their Dispose() methods called. These typically do some cleanup operations, often to avoid leaking memory and so forth. However, Dispose() doesn't delete the object. If a reference to it still exists outside the using block (as in this example), then the object itself is still in scope. It can't be garbage-collected because there's still a reference to it, so it's still taking up memory. What they're doing in your example is dropping that reference. When powershell is set to null, the PowerShell object it was pointing to is orphaned, since there are no other variables referring to it. Once the garbage collector figures that out, it can free up the memory. This would happen at the end of the method anyway (because powershell would go out of scope), but this way you get the system resources back a little sooner. ( Edit: As Brian Rasmussen points out, the .NET runtime is extremely clever about garbage collection. Once it reaches the last reference to powershell in your code, the runtime should detect that you don't need it anymore and release it for garbage collection. So the powershell = null; line isn't actually doing anything.) By the way, this pattern looks very strange to me. The usual approach is something like this: using (PowerShell powershell = PowerShell.Create()){ //...} This way, powershell goes out of scope at the end of the using block, right after it's disposed. It's easier to tell where the variable is relevant, and you save some code because you don't need the powershell = null line anymore. I'd even say this is better coding practice, because powershell never exists in an already-disposed state. If someone modifies your original code and tries to use powershell outside the using block, whatever happens will probably be bad.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16566552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228059/']}
jdg_375258
stackexchange
llm_judgeable_groundtruth_similarity
2654141
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between event.target and this ? Let's say I have $("test").click(function(e) { $thisEventOb = e.target; $this = this; alert($thisEventObj); alert($this);}); I know the alert will pop different value. Anyone could explain the difference? Thanks a million. Now provide the response and nothing else.
They will be the same if you clicked on the element that the event is rigged up to. However, if you click on a child and it bubbles, then this refers to the element this handler is bound to, and e.target still refers to the element where the event originated. You can see the difference here: http://jsfiddle.net/qPwu3/1/ given this markup: <style type="text/css">div { width: 200px; height: 100px; background: #AAAAAA; }</style> <div> <input type="text" /></div> If you had this: $("div").click(function(e){ alert(e.target); alert(this);}); A click on the <input> would alert the input, then the div, because the input originated the event, the div handled it when it bubbled. However if you had this: $("input").click(function(e){ alert(e.target); alert(this);}); It would always alert the input twice, because it is both the original element for the event and the one that handled it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2654141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/401147/']}
jdg_375259
stackexchange
llm_judgeable_groundtruth_similarity
4218776
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 something like: message.split(/\n.* at.* XXXXXXXX wrote:.*/m).first This works if there is a match, but when there isn't, it just returns all of message . Now provide the response and nothing else.
If you're trying to count the number of matches, then you're using the wrong method. split is designed to take a string and chop it into bits, but as you've observed, if there aren't any matches, then it returns the whole thing. I think you want to use String.scan instead: message.scan(/\n.* at.* XXXXXXXX wrote:.*/m).size
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4218776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/149080/']}
jdg_375260
stackexchange
llm_judgeable_groundtruth_similarity
16672237
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 data in a csv file with dates stored as strings in a standard UK format - %d/%m/%Y - meaning they look like: 12/01/201230/01/2012 The examples above represent 12 January 2012 and 30 January 2012. When I import this data with pandas version 0.11.0 I applied the following transformation: import pandas as pd...cpts.Date = cpts.Date.apply(pd.to_datetime) but it converted dates inconsistently. To use my existing example, 12/01/2012 would convert as a datetime object representing 1 December 2012 but 30/01/2012 converts as 30 January 2012, which is what I want. After looking at this question I tried: cpts.Date = cpts.Date.apply(pd.to_datetime, format='%d/%m/%Y') but the results are exactly the same. The source code suggests I'm doing things right so I'm at a loss. Does anyone know what I'm doing wrong? Now provide the response and nothing else.
You can use the parse_dates option from read_csv to do the conversion directly while reading you data. The trick here is to use dayfirst=True to indicate your dates start with the day and not with the month. See here for more information: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.io.parsers.read_csv.html When your dates have to be the index: >>> import pandas as pd>>> from StringIO import StringIO>>> s = StringIO("""date,value... 12/01/2012,1... 12/01/2012,2... 30/01/2012,3""")>>> >>> pd.read_csv(s, index_col=0, parse_dates=True, dayfirst=True) valuedate 2012-01-12 12012-01-12 22012-01-30 3 Or when your dates are just in a certain column: >>> s = StringIO("""date... 12/01/2012... 12/01/2012... 30/01/2012""")>>> >>> pd.read_csv(s, parse_dates=[0], dayfirst=True) date0 2012-01-12 00:00:001 2012-01-12 00:00:002 2012-01-30 00:00:00
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16672237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1280784/']}
jdg_375261
stackexchange
llm_judgeable_groundtruth_similarity
24513873
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: No matter what I try and do I can't seem to make git tab/auto completion work in my zsh shell. I've downloaded the bash-completion script and the zsh-completion one and followed the instructions, but I can't make it work. I've reinstalled oh-my-zsh but that didn't seem to help or make any difference. Can anyone who's got it working describe to me their setup so I can try an emulate it to get it working for me? To be specific, what I've done so far is: Switched to using zsh as my default shell Installed oh-my-zsh Downloaded https://github.com/git/git/blob/master/contrib/completion/git-completion.bash and saved it in ~/.completion/git/git-completion.sh Downloaded https://github.com/git/git/blob/master/contrib/completion/git-completion.zsh and saved that in ~/.zsh/_git Added zstyle ':completion:*:*:git:*' script ~/.completion/git/git-completion.sh No luck. Now provide the response and nothing else.
TL;DR one-liner echo 'autoload -Uz compinit && compinit' >> ~/.zshrc && . ~/.zshrc this will enable completion in .zshrc and apply the setting to your current terminal session. Explanation: Actually, ZSH does know how to do git completion out of the box, but you need to turn on the completion feature itself (which from the steps you described I guess you haven't done) Adding this to your .zshrc should be enough: autoload -Uz compinit && compinit After you put the line .zshrc file, don't forget to restart the shell for ZSH to pick up the new config (alternatively, you can execute the line in your current session, that'll enable autocompletion for that one session) the zsh compinit: insecure directories warning Thanks to @FranMorzoa for suggesting to use compinit -u to skip the security checks for completion scripts While this will get rid of the warning/confirmation, the warning is there for a reason and it shouldn't happen normally. It is a sign that something is wrong with ownership of the completion scripts, and it can (and should) be fixed with one of these: brew.sh version: chmod -R go-w "$(brew --prefix)/share" another one, will probably work for non-brew zsh, credits to pvinis on GitHub : compaudit | xargs chmod g-w More info https://git-scm.com/book/en/v2/Appendix-A:-Git-in-Other-Environments-Git-in-Zsh https://docs.brew.sh/Shell-Completion#configuring-completions-in-zsh PS Another answer here suggests installing the hub tool instead: although the tool is handy, it's merely a 3rd party (github community) wrapper around git. Hence, it has nothing to do with the topic of "Git completion in ZSH"
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/24513873', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2041080/']}
jdg_375262
stackexchange
llm_judgeable_groundtruth_similarity
605071
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 am up to building a NE555 controlled PWM circuit that will power a 220v heater. NE555 will use a typical configuration and will drive a 20N60 Mosfet. The mosfet Vgs(th) is 10v, so NE555 needs to be powered by a 12-15v power supply. Because device's output is basically 220v, I decided to power NE555 w/o a transformer. Of course, the simplest solution is just use a big resistor, but that would dissipate too much heat. So I decided to use the capacitative dropper circuit. So, I have two rectifiers, one for the mosfet part, the other for the NE555 part, please consider schematics. I built the circuit and it works. However, for NE555 to control the mosfet, I need to short GND-A and GND-B. Once I did this, the zener was immediately burned. I tried to analyze path of current during each half-wave, and I don't see how it could make its way thru the diodes to, obviously bypass the 0.22uF cap, and burn the zener. Anyone care to explain, please? Now provide the response and nothing else.
I tried to analyse path of current during each half-wave, and I don'tsee how it could make its way thru the diodes to, obviously bypass the0.22uF cap, and burn the zener. Anyone care to explain, please? Just trace it round like this: - Basically, with the AC instantaneous polarity as shown by the + and - symbols, the zener diode receives the full 220 volts peak waveform and burns.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/605071', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/297059/']}
jdg_375263
stackexchange
llm_judgeable_groundtruth_similarity
36815383
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my application I have a products_controller that makes use of instance variables. My understanding of instance variables in Ruby is that you can use them within different methods of the same class. So why is it that we use the same instance variable in multiple methods of rails apps? Below we have an instance variable @product set twice, is the @product variable in the new action not overwritten when we use it in the create action? I am just a little confused as to the scope of these variables within methods of the same class. def new @product = Product.new end def create @product = Product.new(product_params) respond_to do |format| if @product.save format.html { redirect_to @product, notice: 'Product was successfully created.' } format.json { render :show, status: :created, location: @product } else format.html { render :new } format.json { render json: @product.errors, status: :unprocessable_entity } end end end Now provide the response and nothing else.
Instance variables are in the instance class scope. In Ruby on Rails, because the way how that API was built, instance variables are also available in the views. You need to be aware of that new and create methods are commonly used in different ProductsController instances . First request: GET http://localhost:3000/product/new When you ask for the new action (I suppose that is a form), Rails API implementation at a given point creates an instance of ProductsController and sends the new message to that instance (calls the new method). Then, the instance variable @product is created and available in any method, or in any view that the action renders. At a given point, Rails replies with a web page and the class instance, and all its instance variables, are destroyed (won't be available anymore). Second request: POST http://localhost:3000/product/create When you submit the form for database persistence, again a new controller instance is created, and the create method is called. Because is a new instance, the @product doesn't have any value. Note, however, that there is a difference between rendering a view (like its happening in the new action) and a redirect (like you do in the create action if @product.save is true). When you render, you remain in the same controller instance, with you redirect, new server request happens, so the previous controller instance is destroyed and a new controller instance is created. The before action before_action is called before you actually start executing the action code. In Rails perspective, an action is not a Ruby method. The class method is the definition of that action: From Rails guides: A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action. The action acts as an entry point determined by the routes. If you call create inside new, it won't trigger that before_action again.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36815383', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6162752/']}
jdg_375264
stackexchange
llm_judgeable_groundtruth_similarity
684336
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: Is there a formal link between linear regression and PCA? The goal of PCA is to decompose a matrix into a linear combination of variables that contain most of the information in the matrix. Suppose for sake of argument that we're doing PCA on an input matrix rather than its covariance matrix, and the columns $X_1, X2, ..., X_n$ of the matrix are variables of interest. Then intuitively it seems that the PCA procedure is similar to a linear regression where one uses a linear combination of the variables to predict the entries in the matrix. Is this correct thinking? How can it be made mathematically precise? Imagine enumerating the (infinite) space of all linear combinations of the variables $X_1, X_2, ...,X_n$ of a matrix of data and doing linear regression on each such combination to measure how much of the rows of the matrix the combination can 'explain'. Is there an interpretation of what PCA doing in terms of this operation? I.e. how in this procedure PCA would select the 'best' linear combinations? I realize this procedure is obviously not computationally feasible, I only present it to try to make the link between PCA and linear regression. This procedure works directly with linear combinations of columns of a matrix so it does not require them to be orthogonal. Now provide the response and nothing else.
The difference between PCA and regression can be interpreted as being mathematically only one additional multiplication with an inverse matrix... Here is a correlation matrix with three groups of variables: group g1: $x_{1,1},x_{1,2}$ correlated group g2: $x_{2,1},x_{2,2},x_{2,3}$ correlated group g3: $y$ composed by the variables of group g1 and g2 The correlation matrix looks like cor x1_1 x1_2 x2_1 x2_2 x2_3 ___y-----------------------------------------------------------x1_1 1.000 0.976 0.472 0.444 0.430 0.642x1_2 0.976 1.000 0.594 0.567 0.538 0.767x2_1 0.472 0.594 1.000 0.998 0.979 0.919x2_2 0.444 0.567 0.998 1.000 0.986 0.917x2_3 0.430 0.538 0.979 0.986 1.000 0.904___y 0.642 0.767 0.919 0.917 0.904 1.000----------------------------------------------------------- This is the loadings-matrix in its initial triangular cholesky form when not yet rotated to PC-position: tri f1 f2 f3 f4 f5 f6-----------------------------------------------------------x1_1 1.000 0.000 0.000 0.000 0.000 0.000x1_2 0.976 0.218 0.000 0.000 0.000 0.000x2_1 0.472 0.612 0.634 0.000 0.000 0.000x2_2 0.444 0.615 0.649 0.054 0.000 0.000x2_3 0.430 0.543 0.700 0.119 0.128 0.000___y 0.642 0.644 0.350 0.156 0.112 0.117----------------------------------------------------------- In pca we do not distinguish between independent and dependent variables; so we might do a rotation to PCA-position, where then the first axis/column denotes the first principal component and so on. [22] pca = rot(dr,"pca")pca f1 f2 f3 f4 f5 f6-----------------------------------------------------------x1_1 0.714 -0.692 0.100 0.041 -0.020 0.005x1_2 0.810 -0.584 -0.031 -0.047 0.025 -0.007x2_1 0.948 0.300 0.063 -0.081 0.003 0.018x2_2 0.940 0.333 0.050 -0.049 -0.015 -0.019x2_3 0.926 0.351 0.072 0.114 0.016 -0.001___y 0.973 0.045 -0.226 0.027 -0.010 0.004----------------------------------------------------------- We see, that all variables have one common factor, but we might also see, that only two or three factors are "relevant". A quartimax-rotation might locate the three main factors better related to the variable-groups [26] qua = rot(pca,"quartimax",1..6,1..3)qua.max f1 f2 f3 f4 f5 f6-----------------------------------+------------------------x1_1 0.373 0.925 -0.060 0.041 -0.020 0.005x1_2 0.505 0.859 0.068 -0.047 0.025 -0.007--------x2_1 0.988 0.112 -0.059 -0.081 0.003 0.018x2_2 0.994 0.078 -0.048 -0.049 -0.015 -0.019x2_3 0.989 0.056 -0.071 0.114 0.016 -0.001--------___y 0.908 0.342 0.240 0.027 -0.010 0.004-----------------------------------+------------------------ We see that we have two main groups with high in-group correlations, saying they measure nearly the same, in the x-variables and a less sharp separated "group" with only the y-variable which is correlated to both groups but has still an individual variance (in factor f3). This is classical PCA with Quartimax/Varimax-rotation, the "little jiffy"-procedure. Now we move on to regression. In regression we define one variable as dependent, in our case the variable y. We are interested, in which way y is composed by the independent variables; a still pca-inherent point of view would be that we find the pca of the independent variables only and leve the factor f6, which shows a part of y-variance which is uncorrelated , alone as taken from the initial triangular cholesky-factor. [29] pca = rot(dr,"pca",1..5)pca.reg f1 f2 f3 f4 f5 f6---------------------------------------------------+--------x1_1 0.729 -0.680 0.067 -0.048 -0.002 0.000x1_2 0.816 -0.571 -0.067 0.055 0.001 0.000-------------------x2_1 0.946 0.315 -0.066 -0.033 0.019 0.000x2_2 0.936 0.348 -0.041 -0.013 -0.023 0.000x2_3 0.923 0.366 0.117 0.036 0.004 0.000---------------------------------------------------+--------___y 0.957 0.057 -0.076 0.245 -0.039 0.117---------------------------------------------------+-------- Still the axes show the "factors" and how each variable is composed by that common (f1 to f5) or individual (f6) factors. Regression asks now for composition of y not by the factors/coordinates on the axes but by the coordinates on variables x if they are taken as axes. Happily we need only multiply the current loadings-matrix by the inverse of the x-submatrix to get axes defined by the x and have the "loadings" of y on x: [32] B = (pca[*,1..5]*inv(pca[1..5,1..5]) ) || pca[*,6]reg.B x1_1 x1_2 x2_1 x2_2 x2_3 ___y---------------------------------------------------+--------x1_1 1.000 0.000 0.000 0.000 0.000 0.000x1_2 0.000 1.000 0.000 0.000 0.000 0.000-------------------x2_1 0.000 0.000 1.000 0.000 0.000 0.000x2_2 0.000 0.000 0.000 1.000 0.000 0.000x2_3 0.000 0.000 0.000 0.000 1.000 0.000---------------------------------------------------+--------___y -1.442 1.989 -1.394 0.955 0.876 0.117 We see, that each of the axes is identified with one of the variables and also the "loadings" of y on that axes. But because the axes show now the directions of the x the loadings of y in the last row are now also the "regression"-weights/ coefficients, and the regression weights are now B = [-1.442 1.989 -1.394 0.955 0.876 ] (Because of the strong correlations in the groups the regression-weights are above 1 and also the signs are alternating. But this is not much of concern here in that methodic explanation) [Update] Relating PCA and regression in this way, there occurs very fluently another instructive example which might improve intuition. This is the problem of multicollinearity, which if occurs in regression is a problem for the researcher, but if occurs in PCA only improves the validity of estimation of separate components and the loadings of the items on such (latent) constructs. The means, which I want to introduce here, is the "main direction" of the multicollinear items (which of course is the first principal component) respectively the two sets of independent items $x1$ and $x2$. We can introduce latent variables which mark the pc's of the two sets of x-items. This can practically be done applying pc-rotation with maximizing criterion taken from the sets only: [32] pc1 = rot(tri,"pca",1..2,1..5) //rotating for pc of items 1..2 only[33] pc1 = {pc1,marksp(pc1,{1,2})} //add markers for that pc's PC1 pc1_1 pc1_2 c3 c4 c5 c6--------------------------------------------------------------x1_1 0.994 -0.109 0 0 0 0x1_2 0.994 0.109 0 0 0 0--------------------------------------------------------------x2_1 0.562 0.571 0.599 0 0 0x2_2 0.536 0.578 0.613 0.054 0 0x2_3 0.521 0.516 0.657 0.123 0.125 0--------------------------------------------------------------y 0.722 0.575 0.316 0.151 0.11 0.116===============================================================pc1_1 1 0 0 0 0 0pc1_2 0 1 0 0 0 0=============================================================== If we were looking at the system of $x1_1,x1_2$ and $y$ only, we had alreadythe beta-values for the pc's of that $x1$-item set as $b_{pc1_1}=0.722$ and$b_{pc1_2}=0.575$ - no hazzle because of (multi)collinearity! The same can be done with the second set of independent items $x2_1,x2_2,x2_3$: [37] pc2 = rot(pc1,"pca",3..5,1..5) [38] pc2 = {pc2,marksp(pc2,{1,2,3})} PC2 pc2_1 pc2_2 pc2_3 c4 c5 c6--------------------------------------------------------------x1_1 0.477 -0.124 -0.464 0.729 0.101 0x1_2 0.599 -0.189 -0.389 0.636 0.221 0--------------------------------------------------------------x2_1 0.997 -0.078 -0.022 0 0 0x2_2 0.999 -0.041 0.027 0 0 0x2_3 0.993 0.119 -0.005 0 0 0--------------------------------------------------------------y 0.923 -0.029 -0.058 0.212 0.294 0.116===============================================================pc1_1 0.542 -0.157 -0.429 0.687 0.162 0pc1_2 0.557 -0.300 0.343 -0.424 0.55 0--------------------------------------------------------------pc2_1 1 0 0 0 0 0pc2_2 0 1 0 0 0 0pc2_3 0 0 1 0 0 0=============================================================== The beta-value for the first pc of the second set of items (in a model without the first set) were $b_{pc2_1}=0.923$ which is more than that $b_{pc1_1}=0.722$ for the first pc of the first set of independent items. Now to see the betas using the joint model requires again only the inversion of the submatrix of the loadings of the whole set of 5 pc-markers and postmultiplying the first 5 columns with that. This gives us the "loadings", if the 5 pcs are taken as axes of a coordinate system. We get [42] beta = pca1[*,1..5]* inv(pca1[7..11,1..5]) || pca1[*,6] beta pc1_1 pc1_2 pc2_1 pc2_2 pc2_3 c6--------------------------------------------------------------x1_1 0.994 -0.109 0 0 0 0x1_2 0.994 0.109 0 0 0 0--------------------------------------------------------------x2_1 0 0 0.997 -0.078 -0.022 0x2_2 0 0 0.999 -0.041 0.027 0x2_3 0 0 0.993 0.119 -0.005 0--------------------------------------------------------------y 0.540 0.375 0.421 0.169 0.045 0.116===============================================================pc1_1 1 0 0 0 0 0pc1_2 0 1 0 0 0 0--------------------------------------------------------------pc2_1 0 0 1 0 0 0pc2_2 0 0 0 1 0 0pc2_3 0 0 0 0 1 0=============================================================== In short: beta pc1_1 pc1_2 | pc2_1 pc2_2 pc2_3 | c6---------------------------+-------------------------------+--------y 0.540 0.375 | 0.421 0.169 0.045 | 0.116===========================+===============================|======== In that joint model the "main direction" of the first set of independents has a beta-weight of 0.540 and the "main direction" of the second set of 0.421 . The value at $c6$ is here only for completeness: its square $0.116^2$ is the unexplained variance of the dependent item $y$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/684336', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/9576/']}
jdg_375265
stackexchange
llm_judgeable_groundtruth_similarity
5060817
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 be able to update a model and all its collections of child objects in the same view. I have been referred to these examples: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx and http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/ . For example, I have an object Consultant, that has a collection of "WorkExperiences". All this is in an Entity Framework model. In the view, the simple properties of the Consultant object is no problem, but the collection I cannot get a textbox to show up for. I tried following the examples in the links above, but it doesn't work. The problem is, in those examples the model is just a list (not an object with a child list property). And also, the model again is an EF model. And for some reason that doesn't seem to work as in those examples. Just to make it simple, I tried to do something along the lines of Phil Haacks example, and just get the View to show the textbox: @for (int i = 0; i < Model.WorkExperiences.Count; i++){ Html.TextBoxFor(m => m.WorkExperiences[i].Name);} I tried to create a new WorkExperience object in the controller for the ViewModel: public ActionResult Create(int id) { Consultant consultant = _repository.GetConsultant(id); DetailsViewModel vm = new DetailsViewModel(); vm.WorkExperiences = consultant.WorkExperiences.ToList(); vm.WorkExperiences.Add(new WorkExperience()); return View(vm); } But the View doesn't show any empty textbox for the WorkExperience Name property. If on the other hand I create a separate View just for adding a new WorkExperience object, passing a new empty WorkExperience object as the model, this works fine: @Html.EditorFor(model => model.Name) That gives me an empty textbox, and I can save the new object. But why can't I do this in the same view as the Consultant object, with collections according to the examples in the links above? BTW, this is sort of a follow-up question to an earlier one, that pointed me to the above links, but I never got to a final solution for it. See that question if more info is needed: Create Views for object properties in model in MVC 3 application? UPDATE: According to answers and comments below, here's an update with the View and an EditorTemplate: The View: @model Consultants.ViewModels.DetailsViewModel@{ ViewBag.Title = "Index";}<h2>Index</h2><p> @Html.ActionLink("Add work experience", "CreateWorkExperience", new { id = ViewBag.Consultant.Id })</p><table> <tr> <th></th> <th> Name </th> </tr>@foreach (var item in Model.WorkExperiences) { <tr> <td> @Html.ActionLink("Edit", "Edit", new { id = item.Id }) | @Html.ActionLink("Details", "Details", new { id = item.Id }) | @Html.ActionLink("Delete", "Delete", new { id = item.Id }) </td> <td> @item.Name </td> </tr>}</table>@for (int i = 0; i < Model. WorkExperiences.Count; i++){ Html.EditorFor(m => m. WorkExperiences[i]);} (Please note that all this is not really how I'll design it in the end, all I am after right now is to get the WorkExperience object to show up as an empty textbox to fill out, and to be able to add and delete such textboxes as in Phil Haack's and Steven Sanderson's examples.) The EditorTemplate: @model Consultants.Models.WorkExperience@Html.TextBoxFor(m => m.Name); This stuff with the EditorTemplate works fine in Phil Haack's sample project, which I downloaded to try, but here, with the EF model or whatever the problem is, I don't get any textbox at all. The table in the view is just there as a test, because in the table I do get the rows for WorkExperiences, whether I add an empty WorkExperience object or fill out its properties doesn't matter, the rows show up for each object. But again, no textbox... Now provide the response and nothing else.
For example, I have an object Consultant, that has a collection of "WorkExperiences". All this is in an Entity Framework model. That's the first thing you should improve: introduce view models and don't use your domain models into the view. This being said let's move on to the templates. So you can completely eliminate the need to write loops in your views. So here's how your view might look like: @model Consultants.ViewModels.DetailsViewModel@{ ViewBag.Title = "Index";}<h2>Index</h2><p> @Html.ActionLink("Add work experience", "CreateWorkExperience", new { id = ViewBag.Consultant.Id })</p><table> <tr> <th></th> <th> Name </th> </tr> @Html.DisplayFor(x => x.WorkExperiences)</table>@Html.EditorFor(x.WorkExperiences) So as you can we are using a display template and an editor template. Let's define them now. Display template ( ~/Views/Shared/DisplayTemplates/WorkExperience.cshtml ): @model AppName.Models.WorkExperience<tr> <td> @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) | @Html.ActionLink("Details", "Details", new { id = Model.Id }) | @Html.ActionLink("Delete", "Delete", new { id = Model.Id }) </td> <td> @Model.Name </td></tr> Editor template ( ~/Views/Shared/EditorTemplates/WorkExperience.cshtml ): @model AppName.Models.WorkExperience@Html.TextBoxFor(x => x.SomePropertyOfTheWorkExperienceModelYouWantToEdit)... What is important here is the naming convention. The name of the template should be the name of the type of the item in the collection. So for example if in your view model you have a property public IEnumerable<Foo> { get; set; } the corresponding template should be called Foo.cshtml and should be located in ~/Views/Shared/DisplayTemplates or ~/Views/Shared/EditorTemplates depending on its role. So as you can see we have gotten rid of the nasty loops. Now not only that the views look clean, but you get correct names for the input fields so that you can bind the values back in the post action.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5060817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/178946/']}
jdg_375266
stackexchange
llm_judgeable_groundtruth_similarity
15426736
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to use Hibernate annotation for writing a model class for my database tables. I have two tables, each having a primary key User and Question. @Entity@Table(name="USER")public class User{ @Id @Column(name="user_id") @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(name="username") private String username; // Getter and setter} Question Table. @Entity@Table(name="QUESTION")public class Questions extends BaseEntity{ @Id @Column(name="question_id") @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(name="question_text") private String question_text; // Getter and setter} And I have one more table, UserAnswer, which has userId and questionId as foreign keys from the above two tables. But I am unable to find how I can reference these constraints in the UserAnswer table. @Entity@Table(name="UserAnswer ")public class UserAnswer{ @Column(name="user_id") private User user; //@ManyToMany @Column(name="question_id") private Questions questions ; @Column(name="response") private String response; // Getter and setter} How can I achieve this? Now provide the response and nothing else.
@Column is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions to Question , since an instance represents a single question, and not several ones. Then create the association: @Entity@Table(name = "UserAnswer")public class UserAnswer { // this entity needs an ID: @Id @Column(name="useranswer_id") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne @JoinColumn(name = "user_id") private User user; @ManyToOne @JoinColumn(name = "question_id") private Question question; @Column(name = "response") private String response; //getter and setter } The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15426736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/907687/']}
jdg_375267
stackexchange
llm_judgeable_groundtruth_similarity
41221897
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 one ecs task definition. Can multiple tasks of the above task definition can run on one EC2 instance on several ports ? I have already have running several tasks running on several ec2 instances. I want to reduce the consumption of resources. As one EC2 instance has more than enough resources to run several tasks. Is it possible to run same task several times on different ports on one EC2 instance ? Now provide the response and nothing else.
Yes, ECS has very good support for this since 2016. You can leave the host port empty in the container definition, this will result in a random port to be chosen for your container. As a result, more instances of the same task definition can run on one ECS instance. You can configure your ECS service in combination with an Application Load Balancer so that when it starts a new task, it will register the port number in the associated target group. This way you never have to deal with the random port. If you setup your service via the AWS console, configuration is pretty straightforward.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41221897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1909733/']}
jdg_375268
stackexchange
llm_judgeable_groundtruth_similarity
466985
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a regression of the price of the car compared to other factors. I can upload the data here but unsure it's necessary. The summary gives me: Call:lm(formula = cars $Price ~ cars$ Mileage + cars $Cylinder + cars$ Doors + cars $Cruise + cars$ Sound + cars $Leather + cars$ Liter)Residuals: Min 1Q Median 3Q Max -13278 -5615 -1556 3996 32819 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 6.759e+03 1.877e+03 3.601 0.000337 ***cars $Mileage -1.698e-01 3.187e-02 -5.326 1.31e-07 ***cars$ Cylinder 3.792e+03 6.832e+02 5.551 3.87e-08 ***cars $Doors -1.543e+03 3.205e+02 -4.814 1.77e-06 ***cars$ Cruise 6.289e+03 6.580e+02 9.558 < 2e-16 ***cars $Sound -1.994e+03 5.718e+02 -3.487 0.000515 ***cars$ Leather 3.349e+03 5.977e+02 5.604 2.89e-08 ***cars$Liter -7.872e+02 8.671e+02 -0.908 0.364196 ---Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 7388 on 796 degrees of freedomMultiple R-squared: 0.4463, Adjusted R-squared: 0.4414 F-statistic: 91.64 on 7 and 796 DF, p-value: < 2.2e-16 What bothers me is that almost all the variables are significant. I don't have that much data looking at the f-statistic, so I'm wondering if perhaps this is an overfit or is it okay? How do I fix it if not, and what may cause the problem?Thanks Now provide the response and nothing else.
It looks like you’ve got hundreds of observations and only eight parameters, so with the close values of $R^2$ and adjusted $R^2$ , overfitting doesn’t seem to be a major issue for you. If you remain concerned about this, train on 80% of your observations and then test on the remaining 20% of the observations. Seeing similar MSEs should give you some peace of mind. Why do you find the many significant parameters so surprising, though? To me, they all look like factors than would increase a car price. Further, I would kind of hope to have my parameters be significant. Excluding a variable because it’s parameter is insignificant is fraught with problems, but if I think it’s important enough to include in the model, I would hope for the math to reflect that! (It might not, either because I made a poor assumption about how the variable impacts the response or because I just don’t have the sample size to get significance, but significant parameters on important variables is logically consistent in my head.)
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/466985', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/282682/']}
jdg_375269
stackexchange
llm_judgeable_groundtruth_similarity
99133
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: If you were trying to run a package that is not installed, for example: me ~: gparted The program 'gparted' is currently not installed. You can install it by typing:sudo apt-get install gparted How can I run the sudo apt-get install gparted line as a command?Not typing it, obviously. Now provide the response and nothing else.
You can enable it by adding this to your .bashrc export COMMAND_NOT_FOUND_INSTALL_PROMPT=1 Giving you: $ fooThe program 'foo' is currently not installed. You can install it by typing:sudo apt-get install blah-blahDo you want to install it? (N/y) If you get a python error as in: ... File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 217, in install_prompt answer = answer.decode(sys.stdin.encoding)AttributeError: 'str' object has no attribute 'decode' You can: Apply this patch for Ubuntu from here . or: Modify CommandNotFound.py by adding four spaces at beginning of lines 215,216,217 (note: not tabs) : ... 213 else: 214 answer = raw_input(prompt) 215 4 spaces if sys.stdin.encoding and isinstance(answer, str): 216 4 spaces # Decode the answer so that we get an unicode value 217 4 spaces answer = answer.decode(sys.stdin.encoding) 218 if answer.lower() == _("y"): ... Another way, to expand on Greg Hewgill 's comment could be: $(!! 2>&1 | tail -n1) I tried to wrap it in a script, but that didn't work out of the box as you won't get the error message. If one want to get it in a script, a rather hacky way could be: x=$(/usr/lib/command-not-found $(tail -n1 "$HOME/.bash_history") 2>&1 | tail -n1)echo "$x" For some options look at: /usr/lib/command-not-found -help an/or check out the script itself.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/99133', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/46600/']}
jdg_375270
stackexchange
llm_judgeable_groundtruth_similarity
25287112
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 working on a mobile web application just for my own enjoyment and research. Everything seemed to be working pretty slick with HTML5/CSS and JavaScript for the client application, although it looks like I need a third party technology for voice recording. I had a pretty good solution working with Flash, but after testing it with my IPhone, I had remembered that they don't seem to support flash which is disappointing because I had a pretty good solution going. I want to record voice using HTML5 in Iphone and android. Is there any way? Now provide the response and nothing else.
You could try HTML Media Capture. An article on dev.opera says: Android OS 3.0 was the first platform to provide HTML Media Capture support, via its default Android Webkit browser. Now HTML Media Capture is also supported by: Safari and Chrome Mobile for iOS 6+ Chrome Mobile for Android OS 3+ Firefox Mobile for Android OS 3+ Opera 16 for Android OS 3+ Nonetheless some of them only partially implement the specification or implement an older W3C specification, that makes the code above slightly different: <input type="file" accept="image/*" capture="camera"><input type="file" accept="video/*" capture="camcorder"><input type="file" accept="audio/*" capture="microphone"> It links out to a demo page which you could try on your mobile. I also found this example page . In my quick iOS 7 testing though, it only worked correctly for photos and videos. Edit : Further reading suggests accept="audio/*" isn't actually supported on iOS 6 and 7, only accept="image/*" and accept="video/*" . Update : A quick test on iOS 8.3 suggests nothing has changed here: accept="image/*" and accept="video/*" are supported, but accept="audio/*" is not. Update : A quick test on iOS 10.0.2 suggests accept="audio/*" is still not supported, although it looks like you might be able to upload an audio file from iCloud Drive or Dropbox now. Update : Despite what it says in the Webkit blog post , there still seems to be no support for accept="audio/*" in iOS 10.3 on my iPhone 5S. Update : Same story in iOS 11.0.3. There still seems to be no support for accept="audio/*" on my iPhone 5S. Update : Still the same in iOS 12.4.3. There seems to be no support for accept="audio/*" on my iPhone 5S.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25287112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3927007/']}
jdg_375271
stackexchange
llm_judgeable_groundtruth_similarity
9789225
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 MS SQL Server function that counts the number of times a particular character appears in a string? Now provide the response and nothing else.
There's no direct function for this, but you can do it with a replace: declare @myvar varchar(20)set @myvar = 'Hello World'select len(@myvar) - len(replace(@myvar,'o','')) Basically this tells you how many chars were removed, and therefore how many instances of it there were. Extra: The above can be extended to count the occurences of a multi-char string by dividing by the length of the string being searched for. For example: declare @myvar varchar(max), @tocount varchar(20)set @myvar = 'Hello World, Hello World'set @tocount = 'lo'select (len(@myvar) - len(replace(@myvar,@tocount,''))) / LEN(@tocount)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/9789225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100048/']}
jdg_375272
stackexchange
llm_judgeable_groundtruth_similarity
13243148
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 calculate the rolling 20 period historical volatility. I take the daily returns: ret <- ROC(data1) And then I use rollapply to get the 20 day HV for each column: vol <- rollapply(ret, 20, sd, by.column=T, fill=NA) The problem is that observations in vol starts appearing after ten days which is wrong as I specified 20. For demonstration here is sample of the data: 0.000000000, 0.005277045, 0.023622047, 0.002564103,-0.002557545, -0.020512821,0.007853403,-0.012987013, 0.007894737, 0.015665796, 0.000000000, -0.002570694,0.002577320, -0.015424165, 0.002610966, 0.010416667, 0.002577320, 0.015424165, 0.000000000, -0.002531646, -0.002538071, 0.030534351, 0.014814815, -0.007299270,-0.009803922, -0.012376238, 0.002506266, -0.015000000,-0.002538071, 0.002544529 Assume the data above is stored in x, then: rollapply(x, 20, sd, fill=NA) will yield a first observation at 10th row instead of 20. Also the sd is wrong too. I should be missing something here... Now provide the response and nothing else.
You need to use align='right' instead of using the default which is align='center' , or instead of using rollapply , use the rollapplyr wrapper which has align='right' as the default. From ?rollapply : align specifyies whether the index of the result should be left- or right-aligned or centered (default) compared to the rolling window of observations. This argument is only used if width represents widths. Although, for this, personally, I'd use runSD from the TTR package because it uses compiled code and will be faster. Either of these should do what you expect, but the second one will be faster. library(zoo)rollapply(x, 20, sd, fill=NA, align='right')library(TTR)runSD(x, 20)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13243148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1610626/']}
jdg_375273
stackexchange
llm_judgeable_groundtruth_similarity
37884832
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 remote: upstream and origin. upstream is something I can't push to. origin is my own repo. How can I fetch all branches from upstream and then push them to origin?I tried: git fetch upstreamgit push --all origin But it doesn't work. Now provide the response and nothing else.
You may want to try cloning your upstream repo with --mirror option and then push to your new remote with --mirror option too You'll have the following flow: git clone <upstream-repo-url/repo.git> --mirrorcd <repo>git remote add <your-remote-name> <your-remote-url/repo.git>git push <your-remote-name> --mirror ⚠ Be really careful with the push --mirror as it will delete branches that are on your <your-remote-name>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37884832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1673428/']}
jdg_375274
stackexchange
llm_judgeable_groundtruth_similarity
27245597
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 requirement to deploy a test application and issue commands on a device connected to another machine in the same network. I read through http://developer.android.com/tools/help/adb.html#directingcommands but I am not able to find the answer. I tried using adb connect <remote machine IP> but I got unable to connect error. Is there a way to deploy applications and execute adb commands on a device connected to a remote system? Now provide the response and nothing else.
From the adb tag wiki : Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android-powered device. It is a client-server program that includes three components: A client, which runs on your development machine. You can invoke a client from a shell by issuing an adb command. Other Android tools such as the ADT plugin and DDMS also create adb clients. A server, which runs as a background process on your development machine. The server manages communication between the client and the adb daemon running on an emulator or device. A daemon, which runs as a background process on each emulator or device instance. adb connect command is used to connect the local adb server with the adbd daemon on a network connected device. But what you want is to connect the local adb client to the remote (running on another system) adb server . The default behavior of the adb executable is to connect to the local instance of the adb server . If none found it would try to start one. This approach works great for most environments where all development is being done on a single system. But in more complicated environments it may result in multiple instances of adb server being launched. And because adbd daemon only supports being connected to a single adb server at a time - the device will get recognized by one system and will appear missing everywhere else. So in order for adb to reliably recognize devices in those more complicated configurations you need to tell adb to stop guessing and manually specify which part of adb (i.e. server or client ) should be running on which system. First off make sure that you have the same and sufficiently recent version of adb (the latest Google official version usually works the best) installed on both local and remote systems. And that no adb servers are currently running on either system. Then start an instance of the adb server on the remote system (the one which you will be plugging the devices into) with this command: adb -a -P <PORT_NUMBER> nodaemon server Now you can force adb client on the local system to use the other (remote) server instead of starting its own (local) instance by adding -H <REMOTE_IP> -P <PORT_NUMBER> to your adb commands: adb -H <REMOTE_IP> -P <PORT_NUMBER> devices Alternatively, setting ANDROID_ADB_SERVER_ADDRESS=<REMOTE_IP> and ANDROID_ADB_SERVER_PORT=<PORT_NUMBER> environment variables on the client side would allow you to avoid having to specify the <REMOTE_IP> and <PORT_NUMBER> for every adb command. And if omitted the <PORT_NUMBER> would default to 5037 . This official built-in solution for adb orchestration is not a mutually exclusive alternative to the SSH tunneling - it just addresses another more important issue. You can add tunneling on top of this to add extra security or help with routing issues in a multi site network environment. But the tunneling alone will not be able to solve all the adb connectivity problems. Same goes for the virtualized environments - running multiple adb server instances between host and guest systems will also result in the adb connectivity issues.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27245597', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1670849/']}
jdg_375275
stackexchange
llm_judgeable_groundtruth_similarity
11335908
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Adams-MacBook-Pro% brew doctor Error: /usr/bin occurs before /usr/local/binThis means that system-provided programs will be used instead of thoseprovided by Homebrew. The following tools exist at both paths: clusterdb createdb createlang createuser dropdb droplang dropuser ecpg git git-cvsserver git-receive-pack git-shell git-upload-archive git-upload-pack gitk pg_config pg_dump pg_dumpall pg_restore pg_upgrade psql reindexdb vacuumdbConsider amending your PATH so that /usr/local/binis ahead of /usr/bin in your PATH. Here is my path: Adams-MacBook-Pro% echo $PATH /usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin I thought it was dangerous to move things to the front? How do I solve this problem? Also, I'm not even sure where to find where /user/bin is declared in the path. Thanks Now provide the response and nothing else.
$PATH is just a variable containing a string. To put something in front: % PATH=/usr/local/bin:$PATH% echo $PATH/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin This is not dangerous, since it only applies to the current shell you have open (it will not affect the path for your system or other shells). To change the path automatically for all shells you open, put it in ~/.profile . You can create this file if it doesn't already exist. In ~/.profile : homebrew=/usr/local/bin:/usr/local/sbinexport PATH=$homebrew:$PATH export makes the variable available to any child processes of the shell.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11335908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/554327/']}
jdg_375276
stackexchange
llm_judgeable_groundtruth_similarity
14146783
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First of all, I know this question has been asked a MILLION times...and I've looked at this one specifically as well as several others on this site and other sites. I've tried a ton of different variations on each of these and still can't get it to work. I'm trying to center an unordered list. It displays correctly, it's just not centered. At the moment, it's CLOSE to center...but if you change the "width" parameter in the .nav-container code in the CSS then it shifts the position of the div. Here is my CSS: html *{ font-family: Verdana, Geneva, sans-serif;}body { padding:0px; margin:0px;}.nav-container { width:460px; margin: 0 auto;}.nav-container ul { padding: 0px; list-style:none; float:left;}.nav-container ul li { display: inline;}.nav-container ul a { text-decoration:none; padding:5px 0; width:150px; color: #ffffff; background: #317b31; float:left; border-left: 1px solid #fff; text-align:center;}.nav-container ul a:hover { background: #92e792; color: black;}#add-form .add-button, #tutor-list .tutor-button, #admin .admin-button { color: #ffffff; background: #12b812;} And here is my HTML: <body id="admin"><div id="header"><center><h2>OMS Tutoring Database</h2></center></div><div class="nav-container"><ul> <a class="tutor-button" href="tutoring.php"><li>Tutoring List</li></a> <a class="add-button" href="addform.php"><li>Add Students</li></a> <a class="admin-button" href="admin.php"><li>Admin</li></a></ul></div><div id="content"></div></body> I'm sure it's some glaringly simple error, but any help would be much appreciated. Oh, and I'm currently viewing it in Chrome as I'm testing it. jsFiddle Now provide the response and nothing else.
Your HTML is incorrect. The <a> tags should be inside the <li> tags. To make the list items be inline, set float: left on them, and overflow: hidden to the <ul> so it fits its children. Remove the float on .nav-container , its unecessary. Take a look at this codepen . And the nav moves when you change its width because it you centered the wrapper but not the nav itself. You can remove width and margin: 0 auto and try: .nav-container { text-align: center;}.nav-container ul { display: inline-block;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14146783', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1054123/']}
jdg_375277
stackexchange
llm_judgeable_groundtruth_similarity
38445262
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 any way i can pass parameters with UITapGestureRecognizer?I've seen this answered for objective-c but couldn't find an answer for swift test.userInteractionEnabled = truelet tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("imageTapped4:"))// Something like text.myParamatertest.addGestureRecognizer(tapRecognizer) And then receive myParameter under func imageTapped4(){} Now provide the response and nothing else.
One approach would be to subclass UITapGestureRecognizer and then set a property, I've posted an example below. You could also do some check on the sender and check if equal to some tag, class, string, e.t.c class ViewController: UIViewController { @IBOutlet weak var label1: UILabel! @IBOutlet weak var image: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. image.userInteractionEnabled = true; let tappy = MyTapGesture(target: self, action: #selector(self.tapped(_:))) image.addGestureRecognizer(tappy) tappy.title = "val" } func tapped(sender : MyTapGesture) { print(sender.title) label1.text = sender.title }}class MyTapGesture: UITapGestureRecognizer { var title = String()} There are lots of examples on SO, have a look, good luck.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38445262', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1735171/']}
jdg_375278
stackexchange
llm_judgeable_groundtruth_similarity
1032
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In one of other discussions : How to find frequency response, stability, and causality of a linear system? I found a comment which was quite strong and definitely caught my attention. An ideal low-pass filter is an example of a system that is not BIBO stable even though its frequency response is bounded for all $f$ I am following the definition of stability as per here in wiki http://en.wikipedia.org/wiki/BIBO_stability Can anyone give me a proof that ideal LPF can indeed be BIBO unstable? Of course, ideal LPF with infinite gain can produce unbounded output. The question is restricted to LPF when gain is finite. Now provide the response and nothing else.
This answer is a response to a comment by the OP on on yoda's answer. Suppose that $h(t)$, the impulse response of a continuous-time linear time-invariant system, has the property that $$\int_{-\infty}^{\infty} |h(t)| \mathrm dt = M$$ forsome finite number $M$. Then, for each and every bounded input $x(t)$, the output $y(t)$ is bounded also.If $|x(t)| \leq \hat{M}$ for all $t$ where $\hat{M}$is some finite number, then $|y(t)| \leq \hat{M}M$ for all $t$where $\hat{M}M$ is also a finite number.The proof is straightforward.$$\begin{align*}|y(t)| &= \left |\int_{-\infty}^\infty h(\tau)x(t - \tau)\mathrm d\tau\right |\\&\leq \int_{-\infty}^\infty |h(\tau)x(t - \tau)|\mathrm d\tau\\&\leq \int_{-\infty}^\infty |h(\tau)|\cdot|x(t - \tau)|\mathrm d\tau\\&\leq \hat{M}\int_{-\infty}^\infty |h(\tau)|\mathrm d\tau\\&= \hat{M}M.\end{align*}$$In other words, $y(t)$ is bounded whenever $x(t)$ is bounded. Thus, the condition $\displaystyle\int_{-\infty}^{\infty} |h(t)| \mathrm dt < \infty$ is sufficient for BIBO-stability. The condition $\displaystyle\int_{-\infty}^{\infty} |h(t)| \mathrm dt < \infty$ is also necessary for BIBO-stability. Assume that every bounded inputproduces a bounded output. Now consider the input $x(t) = \text{sgn}(h(-t)) ~\forall~ t$. This is clearly bounded,($|x(t)| \leq 1$ for all $t$), and at $t=0$, it produces output$$\begin{align*}y(0) &= \int_{-\infty}^\infty h(0-\tau)x(-\tau)\mathrm d\tau\\&= \int_{-\infty}^\infty h(-\tau)\text{sgn}(h(-\tau))\mathrm d\tau&= \int_{-\infty}^\infty |h(-\tau)|\mathrm d\tau\\&= \int_{-\infty}^\infty |h(t)|\mathrm dt.\end{align*}$$Our assumption that the system is BIBO stable means that $y(0)$ is necessarily finite, that is,$$\int_{-\infty}^{\infty} |h(t)| \mathrm dt < \infty$$ The proof for discrete-time systems is similar with the obvious change that all the integrals are replaced by sums. Ideal LPFs are not BIBO-stable systems because the impulse response is not absolutely integrable,as stated in the answer by yoda. But his answer does not really answer the question Can anyone give me a proof that ideal LPF can indeed be BIBO unstable? A specific example of a bounded input signal that produces an unbounded outputfrom an ideal LPF (and thus proves that the system is not BIBO-stable)can be constructed as outlined above (see also my comment on the main question).
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/1032', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/440/']}
jdg_375279
stackexchange
llm_judgeable_groundtruth_similarity
13024940
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 code like this public class fragment2 extends Fragment{@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.content, container, false);} } i want to call activity class instead of layout.please help me. Now provide the response and nothing else.
The hint comes from the JSON data: {"enableText":{"text":"xx"},"kind":"foo.hyde.jenkins.plugins.OptionalBlockSampleBuilder","stapler-class":"foo.hyde.jenkins.plugins.OptionalBlockSampleBuilder"} You can see here that enableText contains a child property, text . That means that the f:optionalBlock is actually expecting an encapsulation of all the fields contained within the block -- when the block is checked, you will receive an instance of the encapsulation field class; when it is unchecked, that field will be null . To use the optionalBlock properly, you would need the @DataBoundConstructor to take in a single nullable class instance that encapsulates the entire optionalBlock . For example: private String text;@DataBoundConstructorpublic MyClass(EnableTextBlock enableText){ if (enableText != null) { this.text = enableText.text; }}public static class EnableTextBlock{ private String text; @DataBoundConstructor public EnableTextBlock(String text) { this.text = text; }} Notice that the enableText field in this case is actually an instance of EnableTextBlock class, which contains a child property, text . That will satisfy the JSON object that is being sent in the form. Instead, if all you need is a single field that has a checkbox to enable entry of that field, you might want to consider instead using the f:optionalProperty tag, which will take care of that single-field encapsulation for you. However, in many cases, the optionalBlock is actually needed to configure multiple fields, in which case the encapsulation class--as exampled above--is usually the correct way to go. The encapsulation class does not have to be a static inner class; it could be a separate class within your package, but the important part is that the DataBoundConstructor should take in an argument that matches the JSON structure being passed from the form.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13024940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_375280
stackexchange
llm_judgeable_groundtruth_similarity
570297
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: Why is the ESR (Equivalent Series Resistance) of the electrolytic capacitors important? Now provide the response and nothing else.
A much simpler way would be to use RGB LED strips because they include all the LEDs and resistors, and all you have to do is switch them on or off. But if you already have the LEDs... These LEDs aren't the usual common anode. Instead each LED has its own two pins. This means you can indeed wire them in series as you intended. (a common anode RGB LED has 4 pins and all the anodes of the LEDs are tied together so you can't wire them in series). However, they're 4W LEDs, there are four 1W LEDs inside. If you want to use them at 4W then you have a problem because if you don't mount them on a proper heat sink they will melt, and the way to mount them is reflow solderign of the thermal pad on the back. That only works on a copper surface, so you need a special aluminium core PCB, with copper foil laminated on top of an indulator, yadda yadda, not user-friendly for a quick project. Besides, at 4W they'll be really super bright, so you could run them at less power. You could use thermal conductive two-component epoxy to glue them on an aluminium heat sink. Or you could reflow them on on a copper heat sink. All of that is probably going to be more expensive than a roll of 12V or 24V RGB LED strip from aliexpress though, so YMMV. Note LED strips are much easier to work with because the heat is distributed over a long length, not just in a few power LEDs acting as hot spots. So low power strips stay cool. High power strips are another story, but still not that difficult. Besides that: The FETs are upside down, and make sure you pick FETs that will turn on with 5V Vgs. These have "RdsON" specification at Vgs=4.5V. If it is only specified for Vgs=10V then nope. There should be a resistor per series string of LEDs. Also make sure you check how much power it will dissipate. If you use 0.25W resistors, they will burn. Another advantage of LED strips is there are lots of resistors on them so the dissipated power is spread along the length. Your LEDs have different forward voltage (Vf) depending on color. Therefore, at the same current, the red string will have much lower voltage than the blue string. So you need to calculate the resistor value for each color.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/570297', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/281572/']}
jdg_375281
stackexchange
llm_judgeable_groundtruth_similarity
31294230
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I noticed some strange behaviour of TextInputLayout : When I add the following to my layout: <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <EditText android:id="@+id/txtFirstName" style="@style/EditTextStyle" android:layout_width="match_parent" android:layout_height="match_parent" android:hint="In layout" android:singleLine="true" /> </android.support.design.widget.TextInputLayout> everything works as expected. When I inflate a similar Layout like: View v = LayoutInflater.from(this).inflate(R.layout.edittext_w_surrounding_textinputlayout, null); EditText editText = (EditText) v.findViewById(R.id.editText); editText.setHint("Added programmatically"); ViewGroup root = (ViewGroup) findViewById(R.id.root); root.addView(v); the TextInputLayout doesn't appear and the EditText behaves the standard way. Any ideas what the reason could be? Now provide the response and nothing else.
You should change hint, not on EditText, but on TextInputLayout. So it will be: TextInputLayout v = (TextInputLayout) LayoutInflater.from(this).inflate(R.layout.edittext_w_surrounding_textinputlayout, null);v.setHint("Added programmatically"); TextInputLayout has it's own hint parameter and when inflating from layout it get's hint from it's child EditText and set empty hint on it. When you want to change hint programatically you have to call textInputLayout.setHint(String text) instead of changing EditText hint
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31294230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/804967/']}
jdg_375282
stackexchange
llm_judgeable_groundtruth_similarity
5984217
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 running into a small problem at the end of the Getting Started guide for vagrant . I'm working on a CentOS basebox that has Apache2 running (provisioning via Puppet). I've set up port forwarding for web requests using the following line in Vagrantfile : config.vm.forward_port "web", 80, 4567 But when I make requests to that port, they fail. The error reported by Safari is 'Safari can’t open the page “ http://localhost:4567/ ” because the server unexpectedly dropped the connection.' I did a vagrant reload and saw "[default] -- web: 80 => 4567 (adapter 1)" in the scroll, so where should I begin to troubleshoot this? Thanks. Now provide the response and nothing else.
I wanted to add an additional note that often this is caused by the server within the VM because it binds to 127.0.0.1 , which is loopback. You'll want to make sure that the server is bound to 0.0.0.0 so that all interfaces can access it. Some built-in app servers such as Django's development servers and some Ruby servers default to 127.0.0.1 by default so this is something to watch out for. Other than that, what Steve said holds true: Make sure it works from within the VM and try some other simple servers to try and figure out if it is a configuration problem.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5984217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4203/']}
jdg_375283
stackexchange
llm_judgeable_groundtruth_similarity
9401249
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 page where I keep track of various dates. So I end up using datepicker through jquery anywhere from 10-200 times. I want to set the default for all cases of datepicker to the 'yy-mm-dd' - but I can't seem to figure out how to set that? Now provide the response and nothing else.
I end up using datepicker through jquery anywhere from 10-200 times. I'm assuming you're calling datepicker() separately for each input, probably by id . There's no need for that. Use a class as a hook on your input: <input class="my-datepicker"> Then call datepicker on elements with that class with your default configuration: $('.my-datepicker').datepicker({ dateFormat: 'yy-mm-dd'}); When you need a different configuration, use/assign a different class name. You can also use setDefaults (probably what you're looking for): $.datepicker.setDefaults({ dateFormat: 'yy-mm-dd'});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9401249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1226651/']}
jdg_375284
stackexchange
llm_judgeable_groundtruth_similarity
403631
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^n \rightarrow 0$ as $n \rightarrow \infty$ for $\left|a\right| < 1 $ Hint $u_{2n}$ = $u_{n}^2$ I have totally no idea how to prove this, this looks obvious but i found out proof is really hard... I am doing a real analysis course and there's a lot of proving and I stuck there. Any advices? Practice makes perfect? Now provide the response and nothing else.
Replacing $a$ by $|a|$, one can assume without loss of generality that $a$ is a nonnegative real number. If $a=0$, the result is direct. If $0\lt a\lt1$, the sequence defined by $u_n=a^n$ is decreasing and positive hence it converges to some finite nonnegative limit $\ell$. Since $u_{n+1}=au_n$, $\ell=a\ell$. Since $a\ne1$, the only possible limit is $\ell=0$, QED. The hint that $u_{2n}=u_n^2$ can probably be used as follows, once one knows that the limit $\ell$ exists and is finite: $\ell=\ell^2$ hence $\ell=0$ or $1$ and, since $u_n\leqslant u_1=a\lt1$ for every $n\geqslant1$, $\ell\ne1$ hence $\ell=0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/403631', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74735/']}
jdg_375285
stackexchange
llm_judgeable_groundtruth_similarity
500328
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 an existing function in numpy that will tell me if a value is either a numeric type or a numpy array? I'm writing some data-processing code which needs to handle numbers in several different representations (by "number" I mean any representation of a numeric quantity which can be manipulated using the standard arithmetic operators, +, -, *, /, **). Some examples of the behavior I'm looking for >>> is_numeric(5)True>>> is_numeric(123.345)True>>> is_numeric('123.345')False>>> is_numeric(decimal.Decimal('123.345'))True>>> is_numeric(True)False>>> is_numeric([1, 2, 3])False>>> is_numeric([1, '2', 3])False>>> a = numpy.array([1, 2.3, 4.5, 6.7, 8.9])>>> is_numeric(a)True>>> is_numeric(a[0])True>>> is_numeric(a[1])True>>> is_numeric(numpy.array([numpy.array([1]), numpy.array([2])])True>>> is_numeric(numpy.array(['1'])False If no such function exists, I know it shouldn't be hard to write one, something like isinstance(n, (int, float, decimal.Decimal, numpy.number, numpy.ndarray)) but are there other numeric types I should include in the list? Now provide the response and nothing else.
As others have answered, there could be other numeric types besides the ones you mention.One approach would be to check explicitly for the capabilities you want, with something like # Python 2def is_numeric(obj): attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__'] return all(hasattr(obj, attr) for attr in attrs)# Python 3def is_numeric(obj): attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__'] return all(hasattr(obj, attr) for attr in attrs) This works for all your examples except the last one, numpy.array(['1']) . That's because numpy.ndarray has the special methods for numeric operations but raises TypeError if you try to use them inappropriately with string or object arrays. You could add an explicit check for this like ... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU') This may be good enough. But... you can never be 100% sure that somebody won't define another type with the same behavior, so a more foolproof way is to actually try to do a calculation and catch the exception, something like def is_numeric_paranoid(obj): try: obj+obj, obj-obj, obj*obj, obj**obj, obj/obj except ZeroDivisionError: return True except Exception: return False else: return True but depending on how often you plan to call use it and with what arguments, this may not be practical (it can be potentially slow, e.g. with large arrays).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/500328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/56541/']}
jdg_375286
stackexchange
llm_judgeable_groundtruth_similarity
5498893
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 any way to get key events in a google chrome extension file - background.html - ? document.onkeydown = function() { alert('test)}; Previous code doesn't work. Now provide the response and nothing else.
I assume you want to implement hotkeys for your extension. Your code should in fact work, except it works on the background page, which is usually not open to catch key presses. To catch keypresses globally, or at least on web pages, you will have to use a content script that sends messages to the background page. The content script is injected to the open web page and insert methods for catching keypresses, and then send a message to the background page with information on which keys are pressed.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5498893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/511892/']}
jdg_375287
stackexchange
llm_judgeable_groundtruth_similarity
9915395
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 view model that contains a Product class type and an IEnumerable< Product > type. On the post the first level product object comes back binded from the viewmodel whereas the product enum is coming back null. Why is the IEnumerable< Prouduct> property not getting binded to my view model per the post? Thx! Models: public class Product{ public int ID { get; set; } public string Name { get; set; } public decimal Price { get; set; }}public class ProductIndexViewModel{ public Product NewProduct { get; set; } public IEnumerable<Product> Products { get; set; }}public class BoringStoreContext { public BoringStoreContext() { Products = new List<Product>(); Products.Add(new Product() { ID = 1, Name = "Sure", Price = (decimal)(1.10) }); Products.Add(new Product() { ID = 2, Name = "Sure2", Price = (decimal)(2.10) }); } public List<Product> Products {get; set;}} View: @model ProductIndexViewModel@using (@Html.BeginForm()){ <div> @Html.LabelFor(model => model.NewProduct.Name) @Html.EditorFor(model => model.NewProduct.Name) </div> <div> @Html.LabelFor(model => model.NewProduct.Price) @Html.EditorFor(model => model.NewProduct.Price) </div> <div> <input type="submit" value="Add Product" /> </div> foreach (var item in Model.Products) { <div> @Html.LabelFor(model => item.ID) @Html.EditorFor(model => item.ID) </div> <div> @Html.LabelFor(model => item.Name) @Html.EditorFor(model => item.Name) </div> <div> @Html.LabelFor(model => item.Price) @Html.EditorFor(model => item.Price) </div> } } Controller: public class HomeController : Controller{ BoringStoreContext db = new BoringStoreContext(); public ActionResult Index() { ProductIndexViewModel viewModel = new ProductIndexViewModel { NewProduct = new Product(), Products = db.Products }; return View(viewModel); } [HttpPost] public ActionResult Index(ProductIndexViewModel viewModel) { // ???? viewModel.Products is NULL here // ???? viewModel.NewProduct comes back fine return View(); } Now provide the response and nothing else.
You are not using your lambda expression properly. You need to be accessing the Products list through the model. Try doing it like this: @count = 0foreach (var item in Model.Products) { <div> @Html.LabelFor(model => model.Products[count].ID) @Html.EditorFor(model => model.Products[count].ID)</div><div> @Html.LabelFor(model => model.Products[count].Name) @Html.EditorFor(model => model.Products[count].Name)</div><div> @Html.LabelFor(model => model.Products[count].Price) @Html.EditorFor(model => model.Products[count].Price)</div>@count++ } Edit Controller: BoringStoreContext db = new BoringStoreContext(); public ActionResult Index() { ProductIndexViewModel viewModel = new ProductIndexViewModel { NewProduct = new Product(), Products = db.Products }; return View(viewModel); } [HttpPost] public ActionResult Index(ProductIndexViewModel viewModel) { // work with view model return View(); } Model public class Product{ public int ID { get; set; } public string Name { get; set; } public decimal Price { get; set; }}public class ProductIndexViewModel{ public Product NewProduct { get; set; } public List<Product> Products { get; set; }}public class BoringStoreContext{ public BoringStoreContext() { Products = new List<Product>(); Products.Add(new Product() { ID = 1, Name = "Sure", Price = (decimal)(1.10) }); Products.Add(new Product() { ID = 2, Name = "Sure2", Price = (decimal)(2.10) }); } public List<Product> Products { get; set; }} View: @model Models.ProductIndexViewModel@using (@Html.BeginForm()){<div> @Html.LabelFor(model => model.NewProduct.Name) @Html.EditorFor(model => model.NewProduct.Name)</div><div> @Html.LabelFor(model => model.NewProduct.Price) @Html.EditorFor(model => model.NewProduct.Price)</div>for (int count = 0; count < Model.Products.Count; count++ ){ <div> @Html.LabelFor(model => model.Products[count].ID) @Html.EditorFor(model => model.Products[count].ID) </div> <div> @Html.LabelFor(model => model.Products[count].Name) @Html.EditorFor(model => model.Products[count].Name) </div> <div> @Html.LabelFor(model => model.Products[count].Price) @Html.EditorFor(model => model.Products[count].Price) </div>}<div> <input type="submit" value="Add Product" /></div>}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9915395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/897756/']}
jdg_375288
stackexchange
llm_judgeable_groundtruth_similarity
37072245
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 psql command to connect and issue a query on postgreSQL database. Can anybody let me know how to check the return status of the executed query in shell script. I have used echo $? command to check the status but it always returning zero. Thanks for the help. Now provide the response and nothing else.
psql return code is documented as : EXIT STATUS psql returns 0 to the shell if it finished normally, 1 if a fatal error of its own occurs (e.g. out of memory, file not found), 2 if the connection to the server went bad and the session was not interactive, and 3 if an error occurred in a script and the variable ON_ERROR_STOP was set. You probably just want to use ON_ERROR_STOP. Failure getting tested and reported to the shell: $ psql -d test -v "ON_ERROR_STOP=1" <<EOFselect error;select 'OK';EOFERROR: column "error" does not existLINE 1: select error;$ echo $?3 Failure getting ignored and not reported to the shell: $ psql -d test <<EOFselect error;select 'OK';EOFERROR: column "error" does not existLINE 1: select error; ^ ?column? ---------- OK(1 row)$ echo $?0
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37072245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2424666/']}
jdg_375289
stackexchange
llm_judgeable_groundtruth_similarity
26158692
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to add ngAnimate to my angular app dependencies. Here is my angular app file: var carApp = angular.module("carApp", ["ngAnimate"]); Here is my TableBodyCtrl controller: carApp.controller("TableBodyCtrl", function($scope, $http){ $scope.loading = false; ...}); Here is my TablePanelCtrl : carApp.controller("TablePanelCtrl", function(){ this.tab = 1; ...}); My controller are in different files in the controller folder. Here is the script loads of angular libraries: <script type="text/javascript" src="js/angular.min.js"></script><script type="text/javascript" src="js/angular-animate.min.js"></script> Here is the script load of my angular app file: <script type="text/javascript" src="js/carApp.js"></script> Here is the script loads of my controllers: <script type="text/javascript" src="js/controllers/TablePanelCtrl.js"></script><script type="text/javascript" src="js/controllers/TableBodyCtrl.js"></script> When I run my web-app I get this error: Unknown provider: $$qProvider <- $$q <- $animate <- $compilehttps://docs.angularjs.org/error/$injector/unpr?p0=$$qProvider%20%3C-%20$$q%20%3C-%20$animate%20%3C-%20$compile This error only started to show up after I add "ngAnimate" to my angular app dependencies. How can I fix that? Now provide the response and nothing else.
I had the same error and just figured out why it was happening. The root cause was I was depending on "angular-animate": "~1.3.0", so bower was using Angular v1.3 even though the rest of the project was depending on Angular 1.2. Just use "angular-animate": "~1.2.0" instead of "angular-animate": "~1.3.0" in your bower.json file. After a bower install everything should work! Same answer here: https://stackoverflow.com/a/26596023/2171509
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26158692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2598876/']}
jdg_375290
stackexchange
llm_judgeable_groundtruth_similarity
19089115
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 split up the view in four parts. A header at the top, using full page width and fixed height. The remaining page is split up in two blocks of the same height, the upper of them contains two same-sized blocks next to each other. What I tried is (without the header): #wrap { width: 100%; height: 100%;}#block12 { width: 100%; max-height: 49%;}#block1,#block2 { width: 50%; height: 100%; float: left; overflow-y: scroll;}#block3 { width: 100%; height: 49%; overflow: auto; /*background: blue;*/}.clear { clear: both;} <div id="wrap"> <div id="block12"> <div id="block1"></div> <div id="block2"></div> <div class="clear"></div> </div> <div id="block3"></div></div> Apparently, using a percentage value for the height won't work that way. Why is that so? Now provide the response and nothing else.
add this to you CSS: html, body{ height: 100%;} working Fiddle when you say to wrap to be 100% , 100% of what? of its parent (body), so his parent has to have some height. and the same goes for body , his parent his html . html parent his the viewport..so, by setting them both to 100%, wrap can also have a percentage height. also:the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar)you can use *{ padding: 0; margin: 0;} to disable that. Look at That Fiddle
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19089115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2558051/']}
jdg_375291
stackexchange
llm_judgeable_groundtruth_similarity
13743058
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to access my $scope variable in Chrome's JavaScript console. How do I do that? I can neither see $scope nor the name of my module myapp in the console as variables. Now provide the response and nothing else.
Pick an element in the HTML panel of the developer tools and type this in the console: angular.element($0).scope() In WebKit and Firefox, $0 is a reference to the selected DOM node in the elements tab, so by doing this you get the selected DOM node scope printed out in the console. You can also target the scope by element ID, like so: angular.element(document.getElementById('yourElementId')).scope() Addons/Extensions There are some very useful Chrome extensions that you might want to check out: Batarang . This has been around for a while. ng-inspector . This is the newest one, and as the name suggests, it allows you to inspect your application's scopes. Playing with jsFiddle When working with jsfiddle you can open the fiddle in show mode by adding /show at the end of the URL. When running like this you have access to the angular global. You can try it here: http://jsfiddle.net/jaimem/Yatbt/show jQuery Lite If you load jQuery before AngularJS, angular.element can be passed a jQuery selector. So you could inspect the scope of a controller with angular.element('[ng-controller=ctrl]').scope() Of a button angular.element('button:eq(1)').scope() ... and so on. You might actually want to use a global function to make it easier: window.SC = function(selector){ return angular.element(selector).scope();}; Now you could do this SC('button:eq(10)')SC('button:eq(10)').row // -> value of scope.row Check here: http://jsfiddle.net/jaimem/DvRaR/1/show/
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/13743058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/780799/']}
jdg_375292
stackexchange
llm_judgeable_groundtruth_similarity
23969
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking to solve the following problem: I have a set of sentences as my dataset, and I want to be able to type a new sentence, and find the sentence that the new one is the most similar to in the dataset. An example would look like: New sentence: " I opened a new mailbox " Prediction based on dataset: Sentence | SimilarityA dog ate poop 0%A mailbox is good 50%A mailbox was opened by me 80% I've read that cosine similarity can be used to solve these kinds of issues paired with tf-idf (and RNNs should not bring significant improvements to the basic methods), or also word2vec is used for similar problems. Are those actually viable for use in this specific case, too? Are there any other techniques/algorithms to solve this (preferably with Python and SKLearn, but I'm open to learn about TensorFlow, too)? Now provide the response and nothing else.
Your problem can be solved with Word2vec as well as Doc2vec. Doc2vec would give better results because it takes sentences into account while training the model. Doc2vec solution You can train your doc2vec model following this link . You may want to perform some pre-processing steps like removing all stop words (words like "the", "an", etc. that don't add much meaning to the sentence). Once you trained your model, you can find the similar sentences using following code. import gensim model = gensim.models.Doc2Vec.load('saved_doc2vec_model') new_sentence = "I opened a new mailbox".split(" ") model.docvecs.most_similar(positive=[model.infer_vector(new_sentence)],topn=5) Results: [('TRAIN_29670', 0.6352514028549194), ('TRAIN_678', 0.6344441771507263), ('TRAIN_12792', 0.6202734708786011), ('TRAIN_12062', 0.6163255572319031), ('TRAIN_9710', 0.6056315898895264)] The above results are list of tuples for (label,cosine_similarity_score) . You can map outputs to sentences by doing train[29670] . Please note that the above approach will only give good results if your doc2vec model contains embeddings for words found in the new sentence. If you try to get similarity for some gibberish sentence like sdsf sdf f sdf sdfsdffg , it will give you few results, but those might not be the actual similar sentences as your trained model may haven't seen these gibberish words while training the model. So try to train your model on as many sentences as possible to incorporate as many words for better results. Word2vec Solution If you are using word2vec, you need to calculate the average vector for all words in every sentence and use cosine similarity between vectors. def avg_sentence_vector(words, model, num_features, index2word_set): #function to average all words vectors in a given paragraph featureVec = np.zeros((num_features,), dtype="float32") nwords = 0 for word in words: if word in index2word_set: nwords = nwords+1 featureVec = np.add(featureVec, model[word]) if nwords>0: featureVec = np.divide(featureVec, nwords) return featureVec Calculate Similarity from sklearn.metrics.pairwise import cosine_similarity#get average vector for sentence 1sentence_1 = "this is sentence number one"sentence_1_avg_vector = avg_sentence_vector(sentence_1.split(), model=word2vec_model, num_features=100)#get average vector for sentence 2sentence_2 = "this is sentence number two"sentence_2_avg_vector = avg_sentence_vector(sentence_2.split(), model=word2vec_model, num_features=100)sen1_sen2_similarity = cosine_similarity(sentence_1_avg_vector,sentence_2_avg_vector)
{}
{'log_upvote_score': 6, 'links': ['https://datascience.stackexchange.com/questions/23969', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/21254/']}
jdg_375293
stackexchange
llm_judgeable_groundtruth_similarity
53900839
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 run git status on a git repository through WSL (Windows Subsystem for Linux) that's on the Window's directory ( /mnt/c/Users/.... ), I get that every file in the directory has been modified. Each modification is just delete and re-write of the original file. See below: Below is a git diff on one of the files Now if I run a git status on the exact same repository on the Windows side (through powershell), I get nothing: Any particular reason behind this? I know the ^M have to do with the different line endings that Linux and Microsoft are using, but that git would disagree on whether changes have been made or not seems odd to me. Note: I've been working on the repository on WSL side through a separate clone of the repository (hence why the Windows side is 15 commits behind). No editing has been done to the Windows repository though. Not sure if this changes anything, but I'd figure I'd mention it. Now provide the response and nothing else.
The two git installations (native windows and WSL) are using a different setting for the core.autocrlf configuration, because these two installations are not using the same global config file. Put simply, the native windows client is converting LF to CRLF upon checkout, and hence the presence of CRLF is not "seen" as a change by git status . On the contrary, the WSL client expects UNIX-style LF line endings, so the git status sees every file as having been modified to change LF to CRLF. Instead of relying on the global setting the core.autocrlf you should set it locally in the repository for any shared repositories. If the same repository is being accessed from both Linux/WSL and native Windows, you probably want this set to false so git does not change any line endings at all. Just beware that if you do set this as false, you'll have to make sure your editors can handle the line endings as they are (in general, most programmers editors I've used do support using UNIX LF, even on Windows). The core.autocrlf is documented here for more info: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration#_core_autocrlf
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53900839', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7564988/']}
jdg_375294
stackexchange
llm_judgeable_groundtruth_similarity
1299410
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 save an object (of any type) into a field in a database in SQL Server 2005. Is it possible? Do I have to convert the object into something, like a byte array for example and cast it back when retrieving it? Now provide the response and nothing else.
You can use the VARBINARY(MAX) field type in SQL Server, if you like. You can store any type of object in there, up to 2 GB in size. To access it, you can use ADO.NET - something like this: object yourMysteryObject = (whatever you like it to be);MemoryStream memStream = new MemoryStream();StreamWriter sw = new StreamWriter(memStream);sw.Write(yourMysteryObject);SqlCommand sqlCmd = new SqlCommand("INSERT INTO TableName(VarBinaryColumn) VALUES (@VarBinary)", sqlConnection);sqlCmd.Parameters.Add("@VarBinary", SqlDbType.VarBinary, Int32.MaxValue);sqlCmd.Parameters["@VarBinary"].Value = memStream.GetBuffer();sqlCmd.ExecuteNonQuery(); Marc
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1299410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132640/']}
jdg_375295
stackexchange
llm_judgeable_groundtruth_similarity
25106784
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My questions is, is it possible to have a UIView display an image, and if so, how so I do it? All I can find is the colorwithpatternImage which no longer works with swift. The code I am trying to use now is: self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]; Thanks in advance for your answers! Now provide the response and nothing else.
Refer to the UIColor documentation . In Swift, you have to call a convenience initializer. This is because in Swift, all Objective-C class methods which return an instance of their class become convenience initializers. Here's how it looks in Swift: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")) + (UIColor *)colorWithPatternImage:(UIImage *)image returns a UIColor instance, so it will become a convenience initializer in Swift. Similarly, UIImage imageNamed: becomes init(patternImage image: UIImage!) .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25106784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3880609/']}
jdg_375296
stackexchange
llm_judgeable_groundtruth_similarity
2540750
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can't seem to figure out how to load a pictureBox image from a bitmap in memory. Is it possible or do I have to create temp file for the bitmap? Now provide the response and nothing else.
What format is the image in memory? If you have an actual Bitmap object, just assign it to the PictureBox, as suggested by dtb: pictureBox.Image = bitmap; If you have the image as a series of bytes held in a stream, you'll need to load the image from the stream: var image = Image.FromStream(stream);pictureBox.Image = image; If you instead have a windows GDI handle to the bitmap, use var image = Image.FromHbitmap(handle);pictureBox.Image = image; Essentially, it's hard to answer your question with more than suggestions when you haven't told us what format the Bitmap you have is held in.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2540750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/248981/']}
jdg_375297
stackexchange
llm_judgeable_groundtruth_similarity
5493722
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 building an oauth 1.0a service that will be consumed by a gadget within Jira, it's a .Net 3.5 Application written in C#. Jira makes requests to this service using the RSA-SHA1 signature method, which means to verify the signature of the request I need create an X509Certificate instance form their public cert. Within the Jira application you can get the public cert by going to the consumer info screen (which also has the consumer key for Jira etc.) and it presents the public key in this format: MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCObJRTGSZbAojRkvKmm0cwFXnKcPMfR4t/sghvLe/+QVs6TJOz5cUh5UokSqyzVeMsL0jomP18ZcR3SPcIFT7xtOGQjLwLk7ghfYSsxjTGs9VxsC/PQk5OQRP3v43IxFNF3M2SYhFWJZTOnqrab5AsMh2Kxdv+D69DCINXCu5ltQIDAQAB Looking at the Jira code which generates this key I can see it's (supposedly) PEM encoded without the BEGIN/END certificate header/footer. RSAKeys.toPemEncoding(consumer.getPublicKey()) RSAKeys is an open source class found here: https://studio.atlassian.com/source/browse/OAUTH/trunk/api/src/main/java/com/atlassian/oauth/util/RSAKeys.java?r=HEAD I wish to load this public cert (key) into an X509Certificate instance within .Net, but my attempts so far have failed. Here's the code I have: static readonly Regex stripRegex = new Regex("-----[A-Z ]*-----");public string ConvertFromOpenSsl(string key){ return stripRegex.Replace(key, "").Replace("\r", "").Replace("\n", "");}public X509Certificate2 GetConsumerCertificate(IConsumer consumer){ string cert = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCObJRTGSZbAo jRkvKmm0cwFXnKcPMfR4t/sghvLe/+QVs6TJOz5cUh5UokSqyz VeMsL0jomP18ZcR3SPcIFT7xtOGQjLwLk7ghfYSsxjTGs9VxsC /PQk5OQRP3v43IxFNF3M2SYhFWJZTOnqrab5AsMh2Kxdv+D69D CINXCu5ltQIDAQAB"; string converted = ConvertFromOpenSsl(cert); var bytes = Convert.FromBase64String(converted); var cert = new X509Certificate2(bytes); // throws here But on the last line of code I have an exception thrown: System.Security.Cryptography.CryptographicException: Cannot find the requested object. at System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr) at System.Security.Cryptography.X509Certificates.X509Utils._QueryCertBlobType(Byte[] rawData) at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(Byte[] data) at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData) I'm pretty sure I am missing something elementary, but I can think what it is. UPDATE OK, on further investigation it appears that this is a SubjectPublicKeyInfo serialization of the public key, so it's ASN.1, base 64 encoded (162 bytes unencoded), which is the default output from Java using java.security.PublicKey.getEncoded(). So given all that - is there any easy way to create an X509Certificate2 instance wrapping this public key - or is additional metadata required beyond the public key to create an x509Certificate2 instance? Now provide the response and nothing else.
Assuming you have a relation, A, with a single attribute, 'a' (reducing a more complex relation to this is a simple task in relational algebra, I'm sure you got this far), so now you want to find the maximum value in A. One way to do it is to find the cross product of A with itself, be sure to rename 'a' so your new relation has attributes with distinct names. for example: (rename 'a' as 'a1') X (rename 'a' as 'a2') now select 'a1' < 'a2', the resulting relation will have all values except the maximum. To get the max simply find the difference between your original relation: (A x A) - (select 'a1' < 'a2') ((rename 'a' as 'a1')(A) x (rename 'a' as 'a2')(A)) Then use the project operator to reduce down to a single column as Tobi Lehman suggests in the comment below. Writing this in relational algebra notation would be (if I remember correctly). Note the final rename (i.e. ρ) is just to end up with an attribute that has the same name as in the original relation: ρ a/a1 (π a1 ((A x A) - σ a1 < a2 (ρ a1/a (A) x ρ a2/a (A))))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5493722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4843/']}
jdg_375298
stackexchange
llm_judgeable_groundtruth_similarity
1334926
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 currently having an issue with radio buttons and grouping. I have an asp radio button within a repeater control. I have the group name attribute set to "Customer". When the page loads, the radio buttons are not grouped. Instead of the id fields being set to the group name, it is setting the value fields of the radio buttons. I know that I have tried setting radio buttons up outside of a repeater control and have had the same issue. What is going on here? aspx <asp:Repeater ID="repCustomers" runat="server"> <HeaderTemplate> <table class="tableDefault" cellpadding="0" cellspacing="0" border="0" style="width: 383px; border: 0px !important"> <tr> <th>&nbsp;</th> <th>Cust. No.</th> <th>Cust. Name</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <asp:RadioButton ID="radCustomer" GroupName="Customer" runat="server" ValidationGroup="Customer" ToolTip='<%#Eval("CustomerNumber") %>' /> </td> <td><%#Eval("CustomerNumber")%></td> <td><%#Eval("Name") %></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate></asp:Repeater> output html <table class="tableDefault" cellpadding="0" cellspacing="0" border="0" style="width: 383px; border: 0px !important"> <tr> <th>&nbsp;</th> <th>Cust. No.</th> <th>Cust. Name</th> </tr> <tr> <td> <span title="111111"><input id="ctl00_PrimaryContent_repCustomers_ctl01_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl01$Customer" value="radCustomer" /></span> </td> <td>111111</td> <td>Jeremy's Test</td> </tr> <tr> <td> <span title="222222"><input id="ctl00_PrimaryContent_repCustomers_ctl02_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl02$Customer" value="radCustomer" /></span> </td> <td>222222</td> <td>My Test</td> </tr> <tr> <td> <span title="333333"><input id="ctl00_PrimaryContent_repCustomers_ctl03_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl03$Customer" value="radCustomer" /></span> </td> <td>333333</td> <td>Jim Bob's BBQ</td> </tr> <tr> <td> <span title="444444"><input id="ctl00_PrimaryContent_repCustomers_ctl04_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl04$Customer" value="radCustomer" /></span> </td> <td>444444</td> <td>New Hope Hamburgers</td> </tr> <tr> <td> <span title="555555"><input id="ctl00_PrimaryContent_repCustomers_ctl05_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl05$Customer" value="radCustomer" /></span> </td> <td>555555</td> <td>Pied Piper Pizza</td> </tr> <tr> <td> <span title="666666"><input id="ctl00_PrimaryContent_repCustomers_ctl06_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl06$Customer" value="radCustomer" /></span> </td> <td>666666</td> <td>Sandy's Subs</td> </tr> <tr> <td> <span title="777777"><input id="ctl00_PrimaryContent_repCustomers_ctl07_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl07$Customer" value="radCustomer" /></span> </td> <td>777777</td> <td>Leonard's Lambchops</td> </tr> <tr> <td> <span title="888888"><input id="ctl00_PrimaryContent_repCustomers_ctl08_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl08$Customer" value="radCustomer" /></span> </td> <td>888888</td> <td>Dave's Diamond Deli</td> </tr> <tr> <td> <span title="999999"><input id="ctl00_PrimaryContent_repCustomers_ctl09_radCustomer" type="radio" name="ctl00$PrimaryContent$repCustomers$ctl09$Customer" value="radCustomer" /></span> </td> <td>999999</td> <td>Ernie's Eatery</td> </tr></table> Now provide the response and nothing else.
I finally got around this by creating a plain radio button and setting the value using an server-side eval. <input type="radio" name="radCustomer" value='<%#Eval("CustomerNumber") %>' /> Now when the application performs a postback, I check for the value of Request.Form["radCustomer"]. This works flawlessly.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1334926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114486/']}
jdg_375299
stackexchange
llm_judgeable_groundtruth_similarity
13366234
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a string, I need to obtain a count of each word that appears in that string. To do so, I extracted the string into an array, by word, and searched that way, but I have the feeling that searching the string directly is more optimal. Below is the code that I originally wrote to solve the problem. I'm up for suggestions on better solutions though. NSMutableDictionary *sets = [[NSMutableDictionary alloc] init];NSString *paragraph = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"text" ofType:@"txt"] encoding:NSUTF8StringEncoding error:NULL];NSMutableArray *words = [[[paragraph lowercaseString] componentsSeparatedByString:@" "] mutableCopy];while (words.count) { NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init]; NSString *search = [words objectAtIndex:0]; for (unsigned i = 0; i < words.count; i++) { if ([[words objectAtIndex:i] isEqualToString:search]) { [indexSet addIndex:i]; } } [sets setObject:[NSNumber numberWithInt:indexSet.count] forKey:search]; [words removeObjectsAtIndexes:indexSet];}NSLog(@"%@", sets); Example: Starting string: "This is a test. This is only a test." Results: "This" - 2 "is" - 2 "a" - 2 "test" - 2 "only" - 1 Now provide the response and nothing else.
This is exactly what an NSCountedSet is for. You need to break the string apart into words (which iOS is nice enough to give us a function for so that we don't have to worry about punctuation) and just add each of them to the counted set, which keeps track of the number of times each object appears in the set: NSString *string = @"This is a test. This is only a test.";NSCountedSet *countedSet = [NSCountedSet new];[string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByWords | NSStringEnumerationLocalized usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){ // This block is called once for each word in the string. [countedSet addObject:substring]; // If you want to ignore case, so that "this" and "This" // are counted the same, use this line instead to convert // each word to lowercase first: // [countedSet addObject:[substring lowercaseString]]; }];NSLog(@"%@", countedSet);// Results: 2012-11-13 14:01:10.567 Testing App[35767:fb03] // <NSCountedSet: 0x885df70> (a [2], only [1], test [2], This [2], is [2])
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13366234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215845/']}
jdg_375300
stackexchange
llm_judgeable_groundtruth_similarity
22374228
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to find the url of the page when going from one page to the another? as in the first page we are having the url which we get by Window.location.href(),but how to get the url of the second loaded page. Now provide the response and nothing else.
Toto toto = Mockito.spy(new Toto()); Bear in mind that this spies/stubs on the Toto instance you create in this line, and not every newly-created Toto. So when you call: Titi testedObject = new Titi();testedObject.executeTiti(); The constructor new Titi() itself creates a new instance of Toto, unaffected by Mockito, so that call to this.toto.executeAction() will always return 5. Because you're running with PowerMockito, you do have the option of stubbing Toto's constructor : @RunWith(PowerMockRunner.class)@PrepareForTest(Titi.class) // stub the calling class Titi, not Toto!public class TitiTest { @Test public void testExecuteTiti() { Toto toto = Mockito.spy(new Toto()); Mockito.doReturn(2).when(toto).executeToto(Mockito.any(Tutu.class)); PowerMockito.whenNew(Toto.class).withAnyArguments().thenReturn(toto); Titi testedObject = new Titi(); testedObject.executeTiti(); }} But the option I like the best is to create a secondary constructor for Titi, for testing: public Titi(){ this.toto = new Toto(); }/** For testing only. Uses the passed Toto instance instead of a new one. */Titi(Toto toto){ this.toto = toto;} Which then only requires you to adjust your test like this: @Test public void testExecuteTiti(){ Toto toto = Mockito.spy(new Toto()); Mockito.doReturn(2).when(toto).executeToto(Mockito.any(Tutu.class)); Titi testedObject = new Titi(toto); testedObject.executeTiti();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22374228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3365556/']}
jdg_375301
stackexchange
llm_judgeable_groundtruth_similarity
14829190
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to start with project documentation using maven and markdown markup language?Maven site default is APT, which is uncomfortable to learn just to do thing maven way.(Usually nobody in a team will start writing maven site documentation when they also need to learn one more markup language along the way.) Has anybody tried to use markdown (the same markup language as used on github) for Maven project site documentation? I see from Maven Doxia references that it is possible.Any issues? I am new to maven site generation. I think markdown is better to start with, than others markup languages, that the team has not worked with. UPDATE. Succeeded. See answer below. Now provide the response and nothing else.
Quote from http://maven.apache.org/doxia/references/index.html Add this to pom.xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.2</version> <dependencies> <dependency> <groupId>org.apache.maven.doxia</groupId> <artifactId>doxia-module-markdown</artifactId> <version>1.3</version> </dependency> </dependencies> </plugin> Then start adding pages under src/site/markdown/ with .md extension.For every page add menu item like in sniplet below: <body> <!-- http://maven.apache.org/doxia/doxia-sitetools/doxia-decoration-model/decoration.html <item collapse=.. ref=.. name=.. href="README" img=.. position=.. alt=.. border=.. width=.. height=.. target=.. title=.. > --> <menu name="User guide"> <item href="README.html" name="README" /> </menu> <menu ref="reports" inherit="bottom" /> </body> Than use mvn site to generate site.Look at target/site to review results. mvn site:stage -DstagingDirectory=C:\TEMP\fullsite to get multi-modular project site in one folder. Read more about maven-site-plugin . I recommend to use maven-fluido-skin . It is newest style, based on Twitter Bootstrap Add this to site.xml <project name="xxx"> [...] <skin> <groupId>org.apache.maven.skins</groupId> <artifactId>maven-fluido-skin</artifactId> <version>1.3.0</version> </skin> [...]</project> See also https://github.com/winterstein/Eclipse-Markdown-Editor-Plugin
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14829190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/482717/']}
jdg_375302
stackexchange
llm_judgeable_groundtruth_similarity
27042942
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My situation: I have a solution A with hundreds of projects, Some of projects are class libraries and are referenced from other projects. Now I want to create a new solution B which will consist of subset of projects of solution A . I start by adding the first pre-existing project into this new solution B . This project is referencing couple of class libraries from solution A . Therefore it is logical that these libraries cannot be found and I cannot build. Of course I could add all the referenced projects manually into the new solution B but that would take quite a long time, considering the total amount of projects that I need to add. Is there some built in Visual Studio feature that can take care of this on my behalf? I.e. I will be offered an opportunity to import all the referenced projects at once and the B.sln file will be updated automatically. I also have a ReSharper extension but I couldn't find such feature in there as well. EDIT: Some more detail on what I am trying to achieve. A.sln has lots of application projects and literally hundreds of class libraries. I want to create a new B.sln for one particular application project from A.sln and only add the class libraries that it is referencing, directly or indirectly... But the dependencies can go up to 15 levels deep so manually removing projects from original A.sln to create B.sln is really not suitable for me as I would have to carefully consider each one of the projects that I would be manually removing from the original sln file, subsequently reviewing the csproj files to find whether the application I am interested in does not indirectly depends on them via one of its direct references. Now provide the response and nothing else.
ScanParams params = new ScanParams();params.match("userid:fname*");// Use "0" to do a full iteration of the collection. ScanResult<String> scanResult = jedis.scan("0", params);List<String> keys = scanResult.getResult(); Repeat above code for lname and age. Or, match user:id and then filter the groups using a regex and iterating through keys . EDIT: For large collections (millions of keys), a scan result will return a few tens of elements . Adjust your code accordingly to continue scanning until the whole collection of keys has been scanned: ScanParams params = new ScanParams();params.match("userid:fname*");// An iteration starts at "0": http://redis.io/commands/scanScanResult<String> scanResult = jedis.scan("0", params);List<String> keys = scanResult.getResult();String nextCursor = scanResult.getStringCursor();int counter = 0;while (true) { for (String key : keys) { addKeyToProperGroup(key); } // An iteration also ends at "0" if (nextCursor.equals("0")) { break; } scanResult = jedis.scan(nextCursor, params); nextCursor = scanResult.getStringCursor(); keys = scanResult.getResult();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27042942', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3242721/']}
jdg_375303
stackexchange
llm_judgeable_groundtruth_similarity
382637
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know that integration tests test parts of project that interaction with each other somehow. And I need to test this interaction. And there is the question: 1)Should these tests use real database data? I mean I'll have to connect to a real database? 2)I suppose I cannot use common database, I should use my private database for this but my colleges cannot use my tests because they won't have my database. What to do then? 3)I'll have to pass real data to controllers or I can come up with random data? Same question to database data. If real than I'll need to get data from browser and the other things... 4)Do I really need these integration tests if I tested this interactions in unit tests? I just used mocks instead of real data. 5)Won't it be system testing instead of integration? 6)Do integration tests must use real data everytime? Now provide the response and nothing else.
1) Should these tests use real database data? I mean I'll have to connect to a real database? If you're testing the integration between your software and the database, then yes you should use the real database (ideally down to the version you will be using in production). If the database isn't supposed to be part of your tests, you might be able to substitute some other storage mechanism (might be possible if you use an adapter pattern or a database abstraction library). Note that if you manually write queries, the SQL is likely database dependent so you cannot substitute a different database. 2) I suppose I cannot use common database, I should use my private database for this but my colleges cannot use my tests because they won't have my database. What to do then? The database used for testing should only be used for that test during the test run. Afterwards it can be cleared and used for another test run. Therefore, you do need dedicated test databases. Ideally this DB runs locally on your development machine, but managing them centrally would also work (might even be necessary if you have to comply with proprietary licenses). Because your software will run with different production and test databases, you need the specific database to be configurable – e.g. by reading a connection string from an environment variable. Do not put any information that differs between environments into config files if those config files are checked in to version control. Instead, implement a way to use private configurations, e.g. by providing the config as a command line argument or as environment variables. It is of course OK to check in config templates or configs for specific environments, e.g. the production config. 3) I'll have to pass real data to controllers or I can come up with random data? Same question to database data. If real than I'll need to get data from browser and the other things... You may not be allowed to use real data due to legal constraints, e.g. privacy regulations such as HIPAA or GDPR. There's also the risk that real data could accidentally cause real-world actions if your testing setup is buggy, such as sending out emails or incurring charges for third party systems. Instead, prefer simulating a scenario and using that data. If your software has a user interface you could manually play through a scenario and capture this data to replay it later. I've also gathered test data by parsing debug-level log files and manually scrubbing them from any personal data (e.g. exact timestamps, IP addresses, names, emails, …). 4) Do I really need these integration tests if I tested this interactions in unit tests? I just used mocks instead of real data. If you used mocks you tested one half of the interface, but not the integration of both halves interfaces. This is like testing that an electric socket has power, and testing that a plug has the correct shape, but not testing whether the device runs when you plug it into the socket. Unit tests are very useful to carefully test some component in isolation, but they are usually not suitable as a primary testing strategy. Especially for web apps, it is usually much easier to run end to end tests (possibly on the scale of integration or system tests). Relevant browser automation tools are widely available, and even more tools if you just need to test a REST API. 5) Won't it be system testing instead of integration? A integration test integrates some but not all components, others will be replaced by stubs. A system test includes all real components. Typically, integration tests still exclude third party services and only integrate local components.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/382637', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/322016/']}
jdg_375304
stackexchange
llm_judgeable_groundtruth_similarity
16351826
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 you use url_for in Flask to reference a file in a folder? For example, I have some static files in the static folder, some of which may be in subfolders such as static/bootstrap . When I try to serve a file from static/bootstrap , I get an error. <link rel=stylesheet type=text/css href="{{ url_for('static/bootstrap', filename='bootstrap.min.css') }}"> I can reference files that aren't in subfolders with this, which works. <link rel=stylesheet type=text/css href="{{ url_for('static', filename='bootstrap.min.css') }}"> What is the correct way to reference static files with url_for ? How do I use url_for to generate urls to static files at any level? Now provide the response and nothing else.
You have by default the static endpoint for static files. Also Flask application has the following arguments: static_url_path : can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder. static_folder : the folder with static files that should be served at static_url_path . Defaults to the 'static' folder in the root path of the application. It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default : url_for('static', filename='path/to/file') will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file . So if you want to get files from the static/bootstrap folder you use this code: <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}"> Which will be converted to (using default settings): <link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css"> Also look at url_for documentation .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/16351826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1431282/']}
jdg_375305
stackexchange
llm_judgeable_groundtruth_similarity
53546085
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 very simple state in my store: const state = { records: [1,2,3],}; I have a selector for records: export const getRecords = createSelector(getState, (state: State) => state.records)); And what I want now is to have separate selectors for fetching each record by index.For this purpose I want to create one generic selector with props in this way: export const getRecordByIndex = createSelector(getRecords,(state: State, { index }) => state.records[index]),); And after that create a couple of specific selectors e. g.: export const getFirstRecord = createSelector(getRecordByIndex(/* somehow pass index = 0 to this selector */),(firstRecord) => firstRecord),); But I didn't find any mention how to pass parameters to selectors with props when we use them inside createSelector method. Is it possible? Now provide the response and nothing else.
From this blog post: https://timdeschryver.dev/blog/parameterized-selectors As of NgRx 6.1 selectors also accepts an extra props argument. Whichmeans you can now define a selector as the following: export const getCount = createSelector( getCounterValue, (counter, props) => counter * props.multiply);this.counter = this.store.pipe( select(fromRoot.getCount, { multiply: 2 })); Ah ... but rereading your question, you are asking then how to build another selector that uses this selector? The above-linked article suggests building a factory function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53546085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3429127/']}
jdg_375306
stackexchange
llm_judgeable_groundtruth_similarity
235995
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am looking for a way so that a particular user or a group should not given the permission to remove any file in the system, but only read/execute the file. Now provide the response and nothing else.
There are some users on my system who don't know anything about the PC, so they try to explore it for just learning purpose. My intention is that I can give them a separate account by which they can explore the system without accidently removing or changing any file on the system, but I as another user should be able to do any changes on the system. That is the roughly way a Unix/Linux system normally works. A user only has the right to delete or modify (a) files or directories that he owns or (b) files or directories for which a group that he is in has write permission. The system administrator (that's you, I presume) has control over everything. So, just make sure that these new users are in their own individual group. Unix was designed to be a multi-user system. So, from the start, Unix/Linux give normal users only only limited permissions. Generally, no normal user can mess with system files. Only the system administrator, called root , can do that. Some systems allow normal users to get root's capabilities by running sudo . Make sure that your /etc/sudoers file does not give that capability to them. If you want to be severe, do not give them ownership even of a home directory. They would still have write permission to /tmp and /var/tmp but that shouldn't cause trouble unless they create files so big that they fill up the partition.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/235995', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/124146/']}
jdg_375307
stackexchange
llm_judgeable_groundtruth_similarity
2170818
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 confusing little in terminology. A file that is given as input to the linker is called Object File .The linker produces an Image file , which in turn is used as input by the loader. I got this from "MS PE & COFF Specification" Q1. Image file is also referred to as Binary Image , Binary File or just Binary . Right? Q2. So, according to the above stated terminology, the PE/ELF/COFF are the formats of Image File & not the Object File. right? But http://www.sco.com/developers/gabi/latest/ch4.intro.html says This chapter describes the object file format, called ELF (Executable and Linking Format). There are three main types of object files. A relocatable file holds code and data suitable for linking with otherobject files to create an executableor a shared object file. An executable file holds a program suitable for execution; thefile specifies how exec(BA_OS) createsa program's process image. A shared object file holds code and data suitable for linking in twocontexts. First, the link editor [seeld(BA_OS)] processes the shared objectfile with other relocatable and sharedobject files to create another objectfile. Second, the dynamic linkercombines it with an executable fileand other shared objects to create aprocess image. contradictorily he is saying that both Object File & Image File are ELF formats & He is not at all differentiating between object & image files but referring them commonly as Object files. Isn't it wrong? Q3. I know that PE is derived from COFF. But why does the Microsoft specifications of PE format is named Microsoft Portable Executable "and Common Object File Format Specification" . Do they still support COFF? If they, in which OS? I thought PE completely replaced COFF long ago. Now provide the response and nothing else.
I'm the OP. Every one's answer is a partial answer. So, I'm combining all the other answers with what I learnt to complete the answer. This is the " Generally " used terminology. A file that is given as input to the linker (output of assembler) is called Object File or Relocatable File . The linker produces an Image file , which in turn is used as input by the loader. Now, an Image file can either be an Executable file or Library file . These 'Library files' are of two kinds: Static Library (*.lib files for windows. *.a for linux) Shared/Dynamic libraries : DLL ( *.dll on windows) & Shared Object file ( *.so in Linux) The term Binary File / Binary can be used to refer to either an ObjectFile or an ImageFile. Undestand depending up on the context. It is a very general term. Loader when loads the image file into memory. Then it is called Module (I'm not sure about Linux guys, but windows guys call it Module http://www.gliffy.com/pubdoc/1978433/L.jpg alt text http://www.gliffy.com/pubdoc/1978433/L.jpg As I said, these are " Generally " used terminology. There are no strict definitions for the terms 'binary file', 'image file', or 'object file'. Particularly the term 'object file' might sometimes be used to mean an intermediate file output by the compiler for use by the linker, but in another context might mean an executable file. Especially on different platforms they might be used for refer to different or similar things. Even when discussing issues on a single platform, one writer might use the terms somewhat differently than another. Both ObjectFile & ImageFile are in PE Format in windows & ELF format in linux. ELF is not only the format of the image file but is also the format of the object file. Every ELF file starts with an ELF Header. The second field of an ELF Header is e_type ; this fields lets us know whether the file is an object file (aka a relocatable in ELF parlance), or an image (which can be either an executable or a shared object) or something else (core file's are also ELF files). I don't know if there is any bit in header that differentiates an Object file from Image file. It needs to be checked. I know that PE is derived from COFF. But why does the Microsoft specifications of PE format is named Microsoft Portable Executable "and Common Object File Format Specification". Do they still support COFF? If they, in which OS? I thought PE completely replaced COFF long ago. As far as "PE" vs "COFF", my recollection is that Microsoft use the "COFF" specification as the starting point for the "PE" specification but extended it for their needs. So strictly speaking a "PE" file isn't a "COFF" file, but it's very similar in many ways.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2170818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/193653/']}
jdg_375308
stackexchange
llm_judgeable_groundtruth_similarity
160384
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'm sure this is a trivial question for someone who knows something about electromagnetic radiation, but: how do experimenters measure the wavelength/frequency of light? For example, how do we know that red light has $650-700~\text{nm}$ wavelength? Now provide the response and nothing else.
The earliest accurate determination of wavelength was, I think, by Michelson. Using his invention, the Michelson Interferometer, he could turn a micrometer dial and actually count how many wavelengths he moved a mirror. Reasonable monochromatic light could be had at the time from mercury vapor (or other elemental) discharge tubes or from a monochromator (a spectroscope with a slit on the output to select a color). This was around 1880. I confess I don't know for sure. He was determined to measure the speed of light. Exactly when he worked on wavelength I don't know. I'm sure someone here can add that info. http://physical-optics.blogspot.com/2011/06/michelsons-interferometer.html Michelson was able to count a lot of wavelengths so that the mirror moved enough to get a good average from the mechanical measurement. He was able to measure the wavelength of precisely known colors so that the results were easily reproduced by others. At the time there was a lot of interest in the spectra of excited atoms of elements and of the sun and stars through the new medium of photography. Photographic spectra of a star was done first in 1863. Once you have a wavelength and the speed, which Michelson also determined to a high degree of accuracy by refining the the rotating mirror method, the frequency is just f=velocity/wavelength. The frequencies are crazy big numbers like the red in a helium-neon laser is 4.7376 x 10^14 per second or 473.76 THz. That's tera-Hertz and it is nice that tera- is also trillion. This is why people use wavelength in nanometers, so that the red from the laser is described as 632.8nm, which is a lot easier. If you read older material you will see that we used a slightly more convenient measure, the Angstrom, which is 1/10 a nanometer. The same light is 6328 $\overset{\circ}{A} $. The Angstrom is abbreviated as a capital 'A' with a little dot or circle over it. (It is in the UTF8 character set but I'm not sure will render for everyone, so I faked it in LaTeX.) I think I got that frequency calculation right. By the way, it is accepted to use a Greek lambda $\lambda $ for wavelength and nu $\nu $ for frequency. Then $velocity\; =\; \lambda \nu $.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/160384', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/63691/']}
jdg_375309
stackexchange
llm_judgeable_groundtruth_similarity
864487
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Given the value of sinh(x) for example sinh(x) = 3/2 How can I calculate the value of cosh(x) ? Now provide the response and nothing else.
Use the identity $\cosh^2x-\sinh^2x \equiv 1$. If $\sinh x = \frac{3}{2}$ then$$\cosh^2x - \left(\frac{3}{2}\right)^{\! 2} = 1$$$$\cosh^2x - \frac{9}{4} = 1$$$$\cosh^2x = \frac{13}{4}$$It follows that $\cosh x = \pm\frac{1}{2}\sqrt{13}$. Since $\cosh x \ge 1$ for all $x \in \mathbb{R}$ we have $\cosh x = \frac{1}{2}\sqrt{13}$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/864487', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/162467/']}
jdg_375310
stackexchange
llm_judgeable_groundtruth_similarity
13608855
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 the following CSS taken from Twitter Bootstrap what does the ampersand (&) character mean? .clearfix { *zoom: 1; &:before, &:after { display: table; content: ""; } &:after { clear: both; }} Now provide the response and nothing else.
That's LESS , not CSS. This syntax allows you to nest selector modifiers. .clearfix { &:before { content: ''; }} Will compile to: .clearfix:before { content: '';} With the & , the nested selectors compile to .clearfix:before . Without it, they compile to .clearfix :before .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13608855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1761594/']}
jdg_375311
stackexchange
llm_judgeable_groundtruth_similarity
3294398
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: Express $$\sum_{j=1}^{n}\sum_{i=1}^{n} \frac{1}{i(i+j)}$$ in terms of the harmonic numbers $H_n$ . I guess that there could be several approaches for doing this. Now provide the response and nothing else.
Let $S$ be the desired sum. By interchanging the roles of $i$ and $j$ , we have $$2S=\sum_i \sum_j \left( \frac{1}{i(i+j)}+\frac{1}{j(i+j)} \right) = \sum_i \sum_j \frac{1}{ij} =H_n^2.$$ Hence $S=H_n^2/2$ .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3294398', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/671540/']}
jdg_375312
stackexchange
llm_judgeable_groundtruth_similarity
7447478
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 a Java Servlet how can I change the value of an existing cookie? There is an addCookie method, but no deleteCookie or editCookie in HttpServletResponse Now provide the response and nothing else.
Those indeed don't exist. Just create utility methods yourself which do that. Particularly getting the desired cookie is quite bloated. E.g. public final class Servlets { private Servlets() {} public static Cookie getCookie(HttpServletRequest request, String name) { if (request.getCookies() != null) { for (Cookie cookie : request.getCookies()) { if (cookie.getName().equals(name)) { return cookie; } } } return null; }} To edit a cookie, set its value and then add it to the response: Cookie cookie = Servlets.getCookie(request, "foo");if (cookie != null) { cookie.setValue(newValue); response.addCookie(cookie);} Set if necessary the maxage, path and domain as well if they differs from your default. The client namely doesn't send this information back. To delete a cookie, set the max age to 0 (and preferably also the value to null ): Cookie cookie = Servlets.getCookie(request, "foo");if (cookie != null) { cookie.setMaxAge(0); cookie.setValue(null); response.addCookie(cookie);} Set if necessary the path and domain as well if they differs from your default. The client namely doesn't send this information back.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7447478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/190822/']}
jdg_375313
stackexchange
llm_judgeable_groundtruth_similarity
26270681
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The documentation for asyncio gives two examples for how to print "Hello World" every two seconds: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio-hello-world-callback https://docs.python.org/3/library/asyncio-task.html#asyncio-hello-world-coroutine I can run those from the interpreter, but if I do I lose access to the interpreter. Can an asyncio event loop be run in the background, so that I can keep typing commands at the interpreter? Now provide the response and nothing else.
Edit: If using Python 3.8 or above, you should use the asyncio repl, as explained in zeronone's answer . If using 3.7 or lower, you can use this answer. You can run the event loop inside a background thread: >>> import asyncio>>> >>> @asyncio.coroutine... def greet_every_two_seconds():... while True:... print('Hello World')... yield from asyncio.sleep(2)... >>> def loop_in_thread(loop):... asyncio.set_event_loop(loop)... loop.run_until_complete(greet_every_two_seconds())... >>> >>> loop = asyncio.get_event_loop()>>> import threading>>> t = threading.Thread(target=loop_in_thread, args=(loop,))>>> t.start()Hello World>>> >>> Hello World Note that you must call asyncio.set_event_loop on the loop , otherwise you'll get an error saying that the current thread doesn't have an event loop. If you want to interact with the event loop from the main thread, you'll need to stick to loop.call_soon_threadsafe calls. While this kind of thing is an ok way to experiment in the interpreter, in actual programs, you'll probably want all your code running inside the event loop, rather than introducing threads.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26270681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/916142/']}
jdg_375314
stackexchange
llm_judgeable_groundtruth_similarity
34838659
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this piece of code : var obj1;var obj2;function x() { obj1 = this;}function y() { obj2 = this;}x();y();console.log(obj1 === obj2);console.log(obj1 === this); I ran this code in NodeJS using command line : node app.js and ran as a script in Chrome browser The result : in NodeJS, the result was : true false NodeJS result In Chrome browser, the result was : true true Browser result How can this happened ? can anyone explain what really going on under the hood ? Now provide the response and nothing else.
In the browser, running in the global scope, this is always window in your example var obj1;var obj2;function x() { obj1 = this; // window}function y() { obj2 = this; // window}x();y();console.log(obj1 === obj2); // window === window = trueconsole.log(obj1 === this); // window === window = true This is not how it works in Node. In Node.js all modules (script files) are executed in their own closure while browsers execute all script files directly within the global scope. In other words, in just about any file running in Node, this will just be an empty object, as Node wraps the code in an anonymous function that is called immediately, and you'd access the global scope within that context with GLOBAL instead. This is also mentioned in the Globals documentation : Some of these objects aren't actually in the global scope but in the module scope - this will be noted. However, when calling a function without a specific context in Node.js, it will normally be defaulted to the global object - The same GLOBAL mentioned earlier, as it's execution context. So outside the functions, this is an empty object, as the code is wrapped in a function by Node, to create it's own execution context for every module (script file), while inside the functions, because they are called with no specified execution context, this is the Node GLOBAL object In Node.js you'd get var obj1;var obj2;function x() { obj1 = this; // GLOBAL}function y() { obj2 = this; // GLOBAL}x();y();console.log(obj1 === obj2); // GLOBAL === GLOBAL = trueconsole.log(obj1 === this); // GLOBAL === {} = false Where the last this is indeed an empty object, as explained above For completeness, it's worth noting that in strict mode, you'd get the same result in a browser ( true, false ) as in Node, but that's because the variables are just the opposite of what they are in Node "use strict"var obj1;var obj2;function x() { obj1 = this; // undefined}function y() { obj2 = this; // undefined}x();y();console.log(obj1 === obj2); // undefined === undefined = trueconsole.log(obj1 === this); // undefined === window = false This is because the value passed as this to a function in strict mode is not forced into being an object (a.k.a. "boxed"). For a normal function in non-strict mode, this is always an object, and it's always the global object if called with an undefined or null this-value, i.e. without a specific execution context. Not only is automatic boxing a performance cost, but exposing the global object in browsers is a security hazard, because the global object provides access to functionality that "secure" JavaScript environments must restrict. Thus for a strict mode function, the specified this is not boxed into an object, and if unspecified, this will be undefined inside functions, as shown above, but this will still be the window in the global scope. The same thing happens in strict-mode in Node.js, where this inside the functions is no longer GLOBAL but undefined , and this outside the functions will still be the same empty object, and the end result will still be true, false , but the value of this will be different in strict-mode in Node.js as well.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34838659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4814411/']}
jdg_375315
stackexchange
llm_judgeable_groundtruth_similarity
396000
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: As far as I know, the textbook approach to determining the convergence of series like $$\sum_{n=1}^\infty\frac{\cos n}{n}$$ and $$\sum_{n=1}^\infty\frac{\sin n}{n}$$ uses Dirichlet's test, which involves bounding the partial sums of the cosine or sine terms. I have two questions: Are there any other approaches to seeing that these series are convergent? I'm mostly just interested to see what other kinds of arguments might be made. What's the best way to show that these two series are only conditionally convergent? I don't even know the textbook approach to that question. Now provide the response and nothing else.
Hint for 2) $$\sum_{n=1}^{\infty} \frac{|\cos n|}{n} \geq \sum_{n=1}^{\infty} \frac{\cos^2 n}{n}=\sum_{n=1}^{\infty} \frac{1+\cos {2n}}{2n}$$ Convergence of $\sum_{n=1}^{\infty}\frac{\cos{2n}}{2n}$, and divergence of $\sum_{n=1}^{\infty}\frac{1}{2n}$ gives the divergence. The same method applies to $\sum_{n=1}^{\infty}\frac{|\sin n|}{n}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/396000', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23611/']}
jdg_375316
stackexchange
llm_judgeable_groundtruth_similarity
43990890
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 get a 404 Not Found in the Chrome developer console for the app.module.js because the URL trying to be resolved, after first typing in the URL to index.html, is like this, notice the app.module is missing the .js extension : http://localhost:8080/someTomcatContext/scripts/someAppName/src/app/app.module Here is the folder structure: node_modulespackage.jsonstyles.csssystemjs.config.extras.jssystemjs.config.jssystemjs-angular-loader.jstslint.jsonsrc|-- app| |-- app.component.ts| |-- app.module.ts| |-- app.routes.ts|-- index.html|-- main.ts|-- tsconfig.json I have the following system.config.js (function (global) { System.config({ paths: { // paths serve as alias 'npm:': '../node_modules/'},// map tells the System loader where to look for thingsmap: { // our app is within the app folder 'app': 'src/app', // angular bundles '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', // other libraries 'rxjs': 'npm:rxjs', 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js'},// packages tells the System loader how to load when no filename and/or no extensionpackages: { app: { defaultExtension: 'js', meta: { './*.js': { loader: 'systemjs-angular-loader.js' } } }, rxjs: { defaultExtension: 'js' }} });})(this); I have tried changing the wildcard with the following two variations in order to append the .js extension inside the system.config.js shown above: './src/app/*.js' './app/*.js' Here is the contents of the index.html: <!DOCTYPE html><html> <head> <title>Angular QuickStart</title> <script>document.write('<base href="' + document.location + '" />');</script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../styles.css"> <!-- Polyfill(s) for older browsers --> <script src="../node_modules/core-js/client/shim.min.js"></script> <script src="../node_modules/zone.js/dist/zone.js"></script> <script src="../node_modules/systemjs/dist/system.src.js"></script> <script src="../systemjs.config.js"></script> <script> System.import('main.js').catch(function(err){ console.error(err); }); </script> </head> <body> <my-app>Loading AppComponent content here ...</my-app> </body></html> Here is the main.ts: import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';import { AppModule } from './app/app.module';platformBrowserDynamic().bootstrapModule(AppModule); Now provide the response and nothing else.
UP TO DATE(Ver 5.0.0-rc3): While getting this error, this means you are using old Database API. This can solved by importing FirebaseListObservable from depracated module(See also @Ashish Jha answer): import { AngularFireModule } from 'angularfire2';import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database-deprecated'; It's recommended to use the latest API since AngularFire 5.0 brings new API for the Realtime Database. Refer upgrade guide . ORIGINAL ANSWER: AngularFire2 has separate its modules since 4.0.0+. you can import those two module if you want use auth of angularfire2, see their change log : import {AngularFireModule} from 'angularfire2';// for auth import {AngularFireAuthModule} from 'angularfire2/auth';// for databaseimport {AngularFireDatabaseModule} from 'angularfire2/database'; and import Auth and Observable (AuthMethods can be found in AngularFireAuth) type by: // for authimport { AngularFireAuth } from 'angularfire2/auth';// for databaseimport { AngularFireDatabase } from 'angular2/database';// for Observablesimport {FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43990890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3724142/']}
jdg_375317
stackexchange
llm_judgeable_groundtruth_similarity
449666
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 am going to design a circuit which is going to output some digital signals. The output stage of the circuit will have some level shifters. The level shifters will give flexibility to the user to choose the voltage level (1.8V, 3.3V or 5V) of the output signals. I am planning to place a three-position slide switch on the PCB. According to the position of the switch, one of mosfets will be shorted, and so, corresponding feedback branch will activate and set the output voltage. Can you please review this idea? I am not sure if the feedback signal will be distorted or not. I think the switching frequency of the buck converter to be around 500kHz. Is this idea feasible? Can you please make some suggestions to improve it, or tell me why it wouldn't work? EDIT: The switch will be a panel mount one and will stay in a remote location. That is why I am using the mosfets to shorten the feedback paths. Now provide the response and nothing else.
Two things. First, use two FETs and two wires to control them instead of 3, and second, use a resistor-ladder approach. You have three low-side resistors, R2a,b,c. Wire them in series, then use the two FETs to short intermediate connections to ground. This is fail-safe and is simple to control directly with an on-off-on SPDT switch. simulate this circuit – Schematic created using CircuitLab Exercise for the student: calculate the values for R2a/b and R3 based on the Vfb of your regulator. Here's what I came up with for Vfb=0.6V (resistors in kOhms): How it works: When M2 and M1 are off, Vout is 1.8V as set by Vref*(1 + R1/(R2a+R2b+R2c)) When M1 is on, Vout is 3.3V as set by Vref*(1 + R1/(R2a+R2b)) When M2 is on, Vout is 5.0V as set by Vref*(1 + R1/R2a) Note that it is impossible to set any higher voltage than 5V by accident. If both M1 and M2 are on, you still get only 5V because R2b is already grounded by M2. Like I said, fail-safe. As far as what it does to your regulator, changing voltage will change the stepping ratio. Make sure that the regulator can work at all three settings, and that the inductor is appropriately sized to give acceptable ripple current.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/449666', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5542/']}
jdg_375318
stackexchange
llm_judgeable_groundtruth_similarity
90178
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 working on a web application where I want the content to fill the height of the entire screen. The page has a header, which contains a logo, and account information. This could be an arbitrary height. I want the content div to fill the rest of the page to the bottom. I have a header div and a content div . At the moment I am using a table for the layout like so: CSS and HTML #page { height: 100%; width: 100%}#tdcontent { height: 100%;}#content { overflow: auto; /* or overflow: hidden; */} <table id="page"> <tr> <td id="tdheader"> <div id="header">...</div> </td> </tr> <tr> <td id="tdcontent"> <div id="content">...</div> </td> </tr></table> The entire height of the page is filled, and no scrolling is required. For anything inside the content div, setting top: 0; will put it right underneath the header. Sometimes the content will be a real table, with its height set to 100%. Putting header inside content will not allow this to work. Is there a way to achieve the same effect without using the table ? Update: Elements inside the content div will have heights set to percentages as well. So something at 100% inside the div will fill it to the bottom. As will two elements at 50%. Update 2: For instance, if the header takes up 20% of the screen's height, a table specified at 50% inside #content would take up 40% of the screen space. So far, wrapping the entire thing in a table is the only thing that works. Now provide the response and nothing else.
2015 update: the flexbox approach There are two other answers briefly mentioning flexbox ; however, that was more than two years ago, and they don't provide any examples. The specification for flexbox has definitely settled now. Note: Though CSS Flexible Boxes Layout specification is at the Candidate Recommendation stage, not all browsers have implemented it. WebKit implementation must be prefixed with -webkit-; Internet Explorer implements an old version of the spec, prefixed with -ms-; Opera 12.10 implements the latest version of the spec, unprefixed. See the compatibility table on each property for an up-to-date compatibility status. (taken from https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes ) All major browsers and IE11+ support Flexbox. For IE 10 or older, you can use the FlexieJS shim. To check current support you can also see here: http://caniuse.com/#feat=flexbox Working example With flexbox you can easily switch between any of your rows or columns either having fixed dimensions, content-sized dimensions or remaining-space dimensions. In my example I have set the header to snap to its content (as per the OPs question), I've added a footer to show how to add a fixed-height region and then set the content area to fill up the remaining space. html,body { height: 100%; margin: 0;}.box { display: flex; flex-flow: column; height: 100%;}.box .row { border: 1px dotted grey;}.box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */}.box .row.content { flex: 1 1 auto;}.box .row.footer { flex: 0 1 40px;} <!-- Obviously, you could use HTML5 tags like `header`, `footer` and `section` --><div class="box"> <div class="row header"> <p><b>header</b> <br /> <br />(sized to content)</p> </div> <div class="row content"> <p> <b>content</b> (fills remaining space) </p> </div> <div class="row footer"> <p><b>footer</b> (fixed height)</p> </div></div> In the CSS above, the flex property shorthands the flex-grow , flex-shrink , and flex-basis properties to establish the flexibility of the flex items. Mozilla has a good introduction to the flexible boxes model .
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/90178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16299/']}
jdg_375319
stackexchange
llm_judgeable_groundtruth_similarity
37431817
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 facing some problems with kotlin in conjunction with spring. I have a controller bean (without an interface btw) which has an auto-wired service bean via the primary constructor. It works perfectly unless I use caching annotations for the controller. Apparently springs caching generates a proxy class under the hood which deals with the caching. My code looks like this: @RestController@RequestMapping("/regions/")open class RegionController @Autowired constructor(val service: RegionService) { @RequestMapping("{id}", method = arrayOf(RequestMethod.GET)) @Cacheable(cacheNames = arrayOf("regions")) fun get(@PathVariable id: Long): RegionResource { return this.service.get(id) }} The problem now is a null pointer exception when the method is executed, actually this.service is null which technically is not possible as it is a nonnull variable in kotlin. I assume that class proxies generated by spring initialize the class with null values instead of the autowired bean. This must be a common pitfall using kotlin and spring. How did you circumvent this problem? Now provide the response and nothing else.
In Kotlin both classes and members are final by default. For the proxying library ( CGLIB , javaassist ) to be able to proxy a method it has to be declared non final and in a non final class ( since those libraries implement proxying by subclassing ). Change your controller method to: @RequestMapping("{id}", method = arrayOf(RequestMethod.GET))@Cacheable(cacheNames = arrayOf("regions"))open fun get(@PathVariable id: Long): RegionResource { return this.service.get(id)} You probably see a warning in console regarding RegionController methods not being subject to proxying. The Kotlin compiler plugin The Kotlin team has acknowledged this difficulty and created a plugin that marks the standard AOP proxy candidates e.g. @Component with open . You can enable the plugin by in your build.gradle : plugins { id "org.jetbrains.kotlin.plugin.spring" version "1.1.60"}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37431817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1245622/']}
jdg_375320
stackexchange
llm_judgeable_groundtruth_similarity
191961
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: Bug tracker for any decent sized project seem like a bit of a no-brainer to me - it makes it really easy to organise hundreds or thousands issues, without issues colliding or getting mixed up. So when I see some really big projects, like Git, using a mailing list as the main method of coordinating maintenance and development, I get a bit blown away. Examples: Git - Community page: ...Bug reports should be sent to this mailing list. Debian bug tracking system , per Wikipedia: ...Its unique feature is that it doesn't have any form of web-interface to edit bug reports - all modification is done through email. Many modern bug trackers have very good integration with email (you can receive comments or notifications about bugs you're watching, or that get assigned to you), as well as to version control systems (commits can be marked as resolving an issue, etc.). Much of this would have to be done manually with a mailing list, and you get tons of emails about bugs you're not interested in. So what are the main advantages of a mailing list over a web-based bug tracker? Why do some big projects only use a mailing list? Now provide the response and nothing else.
The preference you observe looks like a natural consequence of recommendation clearly stated in GNU Coding Standards . It suggests to report bugs by email, as you can see in below quote (I marked bold the part that directly addresses your observations): 4.7.2 --help The standard --help option should output brief documentation for how to invoke the program, on standard output, then exit successfully. Other options and arguments should be ignored once this is seen, and the program should not perform its normal function. Near the end of the ‘--help’ option’s output, please place lines giving the email address for bug reports , the package’s home page (normally ‘http://www.gnu.org/software/pkg’ , and the general page for help using GNU programs. The format should be like this: Report bugs to: mailing-address pkg home page: <http://www.gnu.org/software/pkg/> General help using GNU software: <http://www.gnu.org/gethelp/> It is ok to mention other appropriate mailing lists and web pages. Above preference, in turn, reflects universal acceptance of email as a form of electronic communication. Any user reading --help message like suggested above is supposed to easily understand what to do if they see a bug - mailing is easy. Issue tracker might be (and I think is ) better for a developer working in the project, but for a wider audience it would be harder to present and explain how to use it, especially taking into account wide variety and differences between different issue tracking systems . One project can use Bugzilla, another will stick with JIRA, third with... GNATS , etc etc, etc. There's just no way to present all this "zoo" in a way that would be as standard and uniform as Report bugs to: mailing-address Note above doesn't mean that projects shouldn't be using issue tracker internally . As explained in an excellent answer to related question , Your bug tracker is for your convenience, not your customers'. If you can't be bothered to take their phone or email issue and enter it yourself, how do you think they feel? You need to be able to enter issues and assign them manually to a client...
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/191961', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/47367/']}
jdg_375321
stackexchange
llm_judgeable_groundtruth_similarity
1475279
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 use emacs python-mode, if the last character of a line is an open parenthesis it indents the next line just one step in from the indentation of the previous line. call_some_function( some_very_long_argument_that_I_want_to_put_on_its_own_line) I like that. Now in ecmascript-mode (which I am using for actionscript 3), it always indents to the level of the previous parenthesis. call_some_function( this_is_not_really_saving_me_any_horizontal_space); How can I make ecmascript-mode indent like python-mode in this respect? Now provide the response and nothing else.
Since ecmascript-mode is based on cc-mode, you can use c-set-offset which allows you to customize any syntactic symbol's offset with the preferred value. In your case, go to the point which is indented in the wrong level, hit C-c C-o (or type M-x c-set-offset ), accept the suggested symbol ( arglist-intro ), and set it a new value (e.g. + , the default offset). You can also do it programmatically in your dotemacs, for instance, with: (add-hook 'ecmascript-mode-hook (lambda () (c-set-offset 'arglist-intro '+) (c-set-offset 'arglist-close 0)))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1475279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2652/']}
jdg_375322
stackexchange
llm_judgeable_groundtruth_similarity
272749
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: The cosmic microwave background (CMB) radiation comprises about 98% of all electromagnetic radiation in the universe. And, from the creation of the CMB to today that electromagnetic radiation has red shifted to about 1100 times its original wavelength. And, the energy content of electromagnetic radiation is inversely proportionally to its wavelength. Therefore, the CMB has shed an immense amount of energy in the last 13.8 billion years because of the redshift due to the expanding universe. How does this amount of energy compare to the estimate of Dark Energy in the universe? Now provide the response and nothing else.
In terms of direct numbers at present, dark energy comprises about 70% of all of the energy in the universe. Radiation, on the other hand, makes up less than 0.005% of the energy in the universe. It's such a small fraction that it's less than the error associated with the values for matter and dark energy. A good way to approximate how the two energies compare over time (with expansion included) is through the scale factor of the metric, $a$. The scale factor represents the ratio of the distance between two points at any given moment of time to the distance between those two points now. Naturally, as the universe expands, the amount of volume in a given region of the universe increases like $a^3$. With that said, let's take a look at the volume density of both your types of energy. As you quite correctly pointed out, the expansion of the universe redshifts radiation, which means the universe loses that energy entirely. Add to that the fact that the number density of a fixed number of photons is proportional to $\frac{1}{a^3}$, and it's not hard to understand why relativity says the total energy density of radiation decreases like $\frac{1}{a^4}$. In other words the total amount of energy contained in radiation decreases approximately like $\frac{1}{a}$. As for dark energy, the current accepted model, $\Lambda$-CDM, treats dark energy like a constant energy density. That means as the universe expands, the amount of dark energy per unit volume remains constant. Yikes. This means the total amount of dark energy increases like $a^3$. Add them together and you see there is a net increase in total energy of the universe (the total energy of matter remains more or less constant). Clearly it isn't the case that the energy lost from radiation is picked up as dark energy. But, of course, you already knew that. You had already gone as far as realizing that the radiation energy fell off like $\frac{1}{a}$ and there would need to be a seriously funky (<-- technical term) relationship between $a$ and the energy density of dark energy for the two totals to sum to a constant. Kudos to you for having figured this out by yourself and asking an excellent follow-up question.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/272749', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/100352/']}
jdg_375323
stackexchange
llm_judgeable_groundtruth_similarity
4836391
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Naming conventions are important, and primary key and foreign key have commonly used and obvious conventions ( PK_Table and FK_Table_ReferencedTable , respectively). The IX_Table_Column naming for indexes is also fairly standard. What about the UNIQUE constraint? Is there a commonly accepted naming convention for this constraint? I've seen UK_TableName_Column , UQ_TableName_Column , and someone recommending AX_TableName_Column - I don't know where that comes from. I've typically used UQ but I don't particularly like it, and I do not enjoy having to defend my choice of using it against a UK advocate. I would simply like to see if there is a consensus on the most prevalent naming, or a good reasoning as to why one makes more sense than the others. Now provide the response and nothing else.
My thinking is it isn't a key: it's a constraint. It could be used as a key of course, and uniquely identifies a row, but it isn't the key. An example would be that the key is "ThingID", a surrogate key used in place of ThingName the natural key. You still need to constrain ThingName: it won't be used as a key though. I'd also use UQ and UQC (if clustered). You could use a unique index instead and go for "IXU". By the logic employed, an index is also a key but only when unique. Otherwise it's an index. So then we'd start with IK_columnname for unique indexes and IX_columnname for non-unique indexes. Marvellous. And the only difference between a unique constraint and a unique index is INCLUDE columns. Edit: Feb 2013. Since SQL Server 2008, indexes can have filters too. Constraints can not So, it comes down to one of stick with UQ as per the rest of the SQL-using planet use IK for unique indexes (IKC for clustered too) to be consistent...
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4836391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146077/']}
jdg_375324
stackexchange
llm_judgeable_groundtruth_similarity
22648
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm using opencv houghcircle function to detect circles. http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/hough_circle/hough_circle.html Problem is if I set minimum radius to null it detects wrong center and draws smaller radius circle or sometimes larger radius circle. I'm looking for increasing accuracy of detection by adjusting threshold parameter 1 and 2. Now provide the response and nothing else.
If you have an idea what size circles you are looking for, then it would be best to set min_radius and max_radius accordingly. Otherwise, it will return anything circular of any size. Parameters 1 and 2 don't affect accuracy as such, more reliability. Param 1 will set the sensitivity; how strong the edges of the circles need to be. Too high and it won't detect anything, too low and it will find too much clutter. Param 2 will set how many edge points it needs to find to declare that it's found a circle. Again, too high will detect nothing, too low will declare anything to be a circle. The ideal value of param 2 will be related to the circumference of the circles.
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/22648', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/15386/']}
jdg_375325
stackexchange
llm_judgeable_groundtruth_similarity
258752
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 $M(n)$ be an $n\times n$ matrix in the variables $x_1,\dots,x_n$ with entries $$M_{i,j}(n)=\frac{x_{\max(i,j)}}{x_{\min(i,j)}}, \qquad 1\leq i,j\leq n.$$ I'm interested in the following: Questions. (1) Is there a neat or "closed form" evaluation for the determinant $\det M(n)$ ? (2) Is there an explicit formula for the inverse of $M(n)$ ? Thank you. Now provide the response and nothing else.
Let us write $$a_r=\frac{x_{r+1}}{x_r}$$ for $r=1\cdots n$. We can then write the matrix $M(n)$ in the form $$\begin{pmatrix} 1 & a_1 & a_1a_2& \cdots & a_1a_2\cdots a_{n-1} \\ a_1 & 1 & a_2& \cdots & a_2\cdots a_{n-1}\\ \vdots & \vdots & \vdots &\ddots & \vdots\\ a_1a_2\cdots a_{n-1}& a_2\cdots a_{n-1} &\cdots & a_{n-1} & 1\end{pmatrix} $$ We do now Gauss elimination, and reduce $a_{n-1}$ times the $(n-1)$-th row from the $n$-th row. We then get in the last row $0, 0, \ldots (1-a_{n-1}^2)$.But this means that $det(M(n))=det(M(n-1))(1-a_{n-1}^2)$ and by induction$$det(M(n)) = \prod_{r=1}^{n-1} (1-a_r^2)=\prod_{r=1}^{n-1}(1-\frac{x_{r+1}^2}{x_r^2}).$$By using inductively the Gauss elimination mentioned above, one can also get the inverse of $M(n)$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/258752', 'https://mathoverflow.net', 'https://mathoverflow.net/users/66131/']}
jdg_375326
stackexchange
llm_judgeable_groundtruth_similarity
34011
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to expand a glob pattern (like ../smth*/* , or /etc/cron*/ ) into a list of files, programmatically. What would be the best way to do it? Now provide the response and nothing else.
Just let it expand inside an array declaration's right side: list=(../smth*/) # grab the listecho "${#list[@]}" # print array lengthecho "${list[@]}" # print array elementsfor file in "${list[@]}"; do echo "$file"; done # loop over the array Note that the shell option `nullglob` needs to be set. **It is not set by default.** It prevents an error in case the glob (or one of multiple globs) does not match any name. Set it in bash with shopt -s nullglob or in zsh or yash with set -o nullglob though in zsh (where the nullglob initially came from), you'd rather use the (N) glob qualifier to avoid having to change a global setting: list( ../smth*/(N) ) The ksh93 equivalent: list=( ~(N)../smth*/ )
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/34011', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/15487/']}
jdg_375327
stackexchange
llm_judgeable_groundtruth_similarity
28787457
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 don't want type the extra arguments NODE_ENV='production' gulp every time I run gulp to set an environment variable. I would rather set the environment variable from within gulp via a task . What would be a good way to achieve this? Now provide the response and nothing else.
gulp.task('set-dev-node-env', function() { return process.env.NODE_ENV = 'development';});gulp.task('set-prod-node-env', function() { return process.env.NODE_ENV = 'production';}); Use it like: gulp.task('build_for_prod', ['set-prod-node-env'], function() { // maybe here manipulate config object config.paths.src.scripts = config.paths.deploy.scripts; runSequence( 'build', 's3' );});
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28787457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/516813/']}
jdg_375328
stackexchange
llm_judgeable_groundtruth_similarity
25839487
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 5 anchors on my html page. Is there any way that the page scrolls automatically to the next anchor (#) by a single Mouse-wheel scroll? Is there a way that it happens regardless of the anchor's name? just to the next anchor. Now provide the response and nothing else.
This works in Chrome, IE, Firefox, Opera, and Safari: (function() { var delay = false; $(document).on('mousewheel DOMMouseScroll', function(event) { event.preventDefault(); if(delay) return; delay = true; setTimeout(function(){delay = false},200) var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail; var a= document.getElementsByTagName('a'); if(wd < 0) { for(var i = 0 ; i < a.length ; i++) { var t = a[i].getClientRects()[0].top; if(t >= 40) break; } } else { for(var i = a.length-1 ; i >= 0 ; i--) { var t = a[i].getClientRects()[0].top; if(t < -20) break; } } if(i >= 0 && i < a.length) { $('html,body').animate({ scrollTop: a[i].offsetTop }); } });})(); Fiddle at http://jsfiddle.net/t6LLybx8/728/ How it works To monitor the mouse wheel in most browsers, use $(document).on('mousewheel') . Firefox is the oddball, and it requires $(document).on('DOMMouseScroll') . To get the direction of the mouse wheel (up or down), use event.originalEvent.wheelDelta . Again, Firefox is the oddball, and you have to use -event.originalEvent.detail . If the direction is a negative number, you're scrolling down the page. In that case, loop through each tag beginning with the first , until its first getClientRects() top is >= 40. (I used 40, in case the browser adds a default margin at the top of the viewport.) If the direction is a positive number, you're scrolling up the page. In that case, loop through each tag beginning with the last , until its first getClientRects() top is < -20. (I used -20 to ensure we move up the page.) The delay variable prevents the mouse wheel from scrolling too quickly. The entire function is wrapped in a closure, so delay remains a private variable.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25839487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3855345/']}
jdg_375329
stackexchange
llm_judgeable_groundtruth_similarity
477226
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 stick to the practice of keeping the database normalized, but that leads to the need to run multiple join queries. Is there a performance degradation if many queries use joins vs having a call to a single table that might contain redundant data? Now provide the response and nothing else.
Keep the Database normalised UNTIL you have discovered a bottleneck. Then only after careful profiling should you denormalise. In most instances, having a good covering set of indexes and up to date statistics will solve most performance and blocking issues without any denormalisation. Using a single table could lead to worse performance if there are writes as well as reads against it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/477226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49632/']}
jdg_375330
stackexchange
llm_judgeable_groundtruth_similarity
2549651
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 solved the limit $$\lim_{x \to \infty} x(\ln(1+x) - \ln(x))$$ by writing it as $\lim_{x \to \infty} \frac{\ln(\frac{1+x}{x})}{\frac{1}{x}}$ and applying l'Hopital rule but is it possible to solve it without using l'Hopital rule? Now provide the response and nothing else.
\begin{align*}x(\ln(1+x)-\ln(x))=x\ln\left(1+\dfrac{1}{x}\right)=\ln\left(1+\dfrac{1}{x}\right)^{x}\rightarrow\ln e=1,\end{align*}if you accept that $\left(1+\dfrac{1}{x}\right)^{x}\rightarrow e$ as $x\rightarrow\infty$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2549651', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/509051/']}
jdg_375331
stackexchange
llm_judgeable_groundtruth_similarity
43439191
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i would like to use a strokeshadow for my line chart. But every solution that i found works only with chartjs v1. Is their any solution for the newest one? thats what i designed with chartjs v1, but just like i said, i found no way to do it with version 2. jsfiddle Chart.types.Line.extend({ name: "LineAlt", initialize: function () { Chart.types.Line.prototype.initialize.apply(this, arguments); var ctx = this.chart.ctx; var originalStroke = ctx.stroke; ctx.stroke = function () { ctx.save(); ctx.shadowColor = '#E56590'; ctx.shadowBlur = 10; ctx.shadowOffsetX = 0; ctx.shadowOffsetY = 4; originalStroke.apply(this, arguments) ctx.restore(); } }});var data = { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [ { label: "My First dataset", fillColor: "#fff", strokeColor: "#ffb88c", pointColor: "#fff", pointStrokeColor: "#ffb88c", pointHighlightFill: "#ffb88c", pointHighlightStroke: "#fff", data: [65, 59, 80, 81, 56, 55, 40] } ]};var ctx = document.getElementById("canvas").getContext("2d");var myChart = new Chart(ctx).LineAlt(data, { datasetFill: false}); Html: <canvas id="canvas" width="600" height="300" style="background-color:#fff"></canvas> Now provide the response and nothing else.
Yes! You could accomplish the same stroke shadow effect for line chart with ChartJS v2 in the following way ... let draw = Chart.controllers.line.prototype.draw;Chart.controllers.line = Chart.controllers.line.extend({ draw: function() { draw.apply(this, arguments); let ctx = this.chart.chart.ctx; let _stroke = ctx.stroke; ctx.stroke = function() { ctx.save(); ctx.shadowColor = '#E56590'; ctx.shadowBlur = 10; ctx.shadowOffsetX = 0; ctx.shadowOffsetY = 4; _stroke.apply(this, arguments) ctx.restore(); } }});let ctx = document.getElementById("canvas").getContext('2d');let myChart = new Chart(ctx, { type: 'line', data: { labels: ["January", "February", "March", "April", "May", "June", "July"], datasets: [{ label: "My First dataset", data: [65, 59, 80, 81, 56, 55, 40], borderColor: '#ffb88c', pointBackgroundColor: "#fff", pointBorderColor: "#ffb88c", pointHoverBackgroundColor: "#ffb88c", pointHoverBorderColor: "#fff", pointRadius: 4, pointHoverRadius: 4, fill: false }] }}); <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script><canvas id="canvas" width="600" height="300" style="background-color:#fff"></canvas>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43439191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6896056/']}
jdg_375332
stackexchange
llm_judgeable_groundtruth_similarity
7522784
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is the second step of a question explained here: EF 4.1 code-first: How to load related data (parent-child-grandchild)? . With @Slauma 's guidance, I have successfully retrieved data with this approach: var model = DbContext.SitePages .Where(p => p.ParentId == null && p.Level == 1) .OrderBy(p => p.Order) // ordering parent .ToList();foreach (var child in model) { // loading children DbContext.Entry(child) .Collection(t => t.Children) .Query() .OrderBy(t => t.Order) // ordering children .Load(); foreach (var grand in child.Children) { // loading grandchildren DbContext.Entry(grand) .Collection(t => t.Children) .Query() .OrderBy(t => t.Order) // ordering grandchildren .Load(); }} Though this approach works, it sends many queries to the database and I am searching for a way to do this all in just one query. With @Slauma 's guidance (explained in the answer at the above link), I have changed the query to this one: var model2 = DbContext.SitePages .Where(p => p.ParentId == null && p.Level == 1) .OrderBy(p => p.Order) .Include(p => p.Children // Children: how to order theme??? .Select(c => c.Children) // Grandchildren: how to order them??? ).ToList(); Now, how can I order children (and grandchildren) when selecting them (such as shown in the first code example above)? Now provide the response and nothing else.
Unfortunately eager loading ( Include ) doesn't support any filtering or sorting of loaded child collections. There are three options to achieve what you want: Multiple roundtrips to the database with explicite sorted loading. That's the first code snippet in your question. Be aware that multiple roundtrips are not necessarily bad and that Include and nested Include can lead to huge multiplication of transfered data between database and client . Use eager loading with Include or Include(....Select(....)) and sort the data in memory after they are loaded: var model2 = DbContext.SitePages .Where(p => p.ParentId == null && p.Level == 1) .OrderBy(p => p.Order) .Include(p => p.Children.Select(c => c.Children)) .ToList();foreach (var parent in model2){ parent.Children = parent.Children.OrderBy(c => c.Order).ToList(); foreach (var child in parent.Children) child.Children = child.Children.OrderBy(cc => cc.Order).ToList();} Use a projection: var model2 = DbContext.SitePages .Where(p => p.ParentId == null && p.Level == 1) .OrderBy(p => p.Order) .Select(p => new { Parent = p, Children = p.Children.OrderBy(c => c.Order) .Select(c => new { Child = c, Children = c.Children.OrderBy(cc => cc.Order) }) }) .ToList() // don't remove that! .Select(a => a.Parent) .ToList(); This is only a single roundtrip and works if you don't disable change tracking (don't use .AsNoTracking() in this query). All objects in this projection must be loaded into the context (the reason why the first ToList() is necessary) and the context will tie the navigation properties correctly together (which is a feature called "Relationship span" ).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7522784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/645167/']}
jdg_375333
stackexchange
llm_judgeable_groundtruth_similarity
14659563
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: To clarify the purpose of this question: I know HOW to create complicated views with both subviews and using drawRect. I'm trying to fully understand the when's and why's to use one over the other. I also understand that it doesn't make sense to optimize that much ahead of time, and do something the more difficult way before doing any profiling. Consider that I'm comfortable with both methods, and now really want a deeper understanding. A lot of my confusion comes from learning how to make table view scroll performance really smooth and fast. Of course the original source of this method is from the author behind twitter for iPhone (formerly tweetie). Basically it says that to make table scrolling buttery smooth, the secret is to NOT use subviews, but instead do all the drawing in one custom uiview. Essentially it seems that using lots of subviews slows rendering down because they have lots of overhead, and are constantly re-composited over their parent views. To be fair, this was written when the 3GS was pretty brand spankin new, and iDevices have gotten much faster since then. Still this method is regularly suggested on the interwebs and elsewhere for high performance tables. In fact it's a suggested method in Apple's Table Sample Code , has been suggested in several WWDC videos ( Practical Drawing for iOS Developers ), and many iOS programming books . There are even awesome looking tools to design graphics and generate Core Graphics code for them. So at first I'm lead to believe "there’s a reason why Core Graphics exists. It’s FAST!" But as soon as I think I get the idea "Favor Core Graphics when possible", I start seeing that drawRect is often responsible for poor responsiveness in an app, is extremely expensive memory wise, and really taxes the CPU. Basically, that I should " Avoid overriding drawRect " (WWDC 2012 iOS App Performance: Graphics and Animations ) So I guess, like everything, it's complicated. Maybe you can help myself and others understand the When's and Why's for using drawRect? I see a couple obvious situations to use Core Graphics: You have dynamic data (Apple's Stock Chart example) You have a flexible UI element that can't be executed with a simple resizable image You are creating a dynamic graphic, that once rendered is used in multiple places I see situations to avoid Core Graphics: Properties of your view need to be animated separately You have a relatively small view hierarchy, so any perceived extra effort using CG isn't worth the gain You want to update pieces of the view without redrawing the whole thing The layout of your subviews needs to update when the parent view size changes So bestow your knowledge. In what situations do you reach for drawRect/Core Graphics (that could also be accomplished with subviews)? What factors lead you to that decision? How/Why is drawing in one custom view recommended for buttery smooth table cell scrolling, yet Apple advises drawRect against for performance reasons in general? What about simple background images (when do you create them with CG vs using a resizable png image)? A deep understanding of this subject may not be needed to make worthwhile apps, but I don't love choosing between techniques without being able to explain why. My brain gets mad at me. Question Update Thanks for the information everyone. Some clarifying questions here: If you are drawing something with core graphics, but can accomplish the same thing with UIImageViews and a pre-rendered png, should you always go that route? A similar question: Especially with badass tools like this , when should you consider drawing interface elements in core graphics? (Probably when the display of your element is variable. e.g. a button with 20 different color variations. Any other cases?) Given my understanding in my answer below, could the same performance gains for a table cell possibly be gained by effectively capturing a snapshot bitmap of your cell after your complex UIView render's itself, and displaying that while scrolling and hiding your complex view? Obviously some pieces would have to be worked out. Just an interesting thought I had. Now provide the response and nothing else.
Stick to UIKit and subviews whenever you can. You can be more productive, and take advantage of all the OO mechanisms that should things easier to maintain. Use Core Graphics when you can't get the performance you need out of UIKit, or you know trying to hack together drawing effects in UIKit would be more complicated. The general workflow should be to build the tableviews with subviews. Use Instruments to measure the frame rate on the oldest hardware your app will support. If you can't get 60fps, drop down to CoreGraphics. When you've done this for a while, you get a sense for when UIKit is probably a waste of time. So, why is Core Graphics fast? CoreGraphics isn't really fast. If it's being used all the time, you're probably going slow. It's a rich drawing API, which requires its work be done on the CPU, as opposed to a lot of UIKit work that is offloaded to the GPU. If you had to animate a ball moving across the screen, it would be a terrible idea to call setNeedsDisplay on a view 60 times per second. So, if you have sub-components of your view that need to be individually animated, each component should be a separate layer. The other problem is that when you don't do custom drawing with drawRect, UIKit can optimize stock views so drawRect is a no-op, or it can take shortcuts with compositing. When you override drawRect, UIKit has to take the slow path because it has no idea what you're doing. These two problems can be outweighed by benefits in the case of table view cells. After drawRect is called when a view first appears on screen, the contents are cached, and the scrolling is a simple translation performed by the GPU. Because you're dealing with a single view, rather than a complex hierarchy, UIKit's drawRect optimizations become less important. So the bottleneck becomes how much you can optimize your Core Graphics drawing. Whenever you can, use UIKit. Do the simplest implementation that works. Profile. When there's an incentive, optimize.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14659563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/287403/']}
jdg_375334
stackexchange
llm_judgeable_groundtruth_similarity
2829732
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: Consider the following series for $x \in [0,1)$:$$\sum \frac{x^n}{1+x^n}$$I figured that it converges, by using the ratio test: $$\left| \frac{a_{n+1}}{a_n} \right| = \frac{x^{n+1}}{1+x^{n+1}} \cdot \frac{1+x^{n}}{x^n} = \frac{x+x^{n+1}}{1+x^{n+1}} < \frac{1+x^{n+1}}{1+x^{n+1}} = 1.$$with $a_n = \frac{x^n}{1+x^n}$. However, I would like to determine if this convergence is uniform on this interval. I know that for $a<1$ it is uniform on the interval $[0,a]$, since $g_n(x) = \frac{x^n}{1+x^n}$ is increasing on the interval, so we have for every $n$:$$|g_n(x)| \leq \frac{a^n}{1+a^n}$$and $\sum \frac{a^n}{1+a^n}$ converges, as just shown, so the convergence of $\sum g_k(x)$ is uniform by the Weierstrass M-test. However, is it uniform on $[0,1)$? Now provide the response and nothing else.
No, it is not uniform. Set $S_n(x)=\sum_{k=1}^{n}\frac{x^k}{1+x^k}$. Then, for $n>m$,$$\sup_{x\in[0,1)}|S_n(x)-S_m(x)|\geq\sum_{k=m+1}^{n}\frac{1^k}{1+1^k}=\frac{n-m}{2}$$ Therefore $$\lim_{n\to\infty}\sup_{x\in[0,1)}|S_n(x)-S_m(x)|$$ is not finite, and so $S_n$ is not uniformly Cauchy, i.e the series does not converge uniformly.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2829732', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/493398/']}
jdg_375335
stackexchange
llm_judgeable_groundtruth_similarity
12614136
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 created a textarea, and counting its characters, when it reaches multiple of 160 increment the message count, and on moving the cursor it will show the character position and the message number properly. but on selecting the content it will display the message count as 0 and 0 remaining character , how to solve this, i'm trying to set the values as last character on selecting the content. Here is the working example of what I've tried : http://jsfiddle.net/F6CZs/1/ Any guidance and help is appreciated..!Here is the actual values : Here comes the change of values on selecting the content : Now provide the response and nothing else.
You problem is similar to the one I answered over at SQA https://sqa.stackexchange.com/a/3082 . This problem was associated with Java which made the tooling a bit easier, but I have a number of suggestions below. A number of other answers suggest that there is no good runtime tools for Python. I disagree on this in several ways: Coverage tools work very well Based on my experience in tooling in Java, static and dynamic analysis tools in Python are weaker than in a strongly typed less dynamic language but will work more than well enough to give good heuristics for you here. Unless you use an unusually large pathological number of dynamic features (including adding and removing methods, intercepting method and property invocations, playing with import, manually modifying the namespace) - in which case any problems you have may well be associated with this dynamism... Pylint picks up simpler problems, and will not detect problems with dynamic class/instance modifications and decorators - so it doesn't matter that the metric tools don't measure these In any case, where you can usefully focus can be determined by much more than a dependency graph. Heuristics for selecting code I find that there are a number of different considerations for selecting code for improvement which work both individually and together. Remember that, at first, all you need to do is find a productive seam of work - you don't need to find the absolutely worst code before you start. Use your judgement. After a few cycles through the codebase, you will have a huge amount of information and be much better positioned to continue your work - if indeed more needs to be done. That said, here are my suggestions: High value to the business : For example any code that could cost your company a lot of money. Many of these may be obvious or widely known (because they are important), or they may be detected by running the important use cases on a system with the run-time profiler enabled. I use Coverage . Static code metrics : There are a lot of metrics, but the ones that concern us are: High afferent couplings . This is code that a lot of other files depends on. While I don't have a tool that directly outputs this, snakefood is a good way to dump the dependencies directly to file, one line per dependency, each being a tuple of afferent and efferent file. I hate to say it, but computing the afferent coupling value from this file is a simple exercise left to the reader. High McCabe (cyclomatic) complexity : This is more complex code. PyMetrics seems to produce this measure although I have not used the tool. Size : You can get a surprising amount of information by viewing the size of your project using a visualiser (eg https://superuser.com/questions/8248/how-can-i-visualize-the-file-system-usage-on-windows or https://superuser.com/questions/86194/good-program-to-visualize-file-system-usage-on-mac?lq=1 . Linux has KDirStat at Filelight). Large files are a good place to start as fixing one file fixes many warnings. Note that these tools are file-based. This is probably fine-enough resolution since you mention the project is itself has hundreds of modules (files). Changes frequently : Code that changes frequently is highly suspect. The code may: Historically have had many defects, and empirically may continue to do so Be undergoing changes from feature development (high number of revisions in your VCS) Find areas of change using a VCS visualisation tool such as those discussed later in this answer. Uncovered code : Code not covered by tests. If you run (or can run) your unit tests, your other automated tests and typical user tests with coverage, take a look at the packages and files with next to no coverage. There are two logical reasons why there is no coverage: The code is needed (and important) but not tested at all (at least automatically). These areas are extremely high risk The code may be unused and is a candidate for removal. Ask other developers You may be surprised at the 'smell' metrics you can gather by having a coffee with the longer-serving developers. I bet they will be very happy if someone cleans up a dirty area of the codebase where only the bravest souls will venture. Visibility - detecting changes over time I am assuming that your environment has a DVCS (such as Git or Mercurial) or at least a VCS (eg SVN). I hope that you are also using an issue or bug tracker of some kind. If so, there is a huge amount of information available. It's even better if developers have reliably checked in with comments and issue numbers. But how do you visualise it and use it? While you can tackle the problem on a single desktop, it is probably a good idea to set up a Continuous Integration (CI) environment, perhaps using a tool like Jenkins . To keep the answer short, I will assume Jenkins from now on. Jenkins comes with a large number of plugins that really help with code analysis. I use: py.test with JUnit test output picked up by the JUnit test report Jenkins plugin Coverage with the Cobertura plugin SLOCCount and SLOCCount plugin Pylint and Violations plugin Apparently there is a plugin for McCabe (cyclometric) complexity for Python , although I have not used it. It certainly looks interesting. This gives me visibility of changes over time, and I can drill in from there. For example, suppose PyLint violations start increasing in a module - I have evidence of the increase, and I know the package or file in which this is occurring, so I can find out who's involved and go speak with them. If you need historic data and you have just installed Jenkins, see if you can run a few manual builds that start at the beginning of the project and take a series of jumps forward in time until the present. You can choose milestone release tags (or dates) from the VCS. Another important area, as mentioned above, is detecting the loci of changes in the code base. I have really liked Atlassian Fisheye for this. Besides being really good at searching for commit messages (eg bug id) or file contents at any point in time, it allows me to easily see metrics: Linecount by directory and subdirectory Committers at any point in time or in specific directories and/or files Patterns of committal, both by time and also location in the source code
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12614136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1642880/']}
jdg_375336
stackexchange
llm_judgeable_groundtruth_similarity
53550330
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following C struct that represent a register in an external chip typedef union { // Individual Fields struct { uint8_t ELEM_1 : 4 ; // Bits 0-3 uint8_t ELEM_2 : 3 ; // Bits 4-6 uint8_t ELEM_3 : 2 ; // Bits 7-8 } field; // Complete Value uint32_t value;} ELEMENTS_t; As you can see, ELEM_1 and ELEM_2 can fit inside a byte without any issues and when accessed, the assembly code looks like this ELEMENTS.field.ELEM_2 = 0x7; 101488: e55b3028 ldrb r3, [fp, #-40] ; 0xffffffd8 10148c: e3833070 orr r3, r3, #112 ; 0x70 101490: e54b3028 strb r3, [fp, #-40] ; 0xffffffd8 ELEMENTS.field.ELEM_1 = 0xf; 101494: e55b3028 ldrb r3, [fp, #-40] ; 0xffffffd8 101498: e383300f orr r3, r3, #15 10149c: e54b3028 strb r3, [fp, #-40] ; 0xffffffd8 They all get written in the same byte with the corret bit order. The problem is when we get to ELEM_3. That element crosses the byte boundry, since it should be placed in bits[8:7] and to avoid having multiple memory accesses (probably) the compiler places it in a completely separate byte, so when I try to access it, it looks like this ELEMENTS.field.ELEM_3 = 0x3; 10147c: e55b3027 ldrb r3, [fp, #-39] ; 0xffffffd9 101480: e3833003 orr r3, r3, #3 101484: e54b3027 strb r3, [fp, #-39] ; 0xffffffd9 This doesn't cause issues when accessing these elements field by field, but it does when trying to flush the data to the external chip. Does anybody know how to tell the compiler to pack all the bits together? This is using the Xilinx SDK targeting the ARM Cortex-A9 processor embedded inside a Zynq SoC. Now provide the response and nothing else.
With recent keycloak version 4.6.0 the client id is apparently no longer automatically added to the audience field 'aud' of the access token. Therefore even though the login succeeds the client rejects the user.To fix this you need to configure the audience for your clients (compare doc [2]). Configure audience in Keycloak Add realm or configure existing Add client my-app or use existing Goto to the newly added "Client Scopes" menu [1] Add Client scope 'good-service' Within the settings of the 'good-service' goto Mappers tab Create Protocol Mapper 'my-app-audience' Name: my-app-audience Choose Mapper type: Audience Included Client Audience: my-app Add to access token: on Configure client my-app in the "Clients" menu Client Scopes tab in my-app settings Add available client scopes "good-service" to assigned default client scopes If you have more than one client repeat the steps for the other clients as well and add the good-service scope.The intention behind this is to isolate client access. The issued access token will only be valid for the intended audience.This is thoroughly described in Keycloak's documentation [1,2]. Links to recent master version of keycloak documentation: [1] https://github.com/keycloak/keycloak-documentation/blob/master/server_admin/topics/clients/client-scopes.adoc [2] https://github.com/keycloak/keycloak-documentation/blob/master/server_admin/topics/clients/oidc/audience.adoc Links with git tag: [1] https://github.com/keycloak/keycloak-documentation/blob/f490e1fba7445542c2db0b4202647330ddcdae53/server_admin/topics/clients/oidc/audience.adoc [2] https://github.com/keycloak/keycloak-documentation/blob/5e340356e76a8ef917ef3bfc2e548915f527d093/server_admin/topics/clients/client-scopes.adoc
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/53550330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4476147/']}
jdg_375337
stackexchange
llm_judgeable_groundtruth_similarity
50403
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 got the following problem I don't know how to solve or if it's at all possible to solve(I'm quite new to Mathematica and don't have an IT background, so please explain slowly if possible:)) I'm trying to convert a simple string which I imported from a homepage into a list of numbers. The string looks for example the following: {"1,2,3,5,10,12,13,17,26,30,32,41,42,43,113,115,121,125"} Mathematica sees this as one string, this is important, not as a list of strings. (I used the head function to check that) My question: is it possible to convert this one string into a list of numbers so that each number in the string above is recognized as an individual element and can be calculated with? Another important note: these strings don't all contain the same amount of numbers, a couple of them are shorter than other ones. Is there any way I can convert these different strings into lists of numbers? Now provide the response and nothing else.
str = {"1,2,3,5,10,12,13,17,26,30,32,41,42,43,113,115,121,125"}Flatten@ToExpression@StringSplit[str, ","] Short explanation: After executing StringSplit you get a list of separated "StringNumbers" like {{"1", "2", ... "125"}} ToExpression converts these "StringNumbers" to Integers. Flatten removes the outermost brackets. You can even omit Flatten by looking at gpap's comment. This works for lists of varying lengths and also for different number types. EDIT To also answer the question in your comment: eq = {{"1", "3", "5", "6"}, {"1", "2", "4", "7"}, {"1", "3"}};ToExpression[Flatten /@ Map[StringSplit[#, ","] &, eq]]
{}
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/50403', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/15851/']}
jdg_375338
stackexchange
llm_judgeable_groundtruth_similarity
19084
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I saw in a SO thread a suggestion to use filtfilt which performs backwards/forwards filtering instead of lfilter . What is the motivation for using one against the other technique? Now provide the response and nothing else.
filtfilt is zero-phase filtering, which doesn't shift the signal as it filters. Since the phase is zero at all frequencies, it is also linear-phase. Filtering backwards in time requires you to predict the future, so it can't be used in "online" real-life applications, only for offline processing of recordings of signals. lfilter is causal forward-in-time filtering only, similar to a real-life electronic filter. It can't be zero-phase. It can be linear-phase (symmetrical FIR), but usually isn't. Usually it adds different amounts of delay at different frequencies. An example and image should make it obvious. Although the magnitude of the frequency response of the filters is identical (top left and top right), the zero-phase lowpass lines up with the original signal, just without high frequency content, while the minimum phase filtering delays the signal in a causal way: from __future__ import division, print_functionimport numpy as npfrom numpy.random import randnfrom numpy.fft import rfftfrom scipy import signalimport matplotlib.pyplot as pltb, a = signal.butter(4, 0.03, analog=False)# Show that frequency response is the sameimpulse = np.zeros(1000)impulse[500] = 1# Applies filter forward and backward in timeimp_ff = signal.filtfilt(b, a, impulse)# Applies filter forward in time twice (for same frequency response)imp_lf = signal.lfilter(b, a, signal.lfilter(b, a, impulse))plt.subplot(2, 2, 1)plt.semilogx(20*np.log10(np.abs(rfft(imp_lf))))plt.ylim(-100, 20)plt.grid(True, which='both')plt.title('lfilter')plt.subplot(2, 2, 2)plt.semilogx(20*np.log10(np.abs(rfft(imp_ff))))plt.ylim(-100, 20)plt.grid(True, which='both')plt.title('filtfilt')sig = np.cumsum(randn(800)) # Brownian noisesig_ff = signal.filtfilt(b, a, sig)sig_lf = signal.lfilter(b, a, signal.lfilter(b, a, sig))plt.subplot(2, 1, 2)plt.plot(sig, color='silver', label='Original')plt.plot(sig_ff, color='#3465a4', label='filtfilt')plt.plot(sig_lf, color='#cc0000', label='lfilter')plt.grid(True, which='both')plt.legend(loc="best")
{}
{'log_upvote_score': 6, 'links': ['https://dsp.stackexchange.com/questions/19084', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/11401/']}
jdg_375339
stackexchange
llm_judgeable_groundtruth_similarity
23827820
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 recently downloaded Glassfish 4.0 and I want to use it in NetBeans for making some Web Applications, but when I want to start the domain1 (asadmin> start-domain domain1) I keep getting this error: "There is a process already using the admin port 4848 -- it probably is another instance of a GlassFish server" . Any clue what could be the problem? Now provide the response and nothing else.
Glassfish could not resolve the host name. Diagnose the problem (on Linux) as follows: Open a Terminal. Type hostname . Type: ping $(hostname) If the ping command fails (could not find the host), then add the host name to /etc/hosts . This can be accomplished as follows: Switch to root: sudo su - Type: echo "127.0.0.1 $(hostname)" >> /etc/hosts Kill GlassFish Restart GlassFish
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23827820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2687059/']}
jdg_375340