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
1215
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: Can we find $f(x)$ given that $1-f(x) = f(-x)$ for all real $x$? I start by rearranging to: $f(-x) + f(x) = 1$. I can find an example such as $f(x) = |x|$ that works for some values of $x$, but not all. Is there a method here? Is this possible? Now provide the response and nothing else.
$$f(x)=\frac{1}{2}+\text{(any odd function)}.$$For example, $f(x)=\frac{1}{2}+x$ or, say, $f(x)=\frac{1}{2}+99x^3+7x^5$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1215', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_77841
stackexchange
llm_judgeable_groundtruth_similarity
35647044
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 image in which I need to put a button over, the problem is that I don't know how to place the button and automatically re-size and position it when making the browser smaller, right now I have the button in place, but when I re-size the browser to get smaller the button moves, I tried using percentages in the css buy doesn't work, what can I do? <div id="discover" class="container-fluid"><div class="row-fluid"> <div class="col-lg-12 col-sm-12 col-xs-12 col-md-12 withimg"> <img id="discoveryour" src="img/x.png" class="img-responsive"> </div> </div><div class="row-fluid"> <div id="bttnimg" class="col-lg-12 col-sm-12 col-xs-12 col-md-12"><form id="start" method="post" action="x.php"><button class="btn-primary">text</button></form> </div></div></div> Css: .withimg { width: 100%; overflow:hidden; padding: 0px; margin: 0px; } #discover{ position: relative; }#bttnimg{float: left;position: absolute;left: 62%;top: 25%;max-width: 750px; } Now provide the response and nothing else.
Ah, the good old "how to overlay stuff on top of a responsive image -- responsively" question. A little tricky, but not too bad. The tricky bit is how to make the stuff's vertical position responsive when the image size changes. Fear not, here's one simple way to do this: HTML: <div class="img-wrapper"> <img class="img-responsive" src="http://lorempixel.com/output/people-q-c-1200-400-4.jpg"> <div class="img-overlay"> <button class="btn btn-md btn-success">Button</button> </div></div> CSS: .img-wrapper { position: relative;}.img-responsive { width: 100%; height: auto;}.img-overlay { position: absolute; top: 0; bottom: 0; left: 0; right: 0; text-align: center;}.img-overlay:before { content: ' '; display: block; /* adjust 'height' to position overlay content vertically */ height: 50%;} The img-overlay:before pseudo-class handles the vertical positioning job by pushing the img-overlay div down from the top of the image. In this example, the top of the button will always be 50% down the image (change the height: 50% attribute if you want the button higher or lower). jsfiddle To make the button size responsive to window width, you can create a new class for your button. Let's call it btn-responsive (this replaces btn-md in the example above). Then use @media queries to adjust the btn-responsive attributes for different window widths. Something like this: .btn-responsive { /* matches 'btn-md' */ padding: 10px 16px; font-size: 18px; line-height: 1.3333333; border-radius: 6px;}@media (max-width:760px) { /* matches 'btn-xs' */ .btn-responsive { padding: 1px 5px; font-size: 12px; line-height: 1.5; border-radius: 3px; }} and so forth for other screen widths.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35647044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2364246/']}
jdg_77842
stackexchange
llm_judgeable_groundtruth_similarity
14375226
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have three input fields as below: <input type="text" name="address" id="address"/> <input type="text" name="city" id="city"/> <input type="text" name="country" id="country"/> How can i add onChange event to all of these fields at once something like this: $("select the elements with id address,city,country").bind("change", function() { //do something }); Now provide the response and nothing else.
use , in id selector as @Rory said OR add a class to all this and call change function <input type="text" name="address" id="address" class="className"/><input type="text" name="city" id="city" class="className"/><input type="text" name="country" id="country" class="className"/>$('.className').bind("change", function(){ //your stuff}); HOWEVER since it is an input field.. i recommend you to use.. keyup() , using change you have to click out of the text box to make it fire. $('.className').keyup(function(){ //your stuff});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14375226', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1118594/']}
jdg_77843
stackexchange
llm_judgeable_groundtruth_similarity
58492796
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There are a few posts on getting ViewPager to work with varying height items that center around extending ViewPager itself to modify its onMeasure to support this. However, given that ViewPager2 is marked as a final class, extending it isn't something that we can do. Does anyone know if there's a way to make this work out? E.g. let's say I have two views: View1 = 200dp View2 = 300dp When the ViewPager2 ( layout_height="wrap_content" ) loads -- looking at View1, its height will be 200dp. But when I scroll over to View2, the height is still 200dp; the last 100dp of View2 is cut off. Now provide the response and nothing else.
The solution is to register a PageChangeCallback and adjust the LayoutParams of the ViewPager2 after asking the child to re-measure itself. pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { super.onPageSelected(position) val view = // ... get the view view.post { val wMeasureSpec = MeasureSpec.makeMeasureSpec(view.width, MeasureSpec.EXACTLY) val hMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) view.measure(wMeasureSpec, hMeasureSpec) if (pager.layoutParams.height != view.measuredHeight) { // ParentViewGroup is, for example, LinearLayout // ... or whatever the parent of the ViewPager2 is pager.layoutParams = (pager.layoutParams as ParentViewGroup.LayoutParams) .also { lp -> lp.height = view.measuredHeight } } } }}) Alternatively, if your view's height can change at some point due to e.g. asynchronous data load, then use a global layout listener instead: pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { private val listener = ViewTreeObserver.OnGlobalLayoutListener { val view = // ... get the view updatePagerHeightForChild(view) } override fun onPageSelected(position: Int) { super.onPageSelected(position) val view = // ... get the view // ... IMPORTANT: remove the global layout listener from other views otherViews.forEach { it.viewTreeObserver.removeOnGlobalLayoutListener(layoutListener) } view.viewTreeObserver.addOnGlobalLayoutListener(layoutListener) } private fun updatePagerHeightForChild(view: View) { view.post { val wMeasureSpec = MeasureSpec.makeMeasureSpec(view.width, MeasureSpec.EXACTLY) val hMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED) view.measure(wMeasureSpec, hMeasureSpec) if (pager.layoutParams.height != view.measuredHeight) { // ParentViewGroup is, for example, LinearLayout // ... or whatever the parent of the ViewPager2 is pager.layoutParams = (pager.layoutParams as ParentViewGroup.LayoutParams) .also { lp -> lp.height = view.measuredHeight } } } }} See discussion here: https://issuetracker.google.com/u/0/issues/143095219
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58492796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2623229/']}
jdg_77844
stackexchange
llm_judgeable_groundtruth_similarity
1453415
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 set the FontFamily and FontSize for the application in App.xaml? Now provide the response and nothing else.
I've found a blog post by David Padbury from 2008 (sadly no longer in existence) which went into this and how to change it from code. Basically you override the meta data properties which merges in your changes to the existing values. TextElement.FontFamilyProperty.OverrideMetadata(typeof(TextElement),new FrameworkPropertyMetadata( new FontFamily("Comic Sans MS")));TextBlock.FontFamilyProperty.OverrideMetadata(typeof(TextBlock),new FrameworkPropertyMetadata( new FontFamily("Comic Sans MS"))); There's also this MSDN forum post which explains how to do it in XAML in two ways. Firstly you define a "global" style for the Control class and then use the BasedOn property to apply that to other controls. <StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel.Resources> <Style TargetType="{x:Type Control}" x:Key="ControlStyle"> <Setter Property="FontFamily" Value="Constantia"/> </Style> <Style TargetType="{x:Type Label}" x:Key="LabelStyle" BasedOn="{StaticResource ControlStyle}"> <Setter Property="FontWeight" Value="Bold" /> </Style> <Style TargetType="{x:Type Button}" x:Key="ButtonStyle" BasedOn="{StaticResource ControlStyle}"> <Setter Property="Background" Value="Blue"/> </Style> </StackPanel.Resources> <Label Style="{StaticResource LabelStyle}">This is a Label</Label> <Button Style="{StaticResource ButtonStyle}">This is a Button</Button></StackPanel> You can set the system fonts: ./#Segoe UI<System:Double x:Key="{x:Static SystemFonts.MenuFontSizeKey}">11</System:Double>Normal Though I probably wouldn't recommend this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1453415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88096/']}
jdg_77845
stackexchange
llm_judgeable_groundtruth_similarity
14680396
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A Date object’s getMonth() method seems to have a bug. Assuming the Date d is 2013-01-31 , I attempt to set the month on d like this: const d = new Date(); // 2013-01-31d.setMonth(8);console.log(d.getMonth()); The result is 9 . Why? I tested this both in Chrome and Firefox. I found out that when it’s the 31st, 30th, or 29th of a month, setting the date to a month that has a fewer number of days causes getMonth to return the wrong value. Now provide the response and nothing else.
Let's break this down: var d = new Date(); // date is now 2013-01-31d.setMonth(1); // date is now 2013-02-31, which is 3 days past 2013-02-28x = d.getMonth(); // what to do, what to do, 3 days past 2013-02-28 is in March // so, expect x to be March, which is 2 This is only an issue when the day value of d is greater than the maximum number of days in the month passed to setMonth() . Otherwise, it works as you'd expect.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14680396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1181816/']}
jdg_77846
stackexchange
llm_judgeable_groundtruth_similarity
2776386
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: There is an differential given:$$xx'' = (x')^2,$$where $x' \neq 0.$ I tried to solve this problem but I cannot see the proper substitution. Now provide the response and nothing else.
Think that $$\frac{\ddot x}{\dot x} = \frac{\dot x}{x}\Rightarrow \frac{d}{dt}\ln(\dot x) = \frac{d}{dt}\ln (x)$$ so $$\ln(\dot x) = \ln(x) + C \Rightarrow \dot x = C_1 x\Rightarrow x = C_2e^{C_1 t}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2776386', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/403569/']}
jdg_77847
stackexchange
llm_judgeable_groundtruth_similarity
196655
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a chat program in my spare time. If a user inputs html it will be rendered, for example, <a href="example.com">link</a> will render a hyperlink. At the same time, if you use a script tag, the script doesn't seem to be executed, but is inserted into the dom. Should I be worried? Edit: As I fixed the vulnerability, here's the site for anyone interested. wezelchat.herokuapp.com And the repo on github . Now provide the response and nothing else.
All that you've missed is where a hash is supposed to protect you. You are correct that if an attacker has access to the server itself, they can just modify everything. Where a hash is supposed to help you is against a man-in-the-middle attack. For example: Download file Read webpage for plaintext md5 or sha1 Hash downloaded file Compare values If someone were sitting in the middle, they could theoretically sit in the middle and change both also but there are other technical solutions to try to combat this (SSL/TLS (still vulnerable to MITM) and digital signatures). EDIT: On some of the customer remediations I've been on, how we've used download hashes to try and mitigate a MITM is to download the bits, and then verify that the hash on the website is seen as the same over multiple connections/computers. This significantly decreases the liklihood that an attacker will own all of the investigators' means of connections. If the hashes from the source site are the same across the different connections/computers, it should be assumed to be relatively safe.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/196655', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/190097/']}
jdg_77848
stackexchange
llm_judgeable_groundtruth_similarity
4741035
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have created a C++ Dll project which contains a class "myCppClass" and tried to Dll export it using the following code as described by: http://msdn.microsoft.com/en-us/library/a90k134d(v=vs.80).aspx class __declspec(dllexport) CExampleExport : //public CObject{ ... class definition ... }; I have omitted the "public CObject" as that requires afx.h and implies it is an MFC Dll. I am not sure if this is a good thing or not but it differed from the DLL project default settings. From the above linked documentation I am led to believe that all "public functions and member variables" are available for import. How do I accomplish this in C#? Can simply instantiate the class? Edit: I just realized that the Title of the post may be misleading. The emphasis should be on DllImport-ing from C# and ensuring that I followed the documentation properly in C++ Now provide the response and nothing else.
C# cannot directly import C++ classes (which are effectively name-mangled C interfaces). Your options are exposing the class via COM, creating a managed wrapper using C++/CLI or exposing a C-style interface. I would recommend the managed wrapper, since this is easiest and will give the best type safety. A C-style interface would look something like this (warning: untested code): extern "C" __declspec(dllexport)void* CExampleExport_New(int param1, double param2){ return new CExampleExport(param1, param2);}extern "C" __declspec(dllexport)int CExampleExport_ReadValue(void* this, int param){ return ((CExampleExport*)this)->ReadValue(param)} A C++/CLI-style wrapper would look like this (warning: untested code): ref class ExampleExport{private: CExampleExport* impl;public: ExampleExport(int param1, double param2) { impl = new CExampleExport(param1, param2); } int ReadValue(int param) { return impl->ReadValue(param); } ~ExampleExport() { delete impl; }};
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4741035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262964/']}
jdg_77849
stackexchange
llm_judgeable_groundtruth_similarity
2423795
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: (n >= 3 ) && (n <= 99) OR n `elem` [3..99] Which one is faster and why? Now provide the response and nothing else.
The first one is faster (n >= 3) && (n <= 99) it is doing 3 operations n >= 3 n <= 99 and Where as the elem is looking up the item in the array, so is doing upto (99 - 3) * 2 operations. index = 0isFound = falsearray[] = { 3, 4, 5, 6, ... 98, 99 }while isFound == false isFound = (n == array[index++])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2423795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58737/']}
jdg_77850
stackexchange
llm_judgeable_groundtruth_similarity
16483
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 convince Firefox (3.0.1, if it matters) to send an If-Modified-Since header in an HTTPS request? It sends the header if the request uses plain HTTP and my server dutifully honors it. But when I request the same resource from the same server using HTTPS instead (i.e., simply changing the http:// in the URL to https://) then Firefox does not send an If-Modified-Since header at all. Is this behavior mandated by the SSL spec or something? Here are some example HTTP and HTTPS request/response pairs, pulled using the Live HTTP Headers Firefox extension, with some differences in bold: HTTP request/response: http://myserver.com:30000/scripts/site.jsGET /scripts/site.js HTTP/1.1Host: myserver.com:30000User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-alive If-Modified-Since: Tue, 19 Aug 2008 15:57:30 GMTIf-None-Match: "a0501d1-300a-454d22526ae80"-gzipCache-Control: max-age=0 HTTP/1.x 304 Not ModifiedDate: Tue, 19 Aug 2008 15:59:23 GMTServer: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8Connection: Keep-AliveKeep-Alive: timeout=5, max=99Etag: "a0501d1-300a-454d22526ae80"-gzip HTTPS request/response: https://myserver.com:30001/scripts/site.jsGET /scripts/site.js HTTP/1.1Host: myserver.com:30001User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Accept-Language: en-us,en;q=0.5Accept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-aliveHTTP/1.x 200 OKDate: Tue, 19 Aug 2008 16:00:14 GMTServer: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8Last-Modified: Tue, 19 Aug 2008 15:57:30 GMTEtag: "a0501d1-300a-454d22526ae80"-gzipAccept-Ranges: bytesContent-Encoding: gzipContent-Length: 3766Keep-Alive: timeout=5, max=100Connection: Keep-AliveContent-Type: text/javascript UPDATE: Setting browser.cache.disk_cache_ssl to true did the trick (which is odd because, as Nickolay points out, there's still the memory cache). Adding a "Cache-control: public" header to the response also worked. Thanks! Now provide the response and nothing else.
HTTPS requests are not cached so sending an If-Modified-Since doesn't make any sense. The not caching is a security precaution. The not caching on disk is a security pre-caution, but it seems it indeed affects the If-Modified-Since behavior (glancing over the code). Try setting the Firefox preference (in about:config) browser.cache.disk_cache_ssl to true . If that helps, try sending Cache-Control: public header in your response. UPDATE: Firefox behavior was changed for Gecko 2.0 (Firefox 4) -- HTTPS content is now cached.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16483', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164/']}
jdg_77851
stackexchange
llm_judgeable_groundtruth_similarity
5151077
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 my first WCF example working. I have the host on a website which have many bindings. Because of this, I have added this to my web.config. <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/> This is my default binding http://id.web , which works with the following code. EchoServiceClient client = new EchoServiceClient();litResponse.Text = client.SendEcho("Hello World");client.Close(); I am now trying to set the endpoint address at runtime. Even though it is the same address of the above code. EchoServiceClient client = new EchoServiceClient();client.Endpoint.Address = new EndpointAddress("http://id.web/Services/EchoService.svc"); litResponse.Text = client.SendEcho("Hello World");client.Close(); The error I get is: The request for security token could not be satisfied because authentication failed. Please suggest how I may change the endpoint address at runtime? Additional here is my client config, requested by Ladislav Mrnka <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IEchoService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="None" /> </binding> </wsHttpBinding> </bindings> <client> <endpoint address="http://id.web/Services/EchoService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IEchoService" contract="IEchoService" name="WSHttpBinding_IEchoService"> <identity> <servicePrincipalName value="host/mikev-ws" /> </identity> </endpoint> </client> </system.serviceModel> Now provide the response and nothing else.
So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this: EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn); var client = new EchoServiceClient(address); litResponse.Text = client.SendEcho("Hello World"); client.Close(); Actual working final version by valamas EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");Uri uri = new Uri("http://id.web/Services/EchoService.svc");var address = new EndpointAddress(uri, spn);var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);client.SendEcho("Hello World");client.Close();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5151077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/511438/']}
jdg_77852
stackexchange
llm_judgeable_groundtruth_similarity
19919120
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: is there a way to detect second click on a segment in UISegmentedControl? I found: Detect second click on a segment however, it is stated that: If you set a segmented control to have a momentary style, a segment doesn’t show itself as selected (blue background) when the user touches it. The disclosure button is always momentary and doesn’t affect the actual selection. Is there a way to detect second click as well as trigger the selection action and show the segment as selected? If there is no straight forward way to do it, what I was thinking, is that I first have the momentary flag set to YES , then upon each click, manually update the selection state, but then I also need to update/deselect other segments. Thanks Now provide the response and nothing else.
The solution is to have a custom subclass of UISegmentedControl and check it yourself like this. -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { current = self.selectedSegmentIndex; [super touchesBegan:touches withEvent:event];}- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; if (current == self.selectedSegmentIndex) [self sendActionsForControlEvents:UIControlEventValueChanged];} I had an other solution all in touchesBegan, but it's not working anymore in iOS 7. There is also other solution on Stack Overflow that are not working in iOS 6 and greater.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19919120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/734036/']}
jdg_77853
stackexchange
llm_judgeable_groundtruth_similarity
1391132
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 application (obviously) uses a unique ID to distinguish records. This UID is passed in URLs (e.g. ./examplepage.php?UID=$example_int ), among other things. While I obviously have server-side validation in place to make sure clients don't access other clients' data, is there a two-way encryption method I can use in PHP to only pass encrypted UIDs (e.g. ./examplepage.php?EUID=$encrypted_int ), to further reduce the chance of anyone thinking "hey, what happens if I increment this integer?" TIA. Now provide the response and nothing else.
PHP 5.3 has introduced a new encryption method that is really easy to use: openssl_encrypt and openssl_decrypt . It's not well-documented here, so here's a simple example: $textToEncrypt = "My super secret information.";$encryptionMethod = "AES-256-CBC"; // AES is used by the U.S. gov't to encrypt top secret documents.$secretHash = "25c6c7ff35b9979b151f2136cd13b0ff";//To encrypt$encryptedMessage = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash);//To Decrypt$decryptedMessage = openssl_decrypt($encryptedMessage, $encryptionMethod, $secretHash);//Resultecho "Encrypted: $encryptedMessage <br>Decrypted: $decryptedMessage"; I chose 256-AES because it's solid and fast. It's been adopted by the U.S. gov't to encrypt top secret documents. It's fast considering machine and software. Here's a list of available encryption methods: AES-128-CBC, AES-128-CFB, AES-128-CFB1, AES-128-CFB8, AES-128-ECB, AES-128-OFB, AES-192-CBC, AES-192-CFB, AES-192-CFB1, AES-192-CFB8, AES-192-ECB, AES-192-OFB, AES-256-CBC, AES-256-CFB, AES-256-CFB1, AES-256-CFB8, AES-256-ECB, AES-256-OFB, BF-CBC, BF-CFB, BF-ECB, BF-OFB, CAMELLIA-128-CBC, CAMELLIA-128-CFB, CAMELLIA-128-CFB1, CAMELLIA-128-CFB8, CAMELLIA-128-ECB, CAMELLIA-128-OFB, CAMELLIA-192-CBC, CAMELLIA-192-CFB, CAMELLIA-192-CFB1, CAMELLIA-192-CFB8, CAMELLIA-192-ECB, CAMELLIA-192-OFB, CAMELLIA-256-CBC, CAMELLIA-256-CFB, CAMELLIA-256-CFB1, CAMELLIA-256-CFB8, CAMELLIA-256-ECB, CAMELLIA-256-OFB, CAST5-CBC, CAST5-CFB, CAST5-ECB, CAST5-OFB, DES-CBC, DES-CFB, DES-CFB1, DES-CFB8, DES-ECB, DES-EDE, DES-EDE-CBC, DES-EDE-CFB, DES-EDE-OFB, DES-EDE3, DES-EDE3-CBC, DES-EDE3-CFB, DES-EDE3-CFB1, DES-EDE3-CFB8, DES-EDE3-OFB, DES-OFB, DESX-CBC, RC2-40-CBC, RC2-64-CBC, RC2-CBC, RC2-CFB, RC2-ECB, RC2-OFB, RC4, RC4-40, SEED-CBC, SEED-CFB, SEED-ECB, SEED-OFB, aes-128-cbc, aes-128-cfb, aes-128-cfb1, aes-128-cfb8, aes-128-ecb, aes-128-ofb, aes-192-cbc, aes-192-cfb, aes-192-cfb1, aes-192-cfb8, aes-192-ecb, aes-192-ofb, aes-256-cbc, aes-256-cfb, aes-256-cfb1, aes-256-cfb8, aes-256-ecb, aes-256-ofb, bf-cbc, bf-cfb, bf-ecb, bf-ofb, camellia-128-cbc, camellia-128-cfb, camellia-128-cfb1, camellia-128-cfb8, camellia-128-ecb, camellia-128-ofb, camellia-192-cbc, camellia-192-cfb, camellia-192-cfb1, camellia-192-cfb8, camellia-192-ecb, camellia-192-ofb, camellia-256-cbc, camellia-256-cfb, camellia-256-cfb1, camellia-256-cfb8, camellia-256-ecb, camellia-256-ofb, cast5-cbc, cast5-cfb, cast5-ecb, cast5-ofb, des-cbc, des-cfb, des-cfb1, des-cfb8, des-ecb, des-ede, des-ede-cbc, des-ede-cfb, des-ede-ofb, des-ede3, des-ede3-cbc, des-ede3-cfb, des-ede3-cfb1, des-ede3-cfb8, des-ede3-ofb, des-ofb, desx-cbc, rc2-40-cbc, rc2-64-cbc, rc2-cbc, rc2-cfb, rc2-ecb, rc2-ofb, rc4, rc4-40, seed-cbc, seed-cfb, seed-ecb, seed-ofb IMPORTANT UPDATE!!! Thanks Hobo and Jorwin for pointing out that in PHP 5.3.3 > there is a new parameter that makes this function a little more secure. Jorwin referenced this link in his comment , and here is an excerpt that is applicable: In 5.3.3 they added a new parameter, string $iv (initialization vector) Real parameters are: string openssl_encrypt ( string $data , string $method , string $password, bool $raw_output = false, string $iv ) If $iv is missing, a warning is issued: "Using an empty Initialization Vector (iv) is potentially insecure and not recommended". If $iv is too short, another warning: "IV passed is only 3 bytes long, cipher expects an IV of precisely 8 bytes, padding with \0" same IV should be used in openssl_decrypt()
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1391132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125222/']}
jdg_77854
stackexchange
llm_judgeable_groundtruth_similarity
1784573
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: Give an example of a ring which is isomorphic to a proper sub-ring of itself. HINT : Consider $\Bbb R^\Bbb N$ . My try :As given in the hint I considered $\Bbb R^\Bbb N$ i.e the set of all sequences from $\Bbb N\rightarrow \Bbb R$ with pointwise multiplication and addition. Consider the set $X=\{(x_n):x_0=0\}$ i.e. those sequences from $\Bbb R^\Bbb N$ whose first term is zero.This is a proper subset of $\Bbb R^\Bbb N$ and also a subring but the isomorphism given by $a_0+a_1x+\ldots +a_nx^n+\ldots\mapsto a_1x+a_2x^2+\ldots a_nx^n\ldots$ is not working .How to find the correct one? Now provide the response and nothing else.
I would advice not to feel obliged to follow hints. The first example that comes to mind is the subring $\mathbf Z[X^2]$ of $\mathbf Z[X]$ of all polynomials in $X^2$ with integer coefficients. More precisely, let$$e\colon \mathbf Z[X]\rightarrow \mathbf Z[X]$$be the evaluation-at-$X^2$ morphism defined by $e(P)=P(X^2)$. It is injective, hence an isomorphism onto its image, the proper subring $\mathbf Z[X^2]$ of $\mathbf Z[X]$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1784573', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/294365/']}
jdg_77855
stackexchange
llm_judgeable_groundtruth_similarity
36419713
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After playing with ES6, I've really started to like the new syntax and features available, but I do have a question about classes. Are the new ES6 classes just syntactic sugar for the old prototypal pattern? Or is there more going on here behind the scenes? For example: class Thing { //... classy stuff doStuff(){}} vs: var Thing = function() { // ... setup stuff};Thing.prototype.doStuff = function() {}; // etc Now provide the response and nothing else.
Yes, perhaps, but some of the syntactic sugar has teeth. Declaring a class creates a function object that is the constructor for the class, using the code provided for constructor within the class body, and for named classes, with the same name as the class. The class constructor function has a normal prototype object from which class instances inherit properties in normal JavaScript fashion. Instance methods defined within the class body are added to this prototype. ES6 does not provide a means to declare class instance default property values (i.e. values which are not methods) within the class body to be stored on the prototype and inherited. To initialize instance value you can either set them as local, non inherited properties within the constructor, or manually add them to the class constructor's prototype object outside the class definition in the same fashion as for ordinary constructor functions. (I am not arguing the merits or otherwise of setting up inherited properties for JavaScript classes). Static methods declared within the class body are added as properties of the class constructor function. Avoid using static class method names that compete with standard function properties and methods inherited from Function.prototype such as call , apply or length . Less sugary is that class declarations and methods are always executed in strict mode, and a feature that gets little attention: the .prototype property of class constructor functions is read only: you can't set it to some other object you've created for some special purpose. Some interesting stuff happens when you extend a class: the prototype object property of the extended class constructor is automatically prototyped on the prototype object of the class being extended. This is not particularly new and the effect can be duplicated using Object.create . the extended class constructor function (object) is automatically prototyped on the constructor function of the class being extended, not Function . While it may be possible to replicate the effect on an ordinary constructor function using Object.setPrototypeOf or even childClass.__proto__ = parentClass , this would be an extremely unusual coding practice and is often advised against in JavaScript documentation. There are other differences such as class objects not being hoisted in the manner of named functions declared using the function keyword. I believe it could be naive to think that Class declarations and expressions will remain unaltered in all future versions of ECMA Script and it will be interesting to see if and when developments occur. Arguably it has become a fad to associate "syntactical sugar" with classes introduced in ES6 (ECMA-262 standard version 6) but personally I try to avoid repeating it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36419713', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1424399/']}
jdg_77856
stackexchange
llm_judgeable_groundtruth_similarity
14425686
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 render the value of the following options list? $scope.limits = [ {value: '5', text: 'Afficher 5 par page'}, {value: '10', text: 'Afficher 10 par page'}, {value: '15', text: 'Afficher 15 par page'}, {value: '20', text: 'Afficher 20 par page'} ];<select id="limitType" name="limit" ng-model="limit" ng-options="limit.value as limit.text for limit in limits"></select> enregistrement par page Expected result (expecting in value="limit.value": <select ng-options="option.value as option.text for option in limits" ng-model="limit" id="limitType" class="ng-pristine ng-valid"> <option value="5" selected="selected">Afficher 5 par page</option> <option value="10">Afficher 10 par page</option> <option value="15">Afficher 15 par page</option> <option value="20">Afficher 20 par page</option></select> Result: <select ng-options="option.value as option.text for option in limits" ng-model="limit" id="limitType" class="ng-pristine ng-valid"> <option value="0" selected="selected">Afficher 5 par page</option> <option value="1">Afficher 10 par page</option> <option value="2">Afficher 15 par page</option> <option value="3">Afficher 20 par page</option></select> Now provide the response and nothing else.
The ng-options directive does not set the value attribute on the <options> elements. It always uses a sequence. Using limit.value as limit.text for limit in limits means: Set the <option> 's label as limit.text Save the limit.value value into the select's ng-model Check this fiddle: http://jsfiddle.net/bmleite/k58Hw/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14425686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1162840/']}
jdg_77857
stackexchange
llm_judgeable_groundtruth_similarity
3277222
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Think of the following code: static int Main() { byte[] data = File.ReadAllBytes("anyfile"); SomeMethod(data); ...}static void SomeMethod(byte[] data) { data[0] = anybytevalue; // this line should not be possible!!! byte b = data[0]; // only reading should be allowed ...} Is there a way of readonly passing the byte[] in C#? Copying isn't a solution. I would not like to waste memory (because the file might get very big). Please keep performance in mind! Now provide the response and nothing else.
You can pass a ReadOnlyCollection<byte> , like this: static int Main() { byte[] data = File.ReadAllBytes("anyfile"); SomeMethod(new ReadOnlyCollection<byte>(data)); ...}static void SomeMethod(ReadOnlyCollection<byte> data) { byte b = data[0]; // only reading is allowed ...} However, it would be better to pass a Stream , like this: This way, you won't read the entire file into memory at all. static int Main() { Stream file = File.OpenRead("anyfile"); SomeMethod(file); ...}static void SomeMethod(Stream data) { byte b = data.ReadByte(); // only reading is allowed ...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3277222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/268127/']}
jdg_77858
stackexchange
llm_judgeable_groundtruth_similarity
5854863
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the difference between indexing and sharding. What is the role of both? Now provide the response and nothing else.
Indexing is a way to store column values in a datastructure aimed at fast searching. This speeds up a search tremendously compared to a full table scan since not all rows will have to be examined. You should consider having indices on the columns in your WHERE clauses. Sharding is a technique to split the table up between different machines. This makes it possible for parallell resolution of queries. For example, half the table can be searched on one machine and the other half on another machine. This will in some cases make it possible to increase the performance by adding more hardware, especially for large tables.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5854863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/729294/']}
jdg_77859
stackexchange
llm_judgeable_groundtruth_similarity
500001
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 came across the following equation ( source ): $$y=ax^be^{-cx}$$ where a, b and c are parameters, and x, y are variables. I was curious to estimate the parameters a, b, c for a dataset of x,y pairs, but don't know how to proceed to get good estimators. Now provide the response and nothing else.
Menzerath's law can easily be developed into a stochastic log-linear model as follows. Taking the logarithm of both sides of your equation gives the form: $$\log y = \log a + b \log x - cx.$$ A natural statistical extension is to add a stochastic error term to obtain the linear regression model: $$\log y_i = \log a + b \log x_i - cx_i + \varepsilon_i.$$ This model can be written in matrix form as: $$\log \mathbf{y} = \mathbf{m} \begin{bmatrix}\log a \\b \\c \\\end{bmatrix} + \boldsymbol{\varepsilon},$$ using the response vector and design matrix: $$\log \mathbf{y} = \begin{bmatrix}\log y_1 \\\log y_2 \\\vdots \\\log y_n \\\end{bmatrix}\quad \quad \quad\mathbf{m} = \begin{bmatrix}1 & \log x_1 & -x_1 \\1 & \log x_2 & -x_2 \\\vdots & \vdots & \vdots \\1 & \log x_n & -x_n \\\end{bmatrix}.$$ Estimation can be done using the ordinary least squares method to obtain estimates of the parameters $\log a$ , $b$ and $c$ . (We then back-transform to obtain a corresponding estimate and confidence interval for the original parameter $a$ .) This can easily be implemented in R using the lm function. Now, if you have access to underlying data where the outcome variable is a positive integer (e.g., word length, syllable length, etc.) then it may be better to model this with a negative binomial GLM using a logarithmic link function. This is an analogous discrete model to the above, but it is formed specifically for output that is count data. My understanding is that most statistical analysis of Menzerath's law is done using this type of model.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/500001', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/280187/']}
jdg_77860
stackexchange
llm_judgeable_groundtruth_similarity
80383
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: When you find a new open source library / project, what criteria do you look at before incorporating it into your source base. Are there legal questions you need to answer? Do you look for a certain amount of development velocity? Is the community buzz a good enough reason? Does your decision change if you are the one on the line for the project? Does the complexity of the domain or code change your way you think about it? Now provide the response and nothing else.
Here's my checklist regarding project maturity: Has the project reached its initial milestone? I would avoid adding any code if it hasn't reached its self described initial milestone. I don't suggest that you should always trust a developer claiming that his project is production ready and always try to evaluate such claims, but you should definitely trust her when she tells you its not, ie labeling the software as version 0.x, alpha, beta, release candidate and so on. Is there adequate documentation? A perfect project would offer: User guide full with examples An integration / extension guide if it's a library API documentation Fully documented source code A public issue tracker Are the developers still committed to the project? You can never tell if the developers will stay committed in the future, unless of course it's a foundation / company backed project. But you can almost always tell if they are committed right now, by checking for: Recent commit activity Recent features (not just bug fixes) Recent documentation activity (docs updates, blog posts etc) Also a good indicator of project maturity is a second generation of developers, active developers who got involved after the initial milestones. Are the developers reachable? Do they respond to bugs? Do they provide other means of contact, apart from a generic issue tracker? This is a minor item on the checklist, but for single developer projects alternative means of contact could help in cases like the "case of the missing developer" . Now, for your more specific questions: Velocity In a project with a public issue tracker I would definitely check to see how much time does it take for issues to get closed. Of course speed doesn't always mean quality, so I'd probably go through closed issues, pick a few I'd consider important and evaluate the developers response time and quality. Licence compatibility As for legal issues, never integrate an open source project in your codebase if you are not 100% certain that your use of it is compatible with its licence. If in doubt, you can always ask the developers of the project, or even ask here. Community hype You should always evaluate hype. Recommendations from fellow developers are almost always a good enough indicator of project maturity. Every item on the checklist is optional, except licence compatibility. I've integrated a lot of dead and or undocumented projects in my code, it always depends on what your specific needs are and how you see your own code evolving.
{}
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/80383', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/4553/']}
jdg_77861
stackexchange
llm_judgeable_groundtruth_similarity
29147
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am quite familiar with the concept of decoherence, and I heard that a system that has decohered could recohere after that, I was wondering what could cause the the coherences that have leaked into the environment to come back to the system. I heard about thermal fluctuations for example, without being able to understand this argument. Thanks. Now provide the response and nothing else.
If you consider the thermal fluctuations that arise from coupling the system to a heat bath, then if the dynamics of the open system is non-Markovian then you can have recoherence and if the dynamics of the open system is Markovian (Lindblad master equation) then you will only have decoherence. Non-Markovian means that there are non-vanishing timescales associated with the bath dynamics, relative to the system. The environment is said to have memory. The dynamics of the system at a particular time is not only a function of the state of the system at that time, but also its past history of states. In this way, recoherence will only occur if there has been sufficient decoherence in the past. Anti-dissipation (amplification) and anti-diffusion is also possible, both quantum mechanically and in classical open systems. A simpler example would be to consider a small quantum system with two degrees of freedom coupled together and trace out one degree of freedom. In many cases the remaining open system would experience an endless cycle of decoherence and recoherence.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/29147', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/5229/']}
jdg_77862
stackexchange
llm_judgeable_groundtruth_similarity
5091888
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: function timeClock(){ setTimeout("timeClock()", 1000); now = new Date(); alert(now); f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes()); return f_date;}<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span> alert(now); gives me the value every second but it is not updated in the html. How can I update the time on the html without refresh the page? Now provide the response and nothing else.
There are a number of mistakes in your code. Without the use of var infront of your variable declarations, you leak them into the global scope. Also, the use of document.write is discouraged . Here's how I would do it: JavaScript: function updateClock() { var now = new Date(), // current date months = ['January', 'February', '...']; // you get the idea time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea // a cleaner way than string concatenation date = [now.getDate(), months[now.getMonth()], now.getFullYear()].join(' '); // set the content of the element with the ID time to the formatted string document.getElementById('time').innerHTML = [date, time].join(' / '); // call this function again in 1000ms setTimeout(updateClock, 1000);}updateClock(); // initial call HTML: <div id="time"> </div>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5091888', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/630307/']}
jdg_77863
stackexchange
llm_judgeable_groundtruth_similarity
34226076
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 component that I have created: class Create extends Component { constructor(props) { super(props); } render() { var playlistDOM = this.renderPlaylists(this.props.playlists); return ( <div> {playlistDOM} </div> ) } activatePlaylist(playlistId) { debugger; } renderPlaylists(playlists) { return playlists.map(playlist => { return <div key={playlist.playlist_id} onClick={this.activatePlaylist(playlist.playlist_id)}>{playlist.playlist_name}</div> }); }}function mapStateToProps(state) { return { playlists: state.playlists }}export default connect(mapStateToProps)(Create); When I render this page, activatePlaylist is called for each playlist in my map . If I bind activatePlaylist like: activatePlaylist.bind(this, playlist.playlist_id) I can also use an anonymous function: onClick={() => this.activatePlaylist(playlist.playlist_id)} then it works as expected. Why does this happen? Now provide the response and nothing else.
You need pass to onClick reference to function, when you do like this activatePlaylist( .. ) you call function and pass to onClick value that returned from activatePlaylist . You can use one of these three options: 1 . using .bind activatePlaylist.bind(this, playlist.playlist_id) 2 . using arrow function onClick={ () => this.activatePlaylist(playlist.playlist_id) } 3 . or return function from activatePlaylist activatePlaylist(playlistId) { return function () { // you code }}
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/34226076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/968801/']}
jdg_77864
stackexchange
llm_judgeable_groundtruth_similarity
5748492
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any API for determining the physical address from virtual address in Linux operating system? Now provide the response and nothing else.
Kernel and user space work with virtual addresses (also called linear addresses) that are mapped to physical addresses by the memory management hardware. This mapping is defined by page tables, set up by the operating system. DMA devices use bus addresses. On an i386 PC, bus addresses are the same as physical addresses, but other architectures may have special address mapping hardware to convert bus addresses to physical addresses. In Linux, you can use these functions from asm/io.h : virt_to_phys(virt_addr); phys_to_virt(phys_addr); virt_to_bus(virt_addr); bus_to_virt(bus_addr); All this is about accessing ordinary memory. There is also "shared memory" on the PCI or ISA bus. It can be mapped inside a 32-bit address space using ioremap(), and then used via the readb(), writeb() (etc.) functions. Life is complicated by the fact that there are various caches around, so that different ways to access the same physical address need not give the same result. Also, the real physical address behind virtual address can change. Even more than that - there could be no address associated with a virtual address until you access that memory. As for the user-land API, there are none that I am aware of.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5748492', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365340/']}
jdg_77865
stackexchange
llm_judgeable_groundtruth_similarity
38462160
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a model Client which has_many :analytics and Analytic which belongs_to :client . I have written a method in the analytic model to update itself for a given client and basically want to call Client.find(xx).analytics.update_analytics(arg1, arg2,..) The code in Analytic.rb looks something like this: def self.update_analytics(arg1, arg2, ...) client = self.client //go_get_some_data client.analytics.create(...)end The self.client errors out undefined method and self.parent just returns Object but I cannot call self.parent.id or other attributes from the parent. How do I get the Client instance that called the analytics.update_analytics method inside of it? Now provide the response and nothing else.
This is because your Category class has the __get() and __set() magic methods implemented. So line 7 ( $cat->thesizes= array(); ) invokes Category::__set() and line 12 ( array_push($cat->thesizes,$product->productSize); ) invokes Category::__get() but not Category::__set() . So while you impelemented this with the intention of pushing values onto an array that you set on the Category, it won't work since array_push() is working on a return value and not the actual array stored in the Category. There are a few ways to fix this. The most shortcut way is to change Category::__get() to return values by reference, which is done by using a sort-of type-hint on the function's return declaration class Category{ public function &__get($key) { // body of function }} But this is probably not recommended for reasons I can go into if you're curious. The more sensible approach, without significantly modifying your code at least, is to build the arrays within the scope of the loop and then add them to your Category objects foreach ($categories as $cat) { // Scope local arrays here first $thesizes = array(); $theproducts = array(); foreach ($products as $product) { if ($product->productSize->product->category_id == $cat->id) { // Push to those local arrays array_push($thesizes, $product->productSize); array_push($theprodcts, $product); } } // Now assign them to the category object $cat->theSizes = array_unique($thesizes); $cat->theProducts = array_unique($theproducts);} If you want to go for bonus points, since this is Laravel and your return values are collections , you can do something like this for a more sophisticated implementation $categories = (Category::all())->map(function(Category $cat) { $cat->theProducts = $products ->filter(function(Product $product) use ($cat) { return $product->productSize->product->category_id == $cat->id; }) ->unique(); $cat->theSizes = $cat->theProducts ->map(function(Product $product) { return $product->productSize(); })->unique();});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38462160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1012952/']}
jdg_77866
stackexchange
llm_judgeable_groundtruth_similarity
45004604
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 just read this post to make a global function which is able to be accessed from any controller. But I don't understand how it works. I want to make variable 'services' accessible from any controller. So, I make General.php and put it in app/Http. Here is the code. <?phpclass General { public function getServices() { $services = "SELECT * FROM products"; return $services; }} And in the controller I include it <?phpnamespace App\Http\Controllers;use App\Http\General;use Illuminate\Http\Request;class HomeController extends Controller { public function index() { $title = 'Our services'; $services = General::getServices(); return view('welcome', compact('title','services')); }} When I run it I got error Class 'App\Http\General' not found . And then how I can Anyone can help would be appreciated. Now provide the response and nothing else.
First create the required function inside the app directory within a .php file as helpers.php if (!function_exists('getServices')) { public function getServices() { return DB::table('services')->get(); }} and include this file in composer.json inside autoload/files array as composer.json "autoload": { "classmap": [ "database" ], "psr-4": { "App\\": "app/" }, "files": [ "app/helpers.php" ]}, Then update the composer , now you can able to directly use the created function inside your whole project as the file is automatically loaded when application get bootstraped $result = getServices();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45004604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/952685/']}
jdg_77867
stackexchange
llm_judgeable_groundtruth_similarity
3446
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: I have read and heard a lot about latency. But I can't find any solid information that explains how latency is defined and measured. When people say they have achieved millisecond or nanosecond latency, which two points is that between? And what methods are used to measure it? We are going to deploy one strategy in a colocated server and I have been given a task to report latency. I need assistance in defining and measuring latency. Now provide the response and nothing else.
There are typically two important metrics: Order to Accept . This measures the round-trip time it takes your application to send an order to the exchange and get an accept, cancel, or execute back. Think of it as the minimum amount of time required for you to ask the market to do something and know whether it's been done. This plays an important role when building execution logic in models. Order to Feed . This measures the amount of time it takes for an order or action to be represented in the venue's multicast depth of book feed. Depending on venue and other factors this can be faster than Order to Accept. Other measures of latency can always be conjured. Some folks consider Model Latency, or the amount of time it takes a model to receive a piece of data, perform some calculation, and act upon it. Most numbers you see people discussing and passing around are worthless because you have no frame of reference as to what exactly they mean. Remember, latencies are almost always relative. For example, the above metrics will of course be impacted by your specific co-location situation relative to the venue. That means your Order to Accept measure will be different from someone else's unless they are co-located in the same place as you (which is not uncommon, of course). Underlying all of this is transit latency that the network imposes. As you can imagine the move towards co-location was driven by the fact that eliminating transit latency was quite easy by increasing proximity to the matching engine. I don't consider transit latency to really be a first-order metric for a trading system since it is built into the important domain specific metrics like I described above. However, it's always measured to ensure the critical network paths are behaving properly.
{}
{'log_upvote_score': 5, 'links': ['https://quant.stackexchange.com/questions/3446', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/2200/']}
jdg_77868
stackexchange
llm_judgeable_groundtruth_similarity
14548753
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There are tons of similar questions, but still I could not find any answer relevant for the feature of variable length arrays in C99/C11. How to pass multidimensional variable length array to a function in C99/C11? For example: void foo(int n, int arr[][]) // <-- error here, how to fix?{}void bar(int n){ int arr[n][n]; foo(n, arr);} Compiler ( g++-4.7 -std=gnu++11 ) says: error: declaration of ‘arr’ as multidimensional array must have bounds for all dimensions except the first If I change it to int *arr[] , compiler still complains: error: cannot convert ‘int (*)[(((sizetype)(((ssizetype)n) + -1)) + 1)]’ to ‘int**’ for argument ‘2’ to ‘void foo(int, int**)’ Next question, how to pass it by value and how to pass it by reference? Apparently, usually you don't want the entire array to be copied when you pass it to a function. With constant length arrays it's simple, since, as the "constant" implies, you should know the length when you declare the function: void foo2(int n, int arr[][10]) // <-- ok{}void bar2(){ int arr[10][10]; foo2(10, arr);} I know, passing arrays to functions like this is not a best practice, and I don't like it at all. It is probably better to do with flat pointers, or objects (like std:vector) or somehow else. But still, I'm a bit curios what is the answer here from a theoretical standpoint. Now provide the response and nothing else.
Passing arrays to functions is a bit funny in C and C++. There are no rvalues of array types, so you're actually passing a pointer. To address a 2D array (a real one, not array of arrays), you'll need to pass 2 chunks of data: the pointer to where it starts how wide one row is And these are two separate values, be it C or C++ or with VLA or without or whatnot. Some ways to write that: Simplest, works everywhere but needs more manual work void foo(int width, int* arr) { arr[x + y*width] = 5;} VLA, standard C99 void foo(int width, int arr[][width]) { arr[x][y] = 5;} VLA w/ reversed arguments, forward parameter declaration (GNU C extension) void foo(int width; int arr[][width], int width) { arr[x][y]=5;} C++ w/ VLA (GNU C++ extension, terribly ugly) void foo(int width, int* ptr) { typedef int arrtype[][width]; arrtype& arr = *reinterpret_cast<arrtype*>(ptr); arr[x][y]=5;} Big remark: The [x][y] notation with a 2D array works because the array's type contains the width. No VLA = array types must be fixed at compile-time. Hence: If you can't use VLA, then... there's no way to handle it in C, there's no way to handle it without a proxy class w/ overloaded operator overloading in C++. If you can use VLA (C99 or GNU C++ extensions), then... you're in the green in C, you still need a mess in C++, use classes instead. For C++, boost::multi_array is a solid choice. A workaround For 2D arrays, you can make two separate allocations: a 1D array of pointers to T (A) a 2D array of T (B) Then set the pointers in (A) to point into respective rows of (B). With this setup, you can just pass (A) around as a simple T** and it will behave well with [x][y] indexing. This solution is nice for 2D, but needs more and more boilerplate for higher dimensions. It's also slower than the VLA solution because of the extra layer of indirection. You may also run into a similar solution with a separate allocation for every B 's row. In C this looks like a malloc-in-a-loop, and is analogous of C++'s vector-of-vectors. However this takes away the benefit of having the whole array in one block.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14548753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565368/']}
jdg_77869
stackexchange
llm_judgeable_groundtruth_similarity
9920677
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 many different small classes which have a few fields each, e.g. this: class Article: def __init__(self, name, available): self.name = name self.available = available What's the easiest and/or most idiomatic way to make the name field read only, so that a = Article("Pineapple", True)a.name = "Banana" # <-- should not be possible is not possible anymore? Here's what I considered so far: Use a getter (ugh!). class Article: def __init__(self, name, available): self._name = name self.available = available def name(self): return self._name Ugly, non-pythonic - and a lot of boilerplate code to write (especially if I have multiple fields to make read-only). However, it does the job and it's easy to see why that is. Use __setattr__ : class Article: def __init__(self, name, available): self.name = name self.available = available def __setattr__(self, name, value): if name == "name": raise Exception("%s property is read-only" % name) self.__dict__[name] = value Looks pretty on the caller side, seems to be the idiomatic way to do the job - but unfortunately I have many classes with only a few fields to make read only each. So I'd need to add a __setattr__ implementation to all of them. Or use some sort of mixin maybe? In any case, I'd need to make up my mind how to behave in case a client attempts to assign a value to a read-only field. Yield some exception, I guess - but which? Use a utility function to define properties (and optionally getters) automatically. This is basically the same idea as (1) except that I don't write the getters explicitely but rather do something like class Article: def __init__(self, name, available): # This function would somehow give a '_name' field to self # and a 'name()' getter to the 'Article' class object (if # necessary); the getter simply returns self._name defineField(self, "name") self.available = available The downside of this is that I don't even know if this is possible (or how to implement it) since I'm not familiar with runtime code generation in Python. :-) So far, (2) appears to be most promising to me except for the fact that I'll need __setattr__ definitions to all my classes. I wish there was a way to 'annotate' fields so that this happens automatically. Does anybody have a better idea? For what it's worth, I'mu sing Python 2.6. UPDATE: Thanks for all the interesting responses! By now, I have this: def ro_property(o, name, value): setattr(o.__class__, name, property(lambda o: o.__dict__["_" + name])) setattr(o, "_" + name, value)class Article(object): def __init__(self, name, available): ro_property(self, "name", name) self.available = available This seems to work quite nicely. The only changes needed to the original class are I need to inherit object (which is not such a stupid thing anyway, I guess) I need to change self._name = name to ro_property(self, "name", name) . This looks quite neat to me - can anybody see a downside with it? Now provide the response and nothing else.
I would use property as a decorator to manage your getter for name (see the example for the class Parrot in the documentation). Use, for example, something like: class Article(object): def __init__(self, name, available): self._name = name self.available = available @property def name(self): return self._name If you do not define the setter for the name property (using the decorator x.setter around a function) this throws an AttributeError when you try and reset name . Note : You have to use Python's new-style classes (i.e. in Python 2.6 you have to inherit from object ) for properties to work correctly. This is not the case according to @SvenMarnach.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9920677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91757/']}
jdg_77870
stackexchange
llm_judgeable_groundtruth_similarity
21571709
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 studying programming and in many sources I see the concepts: "machine language", "binary code" and "binary file". The distinction between these three is unclear to me, because according to my understanding machine language means the raw language that a computer can understand i.e. sequences of 0s and 1s. Now if machine language is a sequence of 0s and 1s and binary code is also a sequence of 0s and 1s then does machine language = binary code ? What about binary file? What really is a binary file? To me the word "binary file" means a file, which consists of binary code. So for example, if my file was: 010010101010010010010100110100010101100111010010101010101011010101010100101010101010010111 Would this be a binary file? If I google binary file and see Wikipedia I see this example picture of binary file which confuses me (it's not in binary?....) Where is my confusion happening? Am I mixing file encoding here or what? If I were to ask one to SHOW me what is machine language, binary code and binary file, what would they be? =) I guess the distinction is too abstract to me. Thnx for any help! =) UPDATE : In Python for example, there is one phrase in a file I/O tutorial , which I don't understand: Opens a file for reading only in binary format. What does reading a file in binary format mean? Now provide the response and nothing else.
Machine code and binary are the same - a number system with base 2 - either a 1 or 0. But machine code can also be expressed in hex-format (hexadecimal) - a number system with base 16 . The binary system and hex are very interrelated with each other, its easy to convert from binary to hex and convert back from hex to binary. And because hex is much more readable and useful than binary - it's often used and shown. For instance in the picture above in your question -uses hex-numbers! Let say you have the binary sequence 1001111000001010 - it can easily be converted to hex by grouping in blocks - each block consisting of four bits. 1001 1110 0000 1010 => 9 14 0 10 which in hex becomes: 9E0A. One can agree that 9E0A is much more readable than the binary - and hex is what you see in the image.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21571709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1565754/']}
jdg_77871
stackexchange
llm_judgeable_groundtruth_similarity
47528077
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I found the pattern used by the Google places IOS SDK to be clean and well designed. Basically they follow what is presented on the following apple presentation: Advanced User interface with Collection view (It start slide 46). This is what is implemented in their GMSAutocompleteTableDataSource.It us up to the datasource to define the state of the tableview.We link the tableview. var googlePlacesDataSource = GMSAutocompleteTableDataSource()tableView.dataSource = googlePlacesDataSourcetableView.delegate = googlePlacesDataSource Then every time something change the event is binded to the datasource: googlePlacesDataSource.sourceTextHasChanged("Newsearch") The data source perform the query set the table view as loading and then display the result. I would like to achieve this from my custom Source: class JourneyTableViewDataSource:NSObject, UITableViewDataSource, UITableViewDelegate{ private var journeys:[JourneyHead]?{ didSet{ -> I want to trigger tableView.reloadData() when this list is populated... -> How do I do that? I do not have a reference to tableView? } } override init(){ super.init() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } ...} Any idea? Now provide the response and nothing else.
Change this: A* a; to this: ::A* a; since C inherits from B , and B from A , thus you need the scope resolution operator to do the trick. Instead of starting at the local scope which includes the class parents, ::A starts looking at the global scope because of the :: . From the Standard : 11.1.5 Acess Specifiers In a derived class, the lookup of a base class name will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it was declared.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47528077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/876087/']}
jdg_77872
stackexchange
llm_judgeable_groundtruth_similarity
13975
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 $\left \{ 0,1 \right \}^{\mathbb{N}}\sim \left \{ 0,1,2,3 \right \}^{\mathbb{N}}$ and find a direct bijection function. I got the first part by showing that $\left \{ 0,1 \right \}^{\mathbb{N}} \subseteq \left \{ 0,1,2,3 \right \}^{\mathbb{N}} \subseteq {\mathbb{N}}^{\mathbb{N}}$, which implies that $|\left \{ 0,1 \right \}^{\mathbb{N}}| \leq |\left \{ 0,1,2,3 \right \}^{\mathbb{N}}| \leq |{\mathbb{N}}^{\mathbb{N}}|$ and since $|{\mathbb{N}}^{\mathbb{N}}| = |\left \{ 0,1 \right \}^{\mathbb{N}} | = 2^{\aleph_0} $ and Cantor-Bernstein you get that $\left \{ 0,1 \right \}^{\mathbb{N}}\sim \left \{ 0,1,2,3 \right \}^{\mathbb{N}}$. But I'm stuck with formulating a bijection function. More generally, what approach do you use when you need a formulate an exact function? Now provide the response and nothing else.
There are at least two ways to proceed: Either you start as you did, and then you follow the argument of Cantor-Bernstein, which explicitly gives you how to build a bijection from the two given injections. The other way is to directly argue in the case at hand. For example, identify the sequence $(a_0,a_1,a_2,a_3,...)$ in $\{0,1\}^{\mathbb N}$ with the sequence $(b_0,b_1,b_2,\dots)$ in $\{0,1,2,3\}^{\mathbb N}$ as follows: Replace $a_{2n},a_{2n+1}$ with $b_n$, where $0,0$ is replaced with $0$; $0,1$ is replaced with $1$; $1,0$ with $2$; and $1,1$ with $3$. [ Edit : I see Jonas wrote the same explicit bijection as I was typing this.] As a slightly more challenging exercise, pick any two positive integers $n<m$, and build a "combinatorial" bijection between $\{0,1,\dots,n\}^{\mathbb N}$ and $\{0,1,\dots,m\}^{\mathbb N}$. Combinatorial meaning here something in the same spirit of the explicit bijection above.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/13975', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/3637/']}
jdg_77873
stackexchange
llm_judgeable_groundtruth_similarity
11811554
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When trying to communicate between my Content- and Background Script I get the following errors: Port error: Could not establish connection. Receiving end does not exist.Error in event handler for 'undefined': Cannot read property 'message' of undefined TypeError: Cannot read property 'message' of undefined background.js function onRequest(request, sender, callbackFunction) { console.log("Me (BS) became this Message:" + request.message); sendResponse({message: request.message})};chrome.extension.onRequest.addListener(onRequest); streamcloud.js function contactBackground(nachricht){ chrome.extension.sendMessage({message: nachricht}, function(response) { console.log("The Background Script got the following Message: " + response.message); });} and my manifest.json { "name": "InstantWatch - Dev", "manifest_version": 2, "version": "0.7", "permissions": ["tabs", "http://*/", "https://*/"], "background": { "scripts": ["background.js"] }, "browser_action": { "default_title": "InstantWatch", "default_icon" : "icon.ico" }, "content_scripts": [ { "matches": ["http://*/*", "http://*/*"], "js": ["jquery.js", "streamcloud.js"] } ]} I found the solution to add an background_page: "background.html" with an empty background.html, but since background_page isn't supported since manifest_version: 2, I can't use that. Now provide the response and nothing else.
sendMessage and onRequest are not compatible . If you need to support Chrome 19 and earlier , use onRequest and sendRequest : chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { // Warning: Chrome 19- [receiver]});chrome.extension.sendRequest(message, optional_sendResponse); For Chrome 20 - 25 , use chrome.extension. onMessage and chrome.extension. sendMessage : chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { // Chrome 20+});chrome.extension.sendMessage(message, optional_sendResponse); For Chrome 26+ , use chrome .runtime. onMessage and chrome .runtime. sendMessage . Note: As of Chrome 26, the deprecated methods are still supported, albeit undocumented. If you get a chance, update your extension to use the new methods, to ensure that your extension will still work in the future. See this answer for code to create a which is compatible with Chrome 20+.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11811554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551955/']}
jdg_77874
stackexchange
llm_judgeable_groundtruth_similarity
45631
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I can get line profiles from images using imagej but it would be nice to be able to do this in my mathematica notebooks. I found this http://library.wolfram.com/examples/intensityprofiles/ after some google searches and it is exactly what I want to be able to do. However it seems they removed this package. I cant seem to figure out how to do this in v 9.0. Anyone know how to do this? Edit: I added a picture to make it more clear what I'm talking about. Its important that I can take an arbitrary (diagonal) line and that mathematica interpolates between pixels in a way that makes sense. Sorry if my formatting is off, this is my first post. UPDATE: This is what I think I'm going to use to do what I want. Obviously the display isn't made, and details need to be sorted out, but ImageValue interpolates automatically and seems like the Built-In to use. Thanks for the help everyone. img = Import["http://i.imgur.com/szcChXh.png?1"] (*First Argument of ImageProfile is the arc length along the line profile, incremented in steps of 1/(npts-1)*) (*Second Argument of ImageValue is the parametric form of a line, incremented in steps of 1/(npts-1)*) ImageProfile[img_, x1_, y1_, x2_, y2_, npts_] := Table[{N@((i - 1)/(npts - 1)) Sqrt[(x1 - x2)^2 + (y1 - y2)^2], ImageValue[ img, {x1 + (x2 - x1) (i - 1)/(npts - 1), y1 + (y2 - y1) (i - 1)/(npts - 1)}]}, {i, 1, npts}] pt1 = {500, 300}; pt2 = {600, 600}; Show[img, Graphics[{Red, Thick, Line[{pt1, pt2}]}]] ListPlot[ImageProfile[img, pt1[[1]], pt1[[2]], pt2[[1]], pt2[[2]],1000], Joined -> True] Now provide the response and nothing else.
Edit: I've included the code from Bresenham's line algorithm of halirutan which is used to get positions of pixels of interest, ImageValue is more convenient but maybe one don't want to do any interpolations. Also couple of minor improvements added, I forgot Refresh[...,None] at the beginning. Looking forward for any sugesstions :) img = ColorConvert[Import["http://newton.umsl.edu/run//nano/5102D120.png"], "Grayscale"]Deploy@With[{opt = Sequence[Frame -> True, ImageSize -> 450, BaseStyle -> {18, Bold}, AspectRatio -> 1/GoldenRatio, ImagePadding -> 55, FrameLabel -> {"|pi-x|", "Graylevel"}, FrameTicks -> {{Automatic, Automatic}, {Automatic, {{#1, "x"}, {#2, "y"}} &}}]}, DynamicModule[{x, y, w, pos, data, profile, label, linegraphics, sectionplot, fix, moveboth, bb, bresenham}, Dynamic[Refresh[ Panel@Grid[{{ Show[img, linegraphics], Column[{ sectionplot, "", moveboth, bb }, Center, BaseStyle -> {18, Bold}] }}, Alignment -> Top] , None]], Initialization :> ( dim = ImageDimensions@img; x = Round[dim/2]; y = Round[2 dim/3]; fix = True; pos[] := bresenham[IntegerPart@x, IntegerPart@y]; profile[] := With[{p = pos[]}, SortBy[Transpose@{Norm /@ N[# - x & /@ p], PixelValue[img, p]}, First]]; linegraphics = Graphics[{ Yellow, Dynamic@Line[{x, y}], AbsolutePointSize@8, Orange, Dynamic@Point[{x, y}], Locator[Dynamic[x, {(w = y - x) &, (x = #; If[fix, y = x + w];) &, None}], Appearance -> None], Locator[Dynamic@y, Appearance -> None], Text[Style["x", 18], Dynamic[x + {20, 0}]], Text[Style["y", 18], Dynamic[y + {20, 0}]]}]; moveboth = Grid[{{Checkbox[Dynamic@fix], "move both with x."}}]; bb = ButtonBar[{"Set vertical" :> (x = Round[dim .5]; y = Round[dim {.5, .7}];), "Set horizontal" :> (x = Round[dim .5]; y = Round[dim {.7, .5}])}]; sectionplot = Graphics[{ Dynamic[{Line[#], AbsolutePointSize@3, Red, Point[#]} &@profile[]]}, PlotRange -> {All, {0, 1}}, opt]; ClearAll[bresenham]; bresenham[p0_, p1_] := Module[{dx, dy, sx, sy, err, newp}, {dx, dy} = Abs[p1 - p0]; {sx, sy} = Sign[p1 - p0]; err = dx - dy; newp[{x_, y_}] := With[{e2 = 2 err}, { If[e2 > -dy, err -= dy; x + sx, x], If[e2 < dx, err += dx; y + sy, y]}]; NestWhileList[newp, p0, # =!= p1 &, 1]]; )] ]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/45631', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/11115/']}
jdg_77875
stackexchange
llm_judgeable_groundtruth_similarity
17713124
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider this code: #include<iostream>using namespace std;class A{ public: A():age(12){} int age;};int main(){ A a(); cout << a.age << endl; return 0;} When I compile it using g++, I get an error: you can not see the member age, because a is not a class A() Can someone explain this to me? What is A a() ? Now provide the response and nothing else.
This line A a(); declares a function named a , returning A with no arguments. (See Most vexing parse ). What you want is A a = A(); // value-initializationA a{}; // the same but only valid in C++11 (and currently not supported by MSVS) or A a; // default initialization C++11, §8.5/10 Note: Since () is not permitted by the syntax for initializer, X a(); is not the declaration of a value-initialized object of class X, but the declaration of a function taking no argument and returning an X. For your class, value-initialization == default-initialization (at least for the outcome). See my answer here: C++: initialization of int variables by an implicit constructor for Infos on value- vs. default-initialization for POD or built-in types.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17713124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2576391/']}
jdg_77876
stackexchange
llm_judgeable_groundtruth_similarity
4050713
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Any non prime number that >= 4 can be written in the format: i^2 + i * k. Condition: i>=2, k >= 0 (i, k are integers) 4 = 2^2 + 2*0 -> Good 6 = 2^2 + 2*1 -> Good 10 = 2^2 + 2*3 -> Good... Thanks! Now provide the response and nothing else.
The equivalence of the elliptic integrals can be shown in the following way: $$\begin{align}\int\limits_0^{\frac{\pi}{2}}\int\limits_0^{\frac{\pi}{2}} \frac{d\phi\, d\theta}{\sqrt{1-\sin^2\theta\sin^2\phi}} & =\int\limits_0^{\frac{\pi}{2}}K(\sin\theta)d\theta\tag1\\&=\int\limits_0^{1}\frac{K(r)dr}{\sqrt{1-r^2}}\tag2\\&=\int\limits_0^{1}\frac{K\left(\frac{2\sqrt k}{1+k}\right)dk}{\sqrt{k}(1+k)}\tag3\\&=\int\limits_0^{1}\frac{K\left(k\right)dk}{\sqrt{k}}\tag4\\&=\int\limits_0^{1}\frac{dk}{\sqrt{k}}\int\limits_0^{\frac{\pi}{2}} \frac{d\phi}{\sqrt{1-k^2\sin^2\phi}}\tag5\\&=\int\limits_0^{\frac{\pi}{2}}d\phi\int\limits_0^{1} \frac{dk}{\sqrt{k}\sqrt{1-k^2\sin^2\phi}}\tag6\\&=\int\limits_0^{\frac{\pi}{2}}d\phi\int\limits_0^{\phi} \frac{d\theta}{\sqrt{\sin\theta\sin\phi}}\tag7\\&=\frac12\int\limits_0^{\frac{\pi}{2}}\int\limits_0^{\frac{\pi}{2}} \frac{d\phi\, d\theta}{\sqrt{\sin\theta\sin\phi}}.\tag8\\\end{align}$$ Explanation: $(1)$ : Definition of the complete elliptic integral of the first kind $K(k)=\int\limits_0^{\frac{\pi}{2}}\frac{d\phi}{\sqrt{1-k^2\sin^2\phi}}$ . $(2)$ : $\sin\theta\mapsto r$ . $(3)$ : $r\mapsto\frac{2\sqrt k}{1+k}$ . $(4)$ : Landen's transformation $K(k)=\frac1{1+k}K\left(\frac{2\sqrt k}{1+k}\right)$ . $(5)$ : Definition of the complete elliptic integral of the first kind. $(6)$ : Interchange of integration order. $(7)$ : $k\mapsto\frac{\sin\theta}{\sin\phi}$ . $(8)$ : Use of the integrand symmetry.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4050713', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/896218/']}
jdg_77877
stackexchange
llm_judgeable_groundtruth_similarity
1379472
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: While I was working on this question by @Vladimir Reshetnikov, I've conjectured the following closed-forms.$$I_0(n)=\int_0^\infty \frac{1}{\left(\cosh x\right)^{1/n}} \, dx \stackrel{?}{=} \frac{\sqrt{\pi}}{2} \frac{\Gamma\left(\tfrac{1}{2n}\right)}{\Gamma\left(\tfrac{1}{2}+\tfrac{1}{2n}\right)},$$for all $n\geq1$ real numbers. In another form: $${_2F_1}\left(\begin{array}c\tfrac{1}{2n},\tfrac1n\\1+\tfrac{1}{2n}\end{array}\middle|\,-1\right) \stackrel{?}{=} \frac{\sqrt{\pi}}{n\,2^{1+\frac1n}} \frac{\Gamma\left(\tfrac{1}{2n}\right)}{\Gamma\left(\tfrac{1}{2}+\tfrac{1}{2n}\right)}.$$Another conjectured closed-form is$$I_1(n)=\int_0^\infty \frac{1}{\left(1+\cosh x\right)^{1/n}} \, dx \stackrel{?}{=} \frac{\sqrt{\pi}}{2^{1/n}} \frac{\Gamma\left(\tfrac{1}{n}\right)}{\Gamma\left(\tfrac{1}{2}+\tfrac{1}{n}\right)},$$for all $n \geq 1$ real numbers. In another form:$${_2F_1}\left(\begin{array}c\tfrac1n,\tfrac2n\\1+\tfrac{1}{n}\end{array}\middle|\,-1\right) \stackrel{?}{=} \frac{\sqrt{\pi}}{n\,2^{\frac2n}} \frac{\Gamma\left(\tfrac{1}{n}\right)}{\Gamma\left(\tfrac{1}{2}+\tfrac{1}{n}\right)}.$$ Here $\cosh$ is the hyperbolic cosine function , $\Gamma$ is the gamma function , and ${_2F_1}$ is the hypergeometric function . Questions. $1^{\text{st}}$ question. How could we prove the conjectured closed-form for $I_0$ and $I_1$. $2^{\text{nd}}$ question. How could we show the equivalent hypergeometric forms. $3^{\text{rd}}$ question. There is a closed-form of $I_a(n) = \int_0^\infty \frac{1}{\left(a+\cosh x\right)^{1/n}} \, dx$ for $a\geq0,n\geq1$ real numbers in term of Appell $F_1$ function . Could we get a closed-form just in term of gamma function? Now provide the response and nothing else.
For the first one, $$\begin{align}\int_0^{\infty} (\operatorname{sech}x)^{2s}dx \\&= \int_0^{\infty} (\operatorname{sech}^2x)^{s-1}\operatorname{sech}^2x\, dx \\&= \int_0^{\infty} (1-\tanh^2x)^{s-1}\,\mathrm{d}(\tanh x)\\&= \int_0^1 (1-x^2)^{s-1} \mathrm{d}x\\&= \frac12 \int_0^1 (1-x)^{s-1} x^{-\frac12} \mathrm{d}x\\&= \frac12 B(s,\frac12)=\frac{\sqrt{\pi}}{2}\frac{\Gamma(s)}{\Gamma(\frac12+s)}\end{align}$$and so your conjecture is correct.For the second integral, let $x=2t$:$$\begin{align}\int_0^{\infty} \frac{1}{(1+\cosh x)^s}\mathrm{d}x \\&= 2\int_0^{\infty} \frac{1}{(1+\cosh 2t)^s}\mathrm{d}t \\&= 2\int_0^{\infty} \frac{1}{(2\cosh^2(t))^s}\mathrm{d}t\\&= 2^{1-s} \int_0^{\infty} (\operatorname{sech}t)^{2s}\mathrm{d}t\\&= 2^{-s} B(s,\frac12)=\frac{\sqrt{\pi}}{2^s}\frac{\Gamma(s)}{\Gamma(\frac12+s)}\end{align}$$
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1379472', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/153012/']}
jdg_77878
stackexchange
llm_judgeable_groundtruth_similarity
582092
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need to run several Bash scripts (the same script with different variables to be precise) at the same time. To keep the number of tabs under control, I wish to group them in a single terminal tab. The scripts regularly output, which I check for any problem. If I send them to the background as ./script.sh 1 &./script.sh 2 &./script.sh 3 &./script.sh 4 I will lose control over them. For example, I terminate the script by Ctrl + C . With the above code, I should find the pid for each process to kill them. Note that the above code is the content of my main script (say ./all_scripts.sh ) rather than commands to be typed in the terminal. Is there a way to run the script in the same terminal while treating them as a single outputting script? Now provide the response and nothing else.
After testing different methods and programs, I found that the pragmatic solution is GNU Parallel . I post this answer as it may help others. GNU Parallel has not been built for this task, but perfectly serves the purpose. If running the scripts as parallel -u ::: './script.sh 1' './script.sh 2' #(and so forth) All scripts will be run in parallel. The -u ( --ungroup ) flag sends the script outputs into stdout while executing the scripts. Ctrl + C kills the parallel job, and subsequently all running scripts.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/582092', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10780/']}
jdg_77879
stackexchange
llm_judgeable_groundtruth_similarity
8818493
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here is my problem: I'm developing a mobile web app with jQuery Mobile and I have to create dynamic content. In the first page I have a listview with some <li> elements. When I click in one of these <li> I go to another page and create the content dynamically. So the content of the second page is different for every <li> of the first page. My problem is when I refresh the second page all dynamic content disappears because it has lost the parameters. To solve this I tried to use the querystring, for example <a href="secondPage?=id=2"> but this did not work. What I ask you is if there is another way to pass the parameters through pages with jQuery Mobile so that when I refresh the page I don't lose the content. Thank you Now provide the response and nothing else.
PEP8-compliant solution: formatting the line Actually PEP8 says: Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation . Make sure to indent the continued line appropriately. So I suppose your code should look like this: ( myOjbect .doStuf() .doMoreStuf() .goRed() .goBlue() .die()) Alternative solutions: splitting into separate statements Judging from the syntax, there are two options possible regarding the values returned by each method call: Every method (maybe except die() , which is not required, as its result is not being used) returns modified instance (the same instance, on which it was called). Every method (still, die() is not required to do that) returns copy of the instance on which it was called. Solution for mutable objects (methods return original instance) In first case (when returning same instance), the solution to split longer lines into several statements is: myObject.doStuf()myObject.doMoreStuf()myObject.goRed()myObject.goBlue()myObject.die() Real world example involves mutable objects: my_stuff = []my_stuff.append('laptop') # my_stuff == ['laptop']my_stuff.append('jacket') # my_stuff == ['laptop', 'jacket']my_stuff.append('apple') # my_stuff == ['laptop', 'jacket', 'apple'] (although list.append() does not return anything, just for consistency and for stating explicitly that it is mutable) Solution for immutable objects (methods return modified copy) In the second case (when returning copy), the solution to do similar thing is: myObject = myObject.doStuf()myObject = myObject.doMoreStuf()myObject = myObject.goRed()myObject = myObject.goBlue()myObject.die() Real world example involves immutable objects: name = '-Tadek-'name = name.strip('-') # name == 'Tadek'name = name.lower() # name == 'tadek'name = name.replace('k', 'ck') # name == 'tadeck'
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8818493', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1143037/']}
jdg_77880
stackexchange
llm_judgeable_groundtruth_similarity
2258659
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 g be continuous, not negative, and strictly increasing in [a, b]. Prove that if $f$ is continuous and$$\int_{a}^{b}f(x)g^n(x)dx=0, \quad \forall n \in \mathbb{N},$$then $f\equiv 0$. With a change of variable I have arrived here but I could not continue: $$\int_{g(a)}^{g(b)}f(u)u^n \frac{du}{u'}=0, \quad \forall n \in \mathbb{N},$$ Two particular cases already resolved by the community are: $g(x)=x$ and $x \in [0,1]$: $\quad \int_{0}^{1}f(x)x^ndx=0, \quad \forall n \in \mathbb{N}, \; $then $f\equiv 0$. $g(x)=e^x$: $\quad \int_{a}^{b}f(x)e^{nx} dx=0, \quad \forall n \in \mathbb{N}, \; $then $f\equiv 0$. Now provide the response and nothing else.
Per the problem statement, $g$ is a homeomorphism $[a,b]\to [c,d]$. The continuous function $f\circ g^{-1}\colon [c,d]\to\Bbb R$ can be approximated uniformly by polynomials. So for $\epsilon>0$, we find $p\in\Bbb R[X]$ with $|f(g^{-1}(t))-p(t)| <\epsilon$ for all $t\in[c,d]$, or equivalently $|f(x)-p(g(x))|<\epsilon$ for all $x\in[a,b]$. Then$$\begin{align}\int_a^bf(x)^2\,\mathrm dx&=\int_a^b f(x)p(g(x))\,\mathrm dx+\int_a^bf(x)(f(x)-p(g(x))\,\mathrm dx \\&\le\rlap{\qquad0}\hphantom{\int_a^b f(x)p(g(x))\,\mathrm dx+}\llap{+\;\epsilon}\int_a^b|f(x)|\,\mathrm dx.\end{align}$$As $\epsilon$ was arbitrary $>0$, we conclude $\int_a^bf(x)^2\,\mathrm dx\le 0$ and therefore $f\equiv 0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2258659', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/393765/']}
jdg_77881
stackexchange
llm_judgeable_groundtruth_similarity
43703823
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a problem where I don't know how to find the average value of an array. Here are my questions: How do I add up all the numbers within my array? How do I find how many indexes are in my array? How do I take this information and gather the average value from my array? While all of these may seem simple and fairly elementary, I am unsure on how to do this. Any help? Now provide the response and nothing else.
For example purposes, I will define my array as intArray with the values of [10, 15, 5, 7, 13] creating our final array as: var intArray = [10, 15, 5, 7, 13] Now let's answer each of the questions in order: How do I add up all the numbers within my array? In order to add up all the numbers within your array, you'll need to utilize the reduce() function that is integrated within arrays. It will look something like this: intArray.reduce(0, +) This line will take your array, intArray in this case, and reduce it starting at index number 0 and adding all the following consecutive numbers. However , in our case, we need to assign this value to a variable in order to utilize it later in the averaging function. This is what that looks like: let sumArray = intArray.reduce(0, +) How do I find how many indexes are in my array? In our case, we need the total amount of indexes to figure out what to divide by in order to get our final average. That is done by utilizing the count() property of arrays. That will look like this: intArray.count So now that we have the total index count, we can figure out our answer to the next question. How do I take this information and gather the average value from my array? We can take the information from question 1 and question 2 and combine it together to get our average value of the array. It will look something like this: let avgArrayValue = sumArray / intArray.count Altogether the code will look like this: let sumArray = intArray.reduce(0, +)let avgArrayValue = sumArray / intArray.count
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43703823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4847841/']}
jdg_77882
stackexchange
llm_judgeable_groundtruth_similarity
48443167
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just curious: In Kotlin, I would love to get some val that can be initialized by lazy, but with a parameter. That's because I need something that's created very late in order to initialize it. Specifically, I wish I had: private lateinit val controlObj:SomeView or: private val controlObj:SomeView by lazy { view:View->view.findViewById(...)} and then: override fun onCreateView(....) { val view = inflate(....) controlObj = view.findViewById(...) or in the 2nd case controlObj.initWith(view) or something like that: return view I cannot use by lazy because by lazy won't accept external parameters to be used when initialising. In this example - the containing view . Of course I have lateinit var but it would be nice if I could make sure it becomes read only after setting and I could do it in one line. Is there a pretty clean way to create a read only variable that initializes only once but only when some other variables are born? Any init once keyword? That after init the compiler knows it's immutable? I am aware of the potential concurrency issues here but if I dare to access it before init, I surely deserve to be thrown . Now provide the response and nothing else.
You can implement own delegate like this: class InitOnceProperty<T> : ReadWriteProperty<Any, T> { private object EMPTY private var value: Any? = EMPTY override fun getValue(thisRef: Any, property: KProperty<*>): T { if (value == EMPTY) { throw IllegalStateException("Value isn't initialized") } else { return value as T } } override fun setValue(thisRef: Any, property: KProperty<*>, value: T) { if (this.value != EMPTY) { throw IllegalStateException("Value is initialized") } this.value = value }} After that you can use it as following: inline fun <reified T> initOnce(): ReadWriteProperty<Any, T> = InitOnceProperty()class Test { var property: String by initOnce() fun readValueFailure() { val data = property //Value isn't initialized, exception is thrown } fun writeValueTwice() { property = "Test1" property = "Test2" //Exception is thrown, value already initalized } fun readWriteCorrect() { property = "Test" val data1 = property val data2 = property //Exception isn't thrown, everything is correct }} In case when you try to access value before it is initialized you will get exception as well as when you try to reassign new value.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48443167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7919219/']}
jdg_77883
stackexchange
llm_judgeable_groundtruth_similarity
33748538
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've created a UIAlertController with the preferred style of UIAlertControllerStyleAlert . The alert shows when the leftBarButtonItem is tapped. I created a UIBarButtonItem property called backButton and set the leftBarButtonItem = self.backButton . This is working as designed. I'm not using storyboards. The problem is that the leftBarButtonItem moves down (my guess: about 20pts) when the alert shows. Why is this happening? I know how to show/hide the button so the user can't see that the button when it has moved down. However, that sucks. Why is it happening in the first place? I haven't found any similar issues online. @property (strong, nonatomic) IBOutlet UIBarButtonItem *backButton; in viewDidLoad: self.backButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonPressed)];[self.backButton setImage:[UIImage imageNamed:@"back-arrow-grey"]];self.navigationItem.leftBarButtonItem = self.backButton; in backButtonPressed: { self.navigationItem.leftBarButtonItem = nil; //to hide backButton because it moves down UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"My title" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *actionLeave = [UIAlertAction actionWithTitle:@"Leave" style:UIAlertActionStyleDefault handler:...//which works correctly UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"Go back" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { self.navigationItem.leftBarButtonItem = self.backButton; //to show backButton again now that the alert is dismissed //other things happen here that work as designed }]; [alertController addAction:actionLeave]; [alertController addAction:actionCancel]; [self presentViewController:alertController animated:YES completion:^{}];} Now provide the response and nothing else.
I also encountered this issue. Searching for other issues about vertical mis-positioning of the left bar button item took me to this question . The gist of it is that this problem occurs, for unknown reasons, if you have a bar button item that has an image, but an empty string as it's title. Set the title to a single space instead of just an empty string: self.backButton = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStylePlain target:self action:@selector(backButtonPressed)]; I don't know if it will fix it for you, but it mostly did for me - the button still does a slight 'jump' animation as though it's being newly created (but only the first time it appears) - but it stays at the same vertical position. Edit: Passing in nil as the title also removes the extraneous animation. Seems like this is just a peculiarity in how iOS handles whitespace strings as titles.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33748538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3634990/']}
jdg_77884
stackexchange
llm_judgeable_groundtruth_similarity
40771312
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 attempting to print a dictionary to CSV and receive this error when I run the code. Error: ValueError: dict contains fields not in fieldnames: 'u', 'r', 'l' from nytimesarticle import articleAPIimport csvapi = articleAPI('API Key')res = api.search( q = ['Abbott Laboratories'], fq = {'source':['The New York Times']}, begin_date = 20110101, end_date = 20131231, facet_field = ['source'], facet_filter = True)for m in res['response']['docs']: dic = {} dic['url'] = m['web_url'] dic['id'] = m['_id'] print dicwith open('Abbot_test.csv', 'wb') as output_file: dict_writer = csv.DictWriter(output_file, ('url', 'id')) dict_writer.writeheader() dict_writer.writerows(dic) When I run with dict_writer = csv.DictWriter(outputfile, ('url', 'id', 'u', 'r', 'l') Error: AttributeError: 'str' object has no attribute 'get' As a side note, when I run the block of code above with dict_writer.writerow(dic) In the last line, it prints a single url to the CSV with no error. Any thoughts? Now provide the response and nothing else.
Before setting PG count you need to know 3 things. 1. Number of OSD ceph osd lsSample Output: 0 1 2 Here Total number of osd is three. 2. Number of Pools ceph osd pool ls or rados lspools Sample Output: rbd images vms volumes backups Here Total number of pool is five. 3. Replication Count ceph osd dump | grep repliSample Output: pool 0 'rbd' replicated size 2 min_size 2 crush_ruleset 0 object_hash rjenkins pg_num 64 pgp_num 64 last_change 38 flags hashpspool stripe_width 0 pool 1 'images' replicated size 2 min_size 2 crush_ruleset 1 object_hash rjenkins pg_num 30 pgp_num 30 last_change 40 flags hashpspool stripe_width 0 pool 2 'vms' replicated size 2 min_size 2 crush_ruleset 1 object_hash rjenkins pg_num 30 pgp_num 30 last_change 42 flags hashpspool stripe_width 0 pool 3 'volumes' replicated size 2 min_size 2 crush_ruleset 1 object_hash rjenkins pg_num 30 pgp_num 30 last_change 36 flags hashpspool stripe_width 0 pool 4 'backups' replicated size 2 min_size 2 crush_ruleset 1 object_hash rjenkins pg_num 30 pgp_num 30 last_change 44 flags hashpspool stripe_width 0You can see each pool has replication count two. Now Let get into calculation Calculations: Total PGs Calculation: Total PGs = (Total_number_of_OSD * 100) / max_replication_countThis result must be rounded up to the nearest power of 2. Example: No of OSD: 3 No of Replication Count: 2 Total PGs = (3 * 100) / 2 = 150. Nearest Power of 150 to 2 is 256. So Maximum Recommended PGs is 256 You can set PG for every Pool Total PGs per pool Calculation: Total PGs = ((Total_number_of_OSD * 100) / max_replication_count) / pool countThis result must be rounded up to the nearest power of 2. Example: No of OSD: 3 No of Replication Count: 2 No of pools: 5 Total PGs = ((3 * 100) / 2 ) / 5 = 150 / 5 = 30 . Nearest Power of 30 to 2 is 32. So Total No of PGs per pool is 32. Power of 2 Table: 2^0 12^1 22^2 42^3 82^4 162^5 322^6 642^7 1282^8 2562^9 5122^10 1024 Useful Commands ceph osd pool create <pool-name> <pg-number> <pgp-number> - To create a new poolceph osd pool get <pool-name> pg_num - To get number of PG in a poolceph osd pool get <pool-name> pgp_num - To get number of PGP in a poolceph osd pool set <pool-name> pg_num <number> - To increase number of PG in a poolceph osd pool set <pool-name> pgp_num <number> - To increase number of PGP in a pool*usually pg and pgp number is same
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40771312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7133019/']}
jdg_77885
stackexchange
llm_judgeable_groundtruth_similarity
4283538
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 this type of toggle button please click the link below to see my requirement : http://www.redbus.in/Booking/SeatSelection.aspx?rt=4017230&doj=30-Nov-2010&dep=04:55%20PM&showSpInst=false Now provide the response and nothing else.
Zareth's answer helped the OP, but it didn't actually answer the question. Here's the correct solution, from this other post : public ActionResult Download(){ var data = Encoding.UTF8.GetBytes("some data"); var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray(); return File(result, "application/csv", "foo.csv");} The byte-order mark (while not technically required for UTF8) clues certain programs (e.g. Excel >2007) in to the fact that you're using UTF8. You have to manually include it via the GetPreamble() method.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4283538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/520818/']}
jdg_77886
stackexchange
llm_judgeable_groundtruth_similarity
3369588
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have a function which takes variadic arguments ( ... ) or a va_list passed from another such function. The main logic is in this function itself (let's call it f1 ), but I want to have it pass the va_list to another function (let's call it f2 ) which will determine the next argument type, obtain it using va_arg , and properly convert and store it for the caller to use. Is it sufficient to pass a va_list to f2 , or is it necessary to pass a pointer to va_list. Unless va_list is required to be an array type or else store its position data at the location the va_list object points to (rather than in the object itself), I can't see how passing it by value could allow the calling function ( f1 ) to 'see' the changes the called function made by va_arg . Can anyone shed light on this? I'm interested in what the standard requires, not what some particular implementation allows. Now provide the response and nothing else.
It looks like you'll need to pass a pointer to the va_list. For more info, see the C99 standard document section 7.15.In particular, bullet point 3 states: The object ap may be passed as an argument to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap [my italics] Edit: Just noticed a footnote in the standard: 215) It is permitted to create a pointer to a va_list and pass that pointer to another function, in which case the original function may make further use of the original list after the other function returns So you can pass a pointer to the va_list and do va_arg(*va_list_pointer) in the called function.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3369588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/379897/']}
jdg_77887
stackexchange
llm_judgeable_groundtruth_similarity
916552
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 was showing my kids some basic things about directory permissions on an EC2 ubuntu instance, and did this $ sudo chmod 700 /home Then demonstrated that I could no longer cd to my home directory because permission was denied. Then I inadvertantly disconnected from the EC2 instance. Now I cannot log back in because the sshd on the ubuntu side cannot access my /home/ubuntu/.ssh/authorized_keys file. I've tried to think about workarounds, but I'm out of ideas. I am prepared to delete and recreate the entire instance, but would much rather salvage this one if possible. Any ideas?! Now provide the response and nothing else.
Following Tim's suggestion: I clicked Launch Instance to create a new instance. I just took whatever the first AMI was listed (some Amazon version of Linux) and created it with defaults, using a keypair I had already on hand. I then clicked on Volumes and detached the EBS volume from my hosed machine. This took about 30 secs. Then I selected Attach Volume and I attached it to the new instance as /dev/sdf . Then I ssh ed into the new instance. In the new instance I typed $ sudo mkdir /caribou$ sudo mount /dev/sdf1 /caribou$ cd /caribou$ sudo chmod 755 home That repaired the /home dir permissions. I then went back to the EC2 console, detached the EBS volume from the Amazon instance and re-attached it to my original Ubuntu instance as /dev/sda1 . Then I started the old instance and logged in, with everything fixed. Took 30 mins including time to figure out all of the above. Thanks to Tim.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/916552', 'https://serverfault.com', 'https://serverfault.com/users/70903/']}
jdg_77888
stackexchange
llm_judgeable_groundtruth_similarity
63463
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have a web page that currently accepts a single ID value via a url parameter: http://example.com/mypage.aspx?ID=1234 I want to change it to accept a list of ids, like this: http://example.com/mypage.aspx?IDs=1234,4321,6789 So it's available to my code as a string via context.Request.QueryString["IDs"]. What's the best way to turn that string value into a List<int>? Edit: I know how to do .split() on a comma to get a list of strings, but I ask because I don't know how to easily convert that string list to an int list. This is still in .Net 2.0, so no lambdas. Now provide the response and nothing else.
No offense to those who provided clear answers, but many people seem to be answering your question instead of addressing your problem. You want multiple IDs, so you think you could this this: http://example.com/mypage.aspx?IDs=1234,4321,6789 The problem is that this is a non-robust solution. In the future, if you want multiple values, what do you do if they have commas? A better solution (and this is perfectly valid in a query string), is to use multiple parameters with the same name: http://example.com/mypage.aspx?ID=1234;ID=4321;ID=6789 Then, whatever query string parser you use should be able to return a list of IDs. If it can't handle this (and also handle semi-colons instead of ampersands), then it's broken.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3043/']}
jdg_77889
stackexchange
llm_judgeable_groundtruth_similarity
206863
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 would like to know if I am expected to memorize coding in a workspace or am I allow to fall into references whenever I am unsure. In a week of non-stop self learning, I feel I can understand the basics html and CSS, but am I required to memorize every single code once I get a position in this field or is it fair to use references to provide you the edge to finish your development. I was always under the impression you had to hand-code everything but I am wondering if I'll be looked as less of a developer if I fall to references. Understanding that if I do memorize most things, it will save me the time it will take me to code something but I don't want to feel penalized if I need to refer back to a code because I need refresh myself. This Programmers question held a lot of good answers, but they don't quite fit for me. My role is as a graphic designer/illustrator not a developer, and I am still relative new with how the process works. I'll definitely like a strong input to make sure I go along the right path in my learnings Because HTML and CSS are just a starting point, I want to excel in other areas as well. Thanks for taking the time to read my post.P.S (if you have any other additional references or advice, I'll gladly appreciate it) Now provide the response and nothing else.
Programmers are not human encyclopedias. We remember what we use often, and we keep actual encyclopedias nearby for what we don't. I consider myself a "veteran" C# coder, and there are things I Google every day to do my job. That's probably one of the hallmarks of a veteran; that he knows what he doesn't know, and where to find it . The only reason you'd memorize as much technical detail you could is for the same reason any grade-schooler would; to pass an upcoming test. MS certification tests are full of this kind of crap, requiring you to memorize the order of parameters of obscure built-in method calls you typically code once, in a general-purpose library, before moving on to more interesting things. This is one of the reasons I don't like certification tests and don't think the resulting titles are worth much; all they prove is that you have managed to ingrain into your brain the same knowledge the IDE itself could tell you in two seconds. What you usually need to know, given a basic intuitive grasp of how to program, are the basic rules around whatever language you're studying; structure, syntax, formatting and naming conventions, and a few best practices. That allows you to read code in that language, and to maintain it. From there, the reference books or online resources will tell you what the code doesn't, and that's what else you could do.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/206863', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/98453/']}
jdg_77890
stackexchange
llm_judgeable_groundtruth_similarity
2077
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $SX$ be the suspension of CW complex. What are some results available to determine the homotopy groups of $SX$? Now provide the response and nothing else.
This, in general, an incredibly difficult problem. Even we just want to compute the rational homotopy groups of the suspension of $X$ and $X$ is simply connected, where we can do everything using rational homotopy theory to reduce things to commutative DGAs, this starts to involve things like free Lie algebras and the like. Locally at the prime 2, there is actually a famous long exact sequence when $X$ is a sphere called the EHP long exact sequence. It relates the suspension homomorphism, the Hopf map, and a "whitehead product" map. This gives rise to the EHP spectral sequence that, funnily enough, starts with the 2-local homotopy groups of odd -dimensional spheres and computes the 2-local homotopy groups of spheres. Miller and Ravenel have a paper titled "Mark Mahowald's work on the homotopy groups of spheres" that covers some of this material in detail. Another approach is to say: The "stable" homotopy groups of $X$ are a first-order approximation using the Freudenthal suspension theorem that Andrea mentioned. There is then a "quadratic" correction term that you can try to use to get an approximation of the homotopy groups that is correct out to roughly three times the connectivity, and so on. These lead into the subject of Goodwillie calculus. For a classifying space $K(G,1)$, neither of these approaches work very well, because the higher homotopy groups are going to depend pretty intricately on your group itself. For instance, $\pi_3$ of the suspension of the classifying space of a free group is the set of symmetric elements in $G_{\text{ab}}\otimes G_{\text{ab}}$ where $G_{\text{ab}}$ is the abelianization of $G$, and for a general group it lives in an exact sequence between something involving such symmetric elements and the second group homology of $G$. I don't know a closed form for it but maybe someone else knows better. EDIT : Let me at least be precise, there's an exact sequence$$\pi _4 (\Sigma BG)\rightarrow H_3 G \rightarrow (G_{\text{ab}}\otimes G_{\text{ab}})^{\mathbb Z/2} \rightarrow \pi_3 (\Sigma BG)\rightarrow H_2 G\rightarrow 0$$Note that for $R$ a ring, an element of $(G_{\text{ab}}\otimes G_{\text{ab}})^{\mathbb Z/2}$ gives rise to an $R$-valued symmetric bilinear pairing on $\mathsf{Hom}(G_{\text{ab}},R)$. EDIT FOR THE FINAL TIME : sorry for the multiple revisions, switching back and forth between homology and cohomology gave me errors. the exact sequence above should be correct now.
{}
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/2077', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1034/']}
jdg_77891
stackexchange
llm_judgeable_groundtruth_similarity
13159932
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 tablix with two columns of data (the section name and the section text). The section text has grown so large for some sections that the row representing the section takes up 2/3 or more of the page. THe report prints fine until on of these large rows would have to split over the end of a page and continue on the next page. In this case, and only in this case, the rows leaves large amounts of white space on current page and start on the next page (as if it had a page break before it) I have already set the Tablix General Property "keep together on one page if possible" to true and all the other page break options for the tablix and row groups to false, to no avail. Does anyone know of a trick or work around to make the large rows split over pages?? Now provide the response and nothing else.
Setting Keep together on one page if possible to true/checked will cause SSRS to attempt to keep the row on one page, which means if the data spans across page breaks it will move that row to start on a new page so that it can be seen on one page, which would introduce white space where the row would be if the table was contiguous. So you need this setting set to False/Unchecked . Next, ensure that the row group proeprty Keep together is set to False . This can't be accessed through the normal dialog box. If you don't have the properties pane showing in BIDS, then pressing F4 will bring this pane up. Select the row group(s), and ensure the property is appropriately set.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13159932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311127/']}
jdg_77892
stackexchange
llm_judgeable_groundtruth_similarity
23681340
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 wanting to create either a custom ContentControl in WPF that can contain one element. This is easy enough, I've done it plenty of times. But here I want the content control to have rulers on the bottom and left edges. I want these controls to be accessible from the code behind. I'm at a loss with how to move forward. I've considered a template but then the ruler controls would not be readily accessible. I also thought about creating a UserControl with a content like dependency property, but then the XAML would not be as simple for the user of this control as just using a content control. Thanks. Now provide the response and nothing else.
One can also implement diag(A*B) as sum(A.*B',2) . Let's benchmark this along with all other implementations/solutions as suggested for this question. The different methods implemented as functions are listed below for benchmarking purposes: Sum-multiplication method-1 function out = sum_mult_method1(A,B)out = sum(A.*B',2); Sum-multiplication method-2 function out = sum_mult_method2(A,B)out = sum(A.'.*B).'; For-loop method function out = for_loop_method(A,B)M = size(A,1);out = zeros(M,1);for i=1:M out(i) = A(i,:) * B(:,i);end Full/Direct-multiplication method function out = direct_mult_method(A,B)out = diag(A*B); Bsxfun-method function out = bsxfun_method(A,B)out = sum(bsxfun(@times,A,B.'),2); Benchmarking Code num_runs = 1000;M_arr = [100 200 500 1000];N = 4;%// Warm up tic/toc.tic();elapsed = toc();tic();elapsed = toc();for k2 = 1:numel(M_arr) M = M_arr(k2); fprintf('\n') disp(strcat('*** Benchmarking sizes are M =',num2str(M),' and N = ',num2str(N))); A = randi(9,M,N); B = randi(9,N,M); disp('1. Sum-multiplication method-1'); tic for k = 1:num_runs out1 = sum_mult_method1(A,B); end toc clear out1 disp('2. Sum-multiplication method-2'); tic for k = 1:num_runs out2 = sum_mult_method2(A,B); end toc clear out2 disp('3. For-loop method'); tic for k = 1:num_runs out3 = for_loop_method(A,B); end toc clear out3 disp('4. Direct-multiplication method'); tic for k = 1:num_runs out4 = direct_mult_method(A,B); end toc clear out4 disp('5. Bsxfun method'); tic for k = 1:num_runs out5 = bsxfun_method(A,B); end toc clear out5end Results *** Benchmarking sizes are M =100 and N =41. Sum-multiplication method-1Elapsed time is 0.015242 seconds.2. Sum-multiplication method-2Elapsed time is 0.015180 seconds.3. For-loop methodElapsed time is 0.192021 seconds.4. Direct-multiplication methodElapsed time is 0.065543 seconds.5. Bsxfun methodElapsed time is 0.054149 seconds.*** Benchmarking sizes are M =200 and N =41. Sum-multiplication method-1Elapsed time is 0.009138 seconds.2. Sum-multiplication method-2Elapsed time is 0.009428 seconds.3. For-loop methodElapsed time is 0.435735 seconds.4. Direct-multiplication methodElapsed time is 0.148908 seconds.5. Bsxfun methodElapsed time is 0.030946 seconds.*** Benchmarking sizes are M =500 and N =41. Sum-multiplication method-1Elapsed time is 0.033287 seconds.2. Sum-multiplication method-2Elapsed time is 0.026405 seconds.3. For-loop methodElapsed time is 0.965260 seconds.4. Direct-multiplication methodElapsed time is 2.832855 seconds.5. Bsxfun methodElapsed time is 0.034923 seconds.*** Benchmarking sizes are M =1000 and N =41. Sum-multiplication method-1Elapsed time is 0.026068 seconds.2. Sum-multiplication method-2Elapsed time is 0.032850 seconds.3. For-loop methodElapsed time is 1.775382 seconds.4. Direct-multiplication methodElapsed time is 13.764870 seconds.5. Bsxfun methodElapsed time is 0.044931 seconds. Intermediate Conclusions Looks like sum-multiplication methods are the best approaches, though bsxfun approach seems be to catching up with them as M increases from 100 to 1000. Next, higher benchmarking sizes were tested with just the sum-multiplication and bsxfun methods. The sizes were - M_arr = [1000 2000 5000 10000 20000 50000]; The results are - *** Benchmarking sizes are M =1000 and N =41. Sum-multiplication method-1Elapsed time is 0.030390 seconds.2. Sum-multiplication method-2Elapsed time is 0.032334 seconds.5. Bsxfun methodElapsed time is 0.047377 seconds.*** Benchmarking sizes are M =2000 and N =41. Sum-multiplication method-1Elapsed time is 0.040111 seconds.2. Sum-multiplication method-2Elapsed time is 0.045132 seconds.5. Bsxfun methodElapsed time is 0.060762 seconds.*** Benchmarking sizes are M =5000 and N =41. Sum-multiplication method-1Elapsed time is 0.099986 seconds.2. Sum-multiplication method-2Elapsed time is 0.103213 seconds.5. Bsxfun methodElapsed time is 0.117650 seconds.*** Benchmarking sizes are M =10000 and N =41. Sum-multiplication method-1Elapsed time is 0.375604 seconds.2. Sum-multiplication method-2Elapsed time is 0.273726 seconds.5. Bsxfun methodElapsed time is 0.226791 seconds.*** Benchmarking sizes are M =20000 and N =41. Sum-multiplication method-1Elapsed time is 1.906839 seconds.2. Sum-multiplication method-2Elapsed time is 1.849166 seconds.5. Bsxfun methodElapsed time is 1.344905 seconds.*** Benchmarking sizes are M =50000 and N =41. Sum-multiplication method-1Elapsed time is 5.159177 seconds.2. Sum-multiplication method-2Elapsed time is 5.081211 seconds.5. Bsxfun methodElapsed time is 3.866018 seconds. Alternate benchmarking Code (with `timeit) num_runs = 1000;M_arr = [1000 2000 5000 10000 20000 50000 100000 200000 500000 1000000];N = 4;timeall = zeros(5,numel(M_arr));for k2 = 1:numel(M_arr) M = M_arr(k2); A = rand(M,N); B = rand(N,M); f = @() sum_mult_method1(A,B); timeall(1,k2) = timeit(f); clear f f = @() sum_mult_method2(A,B); timeall(2,k2) = timeit(f); clear f f = @() bsxfun_method(A,B); timeall(5,k2) = timeit(f); clear fendfigure,hold onplot(M_arr,timeall(1,:),'-ro')plot(M_arr,timeall(2,:),'-ko')plot(M_arr,timeall(5,:),'-.b')legend('sum-method1','sum-method2','bsxfun-method')xlabel('M ->')ylabel('Time(sec) ->') Plot Final Conclusions It seems sum-multiplication method is great till certain stage, which is around M=5000 mark and after that bsxfun seems to have a slight upper-hand. Future Work One can look into varying N and study the performances for the implementations mentioned here.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23681340', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/443602/']}
jdg_77893
stackexchange
llm_judgeable_groundtruth_similarity
2248759
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can you please tell me if there is a way to layout textaround an image?Like this: ------ text text text| | text text text----- text text texttext text text texttext text text text I have gotten a response from an android developer about this question. But I am not sure what he means by doing my own version of TextView? Thank for any tips. On Mon, Feb 8, 2010 at 11:05 PM, Romain Guy wrote: Hi, This is not possible using only the supplied widgets and layouts. You could write your own version of TextView to do this, it shouldn't be hard. Now provide the response and nothing else.
Now it is possible, but only for phones with version higher or equal 2.2 by using the android.text.style.LeadingMarginSpan.LeadingMarginSpan2 interface which is available in API 8. Here is the article , not in English though, but you can download the source code of the example directly from here . If you want to make your application compatible with older devices, you can display a different layout without a floating text.Here is an example: Layout (default for older versions, will be changed programmatically for newer versions) <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/thumbnail_view" android:src="@drawable/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/message_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/thumbnail_view" android:textSize="18sp" android:text="@string/text" /></RelativeLayout> The helper class class FlowTextHelper { private static boolean mNewClassAvailable; static { if (Integer.parseInt(Build.VERSION.SDK) >= 8) { // Froyo 2.2, API level 8 mNewClassAvailable = true; } } public static void tryFlowText(String text, View thumbnailView, TextView messageView, Display display){ // There is nothing I can do for older versions, so just return if(!mNewClassAvailable) return; // Get height and width of the image and height of the text line thumbnailView.measure(display.getWidth(), display.getHeight()); int height = thumbnailView.getMeasuredHeight(); int width = thumbnailView.getMeasuredWidth(); float textLineHeight = messageView.getPaint().getTextSize(); // Set the span according to the number of lines and width of the image int lines = (int)FloatMath.ceil(height / textLineHeight); //For an html text you can use this line: SpannableStringBuilder ss = (SpannableStringBuilder)Html.fromHtml(text); SpannableString ss = new SpannableString(text); ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); messageView.setText(ss); // Align the text with the image by removing the rule that the text is to the right of the image RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)messageView.getLayoutParams(); int[]rules = params.getRules(); rules[RelativeLayout.RIGHT_OF] = 0; }} The MyLeadingMarginSpan2 class (updated to support API 21) public class MyLeadingMarginSpan2 implements LeadingMarginSpan2 { private int margin; private int lines; private boolean wasDrawCalled = false; private int drawLineCount = 0; public MyLeadingMarginSpan2(int lines, int margin) { this.margin = margin; this.lines = lines; } @Override public int getLeadingMargin(boolean first) { boolean isFirstMargin = first; // a different algorithm for api 21+ if (Build.VERSION.SDK_INT >= 21) { this.drawLineCount = this.wasDrawCalled ? this.drawLineCount + 1 : 0; this.wasDrawCalled = false; isFirstMargin = this.drawLineCount <= this.lines; } return isFirstMargin ? this.margin : 0; } @Override public void drawLeadingMargin(Canvas c, Paint p, int x, int dir, int top, int baseline, int bottom, CharSequence text, int start, int end, boolean first, Layout layout) { this.wasDrawCalled = true; } @Override public int getLeadingMarginLineCount() { return this.lines; }} Example of the usage ImageView thumbnailView = (ImageView) findViewById(R.id.thumbnail_view);TextView messageView = (TextView) findViewById(R.id.message_view);String text = getString(R.string.text);Display display = getWindowManager().getDefaultDisplay();FlowTextHelper.tryFlowText(text, thumbnailView, messageView, display); This is how the application looks on the Android 2.2 device: And this is for the Android 2.1 device:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2248759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/114970/']}
jdg_77894
stackexchange
llm_judgeable_groundtruth_similarity
93771
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: What are the proper compact connected subgroups of $Spin(n)$ of maximal rank where $Spin(n)$ is the spin group, that is, the universal cover of the special orthogonal group $SO(n)$? In fact, I am only interested in the highest dimension of a compact connected subgroup of $Spin(n)$ of maximal rank. I am not sure if this is an easier question. Now provide the response and nothing else.
I think that the answer here is just the double cover of the obvious answer for $SO(n)$, which is $U(n/2)$ when $n$ is even and $SO(n{-}1)$ when $n$ is odd. You can double-check this by consulting the Dynkin tables of maximal subgroups. Added after Mikhail's comment: Mikhail actually went to the tables and checked (which I had not) and observed that, when $n$ is even, the maximal subgroup $SO(n{-}2)\times SO(2)$ of maximal rank has larger dimension than $U(n/2)$ when $n>8$. (They have equal dimension when $n=8$ and the former has smaller dimension when $n<8$.) Thus, the above answer needs to be divided into parts when $n$ is even. By the way, the double covers of the subgroups $SO(6)\times SO(2)$ and $U(4)$ in $Spin(8)$ are actually conjugate by an outer automorphism of $Spin(8)$, so they are essentially the same. This is a consequence of triality as discovered by Cartan.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/93771', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12486/']}
jdg_77895
stackexchange
llm_judgeable_groundtruth_similarity
1627050
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 $f:[a,b]\rightarrow R$ be differentiable at $c\in [a,b]$. Show that for every $\epsilon >0$, there is a $\delta(\epsilon) >0$ s.t if $0<|x-y|<\delta(\epsilon)$ and $a\leq x \leq c\leq y \leq b$, then\$$ |{\frac{f(x)-f(y)}{x-y}-f'(c)}|<\epsilon$$I can only think of using triangle inequality, but it seems does not work. Can anyone help me? Now provide the response and nothing else.
Hint: If $x=c<y$ or $x<c=y$ this is immediately immediate from the definition. So assume $x<c<y$. Then $$\frac{f(y)-f(x)}{y-x}-f'(c)=\frac{y-c}{y-x}\left(\frac{f(y)-f(c)}{y-c}-f'(c)\right)+\frac{c-x}{y-x}\left(\frac{f(c)-f(x)}{c-x}-f'(c)\right).$$ Now you can use the triangle inequality there; when you use the triangle inequality it's going to be very important that the two numbers $(y-c)/(y-x)$ and $(c-x)/(y-x)$ are both positive and add up to $1$. Added: Of course user254665's answer is cleaner, applying directly to the case $x\le c\le y$. It seems possible that my version will seem simpler to some readers (and that his will seem simpler to others). A compromise, a version of my version that doesn't require handling the cases $x=c$ and $y=c$ separately: Define $$S(x)=\begin{cases}\frac{f(x)-f(c)}{x-c}-f'(c),&(x\ne c),\\0,&(x=c).\end{cases}$$ Then for $x\le c\le y$ we have $$\frac{f(y)-f(x)}{y-x}-f'(c)=\frac{y-c}{y-x}S(y)+\frac{c-x}{y-x}S(x).$$ [...]
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1627050', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/307126/']}
jdg_77896
stackexchange
llm_judgeable_groundtruth_similarity
31928887
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I’m new to C and here I'm trying to read integers (separated by whitespaces) from a file and store them in an array called array . Initially, I set array to NULL and then pass it to the read_file function. Everything works fine within read_file . However, when read_file is popped off the stack, array still points to NULL and not to the data loaded by read_file . What am I doing wrong? #include <stdio.h>#include <stdlib.h>#include <iostream>int read_file(FILE *file, int *input_array);FILE *file;int main(){ char *pathname = " numbers.txt"; if(fopen_s(&file, pathname, "r")) puts("File could not be opened."); int *array = NULL; int array_size = read_file(file, array); int i; for(i = 0; i < array_size; i++){ printf("%d\n", array[i]); } fclose(file); std::cin.ignore(); return 0;}int read_file(FILE *file, int *input_array){ int array_size = 10; input_array = (int *) malloc(array_size * sizeof(int)); int i; for(i = 0; !feof(file) && i < array_size; i++){ fscanf_s(file, "%d", &input_array[i]); //printf("%d\n", input_array[i]); } return i;} Now provide the response and nothing else.
I know I am posting very late, but detailed example may be helpful for someone. What I have noticed is, if we check the shouldShowRequestPermissionRationale() flag in to onRequestPermissionsResult() callback method, it shows only two states. State 1:-Return true:-- Any time user clicks Deny permissions (including the very first time. State 2:-Returns false :- if user select s “never asks again. Here is an example with multiple permission request:- The app needs 2 permissions at startup . SEND_SMS and ACCESS_FINE_LOCATION (both are mentioned in manifest.xml). As soon as the app starts up, it asks for multiple permissions together. If both permissions are granted the normal flow goes. public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(checkAndRequestPermissions()) { // carry on the normal flow, as the case of permissions granted. }}private boolean checkAndRequestPermissions() { int permissionSendMessage = ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS); int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION); List<String> listPermissionsNeeded = new ArrayList<>(); if (locationPermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION); } if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.SEND_SMS); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS); return false; } return true;} In case one or more permissions are not granted, activityCompat.requestPermissions() will request permissions and the control goes to onRequestPermissionsResult() callback method. You should check the value of shouldShowRequestPermissionRationale() flag in onRequestPermissionsResult() callback method. There are only two cases:-- Case 1: -Any time user clicks Deny permissions (including the very first time), it will return true. So when the user denies, we can show more explanation and keep asking again. Case 2: -Only if user select “never asks again” it will return false. In this case, we can continue with limited functionality and guide user to activate the permissions from settings for more functionalities, or we can finish the setup, if the permissions are trivial for the app. CASE- 1 CASE- 2 @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { Log.d(TAG, "Permission callback called-------"); switch (requestCode) { case REQUEST_ID_MULTIPLE_PERMISSIONS: { Map<String, Integer> perms = new HashMap<>(); // Initialize the map with both permissions perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED); perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED); // Fill with actual results from user if (grantResults.length > 0) { for (int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); // Check for both permissions if (perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Log.d(TAG, "sms & location services permission granted"); // process the normal flow //else any one or both the permissions are not granted } else { Log.d(TAG, "Some permissions are not granted ask again "); //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission// // shouldShowRequestPermissionRationale will return true //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup. if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { showDialogOK("SMS and Location Services Permission required for this app", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: checkAndRequestPermissions(); break; case DialogInterface.BUTTON_NEGATIVE: // proceed with logic by disabling the related features or quit the app. break; } } }); } //permission is denied (and never ask again is checked) //shouldShowRequestPermissionRationale will return false else { Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG) .show(); // //proceed with logic by disabling the related features or quit the app. } } } } } } private void showDialogOK(String message, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", okListener) .create() .show(); }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31928887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2505757/']}
jdg_77897
stackexchange
llm_judgeable_groundtruth_similarity
10347882
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 keep getting this warning and errors can anyone help? ld: warning: ignoring file /Applications/Xcode.app/Contents/Developer/Platforms /iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/System/Library/Frameworks//SystemConfiguration.framework/SystemConfiguration, missing required architecture armv7 in file Undefined symbols for architecture armv7: "_SCNetworkReachabilityCreateWithAddress", referenced from: +[Reachability reachabilityWithAddress:] in Reachability.o "_SCNetworkReachabilityCreateWithName", referenced from: +[Reachability reachabilityWithHostName:] in Reachability.o "_SCNetworkReachabilityUnscheduleFromRunLoop", referenced from: -[Reachability stopNotifier] in Reachability.o "_SCNetworkReachabilityScheduleWithRunLoop", referenced from: -[Reachability startNotifier] in Reachability.o "_SCNetworkReachabilitySetCallback", referenced from: -[Reachability startNotifier] in Reachability.o "_SCNetworkReachabilityGetFlags", referenced from: -[Reachability connectionRequired] in Reachability.o -[Reachability currentReachabilityStatus] in Reachability.o ld: symbol(s) not found for architecture armv7 clang: error: linker command failed with exit code 1 (use -v to see invocation) My app workings fine in the Simulator I don't get this it is just when I build to the phone. Now provide the response and nothing else.
You need to link against the SystemConfiguration framework. Select your project in Xcode's project navigator, select your app target, and select the Build Phases tab. Under Link Binary With Libraries, click on the "+" button and choose SystemConfiguration.framework. There may be other framework dependencies that you need to add in the same way, but adding SystemConfiguration is what fixed the same errors for me. ETA: I jumped right to the errors and didn't see the ld warning at the top of the paste. If you're already linking to SystemConfiguration, maybe try removing and re-adding it, and if all else fails, update Xcode. The most recent release definitely has the right architecture, so it sounds to me like either your project is looking in the wrong place or something's wrong with the framework itself.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10347882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/980097/']}
jdg_77898
stackexchange
llm_judgeable_groundtruth_similarity
64489
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 have n IID random variables $X_1, X_2, \ldots, X_n$. Let $R_i$ be $X_i$'s rank in the set $\{X_1, X_2, \ldots, X_3 \}$ when we order from large to small. How to prove $R_i, \forall i \in \{1, 2, \ldots, n\}$, is uniformly distributed on $\{1, 2, \ldots, n\}$? My first guess is that, for any position $j$ in ordered sequence of $X$s, as $X_1, X_2, \ldots, X_n$ are equally likely to be the $j$th largest, $$\Pr \{ R_i = j \} = \frac 1 n.$$ So $R_i$ is uniformly distributed on $\{1, 2, \ldots, n\}$. Another way to think about it, is to count how many possible cases are there when $R_i = j$. As $X_i$'s position in ordered sequence is fixed at $j$, then we can just permute the rest of $X$s to get all possible ordered sequence. Since there are $n-1$ variables left, there are $(n-1)!$ situations. As for any $R_i = j, 1 \le j \le n$, there are always $(n-1)!$ possible ordered sequences, we can say $R_i$ is uniformly distributed on $\{1, 2, \ldots, n\}$. Are these 2 proof rigorous? Edit: As cardinal pointed out, an additional condition is needed for the proof, and a sufficient such condition is that $X_i$ to be a continuous random variable. Now provide the response and nothing else.
The first thing you should consider is that there are, in some sense, different "hierarchies" of numbers. At each stage, we enlarge the class of numbers, and try to do so in a way that leaves everything we could do before still the same, but that now we can do more. A common way of doing this is to start with the natural numbers (sometimes called "counting numbers" or positive integers). We start with $1$, $2$, $3,\ldots$. Here, we do define multiplication as repeated addition. For example, one way to define multiplication is to assume we know how to add, and then define it by saying:$$\begin{align*}n\times 1 &= n\\n\times (k+1) &= (n\times k) + n % need to edit at least 6 characters\end{align*}$$Using mathematical induction , we can show this defines multiplication for all positive integers, and that it has the usual properties we know (commutative, so that $n\times k = k\times n$ for all positive integer $n$ and $k$, distributes over the sum, is associative, etc). Then we have two choices for "expanding our universe of numbers": we can now define negative integers, by considering things that would help us solve all equations of the form $a+x=b$ with $a$ and $b$ positive integers; or we can introduce positive rationals (fractions) by considering all things that would help us solve all equations of the form $ax = b$. Let's do the latter, since that came first historically. So, we had the positive integers, and we knew how to add and multiply them. Now we are going to have more numbers: now, for every pair of positive integers $a$ and $b$, we will have a number "$\frac{a}{b}$", which is a number that satisfies the property that$$b\times\left(\frac{a}{b}\right) = a.$$We also say that $\frac{a}{b}$ is "the same fraction" as $\frac{c}{d}$ if and only if $ad=bc$ (here we are comparing products of positive integers, so that's fine). We also notice that our old positive integers can also be considered fractions: the positive integer $a$ is a solution to $1x = a$, so $a$ corresponds to the fraction $\frac{a}{1}$. Now, how do we add two of these numbers? Since $\frac{a}{b}$ represents the solution to $bx=a$, and $\frac{r}{s}$ represents the solution to $sx=r$, then $\frac{a}{b}+\frac{r}{s}$ represents the solution to something ; to what? A bit of algebra will tell you that it is the solution to precisely $(bs)x = (as+br)$. So we define $$\frac{a}{b}+\frac{r}{s} = \frac{as+br}{bs}.$$There's a bit of work that needs to be done to ensure that if you write the fractions differently, the answer comes out the same (if $\frac{c}{d}=\frac{a}{b}$, and if $\frac{t}{u}=\frac{r}{s}$, does $\frac{cu+td}{du} = \frac{as+br}{bs}$? Yes). And we also notice that if we add positive integers as if they were fractions , we get the same answer we did before:$$\frac{a}{1} + \frac{c}{1} = \frac{a1+c1}{1} = \frac{a+c}{1}.$$That's good; it means we are enlarging our universe, not changing it. How about products? If $\frac{a}{b}$ represents the solution to $bx=a$, and $\frac{r}{s}$ represents the solution to $sy=r$, their product will be the solution to $(bs)z = ar$. So we define $$\frac{a}{b}\times\frac{r}{s} = \frac{ar}{bs}.$$And then we notice that it extends the definition of multiplication for integers, since $\frac{a}{1}\times\frac{b}{1} = \frac{a\times b}{1}$. And we check to see that multiplication and addition still have the properties we want (commutativity, associativity, etc). (There are other ways to figure out what multiplication of fractions "should be", on the basis of what we want it to do. For example, we want multiplication to extend multiplication of integers, so $\frac{a}{1}\times\frac{b}{1}$ should be $\frac{ab}{1}$; and we want it to distribute over the sum, so we want$$\frac{a}{1} = \frac{a}{1}\times \frac{1}{1} = \frac{a}{1}\times\left(\underbrace{\frac{1}{b}+\frac{1}{b}+\cdots+\frac{1}{b}}_{b\text{ summands}}\right) = \underbrace{\left(\frac{a}{1}\times\frac{1}{b}\right) + \cdots + \left(\frac{a}{1}\times\frac{1}{b}\right)}_{b\text{ summands}}.$$So $\frac{a}{1}\times \frac{1}{b}$ should be a fraction which, when added to itself $b$ times, equals $a$; that is, a solution to $bx=a$; that is, $\frac{a}{b}$. And so on). Then we move on from the positive rationals (fractions) to the positive reals. This is more complicated, as it involves "filling in gaps" between rationals. It is very technical. But what it turns out is that for every real number you can find a sequence of rationals $q_1,q_2,q_3,\ldots$ that get progressively closer to each other and to $r$ (we say the sequence "converges to $r$"); it won't hurt too much if you think of the $q_i$ as being progressive decimal approximations to $r$ (they don't have to be, and ahead of time you don't have any notion of decimal approximation, but you can think of it that way for our purpose). So then the way we define multiplication of real numbers $r$ and $s$ is to find a sequence of rationals $q_1,q_2,q_3,\ldots$ giving the approximation to $r$, and one $p_1,p_2,p_3,\ldots$ giving the approximation to $s$, and we define $r\times s$ to be whatever it is that the sequence$$p_1\times q_1,\ p_2\times q_2,\ p_3\times q_3,\ \ldots$$approximates. This ensures that if you take rational numbers and multiply them as if they were reals you get the same thing as if you multiply them as rationals, and likewise for integers. So multiplication of positive reals is really a series of approximations made up by multiplying rationals; and multiplication of rationals is really a way to codify solutions to certain equations with integers; and it is only multiplication of (positive) integers that really corresponds to "repeated addition". Finally, once you have the positive reals, you can introduce the negative real numbers. We consider solutions to equations of the form $a+x=b$ with $a$ and $b$ positive real numbers. Some of these already have solutions, some don't. This gives us "zero" and "negative reals". We then extend the definition of multiplication to "zero" and to "the negative reals" in a way that makes sense relative to this definition. Turns out we need to make $0\times r = 0$ for all $r$, and have to respect the "rules of signs" to make sure everything still works. So we define it that way to make sure everything works and what we had before still works exactly the same.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/64489', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1618/']}
jdg_77899
stackexchange
llm_judgeable_groundtruth_similarity
15035442
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to create all my tables from schema.rb I used the command: "rake db:schema:load" However, this fails because in one of my initializers, it is referencing a model/table that obviously doesn't exist (since the database is empty) I could comment out these lines, and then run schema:load again, but is there an alternative? Now provide the response and nothing else.
Probably the fastest way is to just move the offending initializer to a temporary directory that is outside of the app, and then run your schema load. But if that doesn't work, or isn't an option for some reason, you could always work around that by creating a bare bones rails app to do the schema load: Create a new rails app: rails new (app)-fixer Copy your gemfile (unless there are specific exceptions) to the fixer app. Copy your database.yml config to the fixer app. Copy your schema.rb file to the fixer app. Do all appropriate "bundle install" commands as needed for your app. Then run "rake db:drop db:create db:schema:load" That will build up a new database from scratch, based on your current schema.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15035442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/661624/']}
jdg_77900
stackexchange
llm_judgeable_groundtruth_similarity
28698
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: I am just getting started with using the GPIO on the Raspberry Pi for various projects. There are many breakout boards for the RPi and many of those have pins in order to stack boards on top of each other. It seems like the GPIO pins just go straight through and all the boards have the same pins in common. To me this means that all the boards in a stack receive the exact same signals from the RPi and should behave accordingly. This seems like this can produce a lot of errors with commands meant for one board affecting the way another board operates, but apparently this does not happen. So how does the Raspberry Pi know which board is getting which particular commands? Is there some sort of initialization command that only a particular board recognizes and then starts accepting the rest of the commands? Now provide the response and nothing else.
Computers use a system called busing to connect multiple peripheral devices to the CPU via the same set of wires. I2C and SPI are examples of busing systems used with the pi GPIO pins, which enable multiple devices on the same physical pins (managed by the internal bus) but using different addresses . Addressing is an abstraction created by the bus system protocol. It is a little bit like how you can have multiple networked applications using the same physical connection to the internet, all running simultaneously. For example, looking at the RTC Pi Plus , one of the stackable boards from your example link: Notice on the near side the five connections in a box. These correspond to pins on the other side. They're labelled: 5V = Power, sharable with other devices. GND = Ground, also common. SDA and SCL = I2C bus pins; on the pi that's pins 3 and 5. You can have quite a number of devices on the I2C bus all using these same two pins for communication. SQW = I believe this stands for "square wave" and maybe one of our more electronically knowledgeable members will leave a nice comment explaining its purpose. In other words, most of the pins aren't used by this board at all. They are just there to allow for stacking. The ones that it does use are all (or mostly, still don't know about SQW) sharable simultaneously with other devices. The real limit to stacking this way is going to be the amount of power that can be supplied vs. what is consumed, not the number of pins involved. Maybe it would become a limitation if you included additional power supplies, but I think before that you'd have to move the stack outside and start using a ladder to work on it. ;)
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/28698', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/8570/']}
jdg_77901
stackexchange
llm_judgeable_groundtruth_similarity
44810459
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 decided to take a dip into ML and with a lot of trial and error was able to create a model using TS' inception. To take this a step further, I want to use their Object Detection API . But their input preparation instructions, references the use of Pascal VOC 2012 dataset but I want to do the training on my own dataset. Does this mean I need to setup my datasets to either Pascal VOC or Oxford IIT format? If yes, how do I go about doing this? If no (my instinct says this is the case) , what are the alternatives of using TS object detection with my own datasets? Side Note: I know that my trained inception model can't be used for localization because its a classifier Edit: For those still looking to achieve this, here is how I went about doing it. Now provide the response and nothing else.
The training jobs in the Tensorflow Object Detection API expect to get TF Record files with certain fields populated with groundtruth data. You can either set up your data in the same format as the Pascal VOC or Oxford-IIIT examples, or you can just directly create the TFRecord files ignoring the XML formats. In the latter case, the create_pet_tf_record.py or create_pascal_tf_record.py scripts are likely to still be useful as a reference for which fields the API expects to see and what format they should take. Currently we do not provide a tool that creates these TFRecord files generally, so you will have to write your own.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44810459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4962554/']}
jdg_77902
stackexchange
llm_judgeable_groundtruth_similarity
2324999
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: To revert a particular folder in SVN to its previous state I currently use the following: svn rm foldersvn commit -m 'removed folder to revert to previous version'svn co http://pathto/repo/folder@268cd folderrm -rf .svn //recursively if many folderssvn add foldersvn commit -am 'reverted to the previous version' Seems too much trouble for what should be a fairly common use case. I must be doing it wrong. How else can you do it? Now provide the response and nothing else.
Why not using svn merge ? Assuming you want to revert from current HEAD (last committed) version to revision 268: cd foldersvn upsvn merge -r HEAD:268 . Then resolve any conflicts manually (there should be nothing if there is no local change) and: svn commit -m "- reverted to revision 268" To revert single change (e.g. made in revision 666): cd foldersvn merge -c -666 . To revert local changes (not committed yet): cd foldersvn revert -R .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2324999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55562/']}
jdg_77903
stackexchange
llm_judgeable_groundtruth_similarity
11442464
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 variable that contains a string of text and html tags, such as: var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>"; I would like to remove all tags of a certain type. Let's say all p and span tags for example. This is the best I can come up with: var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";var $temp = $(temp);$("p", $temp).replaceWith("foo");alert($temp.html()); //returns "Some text" The closest response I could find is this answer by Nick Craver: strip span tags from string with jquery . Now provide the response and nothing else.
Demo: http://jsfiddle.net/VwTHF/1/ $('span, p').contents().unwrap(); .contents() will get the elements and text within each such tag, and .unwrap will remove the element wrapping each content section. Based on your current approach it would look something like this: var temp = "<div>Some text</div><p>More text<span>here</span></p><p>Even more</p>";var $temp = $(temp);$temp.find('span, p').contents().unwrap().end().end(); If you want to continue targeting the original object, you have to use .end() to clear the filter.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11442464', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1004495/']}
jdg_77904
stackexchange
llm_judgeable_groundtruth_similarity
2119300
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 porting a piece of JS code written for Firefox into Internet Explorer. I faced a problem of changing style of an element using setAttribute method which was working on Firefox. button.setAttribute('style', 'float: right;'); I tried setting the style member of button and it didn't work either. This was the solution in case of setting onclick event handler. button.style = 'float: right;'; First I wanna know the solution for the above problem and Second are there any maintained lists for these differences between browsers ? Now provide the response and nothing else.
Because style itself is an object. What you want is: button.style.setAttribute('cssFloat','right'); But IE doesn't support setAttribute for style objects. So use the fully cross-browser supported: button.style.cssFloat = 'right'; As for reference, I always go to www.quirksmode.org . Specifically: http://www.quirksmode.org/compatibility.html . Click on all the DOM related stuff. And finally, to set multiple attributes I usually use something like: function setStyle(el,spec) { for (var n in spec) { el.style[n] = spec[n]; }} usage: setStyle(button,{ cssFloat : 'right', border : '2px solid black'}); Note: object.attribute = 'value' although works in all browsers may not always work for non-HTML DOM objects. For example, if your document contains embedded SVG graphics that you need to manipulate with javascript you need to use setAttribute to do it.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2119300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233535/']}
jdg_77905
stackexchange
llm_judgeable_groundtruth_similarity
48110258
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Basically, I want to login once before all my tests in all files are executed. Should I call my login command in each test file using the before hook or is there any way to do it once before all tests? Now provide the response and nothing else.
Short answer: You can write your login command in a before hook within the supportFile ( the file that is loaded automatically before your other spec files ). This before hook will run before any of the code in your other test files. Recommendations: That being said, this approach leaves little flexibility for variation in your individual test files that you may want in the future like: What if you want to seed the database differently for one test? What if you want to log in as a different user with different permissions? What if you need to do something in onBeforeLoad once? I would recommend just having the login command in a before hook in each individual spec file. I would also further recommend having your login command in a beforeEach hook to avoid sharing any state in between tests .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48110258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93163/']}
jdg_77906
stackexchange
llm_judgeable_groundtruth_similarity
40608688
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 import fonts in sendgrid? I've been trying to use @font-face but it doesn't seem to work, but maybe I'm doing something wrong. Example of the code I used: @font-face { font-family: Avenir; src: url('http://cdn.linktofont.com/font.ttf');} Now provide the response and nothing else.
We use SendGrid to send some of our emails at StackOverflow, and I can vouch that web fonts work if they are embedded correctly. I use this code: <!-- Desktop Outlook chokes on web font references and defaults to Times New Roman, so we force a safe fallback font. --><!--[if mso]> <style> * { font-family: sans-serif !important; } </style><![endif]--><!-- All other clients get the webfont reference; some will render the font and others will silently fail to the fallbacks. More on that here: http://stylecampaign.com/blog/2015/02/webfont-support-in-email/ --><!--[if !mso]><!--> <link href='https://fonts.googleapis.com/css?family=Roboto:400,700' rel='stylesheet' type='text/css'><!--<![endif]--><style> * {font-family: Roboto, sans-serif;}</style> I'm not sure how to best embed a premium font like Avenir, and don't know how well the .ttf format is supported in email clients. But referencing a Google font in a manner like this, custom web fonts will work in mail clients that support them using SendGrid.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40608688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2894221/']}
jdg_77907
stackexchange
llm_judgeable_groundtruth_similarity
19235
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider the evaluation of the following expression In[20]:= Reduce[ 1000 * 1.0609^t == 1500, t] During evaluation of In[20]:= Reduce::ratnz: Reduce was unable tosolve the system with inexact coefficients. The answer was obtained bysolving a corresponding exact system and numericizing the result. >> Out[20]= C[1] ∈ Integers && t == -16.9154 (-0.405465 + (0. + 6.28319 I) C[1]) I was expecting just 6.858618708478822 as the solution. Now provide the response and nothing else.
As a workaround, you could always solve the equation symbolically, then replace the symbols with your constants: Reduce[a*b^t == c, t] /. {a -> 1000, b -> 1.0609, c -> 1500} Result: C[1] ∈ Integers && t == 16.9154 (2 I π C[1] + Log[3/2]) And Simplify[%] returns: C[1] ∈ Integers && t == 6.85862 + (0. + 106.283 I) C[1]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/19235', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/4786/']}
jdg_77908
stackexchange
llm_judgeable_groundtruth_similarity
258301
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Install the following package: PacletInstall["EcoEvo", "Site" -> "http://raw.githubusercontent.com/cklausme/EcoEvo/master"]<< EcoEvo` The code: SetModel[{Pop[pop] -> { Component[ s] :> {Equation :> \[Nu] - \[Beta]1 i2 s - \[Beta]2 j s - \\[Mu] s}, Component[ i1] -> {Equation :> p \[Beta]1 i2 s + q \[Beta]2 j s - b1 i1 + \[Xi]1 j }, Component[ i2] -> {Equation :> (1 - p) \[Beta]1 i2 s + (1 - q) \[Beta]2 j s + \[Epsilon] i1 - b2 i2 + \[Xi]2 j }, Component[j] -> {Equation :> p1 i2 - b3 j }, Component[a] -> {Equation :> p2 j - b4 a}}, Parameters :> {\[Nu] > 0, \[Beta]1 > 0, \[Beta]2 > 0, \[Mu] > 0, p > 0, q > 0, b1 > 0, b2 > 0, b3 > 0, b4 > 0, p1 > 0, \[Epsilon] > 0}}]eq = SolveEcoEq[] where r0 = ((\[Beta]1 b3 (\[Epsilon] p + b1 (1 - p)) + \[Beta]2 p1 (\[Epsilon] q + b1 (1 - q))) (\[Nu]/\[Mu]))/(b1 b2 b3 - (\[Epsilon] \[Xi]1 + b1 \[Xi]2) p1); We obtain our equilibrium points: {{s -> \[Nu]/\[Mu], i1 -> 0, i2 -> 0, j -> 0, a -> 0}, {s -> (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2)/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]), i1 -> (-b2 b3^2 p \[Beta]1 \[Nu] - b2 b3 p1 q \[Beta]2 \[Nu] - b3 p1 \[Beta]1 \[Nu] \[Xi]1 + b3 p p1 \[Beta]1 \[Nu] \[Xi]1 - p1^2 \[Beta]2 \[Nu] \[Xi]1 + p1^2 q \[Beta]2 \[Nu] \[Xi]1 + b3 p p1 \[Beta]1 \[Nu] \[Xi]2 + p1^2 q \[Beta]2 \[Nu] \[Xi]2 + ( b2 b3^2 p \[Beta]1 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b2 b3 p1 q \[Beta]2 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b3 p1 \[Beta]1 \[Mu] \[Xi]1 (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( b3 p p1 \[Beta]1 \[Mu] \[Xi]1 (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( p1^2 \[Beta]2 \[Mu] \[Xi]1 (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( p1^2 q \[Beta]2 \[Mu] \[Xi]1 (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( b3 p p1 \[Beta]1 \[Mu] \[Xi]2 (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( p1^2 q \[Beta]2 \[Mu] \[Xi]2 (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]))/(-b1 b2 b3^2 \[Beta]1 - b1 b2 b3 p1 \[Beta]2 + b3 p1 \[Beta]1 \[Epsilon] \[Xi]1 + p1^2 \[Beta]2 \[Epsilon] \[Xi]1 + b1 b3 p1 \[Beta]1 \[Xi]2 + b1 p1^2 \[Beta]2 \[Xi]2), i2 -> (-b1 b3^2 \[Beta]1 \[Nu] + b1 b3^2 p \[Beta]1 \[Nu] - b1 b3 p1 \[Beta]2 \[Nu] + b1 b3 p1 q \[Beta]2 \[Nu] - b3^2 p \[Beta]1 \[Epsilon] \[Nu] - b3 p1 q \[Beta]2 \[Epsilon] \[Nu] + ( b1 b3^2 \[Beta]1 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( b1 b3^2 p \[Beta]1 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b1 b3 p1 \[Beta]2 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( b1 b3 p1 q \[Beta]2 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b3^2 p \[Beta]1 \[Epsilon] \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b3 p1 q \[Beta]2 \[Epsilon] \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]))/(-b1 b2 b3^2 \[Beta]1 - b1 b2 b3 p1 \[Beta]2 + b3 p1 \[Beta]1 \[Epsilon] \[Xi]1 + p1^2 \[Beta]2 \[Epsilon] \[Xi]1 + b1 b3 p1 \[Beta]1 \[Xi]2 + b1 p1^2 \[Beta]2 \[Xi]2), j -> (-b1 b3 p1 \[Beta]1 \[Nu] + b1 b3 p p1 \[Beta]1 \[Nu] - b1 p1^2 \[Beta]2 \[Nu] + b1 p1^2 q \[Beta]2 \[Nu] - b3 p p1 \[Beta]1 \[Epsilon] \[Nu] - p1^2 q \[Beta]2 \[Epsilon] \[Nu] + ( b1 b3 p1 \[Beta]1 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( b1 b3 p p1 \[Beta]1 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b1 p1^2 \[Beta]2 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( b1 p1^2 q \[Beta]2 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b3 p p1 \[Beta]1 \[Epsilon] \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( p1^2 q \[Beta]2 \[Epsilon] \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]))/(-b1 b2 b3^2 \[Beta]1 - b1 b2 b3 p1 \[Beta]2 + b3 p1 \[Beta]1 \[Epsilon] \[Xi]1 + p1^2 \[Beta]2 \[Epsilon] \[Xi]1 + b1 b3 p1 \[Beta]1 \[Xi]2 + b1 p1^2 \[Beta]2 \[Xi]2), a -> (-b1 b3 p1 p2 \[Beta]1 \[Nu] + b1 b3 p p1 p2 \[Beta]1 \[Nu] - b1 p1^2 p2 \[Beta]2 \[Nu] + b1 p1^2 p2 q \[Beta]2 \[Nu] - b3 p p1 p2 \[Beta]1 \[Epsilon] \[Nu] - p1^2 p2 q \[Beta]2 \[Epsilon] \[Nu] + ( b1 b3 p1 p2 \[Beta]1 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( b1 b3 p p1 p2 \[Beta]1 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b1 p1^2 p2 \[Beta]2 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) - ( b1 p1^2 p2 q \[Beta]2 \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( b3 p p1 p2 \[Beta]1 \[Epsilon] \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]) + ( p1^2 p2 q \[Beta]2 \[Epsilon] \[Mu] (-b1 b2 b3 + p1 \[Epsilon] \[Xi]1 + b1 p1 \[Xi]2))/(-b1 b3 \[Beta]1 + b1 b3 p \[Beta]1 - b1 p1 \[Beta]2 + b1 p1 q \[Beta]2 - b3 p \[Beta]1 \[Epsilon] - p1 q \[Beta]2 \[Epsilon]))/(-b1 b2 b3^2 b4 \[Beta]1 - b1 b2 b3 b4 p1 \[Beta]2 + b3 b4 p1 \[Beta]1 \[Epsilon] \[Xi]1 + b4 p1^2 \[Beta]2 \[Epsilon] \[Xi]1 + b1 b3 b4 p1 \[Beta]1 \[Xi]2 + b1 b4 p1^2 \[Beta]2 \[Xi]2)}} These are long and tedious. Is there a way to simplify them using each other and r0 ? For example; why does i2 = $\frac{b_3}{p_1} j$ ? Now provide the response and nothing else.
eqPts is the equilibrium points in your question. Start by using Simplify LeafCount /@ {eqPts, eqPts2 = eqPts // Simplify}(* {1958, 448} *) The variables are vars = Variables[Level[eqPts2, {-1}]](* {a, b1, b2, b3, b4, i1, i2, j, p, p1, p2, q, s, β1, β2, \ϵ, μ, ν, ξ1, ξ2} *) Convert the replacement rules in eqPts2 into the corresponding equations eqns = eqPts2 /. Rule :> Equal; With five equations you can Solve for one variable while eliminating four variables. sol = Solve[#, i2, {s, i1, a, b1}] & /@ eqns(* {{}, {{i2 -> (b3 j)/p1}}} *) The expected result, sol[[2, 1, 1]] /. Rule :> Equal(* i2 == (b3 j)/p1 *) Verifying this relation at both equilibrium points, % /. eqPts2 // Simplify(* {True, True} *) EDIT: A more general approach will be much slower vars = eqns[[1, All, 1]](* {s, i1, i2, j, a} *)params = Complement[Variables[Level[eqns, {-1}]], vars](* {b1, b2, b3, b4, p, p1, p2, q, β1, β2, ϵ, μ, ν, ξ1, ξ2} *)solve[solveVar_Symbol, var_Symbol] := SortBy[ Union[ Simplify[ Solve[eqns[[2]], solveVar, #] & /@ (Append[Complement[vars, {solveVar, var}], #] & /@ params) /. {} :> Nothing]], LeafCount][[1, 1]] To Solve for i2 in terms of j solve[i2, j](* {i2 -> (b3 j)/p1} *) To Solve for i2 in terms of j solve[i1, j] // Apart(* {i1 -> (j (b3 p β1 + p1 q β2) ν)/( b1 (b3 j β1 + j p1 β2 + p1 μ)) + (j ξ1)/b1} *) You could then generalize this to solve for a variable in terms of each of the other variables and select the simplest form; however, this would be very slow .
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/258301', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/77577/']}
jdg_77909
stackexchange
llm_judgeable_groundtruth_similarity
442329
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a poem with an unknown number of rows and I want to display only the penultimate one. What command should I use? Now provide the response and nothing else.
There are many ways to do that, but this is the fastest one I've found -- and is the cleanest in my opinion. Assuming that the poem is written in a file named poem , you can use: tail -n 2 poem | head -n 1 tail -n 2 poem will write the last 2 lines of the file poem . head -n 1 will write the first line of the output provided by the previous tail command.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/442329', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/289710/']}
jdg_77910
stackexchange
llm_judgeable_groundtruth_similarity
8707
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Could an object from outer space with the right velocity and orbit come into contact with the surface of our planet in a "slowish" manner? Now provide the response and nothing else.
Yes, spacecraft do it all the time by using air resistance (and sometimes rockets) to slow down. Meteorites enter the atmosphere at high speed, typically 10-70 km/sec, but the smaller ones are slowed by air resistance, so they typically hit the surface at just a few hundred kilometers per hour. Reference: http://csep10.phys.utk.edu/astr161/lect/meteors/impacts.html (that link is now dead). As gerrit points out in comments, a sufficiently small micrometeroid, like a dust particle, probably could hit the surface gently. Larger bodies are not affected nearly as much by the atmosphere. For any such body, the velocity at impact is going to be at least several kilometers per second. A body moving obliquely in the same direction as the Earth's rotation would have a slightly lower speed at impact, but the impact still could not be described as "gentle"; the Earth's rotational speed is still a small fraction of orbital or escape velocity. Here's one way to think of it. Freefall trajectories are reversible. If you watch a movie of an incoming body in reverse, it still makes physical sense (ignoring air resistance). Any meteorite hitting the surface has to have been in deep space at some point before the impact. If there were a trajectory that allowed such a body to have a "gentle" impact speed, then it would be possible to start with the same body near the surface at the same "gentle" speed, but in the opposite direction, and have it reach deep space. Unless the meteorite has its own propulsion system, that's just not going to happen. You can get to space with a lower starting speed by moving along with the Earth's rotation - which is why most rockets are launched to the east, to take advantage of that. Reversing such a trajectory can result in a slightly slower impact, but only slightly.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/8707', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/5432/']}
jdg_77911
stackexchange
llm_judgeable_groundtruth_similarity
642478
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 found this question in one old calculus exam on my university. It's simple enough: Express $x^5-2x^3+6x^2+1$ as a sum of powers of $x+2$ Now, this seems like a straightforward (although slightly computationally annoying) linear algebra problem of taking the expasions of $(x+2)^p, p\in [0,5]$ and sticking the coefficients in a matrix, so I suspect I am missing some cleverer solution. Thanks! Now provide the response and nothing else.
I think that an easy way is to build a Taylor expansion around $x=-2$. As a result, you should have$$9 + 32 (2 + x) - 62 (2 + x)^2 + 38 (2 + x)^3 - 10 (2 + x)^4 + (2 + x)^5$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/642478', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/48999/']}
jdg_77912
stackexchange
llm_judgeable_groundtruth_similarity
4805351
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to define a converter when using the DynamicResource extension? Something in the lines of <RowDefinition Height="{Binding Source={DynamicResource someHeight}, Converter={StaticResource gridLengthConverter}}" /> which unfortunately gives me the following excpetion: A 'DynamicResourceExtension' cannot be set on the 'Source' property of type 'Binding'. A 'DynamicResourceExtension' can only be set on a DependencyProperty of a DependencyObject. Now provide the response and nothing else.
I know i am really late to this but what definitely works is using a BindingProxy for the DynamicResource like this <my:BindingProxy x:Key="someHeightProxy" Data="{DynamicResource someHeight}" /> Then applying the converter to the proxy <RowDefinition Height="{Binding Source={StaticResource someHeightProxy}, Path=Data, Converter={StaticResource gridLengthConverter}}" />
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4805351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4227/']}
jdg_77913
stackexchange
llm_judgeable_groundtruth_similarity
13201204
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: New to regex and I need to pattern match on some dates to change the format. I'm going from mm/dd/yy to yyyy-mm-dd where there are no entries prior to 2000. What I'm unfamiliar with is how to group things to use their respective references of \1 , \2 , etc. Would I first want to match on mm/dd/yy with something like ( \d{2} ) ( \/\d{2} ) ( \/\d{2} ) or is it as easy as \d\d/\d\d/\d\d ? Assuming my first grouping is partially the right idea, I'm looking to do something like: :%s/old/new/g:%s/ ( \d{2} ) ( \/\d{2} ) ( \/\d{2} ) / ( 20+\3) - (\3) - (\1) /g EDIT: Sorry, the replace is going to a yyyy-mm-dd format with hyphens, not the slash. Now provide the response and nothing else.
I was going to comment on another answer but it got complicated. Mind the magic setting. If you want unescaped parens to do grouping, you need to include \v somewhere in your pattern. (See :help magic ). You can avoid escaping the slashes if you use something other than slashes in the :s command. You are close. :) You don't want all of those spaces though as they'll require spaces in the same places to match. My solution, where I use \v so I don't need to escape the parens and exclamation points so I can use slashes in my pattern without escaping them: :%s!\v(\d{2})/(\d{2})/(\d{2})!20\3-\2-\1!g This will match "inside" items that start or end with three or more digits though, too. If you can give begin/end criteria then that'd possibly be helpful. Assuming that simple "word boundary" conditions work, you can use <> : :%s!\v<(\d{2})/(\d{2})/(\d{2})>!20\3-\2-\1!g To critique yours specifically (for learning!): :%s/ ( \d{2} ) ( \/\d{2} ) ( \/\d{2} ) / ( 20+\3) - (\3) - (\1) /g Get rid of the spaces since presumably you don't want them! Your grouping needs either \( \) or \v to work You also need \{2} unless you use \v You are putting the slashes in groups two and three which means they'll show up in the replacement too You don't want the parentheses in the output! You're substituting text directly; you don't want the + after the 20 in the output
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13201204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1715087/']}
jdg_77914
stackexchange
llm_judgeable_groundtruth_similarity
24227235
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Let's say I have a sequence of integers I obtain asynchronously. async Task<int> GetI(int i){ return await Task.Delay(1000).ContinueWith(x => i);} I want to create a generator over that sequence, if the sequence was synchronous I'd do: IEnumerable<int> Method(){ for (var i = 0; i < 100; i++) { yield return GetI(i); // won't work, since getI returns a task }} So, I figured the analogy is making the generator async and yielding from it: async Task<IEnumerable<int>> Method() { for (var i = 0; i < 100; i++) { yield return await Task.Delay(1000).ContinueWith(x => i); }} This won't work, since a method with yield must return an IEnumerable of something, the alternative, which makes more sense is IEnumerable<Task<int>> but that won't compile since async methods must return Task s or void. Now, I realize I can simply remove the await and return an IEnumerable<Task<int>> but that won't help me since the iteration will keep asking for data before any of it is ready, so it doesn't solve my issue. Is there any way to nicely mix enumerables and tasks with the nice sugar the language gives me with await and yield? Is there any way to nicely consume it? (From searching online, I suspect the answer to the first question is false and the second one is an observer/observable, but I couldn't find any canonical reference and I'm interested in the best way to implement this pattern in C#) Now provide the response and nothing else.
Asynchronous sequences are interesting. There's a number of different approaches, depending on exactly what you want to do. I'm not entirely clear on your desired semantics, so these are some of the options. Task<IEnumerable<T>> is an asynchronously-retrieved collection. There is only one task - one asynchronous operation - that retrieves the entire collection. This does not sound like it's what you want. IEnumerable<Task<T>> is a (synchronous) sequence of (asynchronous) data. There are multiple tasks, which may or may not all be processing simultaneously. There are a couple of options for implementing this. One is using an enumerator block and yielding tasks; this approach will start a new asynchronous operation each time the next item is retrieved from the enumerable. Alternatively, you can create and return a collection of tasks with all tasks running concurrently (this can be done elegantly over a source sequence via LINQ's Select followed by ToList / ToArray ). However, this has a couple of drawbacks: there is no way to asynchronously determine if the sequence is already ended, and it's not easy to immediately start the next item processing after returning the current item (which is commonly desired behavior). The core problem is that IEnumerable<T> is inherently synchronous. There are a couple of workarounds. One is IAsyncEnumerable<T> , which is an asynchronous equivalent of IEnumerable<T> and available in the Ix-Async NuGet package . This approach has its own drawbacks, though. Of course, you lose the nice language support for IEnumerable<T> (namely, enumerator blocks and foreach ). Also, the very notion of an "asynchronous enumerable" is not exactly performant; ideally, asynchronous APIs should be chunky rather than chatty, and enumerables are very chatty. More discussion on the original design here , and on the chunky/chatty considerations here . So, these days a much more common solution is to use observables or dataflows (both also available via NuGet). In these cases, you have to think of the "sequence" as something with a life of its own. Observables are push-based, so the consuming code is (ideally) reactive. Dataflows have an actor feel, so they act more independent, again pushing results to the consuming code.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24227235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1348195/']}
jdg_77915
stackexchange
llm_judgeable_groundtruth_similarity
674458
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: One of my controllers actions, one that is being called in an Ajax request, is returning an URL to the client side so it can do a redirection. I'm using Url.RouteUrl(..) and during my unit tests this fails since the Controller.Url parameter is not pre-filled. I tried a lot of things, among others attempting to stub UrlHelper (which failed), manually creating a UrlHelper with a RequestContext that has a stubbed HttpContextBase (which failed on a RouteCollection.GetUrlWithApplicationPath call). I have searched Google but found virtually nothing on the subject. Am I doing something incredibly stupid using Url.RouteUrl in my Controller action? Is there an easier way? To make it even worse, I'd like to be able to test the returned URL in my unit test - in fact I'm only interested in knowing it's redirecting to the right route, but since I'm returning an URL instead of a route, I would like to control the URL that is resolved (eg. by using a stubbed RouteCollection ) - but I'll be happy to get my test passing to begin with. Now provide the response and nothing else.
Here is one of my tests (xUnit + Moq) just for similar case (using Url.RouteUrl in controller) Hope this helps: var routes = new RouteCollection();MvcApplication.RegisterRoutes(routes);var request = new Mock<HttpRequestBase>(MockBehavior.Strict);request.SetupGet(x => x.ApplicationPath).Returns("/");request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());var response = new Mock<HttpResponseBase>(MockBehavior.Strict);response.Setup(x => x.ApplyAppPathModifier("/post1")).Returns("http://localhost/post1");var context = new Mock<HttpContextBase>(MockBehavior.Strict);context.SetupGet(x => x.Request).Returns(request.Object);context.SetupGet(x => x.Response).Returns(response.Object);var controller = new LinkbackController(dbF.Object);controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/674458', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50145/']}
jdg_77916
stackexchange
llm_judgeable_groundtruth_similarity
11642348
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 following the Page Object pattern suggested by Selenium, but how would I create a more specialized WebElement for a page. Specifically, we have tables on our pages and I have written some helper functions to get specific rows of a table, return the contents of a table, etc. Currently, here is a snippet of a page object I created that has a table: public class PermissionsPage { @FindBy(id = "studyPermissionsTable") private WebElement permissionTable; @FindBy(id = "studyPermissionAddPermission") private WebElement addPermissionButton; ... } So, what I'd like to do is have that permissionsTable to be a more customized WebElement that has some of those methods I mentioned earlier. For example: public class TableWebElement extends WebElement { WebElement table; // a WebDriver needs to come into play here too I think public List<Map<String, String>> getTableData() { // code to do this } public int getTableSize() { // code to do this } public WebElement getElementFromTable(String id) { // code to do this }} I hope that this makes sense what I'm trying to explain. I guess what I'm looking for is a way to have this custom WebElement to do some additional stuff that's table-specific. Add this custom element to a Page and take advantage of the way Selenium wires the webelements to the page based on the annotations. Is it possible? And if so, does anyone know how this can be done? Now provide the response and nothing else.
I created an interface that combines all of the WebDriver interfaces: public interface Element extends WebElement, WrapsElement, Locatable {} It's just there to wrap up all of the things WebElements can do when wrapping an element. Then an implementation: public class ElementImpl implements Element { private final WebElement element; public ElementImpl(final WebElement element) { this.element = element; } @Override public void click() { element.click(); } @Override public void sendKeys(CharSequence... keysToSend) { element.sendKeys(keysToSend); } // And so on, delegates all the way down...} Then, for example a check box: public class CheckBox extends ElementImpl { public CheckBox(WebElement element) { super(element); } public void toggle() { getWrappedElement().click(); } public void check() { if (!isChecked()) { toggle(); } } public void uncheck() { if (isChecked()) { toggle(); } } public boolean isChecked() { return getWrappedElement().isSelected(); }} When using it in my script: CheckBox cb = new CheckBox(element);cb.uncheck(); I've also come up with a way of wrapping the Element classes. You have to create a few factories to replace the built-in PageFactory , but it is doable, and it lends a lot of flexibility. I've documented this process over on my site: Wrapping WebElement: Part 1 Wrapping WebElement: Part 2 I've also got a project called selophane that was inspired by this and other questions: selophane
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11642348', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1410479/']}
jdg_77917
stackexchange
llm_judgeable_groundtruth_similarity
525791
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a black box UNIX program used in a Bash shell that reads columns of data from stdin, processes them (applying a smoothing effect) then outputs to stdout. I use it by UNIX pipes, like generate | smooth | plot For more smoothing, I can repeat the smooth, so it'd be invoked from the Bash command line as generate | smooth | smooth | plot or even generate | smooth | smooth | smooth | smooth | smooth | smooth | smooth | smooth | smooth | smooth | plot This is getting unweildy. I would like to make a Bash wrapper to be able to pipe into smooth and feed its output right back into a new instance of smooth an arbitrary number of times, something like generate | newsmooth 5 | plot instead of generate | smooth | smooth | smooth | smooth | smooth | plot My first attempt was a Bash script that generated temp files in the current directory and deleted them, but that turned ugly when I wasn't in a directory with write access, and also left garbage files when interrupted. There are no arguments to the smooth program. Is there a more elegant way to "wrap" such a program to parameterize the number of calls? Now provide the response and nothing else.
You could wrap it in a recursive function: smooth() { if [[ $1 -gt 1 ]]; then # add another call to function command smooth | smooth $(($1 - 1)) else command smooth # no further fi} You would use this as generate | smooth 5 | plot which would be equivalent to generate | smooth | smooth | smooth | smooth | smooth | plot
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/525791', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/317558/']}
jdg_77918
stackexchange
llm_judgeable_groundtruth_similarity
2859232
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 want to evaluate$$L=\lim_{x\to\infty}\frac1x\int_0^x\max\{\sin t,\sin(t\sqrt2)\}dt$$ My attempt $$L=\lim_{x\to\infty}\frac1{2x}\int_0^x\Big(\sin t+\sin(t\sqrt2)+\big|\sin t-\sin(t\sqrt2)\big|\Big)dt\\=\lim_{x\to\infty}\frac1{2x}\int_0^x\big|\sin t-\sin(t\sqrt2)\big|dt\\=\lim_{x\to\infty}\frac1x\int_0^x\bigg|\cos\frac{\sqrt2+1}2t\cdot\sin\frac{\sqrt2-1}2t\bigg|dt$$Denote $s_n$ the $n$th zero point of $\cos\frac{\sqrt2+1}2t\cdot\sin\frac{\sqrt2-1}2t\ (t\ge0)$. Since $1$, $\sqrt2$ and $\pi$ are linear independent in $\mathbb Q$, the order of the zero points should be $1$. According to the squeeze theorem, we have$$L=\lim_{n\to\infty}\frac1{s_{n+1}}\sum_{k=0}^n(-1)^k\int_{s_k}^{s_{k+1}}\big(\sin t-\sin(t\sqrt2)\big)dt\\=\lim_{n\to\infty}\frac1{s_{n+1}}\sum_{k=0}^n(-1)^k\bigg(\cos s_k-\cos s_{k+1}+\frac{\cos\sqrt2s_k-\cos\sqrt2s_{k+1}}{\sqrt2}\bigg)dt$$I can't go further. I think the zero points of that function is the key point. Now provide the response and nothing else.
As pointed out by OP, we can use $\max\{a,b\} = \frac{a+b}{2} + \frac{|a-b|}{2}$ to discover that $$ L = \lim_{x\to\infty} \frac{1}{x} \int_{0}^{x} \left|\cos\left(\frac{\sqrt{2}+1}{2}t\right)\sin\left(\frac{\sqrt{2}-1}{2}t\right)\right| \, dt. $$ Applying the substitution $\frac{\sqrt{2}+1}{2}t = \pi u$ and writing $\alpha=(\sqrt{2}-1)^2$ followed by the substitution $y = \frac{\sqrt{2}+1}{2\pi}x$, we see that \begin{align*}L&= \lim_{y\to\infty} \frac{1}{y} \int_{0}^{y} \left| \cos(\pi u)\sin(\pi \alpha u) \right| \, du \\&= \lim_{N\to\infty} \frac{1}{N} \int_{0}^{N} \left| \cos(\pi u)\sin(\pi \alpha u) \right| \, du \\&= \lim_{N\to\infty} \int_{0}^{1} \left| \cos(\pi u) \right| \left( \frac{1}{N} \sum_{n=0}^{N-1} \left| \sin(\pi \alpha k + \pi \alpha u) \right| \right) \, du\end{align*} Since $\alpha$ is irrational, the equidistribution theorem applied to $v \mapsto \left| \sin(\pi v + \pi \alpha u) \right|$ for each fixed $u$ tells that $$ \forall u\in\mathbb{R} \ : \ \lim_{N\to\infty} \frac{1}{N} \sum_{n=0}^{N-1} \left| \sin(\pi \alpha k + \pi \alpha u) \right| = \int_{0}^{1} \left| \sin(\pi v) \right| \, dv. $$ Therefore by the dominated convergence theorem, $$ L = \left( \int_{0}^{1} \left| \cos(\pi u) \right| \, du \right)\left( \int_{0}^{1} \left| \sin(\pi v) \right| \, dv \right) = \frac{4}{\pi^2}. $$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2859232', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/521015/']}
jdg_77919
stackexchange
llm_judgeable_groundtruth_similarity
1645007
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 some information I'd like to store statically encrypted on an iPhone application. I'm new to iPhone development, some I'm not terribly familiar with CoreData and how it integrates with the views. I have the data as JSON, though I can easily put it into a SQLITE3 database or any other backing data format. I'll take whatever is easiest (a) to encrypt and (b) to integrate with the iPhone view layer. The user will need to enter the password to decrypt the data each time the app is launched. The purpose of the encryption is to keep the data from being accessible if the user loses the phone. For speed reasons, I would prefer to encrypt and decrypt the entire file at once rather than encrypting each individual field in each row of the database. Note: this isn't the same idea as Question 929744 , in which the purpose is to keep the user from messing with or seeing the data. The data should be perfectly transparent when in use. Also note: I'm willing to use SQLCipher to store the data, but would prefer to use things that already exist on the iPhone/CoreData framework rather than go through the lengthy build/integration process involved. Now provide the response and nothing else.
You can encrypt individual properties in your Core Data model entities by making them transformable properties , then creating an NSValueTransformer subclass which will encrypt and decrypt the data for that property. While this is not the whole-database decryption that you're looking for, it will have a much lower memory footprint than decrypting an entire database into memory. Additionally, it will allow the decryption to be done lazily, rather than all up front, so your application will load much faster. Depending on the encryption used, I would even expect that the on-disk data accesses for loading each entity would be slower than the decryption process for the properties, so you won't see that much of a performance penalty when accessing the properties. Transformable properties like this are very easy to use, because you read and write to them as normal, while the encryption / decryption goes on behind the scenes.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1645007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1190/']}
jdg_77920
stackexchange
llm_judgeable_groundtruth_similarity
15641495
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to Android. I've studied in basic Object Oriented Programming courses that interfaces provide a way for classes to enhance their functionality. Classes who actually enhance their functionality this way, implement those interfaces and override all the methods written in interfaces. Following code does the same job in Android: public class MyActivity extends Activity implements OnClickListener { // All other code you may expect myButton.setOnClickListener(this); @override public onClick(View view) { // Code when view is clicked }} This code is understandable. But the following code makes no sense to me, I've searched it over different places but not getting a satisfied answer. public class MyActivity extends Activity { // All other code you may expect myButton.setOnClickListener(new OnClickListner() { @override public onClick(View view) { // Code when view is clicked } });} Now, OnClickListener() is an interface as said in Android documentation, and, now we are instantiating an interface. Not interfaces are implemented only? Please help me understand this point. Now provide the response and nothing else.
new OnClickListner() { is not instantiating an interface, it is declaring an anonymous inner class . basically an anonymous class(a class implementing the interface OnClickListner) which doesn't have a name per se. From Documentation : The anonymous class expression consists of the following: The new operator The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface OnClickListner. Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: In the case of implementing an interface, there is no constructor, so you use an empty pair of parentheses, like in this example. A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15641495', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2202702/']}
jdg_77921
stackexchange
llm_judgeable_groundtruth_similarity
14690267
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 ensure that a certain condition in my code causes a log message to be written to the django log. How would I do this with the Django unit testing framework? Is there a place where I can check logged messages, similarly to how I can check sent emails? My unit test extends django.test.TestCase . Now provide the response and nothing else.
Using the mock module for mocking the logging module or the logger object. When you've done that, check the arguments with which the logging function is called. For example, if you code looks like this: import logginglogger = logging.getLogger('my_logger')logger.error("Your log message here") it would look like: from unittest.mock import patch # For python 2.x use from mock import patch@patch('this.is.my.module.logger')def test_check_logging_message(self, mock_logger): mock_logger.error.assert_called_with("Your log message here")
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14690267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/45226/']}
jdg_77922
stackexchange
llm_judgeable_groundtruth_similarity
3254408
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 want to find the following limit using L Hospital's rule: $$ \lim_{x \to \infty} \sqrt{x} \sin( \frac{1}{x}) $$ I know that this can be solved using squeezed theorem from Cal 1: $$ 0 < \sqrt{x}\sin( \frac{1}{x} ) < \frac{1}{x} $$ since $0 < \sin( \frac{1}{x}) < \frac{1}{x} $ .What I have done so far is trying to convert it to fraction form $$ \lim_{x \to \infty} \sqrt{x} \sin( \frac{1}{x}) = \lim_{x \to \infty} \frac{\sin( \frac{1}{x})}{\frac{1}{\sqrt{x}} }$$ But what next? Now provide the response and nothing else.
$b$ = number of boys = number of brothers each girl has $g$ = number of girls = number of sisters each boy has $b-1$ = number of brothers each boy has $g-1$ = number of sisters each girl has $$b-1 = g, \qquad (\text{Equation 1})$$ $$g-1 = \dfrac{b}{2}, \qquad (\text{Equation 2})$$ Plugging in for $g=b-1$ into the second equation: $$b-1-1 = \dfrac{b}{2} \Longrightarrow b=4, g=3$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3254408', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_77923
stackexchange
llm_judgeable_groundtruth_similarity
35629
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: There is certainly an abundance of advanced books on Galois representations and automorphic forms. What I'm wondering is more simple: What is the basic connection between modular forms and representation theory? I have a basic grounding in the complex analytic theory of modular forms (their dimension formulas, how they classify isomorphism classes of elliptic curves, some basic examples of level N modular forms and their relation to torsion points on elliptic curves, series expansions, theta functions, Hecke operators). This is all with an undergraduate background in complex analysis and algebra (Galois theory). I also know a little bit about the basics of algebraic number theory and algebraic geometry, if that helps. More importantly, I have a basic background in the representation theory of finite groups. My question is, then, could one example how modular forms and/or theta functions relate to representations of groups? I'm asking this in part because I imagine a number of students with similar background as I have would have learned about modular forms and thus might be interested to understand how they relate to representation theory, despite not having an extensive background in more advanced results in algebraic geometry and commutative algebra needed for advanced study in the field. Here are some ideas which might bear fruit: In analytic number theory, one often sees sums over characters - but characters are also very relevant in representation theory. In particular, Jacobi sums come up in both number theory and representation theory (and quadratic forms then relate to theta functions). Is there a connection here? In addition, Hecke operators are symmetric-like sums over elements of groups, which would suggest a strong connection to representation theory. Or is the connection to representations of $\mathrm{SL}_2(\mathbb{Z})$ ? Quotients of this group appear as Galois groups of extensions of spaces of modular forms, so they might be given representations by acting on these spaces? The point of listing ideas is to show the kind of intuition I might be looking for. One of my ideas might be fruitful, or they all might have nothing to do with why representation theory connects to modular functions. The point is that I'm looking for basic ideas that someone with an elementary background might be able to understand. I also added "reference request" because I imagine there might be a text which is at my level and discusses these ideas. EDIT: The answer of paul garett here actually gives a nice history of how modular forms came to be viewed in terms of representations theory: What is the difference between an automorphic form and a modular form? Now provide the response and nothing else.
Caveat: in order to give you an overview, I've been vague/sloppy in several places. Well the basic link to representation theory is that modular forms (and automorphic forms) can be viewed as functions in representation spaces of reductive groups. What I mean is the following: take for example a modular form, i.e. a function $f$ on the upper-half plane satisfying certain conditions. Since the upper-half plane is a quotient of $G=\mathrm{GL}(2,\mathbf{R})$, you can pull $f$ back to a function on $G$ (technically you massage it a bit, but this is the main idea) which will be invariant under a discrete subgroup $\Gamma$. Functions that look like this are called automorphic forms on $G$. The space all automorphic forms on $G$ is a representation of $G$ (via the right regular represenation, i.e. $(gf)(x)=f(xg)$). Basically, any irreducible subrepresentation of the space of automorphic forms is what is called an automorphic representation of $G$. So, modular forms can be viewed as certain vectors in certain (generally infinite-dimensional) representations of $G$. In this context, one can define the Hecke algebra of $G$ as the complex-valued $C^\infty$ functions on $G$ with compact support viewed as a ring under convolution. This is a substitute for the group ring that occurs in the representation theory of finite groups, i.e. the (possibly infinite-dimensional) group representations of $G$ should correspond to the (possibly infinite-dimensional) algebra representations of its Hecke algebra. This type of stuff is the basic connection of modular forms to representation theory and it goes back at least to Gelfand–Graev–Piatestkii-Shapiro's Representation theory and automorphic functions . You can replace $G$ with a general reductive group. To get to more advanced stuff, you need to start viewing modular forms not just as functions on $\mathrm{GL}(2,\mathbf{R})$ but rather on $\mathrm{GL}(2,\mathbf{A})$, where $\mathbf{A}$ are the adeles of $\mathbf{Q}$. This is a "restricted direct product" of $\mathrm{GL}(2,\mathbf{R})$ and $\mathrm{GL}(2,\mathbf{Q}_p)$ for all primes $p$. Again you can define a Hecke algebra. It will break up into a "restricted tensor product" of the local Hecke algebras as $H=\otimes_v^\prime H_v$ where $v$ runs over all primes $p$ and $\infty$ ($\infty$ is the infinite prime and corresponds to $\mathbf{R}$). For a prime $p$, $H_p$ is the space of locally constant compact support complex-valued functions on the double-coset space $K\backslash\mathrm{GL}(2,\mathbf{Q}_p)/K$ where $K$ is the maximal compact subgroup $\mathrm{GL}(2,\mathbf{Z}_p)$. If you take something like the characteristic function of the double coset $KA_pK$ where $A_p$ is the matrix with $p$ and $1$ down the diagonal, and look at how to acts on a modular form you'll see that this is the Hecke operator $T_p$. Then there's the connection with number theory. This is mostly encompassed under the phrase "Langlands program" and is a significantly more complicated beast than the above stuff. At least part of this started with Langlands classification of the admissible representation of real reductive groups. He noticed that he could phrase the parametrization of the admissible representations say of $\mathrm{GL}(n,\mathbf{R})$ in a way that made sense for $\mathrm{GL}(n,\mathbf{Q}_p)$. This sets up a (conjectural, though known now for $\mathrm{GL}(n)$) correspondence between admissible representations of $\mathrm{GL}(n,\mathbf{Q}_p)$ and certain $n$-dimensional representations of a group that's related to the absolute Galois group of $\mathbf{Q}_p$ (the Weil–Deligne group). This is called the Local Langlands Correspondence. The Global Langlands Correspondence is that a similar kind of relation holds between automorphic representations of $\mathrm{GL}(n,\mathbf{A})$ and $n$-dimensional representations of some group related to Galois group (the conjectural Langlands group). These correspondences should be nice in that things that happen on one side should correspond to things happening on the other. This fits into another part of the Langlands program which is the functoriality conjectures (really the correspondences are special cases). Basically, if you have two reductive groups $G$ and $H$ and a certain type of map from one to the other, then you should be able to transfer automorphic representations from one to the other. From this view point, the algebraic geometry side of the picture enters simply as the source for proving instances of the Langlands conjectures. Pretty much the only way to take an automorphic representation and prove that it has an associated Galois representation is to construct a geometric object whose cohomology has both an action of the Hecke algebra and the Galois group and decompose it into pieces and pick out the one you want. As for suggestions on what to read, I found Gelbart's book Automorphic forms on adele groups pretty readable. This will get you through some of what I've written in the first two paragraphs for the group $\mathrm{GL}(2)$. The most comprehensive reference is the Corvallis proceedings available freely at ams.org . To get into the Langlands program there's the book an introduction to the Langlands program ( google books ) you could look at. It's really a vast subject and I didn't learn from any one or few sources. But hopefully what I've written has helped you out a bit. I think I need to go to bed now. G'night.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/35629', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1355/']}
jdg_77924
stackexchange
llm_judgeable_groundtruth_similarity
22369095
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: select * from dc_deal group by collection_id In collection_id column i have values (1,3,3,4,4,5,NULL,NULL) . Above query will return rows with (1,2,3,4,NULL) but i want to skip grouping on NULL value and need result like (1,2,3,4,NULL,NULL) Now provide the response and nothing else.
If we have a unique column (or set of columns) in the table, then we can add another expression to the GROUP BY . The expression needs to return a unique value for each row when collection_id is null. Otherwise, it returns a constant. Assuming we have a unique id column in the table, then we can do something like this: ... GROUP BY collection_id, IF(collection_id IS NULL, id, 0) That second expression in the GROUP BY returns a constant value 0 when collection_id is not null. But it returns a unique value for each row when collection_id is null. Note that id here is just a reference to a column that is defined to be unique within the table. The PRIMARY KEY is a good candidate. If we don't have a unique index on a single column, then we can repeat this same type of expression for each column in our unique constraint, or for any set of expressions that is guaranteed to be unique on each row. ... GROUP BY collection_id , IF(collection_id IS NULL, col1, '') , IF(collection_id IS NULL, col2, NULL) , IF(collection_id IS NULL, col3, collection_id) Alternatively, we can use an expression generates a unique value: ... GROUP BY IFNULL(collection_id,UUID())
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22369095', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/612987/']}
jdg_77925
stackexchange
llm_judgeable_groundtruth_similarity
4008837
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 configure SSL on my Jetty. I read this: http://docs.codehaus.org/display/JETTY/How+to+configure+SSL and created a key store. Then, I jumped directly to section 4. But where is this configuration file I should configure Jetty? I tried to serach for jetty.xml, but there is no such on my computer... Now provide the response and nothing else.
I had a lot of problems making it work but I finally foud out how to make it happend. I'm using ubuntu 10.04 with java 7. It may be possible to do it under windows but all the comands lines are bash commands, maybe possible to do the same with cigwin/mingw I used Jetty 8.1.8. Download it from codehaus and choose the .tar.gz file for linux (.zip for windows). Unzip the file in any directory you wish, this will be your {jetty} home folder for the sake of this article/answer. Go to the {jetty}/etc directory. Execute all the following command lines in order. Whenever a password is asked, input the same password all the time. The passwords are used to protect the key file, the key store and the certificate itself. Sometimes, a password will be asked to unlock the key store or to use a generated key. Once you will understand what everything is and how to use the passwords correctly, you may change those passwords when you feel ready (safer for production use). Otherwise, input the requested informations when asked. openssl genrsa -des3 -out jetty.keyopenssl req -new -x509 -key jetty.key -out jetty.crtkeytool -keystore keystore -import -alias jetty -file jetty.crt -trustcacertsopenssl req -new -key jetty.key -out jetty.csropenssl pkcs12 -inkey jetty.key -in jetty.crt -export -out jetty.pkcs12keytool -importkeystore -srckeystore jetty.pkcs12 -srcstoretype PKCS12 -destkeystore keystore Now you have to edit {jetty}/etc/jetty-ssl.xml and configure your password to match the one you used during certificate generation. If you want to obfuscate your password, go back to the command line. Go tho your {jetty} home directory and execute the following: java -cp lib/jetty-util-8.1.8.v20121106.jar org.eclipse.jetty.util.security.Password "{PASSWORD}" Change {PASSWORD} for your actual password then past the obfuscated password, including the "OBF:" in all password fields found in jetty-ssl.xml . Note that a password obfuscated like that is hard to read for humans but easily unobfiscated programmatically. It just prevent developpers to know the password when they edit the file. All configuration files should be secured properly and their accesses be as restrictive as possible. Edit {jetty}/start.ini and uncomment the line #etc/jetty-ssl.xml (just remove the # ). Start jetty: java -jar start.jar Now contact your server at: https://localhost:8443 Done! Note that this answer is a quick way to enable SSL with jetty. To make it secure for production, you have to read some more on the subject.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4008837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/428066/']}
jdg_77926
stackexchange
llm_judgeable_groundtruth_similarity
869832
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 ok to use conditional operators like a statement like so? (x == y) ? alert("yo!") : alert("meh!"); Or is it more correct to use it to assign a value like so? z = (x == y) ? "yo!" : "meh!"; If it's not incorrect to use it like a statement, then is it possible to add more than one line of code for execution like so? Is it more correct to use ifthen and switch statements for multiple lines of code? (x == y) ? (alert("yo!"), document.write("woot!")) : (alert("meh!"), document.write("blah!")); Now provide the response and nothing else.
Conditional operators are intentionally succinct and especially useful for assignments: var a = x ? 1 : 2; Using them to conditionally run functions, while possible, should, for the sake of readability be done using IF/ELSE statements: // This is possible but IMO not best practice:X ? doSomething() : doSomethingElse(); While long-winded, most of the time, this is the better solution: if (X) { doSomething();} else { doSomethingElse();} One notable benefit to the IF/ELSE structure is that you can add additional tasks under each condition with minimal hassle. Your last snippet is also possible but it looks somewhat long-winded and, again, might be better suited to a more conventional logical structure; like an IF/ELSE block. That said, a conditional operator can still be readable, e.g. (something && somethingElse > 2) ? doSomeLongFunctionName() : doSomeOtherLongFunctionName(); In the end, like many things, it's down to personal preference. Always remember that the code you're writing is not just for you; other developers might have to wade through it in the future; try and make it as readable as possible.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/869832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107826/']}
jdg_77927
stackexchange
llm_judgeable_groundtruth_similarity
30605837
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 been trying to find an alternative for getting the album names with the Photos API in iOS 8. With ALAssets, we can use: valueForProperty:ALAssetsGroupPropertyName however with the Photos API, I can't seem to find an alternative. There is: localizedTitle under PHAssetCollection but that isn't right either, it just gives me the city names. I'm looking for something that can return the actual names of the groups, including ones synced with iTunes. I'd appreciate any help to see how you do this in your apps. Apple is encouraging us to only use the Photos API for apps linked with 8.0, so I'd rather not use both ALAssetLibrary and Photos. Code: - (NSString *)nameForAlbumInCollection:(id)collection{ NSString *title = nil; if ([PHAsset class]) { title = [collection localizedTitle]; } else { title = [collection valueForProperty:ALAssetsGroupPropertyName]; } return title;}- (void)setup{ self.recentsCollectionDataSource = [[NSMutableOrderedSet alloc]init]; self.favoritesCollectionDataSource = [[NSMutableOrderedSet alloc]init]; self.albumsTableDataSource = [[NSMutableOrderedSet alloc]init]; NSMutableArray *segmentTitles = [[NSMutableArray alloc]init]; self.assetsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum | PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAny options:nil]; if (!self.parentController.canTakeOrChooseVideo) { fetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType = %i",PHAssetMediaTypeImage]; } for (PHAssetCollection *sub in self.assetsFetchResult) { PHFetchResult *assetsInCollection = [PHAsset fetchAssetsInAssetCollection:sub options:nil]; for (PHAsset *asset in assetsInCollection) { NSLog(@"%@",[self nameForAlbumInCollection:sub]); [self.recentsCollectionDataSource addObject:asset]; if (![segmentTitles containsObject:@"Recents"]) { [segmentTitles addObject:@"Recents"]; [segmentTitles addObject:@"Albums"]; } if (asset.isFavorite) { [self.favoritesCollectionDataSource addObject:asset]; if (![segmentTitles containsObject:@"Favorites"]) { [segmentTitles addObject:@"Favorites"]; } } } }} Now provide the response and nothing else.
This is how I made a list of the album names in a project of mine. You may have to deviate a bit, but this should work. NSArray *collectionsFetchResults;NSMutableArray *localizedTitles = [[NSMutableArray alloc] init];PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];PHFetchResult *syncedAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumSyncedAlbum options:nil];PHFetchResult *userCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];// Add each PHFetchResult to the arraycollectionsFetchResults = @[smartAlbums, userCollections, syncedAlbums];for (int i = 0; i < collectionsFetchResults.count; i ++) { PHFetchResult *fetchResult = collectionsFetchResults[i]; for (int x = 0; x < fetchResult.count; x ++) { PHCollection *collection = fetchResult[x]; localizedTitles[x] = collection.localizedTitle; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30605837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1533438/']}
jdg_77928
stackexchange
llm_judgeable_groundtruth_similarity
4438577
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 was on a math competition. Is there a triangle, which is not equilateral, whose sides form a geometric sequence and whose angles form an arithmetic sequence? If such a triangle exists, find its sides and angles. My attempt: Assume a triangle with sides $a$ , $ar$ and $ar^2$ and its angles $\theta-\phi$ , $\theta$ and $\theta+\phi$ . Now sum of triangles is always $180°$ .So $\theta = 60°$ . Then using the sine law, $\dfrac{\sin(\theta-\phi)}a=\dfrac{\sin\theta}{ar}=\dfrac{\sin(\theta+\phi)}{ar^2}$ Cancelling the a and plugging in the equation the value of $\theta$ , $\dfrac{\sin(60°-\phi)}1=\dfrac{\sin60°}{r}=\dfrac{\sin(60°+\phi)}{r^2}$ This is where I am stuck. Now provide the response and nothing else.
Following your work, we have $$r = \frac{\sin\frac{\pi}{3}}{\sin\left(\frac{\pi}{3} - \phi\right)} = \frac{\sin\left(\frac{\pi}{3} + \phi\right)}{\sin\frac{\pi}{3}}$$ The last two terms give $\sin\left(\frac{\pi}{3} - \phi\right)\sin\left(\frac{\pi}{3} + \phi\right) = \frac{3}{4}$ . We have $$\begin{align*} LHS &= \left(\frac{\sqrt{3}}{2}\cos\phi - \frac{1}{2}\sin\phi\right)\left(\frac{\sqrt{3}}{2}\cos\phi + \frac{1}{2}\sin\phi\right) \\ &= \frac{3}{4}\cos^2\phi - \frac{1}{4}\sin^2\phi \end{align*}$$ Setting equality, we have $$\cos^2\phi - \frac{1}{3}\sin^2\phi = 1$$ From this, it is clear that we need $\sin^2\phi = 0$ , so there is no non-degenerate triangle satisfying your requirements (assuming your sine law equations are correct :)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4438577', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/971974/']}
jdg_77929
stackexchange
llm_judgeable_groundtruth_similarity
5162
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: Currently I have the entire disk /dev/sda formatted as ext4, and installed Gentoo. (There is no MBR, no partition at all. ) But finally, I can't install GRUB on it, because it seems like GRUB needs to write to MBR. # grub-install /dev/sdaUnknown partition table signatureUnknown partition table signatureUnknown partition table signatureUnknown partition table signatureUnknown partition table signatureThe file /boot/grub/stage1 not read correctly. neither does grub work, # grubgrub> root (hd0) Filesystem type unknown, using whole diskgrub> setup (hd0) Error 17: Cannot mount selected partition Any way can I install GRUB into the /dev/sda without MBR? P.S. The /boot directory and grub.conf files: # tree /boot /boot|-- boot -> .|-- grub| |-- default| |-- device.map| |-- e2fs_stage1_5| |-- fat_stage1_5| |-- ffs_stage1_5| |-- grub.conf| |-- iso9660_stage1_5| |-- jfs_stage1_5| |-- menu.lst -> grub.conf| |-- minix_stage1_5| |-- reiserfs_stage1_5| |-- splash.xpm.gz| |-- stage1| |-- stage2| |-- stage2_eltorito| |-- ufs2_stage1_5| |-- vstafs_stage1_5| `-- xfs_stage1_5`-- kernel-2.6.36-gentoo-r5# cat /boot/grub/grub.confdefault 0timeout 30splashimage=(hd0)/boot/grub/splash.xpm.gztitle Gentoo Linux 2.6.36-r5root (hd0)kernel /boot/kernel-2.6.36-gentoo-r5 root=/dev/sdatitle Gentoo Linux 2.6.36-r5 Rescuekernel /boot/kernel-2.6.36-gentoo-r5 root=/dev/sda init=/bin/bb# cat /boot/grub/devices(fd0) /dev/fd0(hd0) /dev/sda Now provide the response and nothing else.
The BIOS reads the first sector (512 bytes) of the disk and branches into it. If your disk contains PC-style partitions, the first sector also contains the partition table. If your disk contains a single filesystem, the first sector contains whatever the filesystem decides to put there. In the case of ext[234] (and many other filesystems), the first sector¹ is reserved for the bootloader (and is initially zeroed out). You can install Grub on /dev/sda . That being said, there are occasional BIOSes that refuse to boot from a device that don't contain a partition table. (But there are also BIOSes that refuse to boot from some external devices if they do contain a partition table!) If you have one of these BIOSes, you'll have to create a partition table. Even if a partition table is not necessary, it's recommended. You only waste a few kilobytes, and gain readability under many non-Linux OSes and less surprise for any co-sysadmin. If you accidentally plug your disk into a machine running Windows, it might suggest you to reformat the disk if it doesn't see a partition table, whereas it'll just complain it can't read the data if it sees a partition table with a partition type it doesn't recognize. ¹ In fact, the first block, I think, where a block is 1kB, 2kB or 4kB depending on the options passed to mkfs .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/5162', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3267/']}
jdg_77930
stackexchange
llm_judgeable_groundtruth_similarity
109946
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to detect the edges of an image of a mountain and then fit that to a gaussian. I am unsure about how to only get the mountain edge, rather than every single edge in the image. How do I detect the outline of the mountain and then fit it with a gaussian? I think I need to Import Image Detect Edges Binarize Fit Gaussian However I am unable to detect only the edge I want. If I use EdgeDetect Then I get this image Now provide the response and nothing else.
A method not needing "magic numbers": i = Import@"http://i.stack.imgur.com/1Ui83.jpg";id = ImageDimensions@i; mask = {⌊#/2⌋, ⌊#/4⌋} &@ Reverse@id;p = ImageValuePositions[Image@WatershedComponents[i, mask], 0];model = a E^(-b (x - x0)^2) + c;fit = FindFit[p, model, {{a, Max[Last /@ p]}, b, c, {x0, First@id/2}}, x];j = Plot[model /. fit, {x, 0, First@id}, Axes -> False, PlotStyle -> Thick];Show[i, j, ImageSize -> 400]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/109946', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6529/']}
jdg_77931
stackexchange
llm_judgeable_groundtruth_similarity
21617269
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 several methods in an application I'm working on loaded with optional parameters, some of which are enums. Currently, in order to do that I'm writing methods with a similar type of signature: public void SomeMethod(string myFirstParam = "", string mySecondParam = "", MyEnum myThirdParam = (MyEnum )(-1)){ if (myThirdParam != (MyEnum ) (-1)) { //do something with it }} So my first question is, is there some pitfall to this approach I haven't realized, but in time will become painfully aware of, and secondly, is there a more proper - or at least elegant solution to it? I should say that we control the input to this method, it's used internally, so I'm not worried about someone casting in a value of -1 to gum up the works. Now provide the response and nothing else.
I would suggest using nullable enum in this situation, like this: public void SomeMethod(string myFirstParam = "", string mySecondParam = "", MyEnum? myThirdParam = null){ if (myThirdParam.HasValue) { var enumValue = myThirdParam.Value; //do something with it }} and you can use it like this: SomeMethod(myThirdParam: MyEnum.Something);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21617269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/396665/']}
jdg_77932
stackexchange
llm_judgeable_groundtruth_similarity
15151974
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 gone through the thread: binding two VerticalScrollBars one to another it has almost helped to achieve the goal but still there is something missing. It is that moving the scrollbars left-right or up-down gives expected behavior of scrolling in both of my scrollviewers but when we try to scroll using/clicking arrow buttons at the ends of these scrollbars in scrollviewers only one scrollviewer is scrolled which is not the expected behavior. So what else we need to add/edit to solve this? Now provide the response and nothing else.
One way to do this is using the ScrollChanged event to update the other ScrollViewer <ScrollViewer Name="sv1" Height="100" HorizontalScrollBarVisibility="Auto" ScrollChanged="ScrollChanged"> <Grid Height="1000" Width="1000" Background="Green" /></ScrollViewer><ScrollViewer Name="sv2" Height="100" HorizontalScrollBarVisibility="Auto" ScrollChanged="ScrollChanged"> <Grid Height="1000" Width="1000" Background="Blue" /></ScrollViewer>private void ScrollChanged(object sender, ScrollChangedEventArgs e) { if (sender == sv1) { sv2.ScrollToVerticalOffset(e.VerticalOffset); sv2.ScrollToHorizontalOffset(e.HorizontalOffset); } else { sv1.ScrollToVerticalOffset(e.VerticalOffset); sv1.ScrollToHorizontalOffset(e.HorizontalOffset); } }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15151974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1673411/']}
jdg_77933
stackexchange
llm_judgeable_groundtruth_similarity
7584113
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 use a regular expression to perform rounding on a number? The problem is that I've got a lot of numbers to more than 2 decimal places in a file and I need to move them to 2 decimal places. It's in source file so ideally I'd like to use Visual Studio's find and replace, but I'm not against the idea of writing a script to run on the file (treating it as plain text) if regex doesn't have the answer. Now provide the response and nothing else.
You can't do it with regexes alone, as Ryan pointed out, but you can use regexes to find decimals in your input and use a callback function on the replace operation. In Python: >>> import re>>> text = "1.234 and 99.999; .555 12.345">>> simpledec = re.compile(r"\d*\.\d+")>>> def mround(match):... return "{:.2f}".format(float(match.group()))...>>> re.sub(simpledec, mround, text)'1.23 and 100.00; 0.56 12.35' The regex to match decimals is very simplistic; it doesn't match exponential notation, for example, but it should give you an idea.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7584113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6713/']}
jdg_77934
stackexchange
llm_judgeable_groundtruth_similarity
4981087
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 out with learning Table Views. My applications uses a Tab Bar Controller and all the tabs are simple views. I want to add another tab, and in this tab I'm trying to implement a Table style navigation controller. From what i'm reading these views need a UINavigation Controller as the Root View Controller however my tab bar controller is already set a my Root View Controller, so i'm kinda confused. Can someone explain what I should be doing to implement something like this. Now provide the response and nothing else.
This is a good question and one that most developers new to Cocoa always struggle with. You need to think about the architecture of your App to see what will make most sense to your requirements, but in most cases you will want the TabBarController to be the main/root controller serving the other views, and then from there configure the tabItem views based on what data you need to display. For your particular case, when you are creating a new tab item, instead of serving a UIViewController to that tabItem view, you want to use a navigation controller. Then, under the navigation controller, you will be able to assign its root view controller, which should be an instance of UITableViewController (or a UIViewController with a UITableView instance if you need more than a UITableView in your view). So the hierarchy goes a bit like this 1 -- TabBarController 1.1 -----NavigationController 1.1.1 -------UITableViewController 1.1.1 -------Other views on your nav Controller stack 1.2 -----Any other views on your tabBarController And here's a good video tutorial that will help you with it: http://www.youtube.com/watch?v=LBnPfAtswgw Good luck,Rog
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4981087', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485352/']}
jdg_77935
stackexchange
llm_judgeable_groundtruth_similarity
19519557
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my sencha based application I want to make ext.list size depends on the device screen. Here the code which I have used. var tab= Ext.create('Ext.List', { width: 320,//Size wants to change depends on device display height: 290,//Size wants to change depends on device display id : 'itemList', disableSelection: true, selectedItemCls:'', itemTpl: ['<div style="margin:0px;" >'+ '<table style="margin:0px;padding:0px;height:40px;" width="100%" >'+ '<tr><td style="padding-left:2px;width:20%;"><span><img src="data:image/jpeg;base64,{itemImage}" height="42" width="42"/>'+ '</span></td><td><span><b><font size="3">{itemName}</font></b><br>{itemDesc}</span></td>'+ '<td style="padding-left:2px;width:20%;">'+ '<img src="resources/img/arrow.png" onclick="viewgiftdetails(\'{itemID}\')"/>'+ '</td></tr></table></div>'].join(), listeners : { itemtap: function (list, index, item, record, senchaEvent) { var data = record.getData(); var itemID = data.itemID; App.gvars.itidi=data.itemID; var itemPurchased = data.itemPurchased; var imgref=data.itemImage; viewgiftdetails(itemID); Ext.getCmp('homepnl').setActiveItem({ title: 'My item', items: [viewitemspnl] }, {type:'fade', direction:'left'}); } } }); What code needs to change depends on display? Now provide the response and nothing else.
Now we can use the visibility API . To deal with the different browser-specific syntaxes, I made this small code : var vis = (function(){ var stateKey, eventKey, keys = { hidden: "visibilitychange", webkitHidden: "webkitvisibilitychange", mozHidden: "mozvisibilitychange", msHidden: "msvisibilitychange" }; for (stateKey in keys) { if (stateKey in document) { eventKey = keys[stateKey]; break; } } return function(c) { if (c) document.addEventListener(eventKey, c); return !document[stateKey]; }})(); Usage : var visible = vis(); // gives current statevis(aFunction); // registers a handler for visibility changes Example : vis(function(){ document.title = vis() ? 'Visible' : 'Not visible';}); Demonstration page
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19519557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2636859/']}
jdg_77936
stackexchange
llm_judgeable_groundtruth_similarity
5047576
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The selected item in a WPF TreeView has a dark blue background with "sharp" corners. That looks a bit dated today: I would like to change the background to look like in Explorer of Windows 7 (with/without focus): What I tried so far does not remove the original dark blue background but paints a rounded border on top of it so that you see the dark blue color at the edges and at the left side - ugly. Interestingly, when my version does not have the focus, it looks pretty OK: I would like to refrain from redefining the control template as shown here or here . I want to set the minimum required properties to make the selected item look like in Explorer. Alternative: I would also be happy to have the focused selected item look like mine does now when it does not have the focus. When losing the focus, the color should change from blue to grey. Here is my code: <TreeView x:Name="TreeView" ItemsSource="{Binding TopLevelNodes}" VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling"> <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" /> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" /> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="BorderBrush" Value="#FF7DA2CE" /> <Setter Property="Background" Value="#FFCCE2FC" /> </Trigger> </Style.Triggers> </Style> </TreeView.ItemContainerStyle> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type viewmodels:ObjectBaseViewModel}" ItemsSource="{Binding Children}"> <Border Name="ItemBorder" CornerRadius="2" Background="{Binding Background, RelativeSource={RelativeSource AncestorType=TreeViewItem}}" BorderBrush="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType=TreeViewItem}}" BorderThickness="1"> <StackPanel Orientation="Horizontal" Margin="2"> <Image Name="icon" Source="/ExplorerTreeView/Images/folder.png"/> <TextBlock Text="{Binding Name}"/> </StackPanel> </Border> </HierarchicalDataTemplate> </TreeView.Resources></TreeView> Solution With the excellent answers of Sheridan and Meleak my TreeView now looks like this in code (a result I am very happy with and which is pretty near Explorer's style): <TreeView ... <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <!-- Style for the selected item --> <Setter Property="BorderThickness" Value="1"/> <Style.Triggers> <!-- Selected and has focus --> <Trigger Property="IsSelected" Value="True"> <Setter Property="BorderBrush" Value="#7DA2CE"/> </Trigger> <!-- Mouse over --> <Trigger Property="helpers:TreeView_IsMouseDirectlyOverItem.IsMouseDirectlyOverItem" Value="True"> <Setter Property="Background"> <Setter.Value> <LinearGradientBrush EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#FFFAFBFD" Offset="0"/> <GradientStop Color="#FFEBF3FD" Offset="1"/> </LinearGradientBrush> </Setter.Value> </Setter> <Setter Property="BorderBrush" Value="#B8D6FB"/> </Trigger> <!-- Selected but does not have the focus --> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsSelected" Value="True"/> <Condition Property="IsSelectionActive" Value="False"/> </MultiTrigger.Conditions> <Setter Property="BorderBrush" Value="#D9D9D9"/> </MultiTrigger> </Style.Triggers> <Style.Resources> <Style TargetType="Border"> <Setter Property="CornerRadius" Value="2"/> </Style> </Style.Resources> </Style> </TreeView.ItemContainerStyle> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type viewmodels:ObjectBaseViewModel}" ItemsSource="{Binding Children}"> <StackPanel Orientation="Horizontal" Margin="2,1,5,2"> <Grid Margin="0,0,3,0"> <Image Name="icon" Source="/ExplorerTreeView/Images/folder.png"/> </Grid> <TextBlock Text="{Binding Name}" /> </StackPanel> </HierarchicalDataTemplate> <!-- Brushes for the selected item --> <LinearGradientBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#FFDCEBFC" Offset="0"/> <GradientStop Color="#FFC1DBFC" Offset="1"/> </LinearGradientBrush> <LinearGradientBrush x:Key="{x:Static SystemColors.ControlBrushKey}" EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#FFF8F8F8" Offset="0"/> <GradientStop Color="#FFE5E5E5" Offset="1"/> </LinearGradientBrush> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" /> <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Black" /> </TreeView.Resources></TreeView> Now provide the response and nothing else.
Adding to @Sheridan's answer This isn't a 100% accurate but should get you pretty close (it's using the colors from GridView which is pretty close to Windows Explorer) <TreeView ...> <TreeView.Resources> <LinearGradientBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#FFD9F4FF" Offset="0"/> <GradientStop Color="#FF9BDDFB" Offset="1"/> </LinearGradientBrush> <LinearGradientBrush x:Key="{x:Static SystemColors.ControlBrushKey}" EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="#FFEEEDED" Offset="0"/> <GradientStop Color="#FFDDDDDD" Offset="1"/> </LinearGradientBrush> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" /> <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Black" /> </TreeView.Resources> <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="BorderThickness" Value="1.5"/> <Style.Triggers> <Trigger Property="IsSelected" Value="True"> <Setter Property="BorderBrush" Value="#adc6e5"/> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsSelected" Value="True"/> <Condition Property="IsSelectionActive" Value="False"/> </MultiTrigger.Conditions> <Setter Property="BorderBrush" Value="LightGray"/> </MultiTrigger> </Style.Triggers> <Style.Resources> <Style TargetType="Border"> <Setter Property="CornerRadius" Value="2"/> </Style> </Style.Resources> </Style> </TreeView.ItemContainerStyle></TreeView>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5047576', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234152/']}
jdg_77937
stackexchange
llm_judgeable_groundtruth_similarity
34867023
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 create a window with multiple buttons in which do not go away apon clicking them. I'm trying to make a simple Windowed Box with buttons that can open programs. I've been using WBox.exe for my gui, however it closes the window before the program launches when you press any button.HTML crossed my mind, but I don't know how to make buttons or even know if it can launch a program on click. Now provide the response and nothing else.
You may do that in a relatively simple way via a Batch-HTA hybrid file ; this is an example: <!-- :: Batch section@echo offsetlocalecho Select an option:for /F "delims=" %%a in ('mshta.exe "%~F0"') do set "HTAreply=%%a"echo End of HTA window, reply: "%HTAreply%"goto :EOF--><HTML><HEAD><HTA:APPLICATION SCROLL="no" SYSMENU="no" ><TITLE>HTA Buttons</TITLE><SCRIPT language="JavaScript">window.resizeTo(374,100);function closeHTA(reply){ var fso = new ActiveXObject("Scripting.FileSystemObject"); fso.GetStandardStream(1).WriteLine(reply); window.close();}</SCRIPT></HEAD><BODY> <button onclick="closeHTA(1);">First option</button> <button onclick="closeHTA(2);">Second option</button> <button onclick="closeHTA(3);">Third option</button></BODY></HTML> Save this code in a file with .BAT extension. Perhaps you would need to adjust the values in window.resizeTo(374,100); line in order to match the resolution of your screen. This example is simple enough so you may understand it even if you know nothing about .HTA files. For further details and links on this matter, see this post .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34867023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5786856/']}
jdg_77938
stackexchange
llm_judgeable_groundtruth_similarity
5298208
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: use warnings;my @array = (0, 1);my $scalar1 = $array[0];my $scalar2 = @array[0];if($scalar1 == $scalar2) { print "scalars are equal\n";} Here's the output when I run /usr/bin/perl5.10.1 test.pl : Scalar value @array[0] better written as $array[0] at test.pl line 4.scalars are equal I'm concerned about that warning. Now provide the response and nothing else.
You can look up all warning messages in perldoc perldiag , which explains the consequences: (W syntax) You've used an array slice (indicated by @) to select a single element of an array. Generally it's better to ask for a scalar value (indicated by $). The difference is that $foo[&bar] always behaves like a scalar, both when assigning to it and when evaluating its argument, while @foo[&bar] behaves like a list when you assign to it, and provides a list context to its subscript, which can do weird things if you're expecting only one subscript. On the other hand, if you were actually hoping to treat the array element as a list, you need to look into how references work, because Perl will not magically convert between scalars and lists for you. See perlref. Similarly, you can use diagnostics; to get this verbose explanation of the warning message. A third way is to use the splain utility.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5298208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/321731/']}
jdg_77939
stackexchange
llm_judgeable_groundtruth_similarity
10251094
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 remove "www", "http://", "https://" from strings using Ruby? I tried this but it didn't work: s.gsub('/(?:http?:\/\/)?(?:www\.)?(.*)\/?$/i', '') Here what I'm doing in Rails: <%= auto_link(job.description) do |url| url.truncate(25).gsub('http://', '') end %> Url are truncated, but my goal is to remove the beginning of the links, such as "www" or "http://" so the link would look like "google.com/somepage/d...", not like "http://google.com/some..." Now provide the response and nothing else.
s = s.sub(/^https?\:\/\//, '').sub(/^www./,'') If you don't want to use s = , you should use sub! s instead of all sub s. The problems with your code are: Question mark always follows AFTER an optional character Always replace one pattern in a sub. You can "chain up" multiple operations. Use sub instead of gsub and ^ in the beginning of Regexp so it only replaces the http:// in the beginning but leaves the ones in the middle.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10251094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/452466/']}
jdg_77940