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
52528845
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to add the helper _form of my Comment model inside Advertisement view. I call the helper <%= render 'comments/form', comment: @comment %> in the route /advertisement/:id So here is my comments _form : <%= form_with(model: comment, local: true, url: "/comments") do |form| %> <% if comment && comment.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(comment.errors.count, "error") %> prohibited this comment from being saved:</h2> <ul> <% comment.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="form-group"> <%= form.label :content %> <%= form.text_area :content, class:"form-field" %> </div> <%= form.hidden_field :advertisment_id, value:params[:id] %> <div class="actions"> <%= form.submit "Envoyer", class:"btn btn-primary", url: 'comments' %> </div><% end %> I specify the url: "/comments" because I'm at /advertisment/:id and by default the action is aimed to here. But when the post reached my comment controller, it can't read the params. ActionController::ParameterMissing in CommentsController#create The strange part is that I've access to the params : {"utf8"=>"✓", "authenticity_token"=>"0+swOqHPEHN2Gwh0TO3iC7VPRz4ROLoBlkaMkOdnjjYxWHoDer7AwrgnQpu+9VHfSY90yMSRsNp8ojvPJxuzmQ==", "content"=>"Test", "advertisment_id"=>"1", "commit"=>"Envoyer"} So here is the comment controller : class CommentsController < ApplicationController before_action :set_comment, only: [:show, :edit, :update, :destroy] # [...] # POST /comments # POST /comments.json def create @comment = Comment.new(comment_params.merge(:user_id => @session_user.id)) respond_to do |format| if @comment.save format.html { redirect_to @comment, notice: 'Comment was successfully created.' } format.json { render :show, status: :created, location: @comment } else format.html { render :new } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end # [...] private # Use callbacks to share common setup or constraints between actions. def set_comment @comment = Comment.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def comment_params params.require(:comment).permit(:content, :advertisment_id) endend Thanks a lot for your help Now provide the response and nothing else.
Dart objects must be fully initialized before anyone gets a reference to the new object. Since the body of a constructor can access this , the object needs to be initialized before entering the constructor body. To do that, generative Dart constructors have an initializer list, looking similiar to C++, where you can initialize fields, including final fields, but you cannot access the object itself yet. The syntax: Movie.fromJson(Map json) : title = json["title"], posterPath = json["poster_path"], overview = json['overview']; uses an initializer list (the list of assignments after the : ) to initialize the final instance variables title , posterPath and overview . The first constructor uses an "initializing formal" this.title to directly put the parameter into the field. The constructor Movie(this.title, this.posterPath, this.overview); is effectively a shorthand for: Movie(String title, String posterPath, String overview) : this.title = title, this.posterPath = posterPath, this.overview = overview; Your constructor can combine all of these and a body: Movie(this.title, this.posterPath, String overview) : this.overview = overview ?? "Default Overview!" { if (title == null) throw ArgumentError.notNull("title");} (A const constructor cannot have a body, but it can have an initializer list with some restrictions on the allowed expressions to ensure that they can be evaluated at compile-time).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52528845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10421822/']}
jdg_72341
stackexchange
llm_judgeable_groundtruth_similarity
5295616
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 ; class object { // any private datas token in heap area public : ~object () ; }; in function ; vector < object*> tmp ; my question is ; How can I erase/deallocate tmp[i] ? In other words, what things should I write in object::destructor ? Now provide the response and nothing else.
You seem to be a bit confused. There are two concepts at play here: How do I, the owner of tmp , deallocate the objects referred to by the pointers within tmp ? What should the destructor for the object class ( ~object ) do? These are not really that related. When you are finished with the tmp vector, you must manually go through and call delete on each of its elements in order to deallocate the memory occupied by the object object that the element points to. This is assuming the elements were allocated with new , of course. The purpose of the object destructor ~object is to deallocate everything that the object object owns, not to deallocate the object object itself. If the object object does not own any dynamically allocated data, it does not need to do anything. In other words, when you write delete tmp[i] , two things happen: *(tmp[i])::~object() is called The memory pointed to by tmp[i] is deallocated Note that (2) happens even if (1) does absolutely nothing. The point of step (1) is to allow the object that is about to be deallocated to deallocate any of its member objects that need to be deallocated. The destructor's job is emphatically not to deallocate the object that it was invoked on. By way of explicit example: class object { private: int foo; public: object() : foo(42) {} ~object() { /* nothing to do here; foo is not dynamically allocated */ }};int main() { vector<object*> tmp; tmp.push_back(new object()); // Do some stuff with tmp for (int i = 0; i < tmp.size(); ++i) { delete tmp[i]; // Calls ~object and deallocates *tmp[i] } tmp.clear(); return 0;} Or, by contrast class object { private: int* foo; public: object() : foo(new int()) { *foo = 42; } ~object() { // Now since foo is dynamically allocated, the destructor // needs to deallocate it delete foo; }};int main() { vector<object*> tmp; tmp.push_back(new object()); // Do some stuff with tmp for (int i = 0; i < tmp.size(); ++i) { delete tmp[i]; // Calls ~object (which deallocates tmp[i]->foo) // and deallocates *tmp[i] } tmp.clear(); return 0;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5295616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_72342
stackexchange
llm_judgeable_groundtruth_similarity
10537184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wrote some service which uses BroadcastReceiver to capture one of media buttons ("play button" from a headset), and it works perfectly on android 2.3.x (HTC Nexus One or HTC Desire) When I tried to run in on Android 4.0.3 (Samsung Nexus S) it doesn't work (my application doesn't receive intent "android.intent.action.MEDIA_BUTTON" and "play" button behaves as usual: stops/starts music). Content of manifest: ...<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <receiver android:name=".buttonreceiver.MediaButtonIntentReceiver" > <intent-filter android:priority="10000" > <action android:name="android.intent.action.MEDIA_BUTTON" /> </intent-filter> </receiver>... Is there way to make it work on android 4.0.3 edit: I've try proposed solution, I've added action and run it, but my receiver still doesn't receive intent. What is more strange registering receiver by code also doesn't work: @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about_and_activation_view); Log.d("MR", "onCreate - " + getIntent().getAction()); mReceiver = new MediaButtonIntentReceiver(); registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_MEDIA_BUTTON));} Now I'm totally confused. Now provide the response and nothing else.
Make sure that you have an activity in your app, and that the user runs this activity before attempting to press that button. Until then, your <receiver> will not receive any broadcasts . UPDATE On Android 4.0 and higher, it appears that you also need to call registerMediaButtonEventReceiver() on AudioManager in order to receive the events. That state will hold until something else calls registerMediaButtonEventReceiver() or until you call unregisterMediaButtonEventReceiver() . For example, an activity like this: public class MediaButtonActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((AudioManager)getSystemService(AUDIO_SERVICE)).registerMediaButtonEventReceiver(new ComponentName( this, MediaButtonReceiver.class)); }} will enable a manifest-registered MediaButtonReceiver to get ACTION_MEDIA_BUTTON events.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10537184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1387438/']}
jdg_72343
stackexchange
llm_judgeable_groundtruth_similarity
1598632
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 large system, for which I have to use WCF to access a web service. My test code works fine, now I need to integrate my WCF client code into the larger system. I cannot add to the existing 'app.config' file, and would like specify a separate .config file for use by my client code. How best can I accomplish this? Thanks! Now provide the response and nothing else.
There are 2 options. Option 1. Working with channels. If you are working with channels directly, .NET 4.0 and .NET 4.5 has the ConfigurationChannelFactory . The example on MSDN looks like this: ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();fileMap.ExeConfigFilename = "Test.config";Configuration newConfiguration = ConfigurationManager.OpenMappedExeConfiguration( fileMap, ConfigurationUserLevel.None);ConfigurationChannelFactory<ICalculatorChannel> factory1 = new ConfigurationChannelFactory<ICalculatorChannel>( "endpoint1", newConfiguration, new EndpointAddress("http://localhost:8000/servicemodelsamples/service"));ICalculatorChannel client1 = factory1.CreateChannel(); As pointed out by Langdon, you can use the endpoint address from the configuration file by simply passing in null, like this: var factory1 = new ConfigurationChannelFactory<ICalculatorChannel>( "endpoint1", newConfiguration, null);ICalculatorChannel client1 = factory1.CreateChannel(); This is discussed in the MSDN documentation . Option 2. Working with proxies. If you're working with code-generated proxies, you can read the config file and load a ServiceModelSectionGroup . There is a bit more work involved than simply using the ConfigurationChannelFactory but at least you can continue using the generated proxy (that under the hood uses a ChannelFactory and manages the IChannelFactory for you. Pablo Cibraro shows a nice example of this here: Getting WCF Bindings and Behaviors from any config source
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1598632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118962/']}
jdg_72344
stackexchange
llm_judgeable_groundtruth_similarity
69412
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In ZFC, every construction of a Lebesgue or Borel non-measurable set uses the axiom of choice. None of them that I've seen use choice to define a unique set, even though it's entirely possible to do so (e.g. under the AoC, if $\kappa = |A|$ is the cardinality of set $A$, then $\kappa$ is unique). So I've been wondering lately whether the strength of the AoC is enough by itself to construct a non-measurable set. Here's an attempt at a specific question. In the language of set theory (first-order logic with equality extended with the ZFC axioms), is there a formula without parameters that identifies a unique, Lebesgue/Borel non-measurable set? Now provide the response and nothing else.
The answer below has been edited in light of other answers and comments. There are all sorts of models of $ZFC$ in which every set is definable without parameters, including nonmeasurable sets; indeed a recent paper of Hamkins, Linetsky, and Reitz is devoted to such "pointwise definable" models. Also, as pointed out in Theo Buehler's comment to the question, there certainly exist definable subsets of reals that are $ZFC$ -provably not Borel . However, the situation is completely different for measurability. The classical work of Solovay [using an inacessible] shows that there is a model of $ZFC$ in which every subset of reals in $OD(\Bbb{R})$ is Lebesgue measurable. Recall that $X$ is in $OD(\Bbb{R})$ if $X$ is definable with parameters from $Ord \cup \Bbb{R}$ . As pointed out in Demer's answer, Krivine [without an inaccessible] provided a model of $ZFC$ in which every ordinal definable subset of reals is measurable. Moreover, as shown by Harvey Friedman, here , there is a model of $ZFC$ [which is a generic extension of Solovay's model] in which the following property holds: (*) Every equivalence class of sets of reals modulo null sets that is in $OD(\Bbb{R})$ consists of Lebesgue measurable sets. Note that (*) implies that no non-measurable subset of reals in definable, since if $X$ is any definable subset of reals that is not measurable, then the equivalence class $\[X\]$ of $X$ modulo null sets satisfies the following two properties: (1) $\[X\]$ definable, (2) No member of $\[X\]$ is measurable. So, to sum-up, the answer to the question for Lebesgue measurability is negative, i.e., there is no formula $\phi(x)$ in the language of set theory for which $ZFC$ proves "there is a unique nonmeasurable subset of reals satisfying $\phi$ ". However, if $ZFC$ is strengthened to $ZFC+V=L$ then such a formula does exist, as pointed out in Goldstern's answer.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/69412', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10828/']}
jdg_72345
stackexchange
llm_judgeable_groundtruth_similarity
6618013
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using django staticfiles + django-storages and Amazon S3 to host my data. All is working well except that every time I run manage.py collectstatic the command uploads all files to the server. It looks like the management command compares timestamps from Storage.modified_time() which isn't implemented in the S3 storage from django-storages. How do you guys determine if an S3 file has been modified? I could store file paths and last modified data in my database. Or is there an easy way to pull the last modified data from Amazon? Another option: it looks like I can assign arbitrary metadata with python-boto where I could put the local modified date when I upload the first time. Anyways, it seems like a common problem so I'd like to ask what solution others have used. Thanks! Now provide the response and nothing else.
The latest version of django-storages (1.1.3) handles file modification detection through S3 Boto. pip install django-storages and you're good now :) Gotta love open source! Update: set the AWS_PRELOAD_METADATA option to True in your settings file to have very fast syncs if using the S3Boto class. If using his S3, use his PreloadedS3 class. Update 2: It's still extremely slow to run the command. Update 3: I forked the django-storages repository to fix the issue and added a pull request. The problem is in the modified_time method where the fallback value is being called even if it's not being used. I moved the fallback to an if block to be executed only if get returns None entry = self.entries.get(name, self.bucket.get_key(self._encode_name(name))) Should be entry = self.entries.get(name) if entry is None: entry = self.bucket.get_key(self._encode_name(name)) Now the difference in performance is from <.5s for 1000 requests from 100s Update 4: For synching 10k+ files, I believe boto has to make multiple requests since S3 paginates results causing a 5-10 second synch time. This will only get worse as we get more files. I'm thinking a solution is to have a custom management command or django-storages update where a file is stored on S3 which has the metadata of all other files, which is updated any time a file is updated via the collectstatic command. It won't detect files uploaded via other means but won't matter if the sole entry point is the management command.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6618013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/267887/']}
jdg_72346
stackexchange
llm_judgeable_groundtruth_similarity
53373072
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 manually deleted a migration file name 20171125081136-create-task.js . After deleting the migration file, I ran this command db:migrate:undo:all While running this command I'm getting an error in the terminal: ERROR: Unable to find migration: 20171125081136-create-task.js . Due to this error I'm stuck and not able to undo other migration files that exists. Now provide the response and nothing else.
In your case, you must add the deleted migration file back in because Sequelize requires it to roll back your migrations. If you don't have it, you can add a blank migration file titled 20171125081136-create-task.js . The file must have a down function that returns a successful promise. 'use strict';module.exports = { up: function(queryInterface, Sequelize) { return Promise.resolve() }, down: function(queryInterface) { return Promise.resolve() }}; Going forward, if you want to delete a migration: Undo the latest migration: node_modules/.bin/sequelize db:migrate:undo Delete the latest migration file
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53373072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5449187/']}
jdg_72347
stackexchange
llm_judgeable_groundtruth_similarity
2275
Below is a question asked on the forum bioinformatics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The problem: I have a VCF file, a reference genome, and a bunch of annotations for the reference (genes, repeat regions, etc.) as GFF or BED files. What I would like is a tool that takes all of this as input and outputs a tab- or comma-delimited table containing as much information as possible. Potential columns in the output include: Type of variant (SNV, structural, etc) Details of variant (e.g. reference base, variant base, coverage, position, etc) Annotations overlapping variant Annotations near variant (e.g. is it just upstream of a gene) If it appears in a coding region, does it change the amino acid. There are many tools that do something like this . But to the newbie (like me) it is not clear which tools are worth starting with. Since the majority of tools take a little effort to get working in the first place, my question is: What tool comes closest to doing what I have described, is known to reliable, and is likely to be maintained for the next few years. Now provide the response and nothing else.
I have used FEATnotator and I think it can provide all of the columns you would like to see. There are many output files generated, but the consolidated output has the following columns: Chromosome Position Column_3 Consensus_Allele Annotation_Signature Reference_Base Alternate_Base Transition/Transversion SNP_Type Premature_STOP_Gained STOP_Lost START_CODON STOP_CODON SPLICE_SITE InterGenic Gene_Body Intron Exon Coding UTR Transcription_Start_Site Nearest_gene Distance here is some example output records from using a VCF, reference genome and GFF annotation file (sorry about the crappy formatting...there are a lot of fields!): Chr01 28177 T G NA T G TRANSVERSION NA NO NO NO NO NO YES NO NO NO NO NO NO Eucgr.A00211.v2.0 16054Chr01 44876 C G gene:Eucgr.A00211.v2.0 mRNA:Eucgr.A00211.1.v2.0[intron] C G TRANSVERSION NA NO NO NO NO NO NO YES YES NO NO NO NO NA NAChr01 46819 A G gene:Eucgr.A00211.v2.0 mRNA:Eucgr.A00211.1.v2.0 CDS:Eucgr.A00211.1.v2.0.CDS.4[AAA - K => GAA - E (MISSENSE)] exon:Eucgr.A00211.1.v2.0.exon.4 A G TRANSITION MISSENSE NO NO NO NO NO NO YES NO YES YES NO NO NA NA
{}
{'log_upvote_score': 4, 'links': ['https://bioinformatics.stackexchange.com/questions/2275', 'https://bioinformatics.stackexchange.com', 'https://bioinformatics.stackexchange.com/users/156/']}
jdg_72348
stackexchange
llm_judgeable_groundtruth_similarity
375515
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 notice in statistics/machine learning methods, a distribution is often approximated by a Gaussian, and then that Gaussian is used for sampling. They start by computing the first two moments of the distribution, and use those to estimate $\mu$ and $\sigma^2$ . Then they can sample from that Gaussian. It seems to me the more moments I calculate, the better I ought to be able to approximate the distribution I wish to sample. What if I calculate 3 moments...how can I use those to sample from the distribution? And can this be extended to N moments? Now provide the response and nothing else.
Three moments don't determine a distributional form; if you choose a distribution-famiy with three parameters which relate to the first three population moments, you can do moment matching ("method of moments") to estimate the three parameters and then generate values from such a distribution. There are many such distributions. Sometimes even having all the moments isn't sufficient to determine a distribution. If the moment generating function exists (in a neighborhood of 0) then it uniquely identifies a distribution (you could in principle do an inverse Laplace transform to obtain it). [If some moments are not finite this would mean the mgf doesn't exist, but there are also cases where all moments are finite but the mgf still doesn't exist in a neighborhood of 0.] Given there's a choice of distributions, one might be tempted to consider a maximum entropy solution with the constraint on the first three moments, but there's no distribution on the real line that attains it (since the resulting cubic in the exponent will be unbounded). How the process would work for a specific choice of distribution We can simplify the process of obtaining a distribution matching three moments by ignoring the mean and variance and working with a scaled third moment -- the moment-skewness ( $\gamma_1=\mu_3/\mu_2^{3/2}$ ). We can do this because having selected a distribution with the relevant skewness, we can then back out the desired mean and variance by scaling and shifting. Let's consider an example. Yesterday I created a large data set (which still happens to be in my R session) whose distribution I haven't tried to calculate the functional form of (it's a large set of values of the log of the sample variance of a Cauchy at n=10). We have the first three raw moments as 1.519, 3.597 and 11.479 respectively, or correspondingly a mean of 1.518, a standard deviation* of 1.136 and a skewness of 1.429 (so these are sample values from a large sample). Formally, method of moments would attempt to match the raw moments, but the calculation is simpler if we start with the skewness (turning solving three equations in three unknowns into solving for one parameter at a time, a much simpler task). * I am going to handwave away the distinction between using an n-denominator on the variance - as would correspond to formal method of moments - and an n-1 denominator and simply use sample calculations. This skewness (~1.43) indicates we seek a distribution which is right-skew. I could choose, for example, a shifted lognormal distribution (three parameter lognormal, shape $\sigma$ , scale $\mu$ and location-shift $\gamma$ ) with the same moments. Let's begin by matching the skewness. The population skewness of a two parameter lognormal is: $\gamma_1=(e^{\sigma ^{2}}\!\!+2){\sqrt {e^{\sigma ^{2}}\!\!-1}}$ So let's start by equating that to the desired sample value to obtain an estimate of $\sigma^2$ , $\tilde{\sigma}^2$ , say. Note that $\gamma_1^2$ is $(\tau+2)^2(\tau-1)$ where $\tau=e^{\sigma^2}$ . This then yields a simple cubic equation $\tau^3+3\tau^2-4=\gamma_1^2$ . Using the sample skewness in that equation yields $\tilde{\tau}\approx 1.1995$ or $\tilde{\sigma}^2\approx 0.1819$ . (The cubic has only one real root so there's no issue with choosing between roots; nor is there any risk of choosing the wrong sign on $\gamma_1$ -- we can flip the distribution left-for-right if we need negative skewness) We can then in turn solve for $\mu$ by matching the variance (or standard deviation) and then for the location parameter by matching the mean. But we could as easily have chosen a shifted-gamma or a shifted-Weibull distribution (or a shifted-F or any number of other choices) and run through essentially the same process. Each of them would be different. [For the sample I was dealing with, a shifted gamma would probably have been a considerably better choice than a shifted lognormal, since the distribution of the logs of the values was left skew and the distribution of their cube root was very close to symmetric; these are consistent with what you will see with (unshifted) gamma densities, but a left-skewed density of the logs cannot be achieved with any shifted lognormal.] One could even take the skewness-kurtosis diagram in a Pearson plot and draw a line at the desired skewness and thereby obtain a two-point distribution, sequence of beta distributions, a gamma distribution, a sequence of beta-prime distributions, an inverse-gamma disribution and a sequence of Pearson type IV distributions all with the same skewness. We can see this illustrated in a skewness-kurtosis plot (Pearson plot) below (note that $\beta_1=\gamma_1^2$ and $\beta_2$ is the kurtosis), with the regions for the various Pearson-distributions marked in. The green horizontal line represents $\gamma_1^2 = 2.042$ , and we see it pass through each of the mentioned distribution-families, each point corresponding to a different population kurtosis. (The dashed curve represents the lognormal, which is not a Pearson-family distribution; its intersection with the green line marks the particular lognormal-shape we identified. Note that the dashed curve is purely a function of $\sigma$ .) More moments Moments don't pin distributions down very well, so even if you specify many moments, there will still be a lot of different distributions (particularly in relation to their extreme-tail behavior) that will match them. You can of course choose some distributional family with at least four parameters and attempt to match more than three moments; for example the Pearson distributions above allow us to match the first four moments, and there are other choices of distributions that would allow similar degree of flexibility. One can adopt other strategies to choose distributions that can match distributional features - mixture distributions, modelling the log-density using splines, and so forth. Frequently, however, if one goes back to the initial purpose for which one was trying to find a distribution, it often turns out there's something better that can be done than the sort of strategy outlined here.
{}
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/375515', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/225762/']}
jdg_72349
stackexchange
llm_judgeable_groundtruth_similarity
30035001
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 get all the NICs on my system and then using that information to insert registry values of *TCPChecksumOffloadIPv4 etc. However, I am failing this task miserably! I can get all the GUID's and want to match that to what is in this registry path: HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\* I get all the GUID's by this: $GuidSet = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\*" | select -ExpandProperty pschildname Output: {1FE01120-3866-437F-81FF-556B08999AA4}{2533855F-2A59-485D-87A0-167E5DA39E45}{2A6471FB-C1D6-47D2-A665-9F276D142D7C}{306D2DED-18B5-45D8-858E-BB3F49E3BD6A}{30EF50B2-E4B3-400D-9614-B590E37DE4D8}{4A208C06-0D99-4DE4-9B2F-86285AEF864E}{B7883140-E15B-4409-BA1B-96E37A45425C}{D129DDA8-C64B-46A1-B99A-EA74FC4FAF81}{D5C9183B-E542-4010-866F-4443AD55F28C} This is where I am stuck now...how can I use this information to match what is in the registry path of "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\*" ? I tried the below but I get access denied - I think this is because of the "Properties" registry key - how can I ignore that registry key? $path1 = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\*" |?{$_.NetCfgInstanceId -match $guidset} | select -ExpandProperty pspath Once that is done though then do I construct a foreach loop on each entry and then add in the registry keys I need? ANSWER: you know what...when your in a muddle and you have lots of scripts...take a break, open a new window and start from scrath! That's what I did and in 10min I figured it out...! $aGUID_SET = @(Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\*" | select -ExpandProperty pschildname)Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\*" -exclude "Properties" | Where-Object {$aGUID_SET.Contains($_.NetCfgInstanceId)} | ForEach-Object { "" $_.DriverDesc $_.NetCfgInstanceId } Now provide the response and nothing else.
1) in the .h file of your view controller make sure you assign textfield delegate: @interface YourViewController : UIViewController <UITextFieldDelegate> and also have an IBOutlet of the birthday Textfield 2) declare a date picker as a class variable to make it accessible from all different methods in class. in the .m file do the following after import and before implementation: @interface YourViewController () {UIDatePicker *datePicker;}@end 3) in viewdidload: // make the textfield its own delegateself.BirthdateTextfield.delegate = self;// alloc/init your date picker, and (optional) set its initial datedatePicker = [[UIDatePicker alloc]init];[datePicker setDate:[NSDate date]]; //this returns today's date// theMinimumDate (which signifies the oldest a person can be) and theMaximumDate (defines the youngest a person can be) are the dates you need to define according to your requirements, declare them:// the date string for the minimum age required (change according to your needs) NSString *maxDateString = @"01-Jan-1996";// the date formatter used to convert string to dateNSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// the specific format to usedateFormatter.dateFormat = @"dd-MMM-yyyy";// converting string to dateNSDate *theMaximumDate = [dateFormatter dateFromString: maxDateString];// repeat the same logic for theMinimumDate if needed// here you can assign the max and min dates to your datePicker [datePicker setMaximumDate:theMaximumDate]; //the min age restriction [datePicker setMinimumDate:theMinimumDate]; //the max age restriction (if needed, or else dont use this line)// set the mode[datePicker setDatePickerMode:UIDatePickerModeDate];// update the textfield with the date everytime it changes with selector defined below[datePicker addTarget:self action:@selector(updateTextField:) forControlEvents:UIControlEventValueChanged];// and finally set the datePicker as the input mode of your textfield[self.BirthdateTextfield setInputView:datePicker]; 4) in same .m file, define the selector that will update textfield each time the date picker changes: -(void)updateTextField:(id)sender { UIDatePicker *picker = (UIDatePicker*)self.BirthdateTextfield.inputView; self.BirthdateTextfield.text = [self formatDate:picker.date];} 5) last but not least, this is the method called before assigning the date to the textfield.text (textfield.text needs a string not a date): - (NSString *)formatDate:(NSDate *)date { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterShortStyle]; [dateFormatter setDateFormat:@"dd-MMM-yyyy"]; NSString *formattedDate = [dateFormatter stringFromDate:date]; return formattedDate;} enjoy coding!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30035001', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/461030/']}
jdg_72350
stackexchange
llm_judgeable_groundtruth_similarity
11727902
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having trouble getting the sticky footer to work. Essentially, I want it to do exactly what this demo does http://matthewjamestaylor.com/blog/bottom-footer-demo.htm I have tried about a dozen tutorials trying to get this to work, and I just can't do it. Can someone help me out? Here is my site (It's running Wordpress 3.4.1) http://hgsupport.x10.mx/support/ Thanks Now provide the response and nothing else.
You almost did it correctly. The problem with your css is that white-space: nowrap; only works for inline elements - but you are using float . Floated elements become block-level even if you set display: inline; property to such an element (it will not be applied). So - if you replace your floats with display: inline-block; - your white-space property will work :) A live example of inline-block s and white-space can be seen here: http://jsfiddle.net/skip405/wzgcH/ As for your centering method - there is a better solution. (You may remove the padding and set the proper width) Especially if you are using inline-blocks. Simply set text-align: center; on their parent - and you'll have it centered.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11727902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1563304/']}
jdg_72351
stackexchange
llm_judgeable_groundtruth_similarity
127898
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: It is standard that every Borel probability measure on a polish space $X$ can be obtained as pushforward of the uniform measure $\lambda$ on $[0,1]$ along an almost-everywhere-defined Borel-measurable function $d: [0,1] \to X$ . (In fact, $d$ can always be taken to be continuous on a measure-$1$ $G_\delta$ subset. But this is not important for what follows.) My question is whether there is a "conditional" version of this result, along the following lines. I first formulate this below as a precise question, and then discuss possible variations. I shall state the question as a property of the category whose objects are polish probability spaces (i.e., a polish space together with a Borel probability measure) and whose maps are almost-everywhere-defined measure-preserving Borel-measurable functions modulo almost-everywhere equality. Note that, in terms of this category, the fact stated at the start asserts that $[0,1]$ (with $\lambda$ as its probability measure) is a weakly initial object (i.e., there exists at least one map from $[0,1]$ to every object $X$.) Precise question. Given a map $f: X \to Y$, does there exist a map $e : Y \times [0,1] \to X$ such that $f \circ e = \pi_1$ (where $\pi_1$ is first projection)? (Here, $Y \times [0,1]$ is the topological product with product Borel measure.) Remarks and variations This is a conditional version of the initial fact in the following sense. Given such an $e$, the function mapping $y \in Y$ to the pushforward of $\lambda$ along $e(y,-): [0,1] \to X$ is a disintegration of $f$, thus giving conditional probability measures $P(-|f(x) = y)$. Category-theoretically, the question asks if every projection $\pi_1: Y \times [0,1] \to Y$ is a weakly initial object in the slice category over $Y$. For the application I have in mind, a weaker result would suffice. It is enough for there to exist $d: [0,1] \to Y$ and $e:[0,1] \times [0,1] \to X$ such that $f \circ e = d \circ \pi_1$. I am not that fussy about the precise choice of category. One might, e.g., generalise to analytic or standard probability spaces. In general, I'm interested in pointers to any result at all that is similar in nature to the one discussed. Now provide the response and nothing else.
It follows from a classification of morphisms in this category due to Rokhlin. If both the target space and all the conditional measures are purely non-atomic, then this map is (mod 0) just the coordinate projection of the unit square (endowed with the Lebesgue measure). If any of these measures has atoms, then it is essentially the same description with obvious modifications.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/127898', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13506/']}
jdg_72352
stackexchange
llm_judgeable_groundtruth_similarity
6605632
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 relation between Canvas and Bitmap? Bitmap drawingBitmap = Bitmap.createBitmap(bmp1.getWidth(),bmp1.getHeight(), bmp1.getConfig());canvas = new Canvas(drawingBitmap);paint = new Paint();canvas.drawBitmap(bmp1, 0, 0, paint);paint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.SCREEN));canvas.drawBitmap(bmp2, 0, 0, paint);compositeImageView.setImageBitmap(drawingBitmap); I don't understand this code.Why the drawingBitmap is the composition of bmp1 and bmp2? Now provide the response and nothing else.
Basically, the Canvas is backed by a Bitmap , so when you draw anything using the canvas, the canvas will draw into the Bitmap it was created with. So, when you draw those two bitmaps using the canvas, it's going to composite the bitmaps together and the result will be stored in drawingBitmap , as it's backing the canvas. Anh's analogy is correct-ish, though probably confusing (and over-simplifying, which I'm also doing above) – as I mentioned in a comment, you can think of the Canvas as the pen, the Paint as a configuration of that pen (e.g., replaceable ink or something - whatever you can fit into the idea of a configurable pen), and the Bitmap as the paper you draw onto. The analogy becomes confusing if you focus too much on the accepted meaning of the words.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6605632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/687013/']}
jdg_72353
stackexchange
llm_judgeable_groundtruth_similarity
25314
Below is a question asked on the forum math.meta.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I flagged a question as "rude" because it used the letters that spelled a choice Anglo-Saxon expletive beginning with f as the four elements of an example set. Seemed unnecessary and deliberately vulgar, so I flagged it. The status of the flag is "disputed". What does that really mean? Is the dispute among the moderators as to whether the question is rude? Or did the OP dispute the flag? Or what? Also, is my rude threshold set too low? Now provide the response and nothing else.
There are two ways a moderator can act on a "rude or abusive" flag that they disagree with: explicitly decline the flag, and clear the flag from the post. They both have the effect of removing all "rude or abusive" flags from the post, and undoing the automatic downvote associated with each. But while former obviously declines the flag, the latter only disputes it. (When a flag is declined you'll additionally get a note about this in your flagging history.) (The above also holds for "spam" flags.) In Stack Exchange nomenclature having a flag disputed flag is not as strong as having it declined . In fact there are some automatic mechanisms which dispute flags. For example, any edit to a post will dispute all "very low quality" flags on it. I do not think there are any negative effects to having flags disputed, whereas having too many declined flags may lead to a temporary flagging ban. Putting this all together, the flag was disputed because a moderator didn't think that the post warranted a "rude or abusive" flag, and decided to not outright decline it. That being said, I don't believe that the "rude or offensive" flag was warranted on the post you flagged. Sure a "bad word" could be read off of it, but the post itself could have been simply edited (or an edit suggested) to remove this possibility without damaging the post at all. In general I feel that the "rude or abusive" flags should be reserved for posts whose entire intent appears to be being rude or abusive. These flags are really intended to stop the user from posting more, and at a minimum come with pretty hefty penalties (-100 reputation if enough such flags are raised on a post). In cases where a post has perhaps objectionable content but is otherwise meaningful, the objectionable content can usually be edited out without harming the mathematical intent of the post. (If the post author and others get into an "edit war" over the objectionable content, a flag will automatically be raised to summon site moderators to the post.) In other cases a moderator-only "other" flag could be raised, or even pop in to the Math Mods' Office chat room.
{}
{'log_upvote_score': 4, 'links': ['https://math.meta.stackexchange.com/questions/25314', 'https://math.meta.stackexchange.com', 'https://math.meta.stackexchange.com/users/387114/']}
jdg_72354
stackexchange
llm_judgeable_groundtruth_similarity
24373490
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 XML: <bookstore> <books> <book name="book1" title="Title 1" author="Author 1"/> <book name="book2" title="Title 2" author="Author 2"/> <book name="book3" title="Title 1" author="Author 2"/> </books> <myBooks> <book name="Test1" title="Title 1" author="Author 1"/> <book name="Test2" title="Title 2" author="Author 1"/> <book name="Test3" title="Title 1" author="Author 2"/> </myBooks></bookstore> I want to get all name of book in myBooks that have not a corresponding book in books (title and author). So, for the example, I want to retrieve: the book "Test2" because the pair ("Title 2", "Author 1") does not exist in books . So far, I have: //myBooks/book[not(@title = //books/book/@title and @author = //books/book/@author)] But, of course, in that case, the above XPath does not work because the combination ("Title 2", "Author 1") exists (from "book2" and "book1"). How can I apply the and operator on the same node? Now provide the response and nothing else.
It depends on the version of XPath. You can't do this in a single XPath 1.0 expression because it would require a structure like /bookstore/myBooks/book[/bookstore/books/book[ @title = _outer-predicate_/@title and @author = _outer-predicate_/@author]]/@name i.e. you'd need to capture the book being tested by the outer predicate so you can compare it to the inner one. Pure XPath 1.0 doesn't support this, you'd have to iterate over the content of myBooks yourself (e.g. with an xsl:for-each , as you've tagged your question "xslt"). In XPath 2.0 you can do it in one expression with an explicit quantifier /bookstore/myBooks/book[not(some $book in /bookstore/books/book satisfies ($book/@author = @author and $book/@title = @title))]/@name
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24373490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1284526/']}
jdg_72355
stackexchange
llm_judgeable_groundtruth_similarity
32420
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There are some von-Neumann utility functions that I come across quite often in different articles / books like: $ U(x)=\ln(x)$, $U(x)= \frac {1}{\gamma}x^\gamma$ with $\gamma <1$ and $U(x)=\frac {1-\gamma}{\gamma}(\frac{\alpha x}{1-\gamma} +\beta)^{\gamma}$ subject to the restrictions $\gamma \neq 1, \frac{\alpha x}{1-\gamma} +\beta >0$, and $\beta=1$ if $\gamma=-\infty$. My question is: Why are those functions used that often? It's not like they are the only "simple" concave and increasing functions out there? So I guess there must be some specific properties that make them interesting? Now provide the response and nothing else.
These are a natural and easiest (most tractable mathematically) choice. A utility function is defined up to a positive affine transformation: economically there is no difference between the utility functions $U(x)$ and $\tilde{U}(x)=Au(x)+B$. Hence, a measure of risk aversion that remains constant w.r.t. affine transformations would be useful. How does one construct such a measure? Well, the easiest way is to consider the expression$$A(x)= -\frac{U''(x)}{U'(x)}$$a.k.a. ARA (Arrow–Pratt measure of absolute risk aversion ). ARA stays the same under affine transformations and measures the degree of risk aversion - the curvature of the utility function. The reciprocal of ARA measures the level of risk tolerance, and a simple special case is when it is a linear function of wealth:$$T(x)=\frac{1}{A(x)}=\frac{x}{1-\gamma}+\frac{b}{a}.$$Now, what are the utility functions such that the corresponding level of risk tolerance is linear? These are solutions to the ODE$$-\frac{U'(x)}{U''(x)}=\frac{x}{1-\gamma}+\frac{b}{a}$$which is known to be solvable in closed form. The unique solution (up to affine transformation!) to the equation has the form $$\qquad U(x)=\frac{1-\gamma}{\gamma}\left(\frac{ax}{1-\gamma}+b \right)^\gamma.\qquad(1)$$There are other solutions which differ from (1) by additive and/or multiplicative constants but these do not affect the behavior implied by the utility function. (1) is known as the hyperbolic absolute risk aversion. The other utility functions that you've mentioned are just specifications of (1). In particular, assuming $b=0$ one gets the isoelastic utility :$$\quad\qquad U(x) = \begin{cases}\frac{x^\gamma-1}{\gamma},\quad \gamma\neq 0 \\ \ln(x), \quad \gamma =0 \end{cases}\qquad\quad (2)$$(2) is also the only example of utility functions with the constant relative risk aversion $$R(x)=xA(x)=1-\gamma.$$
{}
{'log_upvote_score': 4, 'links': ['https://quant.stackexchange.com/questions/32420', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/26218/']}
jdg_72356
stackexchange
llm_judgeable_groundtruth_similarity
18993915
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 (on the surface of it, simple) task: Copy the values from a number of columns on a spreadsheet into a 2D array using VBA. To make life more interesting, the columns are not adjacent, but they are all of the same length. Obviously one could do this by looping over every element in turn, but that seems very inelegant. I am hoping there is a more compact solution - but I struggle to find it. Here are some attempts of what I would consider "a simple approach" - for simplicity, I am putting the range as A1:A5, D1:D5 - a total of 10 cells in two ranges. Private Sub testIt() Dim r1, r2, ra, rd, rad Dim valString, valUnion, valBlock Set r1 = Range("A1:A5") Set r2 = Range("D1:D5") valString = Range("A1:A5,D1:D5").Value valUnion = Union(r1, r2).Value valBlock = Range("A1:D5").ValueEnd Sub When I look at each of these variables, the first two have dimension (1 To 5, 1 To 1) while the last one has (1 To 5, 1 To 4) . I was expecting to get (1 To 5, 1 To 2) for the first two, but that was not the case. I would be happy if I could loop over the data one column at the time, and assign all the values in one column to one column in the array - but I could not figure out how to do that either. Something like cNames = Array("A", "D")ci = 1For Each c in columnNames vals( , ci) = Range(c & "1:" & c & "5").Value ci = ci + 1Next c But that's not the right syntax. The result I want to get would be achieved with cNames = Array("A", "D")ci = 1For Each c in columnNames For ri = 1 To 5 vals(ri , ci) = Range(c & "1").offset(ri-1,0).Value Next ri ci = ci + 1Next c But that's pretty ugly. So here is my question: Is it possible to get the values of a "composite range" (multiple non-contiguous blocks) into an array - either all at once, or a columns at a time? If so, how do I do it? For extra bonus points - can anyone explain why the arrays returned in testIt() are dimensioned Base 1 , whereas my VBA is set to Option Base 0 ? In other words - why are they not (0 To 4, 0 To 0) ? Is this just one more inconsistency on the part of Microsoft? Now provide the response and nothing else.
Provided each area in rng has the same number of rows then this should work. Function ToArray(rng) As Variant() Dim arr() As Variant, r As Long, nr As Long Dim ar As Range, c As Range, cnum As Long, rnum As Long Dim col As Range nr = rng.Areas(1).Rows.Count ReDim arr(1 To nr, 1 To rng.Cells.Count / nr) cnum = 0 For Each ar In rng.Areas For Each col In ar.Columns cnum = cnum + 1 rnum = 1 For Each c In col.Cells arr(rnum, cnum) = c.Value rnum = rnum + 1 'EDIT: added missing line... Next c Next col Next ar ToArray = arrEnd Function Usage: Dim arrarr = ToArray(Activesheet.Range("A1:A5,D1:D5"))Debug.Print UBound(arr,1), UBound(arr,2) As for why array from rng.Value are 1-based instead of zero-based, I'd guess it's because that maps more readily to actual row/column numbers on the worksheet than if it were zero-based. The Option Base x setting is ignored
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18993915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1967396/']}
jdg_72357
stackexchange
llm_judgeable_groundtruth_similarity
27784956
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 starting with MongoDB and I would like to user/pass access to the dbs.The first thing I did was to create and admin user and start mongodb with auth activate, this is my created user: db.getUser("admin") { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "roles" : [ { "role" : "dbAdminAnyDatabase", "db" : "admin" }, { "role" : "clusterAdmin", "db" : "admin" } ] }} After that, I try to create users with the following commands: use newdbdb.createUser( { user: "newuser", pwd: "12345678", roles: [ { role: "readWrite", db: "newdb" } ] }) But I got this error: Error: couldn't add user: not authorized on newdb to execute command { createUser: "newuser", pwd: "xxx", roles: [ { role: "readWrite", db: "newdb" } ], digestPassword: false, writeConcern: { w: "majority", wtimeout: 30000.0 } } at src/mongo/shell/db.js:1004 I have googled about it but there are only two results, one on Chinese and the other not related, so I'm a little lost. Any idea ? It looks like my admin user doesn't have privilege, I access to the mongodb with the following command: $mongo --port 27017 -u adminUser -p adminPass --authenticationDatabase admin Thanks in advance. Now provide the response and nothing else.
Stop the running instance of mongod mongod --config /usr/local/etc/mongod.conf --auth then start without --auth like mongod --config /usr/local/etc/mongod.conf then update your roles like db.updateUser("admin",{roles : ["userAdminAnyDatabase","userAdmin","readWrite","dbAdmin","clusterAdmin","readWriteAnyDatabase","dbAdminAnyDatabase"]}); Now again start mongod with --auth and try. The idea is you have to create user under "admin" database with all the ROLES mentioned above. But this user is not part of other databases. So once you created the admin user, then login as that admin user, SERVER: mongod --config /usr/local/etc/mongod.conf --auth CLIENT: ./mongodb/bin/mongo localhost:27017/admin -u adminUser -p 123456 use APPLICATION_DB again create a new user (say APP_USER) for this APPLICATION_DB. This time for this application user you need only "dbOwner" role. db.createUser({user:"test", pwd:"test", roles:['dbOwner']}) Now your application has to use this APP_USER and APP_DB.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27784956', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4351814/']}
jdg_72358
stackexchange
llm_judgeable_groundtruth_similarity
1287995
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 not sure when I should use ContentPresenter instead of ContentControl (and vice-versa). At the moment, I'm using ContentControl pretty much all the time in my DataTemplate s. When would ContentPresenter be a better choice? and why? Now provide the response and nothing else.
ContentControl is a base class for controls that contain other elements and have a Content -property (for example, Button ). ContentPresenter is used inside control templates to display content. ContentControl , when used directly (it's supposed to be used as a base class), has a control template that uses ContentPresenter to display it's content. My rules of thumb (not applicable in every case, use your judgment): Inside ControlTemplate use ContentPresenter Outside of ControlTemplate (including DataTemplate and outside templates) try not to use any of them, if you need to, you must prefer ContentPresenter Subclass ContentControl if you are creating a custom "lookless" control that host content and you can't get the same result by changing an existing control's template (that should be extremely rare).
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1287995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1367/']}
jdg_72359
stackexchange
llm_judgeable_groundtruth_similarity
1282232
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Recently my server CPU has been going very high. CPU load averages 13.91 (1 min) 11.72 (5 mins) 8.01 (15 mins) and my site has only had a slight increase in traffic. After running a top command, I saw MySQL was using 160% CPU! Recently I've been optimizing tables and I've switched to persistent connections. Could this be causing MySQL to use high amounts of CPU? Now provide the response and nothing else.
First I'd say you probably want to turn off persistent connections as they almost always do more harm than good. Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check. Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long. Some other things you can check would be to run the following query while the CPU load is high: SHOW PROCESSLIST; This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text). You'll also want to keep an eye on things like your buffer sizes, table cache , query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU. You'll also probably want to give the following a read over as they contain some good information. How MySQL Uses Memory MySQL System Variables It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1282232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138251/']}
jdg_72360
stackexchange
llm_judgeable_groundtruth_similarity
49274143
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following this tutorial: https://reacttraining.com/react-router/web/example/auth-workflow . Trying to reproduce the code: const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => fakeAuth.isAuthenticated ? ( <Component {...props} /> ) : ( <Redirect to={{ pathname: "/login", state: { from: props.location } }} /> ) } />); In TypeScript: import * as React from 'react';import { Route, RouterProps } from 'react-router';interface Props extends RouterProps { component: React.Component;}const PrivateRoute = ({ component: Component, ...rest }: Props) => { return ( <Route {...rest} render={(props) => <Component {...props} />} /> );};export default PrivateRoute; But it would always fail. Tried different variations. The one I've posted the most recent one. Getting: It seems to me that I have to pass Generic for the Component type, but I don't know how. EDIT: The closest solution so far: interface Props extends RouteProps { component: () => any;}const PrivateRoute = ({ component: Component, ...rest }: Props) => { return ( <Route {...rest} render={(props) => <Component {...props} />} /> );}; And then: <PrivateRoute component={Foo} path="/foo" /> Now provide the response and nothing else.
You want to pass a component constructor, not a component instance: import * as React from 'react';import { Route, RouteProps } from 'react-router';interface Props extends RouteProps { component: React.ComponentType;}const PrivateRoute = ({ component: Component, ...rest }: Props) => { return ( <Route {...rest} render={(props) => <Component {...props} />} /> );};export default PrivateRoute;class Foo extends React.Component {}let r = <PrivateRoute component={Foo} path="/foo" /> Edit A more complete solution should be generic and use RouteProps instead RouterProps : import * as React from 'react';import { Route, RouteProps } from 'react-router';type Props<P> = RouteProps & P & { component: React.ComponentType<P>;}const PrivateRoute = function <P>(p: Props<P>) { // We can't use destructuring syntax, because : "Rest types may only be created from object types", so we do it manually. let rest = omit(p, "component"); let Component = p.component; return ( <Route {...rest} render={(props: P) => <p.component {...props} />} /> );};// Helperstype Diff<T extends string, U extends string> = ({[P in T]: P } & {[P in U]: never } & { [x: string]: never })[T]; type Omit<T, K extends keyof T> = Pick<T, Diff<keyof T, K>>; function omit<T, TKey extends keyof T>(value:T, ... toRemove: TKey[]): Omit<T, TKey>{ var result = Object.assign({}, value); for(let key of toRemove){ delete result[key]; } return result;}export default PrivateRoute;class Foo extends React.Component<{ prop: number }>{}let r = <PrivateRoute component={Foo} path="/foo" prop={10} />
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49274143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/865866/']}
jdg_72361
stackexchange
llm_judgeable_groundtruth_similarity
351845
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 class A and another class that inherits from it, B. I am overriding a function that accepts an object of type A as a parameter, so I have to accept an A. However, I later call functions that only B has, so I want to return false and not proceed if the object passed is not of type B. What is the best way to find out which type the object passed to my function is? Now provide the response and nothing else.
dynamic_cast should do the trick TYPE& dynamic_cast<TYPE&> (object);TYPE* dynamic_cast<TYPE*> (object); The dynamic_cast keyword casts a datum from one pointer or reference type to another, performing a runtime check to ensure the validity of the cast. If you attempt to cast to pointer to a type that is not a type of actual object, the result of the cast will be NULL. If you attempt to cast to reference to a type that is not a type of actual object, the cast will throw a bad_cast exception. Make sure there is at least one virtual function in Base class to make dynamic_cast work. Wikipedia topic Run-time type information RTTI is available only for classes that are polymorphic, which meansthey have at least one virtual method. In practice, this is not alimitation because base classes must have a virtual destructor toallow objects of derived classes to perform proper cleanup if they aredeleted from a base pointer.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/351845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/43463/']}
jdg_72362
stackexchange
llm_judgeable_groundtruth_similarity
15893876
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to render h:inputText as following html output : <input id="yourName" type="text" name="name" /> <input id="email" type="text" name="email" /> But h:inputText renders the name attribute same as client id of the component. I want to specify the name attribute myself, instead of putting client id in that, so that the input field can show meaningful autocomplete suggestions from previously submitted values for same field type on other sites. For e.g. when I use name="email" with input field for email, user is shown suggestions of emails ids he submitted previously on other websites. Now provide the response and nothing else.
You can't achieve it using <h:inputText> . Its name is autogenerated by JSF based on the client ID (which is in turn based on component ID and all of its naming container parents). You've basically 2 options to achieve the concrete functional requirement anyway: If there are no other naming container parents, instruct the parent form to not prepend its ID: <h:form prependId="false"> This will however cause <f:ajax> to fail. Use plain HTML elements instead of JSF components: <input name="name" value="#{bean.name}" /><input name="email" value="#{bean.email}" /> You only have to collect them yourself via @ManagedProperty on a request scoped bean: @ManagedProperty("#{param.name}")private String name;@ManagedProperty("#{param.email}")private String email; And you'll miss JSF builtin validation/conversion facility and ajax magic. There's however a completely different alternative: use HTML5 <input type="email"> . This way the browser will autosuggest all previously entered emails on inputs of the very same type. This is not natively supported by <h:inputText> . You can however use a custom render kit to get it to work, as answered in Adding custom attribute (HTML5) support to Primefaces (3.4) : <h:inputText type="email" ... /> Update as of JSF 2.2 you can finally easily declare passthrough attributes without needing a custom render kit. <... xmlns:a="http://xmlns.jcp.org/jsf/passthrough">...<h:inputText a:type="email" ... />
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15893876', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530153/']}
jdg_72363
stackexchange
llm_judgeable_groundtruth_similarity
4520319
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Following up on How to make a record from a sequence of values , how can you write a defrecord constructor call and assign the fields from a Map , leaving un-named fields nil ? (defrecord MyRecord [f1 f2 f3])(assign-from-map MyRecord {:f1 "Huey" :f2 "Dewey"}) ; returns a new MyRecord I imagine a macro could be written to do this. Now provide the response and nothing else.
You can simply merge the map into a record initialised with nil s: (merge (MyRecord. nil nil nil) {:f1 "Huey" :f2 "Dewey"}) Note that records are capable of holding values stored under extra keys in a map-like fashion. The list of a record's fields can be obtained using reflection: (defn static? [field] (java.lang.reflect.Modifier/isStatic (.getModifiers field)))(defn get-record-field-names [record] (->> record .getDeclaredFields (remove static?) (map #(.getName %)) (remove #{"__meta" "__extmap"}))) The latter function returns a seq of strings: user> (get-record-field-names MyRecord)("f1" "f2" "f3") __meta and __extmap are the fields used by Clojure records to hold metadata and to support the map functionality, respectively. You could write something like (defmacro empty-record [record] (let [klass (Class/forName (name record)) field-count (count (get-record-field-names klass))] `(new ~klass ~@(repeat field-count nil)))) and use it to create empty instances of record classes like so: user> (empty-record user.MyRecord)#:user.MyRecord{:f1 nil, :f2 nil, :f3 nil} The fully qualified name is essential here. It's going to work as long as the record class has been declared by the time any empty-record forms referring to it are compiled. If empty-record was written as a function instead, one could have it expect an actual class as an argument (avoiding the "fully qualified" problem -- you could name your class in whichever way is convenient in a given context), though at the cost of doing the reflection at runtime.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4520319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/96233/']}
jdg_72364
stackexchange
llm_judgeable_groundtruth_similarity
4596233
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 Rails app and I want to add a blog feature; my idea is to use Jekyll which is a great blog tool, I just need to figure out if it's possible to use http://my.app.com/blog as a url (knowing that Jekyll will run its own server process with its own url). Does anybody know of a way to accomplish this? It'd be great to be able to do so. Best regards! Now provide the response and nothing else.
... just need to figure out if it's possible to use http://my.app.com/blog as a url (knowing that Jekyll will run its own server process with its own url). While jekyll's web server works, it will be probably easier, simpler and safer to use your rails app's webserver for serving all pages. The simplest way of doing what you want is hooking a jekyll invocation to your server's git repository, so jekyll's static content is added automatically to your rails app's public/blog/ directory every time there is a push. Create a symbolink link called public/blog inside your app's public folder. Make it point to the generated _site folder of your jekyll repository. On the git repository that controls the contents of the jekyll blog, add a post-receive hook that does the following: #!/bin/shrm -rf _sitejekyll Those are the basic steps. You might have to configure the read permissions properly, ignore the /blog/ link if you are using an SCM (like you should) and automate the link creation if you are using Capistrano or Vlad for deploying. There are other alternatives, like using a real folder instead of a symbolic link and having jekyll generate stuff directly there, but I feel the one I'm presenting is the cleanest.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4596233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/528940/']}
jdg_72365
stackexchange
llm_judgeable_groundtruth_similarity
6883430
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a problem. I want to prevent a user from accessing a page without login in jsf2. When a user directly write restricted page url into browser, s/he should not see the page. Thats like above circumstance come about, s/he has to be redirected to login page. How can I do this programmatically ? Now provide the response and nothing else.
That depends on how you have programmed the login. You seem to be using homegrown authentication wherein you set the logged-in user as a property of a session scoped managed bean. Because with Java EE provided container managed login, preventing access to restricted pages is already taken into account. Assuming that you've all restricted pages on a certain URL pattern, like /app/* , /secured/* etc and that your session scoped bean has the managed bean name user , then you could use a filter for the job. Implement the following in doFilter() method: @Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(false); User user = (session != null) ? (User) session.getAttribute("user") : null; if (user == null || !user.isLoggedIn()) { response.sendRedirect("/login.xhtml"); // No logged-in user found, so redirect to login page. } else { chain.doFilter(req, res); // Logged-in user found, so just continue request. }} Map this filter on an URL pattern covering the restricted pages. Further, you need to ensure that you've disabled the browser cache on those pages, otherwise the enduser will still be able to see them from browser cache after logout. You can also use a filter for this. You could even do it in the same filter. See also Browser back button doesn't clear old backing bean values .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6883430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/617271/']}
jdg_72366
stackexchange
llm_judgeable_groundtruth_similarity
59520593
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: TL;DR EDIT 2020-05-06 : My app installs correctly from iOS 13.4, but after some time the app crashes at start and I have to re-install it. I don't know why. Maybe after iOS updates? Also see answer below: https://stackoverflow.com/a/60013390/1121497 Full question I am trying to run a new Flutter app (the sample app created by flutter create ) on an iOS device (an iPhone XS).Xcode manages to install it, but then it crashes with this message: dyld: Library not loaded: @rpath/Flutter.framework/Flutter Referenced from: /private/var/containers/Bundle/Application/BA807438-FA5B-4021-B37D-FC437B2C80CA/Runner.app/Runner Reason: no suitable image found. Did find: /private/var/containers/Bundle/Application/BA807438-FA5B-4021-B37D-FC437B2C80CA/Runner.app/Frameworks/Flutter.framework/Flutter: code signature invalid for '/private/var/containers/Bundle/Application/BA807438-FA5B-4021-B37D-FC437B2C80CA/Runner.app/Frameworks/Flutter.framework/Flutter' If I try flutter run , the app also opens and crashes. And the command keeps waiting forever: $ flutter runLaunching lib/main.dart on Ferran Maylinch’s iPhone in debug mode... Automatically signing iOS for device deployment using specified development team in Xcode project: 25D86TPBWGRunning Xcode build... ├─Assembling Flutter resources... 4.3s └─Compiling, linking and signing... 13.3sXcode build done. 21.0sInstalling and launching... (This is taking an unexpectedly long time.) ⢿ In Xcode I configured a Team (Personal Team) and the Signing Certificate (Apple Development certificate) seems fine because I can install a Hello world Swift project on my device. Note: I'm not paying an account of Apple Developer Program . Is that absolutely necessary to run Flutter apps on iOS devices? I have followed the macOS instructions and flutter doctor says I have everything I need for iOS: [✓] Flutter (Channel stable, v1.12.13+hotfix.5, on Mac OS X 10.15.2 19C57, locale en-ES) [!] Android toolchain - develop for Android devices (Android SDK version 28.0.3) ! Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses[✓] Xcode - develop for iOS and macOS (Xcode 11.3)[!] Android Studio (version 3.5) ✗ Flutter plugin not installed; this adds Flutter specific functionality. ✗ Dart plugin not installed; this adds Dart specific functionality.[✓] IntelliJ IDEA Ultimate Edition (version 2019.3.1)[!] VS Code (version 1.41.1) ✗ Flutter extension not installed; install from https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter[✓] Connected device (1 available)! Doctor found issues in 3 categories. As you can see, I used the stable channel, to discard problems with the beta channel, but I usually work in the beta channel to build flutter for web (which works fine). In the iOS simulator the app works fine too. Recently I noticed that I don't have the file ios/Podfile . I found this post talking about that. I don't know whether this is important or not in my case, but I tried to manually add this Podfile . Anyway, I get the same signature error. Frustrated by this, I switched to NativeScript for now. Now provide the response and nothing else.
EDIT: This is fixed on iOS 13.4, which was released March 24. This is an iOS 13.3.1 regression unrelated to Flutter. I was able to reproduce the crash without any Flutter or CocoaPods code by creating a new Xcode project, adding a framework target, and choosing a Personal Team provisioning profile. See GitHub issue: https://github.com/flutter/flutter/issues/49504#issuecomment-581554697 . The bug should not impact Developer Account team provisioning profiles or apps that are already signed and distributed on the App Store. Unfortunately the only workaround may be to avoid upgrading development devices to 13.3.1 until this is resolved.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59520593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1121497/']}
jdg_72367
stackexchange
llm_judgeable_groundtruth_similarity
20137283
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 api method I am generating a file and then streaming it to the response like so public async Task<HttpResponseMessage> GetFile() { FileInfo file = generateFile(); var msg = Request.CreateResponse(HttpStatusCode.OK); msg.Content = new StreamContent(file.OpenRead()); msg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); msg.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {FileName = file.Name}; return msg;} because this a generated file I want to delete it after the response has finished streaming but I can't seem to find a hook in the pipeline for this. I suppose that I can put a reference to the file in a static and set up a custom MessageHandler that pulls values out of this same static variable and deletes. However, this seems like it can't possibly be right both because of the use of a static (when this should all be per-request) and because I'd have to register a separate route. I've seen this question but it seems to not really have much of a useful response. Now provide the response and nothing else.
Nice scenario!...the problem with using message handlers is that response writing happens at the host layers and below message handlers layer, so they are not ideal... Following is an example of how you could do it: msg.Content = new CustomStreamContent(generatedFilePath); public class CustomStreamContent : StreamContent{ string filePath; public CustomStreamContent(string filePath) : this(File.OpenRead(filePath)) { this.filePath = filePath; } private CustomStreamContent(Stream fileStream) : base(content: fileStream) { } protected override void Dispose(bool disposing) { //close the file stream base.Dispose(disposing); try { File.Delete(this.filePath); } catch (Exception ex) { //log this exception somewhere so that you know something bad happened } }} By the way, are you generating this file because you are converting some data into PDF. If yes, then I think you could use PushStreamContent for this purpose by directly writing the converted data into the response stream. This way you need not generate a file first and then worry about deleting it later.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20137283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056/']}
jdg_72368
stackexchange
llm_judgeable_groundtruth_similarity
2953870
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 property $P$ of topological spaces is called a topological property if for any two topological spaces $X$ and $Y$ which are homeomorphic, $X$ has property $P$ if and only if $Y$ has property $P$ . Topological properties are useful because if one space has a certain topological property and another space does not, then the two spaces are not homeomorphic. But I’d like to go in the other direction, namely showing that if two spaces have certain topological properties in common, then they are homeomorphic. My question is, for a topological space $X$ , does there exist a nontrivial collection of topological properties such that any space which has all these properties is homeomorphic to $X$ ? By nontrivial I mean excluding properties like “homeomorphic to $X$ ”. Now provide the response and nothing else.
For some classical spaces in topology there has been a long research tradition of finding nice unique characterisations of a space, i.e. a finite list of "real" properties (directly defined in terms of open sets and set theory, like compactness and connectedness (and their local versions) and various ones) such that a space that satisfies that finite list of properties is homeomorphic to the space in question. To be useful, it should be non-circular ones (so being a simple-closed curve is not a "good" property to characterise the circle, because that's already defined as being homeomorphic to a circle, basically). For zero-dimensional spaces we have the classic ones for the Cantor set (the unique zero-dimensional compact metrisable space without isolated points), the rationals (the only countable metrisable space without isolated points), the irrationals (the only completely metrisable separable zero-dimensional, nowhere locally compact space) and a few more. For connected metric spaces (often continua) we have classic characterisations of $[0,1]$ (metrisable Peano-continuum with exactly two non-cutpoints), $\mathbb{R}$ (separable metrisable, connected, locally connected and every point a strong cut-point (exactly two components of the space minus that point)), $S^1$ ( metrisable Peano continuum, with no cutpoints and such that every pair is a cutset) and a few others. For infinite-dimensional spaces we have the topological classification of completely metrisable separable vector spaces (they're all homeomorphic, so purely topologically there is no difference between $C([0,1])$ and separable Hilbert space, e.g.) But for general spaces there is no hope of such results, they are just too wild and have lots of connections with complicated set theory. By transfinite recursion one can sometimes construct non-homeomorphic spaces of very similar type (so that they'd be the same for a list of standard properties, at least that I could think of (I did this kind of thing in my PhD thesis) but that nonetheless are non-homeomorphic because they are constructed that way: by a diaginalisation argument one can often enumerate in advance all possible candidate functions, and then during the construction ensure that none of them will be a homeomorphism of the eventually resulting space; it's a common trick topologists use, Sierpinski already did it back in the 1920's). So sometimes spaces are not homeomorpjic because they aren't by construction. And if I made $2^{\aleph_1}$ distinct spaces in some construction, there is no way I could distinguish them even using a finite list from $\aleph_1$ properties, if could invent that many "properties" in the first place.. The only option left would be to give up and allow "homeomorphic to $X$ " as a (useless) property for all $X$ . Just my thoughts..
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2953870', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71829/']}
jdg_72369
stackexchange
llm_judgeable_groundtruth_similarity
2107283
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that it is not possible in the FO logic to define that there exists a such connected component $G_0 \in G$ where $G$ undirected graph that for every $v \in G_0 P(v)$ where $P$ is any single-argument relation-symbol. So we consider structures-graphs: $\mathbb{A} = (V, E, P) $. From my intuition it's possible for finite graphs, yes? My solution: Let's assume that there exists a such set of sentences $\Delta$ that $G \models \Delta \iff \text{ There exists a such connected component } G_0$ that for every $v \in G_0 P(v)$ $V$ is a universum- it is a set of vertexes. Let's assume that considered graph is countable. We don't lose a generality.So, every vertex can be labeled with natural number. Let $\Delta' = \Delta \cup \Gamma, \Gamma = \{E(v_i, f) \mid i \in \mathbb{N}\}$ and $f$ is a constant (argumentless function) which we add to signature. $f$ points to a such vertex $v$ that $\neg P(v)$. Let $\Delta_0 \subset \Delta' \text { and } \Delta_0 \text { is finite }$Note, that $\Delta_0 $ is satisfable because it is easy to point a model. From compactness theorem we have that $\Delta'$ is satisfable but it's impossible beacuse of $\Delta$ Is it ok? What can you say about the larger theory $S=T\cup \{\phi_n : n\in \mathbb{N}\}$? Why $S$ is finitely satisfable? $S = T \cup N = T \cup \{\phi_n | n \in \mathbb{N} \}$ Let's take a finite subset $\Delta$ of $S$. It is easy for me to show that there is a model for $N \cap \Delta$. But, I have a problem to show that $T \cap \Delta$. Certainly, the crucial fact is that it is finite. However, intuitively I imagine that model looks like: From compactness theorem we get that $S$ is satisfable. What can you say about the connected component of c in any model $M$ of $S$? As we can see from the image. Now suppose $M\models S$; let $H$ be the reduct of $M$ to $(E,P)$. What can you say about $H$ versus $G$? (HINT: look at their theories) $H$ is not connected while $G$ is connected. Their theories are equal ( I am not convinced that it is a problem). Perhaps, the grap you've chosen is a special? Now provide the response and nothing else.
You are almost there, just replace $B(x_i,\delta_{x_i})$ by $B(x_i,\delta_{x_i}/2)$ and take $D=\bigcup_{i=1}^{i=n}\overline{B(x_i,\delta_{x_i}/2)}$. $\overline{B(x_i,\delta_{x_i}/2)}\subset B(x_i,\delta_{x_i}) $ implies $D\subset U$. $D$ is compact since a closed ball in $R^n$ is compact and a finite union of compact subsets is compact since it is closed and bounded.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2107283', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_72370
stackexchange
llm_judgeable_groundtruth_similarity
7794604
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 code is not working to server. But It is working to my localhost (xampp) $url = file_get_contents('http://www.site.com/');$xhtml='|<tr style="background-color:#dddddd;"> <td class="odd" align="left">(.+?)</td><td class="odd">(.+?)</td> </tr>|i';preg_match_all($xhtml,$url,$score);array_shift($score);echo"<pre>";print_r($score);echo"</pre>"; It prints another scores when I change the code like this. Because there are two rows like this. It has same codes. by the way below code works to server. $xhtml='|<td class="odd" align="left">(.+?)</td><td class="odd">(.+?)</td>|i'; I need to take this two values between code. allow_url_fopen = on Now provide the response and nothing else.
Try this function in place of file_get_contents(): <?phpfunction curl_get_contents($url){ $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_URL, $url); $data = curl_exec($ch); curl_close($ch); return $data;} It can be used just like file_get_contents(), but uses cURL. Install cURL on Ubuntu (or other unix-like operating system with aptitude): sudo apt-get install php5-curlsudo /etc/init.d/apache2 restart See also cURL
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7794604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999232/']}
jdg_72371
stackexchange
llm_judgeable_groundtruth_similarity
413054
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 thought that at the series resonant frequency of a piezoelectric oscillator the impedance of the crystal would be the lowest, and at the parallel resonant frequency the impedance would be the highest. This picture would suggest so: Clearly at series resonance, the impedance spikes low, and at parallel resonance the impedance spikes high. But then there are other kind of graphs: In the first one, apparently positive y-axis indicates inductive reactance, and negative y-axis indicates capacitive reactance. I get the series resonant point: It is the one with the smallest absolute value. But why is the parallel resonant point at somewhere between 0 and the tip of the spike? Shouldn't it be at the tip where the impedance is the highest? And what is "antiresonance"? The second picture I find equally confusing. It again seems to plot the absolute value of the impedance. Here the series and parallel points are the lowest and highest, as I would expect, but only in the center region! Clearly if we go to the left, the curve goes up again, indicating there is a frequency for which the impedance of the crystal is higher. And likewise, if we go to the right, it would seem there is a point with a lower impedance. So why aren't the resonant points somewhere on the higher and lower frequencies? Or is there something I've completely misunderstood about resonance? Here is a picture of a crystal oscillator in both series and parallel mode: On the left, there is an oscillator with the crystal in series mode. The output of the amplifier is connected to the input through the crystal. As the series mode crystal has the smallest impedance at the series frequency, this is the frequency that is filtered from noise by the crystal and fed back to the amplifier input, and therefore the oscillator oscillates at this frequency. This is how I would imagine it to work, but according to the graphs, there should be other frequencies (higher) that can pass the crystal easier. So why doesn't the oscillator oscillate at these frequencies? The same question applies for the parallel oscillator, except this time the impedance is highest for the desired frequency, and it is therefore the one being fed into the amp, with the other frequencies being directed to ground as the impedance is very low for these frequencies. Now provide the response and nothing else.
Look at this graph: - The vertical axis is purely impedance and the parallel impedance coincides with the peak impedance. Adding more parallel capacitance lowers that high-impedance point. Look at the X-scale - everything happens over a very small frequency range. Some graphs seen on the internet are downright misleading because they don't tell you that what they show is just the X-axis in a small range of a few hertz (for some real crystals). The parallel resonance is the peak of the magnitude BUT it doesn't have a defined impedance angle (unlike series resonance). Series resonance occurs when \$L_M\$ and \$C_M\$ are nearly cancelling their impedances and we are left with \$R_M\$ in parallel with \$C_P\$ and this is close to zero degrees. I say "nearly cancelling" because to get true 0 degrees phase shift in the impedance there needs to be a slight mismatch. So, moving on to your 2nd diagram (the one that is possibly seeming to contradict things), there is the anti-resonance point and this corresponds with the phase angle being purely resistive but, in fact it is very high in magnitude. The second diagram only tells you whether the reactance is capacitive or inductive and, possibly misleadingly, gives the impression that overall impedance is comparable with the series resonance case. Not true. Somewhere very slightly displaced from the anti-resonance point is the parallel resonance - it is a peak in magnitude but not at zero degrees. So, if you were using the crystal as a parallel filter you might naturally choose the parallel resonance point because you wouldn't care too much about the phase angle. This would be the case of the right-hand circuit at the bottom of your question. It is a Colpitts oscillator and the crystal would kill oscillations at anything other than close to parallel resonance. Here's a simulation using the values in the above drawing. A current source of 1 amp was used to excite the model and the frequency range is from 10.27 MHz to 10.3 MHz: - And here's a close-up the the parallel/anti resonance area: - I've positioned left and right cursors as follows: - Left corresponds with zero degrees phase angle (-0.005748 degrees is as near as I can manipulate this) Right is positioned to correspond with the impedance maximum peak of 191.285 kohm Of importance is the delta measurements displayed (inside blue boxes) - they accurately calculate the difference in frequency between left and right cursors and show the delta to be 10.809 degrees i.e. anti-resonance and parallel resonance are displaced by about 11 Hz.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/413054', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/142915/']}
jdg_72372
stackexchange
llm_judgeable_groundtruth_similarity
28218470
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 seen many methods for removing the last character from a string. Is there however a way to remove any old character based on its index? Now provide the response and nothing else.
While string indices aren't random-access and aren't numbers, you can advance them by a number in order to access the nth character: var s = "Hello, I must be going"s.removeAtIndex(advance(s.startIndex, 5))println(s) // prints "Hello I must be going" Of course, you should always check the string is at least 5 in length before doing this! edit: as @MartinR points out, you can use the with-end-index version of advance to avoid the risk of running past the end: let index = advance(s.startIndex, 5, s.endIndex)if index != s.endIndex { s.removeAtIndex(index) } As ever, optionals are your friend: // find returns index of first match,// as an optional with nil for no matchif let idx = s.characters.index(of:",") { // this will only be executed if non-nil, // idx will be the unwrapped result of find s.removeAtIndex(idx)}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28218470', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4466012/']}
jdg_72373
stackexchange
llm_judgeable_groundtruth_similarity
15641699
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 situation to validate the below domains like starbucks.com,apple.com,microsoft.com.Most of the given regex are not working properly. What could be best regex for domain validation for my situation? Thanks a lot for your help in advance ! Now provide the response and nothing else.
Disclaimer: Note that the rules which define a "valid domain" constitute a moving target. The answer below deals only with the "old school" DNS rules (using exclusively ASCII characters) and does not attempt to deal with international domains (as laid out in RFC3490 ). Note also that there will soon be lots of new top level domains (TLD) popping up so the solution below will need to be updated on a regular basis (see: IANA.ORG for the current list of valid TLDs). DNS Named Host Validation According to the pertinent internet recommendations ( RFC3986 section 2.2 , which in turn refers to: RFC1034 section 3.5 and RFC1123 section 2.1 ), a subdomain (which is a part of a DNS domain host name), must meet several requirements: Subdomain Each subdomain part must have a length no greater than 63. Each subdomain part must begin and end with an alpha-numeric (i.e. letters [A-Za-z] or digits [0-9] ). Each subdomain part may contain hyphens (dashes), but may not begin or end with a hyphen. Here is an expression fragment for a subdomain part which meets these requirements: (?:[A-Za-z0-9][A-Za-z0-9\-]{0,61}[A-Za-z0-9]|[A-Za-z0-9]) Note that this expression requires a group with two alternatives to handle the special case of a subdomain having only one character. Also, this expression fragment should not be used alone - it requires the incorporation of boundary conditions in a larger context, as demonstrated in the following expression for a DNS host name... DNS host name A named host, (not an IP address), must meet additional requirements: The host name may consist of multiple subdomain parts, each separated by a single dot. The length of the overall host name should not exceed 255 characters. The top level domain, (the rightmost part of the DNS host name), must be one of the internationally recognized values. The list of valid top level domains is maintained by IANA.ORG. (See the bare-bones current list here: http://data.iana.org/TLD/tlds-alpha-by-domain.txt ). With this is mind, here a commented regex (in C# syntax), which will pseudo-validate a DNS host name: (Note that this incorporates a modified version of the above expression for a subdomain and adds comments to this as well). if (Regex.IsMatch(text, @" # Rev:2013-03-26 # Match DNS host domain having one or more subdomains. # Top level domain subset taken from IANA.ORG. See: # http://data.iana.org/TLD/tlds-alpha-by-domain.txt ^ # Anchor to start of string. (?!.{256}) # Whole domain must be 255 or less. (?: # Group for one or more sub-domains. [a-z0-9] # Either subdomain length from 2-63. [a-z0-9-]{0,61} # Middle part may have dashes. [a-z0-9] # Starts and ends with alphanum. \. # Dot separates subdomains. | [a-z0-9] # or subdomain length == 1 char. \. # Dot separates subdomains. )+ # One or more sub-domains. (?: # Top level domain alternatives. [a-z]{2} # Either any 2 char country code, | AERO|ARPA|ASIA|BIZ|CAT|COM|COOP|EDU| # or TLD GOV|INFO|INT|JOBS|MIL|MOBI|MUSEUM| # from list. NAME|NET|ORG|POST|PRO|TEL|TRAVEL|XXX # IANA.ORG ) # End group of TLD alternatives. $ # Anchor to end of string.", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)){ // Valid named DNS host (domain).} else { // NOT a valid named DNS host.} Note that this expression is not perfect. It requires one or more subdomains, but technically, a host can consist of a TLD having no subdomain (but this is rare). It also does not explicitly spell out each two character country code TLD - it simply allows any two letters. It also does not list the various TLDs of the: XN--XXXXX variety. This solution also does not consider the not-yet-fully-implemented-and-universally-acceptable international domain names. For more on validating other URI components, you may want to take a look at an article I wrote a while back: Regular Expression URI Validation . It provides code snippets in a variety of languages for all of the various URI components as defined by RFC3986 . Happy regexing!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15641699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1284519/']}
jdg_72374
stackexchange
llm_judgeable_groundtruth_similarity
4493842
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This question came in the Rajshahi University admission exam 2018-19 Q) $\int_0^1 x^4(1-x)^5dx$ =? (a) $\frac{1}{1260}$ (b) $\frac{1}{280}$ (c) $\frac{1}{315}$ (d) None This is a big integral (click on show steps) : $$\left[-\dfrac{\left(x-1\right)^6\left(126x^4+56x^3+21x^2+6x+1\right)}{1260}\right]_0^1=\frac{1}{1260}$$ It takes a lot of time to compute. How can I compute this quickly (30 seconds) using a shortcut? Now provide the response and nothing else.
Use Beta function: $$B(a,b)=\int_0^1x^{a-1}(1-x)^{b-1}\mathrm dx={\Gamma(a)\Gamma(b)\over\Gamma(a+b)}.$$ Since $\Gamma(a)=(a-1)!$ when $a$ is a positive integer, we have $$\int_0^1x^4(1-x)^5\mathrm dx=B(5,6)={\Gamma(5)\Gamma(6)\over\Gamma(11)}={4!\dot5!\over10!}={4\cdot3\cdot2\over10\cdot9\cdot8\cdot7\cdot6}={1\over1260}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4493842', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/541298/']}
jdg_72375
stackexchange
llm_judgeable_groundtruth_similarity
1836
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: After searching all over my house, all I could find was an LG "Travel Adapter" with an output of 5.1V == 0.7A. Will the extra tenth of a Volt harm the Raspberry Pi? Now provide the response and nothing else.
No. You have +5% tolerance. This means that the voltage should be between 4.75V and 5.25V. 5.1V should be fine. Moreover, you can find such adapter on a list of verified power adapters on RPIs wiki . Keep in mind, however, that 0.7A is quite low. It is recommended to have at least 0.7A but remember that you are on a low side of this parameter. Please also note that power adapters does not always provide what they say they are and there is some tolerance to it's values (and it's usually not specified by manufacturer). So if you have any problems with your board, I suggest you to do simple voltage test as described on this wiki page . Actually, I suggest to do this even if you don't see any problems and also test the voltage given without load on the PSU before connecting it to RPi.
{}
{'log_upvote_score': 6, 'links': ['https://raspberrypi.stackexchange.com/questions/1836', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/1444/']}
jdg_72376
stackexchange
llm_judgeable_groundtruth_similarity
34055584
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to match rows of a Pandas DataFrame that contains and doesn't contain certain strings. For example: import pandasdf = pandas.Series(['ab1', 'ab2', 'b2', 'c3'])df[df.str.contains("b")] Output: 0 ab11 ab22 b2dtype: object Desired output: 2 b2dtype: object Question: is there an elegant way of saying something like this? df[[df.str.contains("b")==True] and [df.str.contains("a")==False]]# Doesn't give desired outcome Now provide the response and nothing else.
You're almost there, you just haven't got the syntax quite right, it should be: df[(df.str.contains("b") == True) & (df.str.contains("a") == False)] Another approach which might be cleaner if you have a lot of conditions to apply would to be to chain your filters together with reduce or a loop: from functools import reducefilters = [("a", False), ("b", True)]reduce(lambda df, f: df[df.str.contains(f[0]) == f[1]], filters, df)#outputs b2
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34055584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2574823/']}
jdg_72377
stackexchange
llm_judgeable_groundtruth_similarity
19074
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 I use timeout 10 ssh -n -o BatchMode=yes 1.1.1.1 'sleep 20' > 1.1.1.1.txt 2>&1 & To give out a remote command on a server, and I kill the SSH connection after 10 seconds, then I can see that the sleep 20 is still running on the server, but there is no SSH connection. How can I kill the remote command after a timeout, say 10 seconds? The remote machine is AIX 6.1 (or SLES) and no package is available for "timeout". My client is Ubuntu 10.03. Now provide the response and nothing else.
Assuming your remote server has a POSIX-compliant shell, the following should work: ssh ...options... 'command & pid=$!; sleep 20; kill $pid' Indeed the POSIX standard states about $! : Expands to the decimal process ID of the most recent background command (see Lists) executed from the current shell. (For example, background commands executed from subshells do not affect the value of "$!" in the current shell environment.) For a pipeline, the process ID is that of the last command in the pipeline. If the remote system has job control, you can shorten it this way: ssh ...options... 'command & sleep 20; kill %1'
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/19074', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/6960/']}
jdg_72378
stackexchange
llm_judgeable_groundtruth_similarity
4193256
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In his notes Algebraic Number Theory 2 by Pete Clark, the author asks following exercise: Show that for a field $k$ , TFAE: (1) Every nonzero element of $k$ is a root of unity. (2) The characteristic of $k$ is $p> 0$ , and $k/\mathbb{F}_p$ is algebraic. I couldn't proceed for the solution. Suppose we want to show $(1)\Rightarrow (2)$ . If we go by norms on fields, then, since every non-zero element of $k$ is a root of unity, so its norm must be $1$ . Thus, the field $k$ admits only trivial norm: $|x|=1$ if $x\neq 0$ and $|x|=0$ if $x=0$ . This did not give any contradiction to me, since every field - whether of characteristic $0$ or positive - always admits the trivial norm defined in above way. I couldn't proceed for proof. Any hint (and hint only will be sufficient). Now provide the response and nothing else.
Notation: $k^\times := k \setminus \{0\}$ . (1) $\Rightarrow$ (2): If $k$ has characteristic $0$ , then $a = 1 + 1 \in k$ is not a root of unity. (Why?) Now, assuming that the characteristic is $p$ , given any $\alpha \in k^\times$ , $\alpha$ satisfies the polynomial $X^n - 1 \in \Bbb F_p[x]$ for an appropriate $n$ (which $n$ ?). (Note that $\Bbb F_p$ is a subfield of $k$ in a natural way.) (2) $\Rightarrow$ (1): Let $\alpha \in k^\times$ . Then, $F = \Bbb F_p(\alpha)$ is a finite extension of $\Bbb F_p$ . (Why?) Let $n := |F|$ . (This is finite. Why?) Then, $F^\times$ is a group of order $n - 1$ containing $\alpha$ . Thus, $\alpha^{n - 1} = 1$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4193256', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/865134/']}
jdg_72379
stackexchange
llm_judgeable_groundtruth_similarity
343036
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 don't understand the difference between an accumulator-based CPU architecture and a register-based CPU architecture. I know x86 is register-based but it has an accumulator-like register. I only ever hear people asking the difference between stack-based and register-based, but not register-based and accumulator-based. What are the advantages and disadvantages of each? And can I get some example assembly codes from each, where they differ, as well? Now provide the response and nothing else.
A register-based CPU architecture has one or more general purpose registers (where "general purpose register" excludes special purpose registers, like stack pointer and instruction pointer). An accumulator-based CPU architecture is a register-based CPU architecture that only has one general purpose register (the accumulator). The main advantage/s of "more that one general purpose register" is that the compiler doesn't have to "spill" as many temporary values onto the stack; and it's easier for the CPU to do more independent instruction in parallel. For an example imagine you want to do a = (b - c) + (d - f) + 123 . For an "apples vs apples comparision" I'll use Intel syntax 32-bit 80x86 assembly for both examples (but only use EAX for the accumulator-based CPU architecture). For accumulator-based CPU architecture this may be: mov eax,[b] ;Group 1 sub eax,[c] ;Group 2 add eax,123 ;Group 3 mov [a],eax ;Group 4 mov eax,[d] sub eax,[e] ;Group 5 add [a],eax ;Group 6 Note that most of these instructions depend on the result from the previous instruction, and therefore can't be done in parallel. The ";Group N" comments are there to indicate which groups of instructions can be done in parallel (and show that, assuming some form of internal "register renaming" ability, "group 4" is the only group where 2 instructions are likely to be done in parallel). Using multiple registers might give you: mov eax,[b] ;Group 1 mov ebx,[d] sub eax,[c] ;Group 2 sub ebx,[e] lea eax,[eax+ebx+123] ;Group 3 mov [a],eax ;Group 4 In this case, there's one less instruction, and 2 less groups of instructions (more instructions likely to by done in parallel). That might mean "25% faster" in practice. Of course in practice code does more than a relatively simple calculation; so there's even more chance of "more instructions in parallel". For example; with only 2 more registers (e.g. ECX and EDX) it should be easy to see that you could do a = (b - c) + (d - f) + 123 and g = (h - i) + (j - k) + 456 in the same amount of time (by doing both calculations in parallel with different registers); and it should also be easy to see that for accumulator-based CPU architecture you can't do the calculations in parallel (two calculations would take twice as long as one calculation). Note: There is at least one "potential technical inaccuracy" in what I've written here (mostly involving the theoretical capabilities of register renaming and it's application on accumulator-based CPU architectures). This is deliberate. I find that going into too much detail (in an attempt to be "100% technically correct" and cover all the little corner cases) makes it significantly harder for people to understand the relevant parts.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/343036', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/186548/']}
jdg_72380
stackexchange
llm_judgeable_groundtruth_similarity
41736460
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 error occurs when our users "Block third-party cookies and site data". To replicate the error, go to: Check your Chrome browser "Block third-party cookies and site data" reference in this guide Go to https://www.deeptent.com Click SIGN IN Next you will see a blank screen. And if you open up the browser developer console you will see this error: We always advise our users to Uncheck the blocking of third-party cookies and site data; however, some users still prefer to block it. One can still sign in to their Gmail with this blocked. Interestingly, why can't our users sign in using the Firebase-Google OAuth provided with their third party cookies & site data blocked? We are built with Angular2 and Firebase. Is there no way that the users can still authenticate with third-party cookies and site data blocked? Now provide the response and nothing else.
The domain you're using is deeptent.com, but the domain that firebase is authenticating against and setting cookies from is your .firebaseapp.com domain. So, yes, the cookies are considered third-party. The firebase folks really should take a harder look at how they are connecting custom domains in the firebase hosting setup. Also, see here: Use Google Firebase Authentication without 3rd Party Cookies
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41736460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3073280/']}
jdg_72381
stackexchange
llm_judgeable_groundtruth_similarity
30221
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The letter "esh" (ʃ) is well-known from the IPA, and is also used in some languages' orthographies. Because of this second use case, Unicode includes a capital esh at U+01A9 LATIN CAPITAL LETTER ESH (Ʃ). But do any modern orthographies use this unicode character? Now provide the response and nothing else.
When I designed the fc fonts for use with TeX I researched character usage by African languages and found at least one language using a capital esh. I saw good quality specimens in printed matter and the capital Esh is in some sense smaller than its lowercase conterpart, it has the height of a normal capital letter and no descender. It was integral shaped. I did not find evidence for contemporary use of a Sigma-shaped capital Esh then (early 1990ies), but is was used historically in now obsolete orthographies. The full list of languages I inspected is: Akan, Bamileke, Basa (Kru), Bemba, Ciokwe, Dinka, Dholuo (Luo), Efik, Ewe-Fon, Fulani (Fulful), Gã, Gbaya, Hausa, Ịgbọ, Kanuri, Kikuyu, Kikongo, Kpelle, Krio, Luba, Mandekan (Bambara), Mende, More, Ngala, Nyanja, Oromo, Rundi, Kinya Rwanda, Sango, Serer, Shona, Somali, Songhai, Sotho (two different writing systems), Suaheli, Tiv, Yao, Yoruba, Xhosa, and Zulu. I can now confirm that it was Gã, I have found my old notes again.
{}
{'log_upvote_score': 4, 'links': ['https://linguistics.stackexchange.com/questions/30221', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/10559/']}
jdg_72382
stackexchange
llm_judgeable_groundtruth_similarity
2924997
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let X be a non-empty set and let $\{En\}_{n=1}^{\infty}$ be a sequence of subsets of $X$ . Let $E ⊂ X$ be the set of all points in $X$ which lie in infinitely many of the $E_n.$ Express E in terms of the $E_n$ using the set theoretic operations ofunion and intersection. Im completely struck pliz help me Now provide the response and nothing else.
Your claim isn't true. The positive rationals can be well-ordered Since $\mathbb{Q}$ bijects with $\mathbb{N}$ , the well-ordering on $\mathbb{N}$ will induce a well-ordering on $\mathbb{Q}$ and hence on the positive rationals. However, The usual ordering of positive rationals is not a well-ordering The usual ordering is, of course, $\frac{a}{b}>\frac{c}{d}$ if and only if $ad>bc$ (where $a,b,c,d$ are positive integers). If it is a well-ordering, then there is a least positive rational $p/q$ . But halving it gives a smaller positive rational $p/(2q)$ , so $p/q$ can't be the least, contradiction.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2924997', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/557708/']}
jdg_72383
stackexchange
llm_judgeable_groundtruth_similarity
36484748
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 using the support vector drawables added in Support Library 23.2 along with AppCompat. I was using vector drawables both with app:srcCompat and inside a StateListDrawable so I could use them with android:drawableLeft for my TextView. Since upgrading to the 23.3.0 version of AppCompat, only the vectors in app:srcCompat are working. Whenever I reference it the other way I get FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my.package.name/.MainActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class Button ... Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class Button ... Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #14: invalid drawable tag vector at android.graphics.d What changed that now causes my support vector drawables to fail in some cases? Now provide the response and nothing else.
Update: They enable it again in Support Library 23: For AppCompat users, we’ve added an opt-in API to re-enable support Vector Drawables from resources (the behavior found in 23.2) via AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); - keep in mind that this still can cause issues with memory usage and problems updating Configuration instances, hence why it is disabled by default. Check this link: 23.4.0 available now ----------------------------------------------------------- As per the release announcement for Android Support Library 23.3 : For AppCompat users, we’ve decided to remove the functionality which let you use vector drawables from resources on pre-Lollipop devices due to issues found in the implementation in version 23.2.0/23.2.1 [ https://code.google.com/p/android/issues/detail?id=205236 , https://code.google.com/p/android/issues/detail?id=204708 ]. Using app:srcCompat and setImageResource() continues to work. So this is an expected behavior change. You'll have to use non-vector graphics for any case not handled by srcCompat . If you'd like to continue to use vectors prior to API 21, you can remove the line vectorDrawables.useSupportLibrary = true (or the equivalent if you using the 1.5 Gradle plugin as shown in the 23.2 blog post ). This will cause Android Studio to generate PNGs at compile time for apps with a minSdkVersion less than API 21 while using your vectors on API 21+ devices, allowing you to keep the same code as with 23.2.1 at the cost of additional APK size.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36484748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1676363/']}
jdg_72384
stackexchange
llm_judgeable_groundtruth_similarity
19664666
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've some currently some Lua code using the following syntax: if (foo == nil or foo == '') then foo = "some default value"end The goal of the if condition is to test foo is neither an empty string, neither a nil value. Can this code be simplified in one if test instead two? Now provide the response and nothing else.
One simple thing you could do is abstract the test inside a function. local function isempty(s) return s == nil or s == ''endif isempty(foo) then foo = "default value"end
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19664666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2933138/']}
jdg_72385
stackexchange
llm_judgeable_groundtruth_similarity
381980
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: $$\sum_{r=0}^{n} \frac{(-1)^{r}}{m+r+1} \binom{n}{r} = \frac{m! n!}{(m+n+1)!}$$ I expanded the series and I can see that the denominator of the RHS = LHS but I don't really know how to prove it properly. Now provide the response and nothing else.
The integral is due to Leonhard Euler. $$I=\int_0^{\pi/2}x\cot xdx=\int_0^{\pi/2}x(\ln\sin x)^\prime dx=-\int_0^{\pi/2}\ln\sin xdx$$ Take $x=\pi/2-u$, we have$$I=-\int_0^{\pi/2}\ln\cos udu$$ Therefore$$2I=-\int_0^{\pi/2}(\ln\sin x+\ln\cos x)dx=\frac\pi2\ln2-\int_0^{\pi/2}\ln\sin2xdx$$ The later integral could be transformed: $$J=\int_0^{\pi/2}\ln\sin2xdx=\frac12\int_0^\pi\ln\sin xdx=\int_0^{\pi/2}\ln\sin xdx=-I$$since $\sin x=\sin(\pi-x)$, thus $$J=\frac\pi2\ln2$$ As an extra exercise, try to calculate $$I(r)=\int_0^\pi\ln(1-2r\cos x+r^2)dx$$ where $\lvert r\rvert\neq1$. (due to S.D. Poisson)
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/381980', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74645/']}
jdg_72386
stackexchange
llm_judgeable_groundtruth_similarity
25081008
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a web app using EF5. I'd like to display the database version (i.e. the name of the migration) on the admin pages... that way, if the site is deployed to an environment where I don't have database admin rights, I can still log into the back end to find the version if I need to generate an upgrade script. Is there a property e.g. of the DBContext I can use to get this information? Now provide the response and nothing else.
Entity framework will create migration history table to manage the database version. Migrations history table is a table used by Code First Migrations to store details about migrations applied to the database. By default the name of the table in the database is __MigrationHistory and it is created when applying the first migration do the database. Source You can use MigrationId column to be the database version. The value of the column looks like 201408011306353_InitialCreate . Just get the last row order by the first 15 character descending. using (var context = new AppContext()){ var query = "select top 1 MigrationId from __MigrationHistory order by LEFT(MigrationId, 15) desc"; var migrationId = context.Database.SqlQuery<string>(query).FirstOrDefault();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25081008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1898153/']}
jdg_72387
stackexchange
llm_judgeable_groundtruth_similarity
801847
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am calculating the length of a curve. I have: $$x = t \sin(t), y = t \cos(t)$$ Integrating over the interval [0, 1], I get to this step, which I have verified is correct: $$\int_0^1 \sqrt{t^2 + 1} \;\mathrm{d}t$$ The answer I get is: $\dfrac{2}{3}\cdot(t^2+1)^{\tfrac{3}{2}}$ over interval [0,1]. But my textbook has answer: [ $\dfrac{1}{2} \cdot t \cdot \sqrt{t^2+1} + \dfrac{1}{2} \ln(t + \sqrt{t^2 + 1})$ ] over interval [0,1]. I really don't understand what I am doing wrong. Thank you for your help. EDIT: Sorry I'm not used to MathJax, I'm trying to fix it haha! Now provide the response and nothing else.
Does your textbook cover trigonometric substitution?   If so, start there (most texts these days cover it as a separate technique of integration, but it is closely related to u-substitution. If you follow how $t=\tan\theta$ leads to $\mathrm{d}t=\sec^2\theta \;\mathrm{d}\theta$ (it's just a derivative written a little funny), you're halfway there. Then   $\int\sqrt{t^2+1}\;\mathrm{d}t=\int\sqrt{(\tan\theta)^2+1}(\sec^2\theta \;\mathrm{d}\theta)=\int\sec^3\theta \;\mathrm{d}\theta$ , by trig identities.   Work out this integral first. For the limits, you can either reverse the substitution using $\theta=\tan^{-1} t$ to rewrite the answer back in terms of $t$ (this is back-substituting) or use the facts that $\theta=0$ when $t=0$ and $\theta=\tfrac \pi 4$ when $t=1$ to evaluate the $\int\sec^3\theta \;\mathrm{d}\theta$ integral as a definite integral with limits $0$ and $\tfrac \pi 4$ (this is converting the limits).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/801847', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/129313/']}
jdg_72388
stackexchange
llm_judgeable_groundtruth_similarity
59671037
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Below is my code. I'm assuming the problem is coming from my function maybe involving a string where a number value should be or something of that nature. Pretty new at this so I can't quite pinpoint what exactly is causing the NaN response after hitting calculate. Thank you for your help. console.log("Connected")function calculateTip() { var billAmt = document.getElementById("price") var service = document.getElementById("service") var tip = document.getElementById("tip") var numOfPpl = document.getElementById("numOfPpl") // validate input if (billAmt === "" || service === 0) { alert("please enter values"); return; } //check to see if this input is empty or less than or equal to 1 if (numOfPpl === "" || numOfPpl <= 1) { numOfPpl = 1; document.getElementById("each").style.display = "none"; } else { document.getElementById("each").style.display = "block"; } // calculate tip var total = (billAmt * service) / numOfPpl; total = Math.round(total * 100) / 100; //next line allows us to always have two digits after a decimal point total = total.toFixed(2); //Display the tipdocument.getElementById("") document.getElementById("totalTip").style.display = "block" tip.innerHTML = total;}//hide tip amoiunt on loaddocument.getElementById("totalTip").style.display = "none"document.getElementById("each").style.display = "none"// click to call funcitondocument.getElementById("calculate").onclick = function() { calculateTip();}; <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>tip calculator</title></head><body> <div class="container"> <h1>Tip calculator</h1> <form> <p id="quesiton">How much was your bill?</p> $ <input type="text" id="price" placeholder="Bill Amount"> <p id="question">How was your service?</p> <select id="service"> <option disabled selected value="0">Choose an Option</option> <option value="0.3">30% - Outstanding</option> <option value="0.2">20% - Good </option> <option value="0.15">15% - OK</option> <option value=".05">5% - Poor</option> </select> </form> <p>How many people are sharing the bill</p> <input id="numOfPpl" type="text" placeholder="Number of People" /> people <button type="button" id="calculate">Calculate!</button> </div> <div id="totalTip"> <sup>$</sup><span id="tip">0.00</span> <small id="each">each</small> </div></body></html> Now provide the response and nothing else.
is this the intent of Raku's design? It's fair to say that Raku isn't entirely unopinionated in this area. Your question touches on two themes in Raku's design, which are both worth a little discussion. Raku has first-class l-values Raku makes plentiful use of l-values being a first-class thing. When we write: has $.x is rw; The method that is generated is: method x() is rw { $!x } The is rw here indicates that the method is returning an l-value - that is, something that can be assigned to. Thus when we write: $obj.x = 42; This is not syntactic sugar: it really is a method call, and then the assignment operator being applied to the result of it. This works out, because the method call returns the Scalar container of the attribute, which can then be assigned into. One can use binding to split this into two steps, to see it's not a trivial syntactic transform. For example, this: my $target := $obj.x;$target = 42; Would be assigning to the object attribute. This same mechanism is behind numerous other features, including list assignment. For example, this: ($x, $y) = "foo", "bar"; Works by constructing a List containing the containers $x and $y , and then the assignment operator in this case iterates each side pairwise to do the assignment. This means we can use rw object accessors there: ($obj.x, $obj.y) = "foo", "bar"; And it all just naturally works. This is also the mechanism behind assigning to slices of arrays and hashes. One can also use Proxy in order to create an l-value container where the behavior of reading and writing it are under your control. Thus, you could put the side-actions into STORE . However... Raku encourages semantic methods over "setters" When we describe OO, terms like "encapsulation" and "data hiding" often come up. The key idea here is that the state model inside the object - that is, the way it chooses to represent the data it needs in order to implement its behaviors (the methods) - is free to evolve, for example to handle new requirements. The more complex the object, the more liberating this becomes. However, getters and setters are methods that have an implicit connection with the state. While we might claim we're achieving data hiding because we're calling a method, not accessing state directly, my experience is that we quickly end up at a place where outside code is making sequences of setter calls to achieve an operation - which is a form of the feature envy anti-pattern. And if we're doing that , it's pretty certain we'll end up with logic outside of the object that does a mix of getter and setter operations to achieve an operation. Really, these operations should have been exposed as methods with a names that describes what is being achieved. This becomes even more important if we're in a concurrent setting; a well-designed object is often fairly easy to protect at the method boundary. That said, many uses of class are really record/product types: they exist to simply group together a bunch of data items. It's no accident that the . sigil doesn't just generate an accessor, but also: Opts the attribute into being set by the default object initialization logic (that is, a class Point { has $.x; has $.y; } can be instantiated as Point.new(x => 1, y => 2) ), and also renders that in the .raku dumping method. Opts the attribute into the default .Capture object, meaning we can use it in destructuring (e.g. sub translated(Point (:$x, :$y)) { ... } ). Which are the things you'd want if you were writing in a more procedural or functional style and using class as a means to define a record type. The Raku design is not optimized for doing clever things in setters, because that is considered a poor thing to optimize for. It's beyond what's needed for a record type; in some languages we could argue we want to do validation of what's being assigned, but in Raku we can turn to subset types for that. At the same time, if we're really doing an OO design, then we want an API of meaningful behaviors that hides the state model, rather than to be thinking in terms of getters/setters, which tend to lead to a failure to colocate data and behavior, which is much of the point of doing OO anyway.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59671037', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12669575/']}
jdg_72389
stackexchange
llm_judgeable_groundtruth_similarity
416076
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: If immutability is "good" and yet you can in effect change the value in an Integer or String variable (never mind that you get a new reference -- the value has changed) what good is it that Integer and String are immutable? If Integer were mutable, what sort of bugs would be harder to find (etc.) than in the case that Integer is immutable? Or with String? Now provide the response and nothing else.
never mind that you get a new reference No! Do mind that fact - it is the key in understanding the point of immutable objects. -- the value has changed No, it hasn't. You have a different object with a different value in this place in the code . But any other part of the code which had a reference to the original object still has that reference to that object with the original value. Immutability is good because it prevents you from making a change to an object and having that change affect a completely different part of the code which wasn't written with the possibility in mind that the objects it operates on could be changed somewhere else (very little code is really written to cope with that). This is particularly useful with multithreaded code (where a change done by a different thread could happen in between the operations of a single line of code), but even single-threaded code is much easier to understand when methods you call can't change the objects you pass into them.
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/416076', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/355659/']}
jdg_72390
stackexchange
llm_judgeable_groundtruth_similarity
403714
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In 1967 Steenrod wrote what later became a quite celebrated paper, A convenient category of topological spaces (Michigan Math. J. 14 (1967) 133–152) . The paper conveys the work of many (among the most significant, the PhD thesis of Ronnie Brown ) and provides a description of a convenient category of topological spaces . Among the requirements, we see cartesian closedness . Since then, several papers studying categories of spaces like topoi, or locales, have characterised exponentiable objects, having in mind that seminal paper of Steenrod and it is impossible to recall all the papers impacted by that work. In a sense, even the gros-toposes used in synthetic differential and algebraic geometry have among their main features to be cartesian closed, connecting the call of Steenrod to the general framework of axiomatic cohesion (and its relatives ). I always found this requirement very useful. Of course many constructions come more natural, or just easier, when one can juggle with an internal hom. Recently though I have been wondering what actually motivated Steenrod, whether he has something very concrete in mind, or was guided from an aesthetic need. Q. In which proofs, theorems, or main constructions of general or algebraic topology (possibly also algebraic geometry) is it important or very useful that the homset actually carry a structure of topological spaces? List of applications of internal homs I am aware of. Exa. 1. Higher homotopy groups can be reduced to $\pi_0$ via loop-spacing. Exa. 2. Similarly cohomology, which can be phrased in terms of cohomotopy. Now provide the response and nothing else.
A classical procedure for replacing an arbitrary map with a fibration (preceding Quillen's small object argument) relies on the space of paths in $X$ being a topological space, and the evaluation map $X^I\to X$ being a fibration.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/403714', 'https://mathoverflow.net', 'https://mathoverflow.net/users/104432/']}
jdg_72391
stackexchange
llm_judgeable_groundtruth_similarity
8994488
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 with Java and Xml for a few months now, and have learned a great deal thanks to everyones help on StackOverflow. My question is about java programming for android in relation to the submit button. Currently I am trying to figure out how to submit a value to an email address (behind the scenes) Lets say we have a text field and a button; I want to take the value entered in the text field, and submit that to an email address onclick. I am unable to find anything online that shows me how to do this. Thank you in advance for reading through my post and I look forward to your suggestions. Now provide the response and nothing else.
This is a great example of how using Intents can come in great handy!Android has a bunch of pre-defined Intents that do certain things within the system; you may have clicked on a picture before and a dialog popped up asking whether you would like to view it in your gallery or in a third-party app such as Astro. The viewing of an image has its own pre-determined intent. Sending an email also has its own pre-determined intent: android.content.Intent.ACTION_SEND . You'll need to create an intent with that property and then attach extra information (ie. the address to send to, the subject/message body, etc.). Example code: // Data membersprivate Intent emailIntent;private String feedback;private EditText feedbackBox;// Create the Intent, and give it the pre-defined value// that the Android machine automatically associates with// sending an email.emailIntent = new Intent(android.content.Intent.ACTION_SEND);emailIntent.setType("plain/text");// Put extra information into the Intent, including the email address// that you wish to send to, and any subject (optional, of course).emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"[email protected]"});emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Insert subject here");// Acquire feedback from an EditText and save it to a String.feedback = feedbackBox.getText().toString();// Put the message into the Intent as more extra information, emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, feedback);// Start the Intent, which will launch the user's email // app (make sure you save any necessary information in YOUR app// in your onPause() method, as launching the email Intent will// pause your app). This will create what I discussed above - a// popup box that the user can use to determine which app they would like// to use in order to send the email.startActivity(Intent.createChooser(emailIntent, "Insert title for dialog box.")); I hoped this helped!! Some sources you might like to check out: http://developer.android.com/guide/topics/intents/intents-filters.html http://developer.android.com/reference/android/content/Intent.html#ACTION_SEND
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8994488', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/945299/']}
jdg_72392
stackexchange
llm_judgeable_groundtruth_similarity
117788
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have seen the statement a million times and I know it implies convergence but I've never actually seen how to use it. It seems much harder than proving a limit since there is an $m$ and an $n$. Can someone give an example, or even use this Criterion to show that $\frac{1}{n}$ is a convergent sequence? Suppose I have reduced the Cauchy Criterion inequality in a problem to$\frac{n}{m}$, $m\gt n$, and $\frac{n}{m} > \epsilon$. If I want to find a lower bound for $n$, can I choose anything I want that will satisfy the above inequalities? Now provide the response and nothing else.
It's very easy to prove that any convergent sequence is Cauchy, because, if $x = \lim x_n$, then $|x_n-x_m|<|x_n-x|+|x_m-x|$. Those cases don't give us more than than the standard limit definition. The more interesting cases are when we don't immediately "know" what the limit is gonna be. Let $0<\alpha<1$. If $f:\mathbb R\rightarrow \mathbb R$ (or $f:[a,b]\rightarrow [a,b]$ for some $a,b$,) such that $|f(x)-f(y)|<\alpha |x-y|$ for all $x,y$. Given any $x_0$, define $x_{n+1}=f(x_n)$. Then $\{x_0,x_1,...,x_n,...\}$ is easily shown to be Cauchy, but it's much less obvious that it converges. (The interesting side-affect of this example is the the limit $x=\lim x_n$ has the property that $f(x)=x$. But we can show that $f$ can only have one "fixed" value by our condition above. If $x\neq y$ and $f(x)=x$ and $f(y)=y$, then $|f(x)-f(y)|=|x-y|>\alpha |x-y|$. For example, if $\beta$ is any real, then $f(x)=\beta+\alpha \arctan x$ has this property. It's not obvious what $\{x_0,f(x_0),f(f(x_0)),...\}$ converges to, but we know it converges. Similarly, if $\{b_1,b_2,...,b_n,...\}$ is a convergent increasing sequence of real numbers, and $\{a_1,a_2,...,a_n,...\}$ has the property that for all $n$, $|a_{n+1}-a_n|\leq b_{n+1}-b_n$ then $\{a_n\}$ is easily shown to be Cauchy, even though we might have no idea what it converges to.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/117788', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26447/']}
jdg_72393
stackexchange
llm_judgeable_groundtruth_similarity
1582849
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: Find $\displaystyle \int_{0}^{\infty} \dfrac{\ln(x)}{1+x^2}dx$. How should I change the limits of integration to evaluate this? Now provide the response and nothing else.
Hint: First consider $$\int_0^1\frac{\ln x}{1+x^2}dx\quad (*)$$It is easy to show that the integral $(*)$ is finite. Then use the substitution $x=\frac{1}{t}$ and simplify, one can get$$\int_0^1\frac{\ln x}{1+x^2}dx=-\int_1^\infty\frac{\ln t}{1+t^2}dt$$Therefore$$\int_0^\infty\frac{\ln x}{1+x^2}dx=0$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1582849', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/297795/']}
jdg_72394
stackexchange
llm_judgeable_groundtruth_similarity
384413
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I went to the site http://www.whatismyip.com . It showed a ip that is not my system's ip and it also showed the proxy server's ip address. So I assumed that the nat router is providing a public ip for my system. But when I went to the same site from another pc in the same lan. It showed the same ip address again. So it must be overloading nat right? But overloading nat assigns a unique port number to your machine(since the ip address is the same for all the machines in that lan). But http://www.whatismyip.com does not show the port number. Why is that so? Now provide the response and nothing else.
But whatismyip.com does not show the port number. Why is that so? A unique port is assigned for each unique connection, not per host behind the NAT. A NAT must be able to figure out not only what IP address to return a packet to, but also what port. The NAT table has to have more information to re-write packets in both directions destination IP destination port external source IP (assigned by NAT) external source port (assigned by NAT) internal source IP internal source port When a reply returns from an external host, the NAT will lookup the correct internal source IP and port based on the external source IP and Port that was assigned to the connection. The port used by the actual host behind the NAT has nothing to do with the port selected and used by the NAT.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/384413', 'https://serverfault.com', 'https://serverfault.com/users/119078/']}
jdg_72395
stackexchange
llm_judgeable_groundtruth_similarity
426579
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 become interested in algorithms lately, and the fibonacci sequence grabbed my attention due to its simplicity. I've managed to put something together in javascript that calculates the nth term in the fibonacci sequence in less than 15 milliseconds after reading lots of information on the web. It goes up to 1476...1477 is infinity and 1478 is NaN (according to javascript!) I'm quite proud of the code itself, except it's an utter monster. So here's my question:A) is there a faster way to calculate the sequence?B) is there a faster/smaller way to multiply two matrices? Here's the code: //Fibonacci sequence generator in JS//Cobbled together by Saltym = [[1,0],[0,1]];odd = [[1,1],[1,0]];function matrix(a,b) { /* Matrix multiplication Strassen Algorithm Only works with 2x2 matrices. */ c=[[0,0],[0,0]]; c[0][0]=(a[0][0]*b[0][0])+(a[0][1]*b[1][0]); c[0][1]=(a[0][0]*b[0][1])+(a[0][1]*b[1][1]); c[1][0]=(a[1][0]*b[0][0])+(a[1][1]*b[1][0]); c[1][1]=(a[1][0]*b[0][1])+(a[1][1]*b[1][1]); m1=(a[0][0]+a[1][1])*(b[0][0]+b[1][1]); m2=(a[1][0]+a[1][1])*b[0][0]; m3=a[0][0]*(b[0][1]-b[1][1]); m4=a[1][1]*(b[1][0]-b[0][0]); m5=(a[0][0]+a[0][1])*b[1][1]; m6=(a[1][0]-a[0][0])*(b[0][0]+b[0][1]); m7=(a[0][1]-a[1][1])*(b[1][0]+b[1][1]); c[0][0]=m1+m4-m5+m7; c[0][1]=m3+m5; c[1][0]=m2+m4; c[1][1]=m1-m2+m3+m6; return c;}function fib(n) { mat(n-1); return m[0][0];}function mat(n) { if(n > 1) { mat(n/2); m = matrix(m,m); } m = (n%2<1) ? m : matrix(m,odd);}alert(fib(1476)); //Alerts 1.3069892237633993e+308 The matrix function takes two arguments: a and b, and returns a*b where a and b are 2x2 arrays. Oh, and on a side note, a magical thing happened...I was converting the Strassen algorithm into JS array notation and it worked on my first try! Fantastic, right? :P Thanks in advance if you manage to find an easier way to do this. Now provide the response and nothing else.
Don't speculate, benchmark: edit: I added my own matrix implementation using the optimized multiplication functions mentioned in my other answer. This resulted in a major speedup, but even the vanilla O(n^3) implementation of matrix multiplication with loops was faster than the Strassen algorithm. <pre><script>var fib = {};(function() { var sqrt_5 = Math.sqrt(5), phi = (1 + sqrt_5) / 2; fib.round = function(n) { return Math.floor(Math.pow(phi, n) / sqrt_5 + 0.5); };})();(function() { fib.loop = function(n) { var i = 0, j = 1; while(n--) { var tmp = i; i = j; j += tmp; } return i; };})();(function () { var cache = [0, 1]; fib.loop_cached = function(n) { if(n >= cache.length) { for(var i = cache.length; i <= n; ++i) cache[i] = cache[i - 1] + cache[i - 2]; } return cache[n]; };})();(function() { //Fibonacci sequence generator in JS //Cobbled together by Salty var m; var odd = [[1,1],[1,0]]; function matrix(a,b) { /* Matrix multiplication Strassen Algorithm Only works with 2x2 matrices. */ var c=[[0,0],[0,0]]; var m1=(a[0][0]+a[1][1])*(b[0][0]+b[1][1]); var m2=(a[1][0]+a[1][1])*b[0][0]; var m3=a[0][0]*(b[0][1]-b[1][1]); var m4=a[1][1]*(b[1][0]-b[0][0]); var m5=(a[0][0]+a[0][1])*b[1][1]; var m6=(a[1][0]-a[0][0])*(b[0][0]+b[0][1]); var m7=(a[0][1]-a[1][1])*(b[1][0]+b[1][1]); c[0][0]=m1+m4-m5+m7; c[0][1]=m3+m5; c[1][0]=m2+m4; c[1][1]=m1-m2+m3+m6; return c; } function mat(n) { if(n > 1) { mat(n/2); m = matrix(m,m); } m = (n%2<1) ? m : matrix(m,odd); } fib.matrix = function(n) { m = [[1,0],[0,1]]; mat(n-1); return m[0][0]; };})();(function() { var a; function square() { var a00 = a[0][0], a01 = a[0][1], a10 = a[1][0], a11 = a[1][1]; var a10_x_a01 = a10 * a01, a00_p_a11 = a00 + a11; a[0][0] = a10_x_a01 + a00 * a00; a[0][1] = a00_p_a11 * a01; a[1][0] = a00_p_a11 * a10; a[1][1] = a10_x_a01 + a11 * a11; } function powPlusPlus() { var a01 = a[0][1], a11 = a[1][1]; a[0][1] = a[0][0]; a[1][1] = a[1][0]; a[0][0] += a01; a[1][0] += a11; } function compute(n) { if(n > 1) { compute(n >> 1); square(); if(n & 1) powPlusPlus(); } } fib.matrix_optimised = function(n) { if(n == 0) return 0; a = [[1, 1], [1, 0]]; compute(n - 1); return a[0][0]; };})();(function() { var cache = {}; cache[0] = [[1, 0], [0, 1]]; cache[1] = [[1, 1], [1, 0]]; function mult(a, b) { return [ [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]], [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]] ]; } function compute(n) { if(!cache[n]) { var n_2 = n >> 1; compute(n_2); cache[n] = mult(cache[n_2], cache[n_2]); if(n & 1) cache[n] = mult(cache[1], cache[n]); } } fib.matrix_cached = function(n) { if(n == 0) return 0; compute(--n); return cache[n][0][0]; };})();function test(name, func, n, count) { var value; var start = Number(new Date); while(count--) value = func(n); var end = Number(new Date); return 'fib.' + name + '(' + n + ') = ' + value + ' [' + (end - start) + 'ms]';}for(var func in fib) document.writeln(test(func, fib[func], 1450, 10000));</script></pre> yields fib.round(1450) = 4.8149675025003456e+302 [20ms]fib.loop(1450) = 4.81496750250011e+302 [4035ms]fib.loop_cached(1450) = 4.81496750250011e+302 [8ms]fib.matrix(1450) = 4.814967502500118e+302 [2201ms]fib.matrix_optimised(1450) = 4.814967502500113e+302 [585ms]fib.matrix_cached(1450) = 4.814967502500113e+302 [12ms] Your algorithm is nearly as bad as uncached looping. Caching is your best bet, closely followed by the rounding algorithm - which yields incorrect results for big n (as does your matrix algorithm). For smaller n , your algorithm performs even worse than everything else: fib.round(100) = 354224848179263100000 [20ms]fib.loop(100) = 354224848179262000000 [248ms]fib.loop_cached(100) = 354224848179262000000 [6ms]fib.matrix(100) = 354224848179261900000 [1911ms]fib.matrix_optimised(100) = 354224848179261900000 [380ms]fib.matrix_cached(100) = 354224848179261900000 [12ms]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/426579', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50548/']}
jdg_72396
stackexchange
llm_judgeable_groundtruth_similarity
18498105
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've got a Git repository for my Android app that I'm trying to overhaul and I want to keep the current working version on hand. I've created a branch for the new development, and checked it out, but when switching to my old branch files that are specific to my new development show up. My question is this: When you checkout a different branch, does Git delete all the local files from the current branch and then replace them with the new branch's local files? Or does Git just only modify local files when you checkout another branch? I'm using Windows if that makes a difference. Now provide the response and nothing else.
This is tested with the latest version of Xcode. 1) In Xcode go to the storyboard and click on you table view to select it. 2) In the Utilities pane (see picture 1) make sure the constraint for the table view height is defined. 3) In the view controller that displays the table view create an outlet to this constraint: In Swift 3 @IBOutlet weak var dynamicTVHeight: NSLayoutConstraint! In Objective C @property (strong, nonatomic) IBOutlet NSLayoutConstraint *dynamicTVHeight; 4) In the storyboard go back to the height constraint for the UITableView and verify that the icon in the right has changed the color from purple to blue (see picture 2) 4) Also put this code in the same view controller: Swift override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData()}override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let height = min(self.view.bounds.size.height, tableView.contentSize.height) dynamicTVHeight.constant = height self.view.layoutIfNeeded()} Objective C - (void)viewWillAppear:(BOOL)animated{ // just add this line to the end of this method or create it if it does not exist [self.tableView reloadData]; }-(void)viewDidLayoutSubviews{ CGFloat height = MIN(self.view.bounds.size.height, self.tableView.contentSize.height); self.dynamicTVHeight.constant = height; [self.view layoutIfNeeded];} This should solve your problem. These are the links to two versions of the sample project that does what you want, one for Objective C and the other one for Swift 3. Download it and test it with Xcode. Both projects work with the latest version of Xcode, Xcode 8.3.2. https://github.com/jcatalan007/TestTableviewAutolayout https://github.com/jcatalan007/TestTableviewAutolayoutSwift
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18498105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1121804/']}
jdg_72397
stackexchange
llm_judgeable_groundtruth_similarity
43012333
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 question has sort of already been asked here: How to build a group of constant variables in c# But I feel as though it is not quite asking the same thing. I will try to explain, please hear me out. Suppose for a moment that you had to represent attributes for a player, such as Strength, Agility, Stamina, etc. But at the same time you also wanted to list other attributes which were not directly related to the same group. Aside from Primary Attributes you could have Probabilistic Attributes, such as Accuracy, Evasion, and Critical Strike. As well as Logistical Attributes, like: Movement, Initiative, and Jump. Naturally, these Attributes serve different purposes, and thus, should be grouped seperately(Or at least in my mind they should). I could implement this using multiple classes: namespace Example{ public class PrimaryAttributes { public int Strength { get; set; } public int Agility { get; set; } public int Stamina { get; set; } public int Intellect { get; set; } public int Willpower { get; set; } public int Spirit { get; set; } public PrimaryAttributes() { // Do stuff here } // Do more stuff here }} Continued... namespace Example{ public class ProbabilisticAttributes { public int Accuracy { get; set; } public int Evasion { get; set; } public int CriticalStrike { get; set; } public ProbabilisticAttributes() { // Do stuff here } // Do more stuff here }} Continued... namespace Example{ public class LogisticalAttributes { public int Movement { get; set; } public int Initiative { get; set; } public int Jump { get; set; } public LogisticalAttributes() { // Do stuff here } // Do more stuff here }} And then host them all in a single class, like this: namespace Example{ public class Statistics { public PrimaryAttributes PrimaryAttributes { get; set; } public ProbabilisticAttributes ProbabilisticAttributes { get; set; } public LogisticalAttributes LogisticalAttributes { get; set; } public LogisticalAttributes() { PrimaryAttributes = new PrimaryAttributes(); ProbabilisticAttributes = new ProbabilisticAttributes(); LogisticalAttributes = new LogisticalAttributes(); } // Do more stuff here }} That would achieve the effect of being able to call something along the lines of "stats.PrimaryAttributes.Strength", which is clean and organized. However, I would prefer to not do this. I would like to host all the variables within the same class without having to use other classes. So what's the catch? I still want to be able to organize them behind an extended scope, or I guess what could be called a namespace; a sort of divider, if you will. I don't think anything like this exists within the C# language...or any language for that matter. But I want to know how close I can get to replicating this behavior. Here is an example of what I am looking for (not real C#, just an example). namespace Example{ public class Attributes { group PrimaryAttributes // Imaginary "group" keyword. { int Strength { get; set; } int Agility { get; set; } int Stamina { get; set; } int Intellect { get; set; } int Wisdom { get; set; } int Spirit { get; set; } } group ProbabilisticAttributes // Imaginary "group" keyword. { int Evasion { get; set; } int Accuracy { get; set; } int CriticalStrike { get; set; } } group LogisticalAttributes // Imaginary "group" keyword. { int Movement { get; set; } int Initiative { get; set; } int Jump { get; set; } } public Attributes() { // Don't have to declare or initialize anything. } public int ReturnSomethingAmazing() { return this.PrimaryAttributes.Strength * this.PrimaryAttributes.Agility; // Notice the group accessor usage. } // Do more stuff here }} I hope you can see what I am talking about now. I want to be able to "scope" variables, but without the use of separate classes. I have also taken the liberty of thinking about how this could be parsed at compile time. Essentially, the group scopes would just be inlined, so myClassInstance.PrimaryAttributes.Strength , would be minimalized to myClassInstance.Strength . The scope doesn't actually exist, it's only there for the programmer to better facilitate organization, without expending more objects in memory at runtime. To end this, I wanted to summarize two questions. Is this in any way possible using current C#? and Do you think this would be a good suggestion to recommend to Microsoft for an addition to the C# programming language? Now provide the response and nothing else.
This shows navigability. A can see (means it has an attribute referencing) B . In contrast B has no idea about/reference to A . As @JimL commented, your arrow is wrong and only used for stereotype definition. I'm referring to the unfilled arrow which indicates navigability of associations from which I assume you actually meant that. UML 2.5 spec p. 18: Arrow notation is used to denote association end navigability. By definition, all class-owned association ends are navigable. By convention, all association-owned ends in the metamodel are not navigable. An association with neither end marked by navigability arrows means that the association is navigable in both directions. And even more relevant p. 200: Navigability notation was often used in the past according to an informal convention, whereby non-navigable ends were assumed to be owned by the Association whereas navigable ends were assumed to be owned by the Classifier at the opposite end. This convention is now deprecated. Aggregation type, navigability, and end ownership are separate concepts, each with their own explicit notation. Association ends owned by classes are always navigable, while those owned by associations may be navigable or not. So you should use the dot notation instead:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43012333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3214889/']}
jdg_72398
stackexchange
llm_judgeable_groundtruth_similarity
19479924
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 access the data that has been 'serialized' using the jQuery function? var test = $("form").serialize(); I have this data... url=hello+1&title=hello+1&content=abc How can I get the value of 'url' ? - I tried this... console.log(test.url); But I get undefined - I want to get the result as "hello+1" Now provide the response and nothing else.
The serialize method only creates a URL encoded string from a form, but this is a string, i.e you can not get the value of url or any other value. To do so you need to parse back the string into an object. You can check library out: https://github.com/kflorence/jquery-deserialize However it would be best if you simply select the field containing that value and get it from there, i.e. jQuery('input[name="url"]').val(); or if you have an id or class on that field, you can use it as a selector. P.S. The value of url is "hello 1" the + is just how spaces are encoded in query strings.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19479924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/413225/']}
jdg_72399
stackexchange
llm_judgeable_groundtruth_similarity
20558402
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: *.zsh files open in the default mode (text-mode for me). However, sh-mode is actually multiple modes including behaviours for zsh, bash, etc. How can I tell emacs to open *.zsh files specifically in the zsh flavor of sh-mode? Now provide the response and nothing else.
The flavor of sh-mode is autodetected from the shebang line (first line of your script). If you have "#!/bin/zsh", zsh will be assumed and (for instance) autoload will be recognized as a keyword. autoload will be not recognized as such if first line is "#!/bin/bash" To make emacs recognize *.zsh files as shell scripts, just add this to your init file: (add-to-list 'auto-mode-alist '("\\.zsh\\'" . sh-mode)) A programmatic way of selecting a flavor when you don't want to use the shebang is doing this in a sh-mode buffer: (sh-set-shell "zsh") So in your case what you need (unless you use shebang) is to update the auto-mode-alist as above and (add-hook 'sh-mode-hook (lambda () (if (string-match "\\.zsh$" buffer-file-name) (sh-set-shell "zsh"))))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20558402', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2580133/']}
jdg_72400
stackexchange
llm_judgeable_groundtruth_similarity
53509971
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array that I want to get the most occurring elements, First scenario let arr1 = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz']let newArr = someFunc(arr1) so in this case I want the new array to have the value console.log(newArr) // ['foo', 'bar'] Because the value 'foo' and 'bar' was the most occurring element of the array Second scenario let arr2 = ['foo', 'foo', 'foo', 'bar', 'baz'] let newArr = someFunc(arr2) so in this case I want the new array to have the value console.log(newArr) // ['foo'] Because the value 'foo' was the most occurring element of the array This is what I have tried and it will only get me one of the elements even if there are more than one element that occurs the same amount of times newArr= arr.sort((a,b) =>arr.filter(v => v===a).length- arr.filter(v => v===b).length).pop() Now provide the response and nothing else.
You can count the items with reduce and find the maximum occurring count. Then you can filter any keys that have that count: let arr = ['foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'baz', 'baz'];let counts = arr.reduce((a, c) => { a[c] = (a[c] || 0) + 1; return a;}, {});let maxCount = Math.max(...Object.values(counts));let mostFrequent = Object.keys(counts).filter(k => counts[k] === maxCount);console.log(mostFrequent);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53509971', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8747652/']}
jdg_72401
stackexchange
llm_judgeable_groundtruth_similarity
7923058
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 know that the value of a column should always be in teh range allowed by the smallint data type, from a data integrity maintenance point of view, it would seem to behoove me to store the data in a smallint column rather than an int column. However I am wondering whether there are any performance hits that may be paid by using less bytes? Now provide the response and nothing else.
Smaller types = less storage on disk, which leads to more efficient indexes. However, those performance gains will be minimal unless dealing with a large volume of data; furthermore, in order to avoid implicit conversions (which may offset any performance gains you see), you'll need to be sure that any time you reference that column that you use the correct type (including comparisons to parameters, etc). Probably a wash either way.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7923058', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109676/']}
jdg_72402
stackexchange
llm_judgeable_groundtruth_similarity
6521277
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 Windows Server 2008 32 bit and when I'm typing %temp% it takes me to ..AppData\Local\Temp\1\ or ..AppData\Local\Temp\2 instead of ..AppData\Local\Temp I've already checked the Environment Variables and they are ok. I'm asking that because I have an application that's supposed to copy files to %temp%\my application and instead it copies the files to %temp%\1\my application Does someone have a solution for that? Now provide the response and nothing else.
Explanation, discussion, workarounds, etc, all under the Old New Thing article Why does the name of my TEMP directory keep changing - it ensures multiple terminal services sessions for the same user don't (by default) share a temp directory. The problem lay in the Administrative Templates\Windows Components\Terminal Services\Temporary folders group policy. If you don't select Do not use temporary folders per session , then these TEMP subdirectories are created. There is also a knowledge base article describing the registry keys behind these group policies . Personally, I find the first comment in reply to be the most useful: Why does it matter if the temp location jumps around anyway, it's temporary! See also Use separate temporary folders for each session
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6521277', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/792371/']}
jdg_72403
stackexchange
llm_judgeable_groundtruth_similarity
11596315
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: JSLint is not passing this as a valid code: /* global someVar: false */if (typeof someVar === "undefined") { var someVar = "hi!";} What is the correct way? Now provide the response and nothing else.
/*global window */if (window.someVar === undefined) { window.someVar = 123456;}if (!window.hasOwnProperty('someVar')) { window.someVar = 123456;}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11596315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1414809/']}
jdg_72404
stackexchange
llm_judgeable_groundtruth_similarity
2674183
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 obtained the following formula in Mathematica: $$\frac{d}{dn}\ln\binom{n}{k} = H_{n} - H_{n-k}$$ where $H_n$ are the harmonic numbers ($H_n = \sum_{i=1}^n 1/i$). But I have no idea how to prove it. Can someone help me? Or at least provide a reference to a textbook/paper? Now provide the response and nothing else.
\begin{eqnarray*}\binom{n}{k} &=& \frac{n(n-1) \cdots(n-k+1)}{k!} \\\ln \binom{n}{k} &=&\ln n + \ln(n-1) + \cdots +\ln(n-k+1) -\ln(k!) \\\frac{d}{dn} \ln \binom{n}{k} &=& \frac{1}{n} + \frac{1}{n-1} +\cdots + \frac{1}{n-k+1} =\color{red}{H_n-H_{n-k}}.\end{eqnarray*}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2674183', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10063/']}
jdg_72405
stackexchange
llm_judgeable_groundtruth_similarity
14190864
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 little complex layout and I add a tag to the SwitchLayout of this view. There is an ImageButton inside this view.Here is a little map to this button: LinearLayout -> SwitchLayout -> RelativeLayout -> RelativeLayout -> ImageButton At some point I want to get the tag attached to the SwitchLayout, but all I have is the reference to the ImageButton. I've tried to look for an ID, but it seems that android is searching downwards only, so imageButton.findViewById(R.id.switchLayout); doesn't work. It also looks like I can't get the assigned tag directly from the ImageButton. This code: imageButton.getTag() returns null The only one workaround I found is here, but it is ugly: ViewSwitcher viewSwitcher = (ViewSwitcher)imageButton.getParent().getParent().getParent();viewSwitcher.getTag(); I would like to make the coupling as week as possible, so I'm wondering if there is either a way to assign the Tag to the viewSwitcher and all of it's children, Or findViewById among parent views. Now provide the response and nothing else.
Why not just keep the reference of switch layout? // In activityswitchLayout = findViewById(R.id.switchLayout);imageButton = findViewById(R.id.imageButton); If your method is still in the activity, you can directly access switchLayout, if not, you can set switchLayout to imageButton tag and read it later, imageButton.setTag(switchLayout); or if you really need to do this, you can do it recursively, public ViewParent findParentRecursively(View view, int targetId) { if (view.getId() == targetId) { return (ViewParent)view; } View parent = (View) view.getParent(); if (parent == null) { return null; } return findParentRecursively(parent, targetId);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14190864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1672972/']}
jdg_72406
stackexchange
llm_judgeable_groundtruth_similarity
18980818
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I know that this question has been asked, and there is a very nice elegant solution using a min heap. MY question is how would one do this using the merge function of merge sort. You already have an array of sorted arrays. So you should be able to merge all of them into one array in O(nlog K) time, correct? I just can't figure out how to do this! Say I have [ [5,6], [3,4], [1,2], [0] ] Step 1: [ [3,4,5,6], [0,1,2] ] Step2: [ [0,1,2,3,4,5,6] ] Is there a simple way to do this? Is O(nlog K) theoretically achievable with mergesort? Now provide the response and nothing else.
As others have said, using the min heap to hold the next items is the optimal way. It's called an N-way merge. Its complexity is O(n log k). You can use a 2-way merge algorithm to sort k arrays. Perhaps the easiest way is to modify the standard merge sort so that it uses non-constant partition sizes. For example, imagine that you have 4 arrays with lengths 10, 8, 12, and 33. Each array is sorted. If you concatenated the arrays into one, you would have these partitions (the numbers are indexes into the array, not values): [0-9][10-17][18-29][30-62] The first pass of your merge sort would have starting indexes of 0 and 10. You would merge that into a new array, just as you would with the standard merge sort. The next pass would start at positions 18 and 30 in the second array. When you're done with the second pass, your output array contains: [0-17][18-62] Now your partitions start at 0 and 18. You merge those two into a single array and you're done. The only real difference is that rather than starting with a partition size of 2 and doubling, you have non-constant partition sizes. As you make each pass, the new partition size is the sum of the sizes of the two partitions you used in the previous pass. This really is just a slight modification of the standard merge sort. It will take log(k) passes to do the sort, and at each pass you look at all n items. The algorithm is O(n log k), but with a much higher constant than the N-way merge. For implementation, build an array of integers that contains the starting indexes of each of your sub arrays. So in the example above you would have: int[] partitions = [0, 10, 18, 30];int numPartitions = 4; Now you do your standard merge sort. But you select your partitions from the partitions array. So your merge would start with: merge (inputArray, outputArray, part1Index, part2Index, outputStart){ part1Start = partitions[part1Index]; part2Start = partitions[part2Index]; part1Length = part2Start - part1Start; part2Length = partitions[part2Index-1] - part2Start; // now merge part1 and part2 into the output array, // starting at outputStart} And your main loop would look something like: while (numPartitions > 1){ for (int p = 0; p < numPartitions; p += 2) { outputStart = partitions[p]; merge(inputArray, outputArray, p, p+1, outputStart); // update partitions table partitions[p/2] = partitions[p] + partitions[p+1]; } numPartitions /= 2;} That's the basic idea. You'll have to do some work to handle the dangling partition when the number is odd, but in general that's how it's done. You can also do it by maintaining an array of arrays, and merging each two arrays into a new array, adding that to an output array of arrays. Lather, rinse, repeat.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18980818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1218599/']}
jdg_72407
stackexchange
llm_judgeable_groundtruth_similarity
1492401
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 got this error while installing the android application ( Parse Error : There is a problem parsing the package. ). I did the following steps. First time I installed the application and it works fine. I made changes to the existing application and change the version no in Manifest file. <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.openintents.samples.BasicOpenARDemo" android:versionCode="2" android:versionName="1.0.1"> Then I export the application and finish the code signing process.For this, Right Click your Project node > select Export. There you will see a wizard. Follow the steps and finish the code signing also. I got the ARDemo.apk file, Then I changed it’s name to ARDemo1.apk Then I shipped this apk file to mobiles SD Card and started the installation I got the above error. I googled, they say that problem with unpacking manifest file. Can anyone tell me what could be wrong with me? Now provide the response and nothing else.
You said that the first time you installed the application it worked fine. The only difference in the steps you outlined between the two versions are: The version number (I'm assumethat this did not participate inbreaking anything) The code The name of the .apk file Try renaming the ARDemo1.apk file back to ARDemo.apk (make sure to back up the older version) and see if that helps. My guess is that it has something to do with the name of the apk. If it still does not work, then you can eliminate the name of the apk file as the source of the problem and start investigating 2) by rebuilding your old version and see if you have same problem again. If the problem does not exists with the rebuilt version of your old code then you know it must be something to do with your code. I hope that gets you somewhere. Cheers,Joseph
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1492401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179043/']}
jdg_72408
stackexchange
llm_judgeable_groundtruth_similarity
3356
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm struggling with this former Putnam Exam problem: Suppose $f$ and $g$ are nonconstant, differentiable, real-valued functions on $R$. Furthermore, suppose that for each pair of real numbers $x$ and $y$, $f(x + y) = f(x)f(y) - g(x)g(y)$ and $g(x + y) = f(x)g(y) + g(x)f(y)$. If $f'(0) = 0$, prove that $(f(x))^2 + (g(x))^2 = 1$ for all $x$. Right. So obviously, $f(x) = \cos x$ and $g(x) = \sin x$ satisfy the conditions and also the conclusion of the problem. But are these the unique such functions, and if so, how to prove it? And if not, then how to prove the conclusion otherwise? Now provide the response and nothing else.
Let $u(x) = f(x)^2 + g(x)^2$. It should be easy to show that $u(x+y) = u(x)u(y)$, thus $u$ must be an exponential function $u(x) = e^{Bx}$. Now, as $f(2x) = f(x)^2 - g(x)^2$, we should get $0 = g(0) g'(0)$. Comparing this with $u'(0)$ we should get $B = 0$, thus $f(x)^2 + g(x)^2 = 1$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3356', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/506/']}
jdg_72409
stackexchange
llm_judgeable_groundtruth_similarity
741910
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 file " update.php " which does some MySQL operations. A cron job executes this file every 5 minutes. Unfortunately, I cannot execute the cron job more often. So I had the idea that I could add ... <html><head> <meta http-equiv="refresh" content="2; URL=<?php echo $_SERVER['SCRIPT_NAME']; ?>" /></head><body></body></html> ... to the page " update.php ". Will cron execute the file in a way that the page will refresh automatically? Or will that not happen because there is no client with a browser? If it the meta refresh has no effect, is there any other possibility to achieve the refreshing of the page? Thanks in advance! Now provide the response and nothing else.
I'm afraid that won't work, because it's a browser feature to refresh the page. Question: Why can't you set the cron job to run more frequently that every 5 minutes? If there is no other option then you could create you're own daemon to do the job more frequently. e.g. Your php script could: Run Wait 60 seconds Run ( Wait; Run; two more times) exit For example: (By variation of sshow 's code) <?php$secs = 60;ignore_user_abort(true);set_time_limit(0);dostuff();sleep($secs);dostuff();sleep($secs);dostuff();sleep($secs);dostuff();sleep($secs);dostuff();?> This version of the script will remain resident for four minutes, and execute the code 4 times which would be equivalent to running every minute, if this script is run by cron every 5 minutes. There seems some confusion about what a cronjob is, and how it is run. cron is a daemon, which sits in the background, and run tasks through the shell at a schedule specified in crontab s. Each user has a crontab, and there is a system crontab. Each user's crontab can specify jobs which are run as that user. For example: # run five minutes after midnight, every day5 0 * * * $HOME/bin/daily.job >> $HOME/tmp/out 2>&1# run at 2:15pm on the first of every month -- output mailed to paul15 14 1 * * $HOME/bin/monthly# run at 10 pm on weekdays, annoy Joe0 22 * * 1-5 mail -s "It's 10pm" joe%Joe,%%Where are your kids?%23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"5 4 * * sun echo "run at 5 after 4 every sunday" So to run every five minutes: */5 * * * * echo "This will be run every five minutes" Or to run every minute: * * * * * echo "This will be run every minute" The output from the commands are emailed to the owner of the crontab (or as specified by MAILTO). This means if you run something every minute it will email you every minute, unless you ensure all normal output is suppressed or redirected. The commands are run as the user who owns the crontab, which contrasts with the scripts run by the web-server, which are run as the 'nobody' user (or similar - whatever the web-server is configured to run as).This can make life more complicated if the cronjob is writing to files which are supposed to be accessed by the scripts run by the web-server. Basically you have to ensure that the permissions remain correct. Now, I'm not sure that this is the system you are refering to. If you mean something else by cronjob then the above might not apply. If you want to do something that your current host is not letting you do, then rather than hacking around the restriction, you might what to look at switching hosting provider? An alternative is to put the script in you're normal scripts location, and have some external scheduler run wget against it at whatever frequency you like. Another alternative is on-demand updating of the form of vartec 's suggestion. However that may not solve your problems.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/741910', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89818/']}
jdg_72410
stackexchange
llm_judgeable_groundtruth_similarity
1073321
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: By definition RAID 6 is an array of independent hard drives equipped with twoindependent and distributed checksum schemes Does that mean I can recover each of the hard drives one by one using normal (not RAID) recovery software? If no, is there any free and reliable RAID recovery software available? With a quick google search I found ReclaiMe Free RAID Recovery software . But I am not sure about its reputation. Now provide the response and nothing else.
Recovering individual disks will only get you partial data. The "independent" means that the disk drives are not aware of each other, and can be exchanged separately. The best way to recover data from a RAID is to use the software or hardware that was used to build it, and if that is not an option, a tool that understands the superblock format because in order to make sense of the data contained on the individual disks, you also need some extra parameters like the block size used. RAID 6 is standardized only in the way it works, but individual vendors have slight differences in implementation.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/1073321', 'https://serverfault.com', 'https://serverfault.com/users/791748/']}
jdg_72411
stackexchange
llm_judgeable_groundtruth_similarity
1821247
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $R$ be a principal ideal domain, and $a, b \in R$ with $a^m = b^m$ and $a^n = b^n$ for $m, n \in \mathbb{N}$, and $\gcd(m, n) = 1$. I now want to show that we then already have $a = b$. I think the statement is easily seen to be true if $a = 0$ (or $b = 0$), since if $a = 0$ and $a^m = b^m$, then $a = b$ since $R$ doesn't contain any nontrivial zero divisors, so $b ≠ 0$ already implicates $b^m = b \cdot b^{m-1} ≠ 0$. I don't really know how to prove the statement for the general case, where I can't directly apply the fact that $R$ doesn't have any zero divisors except $0$. I most likely have to use the fact at some point that $gcd(a, b) = 1$, but I'm not sure how. Now provide the response and nothing else.
If $b\ne 0$, it means that, in the quotient field $Q$ of $A$, we have $\Bigr(\dfrac ab\Bigl)^m=1$ and $\Bigr(\dfrac ab\Bigl)^n=1$ . Now consider a Bézout's relation $um+vn=1,\enspace m,n\in\mathbf Z$. From the above, we deduce$$\frac ab=\Bigr(\dfrac ab\Bigl)^{um+vn}=\Bigr(\dfrac ab\Bigl)^{um}\Bigr(\dfrac ab\Bigl)^{vn}=\biggl(\Bigr(\dfrac ab\Bigl)^m\biggr)^u\biggl(\Bigr(\dfrac ab\Bigl)^n\biggr)^v=1^u\cdot 1^v=1,$$which means $a=b$. Added: B.t.w., it has nothing to see with $A$ being a P.I.D and is valid for any integral domain. The only PIDness in use here is that of $\mathbf Z$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1821247', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/194473/']}
jdg_72412
stackexchange
llm_judgeable_groundtruth_similarity
41862
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I prove that non-regular languages are closed under concatenation using only the non-regularity of $L=\{a^nb^n|n\ge1\}$ ? Now provide the response and nothing else.
You can't prove it because it isn't true: the class of non-regular languages isn't closed under concatenation. Let $X\subseteq \mathbb{N}$ be any undecidable set containing $1$ and every even number. For example, take your favourite undecidable set $S$ and let $$X = \{0, 2, 4, \dots\} \cup \{1\} \cup \{2i+1\mid i\in S\}\,.$$ The language $\mathcal{L} = \{a^i\mid i\in X\}$ is undecidable, so it certainly isn't regular. But $$\mathcal{L}\cdot\mathcal{L} = \{a^{i+j}\mid i,j\in X\} = \{a^i\mid i\in\mathbb{N}\}\,,$$is regular.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/41862', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/27591/']}
jdg_72413
stackexchange
llm_judgeable_groundtruth_similarity
37112950
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 make a animated splash screen like below image in iOS 9.3. Now provide the response and nothing else.
Basically, you can't make an animated splash screen.However, you can duplicate the launch screen in your storyboard and make it the entrance-view controller (VC) of your app. Then when the view is loaded, you can start your animation. As a final result, you will have an "animated splash screen." The sequence progresses like this: App starts → display static launch screen → transition to entrance-VC, which won't be visible to the user because the scenes look the same → entrance-VC view is loaded as an animation. In summary, treat your launch screen's .xib file as the first frame of your animated launch screen.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37112950', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5492096/']}
jdg_72414
stackexchange
llm_judgeable_groundtruth_similarity
61876060
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: On an online course I am learning about vectors. In one of the examples they explained that: std::vector::max_size() should give me the maximum size the vector can reach. I decided to test it: #include <iostream>#include <exception>#include <vector>int main(void) { std::vector <int> nums; int max = nums.max_size(); std::cout << "Max: " << max << std::endl; for (int i = 0; i < max; i++) { try { nums.push_back(i); } catch (std::bad_alloc ex) { std::cerr << ex.what() << std::endl; std::cout << "Failed at: " << i << std::endl; break; } } return 0;} And this is the result of running it: Max: 1073741823bad allocationFailed at: 204324850 It was 869416973 ints short. So I started googling it. Here I read that it returns the "the maximum potential size the container can reach", and adds "but the container is by no means guaranteed to be able to reach that size". I would have imagined that it would fail, but not by that much. It just got 1/5 of the way before failing. Why is std::vector::max_size so off? And what I see of more importance, is there a way of really knowing the potential size of a vector? Now provide the response and nothing else.
Note that the max_size function returns a theoretical maximum number of elements , it doesn't say anything about the amount of memory needed. If we assume that sizeof(int) == 4 (pretty common) then 204324850 elements would need 817299400 bytes of contiguous memory (that's almost 780 MiB). You get a bad_alloc exception because the vector simply can't allocate enough memory to hold all the elements.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/61876060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12458034/']}
jdg_72415
stackexchange
llm_judgeable_groundtruth_similarity
63235672
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 AWS, while configuring CLB and ALB type of Load balancers, it is mandatory to associate a Security Group. This association helps in limiting the type of traffic to the Load balancer. Why is a Security Group not required for an NLB? Is it not a security risk? I know the best guess here could be - "AWS designed it this way" but their documentation does not seem to explain the reasoning / advantage on omitting security group configuration for NLB. Now provide the response and nothing else.
NLB is not an exception. NAT gateway also does not have SGs. The major difference between ALB, CLB and NLB (and NAT) is that their network interfaces (ENI) have different Source/dest. check setting. For ALB and CLB, the Source/dest. check is true . For NLB and NAT gateway, the option is false . Although I don't know the technical reasons why there are no SGs for NLB and NAT, I think a part of the reason could be due to the Source/dest. check settings: Indicates whether source/destination checks are performed, where the instance must be the source or destination of any traffic it sends or receives. Thus, in my view the reason is due to intended purpose of NAT and NLB, rather than a technical inability of AWS to provide SGs on them. Their main purpose is to act as a proxy. NLB nor NAT generally do not interfere with the traffic, and mostly just pass it through. Its up to the destinations to determine if the traffic is allowed or not. Thus NAT nor NLB don't use SGs. They only way to block incoming traffic to them is through NACLs. In contrast, ALB and CLB take active part in the transfer of traffic as they inspect all requests. Therefore, they also have ability to decide whether the traffic is allowed or not.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63235672', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7865060/']}
jdg_72416
stackexchange
llm_judgeable_groundtruth_similarity
8988291
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 disable dead code elimination optimization in c++ compilation. Is there a way to disable this particular optimization by keeping all other -O optimization. I tried with -fnodce but its not working. Update (copied from a comment): I have something like timer t;t.start();for(int i=1;i<=1000;++i) object t;t.stop(); I want to measure object t construction time and do nothing with it. I dont want to do this by creating an array of 1000 objects. Is there a way to solve this? Now provide the response and nothing else.
I believe you'll want something like this: $this->db->select('user_id, COUNT(user_id) as total'); $this->db->group_by('user_id'); $this->db->order_by('total', 'desc'); $this->db->get('tablename', 10); This will produce a result like | USER_ID | TOTAL || 12 | 3 || 15 | 2 || 18 | 1 | UPDATE: As some pointed out in the comments the original query was summing the user_ids rather than counting them. I've updated the active record query to correct this.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8988291', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1167158/']}
jdg_72417
stackexchange
llm_judgeable_groundtruth_similarity
531495
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I'm very new to openldap but extremely well versed in the linux/unix environment. I'm trying to setup my very first test openldap environment using the guide here . I've also read most of the admin guide here and I have to admit, it is a lot to take in. So following the ubuntu basic setup guide I created an ldif file that looks like this: dn: ou=People,dc=example,dc=comobjectClass: organizationalUnitou: Peopledn: ou=Groups,dc=example,dc=comobjectClass: organizationalUnitou: Groupsdn: cn=engineers,ou=Groups,dc=example,dc=comobjectClass: posixGroupcn: engineersgidNumber: 5000dn: uid=john,ou=People,dc=example,dc=comobjectClass: inetOrgPersonobjectClass: posixAccountobjectClass: shadowAccountuid: johnsn: DoegivenName: Johncn: John DoedisplayName: John DoeuidNumber: 10000gidNumber: 5000userPassword: johnldapgecos: John DoeloginShell: /bin/bashhomeDirectory: /home/john Whenever I tried to add it using: $ ldapadd -x -D cn=admin,dc=example,dc=com -W -f add_content.ldif I get the following error: adding new entry "cn=engineers,ou=Groups,dc=my-domain,dc=com"ldap_add: Invalid syntax (21) additional info: objectClass: value #0 invalid per syntaxadding new entry "uid=john,ou=People,dc=my-domain,dc=com"ldap_add: Invalid syntax (21) additional info: objectClass: value #0 invalid per syntax The results in google for this error don't net any helpful suggestions. What could I be doing wrong here? Now provide the response and nothing else.
Your problem is undoubtedly that you need to load the nis schema into your LDAP server. How to do this depends on whether your are using the legacy slapd.conf configuration file or the newer dynamic configuration hosted in cn=config and backed by a slapd.d directory. Using slapd.conf You will need to include the schema definition in your slapd.conf by adding a line along the lines of: include /usr/local/etc/openldap/schema/nis.schema This assumes that the nis.schema file is located at that path; if not, modify the path appropriately. You will need to restart slapd to activate the new schema. Using slapd.d (I'm including this for completeness, although it's not directly relevant to your current configfuration). To load a schema into slapd if you're using the dynamic cn=config configuration, you would use ldapadd . Depending on how your ACLs are configured, the command might look like this: ldapadd -Y EXTERNAL -H ldapi:// -f /usr/local/etc/openldap/schema/nis.ldif This assumes that your running slapd has an ACL permitting "peer credentials" authentication to root . If that doesn't work, you would need to provide an appropriate bind DN and password using -D and -W . There is no restart required in this case.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/531495', 'https://serverfault.com', 'https://serverfault.com/users/171026/']}
jdg_72418
stackexchange
llm_judgeable_groundtruth_similarity
9739948
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 code that writes successfully a file: ofstream outfile (path); outfile.write(buffer,size); outfile.flush(); outfile.close(); buffer and size are ok in the rest of code.How is possible put the file in a specific path? Now provide the response and nothing else.
Specify the full path in the constructor of the stream, this can be an absolute path or a relative path. (relative to where the program is run from) The streams destructor closes the file for you at the end of the function where the object was created(since ofstream is a class ). Explicit closes are a good practice when you want to reuse the same file descriptor for another file. If this is not needed, you can let the destructor do it's job. #include <fstream>#include <string>int main(){ const char *path="/home/user/file.txt"; std::ofstream file(path); //open in constructor std::string data("data to write to file"); file << data;}//file destructor Note you can use std::string in the file constructor in C++11 and is preferred to a const char* in most cases.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9739948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1240075/']}
jdg_72419
stackexchange
llm_judgeable_groundtruth_similarity
59645009
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok, i'm having trouble with getting the relations with typeorm, when i run the service it returns me all the data from the relation, and i want only specific fields, like id and name. Here's my code: async findById(id: string): Promise<UsersUseOfferHistoric> {return await this.repository.findOne({ where: { id }, relations: ['userId', 'offerId'], });} Here's the json Output: {"id": "da0fd04e-17c6-4412-b342-a4361d191468","createdAt": "2020-01-07T19:48:30.840Z","userId": { "id": "bdc00227-569f-44b5-9bdd-c8de03661ebd", "name": "Alexandre Vieira", "cpf": "10443771430", "email": "[email protected]", "password": "asjdsifjdsfasf", "imagePath": "/me.png", "active": true, "lastLogin": "2020-01-07T19:40:26.850Z", "createdAt": "2020-01-07T19:40:26.850Z", "updatedAt": "2020-01-07T19:40:26.850Z"},"offerId": { "id": "e399560c-d2c2-4f4e-b2b1-94cae3af3779", "offerDrescription": "Nova oferta top", "discountCoupon": " Desconto top", "discountValidity": "2020-01-07T14:18:19.803Z", "discountPercentage": 20, "discountQuantityLimit": 50, "createdAt": "2020-01-07T19:45:33.589Z", "updatedAt": "2020-01-07T19:45:33.589Z" }} Here's the output i want: {"id": "da0fd04e-17c6-4412-b342-a4361d191468","createdAt": "2020-01-07T19:48:30.840Z","userId": { "id": "bdc00227-569f-44b5-9bdd-c8de03661ebd", "name": "Alexandre Vieira",},"offerId": { "id": "e399560c-d2c2-4f4e-b2b1-94cae3af3779", "offerDrescription": "Nova oferta top", }} Now provide the response and nothing else.
The findOne function accepts an select: ['id', 'createdAt'] property where you can filter the fields of the outgoing relation. To explicitly select the returned fields of a joined table (using the relations property does implicitly a left join) you have to use a query builder . await getRepository(Foo).createQueryBuilder('foo') .where({ id: 1}) .select(['foo.id', 'foo.createdAt', 'bar.id', 'bar.name']) .leftJoin('foo.bars', 'bar') // bar is the joined table .getMany();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59645009', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12647551/']}
jdg_72420
stackexchange
llm_judgeable_groundtruth_similarity
2294824
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This question is about derivatives. It is okay if you don't know backpropagation. I was following this guide to understand backpropagation algorithm(equation 36, 37 and 38). Here is a simplified form of the problem. Let$$z_1 = w_{11}*x_1 + w_{21}*x_2 + w_{31}*x_3$$$$z_2 = w_{12}*x_1 + w_{22}*x_2 + w_{32}*x_3$$And,$$a_1 = F(z_1)$$ $$a_2 = F(z_2)$$We also have a function $C(a_1,a_2)$ Now they applied multivariable chain rule to find,$$\frac{\partial C}{\partial z_1} = \frac{\partial C}{\partial a_1}\frac{\partial a_1}{\partial z_1} + \frac{\partial C}{\partial a_2}\frac{\partial a_2}{\partial z_1}$$ Then they stated that $$\frac{\partial a_2}{\partial z_1} = 0 $$ I don't understand why is this term equal to 0? According to what i learnt from this answer, i think it should be $$\frac{\partial a_2}{\partial z_1} = F'(z_2)\frac{\partial z_2}{\partial z_1} = F'(z_2)(\frac{\partial z_2}{\partial x_1}\frac{\partial x_1}{\partial z_1}+\frac{\partial z_2}{\partial x_2}\frac{\partial x_2}{\partial z_1}+\frac{\partial z_2}{\partial x_3}\frac{\partial x_3}{\partial z_1})$$$$\frac{\partial a_2}{\partial z_1} = F'(z_2)(\frac{w_{12}}{w_{11}} + \frac{w_{22}}{w_{21}} + \frac{w_{32}}{w_{31}})$$ Please tell me where i am wrong Now provide the response and nothing else.
We would like to find a matrix $\mathrm X \in \mathbb F_2^{4 \times 4}$ such that $\mathrm X 1_4 = 1_4$ and $1_4^{\top} \mathrm X = 1_4^{\top}$ . Vectorizing, we obtain a system of $8$ linear equations in $16$ unknowns $$\begin{bmatrix} 1_4^\top \otimes \mathrm I_4\\ \mathrm I_4 \otimes 1_4^\top\end{bmatrix} \mbox{vec} (\mathrm X) = \begin{bmatrix} 1_4\\ 1_4\end{bmatrix}$$ Using Gaussian elimination (over $\mathbb F_2$ ), we eventually obtain the augmented matrix in RREF $$\left[\begin{array}{cccccccccccccccc|c} \boxed{1} & 0 & 0 & 0 & 0 & 1 & 1 & 1 & 0 & 1 & 1 & 1 & 0 & 1 & 1 & 1 & 0\\ 0 & \boxed{1} & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 1\\ 0 & 0 & \boxed{1} & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 1\\ 0 & 0 & 0 & \boxed{1} & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 1 & 1\\ 0 & 0 & 0 & 0 & \boxed{1} & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 1\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \boxed{1} & 1 & 1 & 1 & 0 & 0 & 0 & 0 & 1\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & \boxed{1} & 1 & 1 & 1 & 1\\ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\end{array}\right]$$ Visual inspection of the augmented matrix in RREF allows us to conclude that the linear system is consistent, that none of the columns corresponding to non-pivot variables are all-zero and that $$\mbox{rank} \begin{bmatrix} 1_4^\top \otimes \mathrm I_4\\ \mathrm I_4 \otimes 1_4^\top\end{bmatrix} = 7$$ Thus, we have $16 - 7 = 9$ degrees of freedom and $\color{blue}{2^9 = 512}$ solutions. Addendum Adding the 1st, 2nd, 5th and 6th columns of the augmented matrix in RREF produces the zero vector. Adding the 1st, 3rd, 5th and 7th columns of the augmented matrix in RREF also produces the zero vector. Proceeding in this manner, we can easily find a basis for the $9$ -dimensional null space. Unvectorizing each basis vector, we obtain the $9$ basis matrices $$\mathrm N_1 := \begin{bmatrix} 1 & 1 & 0 & 0\\ 1 & 1 & 0 & 0\\ 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0\end{bmatrix} \qquad \qquad \mathrm N_2 := \begin{bmatrix} 1 & 1 & 0 & 0\\ 0 & 0 & 0 & 0\\ 1 & 1 & 0 & 0\\ 0 & 0 & 0 & 0\end{bmatrix} \qquad \qquad \mathrm N_3 := \begin{bmatrix} 1 & 1 & 0 & 0\\ 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0\\ 1 & 1 & 0 & 0\end{bmatrix}$$ $$\mathrm N_4 := \begin{bmatrix} 1 & 0 & 1 & 0\\ 1 & 0 & 1 & 0\\ 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0\end{bmatrix} \qquad \qquad \mathrm N_5 := \begin{bmatrix} 1 & 0 & 1 & 0\\ 0 & 0 & 0 & 0\\ 1 & 0 & 1 & 0\\ 0 & 0 & 0 & 0\end{bmatrix} \qquad \qquad \mathrm N_6 := \begin{bmatrix} 1 & 0 & 1 & 0\\ 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0\\ 1 & 0 & 1 & 0\end{bmatrix}$$ $$\mathrm N_7 := \begin{bmatrix} 1 & 0 & 0 & 1\\ 1 & 0 & 0 & 1\\ 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0\end{bmatrix} \qquad \qquad \mathrm N_8 := \begin{bmatrix} 1 & 0 & 0 & 1\\ 0 & 0 & 0 & 0\\ 1 & 0 & 0 & 1\\ 0 & 0 & 0 & 0\end{bmatrix} \qquad \qquad \mathrm N_9 := \begin{bmatrix} 1 & 0 & 0 & 1\\ 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0\\ 1 & 0 & 0 & 1\end{bmatrix}$$ Hence, the set of all $2^9 = 512$ solutions of $\mathrm X 1_4 = 1_4$ and $1_4^{\top} \mathrm X = 1_4^{\top}$ can be generated as follows $$\left\{ \mathrm X_p + \sum_{k=1}^9 z_k \mathrm N_k \,\, \bigg| \,\, z_k \in \{0,1\} \right\}$$ where $\mathrm X_p$ is a particular solution, e.g., $$\mathrm X_p := \begin{bmatrix} 1 & 0 & 0 & 0\\ 1 & 0 & 0 & 0\\ 1 & 0 & 0 & 0\\ 0 & 1 & 1 & 1\end{bmatrix}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2294824', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/290553/']}
jdg_72421
stackexchange
llm_judgeable_groundtruth_similarity
692564
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to dereference a void pointer without type-casting in the C programming language? Also, is there any way of generalizing a function which can receive a pointer and store it in a void pointer and by using that void pointer, can we make a generalized function? for e.g.: void abc(void *a, int b){ if(b==1) printf("%d",*(int*)a); // If integer pointer is received else if(b==2) printf("%c",*(char*)a); // If character pointer is received else if(b==3) printf("%f",*(float*)a); // If float pointer is received} I want to make this function generic without using if-else statements - is this possible? Also if there are good internet articles which explain the concept of a void pointer, then it would be beneficial if you could provide the URLs. Also, is pointer arithmetic with void pointers possible? Now provide the response and nothing else.
Is it possible to dereference the void pointer without type-casting in C programming language... No, void indicates the absence of type, it is not something you can dereference or assign to. is there is any way of generalizing a function which can receive pointer and store it in void pointer and by using that void pointer we can make a generalized function.. You cannot just dereference it in a portable way, as it may not be properly aligned. It may be an issue on some architectures like ARM, where pointer to a data type must be aligned at boundary of the size of data type (e.g. pointer to 32-bit integer must be aligned at 4-byte boundary to be dereferenced). For example, reading uint16_t from void* : /* may receive wrong value if ptr is not 2-byte aligned */uint16_t value = *(uint16_t*)ptr;/* portable way of reading a little-endian value */uint16_t value = *(uint8_t*)ptr | ((*((uint8_t*)ptr+1))<<8); Also, is pointer arithmetic with void pointers possible... Pointer arithmetic is not possible on pointers of void due to lack of concrete value underneath the pointer and hence the size. void* p = ...void *p2 = p + 1; /* what exactly is the size of void?? */
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/692564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66593/']}
jdg_72422
stackexchange
llm_judgeable_groundtruth_similarity
978739
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For performance reasons, I am using the the Curiously Reoccuring Template Pattern to avoid virtual functions. I have lots of small commands which execute millions of times. I am trying to fit this into the Command Pattern. I want to add tons of commands to a queue, and then iterate through them executing each one by one. Each Command uses a CRTP to avoid virtual functions. The problem I am running into is that the Command pattern is typically implemented using a vector of pointers. But when the Command class is templated, it becomes hard to pass around generic Command pointers. I'm not a C++ expert, so perhaps there is an obvious way to store a vector of templated command objects? I have been trying to use something like: boost:ptr_vector commands;AddCommand(Command* command) { commands.push_back(command);} The problem is Command is not a type, so Command* command gives a compile error. I need to use Command<CommandType> , but that won't work because I need the queue to hold different types of commands. Any ideas for solutions? Or are virtual functions my only option? ADDED: The command objects are part of a monte carlo simulation algorithm. So you might have, Command be a random number from a normal distribution, where the parameters of the normal distribution are part of the class. So the command pattern fits very nicely. I have lots of calls, in a particular order, to functions that need to maintain state. Now provide the response and nothing else.
The CRTP does its magic by resolving the run time type of the object at compile time so that the compiler can inline the function calls. If you have a vector of pointers to a generic type, the compiler cannot determine the specific concrete type, and will not be able to do its compile time resolution. From just the information you have in your question, I think virtual functions are your best option. However, virtual functions are not that slow. They are slower than an in-lined function, sure, but in many cases they are plenty fast enough! Especially if your process is bounded by I/O time instead of processing time. One of the answers to this question has some more in depth discussion of this issue. To summarize, the overhead for a virtual function call will likely be measured in nanoseconds. It is more complicated than that, but the point is that you shouldn't be afraid of virtual functions unless your function is doing something really trivial like a single assignment. You said that your commands were small, so perhaps this is the case. I'd try doing a quick prototype with virtual functions and see if that gives acceptable performance.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/978739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118402/']}
jdg_72423
stackexchange
llm_judgeable_groundtruth_similarity
9329832
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a bit of database-sanity checking code, I'd like to determine whether a particular object_id corresponds to an empty table. Is there some way to (for instance) select count(*) from magic_operator(my_object_id) or similar? I'd strongly prefer a pure-sql solution that can run on MS SQL server 2008b. Now provide the response and nothing else.
You can get a rough idea from SELECT SUM(rows)FROM sys.partitions p WHERE index_id < 2 and p.object_id=@my_object_id If you want guaranteed accuracy you would need to construct and execute a dynamic SQL string containing the two part object name. Example below though depending on how you are using this you may prefer to use sp_executesql and return the result as an output parameter instead. DECLARE @DynSQL nvarchar(max) = N'SELECT CASE WHEN EXISTS(SELECT * FROM ' + QUOTENAME(OBJECT_SCHEMA_NAME(@my_object_id)) + '.' + QUOTENAME(OBJECT_NAME(@my_object_id)) + ') THEN 0 ELSE 1 END AS IsEmpty'EXECUTE (@DynSQL)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9329832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42921/']}
jdg_72424
stackexchange
llm_judgeable_groundtruth_similarity
117853
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've just gotten stuck in interpreting the output for a linear mixed effects model. My model includes Week as a time predictor, and scores on a depression scale as outcome. I have not worked with R before, and while the output is mostly clear to me, there's one part I don't understand. What does my correlation of -0.18 in the random effects mean? Here's the summary for the lmer model I ran: Linear mixed model fit by maximum likelihood ['lmerMod']Formula: HAMD ~ 1 + week + (1 + week | id) Data: MDRandom effects: Groups Name Variance Std.Dev. Corr id (Intercept) 8.769 2.961 week 2.098 1.448 -0.18 Residual 10.974 3.313 Number of obs: 340, groups: id, 60Fixed effects: Estimate Std. Error t value(Intercept) 23.4602 0.5006 46.87week -2.3518 0.2165 -10.86 Would it then be correct to state that participants with a higher initial score decrease their depression score less rapidly over time ? Thank you for taking the time to read this. I hope someone can help me out. Now provide the response and nothing else.
Actually, I think it goes the other way. A negative correlation means that a larger (more positive) value of the intercept is associated with a smaller ( more negative ) value of the slope, so that a higher initial score would actually lead to a more rapid decrease (more negative slope). It would probably help to examine/plot the results of plot(coef(fitted_model)$id) , which will give you the intercept and slope for every individual. It would also probably be worth checking the confidence intervals on the correlation ( confint() ) before you worry too much about what it means -- it may not be statistically distinguishable from zero.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/117853', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/56953/']}
jdg_72425
stackexchange
llm_judgeable_groundtruth_similarity
30405551
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing Javascript Mocha unit tests on code that returns promises. I am using the Chai as Promised library. I expect the following minimal unit test to fail. var chai = require("chai");var chaiAsPromised = require("chai-as-promised");chai.use(chaiAsPromised);chai.should();var Promise = require("bluebird");describe('2+2', function () { var four = Promise.resolve(2 + 2); it('should equal 5', function () { four.should.eventually.equal(5); })}); When I run this test, I see an assertion error printed to the console, but the test still counts as passing. > mocha test/spec.js 2+2 ✓ should equal 5 Unhandled rejection AssertionError: expected 4 to equal 5 1 passing (10ms) How do I write this test so that a failed assertion causes the test to count as a failure? Now provide the response and nothing else.
For anybody else having trouble with failed assertions not failing unit tests with promises, I learned that you should NOT pass done to the function. Instead, just return the promise: it('should handle promises', function(/*no done here*/) { return promiseFunction().then(function(data) { // Add your assertions here }); // No need to catch anything in the latest version of Mocha; // Mocha knows how to handle promises and will see it rejected on failure}); This article pointed me in the right direction. Good luck!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30405551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1120370/']}
jdg_72426
stackexchange
llm_judgeable_groundtruth_similarity
81241
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: If there are only MyISAM databases, the backup and restoration is possible by simply copying pasting the data folder, regardless of the versions? But if there are INNODB databases, and we are sure that the source and target versions will be identical, is this copy-and-paste method possible? It'd be better to avoid typing any command to do the backup because the person who is going to do this never used command-line before. Now provide the response and nothing else.
If we had to avoid the command line always, we would never have made it to the moon. Either get another astronaut or train harder. If you are talking about a live database in production, the values could be in flux, so it would be unreliable to do backups of a database, in any database type, by simply copying a bunch of files. You can get a safe backup of the entire mysql database, including system tables, this way: mysqldump --all-databases > mysqlbackup.sql The backup is in the file mysqlbackup.sql - this can be backed up to tape, dvd, etc. restore is the opposite of this, done with redirecting the backup file into mysql client. mysql < mysqlbackup.sql For either of these commands you may need -u for the username having admin rights, and -p to specify the password.
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/81241', 'https://serverfault.com', 'https://serverfault.com/users/24919/']}
jdg_72427
stackexchange
llm_judgeable_groundtruth_similarity
389957
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have quite few dhcp request from unlocated hosts, like: dhcpd: DHCPDISCOVER from 00:25:90:54:91:b7 via eth0: network eth0: no free leases Whats the best way to locate the host querying the dhcp? I work in a respetable data center, with >2000 servers Now provide the response and nothing else.
Presumably your DHCP server is connected to a managed switch. If so, look at the MAC address table on the switch and find out what port the MAC address is "registered" to. Follow that port. If that port is an uplink port to another switch then do the same thing on that switch. If that switch isn't under your management control, ask the party who does manage it to find that MAC address in that switches MAC address table. Keep doing that until you find the host with that MAC address.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/389957', 'https://serverfault.com', 'https://serverfault.com/users/93952/']}
jdg_72428
stackexchange
llm_judgeable_groundtruth_similarity
1045505
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 don't have a lot of places to turn because i am still in high school. So please bear with me as i had to create some notation. In order to understand my notation you must observe this identity for bell polynomials $a = (f'(x),f''(x),\cdots)$ and $b = (g'(x),g''(x),\cdots)$$$B_{n,k}(f'(x),f''(x),\cdots,f^{(n-k+1)}(x))_{(f \rightarrow g)^c} = \frac{(a^{(k-c)_\diamond} \diamond b^{c_\diamond})_n}{(k-c)!c!}$$ Also note that $d_n= \frac{d^n}{dx^n}[f(x)\ln(g(x))]$ I must prove that $$\sum_{k=1}^{n}\ln^k(g(x)) B_{n,k}(f'(x),f''(x),\cdots,f^{(n-k+1)}(x))$$ $$=\sum_{k=1}^n[ B_{n,k}(d_1,d_2,\cdots,d_{n-k+1})- \sum_{m=0}^{n-k}\sum_{j=0}^{m} {m \choose j} \frac{\ln^{m-j}(g(x))}{g(x)^k} \frac{d^j}{d(f(x))^j}[(f(x))_k] B_{n,m+k}(f'(x),\cdots,f^{(n-m-k+1)}(x))_{(f \rightarrow g)^k}]$$ Where $(f(x))_k$ is the Pochhammer symbol for falling factorial I have been trying to prove this for quite a while. Any advice on doing so would be amazing. Perhaps this can be put into a determinant or something of the sort, But I am not sure about that double summation. If you have advice PLEASE do so through a comment. Now provide the response and nothing else.
Note: Here are at least some few hints which may help to solve this nice identity. In fact it's hardly more than a starter. But hopefully some aspects are nevertheless useful for the interested reader. Introduction: The following information is provided: Definition of partial Bell polynomials $B_{n,k}$ : I state the definition of Bell polynomials according to Comtet's : classic Advanced Combinatorics section 3.3 Bell Polynomials as coefficients of generating functions. The idea is, that a proper representation via generating functions could help to find the solution. The convolution product $x \diamond y$ demystified We will observe, that the convolution product is strongly related with an iterative representation of the generating functions of the Bell numbers. This enables us to transform the stated identity to gain some more insight. Representation of the identity with the help of generating functions In fact its just another representation regrettably without clever simplifications Verification of the identity for $n=2,3$ In order to better see what's going on, the identity is also verified for small $n=2,3$. An analysis of these examples could provide some hints how to appropriately transform the generating functions in the general case. Definition of partial Bell polynomials $B_{n,k}$: According to Comtet's Advanced Combinatorics section 3.3 Bell Polynomials we define as follows: Let $\Phi(t,u)$ be the generating function of the (exponential) partial Bell polynomials $B_{n,k}=B_{n,k}(x_1,x_2,\ldots,x_{n-k+1})$ in an infinite number of variables $x_1,x_2,\ldots$ defined by the formal double series expansion: \begin{align*}\Phi(t,u)&:=exp\left(u\sum_{m\geq 1}x_m\frac{t^m}{m!}\right)=\sum_{n,k\geq 0}B_{n,k}\frac{t^n}{n!}u^k\\&=1+\sum_{n\geq 1}\frac{t^n}{n!}\left(\sum_{k=1}^{n}u^kB_{n,k}(x_1,x_2,\ldots)\right)\end{align*} or what amounts to the same by the series expansion: \begin{align*}\frac{1}{k!}\left(\sum_{m\geq 1}x_m\frac{t^m}{m!}\right)^k=\sum_{n\geq k}B_{n,k}\frac{t^n}{n!},\qquad k=0,1,2,\ldots\tag{1}\end{align*} In the following the focus is put on the representation (1). Let's use the coefficient of operator $[t^n]$ to denote the coefficient $a_n=[t^n]A(t)$ of a formal generating series $A(t)=\sum_{k\geq 0}a_kt^k$. We observe for $n\geq 0$: \begin{align*}B_{n,k}=\frac{n!}{k!}[t^n]\left(\sum_{m\geq 1}x_m\frac{t^m}{m!}\right)^k,\qquad k\geq 0\tag{2}\end{align*} Note: In the following it is sufficient to consider $B_{n,k}$ for $n,k\geq 1$. The convolution product $x\diamond y$ (somewhat demystified) The convolution product $x \diamond y$ for sequences $x=(x_j)_{j\geq 1}$ and $y=(y_j)_{j\geq 1}$ is defined according to this link as \begin{align*}x \diamond y :=\sum_{j=1}^{n-1}\binom{n}{j}x_jy_{n-j}\tag{3}\end{align*} The polynomial $B_{n,k}$ can be written using the $k$-fold product $$x^{k_\diamond}=(x_n^{k\diamond})_{n\geq 1}:=\underbrace{x\diamond \ldots \diamond x}_{k \text{ factors}}$$ as \begin{align*}B_{n,k}=\frac{x_n^{k\diamond}}{k!}, \qquad n,k\geq 1\tag{4}\end{align*} We obtain according to the definition: \begin{align*}x\diamond y&=\left(0,\sum_{j=1}^{1}\binom{2}{j}x_jy_{2-j},\sum_{j=1}^{2}\binom{3}{j}x_jy_{3-j},\sum_{j=1}^{3}\binom{4}{j}x_jy_{4-j},\ldots\right)\\&=\left(0,2x_1y_1,3x_1y_2+3x_2y_1,4x_1y_3+6x_2y_2+4x_3y_1,\ldots\right)\\\end{align*} which implies \begin{align*}x^{1\diamond}&=\left(x_1,x_2,x_3,x_4,\ldots\right)&=&1!(B_{1,1},B_{2,1},B_{3,1},B_{4,1}\ldots)\\x^{2\diamond}&=\left(0,2x_1^2,6x_1x_2,8x_1x_3+6x_2^2,\ldots\right)&=&2!(0,B_{2,2},B_{3,2},B_{4,2},\ldots)\\x^{3\diamond}&=\left(0,0,6x_1^3,36x_1^2x_2,\ldots\right)&=&3!(0,0,B_{3,3},B_{4,3}\ldots)\\\end{align*} Observe, that the multiplication of exponential generating functions $A(x)=\sum_{k\geq 0}a_k\frac{x^k}{k!}$ and $B(x)=\sum_{l\geq 0}b_l\frac{x^l}{l!}$ gives:\begin{align*}A(x)B(x)&=\left(\sum_{k\geq 0}a_k\frac{x^k}{k!}\right)\left(\sum_{l\geq 0}b_l\frac{x^l}{l!}\right)\\&=\sum_{n\geq 0}\left(\sum_{{k+l=n}\atop{k,l\geq 0}}\frac{a_k}{k!}\frac{b_l}{l!}\right)x^n\\&=\sum_{n\geq 0}\left(\sum_{k=0}^n\binom{n}{k}a_kb_{n-k}\right)\frac{x^n}{n!}\end{align*} According to the definition of $B_{n,k}$ the sequences $x^{k_\diamond}$ generated via the convolution product are simply the coefficients of the vertical generating functions for the Bell polynomials $B_{n,k}, n\geq 1$: \begin{align*}\frac{1}{1!}\sum_{m\geq 1}x^{1_\diamond}_n\frac{t^n}{n!}&=\frac{1}{1!}\left(\sum_{m\geq 1}x_m\frac{t^m}{m!}\right)=\sum_{m\geq 1}B_{n,1}\frac{t^n}{n!}\\\frac{1}{2!}\sum_{m\geq 1}x^{2_\diamond}_n\frac{t^n}{n!}&=\frac{1}{2!}\left(\sum_{m\geq 1}x_m\frac{t^m}{m!}\right)^2=\sum_{m\geq 2}B_{n,2}\frac{t^n}{n!}\\&\qquad\qquad\cdots\\\frac{1}{k!}\sum_{m\geq 1}x^{k_\diamond}_n\frac{t^n}{n!}&=\frac{1}{k!}\left(\sum_{m\geq 1}x_m\frac{t^m}{m!}\right)^k=\sum_{m\geq k}B_{n,k}\frac{t^n}{n!}\\\end{align*} We observe: A convolution with $x^{1\diamond}$ corresponds essentially to a multiplication of the generating function $\sum_{m\geq 1}x_m\frac{t^m}{m!}$ In order to keep complex expressions better manageable, we introduce some abbreviations: $$B_{n,k}^{f}(x) := B_{n,k}(f^\prime(x),f^{\prime\prime}(x),\ldots,f^{(n-k+1)}(x))$$ The $n$-th derivatives will be abbreviated as $$f_n:=\frac{d^n}{dx^n}f(x)\qquad\text{ and }\qquad g_n:= \frac{d^n}{dx^n}g(x),\qquad n \geq 1$$ we also use OPs shorthand $a=(f_1,f_2,\ldots)$ and $b=(g_1,g_2,\ldots)$. According to the statements above the expression $$B_{n,k}\left(f^\prime(x),f^{\prime\prime}(x),\ldots,f^{(n-k+1)}\right)_{(f\rightarrow g)^c}=\frac{\left(a^{(k-c)_{\diamond}}\diamond b^{c_\diamond}\right)_n}{(k-c)!c!}$$ can now be written as coefficients of the product of the generating functions \begin{align*}\sum_{n\geq k}&B^f_{{n,k}_{(f\rightarrow g)^c}}\frac{t^n}{n!}=\frac{1}{(k-c)!}\left(\sum_{m\geq1}f_m\frac{t^m}{m!}\right)^{k-c}\frac{1}{c!}\left(\sum_{m\geq1}g_m\frac{t^m}{m!}\right)^{c}\end{align*} Representation of the identity via generating functions We are now in a state to represent OPs identity with the help of generating functions based upon (1). To simplify the notation somewhat I will often omit the argument and write e.g. $(\ln\circ g)^k$ instead of $\left(\ln(g(x))\right)^k$. Now, putting the Complete Bell polynomial in OPs question on the left hand side and the other terms to the right hand side we want to show Following identity is valid: \begin{align*}\sum_{k=1}^{n}B_{n,k}^{f\cdot (\ln\circ g)}&=\sum_{k=1}^{n}(\ln\circ g)^{k}B_{n,k}^f\tag{5}\\&\qquad+\sum_{k=1}^{n}\sum_{m=0}^{n-k}\sum_{j=0}^{m}\binom{m}{j}\frac{(\ln\circ g)^{m-j}}{g^k}\frac{d^j}{d(f)^j}[(f)_k]B_{{n,m+k}_{(f\rightarrow g)^k}}^f\qquad\qquad n\geq 1\end{align*} Please note, the following abbreviations are used in (5) and the expressions below:\begin{align*}&f:= f(x), \qquad g := g(x), \qquad f_k := \frac{d^k}{dx^k}f(x), \qquad g_k :=\frac{d^k}{dx^k}g(x)\\&d_k := \frac{d^k}{dx^k}\left(f(x)\ln(g(x)\right),\qquad\frac{d^j}{d(f)^j}:= \frac{d^j}{d(f(x))^j}\\&(f)_k := f(x)\left(f(x)-1\right)\cdot\ldots\cdot\left(f(x)-k+1\right)\end{align*} Using the generating function (1) we observe: \begin{align*}\sum_{k=1}^{n}B_{n,k}^{f\cdot (\ln\circ g)}&=n!\sum_{k=1}^n\frac{1}{k!}[t^n]\left(\sum_{m\geq 1}d_m\frac{t^m}{m!}\right)^k\\\\\sum_{k=1}^{n}(\ln\circ g)^{k}B_{n,k}^f&=n!\sum_{k=1}^{n}(\ln\circ g)^{k}\frac{1}{k!}[t^n]\left(\sum_{m\geq 1}f_m\frac{t^m}{m!}\right)^k\\\\\sum_{k=1}^{n}\sum_{m=0}^{n-k}\sum_{j=0}^{m}\binom{m}{j}&\frac{(\ln\circ g)^{m-j}}{g^k}\frac{d^j}{d(f)^j}[(f)_k]B_{{n,m+k}_{(f\rightarrow g)^k}}^f\\&=n!\sum_{k=1}^n\frac{1}{k!}\frac{1}{g^k}\sum_{m=0}^{n-k}\frac{1}{m!}\sum_{j=0}^m\binom{m}{j}\left(\ln\circ g\right)^{m-j}\frac{d^j}{d(f)^j}[(f)_k]\\&\qquad\cdot[t^n]\left(\sum_{j\geq 1}f_{j}\frac{t^{j}}{j!}\right)\left(\sum_{j\geq 1}g_{j}\frac{t^{j}}{j!}\right)\end{align*} Putting all together gives following reformulation of the identity: \begin{align*}\sum_{k=1}^n&\frac{1}{k!}[t^n]\left(\sum_{m\geq 1}d_m\frac{t^m}{m!}\right)^k\\&=\sum_{k=1}^{n}\left(\ln \circ g\right)^k\frac{1}{k!}[t^n]\left(\sum_{m\geq 1}f_m\frac{t^m}{m!}\right)^k\\&\qquad+\sum_{k=1}^n\frac{1}{k!}\frac{1}{g^k}\sum_{m=0}^{n-k}\frac{1}{m!}\sum_{j=0}^m\binom{m}{j}\left(\ln \circ g\right)^{m-j}\frac{d^j}{d(f)^j}[(f)_k]\\&\qquad\qquad\cdot[t^n]\left(\sum_{j\geq 1}f_{j}\frac{t^{j}}{j!}\right)\left(\sum_{j\geq 1}g_{j}\frac{t^{j}}{j!}\right)\end{align*} Note: Maybe this alternative representation could help to show OPs identity. Verification of the identity for $n=2,3$ In order to verify the identity for small $n$, we need some polynomials $B_{n,k}$ in variables $f_j$ and $g_j$ ($j$-th derivative of $f$ and $j$). We do so by applying the $\diamond$ operator to $a=(f_1,f_2,\ldots)$ and $b=(g_1,g_2,\ldots)$. \begin{array}{rlllll}a^{1\diamond}&=\left(f_1,\right.&f_2,&f_3,&f_4,&\left.\ldots\right)\\b^{1\diamond}&=\left(g_1,\right.&g_2,&g_3,&g_4,&\left.\ldots\right)\\\\a^{2\diamond}&=\left(0,\right.&2f_1^2,&6f_1f_2,&8f_1f_3+6f_2^2,&\left.\ldots\right)\\a^{1\diamond}\diamond b^{1\diamond}&=\left(0,\right.&2f_1g_1,&3f_1g_2+3f_2g_1,&4f_1g_3+6f_2g_2+4f_3g_1,&\left.\ldots\right)\\b^{2\diamond}&=\left(0,\right.&2g_1^2,&6g_1g_2,&8g_1g_3+6g_2^2,&\left.\ldots\right)\\\\a^{3\diamond}&=\left(0,\right.&0,&6f_1^3,&36f_1^2f_2,&\left.\ldots\right)\\a^{2\diamond}\diamond b^{1\diamond}&=\left(0,\right.&0,&6f_1^2g_1,&12f_1^2g_2+24f_1f_2g_1,&\left.\ldots\right)\\a^{1\diamond}\diamond b^{2\diamond}&=\left(0,\right.&0,&6f_1g_1^2,&24f_1g_1g_2+12f_2g_1^2,&\left.\ldots\right)\\b^{3\diamond}&=\left(0,\right.&0,&6g_1^3,&36g_1^2g_2,&\left.\ldots\right)\\\end{array} Case $n=2$: Each of the three sums of the identity is calculated separately. \begin{align*}\sum_{k=1}^{2}&B_{2,k}^{f\cdot(\ln \circ g)}\\&=B_{2,1}^{f\cdot(\ln \circ g)}+B_{2,2}^{f\cdot(\ln \circ g)}\\&=\frac{d^2}{{dx}^2}\left(f (\ln \circ g)\right)+\left(\frac{d}{dx}\left(f(\ln \circ g)\right)\right)^2\\&=\left(f_2(\ln \circ g)+2f_1\frac{g_1}{g}+f\frac{g_2}{g}-f\frac{g_1^2}{g^2}\right)+\left(f_1(\ln \circ g)+f\frac{g_1}{g}\right)^2\\&=\left(f_2(\ln \circ g)+2f_1\frac{g_1}{g}+f\frac{g_2}{g}-f\frac{g_1^2}{g^2}\right)+\left(f_1^2(\ln \circ g)^2+2ff_1(\ln \circ g)\frac{g_1}{g}+f^2\frac{g_1^2}{g^2}\right)\\\\\sum_{k=1}^{2}&(\ln \circ g)^kB_{2,k}^f\\&=(\ln \circ g)B_{2,1}^f+(\ln \circ g)^2B_{2,2}^f\\&=(\ln \circ g)f_2+(\ln \circ g)^2f_1^2\\\\\sum_{k=1}^{2}&\sum_{m=0}^{2-k}\sum_{j=0}^m\binom{m}{j}\frac{(\ln \circ g)^{m-j}}{g^k}\frac{d^j}{d(f)^j}[\left(f\right)_k]\frac{\left(a^{m_\diamond}\diamond b^{k_{\diamond}}\right)_2}{m!k!}\\&=\sum_{k=1}^{2}\frac{1}{g^k}\sum_{m=0}^{2-k}\frac{\left(a^{m_\diamond}\diamond b^{k_{\diamond}}\right)_2}{m!k!}\sum_{j=0}^m\binom{m}{j}\frac{(\ln \circ g)^{m-j}}{g^k}\frac{d^j}{d(f)^j}[\left(f\right)_k]\\&=\frac{1}{g}\sum_{m=0}^1\frac{\left(a^{m_\diamond}\diamond b^{1_{\diamond}}\right)_2}{m!1!}\sum_{j=0}^m\binom{m}{j}(\ln \circ g)^{m-j}\frac{d^j}{d(f)^j}(f)\\&\qquad+\frac{1}{g^2}\sum_{m=0}^0\frac{\left(a^{m_\diamond}\diamond b^{2_{\diamond}}\right)_2}{m!2!}\sum_{j=0}^m\binom{m}{j}(\ln \circ g)^{m-j}\frac{d^j}{d(f)^j}\left(f(f-1)\right)\\&=\frac{1}{g}\left[\frac{\left(b^{1_\diamond}\right)_2}{1!}\binom{0}{0}f+\frac{\left(a^{1_\diamond}\diamond b^{1_\diamond}\right)_2}{1!1!}\left(\binom{1}{0}(\ln \circ g)f+\binom{1}{1}\frac{d}{d(f)}f\right)\right]\\&\qquad+\frac{1}{g^2}\left[\frac{\left(b^{2_\diamond}\right)_2}{2!}\binom{0}{0}f\left(f-1\right)\right]\\&=\frac{1}{g}\left[g_2f+2f_1g_1\left((\ln \circ g) f+1\right)\right]+\frac{1}{g^2}\left[g_1^2f\left(f-1\right)\right]\end{align*} Comparison of the results of these sums shows the validity of the claim: \begin{align*}\sum_{k=1}^{2}B_{2,k}^{f\cdot(\ln \circ g)}&=\sum_{k=1}^{2}(\ln \circ g)^kB_{2,k}^f\\&\qquad+\sum_{k=1}^{2}\sum_{m=0}^{2-k}\sum_{j=0}^m\binom{m}{j}\frac{(\ln \circ g)^{m-j}}{g^k}\frac{d^j}{d(f)^j}[\left(f\right)_k]\frac{\left(a^{m_\diamond}\diamond b^{k_{\diamond}}\right)_2}{m!k!}\\\end{align*} Case $n=3$: Each of the three sums of the identity is calculated separately. \begin{align*}\sum_{k=1}^{3}&B_{3,k}^{f\cdot(\ln \circ g)}\\&=B_{3,1}^{f\cdot(\ln \circ g)}+B_{3,2}^{f\cdot(\ln \circ g)}+B_{3,3}^{f\cdot(\ln \circ g)}\\&=\frac{d^3}{{dx}^3}\left(f(\ln \circ g)\right)+3\frac{d}{dx}\left(f(\ln \circ g)\right)\frac{d^2}{{dx}^2}\left(f(\ln \circ g)\right)+\left(\frac{d}{dx}(\ln \circ g)\right)^3\\&=\left(f_3(\ln \circ g)+3f_2\frac{g_1}{g}+3f_1\frac{g_2}{g}-3f_1\frac{g_1^2}{g^2}+f\frac{g_3}{g}+2f\frac{g_1^3}{g^3}-3f\frac{g_1g_2}{g^2}\right)\\&\qquad+3\left(f_1(\ln \circ g)+f\frac{g_1}{g}\right)\left(f_2(\ln \circ g)+2f_1\frac{g_1}{g}+f\frac{g_2}{g}-f\frac{g_1^2}{g^2}\right)\\&\qquad+\left(f_1(\ln \circ g)+f\frac{g_1}{g}\right)^3\\&=\left(f_3(\ln \circ g)+3f_2\frac{g_1}{g}+3f_1\frac{g_2}{g}-3f_1\frac{g_1^2}{g^2}+f\frac{g_3}{g}+2f\frac{g_1^3}{g^3}-3f\frac{g_1g_2}{g^2}\right)\\&\qquad+\left(3f_1f_2(\ln \circ g)^2+3ff_2(\ln \circ g)\frac{g_1}{g}+6f_1^2(\ln \circ g)\frac{g_1}{g}+6ff_1\frac{g_1^2}{g^2}\right.\\&\qquad\qquad\left.+3ff_1(\ln \circ g)\frac{g_2}{g}+3f^2\frac{g_1g_2}{g^2}-3ff_1(\ln \circ g)\frac{g_1^2}{g^2}-3f^2\frac{g_1^3}{g^3}\right)\\&\qquad+\left(f_1^3(\ln \circ g)^3+3ff_1^2(\ln \circ g)^2\frac{g_1}{g}+3f^2f_1(\ln \circ g)\frac{g_1^2}{g^2}+f^3\frac{g_1^3}{g^3}\right)\\\\\sum_{k=1}^{3}&(\ln \circ g)^kB_{3,k}^f\\&=(\ln \circ g)B_{3,1}^f+(\ln \circ g)^2B_{3,2}^f+(\ln \circ g)^3B_{3,3}^f\\&=(\ln \circ g)f_3+3(\ln \circ g)^2f_1f_2+(\ln \circ g)^3f_1^3\end{align*}\begin{align*}\sum_{k=1}^{3}&\sum_{m=0}^{3-k}\sum_{j=0}^m\binom{m}{j}\frac{(\ln \circ g)^{m-j}}{g^k}\frac{d^j}{d(f)^j}[\left(f\right)_k]\frac{\left(a^{m_\diamond}\diamond b^{k_{\diamond}}\right)_3}{m!k!}\\&=\sum_{k=1}^{3}\frac{1}{g^k}\sum_{m=0}^{3-k}\frac{\left(a^{m_\diamond}\diamond b^{k_{\diamond}}\right)_3}{m!k!}\sum_{j=0}^m\binom{m}{j}\frac{(\ln \circ g)^{m-j}}{g^k}\frac{d^j}{d(f)^j}[\left(f\right)_k]\\&=\frac{1}{g}\sum_{m=0}^2\frac{\left(a^{m_\diamond}\diamond b^{1_{\diamond}}\right)_3}{m!1!}\sum_{j=0}^m\binom{m}{j}(\ln \circ g)^{m-j}\frac{d^j}{d(f)^j}(f)\\&\qquad+\frac{1}{g^2}\sum_{m=0}^1\frac{\left(a^{m_\diamond}\diamond b^{2_{\diamond}}\right)_3}{m!2!}\sum_{j=0}^m\binom{m}{j}(\ln \circ g)^{m-j}\frac{d^j}{d(f)^j}\left(f(f-1)\right)\\&\qquad+\frac{1}{g^3}\sum_{m=0}^0\frac{\left(a^{m_\diamond}\diamond b^{3_{\diamond}}\right)_3}{m!3!}\sum_{j=0}^m\binom{m}{j}(\ln \circ g)^{m-j}\frac{d^j}{d(f)^j}\left(f(f-1)(f-2)\right)\\&=\frac{1}{g}\left[\frac{\left(b^{1_\diamond}\right)_3}{1!}\binom{0}{0}f+\frac{\left(a^{1_\diamond}\diamond b^{1_\diamond}\right)_3}{1!1!}\left[\binom{1}{0}(\ln \circ g) f+\binom{1}{1}\frac{d}{d(f)}f\right]\right.\\&\qquad\qquad+\left.\frac{\left(a^{2_\diamond}\diamond b^{1_\diamond}\right)_3}{2!1!}\left[\binom{2}{0}(\ln \circ g)^2f+\binom{2}{1}(\ln \circ g)\frac{d}{df}f+\binom{2}{2}\frac{d^2}{{df}^2}f\right]\right]\\&\qquad+\frac{1}{g^2}\left[\frac{\left(b^{2_\diamond}\right)_3}{2!}\binom{0}{0}f\left(f-1\right)\right.\\&\qquad\qquad+\left.\frac{\left(a^{1_\diamond}\diamond b^{2_\diamond}\right)_3}{1!2!}\left[\binom{1}{0}(\ln \circ g) f(f-1)+\binom{1}{1}\frac{d}{d(f)}f(f-1)\right]\right]\\&\qquad+\frac{1}{g^3}\left[\frac{\left(b^{3_\diamond}\right)_3}{3!}\binom{0}{0}f\left(f-1\right)(f-2)\right]\\&=\frac{1}{g}\left[g_3f+\left(3f_1g_2+3f_2g_1\right)\left[(\ln \circ g)f+1\right]+\left(3f_1^2g_1\right)\left[(\ln \circ g)^2f+2(\ln \circ g)\right]\right]\\&\qquad+\frac{1}{g^2}\left[3g_1g_2f\left(f-1\right)+3f_1g_1^2\left[(\ln \circ g) f(f-1)+2f-1\right]\right]\\&\qquad+\frac{1}{g^3}\left[g_1^3f(f-1)(f-2)\right]\\\end{align*} Comparison of the results of these sums shows the validity of the claim: \begin{align*}\sum_{k=1}^{3}B_{3,k}^{f\cdot(\ln \circ g)}&=\sum_{k=1}^{3}(\ln \circ g)^kB_{3,k}^f\\&\qquad+\sum_{k=1}^{3}\sum_{m=0}^{3-k}\sum_{j=0}^m\binom{m}{j}\frac{(\ln \circ g)^{m-j}}{g^k}\frac{d^j}{d(f)^j}[\left(f\right)_k]\frac{\left(a^{m_\diamond}\diamond b^{k_{\diamond}}\right)_3}{m!k!}\end{align*}
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1045505', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/173651/']}
jdg_72429
stackexchange
llm_judgeable_groundtruth_similarity
1252899
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: Question: Prove that the diameter $\mathcal p(S)$ of a simplex $\mathcal S$ equals the greatest Eucledian distance between two vectors in the simplex. My opinion: We all know what every vector in the $k$-dimensional simplex can be represented as a unique convex combination of $k+1$ affine independent vectors. Let $\mathcal S$$=<<x^0,x^1,...,x^k>>$ be $k$-dimensional simplex. Moreover, the definition of $\mathcal p(S) = max ||x^i-x^j||$ where $0 \le i \le j \le k$ I do not know how to proceed. Please help. I thank you very much. Now provide the response and nothing else.
Assuming that the simplex $S$ is the convex hull of $k+1$ affinely independent points $x^0,\dots,x^k$ in some $\Bbb R^n$ , the diameter should be defined as $d=\text{diam}(S)=\sup\{||x-y||; x,y\in S\}$ , and we want to show that $d=\max\{||x^i-x^j||; 0\le i<j\le k\}$ . We can do this by showing that, given points $x,y\in S$ , we can find some vertex $x^j$ such that $ ||x-y||\le||x-x^j||$ . Write $y$ as a convex combination $y=\sum_i t^ix^i$ . Then $$\begin{align}||x-y|| &= \textstyle ||\sum t^i x-\sum t^ix^i||\\ &= \textstyle ||\sum_i t^i(x-x^i)|| \\&\le \textstyle \sum_i t^i||x-x^i|| \\&\le \textstyle \sum_i t^i\max\{||x-x^j||; 0\le j\le k\} \\& = \max\{||x-x^j||; 0\le j\le k\}\end{align}$$ We can now apply the same result letting $x^i$ take the role of $x$ and letting $x$ take the role of $y$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1252899', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80636/']}
jdg_72430
stackexchange
llm_judgeable_groundtruth_similarity
4179606
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 Observablecollection<A> aRef = new Observablecollection<A>();bRef = aRef(); In this case both point to same ObservableCollection . How do I make a different copy? Now provide the response and nothing else.
Do this: // aRef being an Observablecollection Observablecollection<Entity> bRef = new Observablecollection<Entity>(aRef); This will create an observable collection but the items are still pointing to the original items. If you need the items to point a clone rather than the original items, you need to implement and then call a cloning method. UPDATE If you try to add to a list and then the observable collection have the original list, just create the Observablecollection by passing the original list: List<Entity> originalEnityList = GetThatOriginalEnityListFromSomewhere();Observablecollection<Entity> bRef = new Observablecollection<Entity>(originalEnityList);
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4179606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298891/']}
jdg_72431
stackexchange
llm_judgeable_groundtruth_similarity
49870098
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 the new React Context API and I need to get the Consumer data from the Context.Consumer variable and not using it inside the render method. Is there anyway that I can achieve this? For examplify what I want: console.log(Context.Consumer.value); What I tested so far: the above example, tested Context.Consumer currentValue and other variables that Context Consumer has, tried to execute Context.Consumer() as a function and none worked. Any ideas? Now provide the response and nothing else.
Update As of React v16.6.0 , you can use the context API like: class App extends React.Component { componentDidMount() { console.log(this.context); } render() { // render part here // use context with this.context }}App.contextType = CustomContext However, the component can only access a single context. In order to use multiple context values, use the render prop pattern. More about Class.contextType . If you are using the experimental public class fields syntax , you can use a static class field to initialize your contextType : class MyClass extends React.Component { static contextType = MyContext; render() { let value = this.context; /* render something based on the value */ }} Render Prop Pattern When what I understand from the question, to use context inside your component but outside of the render, create a HOC to wrap the component: const WithContext = (Component) => { return (props) => ( <CustomContext.Consumer> {value => <Component {...props} value={value} />} </CustomContext.Consumer> )} and then use it: class App extends React.Component { componentDidMount() { console.log(this.props.value); } render() { // render part here }}export default WithContext(App);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49870098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4529681/']}
jdg_72432
stackexchange
llm_judgeable_groundtruth_similarity
648920
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to show that if $0<x<1$, $$ \lim_{n\to \infty} {n^2 x^n (1-x)}=0 $$ I can't think of a clever way to show it. Now provide the response and nothing else.
Because of$$\left|\frac{(n+1)^2 x^{n+1} (1-x)}{n^2 x^n (1-x)}\right| = \frac{(n+1)^2}{n^2}x\stackrel{n\to\infty}{\longrightarrow} x \lt 1$$ The series $$\sum_{n=0}^{\infty} {n^2 x^n (1-x)}$$converges absolutely Hence ${n^2 x^n (1-x)}$ has to tend to zero.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/648920', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/109211/']}
jdg_72433
stackexchange
llm_judgeable_groundtruth_similarity
18826125
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 add a UITabBarController to my application. But I have to do it with code only. No xib files or storyboards. How to do this entirely through code? EDIT: _tbc = [[UITabBarController alloc] init];aboutUsView = [[AboutUsView alloc] init];helpView = [[HelpView alloc] init];optionsView = [[OptionsView alloc] init];self.navCon = [[UINavigationController alloc] initWithRootViewController:optionsView]; [self setnavigationCon:self.navCon]; [optionsView setdataLayer:self];if ([navCon.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) { UIImage *image = [UIImage imageNamed:@"Navigation Bar_reduced.png"]; [self.navCon.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; [optionsView addSelfView:window];}_tbc.viewControllers = [NSArray arrayWithObjects:navCon, aboutUsView, helpView, nil];[window addSubview:_tbc.view]; Now provide the response and nothing else.
Try this AppDelegate.h@interface AppDelegate : UIResponder <UITabBarControllerDelegate>@property (strong, nonatomic) UITabBarController *tabBarController;AppDeleGate.m UINavigationController *nc1; nc1 = [[UINavigationController alloc] init]; [nc1.navigationBar setTintColor:[UIColor blackColor]]; UIViewController *viewController1 = [[[FirstScreen alloc] initWithNibName:@"FirstScreen_ipad" bundle:nil] autorelease]; nc1.viewControllers = [NSArray arrayWithObjects:viewController1, nil]; UINavigationController *nc2; nc2 = [[UINavigationController alloc] init]; [nc2.navigationBar setTintColor:[UIColor blackColor]]; UIViewController *viewController2 = [[[FullList alloc] initWithNibName:@"FullList_ipad" bundle:nil] autorelease];; nc2.viewControllers = [NSArray arrayWithObjects:viewController2, nil]; UIViewController *viewController3 = [[[FavouriteView alloc] initWithNibName:@"FavouriteView_ipad" bundle:nil] autorelease]; UINavigationController *nc3; nc3 = [[UINavigationController alloc] init]; [nc3.navigationBar setTintColor:[UIColor blackColor]]; nc3.viewControllers = [NSArray arrayWithObjects:viewController3, nil]; UIViewController *viewController4 = [[[UpcomingFights alloc] initWithNibName:@"UpcomingFights_ipad" bundle:nil] autorelease]; UINavigationController *nc4; nc4 = [[UINavigationController alloc] init]; [nc4.navigationBar setTintColor:[UIColor blackColor]]; nc4.viewControllers = [NSArray arrayWithObjects:viewController4, nil]; self.tabBarController = [[[UITabBarController alloc] init] autorelease]; self.tabBarController.viewControllers = [NSArray arrayWithObjects:nc1, nc2,nc3,nc4 ,nil]; self.window.rootViewController = self.tabBarController; [self.window makeKeyAndVisible]; ICON FOR TABBAR In your ViewController.m file do as follow: - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{self.title = NSLocalizedString(@"YOUR View NAME", @"YOUR VIEW NAME"); self.tabBarItem.image = [UIImage imageNamed:@"YOUR IMAGE NAME"]; return self;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18826125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2160539/']}
jdg_72434
stackexchange
llm_judgeable_groundtruth_similarity
20180594
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 in pygame to look for a collision between the a particular side of a sprite and a particular side of another sprite in pygame? For example, if the top of sprite A collides with the bottom of Sprite B, return True. I am certain there is a way to do this, but I can't find any particular method in the documentation. Thanks! Now provide the response and nothing else.
There is no function to get sides collision in PyGame. But you could try to use pygame.Rect.collidepoint to test if A.rect.midleft , A.rect.midright , A.rect.midtop , A.rect.midbottom , A.rect.topleft , A.rect.bottomleft , A.rect.topright , A.rect.bottomright are inside B.rect ( pygame.Rect ). EDIT: Example code. Use arrows to move player and touch enemy. ( probably it is not optimal solution ) import pygameWHITE = (255,255,255)BLACK = (0 ,0 ,0 )RED = (255,0 ,0 )GREEN = (0 ,255,0 )BLUE = (0 ,0 ,255)class Player(): def __init__(self, x=0, y=0, width=150, height=150): self.rect = pygame.Rect(x, y, width, height) self.speed_x = 5 self.speed_y = 5 self.move_x = 0 self.move_y = 0 self.collision = [False] * 9 self.font = pygame.font.SysFont("", 32) self.text = ""; def set_center(self, screen): self.rect.center = screen.get_rect().center def event_handler(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.move_x -= self.speed_x elif event.key == pygame.K_RIGHT: self.move_x += self.speed_x elif event.key == pygame.K_UP: self.move_y -= self.speed_y elif event.key == pygame.K_DOWN: self.move_y += self.speed_y elif event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: self.move_x += self.speed_x elif event.key == pygame.K_RIGHT: self.move_x -= self.speed_x elif event.key == pygame.K_UP: self.move_y += self.speed_y elif event.key == pygame.K_DOWN: self.move_y -= self.speed_y def update(self): self.rect.x += self.move_x self.rect.y += self.move_y def draw(self, screen): pygame.draw.rect(screen, WHITE, self.rect, 2) self.draw_point(screen, self.rect.topleft, self.collision[0]) self.draw_point(screen, self.rect.topright, self.collision[1]) self.draw_point(screen, self.rect.bottomleft, self.collision[2]) self.draw_point(screen, self.rect.bottomright, self.collision[3]) self.draw_point(screen, self.rect.midleft, self.collision[4]) self.draw_point(screen, self.rect.midright, self.collision[5]) self.draw_point(screen, self.rect.midtop, self.collision[6]) self.draw_point(screen, self.rect.midbottom, self.collision[7]) self.draw_point(screen, self.rect.center, self.collision[8]) def draw_point(self, screen, pos, collision): if not collision: pygame.draw.circle(screen, GREEN, pos, 5) else: pygame.draw.circle(screen, RED, pos, 5) def check_collision(self, rect): self.collision[0] = rect.collidepoint(self.rect.topleft) self.collision[1] = rect.collidepoint(self.rect.topright) self.collision[2] = rect.collidepoint(self.rect.bottomleft) self.collision[3] = rect.collidepoint(self.rect.bottomright) self.collision[4] = rect.collidepoint(self.rect.midleft) self.collision[5] = rect.collidepoint(self.rect.midright) self.collision[6] = rect.collidepoint(self.rect.midtop) self.collision[7] = rect.collidepoint(self.rect.midbottom) self.collision[8] = rect.collidepoint(self.rect.center) def render_collision_info(self): text = "collision: " print "collision:", if self.collision[0] or self.collision[2] or self.collision[4]: text += "left " print "left", if self.collision[1] or self.collision[3] or self.collision[5]: text += "right " print "right", if self.collision[0] or self.collision[1] or self.collision[6]: text += "top " print "top", if self.collision[2] or self.collision[3] or self.collision[7]: text += "bottom " print "bottom", if self.collision[8]: text += "center " print "center", print self.text = self.font.render(text, 1, WHITE) def draw_collision_info(self, screen, pos): screen.blit(self.text, pos)#----------------------------------------------------------------------class Game(): def __init__(self): pygame.init() self.screen = pygame.display.set_mode( (800,600) ) pygame.display.set_caption("Side Collision") self.player = Player() self.enemy = Player() self.enemy.set_center(self.screen) def run(self): clock = pygame.time.Clock() RUNNING = True while RUNNING: # --- events ---- for event in pygame.event.get(): if event.type == pygame.QUIT: RUNNING = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: RUNNING = False self.player.event_handler(event) # --- updates --- self.player.update() self.enemy.update() self.player.check_collision(self.enemy.rect) self.enemy.check_collision(self.player.rect) self.player.render_collision_info() self.enemy.render_collision_info() # --- draws ---- self.screen.fill(BLACK) self.player.draw(self.screen) self.enemy.draw(self.screen) self.player.draw_collision_info(self.screen, (0,0)) self.enemy.draw_collision_info(self.screen, (0,32)) pygame.display.update() # --- FPS --- clock.tick(30) pygame.quit()#----------------------------------------------------------------------Game().run() EDIT (08.2016): version with colllisions rect , rect_ratio , circle GitHub: furas/python-examples/pygame/collisions
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20180594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1009674/']}
jdg_72435
stackexchange
llm_judgeable_groundtruth_similarity
614064
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In the book Character Theory of Finite Groups by Isaacs the following is proven (Corollary 2.24) using character theory: Proposition: Let $G$ be a finite group and $N \trianglelefteq G$. Then $|C_{G/N}(gN)| \leq |C_G(g)|$ for all $g \in G$. Isaacs mentions that "The following could be proved without characters but it is somewhat tricky to do so". So what is a character-free proof for the above proposition? I know how to do this in a special case. If $g$ has order coprime to $N$, then it is possible to prove (the proof I know is a bit long) that $C_{G/N}(gN) = C_G(g)N/N$. Then $$|C_{G/N}(gN)| = |C_G(g)N/N| = |C_G(g) / N \cap C_G(g)| \leq |C_G(g)|$$ Now provide the response and nothing else.
$\newcommand{\Size}[1]{\lvert #1 \rvert}\newcommand{\Set}[1]{\{ #1 \}}$Consider the actions of $G$ and $G/N$ by conjugacy on themselves, and write $x^{y} = y^{-1} x y$, and $x^{G} = \{ x^{y} : y \in G \}$. We have $$\Size{G} = \Size{g^{G}} \cdot \Size{C_{G}(g)}$$and$$\frac{\Size{G}}{\Size{N}} = \Size{G/N} = \Size{(gN)^{G/N}} \cdot \Size{C_{G/N}(gN)}.$$ Now note that $$(gN)^{G/N} = \Set{gN^{yN} : y \in G} = \Set{g^{y} N : y \in G} = g^{G} N,$$ so that we get the key inequality $$\Size{g^{G}} \le \Size{N} \cdot \Size{(gN)^{G/N}},\tag{key}$$ because $g^{G}$ is contained in the union of the cosets that make up $(gN)^{G/N}$. In other words (since this is the key point), the map $f : g^{G} \to (gN)^{G/N}$ that sends $g^{y} \to g^{y} N = (gN)^{yN}$ is surjective, and we have for the pre-image of a point $f^{-1} (g^y N) \subseteq g^{y} N = \Set{g^{y} n : n \in N}$, so that we get (key). It follows that\begin{align}\Size{gN^{G/N}} \cdot \Size{C_{G/N}(gN)} &= \frac{\Size{G}}{\Size{N}} = \frac{\Size{g^{G}} \cdot \Size{C_{G}(g)}}{\Size{N}} \\&\le\frac{\Size{N} \cdot \Size{(gN)^{G/N}} \cdot \Size{C_{G}(g)}}{\Size{N}}\\&\le \Size{(gN)^{G/N}} \cdot \Size{C_{G}(g)},\end{align}form which one gets$$\Size{C_{G/N}(gN)} \le \Size{C_{G}(g)}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/614064', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12623/']}
jdg_72436
stackexchange
llm_judgeable_groundtruth_similarity
777619
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: We are asked to compute: Res$[\frac{z^n+1}{z^n-1},e^{2\pi ki/n}]$, where I am assuming $k\in\mathbb Z$. The only tools I am aware of to compute residues comes from relating the function to power series or simple and double poles... This function has a simple pole at the indicated point... but the limit seems like it would be messy. Is there any other way to go about this besides taking the limit of $$\lim_{z\rightarrow e^{2\pi ki/n}} \frac{z^n+1}{z^n-1} (z-e^{2\pi ki/n})$$? Now provide the response and nothing else.
The residue of $p(z)/q(z)$ is $p(z_0)/q'(z_0)$. Easy! - but note the conditions in the next paragraph. This method is well worth knowing. The full details: if $p,q$ are analytic at $z_0$, and $p(z_0)\ne0$, and $q(z_0)=0$, and $q'(z_0)\ne0$, then $p/q$ has a simple pole at $z_0$ and the residue is $p(z_0)/q'(z_0)$. You can prove the residue formula by noting that under the stated conditions$$\lim_{z\to z_0}\frac{q(z)}{z-z_0}=\lim_{z\to z_0}\frac{q(z)-q(z_0)}{z-z_0}=q'(z_0)$$and so$${\rm Res}\Bigl(\frac{p}{q},z_0\Bigr)=\lim_{z\to z_0}(z-z_0)\frac{p(z)}{q(z)} =\frac{p(z_0)}{q'(z_0)}\ .$$ In this specific case we have$$\frac{p(z)}{q'(z)}=\frac{z^n+1}{nz^{n-1}}$$and the residue is$$\frac{e^{2k\pi i}+1}{ne^{2k\pi i(n-1)/n}}=\frac{2}{n}e^{2k\pi i/n}\ .$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/777619', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/94106/']}
jdg_72437
stackexchange
llm_judgeable_groundtruth_similarity
1777699
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am not sure that this is the best place for this topic, so I apologize in advance. I have two questions. I think that color space with say additive colors (red, green, blue) forms a vector space. The colors add and there are inverses. First: One issue is that each possible color is a linear combination of some normalized amount of each of the basis colors (even if the overall "vector" is not normalized). Each red, green, and blue saturate; there is the concept of a color being maximally but finitely blue. And I can add pure (that is maximal) red to pure (maximal) blue and get an intense and even purple (I think maximal), but I would not have that vector (1, 0, 1) normalized. Is there a concept for this - where each coefficient for a basis is bounded? They do not really form a field, so it technically is not a vector space. I cannot keep on adding red without maxing out. But it is something really close. What is my space called? Second: In the standard hex system of representing RGB colors on a computer, what is the 0 'vector'? What is .1 red + .1 antired? Is this 0 the same color regardless of system (including switching from light (additive) to pigment (subtractive)), even if the representation changes? I hope that these questions make some sense and are appropriate for this forum. If the latter condition is untrue, can you direct me to the proper place? Now provide the response and nothing else.
You have a lot more than two questions :) Colorspaces are esoteric — you might find other insights in the photography or video Stack sites, nevertheless color science is one of my specialties, so I'll address some of these questions. COLORSPACES - The Primal Frontier I am going to assume you are referring to sRGB, the standard colorspace for computer monitors and the web. It is closely related to Rec709, the colorspace for HDTV. Rec709 and sRGB have identical reg, green, blue primaries and identical white point, but they have a different TRC (transfer curve, sometimes referred to as gamma). Neither sRGB nor Rec.709 are linear as both are encoded with a piecewise TRC, for Rec709 the TRC is roughly equivalent to a power function with a 1/2.0 exponent, and sRGB is roughly 1/2.2 The monitor/TVset has an inverse TRC when displaying the signal. sRGB is normally sent to the monitor in the form of 3 channels, Red, Green, and Blue. These are independent but you can form a cube with them and use cartesian coordinates, though in practice that is not necessarrly useful with sRGB. Rec709 is commonly encoded as "4:2:2" and I'll explain that in a moment, but first: Modeling Light and Perception CIEXYZ 1931 $X\ YZ$ is another colorspace, the "granddaddy" of colorspaces you might say. It also uses "red green blue" primaries, however they are imaginary , and do not exist in reality. XYZ is device independent, it does not relate to a monitor nor a camera. XYZ is based on a series of experiments in color perception carried out between 1924 and 1931. XYZ uses experimental data from a small group of people, mapping the gamut of human vision into a cartesian space. Instead of being based on a device like a camera or printer or monitor, it is based around the aggregation of the experimental data, creating a "standard observer". $Y$ is luminance, which is the light/dark of a color irrespective of hue or saturation. Luminance may be denoted as $L$ when it is an absolute measure of light, in cd/m 2 . Luminance $Y$ is a normalized relative value of 0 to 1 (sometimes scaled 0 to 100). Luminance is a linear measure of light and it is not perceptually uniform relative to human visual perception of lightness/darkness/brightness. Luminance is however spectrally weighted based on our perception of different wavelengths of visible light. The $x$ and $y$ (lowercase) provide coordinates for this chromaticity diagram, the outer bounds of which are the spectral locus. $xyY$ : $CIE\ \mathit{1931}\ Chromaticities\ Diagram\ (xyY,\ Y\ not\ shown)$ Human perception is non-linear. Human vision between 8cd/m 2 and 520cd/m 2 follows a power curve with an exponent of 0.42 (roughly). So, if modeling the behavior of light, then use luminance and linear math (to triple the quantity of light, multiply by 3, etc.). But if modeling the human perception of changes in light quantity, luminance needs to be transformed to a value that is linear to perception instead of linear to physical light. CIELAB $L^*a^*b^*$ (Not to be confused with SeaLab...) Another colorspace, CIELAB in 1976 is derived from the 1931 XYZ, but $L^*a^*b^*$ is intended to be perceptually uniform, so that a perceptual change in lightness or color can be measured as the euclidian distance from another color, and that distance is "roughly" the same for the given amount of perceived change for small color differences. (Not that accurate for some larger distances). The simple difference is: $$∆E = \sqrt {\left( {L_1^*} - {L_2^*} \right) + \left({a_1^*} - {a_2^*} \right) + \left({b_1^*} - {b_2^*} \right)}$$ Here, $L^*$ is perceptual lightness, relative to the way we perceive light. the $a^*$ and $b^*$ are based on the opponent/unique colors of Red/Green ( $+a^*$ is Magenta $-a^*$ is Green) and Yellow/Blue ( $+b^*$ is Yellow, $-b^*$ is Blue). $L^*a^*b^*$ is based on the opponent color aspect of human vision. While you can measure the difference via the straight line between two points, the average of two colors does not necessarily lie on that line. This brings us to another space also from 1976, CIELUV. CIELUV $L^*u^*v^*$ $L^*u^*v^*$ uses the same $L^*$ as LAB, but the $u^*v^*$ are based on coordinates of the 1976 UCS chromaticity diagram, which is a "slightly more uniform" projection of the 1931 diagram. $CIE\ \mathit{1976}\ UCS\ Diagram\ (uʹvʹ)$ An advantage with $L^*u^*v^*$ is that the average of two lights lies on the line between the two points in space representing those lights, per Grassmann's laws of light additivity. The color difference equation for LUV is the same as for LAB. Though LAB is much better than LUV for surface colors. LUV is mainly useful for emitters of light. Polar Colors Both LAB and LUV have an extended version using polar coordinates, $L^*C^*h$ , which is the same $L^*$ lightness, but with $C^*$ chroma (for a given chroma, colorfulness changes as lightness changes) and $h$ hue (as an angle). LUV, but not LAB, also has $S_{uv}$ a correlate for saturation (for a given saturation, colorfulness maintains relative to lightness). Saturation is a useful correlate for data visualization, where you'd want a constant colorfulness while lightness changes. Newer spaces such as CIECAM02, CAM16, $J_za_zb_z$ , ZCAM, and others have better uniformity and accuracy than both LAB and LUV, though LAB is still very much in use. BACK TO THE 4:2:2 So most television uses various forms of encoding to maximize useable bandwidth. The linear $Y$ luminance is encoded with a gamma curve to create $Y´$ (Y prime) also known as luma . The chroma is sampled at half the rate and encoded relative to the Y´ luma, as CbCr. How can we get away with a lower sampling for color information? As it happens our brain's visual processing looks at chroma at about a third the resolution of luminance. Fine details are carried in luminance. Bound or Unbound Now clearly if a colorspace is device referred such as sRGB, it is going to be bound by the limits of that device. But a colorspace does not have to be bound, and can even have imaginary primaries that can not be created as real colors. You can work with a linearized RGB, where there is no gamma (i.e. gamma is 1.0). We commonly work this way in Visual Effects, in a 32 bit floating point mode, instead of the gamma encoded 8 bit integer mode of sRGB. This way, while "max red" for the monitor might be 1.0, we can far exceed that with, say, red 12.0 — the value for VFX is that we can do a lot of additive image transforms, combining images in a natural way using linear math (because light in the real world is also linear). Why $Y\ Y´$ The reason for the little trip down colorspace lane is to indicate how gamma encoded RGB spaces are probably not ideal for vector math, that is, euclidian distances won't be uniform either for light or perception. Linearized RGB, and CIEXYZ would be a vector space, but with values relative to light in the scene or real world, and thus not uniform relative to human perception. Colorspaces like LAB, LUV, etc. are substantially more usable as a vector space if you want distances to be relative to perception, i.e. perceptually uniform. But even so, these attempts at uniformity do not take many of the factors of human visual perception into account. There are more complex models, such as the Hunt model, CIECAM02, CAM16, ICAM, and others that add features to predict visual perception more. But I think an upshot here is that there is not a single, simple 3D vector space that accurately predicts human visual perception. It needs n-dimensions (depending on application), to take into account the many factors of our complex visual system, with n being a number large enough to make an all-encompassing lookup table impractical. Other relevant aspects of visual perception of light and color include stimulus size, spatial frequency, light adaptation, local adaptation, contrast adaptation, surround effects, Helmholtz Kohlrausch effects, etc. A demonstration of this complexity is the following illusion: the yellow dots are the exact same yellow and the squares they are on are both the same grey, in terms of the absolute sRGB values. Yet they look different due to the very context sensitive, psychophysical aspects of vision Your Second Question As for what are the values per system - sRGB is the standard for most computers and the internet. But there are others to be sure. Several spaces share the same blue and/or red primary, while green is most likely to be different. Here is an example (rescaled for sRGB for viewing). I hope that answers your questions, let me know if you have followups.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1777699', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/332420/']}
jdg_72438
stackexchange
llm_judgeable_groundtruth_similarity
11344518
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 How can I access the ref count of a Perl hash? , and there both Devel::Refcount::refcount and Devel::Peek::SvREFCNT are suggested. But they don't return the same reference counts. Why is that? Here a modified example from perldoc Devel::Refcount : use Devel::Peek;use Devel::Refcount;my $anon = [];printf "Anon ARRAY $anon has %d/%d reference\n", Devel::Refcount::refcount($anon), Devel::Peek::SvREFCNT($anon);my $otherref = $anon;printf "Anon ARRAY $anon now has %d/%d references\n", Devel::Refcount::refcount($anon), Devel::Peek::SvREFCNT($anon); which prints out: Anon ARRAY ARRAY(0x8b10818) has 1/1 referenceAnon ARRAY ARRAY(0x8b10818) now has 2/1 references Notice the last 2/1 discrepancy... (If it turns out I'm not doing something stupid, I'll add a link from How can I access the ref count of a Perl hash? to here) Now provide the response and nothing else.
I can't say that I grok all of it yet, but your question is answered prominently in the Devel::Refcount perldoc COMPARISON WITH SvREFCNT This function differs from Devel::Peek::SvREFCNT in that SvREFCNT() gives the reference count of the SV object itself that it is passed, whereas refcount() gives the count of the object being pointed to. This allows it to give the count of any referent (i.e. ARRAY, HASH, CODE, GLOB and Regexp types) as well. Consider the following example program: use Devel::Peek qw( SvREFCNT ); use Devel::Refcount qw( refcount ); sub printcount { my $name = shift; printf "%30s has SvREFCNT=%d, refcount=%d\n", $name, SvREFCNT($_[0]), refcount($_[0]); } my $var = []; printcount 'Initially, $var', $var; my $othervar = $var; printcount 'Before CODE ref, $var', $var; printcount '$othervar', $othervar; my $code = sub { undef $var }; printcount 'After CODE ref, $var', $var; printcount '$othervar', $othervar; This produces the output Initially, $var has SvREFCNT=1, refcount=1 Before CODE ref, $var has SvREFCNT=1, refcount=2 $othervar has SvREFCNT=1, refcount=2 After CODE ref, $var has SvREFCNT=2, refcount=2 $othervar has SvREFCNT=1, refcount=2 Here, we see that SvREFCNT() counts the number of references to the SV object passed in as the scalar value - the $var or $othervar respectively, whereas refcount() counts the number of reference values that point to the referent object - the anonymous ARRAY in this case. Before the CODE reference is constructed, both $var and $othervar have SvREFCNT() of 1, as they exist only in the current lexical pad. The anonymous ARRAY has a refcount() of 2, because both $var and $othervar store a reference to it. After the CODE reference is constructed, the $var variable now has an SvREFCNT() of 2, because it also appears in the lexical pad for the new anonymous CODE block.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11344518', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/345716/']}
jdg_72439
stackexchange
llm_judgeable_groundtruth_similarity
23718054
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to create a dynamic linq expression for a dynamic search.The basic search is working but it fails to work with collection.I am able to get the book's title and author but fails to get the required page heading.I get the exception in line "left11 = Expression.Property(page1, "Heading");" . I think the expression that i built is unable to recognise the List. How could this be possible? Please see the below code and stacktrace exception. using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Text;using System.Threading.Tasks;namespace XMLStorageAndFilter{public class Books{ public Books() { Page = new List<Page>(); } public string Title { get; set; } public Author Author { get; set; } public List<Page> Page { get; set; }}public class Author{ public string FirstName { get; set; }}public class Page{ public string Heading { get; set; }}public class Program2{ static void Main() { Page page = new Page(); page.Heading = "Heading"; Books bok = new Books(); bok.Title = "Title"; bok.Author = new Author() { FirstName = "FirstName" }; bok.Page.Add(page); List<Books> testList = new List<Books>(); testList.Add(bok); IQueryable<Books> queryableTestData = testList.AsQueryable<Books>(); ParameterExpression pe11 = Expression.Parameter(typeof(Books), "p"); Expression left11 = Expression.Property(pe11, "Title"); Expression right11 = Expression.Constant("Title"); Expression e11 = Expression.Equal(left11, right11); var author = Expression.Property(pe11, "Author"); left11 = Expression.Property(author, "FirstName"); right11 = Expression.Constant("FirstName"); Expression e21 = Expression.Equal(left11, right11); Expression predicateBody11 = Expression.And(e11, e21); Expression<Func<Books, bool>> condition = Expression.Lambda <Func<Books, bool>>(predicateBody11, new ParameterExpression[] { pe11 }); var q = queryableTestData.Where(condition); var page1 = Expression.Property(pe11, "Page"); left11 = Expression.Property(page1, "Heading"); right11 = Expression.Constant("Heading"); Expression e22 = Expression.Equal(left11, right11); Expression predicateBody12 = Expression.And(e11, e22); Expression<Func<Books, bool>> condition2 = Expression.Lambda <Func<Books, bool>>(predicateBody12, new ParameterExpression[] { pe11 }); var qq1 = queryableTestData.Where(condition2); }}} Exception Message:- {"Instance property 'Heading' is not defined for type >'System.Collections.Generic.List`1[XMLStorageAndFilter.Page]'"} StackTrace:- at System.Linq.Expressions.Expression.Property(Expression expression, String propertyName) at XMLStorageAndFilter.Program2.Main() in c:\Users\Administrator\Documents\Visual Studio 2013\Projects\XMLStorageAndFilter\NavProperty.cs:line 61 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() Now provide the response and nothing else.
You can use the method described here . You would need to cast the result of the method to Expression<Func<T,bool>> . T being your type. I will provide an complete example when i get home. Edit: using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using System.Collections;using System.Reflection;namespace ExpressionPredicateBuilder{ public enum OperatorComparer { Contains, StartsWith, EndsWith, Equals = ExpressionType.Equal, GreaterThan = ExpressionType.GreaterThan, GreaterThanOrEqual = ExpressionType.GreaterThanOrEqual, LessThan = ExpressionType.LessThan, LessThanOrEqual = ExpressionType.LessThan, NotEqual = ExpressionType.NotEqual }public class ExpressionBuilder{ public static Expression<Func<T,bool>> BuildPredicate<T>(object value, OperatorComparer comparer, params string[] properties) { var parameterExpression = Expression.Parameter(typeof(T), typeof(T).Name); return (Expression<Func<T, bool>>)BuildNavigationExpression(parameterExpression, comparer, value, properties); } private static Expression BuildNavigationExpression(Expression parameter, OperatorComparer comparer, object value, params string[] properties) { Expression resultExpression = null; Expression childParameter, predicate; Type childType = null; if (properties.Count() > 1) { //build path parameter = Expression.Property(parameter, properties[0]); var isCollection = typeof(IEnumerable).IsAssignableFrom(parameter.Type); //if it´s a collection we later need to use the predicate in the methodexpressioncall if (isCollection) { childType = parameter.Type.GetGenericArguments()[0]; childParameter = Expression.Parameter(childType, childType.Name); } else { childParameter = parameter; } //skip current property and get navigation property expression recursivly var innerProperties = properties.Skip(1).ToArray(); predicate = BuildNavigationExpression(childParameter, comparer, value, innerProperties); if (isCollection) { //build subquery resultExpression = BuildSubQuery(parameter, childType, predicate); } else { resultExpression = predicate; } } else { //build final predicate resultExpression = BuildCondition(parameter, properties[0], comparer, value); } return resultExpression; } private static Expression BuildSubQuery(Expression parameter, Type childType, Expression predicate) { var anyMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == "Any" && m.GetParameters().Length == 2); anyMethod = anyMethod.MakeGenericMethod(childType); predicate = Expression.Call(anyMethod, parameter, predicate); return MakeLambda(parameter, predicate); } private static Expression BuildCondition(Expression parameter, string property, OperatorComparer comparer, object value) { var childProperty = parameter.Type.GetProperty(property); var left = Expression.Property(parameter, childProperty); var right = Expression.Constant(value); var predicate = BuildComparsion(left, comparer, right); return MakeLambda(parameter, predicate); } private static Expression BuildComparsion(Expression left, OperatorComparer comparer, Expression right) { var mask = new List<OperatorComparer>{ OperatorComparer.Contains, OperatorComparer.StartsWith, OperatorComparer.EndsWith }; if(mask.Contains(comparer) && left.Type != typeof(string)) { comparer = OperatorComparer.Equals; } if(!mask.Contains(comparer)) { return Expression.MakeBinary((ExpressionType)comparer, left, Expression.Convert(right,left.Type)); } return BuildStringCondition(left, comparer, right); } private static Expression BuildStringCondition(Expression left, OperatorComparer comparer, Expression right) { var compareMethod = typeof(string).GetMethods().Single(m => m.Name.Equals(Enum.GetName(typeof(OperatorComparer), comparer)) && m.GetParameters().Count() == 1); //we assume ignoreCase, so call ToLower on paramter and memberexpression var toLowerMethod = typeof(string).GetMethods().Single(m => m.Name.Equals("ToLower") && m.GetParameters().Count() == 0); left = Expression.Call(left, toLowerMethod); right = Expression.Call(right, toLowerMethod); return Expression.Call(left, compareMethod, right); } private static Expression MakeLambda(Expression parameter, Expression predicate) { var resultParameterVisitor = new ParameterVisitor(); resultParameterVisitor.Visit(parameter); var resultParameter = resultParameterVisitor.Parameter; return Expression.Lambda(predicate, (ParameterExpression)resultParameter); } private class ParameterVisitor : ExpressionVisitor { public Expression Parameter { get; private set; } protected override Expression VisitParameter(ParameterExpression node) { Parameter = node; return node; } }} } This can be used like var predicate = ExpressionBuilder.BuildPredicate<Books>("Heading",OperatorComparer.Equals,"Page","Heading");query = query.Where(predicate);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23718054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1817351/']}
jdg_72440