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 | 31311125 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hi i am search the answer for avoid new facebooksdk redirect to safari.how to open facebook login view inside the app.if it redirect to safari may reject in app store? help me.. thanks in advance
Now provide the response and nothing else.
| yesterday I submit my app to store using FBSDKLoginManager using three kinds of Login with Facebook , actually Facebook follow the first three conditions automatically Type -1 if the user already installed the Facebook native app the details will be retrieved from the app. Type -2 if the user does't have the Facebook app, but he is logged in at the device's Settings, the user details will be taken from those. Type -3 if none of the condition above is satisfied the user will be automatically redirected to Safari . Type -4 if you none of the above three conditions is relevant for you please continue below code. apple does not reject your app Objective-C FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];login.loginBehavior=FBSDKLoginBehaviorWeb; // it open inside the app using popup menu Swift var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()fbLoginManager.loginBehavior = FBSDKLoginBehavior.Native FBSDKLoginBehavior Types typedef NS_ENUM(NSUInteger, FBSDKLoginBehavior){ /*!@abstract Attempts log in through the native Facebook app. If the Facebook app isnot installed on the device, falls back to \c FBSDKLoginBehaviorBrowser. This is thedefault behavior.*/ FBSDKLoginBehaviorNative = 0,/*!@abstract Attempts log in through the Safari browser */FBSDKLoginBehaviorBrowser, /*! @abstract Attempts log in through the Facebook account currently signed in through Settings. If no Facebook account is signed in, falls back to \c FBSDKLoginBehaviorNative. */ FBSDKLoginBehaviorSystemAccount, /*! @abstract Attemps log in through a modal \c UIWebView pop up @note This behavior is only available to certain types of apps. Please check the Facebook Platform Policy to verify your app meets the restrictions. */ FBSDKLoginBehaviorWeb, }; the new concept Facebook SDK for iOSv4.x (v4.6.0 - September 10, 2015) In addition, the SDK dialogs such as Login, Like, Share Dialogs automatically determine the best UI based on the device, including SFSafariViewController instead of Safari. Follow the our Preparing for iOS 9 guide. you can get like | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31311125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4772431/']} | jdg_80141 |
stackexchange | llm_judgeable_groundtruth_similarity | 16707747 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need append the following characters ‡, †, * as superscript to NSString in iOS . Need your help. I use the following http://en.wikipedia.org/wiki/General_Punctuation_(Unicode_block) link but they are appending to NSString , But i want them as superscript
Now provide the response and nothing else.
| Try to use this one. And you need to #import <CoreText/CTStringAttributes.h> . This code works only in iOS6 or later version. UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 200, 40)];NSString *infoString=@"X2 and H20 A‡ B† C*";NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:infoString];[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(1, 1)];[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@-1 range:NSMakeRange(8, 1)];[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(12, 1)];[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(15, 1)];[attString addAttribute:(NSString *)kCTSuperscriptAttributeName value:@1 range:NSMakeRange(18, 1)];lbl.attributedText = attString;[self.view addSubview:lbl]; Output I hope this will help you | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16707747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1142743/']} | jdg_80142 |
stackexchange | llm_judgeable_groundtruth_similarity | 16129 |
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:
Definition of lattice require that any two elements of lattice should have LUB and GLB, while complete lattice extends it to, every subset should have LUB and GLB. But by induction , it is possible to show that if any two elements have LUB and GLB then every subset should have LUB and GLB. I read somewhere that the difference is because of infinite set, in that case it is possible that set along with some partial order is lattice but not complete lattice, can someone please elaborate it with one example? regards
Now provide the response and nothing else.
| Regular induction ("holds for $1$" and "if it holds for $k$ then it holds for $k+1$") only gives you that the result holds for every natural number $n$; it does not let you go beyond the finite numbers. For example, you can prove by induction that there are natural numbers that require $n$ digits to write down in base $10$ for every $n$, but this does not mean that there are natural numbers that require an infinite number of digits to write down in base $10$. "For all $n$" is not the same as "for all sizes, finite or infinite". (There is a kind of induction that would allow you to prove something for all sizes, not just finite. This is called transfinite induction . You prove the result holds for $1$, and that whenever it holds for all $m\lt k$, then it also holds for $k$ (or, you prove it holds for $1$, that if it holds for an ordinal/cardinal $\alpha$ then it holds for $\alpha+1$, and that if it holds for all ordinals/cardinals strictly smaller than $\gamma$, then it holds for $\gamma$). However you would be unable to do such a proof with lattices, because it is false). So, if you have a lattice, then any nonempty finite subset has a least upper bound and a greatest lower bound, by induction. Even if you have a $0$ and a $1$ (a minimum and a maximum element) so that every set has an upper and a lower bound, you still don't get that every set has a least upper bound. For example, take $P = \mathbb{Q}\cup\{-\infty,\infty\}$, with the usual order among rationals, $-\infty\leq q\leq \infty$ for all $q\in\mathbb{Q}$. This is a lattice, with operations $a\wedge b = \min\{a,b\}$ and $a\vee b = \max\{a,b\}$ (since it is a totally ordered set). Every finite subset has a least upper bound (the maximum) and a greatest lower bound (the minimum). But it is precisely the absence of suprema and infima for general sets that stops it from being a complete lattice: the set $\{q\in\mathbb{Q}\mid q^2\lt 2\}$ has no least upper bound and no greatest lower bound. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/16129', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5318/']} | jdg_80143 |
stackexchange | llm_judgeable_groundtruth_similarity | 14332729 |
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 displaying Menu and Sub Menu in table format like Menu1Menu2 SubMenu1 SubMenu2 SubMenu3Menu3 SubMenu4 SubMenu5 SubMenu6Menu4 So far, I was able to come up with below code but its not showing any record. Views.py def getCompleteMenuList(): return Menu.objects.getMenuListing(id)#mainMenuObj=Menu.objects.getMenuListing(id)return render_to_response('manageMenu.html', {'title': menu_title,'name':name,'mainMenu':getCompleteMenuList,},context_instance=RequestContext(request)) Models.py def getMenuListing(self, id): mainMenus = self.filter(parent_menu=0,business=id).order_by('order') result = [] menus = [] for menu in mainMenus: menus.append(menu) submenu = self.filter(parent_menu=menu,business=id).order_by('order') if submenu.exists(): result.append(submenu) return dict(zip(menus, result)) template.html {% with mainMenu.items as pop_menus %} {% for key, value in pop_menus %} display main menu rows {% for data in value %} display sub menu rows {% endfor %} {% endfor %} {% endwith %} Current Situation I have 5 rows in table with 4 as parent_menu =0 and 1 as parent_menu = 1 (which exists). When I try to print mainMenus its show 4 menu object. < Menu: Menu object >, < Menu: Menu object >, < Menu: Menu object >, < Menu: Menu object > But when I print menu inside for loop it only print 1 Menu objectMenu object Can you please advise what I am doing wrong or is there any other way to achieve same thing?
Now provide the response and nothing else.
| I'm still getting my feet wet with Node.js, but I have a few ideas. first, I believe you need to use execFile instead of spawn ; execFile is for when you have the path to a script, whereas spawn is for executing a well-known command that Node.js can resolve against your system path. 1. Provide a callback to process the buffered output: var child = require('child_process').execFile('path/to/script', [ 'arg1', 'arg2', 'arg3', ], function(err, stdout, stderr) { // Node.js will invoke this callback when process terminates. console.log(stdout); }); 2. Add a listener to the child process' stdout stream ( 9thport.net ) var child = require('child_process').execFile('path/to/script', [ 'arg1', 'arg2', 'arg3' ]); // use event hooks to provide a callback to execute when data are available: child.stdout.on('data', function(data) { console.log(data.toString()); }); Further, there appear to be options whereby you can detach the spawned process from Node's controlling terminal, which would allow it to run asynchronously. I haven't tested this yet, but there are examples in the API docs that go something like this: child = require('child_process').execFile('path/to/script', [ 'arg1', 'arg2', 'arg3', ], { // detachment and ignored stdin are the key here: detached: true, stdio: [ 'ignore', 1, 2 ]}); // and unref() somehow disentangles the child's event loop from the parent's: child.unref(); child.stdout.on('data', function(data) { console.log(data.toString()); }); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14332729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1935504/']} | jdg_80144 |
stackexchange | llm_judgeable_groundtruth_similarity | 1124548 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I pass a value from one screen to its previous screen? Consider this case: I have two activities. The first screen has one TextView and a button and the second activity has one EditText and a button. If I click the first button then it has to move to second activity and here user has to type something in the text box. If he presses the button from the second screen then the values from the text box should move to the first activity and that should be displayed in the first activity TextView .
Now provide the response and nothing else.
| To capture actions performed on one Activity within another requires three steps. Launch the secondary Activity (your 'Edit Text' Activity) as a subactivity by using startActivityForResult from your main Activity. Intent i = new Intent(this,TextEntryActivity.class); startActivityForResult(i, STATIC_INTEGER_VALUE); Within the subactivity, rather than just closing the Activity when a user clicks the button, you need to create a new Intent and include the entered text value in its extras bundle. To pass it back to the parent call setResult before calling finish to close the secondary Activity. Intent resultIntent = new Intent();resultIntent.putExtra(PUBLIC_STATIC_STRING_IDENTIFIER, enteredTextValue);setResult(Activity.RESULT_OK, resultIntent);finish(); The final step is in the calling Activity: Override onActivityResult to listen for callbacks from the text entry Activity. Get the extra from the returned Intent to get the text value you should be displaying. @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case (STATIC_INTEGER_VALUE) : { if (resultCode == Activity.RESULT_OK) { String newText = data.getStringExtra(PUBLIC_STATIC_STRING_IDENTIFIER); // TODO Update your TextView. } break; } } } | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1124548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132724/']} | jdg_80145 |
stackexchange | llm_judgeable_groundtruth_similarity | 2184098 |
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:
Does $$\log_{a^2}x=\log_a 2x$$ If it does, then how would you prove it? If it doesn't, then how would I simplify $\log_{a^2} x$ so that it is in the form of $\log_a n$ where $n$ is some polynomial?
Now provide the response and nothing else.
| We have$$\log{_{a^2}}{x}=\frac{\log x}{\log (a^2)}=\frac{\log x}{2\log a}=\frac12\log{_{a}}{x}=\log{_{a}}{(x^{1/2})}\ne \log{_{a}}(2x)$$ in general. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2184098', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/384022/']} | jdg_80146 |
stackexchange | llm_judgeable_groundtruth_similarity | 216925 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using Debian GNU/Linux 7.8 (wheezy). While running my MATLAB program today, I got this message in terminal. Message from syslogd@sas21 at Jul 18 16:40:49 ... kernel:[1747708.091929] Uhhuh. NMI received for unknown reason 20 on CPU 4.Message from syslogd@sas21 at Jul 18 16:40:49 ... kernel:[1747708.091932] Do you have a strange power saving mode enabled?Message from syslogd@sas21 at Jul 18 16:40:49 ... kernel:[1747708.091932] Dazed and confused, but trying to continue I also remember hearing some beep sound in between. What does this mean? And what should I do further?
Now provide the response and nothing else.
| The problem seems to be that the End of Interrupt isn't communicated properly. For libvirt, make sure eoi is enabled: <domain> … <features> <apic eoi='on'/> … On the command line for KVM that translates to -cpu …,+kvm_pv_eoi This seems to work for us with -M q35 , host cpu passthrough and default config otherwise (RTC interrupts queued, PIT interrupts dropped, HPET unavailable). | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/216925', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/102841/']} | jdg_80147 |
stackexchange | llm_judgeable_groundtruth_similarity | 3462141 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
<% if(Eval("SaveDate") != DBNull.Value){ %> do magic <%} %> gives me error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. I could write : <%# Eval("SaveDate") != DBNull.Value ? do magicBut I need to do lots of html magic in if statement. I know I should add # in order to use Eval, but not sure about correct syntax.
Now provide the response and nothing else.
| One solution is to wrap the content in a runat="server" tag with a Visible value, e.g., <div runat="server" Visible='<%# Eval("SaveDate") != DBNull.Value %>'> do magic</div> div can be any HTML tag, but <asp:Panel> and <asp:PlaceHolder> could also be used. Note that "do magic" is still databound, so it's not a perfect solution if it contains expensive code or code that could generate an error if Eval("SaveDate") == DBNull.Value . Note that Visible="false" will omit the tag and all its contents from the generated HTML, this means that it is very different from style="display:none" or style="visible:hidden" , so don't worry about that. But, if your "do magic" is reasonably complex, another rather simple solution (a bit of a hack) is: use a Repeater (or FormView) with its DataSource set to an array of one item (visible) or no items (hidden): <asp:Repeater runat="server" DataSource='<%# ElementIfTrue(Eval("SaveDate") != DBNull.Value) %>' <ItemTemplate> do magic </ItemTemplate></asp:Repeater>protected IEnumerable ElementIfTrue(bool condition) { if (condition) return new object[] { Page.GetDataItem() }; else return new object[0];} The actual contents of the datasource array is either empty (hidden) or the element you were already binding to. This makes sure you can still call <%# Eval(...) %> inside the ItemTemplate. With this approach, your "do magic" is a template which will only be executed if DataSource has one or more items. Which is taken care of by ElementIfTrue . It's a bit of a mind bender, but it can save you every once in a while. As a side note: packing your "do magic" in a user control can also keep the complexity down. You don't really need to change a thing in your HTML/ASP.NET tag mix ( <%# Eval("...") %> still works even inside a user control). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3462141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/266250/']} | jdg_80148 |
stackexchange | llm_judgeable_groundtruth_similarity | 36903 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
According to The Hill : "If you force Muslims to register, we will all register as Muslims,” Steinem said during a speech at the Women’s March on Washington, drawing raucous cheers. Trump during his presidential campaign called for a temporary ban on Muslims coming into the U.S. and said he would "absolutely" require Muslims in the U.S. to register in a database. This is also backed up by a tweet from Madeleine Albright where she says: I was raised Catholic, became Episcopalian & found out later my family was Jewish. I stand ready to register as Muslim in #solidarity. Is this claim true?
Now provide the response and nothing else.
| Trump didn't propose a Muslim registry, it was proposed by a reporter during an interview , while Trump was talking about the wall. Trump did call for a database for Syrian refugees coming to the US. Trump's answers on the issue have been confusing, as it seems that he was always talking about the Syrian refugees registry. Trump never accepted the all Muslim registry, nor did he unequivocally deny it. Politifact has an article that summarizes the issue and presents it step by step as it unfolded. A full answer would be a copy-paste of the entire article; to avoid that, I've put forth just a few excerpts here, but I highly recommend reading the article fully for a full view of the issue: But Trump has said he didn’t propose such an idea -- a reporter did, and Trump just didn’t understand the question. It all started on Thursday, Nov. 19, when a Yahoo News reporter asked Trump about his position on increased surveillance of American Muslims. "France declared this state of emergency where they closed the borders and they established some degree of warrantless searches. I know how you feel about the borders, but do you think there is some kind of state of emergency here, and do we need warrantless searches of Muslims?" the reporter asked. "We’re going to have to do certain things that were frankly unthinkable a year ago," Trump said. The Yahoo reporter then asked Trump, "Do you think we might need to register Muslims in some type of database, or note their religion on their ID?" Trump responded, "We’re going to have to look at a lot of things very closely. We’re going to have to look at the mosques. We’re going to have to look very, very carefully." Here, Trump didn’t reject the idea of a Muslim registry, but he also didn’t give an affirmative "yes" that he wanted to create such a database. The next day, an MSNBC reporter asked Trump, "Should there be a database or system that tracks Muslims in this country?" "There should be a lot of systems," Trump responded. "Beyond databases. I mean, we should have a lot of systems." Trump then digressed to talk about a wall along the southern border, before the reporter interjected, "But that’s something your White House would like to implement." "I would certainly implement that. Absolutely," Trump said. Here, we’re not clear if Trump is talking about implementing a wall or implementing a database. [...] While many headlines came out after this exchange saying Trump would "absolutely" require Muslims to register in a database, it’s not entirely clear that’s what he said. Trump was talking about building a wall along the border when the reporter asked if he would implement an unspecified policy -- "that" -- as president. Through the end of the conversation, it’s possible Trump thought the exchange was about illegal immigration. Later that day, Trump wrote on Twitter , "I didn't suggest a database -- a reporter did. We must defeat Islamic terrorism & have surveillance, including a watch list, to protect America." After Trump’s tweet, Fox News asked him about his position on a Muslim registry. "Let's hear it directly from you," said host Kimberly Guilfoyle. "Would President Donald Trump support a full Muslim database?" "Basically the suggestion was made and (it’s) certainly something we should start thinking about," Trump said, repeating that the reporter presented the idea. "But what I want is a watch list. I want surveillance programs. Obviously, there are a lot of problems. … But, certainly, I would want to have a database for the refugees, for the Syrian refugees that are coming in because nobody knows where they're coming from." Guilfoyle followed up: "So to be clear, you are not saying anything with respect to a religious database. You are talking about the Syrian refugees in light of the national security development affecting this country as we speak here tonight." Trump said he didn’t hear the MSNBC reporter’s question clearly, "but even if I did, I mean, I want databases for the Syrian refugees that Obama is going to let in if they come in." On ABC News’ This Week, host George Stephanopoulos asked Trump, "You did stir up a controversy with those comments over the database. Let's try to clear that up. Are you unequivocally now ruling out a database on all Muslims?" "No, not at all," Trump responded. "I want a database for the refugees that -- if they come into the country. We have no idea who these people are. When the Syrian refugees are going to start pouring into this country, we don't know if they're ISIS, we don't know if it's a Trojan horse. And I definitely want a database and other checks and balances. We want to go with watchlists. We want to go with databases. And we have no choice." Trump’s exchange with Stephanopoulos seems to be the clearest explanation of his position. No, he would not rule out a database on all Muslims. But for now, he wants a database for refugees. | {} | {'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/36903', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/23144/']} | jdg_80149 |
stackexchange | llm_judgeable_groundtruth_similarity | 19952200 |
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 this following bit of code in C: double var;scanf("%lf", &var);printf("%lf", var);printf("%f", var); It reads from stdin variable 'var' and then prints twice in stdout 'var'.I understand that's how you read a double variable from stdin, but my questions are: Why can you print a double with %lf? Why can you print a double with %f? Which one is better and correct to use?
Now provide the response and nothing else.
| For variable argument functions like printf and scanf , the arguments are promoted, for example, any smaller integer types are promoted to int , float is promoted to double . scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double* . printf will never see a float argument, float is always promoted to double . The format specifier is %f . But C99 also says %lf is the same as %f in printf : C99 §7.19.6.1 The fprintf function l (ell) Specifies that a following d , i , o , u , x , or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a , A , e , E , f , F , g , or G conversion specifier. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19952200', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1769519/']} | jdg_80150 |
stackexchange | llm_judgeable_groundtruth_similarity | 1531977 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The partial integration rule says: $\int f'g=fg-\int fg'$ . If I use the rule for $f'(x)=2x,g(x)=\frac{1}{x^2}$, I get that: \begin{align}\int\frac{1}{x^2}2x\,dx& =\frac{1}{x^2}x^2-\int\frac{-2}{x^3}x^2\,dx,\\\int\frac{2}{x}\,dx& =1+\int\frac{2}{x}\,dx\end{align}and from this equation I get that $0=1$ Where did I make a mistake?
Now provide the response and nothing else.
| The mistake is thinking that antiderivatives are unique. The fact that $(x^2 + 1)' = (x^2 + 0)'$ does not imply $1 = 0$. In the case of the integration by parts formula, you can avoid the nonuniqueness issue if you use definite integrals. You will have $$\int_a^b \frac{1}{x^2} 2x \, dx = \left.1 \right|_a^b - \int_a^b \frac{-2}{x^3}x^2 \, dx$$where $1|_a^b = 1 - 1 = 0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1531977', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/188749/']} | jdg_80151 |
stackexchange | llm_judgeable_groundtruth_similarity | 29700557 |
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 best way to add/delete rows to a table when a button is clicked? I need rows created from ChildClass properties (child class is a list within the main class/model). Currently have a View (model is MyMain) which references a Partial View using RenderPartial. The partial view displays the properties of the model, a class called MyChild which is an object list within MyMain. I want to have add and delete buttons to dynamically add the rows which are held within the partial view. So adding MyChild repeatedly for more rows on the list.Is this possible? Or should I not be using partial views for this? Updated Code Below are the current classes and views I'm working with, I've been trying to implement the BeginCollectionItem helper but I'm getting null ref where I'm trying to load the partial view despite the if statement saying to create a new instance of the child class if doesn't exist - why is this being ignored? Main View @using (Html.BeginForm()){ <table> <tr> <th>MyMain First</th> <th>MyChild First</th> </tr> <tr> <td> @Html.EditorFor(m => m.First) </td> <td> @if (Model.child != null) { for (int i = 0; i < Model.child.Count; i++) { Html.RenderPartial("MyChildView"); } } else { Html.RenderPartial("MyChildView", new MvcTest.Models.MyChild()); } </td> </tr> @Html.ActionLink("Add another", "Add", null, new { id = "addItem" }) </table>} Partial View @model MvcTest.Models.MyChild@using (Html.BeginCollectionItem("myChildren")){ Html.EditorFor(m => m.Second);} Models public class MyMain{ [Key] public int Id { get; set; } public string First { get; set; } public List<MyChild> child { get; set; }}public class MyChild{ [Key] public int Id { get; set; } public string Second { get; set; }} Controller public class MyMainsController : Controller{ // GET: MyMains public ActionResult MyMainView() { return View(); } [HttpPost] public ActionResult MyMainView(IEnumerable<MyChild> myChildren) { return View("MyMainView", myChildren); } public ViewResult Add() { return View("MyChildView", new MyChild()); }}
Now provide the response and nothing else.
| Updated Answer - The original code is NOT true to 'dynamic', however it allows for everything I needed to do within the question parameters. Initially, I couldn't get Stephen's BCI suggestion in the question comments working, since then I have and it's brilliant. The code below in the updated section will work if you copy + paste, but you will need to either manually download BCI from GIT or use PM> Install-Package BeginCollectionItem with Package Manager Console in Visual Studio. I had some issue with various points using BCI due to the complexity and not having done MVC before - here is more information on dealing with accessing class.property(type class).property(type class).property . Original answer - I've gone with a more clear example below than in my question which quickly got too confusing. Using two partial views, one for the list of employees and another for the creation of a new employee all contained within the viewmodel of companyemployee which contains an object of company and a list of employee objects. This way multiple employees can be added, edited or deleted from the list. Hopefully this answer will help anyone looking for something similar, this should provide enough code to get it working and at the very least push you in the right direction. I've left out my context and initialiser classes as they're only true to code first, if needed I can add them. Thanks to all who helped. Models - CompanyEmployee being the view model public class Company{ [Key] public int id { get; set; } [Required] public string name { get; set; }}public class Employee{ [Key] public int id { get; set; } [Required] public string name { get; set; } [Required] public string jobtitle { get; set; } [Required] public string number { get; set; } [Required] public string address { get; set; }}public class CompanyEmployee{ public Company company { get; set; } public List<Employee> employees { get; set; }} Index @model MMV.Models.CompanyEmployee@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml";}<h2>Index</h2><fieldset> <legend>Company</legend> <table class="table"> <tr> <th>@Html.LabelFor(m => m.company.name)</th> </tr> <tr> <td>@Html.EditorFor(m => m.company.name)</td> </tr> </table></fieldset><fieldset> <legend>Employees</legend> @{Html.RenderPartial("_employeeList", Model.employees);}</fieldset><fieldset> @{Html.RenderPartial("_employee", new MMV.Models.Employee());}</fieldset><div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Submit" class="btn btn-default" /> </div></div> PartialView of List of Employees @model IEnumerable<MMV.Models.Employee>@using (Html.BeginForm("Employees")){ <table class="table"> <tr> <th> Name </th> <th> Job Title </th> <th> Number </th> <th> Address </th> <th></th> </tr> @foreach (var emp in Model) { <tr> <td> @Html.DisplayFor(modelItem => emp.name) </td> <td> @Html.DisplayFor(modelItem => emp.jobtitle) </td> <td> @Html.DisplayFor(modelItem => emp.number) </td> <td> @Html.DisplayFor(modelItem => emp.address) </td> <td> <input type="submit" formaction="/Employees/Edit/@emp.id" value="Edit"/> <input type="submit"formaction="/Employees/Delete/@emp.id" value="Remove"/> </td> </tr> } </table>} Partial View Create Employee @model MMV.Models.Employee@using (Html.BeginForm("Create","Employees")){ <table class="table"> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <tr> <td> @Html.EditorFor(model => model.name) @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" }) </td> <td> @Html.EditorFor(model => model.jobtitle) @Html.ValidationMessageFor(model => model.jobtitle) </td> <td> @Html.EditorFor(model => model.number) @Html.ValidationMessageFor(model => model.number, "", new { @class = "text-danger" }) </td> <td> @Html.EditorFor(model => model.address) @Html.ValidationMessageFor(model => model.address, "", new { @class = "text-danger" }) </td> </tr> </table> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div>} Controller - I used multiple but you can put them all in one public class CompanyEmployeeController : Controller{ private MyContext db = new MyContext(); // GET: CompanyEmployee public ActionResult Index() { var newCompanyEmployee = new CompanyEmployee(); newCompanyEmployee.employees = db.EmployeeContext.ToList(); return View(newCompanyEmployee); } [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { Employee employee = db.EmployeeContext.Find(id); db.EmployeeContext.Remove(employee); db.SaveChanges(); return RedirectToAction("Index", "CompanyEmployee"); } [HttpPost] public ActionResult Create([Bind(Include = "id,name,jobtitle,number,address")] Employee employee) { if (ModelState.IsValid) { db.EmployeeContext.Add(employee); db.SaveChanges(); return RedirectToAction("Index", "CompanyEmployee"); } return View(employee); }} Updated Code - using BeginCollectionItem - dynamic add/delete Student Partial @model UsefulCode.Models.Person<div class="editorRow"> @using (Html.BeginCollectionItem("students")) { <div class="ui-grid-c ui-responsive"> <div class="ui-block-a"> <span> @Html.TextBoxFor(m => m.firstName) </span> </div> <div class="ui-block-b"> <span> @Html.TextBoxFor(m => m.lastName) </span> </div> <div class="ui-block-c"> <span> <span class="dltBtn"> <a href="#" class="deleteRow">X</a> </span> </span> </div> </div> }</div> Teacher Partial @model UsefulCode.Models.Person<div class="editorRow"> @using (Html.BeginCollectionItem("teachers")) { <div class="ui-grid-c ui-responsive"> <div class="ui-block-a"> <span> @Html.TextBoxFor(m => m.firstName) </span> </div> <div class="ui-block-b"> <span> @Html.TextBoxFor(m => m.lastName) </span> </div> <div class="ui-block-c"> <span> <span class="dltBtn"> <a href="#" class="deleteRow">X</a> </span> </span> </div> </div> }</div> Register Controller public ActionResult Index(){ var register = new Register { students = new List<Person> { new Person { firstName = "", lastName = "" } }, teachers = new List<Person> { new Person { lastName = "", firstName = "" } } }; return View(register);} Register and Person Model public class Register{ public int id { get; set; } public List<Person> teachers { get; set; } public List<Person> students { get; set; }}public class Person{ public int id { get; set; } public string firstName { get; set; } public string lastName { get; set; }} Index @{ Layout = "~/Views/Shared/_Layout.cshtml";}@model UsefulCode.Models.Register<div id="studentList">@using (Html.BeginForm()){ <div id="editorRowsStudents"> @foreach (var item in Model.students) { @Html.Partial("StudentView", item) } </div> @Html.ActionLink("Add", "StudentManager", null, new { id = "addItemStudents", @class = "button" });}</div><div id="teacherList">@using (Html.BeginForm()){ <div id="editorRowsTeachers"> @foreach (var item in Model.teachers) { @Html.Partial("TeacherView", item) } </div> @Html.ActionLink("Add", "TeacherManager", null, new { id = "addItemTeachers", @class = "button" });}</div>@section scripts { <script type="text/javascript"> $(function () { $('#addItemStudents').on('click', function () { $.ajax({ url: '@Url.Action("StudentManager")', cache: false, success: function (html) { $("#editorRowsStudents").append(html); } }); return false; }); $('#editorRowsStudents').on('click', '.deleteRow', function () { $(this).closest('.editorRow').remove(); }); $('#addItemTeachers').on('click', function () { $.ajax({ url: '@Url.Action("TeacherManager")', cache: false, success: function (html) { $("#editorRowsTeachers").append(html); } }); return false; }); $('#editorRowsTeachers').on('click', '.deleteRow', function () { $(this).closest('.editorRow').remove(); }); }); </script>} StudentManager Action: public PartialViewResult StudentManager(){ return PartialView(new Person());} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29700557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/991570/']} | jdg_80152 |
stackexchange | llm_judgeable_groundtruth_similarity | 12438567 |
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 wondering why the Exception in the following bytecode (used to throw an Exception) is duplicated. NEW java/lang/IllegalArgumentExceptionDUPINVOKESPECIAL java/lang/IllegalArgumentException <init> ()VATHROW
Now provide the response and nothing else.
| I'll analyze this line by line where [] = new stack after that op is used: NEW puts a new IllegalArgumentException onto the stack [SomeIllegalArgumentException] DUP duplicates it [SomeIllegalArgumentException, SomeIllegalArgumentException] INVOKESPECIAL pops off the top one and initializes it by calling it's <init> method [SomeIllegalArgumentException] (The init method will not return the object to put back onto the stack, so the object must first be duplicated so as to keep it on the stack) ATHROW Throws the other (a duplicate off the one we initialized) [] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12438567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/603732/']} | jdg_80153 |
stackexchange | llm_judgeable_groundtruth_similarity | 53472993 |
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 set up bazel to build a number of CLI tools that perform various database maintenance tasks. Each one is a py_binary or cc_binary target that is called from the command line with the path to some data file: it processes that file and stores the results in a database. Now, I need to create a dependent package that contains data files and shell scripts that call these CLI tools to perform application-specific database operations. However, there doesn't seem to be a way to depend on the existing py_binary or cc_binary targets from a new package that only contains sh_binary targets and data files. Trying to do so results in an error like: ERROR: /workspace/shbin/BUILD.bazel:5:12: in deps attribute of sh_binary rule //shbin:run: py_binary rule '//pybin:counter' is misplaced here (expected sh_library) Is there a way to call/depend on an existing bazel binary target from a shell script using sh_binary ? I have implemented a full example here: https://github.com/psigen/bazel-mixed-binaries Notes: I cannot use py_library and cc_library instead of py_binary and cc_binary . This is because (a) I need to call mixes of the two languages to process my data files and (b) these tools are from an upstream repository where they are already designed as CLI tools. I also cannot put all the data files into the CLI tool packages -- there are multiple application-specific packages and they cannot be mixed.
Now provide the response and nothing else.
| You can either create a genrule to run these tools as part of the build, or create a sh_binary that depends on the tools via the data attribute and runs them them. The genrule approach This is the easier way and lets you run the tools as part of the build. genrule( name = "foo", tools = [ "//tool_a:py", "//tool_b:cc", ], srcs = [ "//source:file1", ":file2", ], outs = [ "output_file1", "output_file2", ], cmd = "$(location //tool_a:py) --input=$(location //source:file1) --output=$(location output_file1) && $(location //tool_b:cc) < $(location :file2) > $(location output_file2)",) The sh_binary approach This is more complicated, but lets you run the sh_binary either as part of the build (if it is in a genrule.tools , similar to the previous approach) or after the build (from under bazel-bin ). In the sh_binary you have to data-depend on the tools: sh_binary( name = "foo", srcs = ["my_shbin.sh"], data = [ "//tool_a:py", "//tool_b:cc", ],) Then, in the sh_binary you have to use the so-called "Bash runfiles library" built into Bazel to look up the runtime-path of the binaries. This library's documentation is in its source file . The idea is: the sh_binary has to depend on a specific target you have to copy-paste some boilerplate code to the top of the sh_binary (reason is described here ) then you can use the rlocation function to look up the runtime-path of the binaries For example your my_shbin.sh may look like this: #!/bin/bash# --- begin runfiles.bash initialization ---...# --- end runfiles.bash initialization ---path=$(rlocation "__main__/tool_a/py")if [[ ! -f "${path:-}" ]]; then echo >&2 "ERROR: could not look up the Python tool path" exit 1fi$path --input=$1 --output=$2 The __main__ in the rlocation path argument is the name of the workspace. Since your WORKSPACE file does not have a "workspace" rule in, which would define the workspace's name, Bazel will use the default workspace name, which is __main__ . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53472993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2044807/']} | jdg_80154 |
stackexchange | llm_judgeable_groundtruth_similarity | 5235344 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For some reason I can't get Nexus to serve my SNAPSHOT artifacts via the default public group. I've read the relevant bit of the Nexus manual and search Google, but nothing I do seems to work. I've implemented the stuff in section 4.2. ( Configuring Maven to Use a Single Nexus Group ) of the manual, so my settings.xml looks like: <settings> <mirrors> <mirror> <id>nexus</id> <mirrorOf>*</mirrorOf> <url>http://my-server/nexus/content/groups/public</url> </mirror> </mirrors> <profiles> <profile> <id>nexus</id> <activation> <activeByDefault>true</activeByDefault> </activation> <repositories> <repository> <id>central</id> <url>http://central</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>central</id> <url>http://central</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> </profile> </profiles></settings> Everything was working fine until I started building stuff on a clean machine (i.e. one I hadn't built any of the SNAPSHOT projects on) and it wouldn't down load the required SNAPSHOT dependencies. Maven gives me the following: [INFO] Scanning for projects...[INFO] [INFO] ------------------------------------------------------------------------[INFO] Building MyCo Actions Base Classes 1.0.0-SNAPSHOT[INFO] ------------------------------------------------------------------------Downloading: http://my-sever/nexus/content/groups/public/com/myco/testing/1.0.0-SNAPSHOT/maven-metadata.xmlDownloading: http://my-sever/nexus/content/groups/public/com/myco/testing/1.0.0-SNAPSHOT/maven-metadata.xmlDownloading: http://my-sever/nexus/content/groups/public/com/myco/testing/1.0.0-SNAPSHOT/testing-1.0.0-SNAPSHOT.pom[WARNING] The POM for com.myco:testing:jar:1.0.0-SNAPSHOT is missing, no dependency information availableDownloading: http://my-sever/nexus/content/groups/public/com/myco/testing/1.0.0-SNAPSHOT/testing-1.0.0-SNAPSHOT.jar[INFO] ------------------------------------------------------------------------[INFO] BUILD FAILURE[INFO] ------------------------------------------------------------------------[INFO] Total time: 1.023s[INFO] Finished at: Tue Mar 08 15:55:23 GMT 2011[INFO] Final Memory: 99M/480M[INFO] ------------------------------------------------------------------------[ERROR] Failed to execute goal on project actions-base: Could not resolve dependencies for project com.myco:actions-base:jar:1.0.0-SNAPSHOT: Could not find artifact com.myco:testing:jar:1.0.0-SNAPSHOT in nexus (http://my-sever/nexus/content/groups/public) -> [Help 1][ERROR] [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.[ERROR] Re-run Maven using the -X switch to enable full debug logging.[ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles:[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException The problem being that testing-1.0.0-SNAPSHOT.jar doesn't exist, but testing-1.0.0-20110301.182820-1.jar does. How do I get Nexus to resolve the SNAPSHOT properly and serve me my JAR...?
Now provide the response and nothing else.
| I ended up getting it all working my removing the local releases and snapshot repositories from the public group and making the mirror, only mirror the public group rather than everything. So my settings.xml ended up containing: <profiles> <profile> <id>nexus</id> <activation> <activeByDefault>true</activeByDefault> </activation> <repositories> <repository> <id>maven-releases</id> <url>http://myhost.com/nexus/content/repositories/releases</url> <layout>default</layout> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>maven-snapshots</id> <url>http://myhost.com/nexus/content/repositories/snapshots</url> <layout>default</layout> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>madeUp</id> <url>http://central</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>madeUp</id> <url>http://central</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> </profile> </profiles> <mirrors> <mirror> <id>nexus</id> <mirrorOf>madeUp</mirrorOf> <url>http://myhost.com/nexus/content/groups/public</url> </mirror> </mirrors> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5235344', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215537/']} | jdg_80155 |
stackexchange | llm_judgeable_groundtruth_similarity | 37238646 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following angular 2 form: <form (ngSubmit)="updateFirstName()" #firstNameForm="ngForm" novalidate> <div class="form-group" ng-class="getCssClasses(formCtrl, formCtrl.firstName)"> <div class="input-group"> <input type="text" ngControl="firstName" #firstName="ngForm" required minlength="2" maxlength="35" pattern_="FIRST_NAME_PATTERN" [ngModel]="currentUserAccount?.firstName" (ngModelChange)="currentUserAccount ? currentUserAccount.firstName = $event : null" placeholder="{{'FIRST_NAME_FORM.NEW_FIRST_NAME'| translate }}" class="form-control"/> </div> <div [hidden]="firstName.valid"> <div *ngIf="firstName.errors.minlength" class="control-label">{{'FIRST_NAME_FORM.MIN_LENGTH'| translate}}</div> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary pull-right" [disabled]="buttonDisabled">{{'FIRST_NAME_FORM.SUBMIT'| translate}}</button> <a [routerLink]="['/dashboard/useraccount']" class="btn btn-link pull-right text-right">{{'FORM_CANCEL' | translate}}</a> </div></form> However it seems errors is null as I get the following error when I load the form in the browser: TypeError: Cannot read property 'minlength' of null What I am getting wrong here? Is the declarative use of minlength attribute in the template not sufficient? Is there another way to declare the minlength validator than in a programmatic way i.e. this.name = new Control('', Validators.minLength(4)); ?
Now provide the response and nothing else.
| I have faced the same problem, i.e. TypeError: Cannot read property 'minlength' of null . For me, the solution proposed by @yurzui solved the problem. I am adding it as an answer here (as suggested by @günter-zöchbauer), so that others (who may not read the comments) can easily find it. Problem: The minlength property may be accessed, before errors is defined: <div *ngIf="firstName.errors.minlength"> Too short</div> Solution: Use the ? operator to ensure that errors is defined, before accessing its minglength property: <div *ngIf="firstName.errors?.minlength"> Too short</div> Alternative Solution: Wrap your div in another div that checks if errors is defined: <div *ngIf="firstName.errors"> <div *ngIf="firstName.errors.minlength"> Too short </div> </div> Note that both solutions assume that firstName is defined. PS: For anyone who needs it, the same applies to errors.maxlength as well! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37238646', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/536299/']} | jdg_80156 |
stackexchange | llm_judgeable_groundtruth_similarity | 237083 |
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's consider the Littlewood-Richardson coefficients $c^{\lambda}_{\mu \nu}$ so that\begin{equation}V_\mu \otimes V_\nu = \bigoplus_\lambda V_\lambda^{\oplus c^{\lambda}_{\mu \nu}}\end{equation}where $V_\mu$ are representations of $GL_n$. Usually the basis elements of the (infinite dimensional) vector space of irreducible representations of $GL_n$ are labelled by partitions. I have two questions: Is there a basis (with basis elements labelled by $i, j, k, \cdots$) that "diagonalizes" the Littlewood-Richardson coefficients? In other words, $c^{i}_{jk} = 0$ unless $i=j=k$? If so, is there an elegant way of relating such a basis to the basis labelled by partitions?
Now provide the response and nothing else.
| If a diagonal basis existed, tensoring with a fixed representation would kill all but finitely many basis elements. This is not the case because e.g. tensoring with the $1$-dimensional trivial representation doesn't kill anything. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/237083', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13731/']} | jdg_80157 |
stackexchange | llm_judgeable_groundtruth_similarity | 382798 |
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 developing a web app in Perl with some C as necessary for some heavy duty number crunching. The main problem I'm having so far is trying to decide if I should use mod-perl, mod-fastcgi or both to run my scripts because I'm having a difficult time trying to analyze the pros and cons of each mod. Can anyone post a summary or give a link where I can find some comparison information and perhaps some recommendations with examples?
Now provide the response and nothing else.
| They are quite different beasts. mod_fastcgi (by the way, mod_fcgid is recommended) just supports the FCGI protocol to execute CGIs faster with some knobs to control how many processes will it run simutaneously and not much more. mod_perl, on the other hand is a platform for development of applications that exposes most Apache internals to you so you can tweak every webserver knob from your code, accelerates CGIs, and much more . If all you wish is to run your CGIs quickly, and want to support as many hosts as possible, you should stick with supporting those two ways to run your code and probably standard CGI as well. If you care about maximum efficiency at the cost of flexibility, you could aim for a single platform, probably mod_perl. But probably the sanest option is to run everywhere and use a framework to build the application that'll take care of using the advantages of a particular way of executing if present, like Catalyst . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/382798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31787/']} | jdg_80158 |
stackexchange | llm_judgeable_groundtruth_similarity | 1300964 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am stuck on this problem: If the lines $y=x+\sqrt{2}$ and $y=x-2\sqrt{2}$ are two tangents of a circle and $(0,\sqrt{2})$ lies on this circle then what is the equation of the circle? I found out the distance between the two tangents $y=x+\sqrt{2}$ and $y=x-2\sqrt{2}$ is $3$. The radius is $3/2$ but I don't know how to find the center. I tried forming the equations but could not succeed. Please tell me the easiest way. Thank you
Now provide the response and nothing else.
| Hint: A sketch of the situation should be helpful: What can we say about the position of the center of a circle with those two tangents? What is its radius? The equation of a circle with radious $r$ and center $(x_0,y_0)$ is:$$(x - x_0)^2 + (y - y_0)^2 = r^2$$ Solution: a) Center line: The center points lie on a line in the middle of the lines, thus on\begin{align}y_c(x) &= \frac{1}{2}(y_1(x) + y_2(x)) \\&= \frac{1}{2}((x + \sqrt{2}) + (x - 2 \sqrt{2})) \\&= x - \frac{1}{\sqrt{2}}\end{align} b) Radius: The radius of the circle is two times the distance of the tangent lines. An orthogonal line to both tangents is $y = - x$ it intersects $y_1$ if $$x + \sqrt{2} = - x \iff 2x = -\sqrt{2} \iff x = - 1/\sqrt{2}$$thus at $P = (-1/\sqrt{2}, 1/\sqrt{2})$. The distance to the origin is $\lVert OP \rVert = \sqrt{1/2 + 1/2} = 1$ It intersects $y_2$ if$$x - 2 \sqrt{2} = -x \iff 2x = 2 \sqrt{2} \iff x = \sqrt{2}$$thus at $Q = (\sqrt{2}, -\sqrt{2})$. The distance to the origin is $\lVert OQ \rVert = \sqrt{2 + 2} = 2$.So both tangents are at a distance $3$ and the radius is $3/2$. c) Equation of any circle with those tangents: So all circles with those two tangents have the equation$$(x - x_0)^2 + \left(y - x_0 + \frac{1}{\sqrt{2}}\right)^2 = 9/4$$ d) The circle with those tangents that contains $(0, \sqrt{2})$: We want the one that contains $(0, \sqrt{2})$ thus$$9/4 = x_0^2 + (\sqrt{2} - x_0 + 1/\sqrt{2})^2= x_0^2 + (3/\sqrt{2} - x_0)^2= x_0^2 + 9/2 + x_0^2 - 3\sqrt{2} x_0 \Rightarrow \\-9/4 = 2 x_0^2 - 3\sqrt{2} x_0 \Rightarrow \\-9/8 = x_0^2 - (3/\sqrt{2}) x_0 = (x_0-3/(2\sqrt{2}))^2 - 9/8 \Rightarrow \\x_0 = \frac{3}{2\sqrt{2}}$$This gives the center $C=(3/(2\sqrt{2}), 3/(2\sqrt{2}) - 1/\sqrt{2}) = (3/(2\sqrt{2}), 1/(2\sqrt{2}))$.And we have the equation$$\left(x - \frac{3}{2\sqrt{2}} \right)^2 + \left(y - \frac{1}{2\sqrt{2}} \right)^2 = 9/4$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1300964', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/224050/']} | jdg_80159 |
stackexchange | llm_judgeable_groundtruth_similarity | 3174 |
Below is a question asked on the forum engineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So i had this experience when driving in a cold night, where my windshield just got all blurry. I knew that on the drivers manual they say you should turn the hot air and soon it will go off, but my friend that was on the passenger seat said the cold air will work too. We turned the AC off and re-experienced the fact. I got the chronometer and and got the time of both situations, defog with hot and cold air and there were really small diference btween them. How can i explain this in terms of thermodynamics?
Now provide the response and nothing else.
| The reason the cooled air appears to work about as well as the heated air is that the cooled air is also de-humidified. For the fastest de-misting, you want warm and dry air. Car owner manuals often tell you to turn on the air conditioner and the defroster at the same time in these conditions. The air conditioner cools the air, which forces it to dump much of whatever moisture it contained. The heater then warms the air again, but without adding any moisture back. The result has high capacity for obsorbing more moisture, so quickly removes the condensation from the inside of the windshield. | {} | {'log_upvote_score': 5, 'links': ['https://engineering.stackexchange.com/questions/3174', 'https://engineering.stackexchange.com', 'https://engineering.stackexchange.com/users/1853/']} | jdg_80160 |
stackexchange | llm_judgeable_groundtruth_similarity | 15439134 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Got a question about why they ask to use immutable objects as keys in a Dictionary. The question actually got in my head when I recently used a dictionary (not for the very purpose of a Hash table apparently though) to place Xml Node objects as keys. I then updated the nodes several times during the usage. So what does 'use immutable keys' really mean?
Now provide the response and nothing else.
| When you insert a key into a hash table, the hash table asks the key for its hash code, and remembers it along with the key itself and the associated value. When you later perform a lookup, the hash table asks the key you're looking for for its hash code, and can very quickly find all the keys in the table that have the same hash code. That's all fine so long as the keys in the hash table keep the same hash code throughout their lives - but if they're mutable (and are mutated after being inserted into the hash table) then typically the hash code will change, at which point the entry will never be found when you search for it. Of course, this only applies to mutations which affect equality. For example, if you hash a Person entity with a name and birthday, but for some reason only the name is used for equality (and thus only the name is used when computing the hash code) then you could insert a Person into a hash table as a key, change its birthday, and still be able to look it up again later with no problems. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15439134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1578274/']} | jdg_80161 |
stackexchange | llm_judgeable_groundtruth_similarity | 3125736 |
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 conceptual problem here, I have like this: abstract class A{ abstract setSomething(bool f1, bool f2);} class C : A {setSomethng(bool f1, bool f2){/*implementation*/}}class B : A {setSomething(bool f1, bool f2, bool f3){/*implementation*/} !! ERROR I'm trying to change the signature of the "setSomething" method in the subClass "B" but it gives me an error that the subClass B doesn't implement the base abstract class, is there anyway to do this? I mean to overload an inherited abstract method?
Now provide the response and nothing else.
| When you inherit from an abstract class you either need to provide implementations for all abstract methods, or else you must declare the subclass also as abstract. You are allowed to add new methods, but you can't remove or change existing methods. With this in mind you can provide two overloads of the method, one with and one without the extra boolean: class B : A{ void setSomething(bool f1, bool f2){ /* implementation */ } void setSomething(bool f1, bool f2, bool f3){ /* implementation */ }} You might even want to consider implementing one in terms of the other: void setSomething(bool f1, bool f2) { setSomething(f1, f2, false); }void setSomething(bool f1, bool f2, bool f3) { /* implementation */ } If you don't want the two parameter version to be there then you should probably reconsider if it is appropriate to use class A as the base class. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3125736', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/274601/']} | jdg_80162 |
stackexchange | llm_judgeable_groundtruth_similarity | 80649 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In my answer here I prove, using generating functions, a statement equivalent to $$\sum_{k=0}^n \binom{2k}{k} \binom{2n-2k}{n-k} (-1)^k = 2^n \binom{n}{n/2}$$when $n$ is even. (Clearly the sum is $0$ when $n$ is odd.) The nice expression on the right-hand side indicates that there should be a pretty combinatorial proof of this statement. The proof should start by associating objects with even parity and objects with odd parity counted by the left-hand side. The number of leftover (unassociated) objects should have even parity and should "obviously" be $2^n \binom{n}{n/2}$. I'm having trouble finding such a proof, though. So, my question is Can someone produce a combinatorial proof that, for even $n$, $$\sum_{k=0}^n \binom{2k}{k} \binom{2n-2k}{n-k} (-1)^k = 2^n \binom{n}{n/2}?$$ Some thoughts so far: Combinatorial proofs for $\sum_{k=0}^n \binom{2k}{k} \binom{2n-2k}{n-k} = 4^n$ are given by Phira here and by Brian M. Scott here . The proofs are basically equivalent. In Phira's argument, both sides count the number of paths of length $2n$ starting from $(0,0)$ using steps of $(1,1)$ and $(1,-1)$. By conditioning on the largest value of $2k$ for which a particular path returns to the horizontal axis at $(2k,0)$ and using the facts that there are $\binom{2k}{k}$ paths from $(0,0)$ to $(2k,0)$ and $\binom{2n-2k}{n-k}$ paths of length $2n-2k$ that start at the horizontal axis but never return to the axis we obtain the left-hand side. With these interpretations of the central binomial coefficients $2^n \binom{n}{n/2}$ could count (1) paths that do not return to the horizontal axis by the path's halfway point of $(n,0)$, or (2) paths that touch the point $(n,0)$. But I haven't been able to construct the association that makes these the leftover paths (nor do all of these paths have even parity anyway). So perhaps there's some other interpretation of $2^n \binom{n}{n/2}$ as the number of leftover paths. Update. Some more thoughts : There's another way to view the identity $\sum_{k=0}^n \binom{2k}{k} \binom{2n-2k}{n-k} = 4^n$. Both sides count the number of lattice paths of length $n$ when north, south, east, and west steps are allowed. The right side is obvious. The left side has a similar interpretation as before: $\binom{2k}{k}$ counts the number of NSEW lattice paths of length $k$ that end on the line $y=0$, and $\binom{2n-2k}{n-k}$ counts the number of NSEW lattice paths of length $n-k$ that never return to the line $y =0$. So far, this isn't much different as before. However, $2^n \binom{n}{n/2}$ has an intriguing interpretation: It counts the number of NSEW lattice paths that end on the diagonal $y = x$ (or, equivalently, $y = -x$). So maybe there's an involution that leaves these as the leftover paths. (Proofs of all of these claims can be found on this blog post , for those who are interested.)
Now provide the response and nothing else.
| Divide by $4^n$ so that the identity reads (again, for $n$ even) $$ \sum_{k=0}^n \binom{2k}{k} \binom{2n-2k}{n-k} \frac{1}{4^n} (-1)^k = \frac{1}{2^n} \binom{n}{n/2}. \tag{1}$$ Claim 1 : Select a permutation $\sigma$ of $[n]$ uniformly at random. For each cycle $w$ of $\sigma$, color $w$ red with probability $1/2$; otherwise, color it blue. This creates a colored permutation $\sigma_C$. Then $$\binom{2k}{k} \binom{2n-2k}{n-k} \frac{1}{4^n}$$ is the probability that exactly $k$ of the $n$ elements of a randomly-chosen permutation $\sigma$ are colored red. (See proof of Claim 1 below.) Claim 2 : Select a permutation $\sigma$ of $[n]$ uniformly at random. Then, if $n$ is even, $$\frac{1}{2^n} \binom{n}{n/2}$$ is the probability that $\sigma$ contains only cycles of even length. (See proof of Claim 2 below.) Combinatorial proof of $(1)$, given Claims 1 and 2 : For any colored permutation $\sigma_C$, find the smallest element of $[n]$ contained in an odd-length cycle $w$ of $\sigma_C$. Let $f(\sigma_C)$ be the colored permutation for which the color of $w$ is flipped. Then $f(f(\sigma_C)) = \sigma_C$, and $\sigma_C$ and $f(\sigma_C)$ have different parities for the number of red elements but the same probability of occurring. Thus $f$ is a sign-reversing involution on the colored permutations for which $f$ is defined. The only colored permutations $\sigma_C$ for which $f$ is not defined are those that have only even-length cycles. However, any permutation with an odd number of red elements must have at least one odd-length cycle, so the only colored permutations for which $f$ is not defined have an even number of red elements. Thus the left-hand side of $(1)$ must equal the probability of choosing a colored permutation that contains only even-length cycles. The probability of selecting one of the several colored variants of a given uncolored permutation $\sigma$, though, is that of choosing an uncolored permutation uniformly at random and obtaining $\sigma$, so the left-hand side of $(1)$ must equal the probability of selecting a permutation of $[n]$ uniformly at random and obtaining one containing only cycles of even length. Therefore, $$\sum_{k=0}^n \binom{2k}{k} \binom{2n-2k}{n-k} \frac{1}{4^n} (-1)^k = \frac{1}{2^n} \binom{n}{n/2}.$$ (Clearly, $$\sum_{k=0}^n \binom{2k}{k} \binom{2n-2k}{n-k} \frac{1}{4^n} = 1,$$which gives another combinatorial proof of the unsigned version of $(1)$ mentioned in the question.) Proof of Claim 1 : There are $\binom{n}{k}$ ways to choose which $k$ elements of a given permutation will be red and which $n-k$ elements will be blue. Given $k$ particular elements of $[n]$, the number of ways those $k$ elements can be expressed as the product of $i$ disjoint cycles is $\left[ {k \atop i} \right]$, an unsigned Stirling number of the first kind . Thus the probability of choosing a permutation $\sigma$ that has those $k$ elements as the product of $i$ disjoint cycles and the remaining $n-k$ elements as the product of $j$ disjoint cycles is $\left[ {k \atop i} \right] \left[ {n-k \atop j}\right] /n!$, and the probability that the $i$ cycles are colored red and the $j$ cycles are colored blue as well is $\left[ {k \atop i} \right] \left[ {n-k \atop j}\right]/(2^i 2^j n!).$ Summing up, the probability that exactly $k$ of the $n$ elements in a randomly chosen permutation are colored red is\begin{align}\frac{\binom{n}{k}}{n!} \sum_{i=1}^k \sum_{j=1}^{n-k} \frac{\left[ {k \atop i} \right] \left[ n-k \atop j \right]}{2^i 2^j} = \frac{\binom{n}{k}}{n!} \sum_{i=1}^k \frac{\left[ {k \atop i} \right]}{2^i} \sum_{j=1}^{n-k} \frac{\left[ {n-k \atop j} \right]}{2^j}.\end{align}The two sums are basically the same, so we'll just do the first one.$$\sum_{i=1}^k \frac{\left[ {k \atop i} \right]}{2^i} = \left( \frac{1}{2} \right)^{\overline{k}} = \prod_{i=0}^{k-1} \left(\frac{1}{2} + i\right) = \frac{1 (3) (5) \cdots (2k-1)}{2^k} = \frac{1 (2) (3) \cdots (2k-1)(2k)}{2^k 2^k k!} = \frac{(2k)!}{4^k k!}.$$ (The first equality is the well-known property that Stirling numbers of the first kind are used to convert rising factorial powers to ordinary powers. This property can be proved combinatorially. For example, Vol. 1 of Richard Stanley's Enumerative Combinatorics , 2nd ed., pp. 34-35 contains two such combinatorial proofs.) Thus the probability that exactly $k$ of the $n$ elements of a randomly chosen permutation are colored red is $$\frac{\binom{n}{k}}{n!} \frac{(2k)!}{4^k k! } \frac{(2n-2k)!}{4^{n-k} (n-k)!} = \binom{2k}{k} \binom{2n-2k}{n-k} \frac{1}{4^n}.$$ Proof of Claim 2 : Since there can be no odd cycles, $\sigma(1) \neq 1$. Thus there are $n-1$ choices for $\sigma(1)$. We have already chosen the element that maps to $\sigma(1)$, but otherwise there are no restrictions on the value of $\sigma(\sigma(1))$, and so we have $n-1$ choices for $\sigma(\sigma(1))$ as well. Now $n-2$ elements are unassigned. If $\sigma(\sigma(1)) \neq 1$, then we have an open cycle. We can't assign $\sigma^3(1) = 1$, as that would close the current cycle at an odd number of elements. Also, $\sigma(1)$ and $\sigma^2(1)$ are already taken. Thus there are $n-3$ choices for the value of $\sigma^3(1)$. If $\sigma(\sigma(1)) = 1$, then we have just closed an even cycle. Selecting any unassigned element in $[n]$, say $j$, we cannot have $\sigma(j) = j$, as that would create an odd cycle, and $1$ and $\sigma(1)$ are already taken. Thus we have $n-3$ choices for $\sigma(j)$ as well. In general, if there are $i$ elements unassigned and $i$ is even, there is either one even-length open cycle or no open cycles. If there is an open cycle, we cannot close it, and so we have $i-1$ choices for the next element in the cycle. If there is not an open cycle, we select the smallest unassigned element $j$. Since we cannot have $\sigma(j) = j$, there are $i-1$ choices for $\sigma(j)$. Either way, we have $i-1$ choices. If there are $i$ elements unassigned and $i$ is odd, though, there must always be an odd-length open cycle. Since we can close it, there are $i$ choices for the next element in the cycle. All together, then, if $n$ is even then the number of permutations of $[n]$ that contain only cycles of even length is $$(n-1)^2 (n-3)^2 \cdots (1)^2 = \left(\frac{n!}{2^{n/2} (n/2)!}\right)^2 = \frac{n!}{2^n} \binom{n}{n/2}.$$ Thus the probability of choosing a permutation uniformly at random and obtaining one that contains only cycles of even length is $$\frac{1}{2^n} \binom{n}{n/2}.$$ (I've been thinking about this problem off and on for the two months since I first posted it. What finally broke it open for me was discovering the interpretation of the unsigned version of the identity mentioned as #60 on Richard Stanley's " Bijective Proof Problems " document.) | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/80649', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/2370/']} | jdg_80163 |
stackexchange | llm_judgeable_groundtruth_similarity | 15217524 |
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 explain the two methodologies which has been implemented in various servlet implementations: Thread per connection Thread per request Which of the above two strategies scales better and why?
Now provide the response and nothing else.
| Which of the above two strategies scales better and why? Thread-per-request scales better than thread-per-connection. Java threads are rather expensive, typically using a 1Mb memory segment each, whether they are active or idle. If you give each connection its own thread, the thread will typically sit idle between successive requests on the connection. Ultimately the framework needs to either stop accepting new connections ('cos it can't create any more threads) or start disconnecting old connections (which leads to connection churn if / when the user wakes up). HTTP connection requires significantly less resources than a thread stack, although there is a limit of 64K open connections per IP address, due to the way that TCP/IP works. By contrast, in the thread-per-request model, the thread is only associated while a request is being processed. That usually means that the service needs fewer threads to handle the same number of users. And since threads use significant resources, that means that the service will be more scalable. (And note that thread-per-request does not mean that the framework has to close the TCP connection between HTTP request ...) Having said that, the thread-per-request model is not ideal when there are long pauses during the processing of each request. (And it is especially non-ideal when the service uses the comet approach which involves keeping the reply stream open for a long time.) To support this, the Servlet 3.0 spec provides an "asynchronous servlet" mechanism which allows a servlet's request method to suspend its association with the current request thread. This releases the thread to go and process another request. If the web application can be designed to use the "asynchronous" mechanism, it is likely to be more scalable than either thread-per-request or thread-per-connection. FOLLOWUP Let's assume a single webpage with 1000 images. This results in 1001 HTTP requests. Further let's assume HTTP persistent connections is used. With the TPR strategy, this will result in 1001 thread pool management operations (TPMO). With the TPC strategy, this will result in 1 TPMO... Now depending on the actual costs for a single TPMO, I can imagine scenarios where TPC may scale better then TPR. I think there are some things you haven't considered: The web browser faced with lots of URLs to fetch to complete a page may well open multiple connections. With TPC and persistent connections, the thread has to wait for the client to receive the response and send the next request. This wait time could be significant if the network latency is high. The server has no way of knowing when a given (persistent) connection can be closed. If the browser doesn't close it, it could "linger", tying down the TPC thread until the server times out the connection. The TPMO overheads are not huge, especially when you separate the pool overheads from the context switch overheads. (You need to do that, since TPC is going to incur context switches on a persistent connections; see above.) My feeling is that these factors are likely to outweigh the TPMO saving of having one thread dedicated to each connection. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15217524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1527084/']} | jdg_80164 |
stackexchange | llm_judgeable_groundtruth_similarity | 55591063 |
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 highly imbalanced dataset and would like to perform SMOTE to balance the dataset and perfrom cross validation to measure the accuracy. However, most of the existing tutorials make use of only single training and testing iteration to perfrom SMOTE. Therefore, I would like to know the correct procedure to perfrom SMOTE using cross-validation. My current code is as follows. However, as mentioned above it only uses single iteration. from imblearn.over_sampling import SMOTEfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)sm = SMOTE(random_state=2)X_train_res, y_train_res = sm.fit_sample(X_train, y_train.ravel())clf_rf = RandomForestClassifier(n_estimators=25, random_state=12)clf_rf.fit(x_train_res, y_train_res) I am happy to provide more details if needed.
Now provide the response and nothing else.
| You need to perform SMOTE within each fold. Accordingly, you need to avoid train_test_split in favour of KFold : from sklearn.model_selection import KFoldfrom imblearn.over_sampling import SMOTEfrom sklearn.metrics import f1_scorekf = KFold(n_splits=5)for fold, (train_index, test_index) in enumerate(kf.split(X), 1): X_train = X[train_index] y_train = y[train_index] # Based on your code, you might need a ravel call here, but I would look into how you're generating your y X_test = X[test_index] y_test = y[test_index] # See comment on ravel and y_train sm = SMOTE() X_train_oversampled, y_train_oversampled = sm.fit_sample(X_train, y_train) model = ... # Choose a model here model.fit(X_train_oversampled, y_train_oversampled ) y_pred = model.predict(X_test) print(f'For fold {fold}:') print(f'Accuracy: {model.score(X_test, y_test)}') print(f'f-score: {f1_score(y_test, y_pred)}') You can also, for example, append the scores to a list defined outside. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55591063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10704050/']} | jdg_80165 |
stackexchange | llm_judgeable_groundtruth_similarity | 14035089 |
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 Usecase: I don't use the blobstore for uploading and downloading files. I use the blobstore to store very large strings my program is creating. With persisting the path where the blob is stored, I can later load the string again (see documentation ) My Question: Is there an easier way to access the blob content without the need to store the path? BlobstoreService only allows me to directly serve to the HttpServletReponse.
Now provide the response and nothing else.
| I've done a significant amount of work with the FTDI chips on the Mac, so I can provide a little insight here. I've used the single-channel and dual-channel variants of their USB-serial converters, and they all behave the same way. FTDI has both their Virtual COM Port drivers, which create a serial COM port on your system representing the serial connection attached to their chip, and their D2XX direct communication libraries. You're going to want to work with the latter, which can be downloaded from their site for various platforms . The D2XX libraries for the Mac come in a standalone .dylib (the latest being libftd2xx.1.2.2.dylib) or a new static library they started shipping recently. Included in that package will be the appropriate header files you need (ftd2xx.h and WinTypes.h) as well. In your Xcode project, add the .dylib as a framework to be linked in, and add the ftd2xx.h, WinTypes.h, and ftd2xx.cfg files to your project. In your Copy Bundled Frameworks build phase, make sure that libftd2xx.1.2.2.dylib and ftd2xx.cfg are present in that phase. You may also need to adjust the relative path that this library expects, in order for it to function within your app bundle, so you may need to run the following command against it at the command line: install_name_tool -id @executable_path/../Frameworks/libftd2xx.1.2.2.dylib libftd2xx.1.2.2.dylib Once your project is all properly configured, you'll want to import the FTDI headers: #import "ftd2xx.h" and start to connect to your serial devices. The example you link to in your question has a downloadable C++ sample that shows how they communicate to their device. You can bring across almost all of the C code used there and place it within your Objective-C application. They just look to be using the standard FTDI D2XX commands, which are described in detail within the downloadable D2XX Programmer's Guide . This is some code that I've lifted from one of my applications, used to connect to one of these devices: DWORD numDevs = 0; // Grab the number of attached devices ftdiPortStatus = FT_ListDevices(&numDevs, NULL, FT_LIST_NUMBER_ONLY); if (ftdiPortStatus != FT_OK) { NSLog(@"Electronics error: Unable to list devices"); return; } // Find the device number of the electronics for (int currentDevice = 0; currentDevice < numDevs; currentDevice++) { char Buffer[64]; ftdiPortStatus = FT_ListDevices((PVOID)currentDevice,Buffer,FT_LIST_BY_INDEX|FT_OPEN_BY_DESCRIPTION); NSString *portDescription = [NSString stringWithCString:Buffer encoding:NSASCIIStringEncoding]; if ( ([portDescription isEqualToString:@"FT232R USB UART"]) && (usbRelayPointer != NULL)) { // Open the communication with the USB device ftdiPortStatus = FT_OpenEx("FT232R USB UART",FT_OPEN_BY_DESCRIPTION,usbRelayPointer); if (ftdiPortStatus != FT_OK) { NSLog(@"Electronics error: Can't open USB relay device: %d", (int)ftdiPortStatus); return; } //Turn off bit bang mode ftdiPortStatus = FT_SetBitMode(*usbRelayPointer, 0x00,0); if (ftdiPortStatus != FT_OK) { NSLog(@"Electronics error: Can't set bit bang mode"); return; } // Reset the device ftdiPortStatus = FT_ResetDevice(*usbRelayPointer); // Purge transmit and receive buffers ftdiPortStatus = FT_Purge(*usbRelayPointer, FT_PURGE_RX | FT_PURGE_TX); // Set the baud rate ftdiPortStatus = FT_SetBaudRate(*usbRelayPointer, 9600); // 1 s timeouts on read / write ftdiPortStatus = FT_SetTimeouts(*usbRelayPointer, 1000, 1000); // Set to communicate at 8N1 ftdiPortStatus = FT_SetDataCharacteristics(*usbRelayPointer, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE); // 8N1 // Disable hardware / software flow control ftdiPortStatus = FT_SetFlowControl(*usbRelayPointer, FT_FLOW_NONE, 0, 0); // Set the latency of the receive buffer way down (2 ms) to facilitate speedy transmission ftdiPortStatus = FT_SetLatencyTimer(*usbRelayPointer,2); if (ftdiPortStatus != FT_OK) { NSLog(@"Electronics error: Can't set latency timer"); return; } } } Disconnection is fairly simple: ftdiPortStatus = FT_Close(*electronicsPointer); *electronicsPointer = 0; if (ftdiPortStatus != FT_OK) { return; } Writing to the serial device is then pretty easy: __block DWORD bytesWrittenOrRead; unsigned char * dataBuffer = (unsigned char *)[command bytes]; //[command getBytes:dataBuffer]; runOnMainQueueWithoutDeadlocking(^{ ftdiPortStatus = FT_Write(electronicsCommPort, dataBuffer, (DWORD)[command length], &bytesWrittenOrRead); }); if((bytesWrittenOrRead < [command length]) || (ftdiPortStatus != FT_OK)) { NSLog(@"Bytes written: %d, should be:%d, error: %d", bytesWrittenOrRead, (unsigned int)[command length], ftdiPortStatus); return NO; } ( command is an NSData instance, and runOnMainQueueWithoutDeadlocking() is merely a convenience function I use to guarantee execution of a block on the main queue ). You can read raw bytes from the serial interface using something like the following: NSData *response = nil;DWORD numberOfCharactersToRead = size;__block DWORD bytesWrittenOrRead;__block unsigned char *serialCommunicationBuffer = malloc(numberOfCharactersToRead); runOnMainQueueWithoutDeadlocking(^{ ftdiPortStatus = FT_Read(electronicsCommPort, serialCommunicationBuffer, (DWORD)numberOfCharactersToRead, &bytesWrittenOrRead);});if ((bytesWrittenOrRead < numberOfCharactersToRead) || (ftdiPortStatus != FT_OK)){ free(serialCommunicationBuffer); return nil;}response = [[NSData alloc] initWithBytes:serialCommunicationBuffer length:numberOfCharactersToRead];free(serialCommunicationBuffer); At the end of the above, response will be an NSData instance containing the bytes you've read from the port. Additionally, I'd suggest that you should always access the FTDI device from the main thread. Even though they say they support multithreaded access, I've found that any kind of non-main-thread access (even guaranteed exclusive accesses from a single thread) cause intermittent crashes on the Mac. Beyond the cases I've described above, you can consult the D2XX programming guide for the other functions FTDI provides in their C library. Again, you should just need to move over the appropriate code from the samples that have been provided to you by your device manufacturer. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14035089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1066081/']} | jdg_80166 |
stackexchange | llm_judgeable_groundtruth_similarity | 9072600 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Easy interview question got harder: given numbers 1..100, find the missing number(s) Find the missing and duplicate elements in an array in linear time and constant space I saw an interesting Question on one forum. you have 100 elements from 1 to 100 but byy mistake one of those number overlapped another by repeating itself.E.g. 1,99,3,...,99,100Array is not in sorted format , how to find the repeating number ? I know Hash can do it O(n) time and O(n) space, I need O(1) space.
Now provide the response and nothing else.
| Calculate two sums: sum and square sum. In your example: sum = 1+99+3...+100sq_sum = 1^2+99^2+3^2+...+100^2 Assume y replaced x in the sequence. sum = n(n+1)/2 -y+x.sq_sum = n(n+1)(2n+1)/6 -x^2 +y^2 Now, solve for x & y. Constant space and O(n) time. How to solve for x and y From equation: x = sum - n(n+1)/2 +y Substitute this in the second equation: sq_sum = n(n+1)(2n+1)/6 -(sum - n(n+1)/2 +y)^2 +y^2 Note that y^2 cancels and you are left with a linear equation with only one unknown:y. Solve it! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9072600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/973931/']} | jdg_80167 |
stackexchange | llm_judgeable_groundtruth_similarity | 5467007 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i have lots of sprites arranged in 3D space, and their parent container has rotations applied.How do i reverse the sprites 3D rotation, that they always face the camera (Actionscript 3)? heres a code to test it: package{import flash.display.Sprite;import flash.events.Event;public class test extends Sprite{var canvas:Sprite = new Sprite();var sprites:Array = []public function test(){ addChild(canvas) for (var i:int=0;i<20;i++){ var sp:Sprite = new Sprite(); canvas.addChild(sp); sp.graphics.beginFill(0xFF0000); sp.graphics.drawCircle(0,0,4); sp.x = Math.random()*400-200; sp.y = Math.random()*400-200; sp.z = Math.random()*400-200; sprites.push(sp); } addEventListener(Event.ENTER_FRAME,function():void{ canvas.rotationX++; canvas.rotationY = canvas.rotationY+Math.random()*2; canvas.rotationZ++; for (var i:int=0;i<20;i++){ //this is not working... sprites[i].rotationX = -canvas.rotationX sprites[i].rotationY = -canvas.rotationY sprites[i].rotationZ = -canvas.rotationZ } })}}} I am guessing i have to do some magic with the rotation3D matrices of the sprites...I've tried to implement this script: http://ughzoid.wordpress.com/2011/02/03/papervision3d-sprite3d/ , but had so success Thanks for help.
Now provide the response and nothing else.
| The easiest way to do this is "clearing" the rotational part of the transform matrix. Your typical homogenous transformation looks like this | xx xy xz xw || yx yy yz yw || zx zy zz zw || wx wy wz ww | with wx = wy = wz = 0, ww = 1. If you take a closer look you'll see that in fact this matrix is composed of a 3x3 submatrix defining the rotation, a 3 subvector for the translation and a homogenous row 0 0 0 1 | R T || (0,0,0) 1 | For a billboard/sprite you want to keep the translation, but get rid of the rotation, i.e. R = I. In case some scaleing was applied the identity needs to be scaled as well. This gives the following recipie: d = sqrt( xx² + yx² + zx² ) | d 0 0 T.x || 0 d 0 T.y || 0 0 d T.z || 0 0 0 1 | Loading this matrix allows you to draw camera aligned sprites. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5467007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/319473/']} | jdg_80168 |
stackexchange | llm_judgeable_groundtruth_similarity | 2662 |
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In the numerical solution of initial boundary value PDEs, it is very common to employ parallelism in space . It is much less common to employ some form of parallelism in the time discretization , and that parallelism is usually much more limited. I'm aware of an increasing number of codes and published works demonstrating temporal parallelism, but none of them include spatial parallelism. Are there examples of implementations that include parallelism in both space and time? I'm interested in both publications and available codes.
Now provide the response and nothing else.
| The PFASST (Parallel Full Approximation Scheme in Space and Time) and PEPC (Pretty Efficient Parallel Coulomb) algorithms have recently been used together to achieve parallelism in both space and time. PFASST does the time parallelism, PEPC does the space parallelism. The results of this were recently presented at the DD21 conference, and we have prepared a submission for SC12 describing the combination of PFASST+PEPC. A "small" problem consisting of 4 million particles (PEPC is a parallel N-body solver) was shown to scale well up to 8192 cores on JUGENE using only PEPC (ie, only parallel in space). Beyond this, communication costs became significant and the parallel efficiency began to degrade. The addition of PFASST allows this fixed sized problem to be run on 262,144 cores (ie, we filled up JUGENE) by using 32 "time" processors (each of which consists of 8192 "spatial" cores). Although the parallel efficiency of time-parallel algorithms isn't 100%, we were able to obtain speedups of about 6.5x using 32 PFASST processors with this PFASST+PEPC configuration. Here is a link to a preprint: A massively space-time parallel N-body solver | {} | {'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/2662', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/123/']} | jdg_80169 |
stackexchange | llm_judgeable_groundtruth_similarity | 5924072 |
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 reduced my code to the simplest express-js app I could make: var express = require("express"), app = express.createServer();app.use(express.static(__dirname + '/styles'));app.listen(3001); My directory look like this: static_file.js/styles default.css Yet when I access http://localhost:3001/styles/default.css I get the following error: Cannot GET / styles /default.css I'm using express 2.3.3 and node 0.4.7 . What am I doing wrong?
Now provide the response and nothing else.
| Try http://localhost:3001/default.css . To have /styles in your request URL, use: app.use("/styles", express.static(__dirname + '/styles')); Look at the examples on this page : //Serve static content for the app from the "public" directory in the application directory. // GET /style.css etc app.use(express.static(__dirname + '/public'));// Mount the middleware at "/static" to serve static content only when their request path is prefixed with "/static". // GET /static/style.css etc. app.use('/static', express.static(__dirname + '/public')); | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5924072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/29347/']} | jdg_80170 |
stackexchange | llm_judgeable_groundtruth_similarity | 48395619 |
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 make one array from two arrays. I tried to do use +: var array1 = intArrayOf(1,2,3)var array2 = intArrayOf(4,5,6)var array3 = array1 + array2 But it is not working unfortunately... How can I combine them?
Now provide the response and nothing else.
| Actually, your exact code works for me. Tried it on multiple Kotlin versions. You can find the operator fun IntArray.plus(elements: IntArray): IntArray function that's being used for this in the docs here , and its source here . var array1 = intArrayOf(1, 2, 3) // 1, 2, 3var array2 = intArrayOf(4, 5, 6) // 4, 5 ,6var array3 = array1 + array2 // 1, 2, 3, 4, 5, 6 Are you perhaps looking to do something different, like add the elements one by one and create a new array of length 3? You can do that like this: val array4 = array1.zip(array2, Int::plus).toTypedArray() // 5, 7, 9 The extra toTypedArray call is necessary only if you actually need an array, otherwise you can use the List<Int> that the zip function returns. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48395619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9255158/']} | jdg_80171 |
stackexchange | llm_judgeable_groundtruth_similarity | 38205 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How might it be possible to alter some variable in the env of an already running process, for example through /proc/PID/environ? That "file" is read-only . Need to change or unset the DISPLAY variable of a long-running batch job without killing it.
Now provide the response and nothing else.
| You can't do this without a nasty hacks - there's no API for this, no way to notify the process that its environment has changed (since that's not really possible anyway). Even if you do manage to do that, there is no way to be sure that it will have any effect - the process could very well have cached the environment variable you're trying to poke (since nothing is supposed to be able to change it). If you really do want to do this, and are prepared to pick up the pieces if things go wrong, you can use a debugger. See for instance this Stack Overflow question: Is there a way to change another process's environment variables? Essentially: (gdb) attach process_id(gdb) call putenv ("DISPLAY=your.new:value")(gdb) detach Other possible functions you could try to call are setenv or unsetenv . Please do really keep in mind that this may not work, or have dire consequences if the process you target does "interesting" things with its environment block. Do test it out on non-critical processes first, but make sure these test processes mirror as close as possible the one you're trying to poke. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/38205', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/13496/']} | jdg_80172 |
stackexchange | llm_judgeable_groundtruth_similarity | 20070681 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the following piece of code, what is the meaning of ::~ GaussianMex::~GaussianMex(){ int i;}
Now provide the response and nothing else.
| This is not a single operator ::~ , but a definition of GaussianMex destructor. You define class methods by ClassName::ClassMethod syntax and since destructor name is ~ClassName resulting destructor definition is ClassName::~ClassName . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20070681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2224801/']} | jdg_80173 |
stackexchange | llm_judgeable_groundtruth_similarity | 3820985 |
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 HTTPSystemDefinitions.cs file in C# project which basically describes the older windows ISAPI for consumption by managed code. This includes the complete set of Structures relevant to the ISAPI not all or which are consumed by code. On compilation all the field members of these structures are causing a warning like the following:- Warning Field 'UnionSquare.ISAPI.HTTP_FILTER_PREPROC_HEADERS.SetHeader' is never assigned to, and will always have its default value null or Warning The field 'UnionSquare.ISAPI.HTTP_FILTER_PREPROC_HEADERS.HttpStatus' is never used Can these be disabled with #pragma warning disable ? If so what would the corresponding error numbers be? If not is there anything else I can do? Bear in mind that I only what to do this for this file, its important that I get see warnings like these coming from other files. Edit Example struct:- struct HTTP_FILTER_PREPROC_HEADERS{ // // For SF_NOTIFY_PREPROC_HEADERS, retrieves the specified header value. // Header names should include the trailing ':'. The special values // 'method', 'url' and 'version' can be used to retrieve the individual // portions of the request line // internal GetHeaderDelegate GetHeader; internal SetHeaderDelegate SetHeader; internal AddHeaderDelegate AddHeader; UInt32 HttpStatus; // New in 4.0, status for SEND_RESPONSE UInt32 dwReserved; // New in 4.0}
Now provide the response and nothing else.
| Yes, these can be suppressed. Normally, I'm opposed to suppressing warnings, but in this case, structs used for interop absolutely requires some fields to be present, even though you never intend to (or can) use them, so in this case I think it should be justified. Normally, to suppress those two warnings, you would fix the offending code. The first ("... is never used") is usually a code-smell of leftovers from earlier versions of the code. Perhaps code was deleted, but fields left behind. The second is usually a code-smell for incorrectly used fields. For instance, you might incorrectly write the new value of a property back to the property itself, never writing to the backing field. To suppress warnings for " Field XYZ is never used ", you do this: #pragma warning disable 0169... field declaration#pragma warning restore 0169 To suppress warnings for " Field XYZ is never assigned to, and will always have its default value XX ", you do this: #pragma warning disable 0649... field declaration#pragma warning restore 0649 To find such warning numbers yourself (ie. how did I know to use 0169 and 0649), you do this: Compile the code as normal, this will add some warnings to your error list in Visual Studio Switch to the Output window, and the Build output, and hunt for the same warnings Copy the 4-digit warning code from the relevant message, which should look like this: C:\Dev\VS.NET\ConsoleApplication19\ConsoleApplication19\Program.cs(10,28): warning CS 0649 : Field 'ConsoleApplication19.Program.dwReserved' is never assigned to, and will always have its default value 0 Caveat : As per the comment by @Jon Hanna , perhaps a few warnings is in order for this, for future finders of this question and answer. First, and foremost, the act of suppressing a warning is akin to swallowing pills for headache. Sure, it might be the right thing to do sometimes, but it's not a catch-all solution. Sometimes, a headache is a real symptom that you shouldn't mask, same with warnings. It is always best to try to treat the warnings by fixing their cause, instead of just blindly removing them from the build output. Having said that, if you need to suppress a warning, follow the pattern I laid out above. The first code line, #pragma warning disable XYZK , disables the warning for the rest of that file , or at least until a corresponding #pragma warning restore XYZK is found. Minimize the number of lines you disable these warnings on. The pattern above disables the warning for just one line. Also, as Jon mentions, a comment as to why you're doing this is a good idea. Disabling a warning is definitely a code-smell when done without cause, and a comment will prevent future maintainers from spending time either wondering why you did it, or even by removing it and trying to fix the warnings. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3820985', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17516/']} | jdg_80174 |
stackexchange | llm_judgeable_groundtruth_similarity | 36435236 |
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 below decorator demonstration code. If I execute it without explicitly calling greet function, it is executing print statement inside decorator function and outputs Inside decorator . I am unable to understand this behavior of decorator. How the time_decorator is called even if I didn't call greet function? I am using Python 3. def time_decorator(original_func): print('Inside decorator') def wrapper(*args, **kwargs): start = time.clock() result = original_func(*args, **kwargs) end = time.clock() print('{0} is executed in {1}'.format(original_func.__name__, end-start)) return result return wrapper@time_decoratordef greet(name): return 'Hello {0}'.format(name)
Now provide the response and nothing else.
| Decorators are called at start time (when the python interpreter reads the code as the program starts) , not at runtime (when the decorated function is actually called) . At runtime, it is the wrapped function wrapper which is called and which itself calls the decorated function and returns its result. So this is totally normal that the print line gets executed. If, i.e, you decorate 10 functions, you will see 10 times the print output. No need to even call the decorated functions for this to happen. Move the print inside wrapper and this won't happen anymore. Decorators as well as metaclasses are part of what is called meta-programming (modify / create code, from existing code) . This is a really fascinating aspect of programming which takes time to understand but offers amazing possibilities. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36435236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1367230/']} | jdg_80175 |
stackexchange | llm_judgeable_groundtruth_similarity | 47101 |
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:
Can ordinary least squares estimation be considered an optimization technique? If so, how can I explain this? Note: From an AI perspective, supervised learning involves finding a hypothesis function $h_\vec{w}(\vec{x})$ that approximates the true nature between predictor variables and the predicted variable. Let some set of functions with the same model representation define the hypothesis space $\mathbb{H}$ (That is we hypothesise the true relationship to be a linear function of inputs or a quadratic function of inputs and so forth). The objective is to find the model $h\in\mathbb{H}$ that optimally maps inputs to outputs. This is done by application of some technique to finds optimal values for the adjustable parameters $\vec{w}$ that defines the function $h_w(\vec{x})$. In AI we call this parameter optimization. A parameter optimization technique/model inducer/learning algorithm would for example be the back propagation algorithm. OLS is used to find/estimate for $\beta$ parameters that defines the linear regression line that optimally maps predictor variables to output variables. This would be parameter optimization in the scenario above.
Now provide the response and nothing else.
| Yes, it is. In OLS, you are looking for the linear model that provides the "best" fit to the data. Implementation requires specifying some notion of what you mean by "best". OLS works by defining the "best" model as the one that minimizes a certain measure of model error -- in this case, the sum of the squares of the model residuals. The residuals are the part of the data that aren't explained by the model: OLS seeks to give the best description of the data, by minimizing the "total amount" of unexplained variation in the data. Formally, any operaton in which you are solving for the minimum or maximum of some function can be interpreted as an optimization. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/47101', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/16837/']} | jdg_80176 |
stackexchange | llm_judgeable_groundtruth_similarity | 11263538 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ok, this may have been answered, but I'm new and trying to learn, so I guess I'm not "getting" it. I have a variable that contains a table of information (I got it from a SQL query). I can output the variable to the screen and see the table, but when I try to build an HTML email with it in the body, it gets garbled. Here is the code: # This code sets up the HTML table in a more friendly format$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"$style = $style + "TD{border: 1px solid black; padding: 5px; }"$style = $style + "</style>"# This code defines the search string in the IssueTrak database tables$SQLServer = "Blah"$SQLDBName = "Blah"$SQLUsername = "Blah"$SQLPassword = "Blah"$SQLQuery = "SELECT u.FirstName,u.LastName,u.EMail,COUNT(UserID) as Count FROM dbo.Issues i with(nolock) JOIN DBO.Users u with(nolock) on u.UserID = i.NextActionBy where i.Status='Open' group by u.FirstName,u.LastName,u.EMail order by Count(*) desc"# This code connects to the SQL server and retrieves the data$SQLConnection = New-Object System.Data.SqlClient.SqlConnection$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; uid = $SQLUsername; pwd = $SQLPassword"$SqlCmd = New-Object System.Data.SqlClient.SqlCommand$SqlCmd.CommandText = $SqlQuery$SqlCmd.Connection = $SqlConnection$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter$SqlAdapter.SelectCommand = $SqlCmd$DataSet = New-Object System.Data.DataSet$SqlAdapter.Fill($DataSet)$SqlConnection.Close()# This code outputs the retrieved data$DataSet.Tables | Format-Table -Auto# This code emails a report regarding the results of the retrieved data$smtpServer = "Blah"$smtpFrom = "Blah"$smtpTo = "Blah"$messageSubject = "IssueTrak Open Issues By Next Action Report"$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto$message.Subject = $messageSubject$message.IsBodyHTML = $true$message.Body = "Here is a listing of open issues in IssueTrak, sorted by Next Action.<br><br>"$message.Body = $message.Body + $html$smtp = New-Object Net.Mail.SmtpClient($smtpServer)$smtp.Send($message) The output on the screen looks like this: 35FirstName LastName EMail Count--------- -------- ----- -----John Doe [email protected] 51Jane Doe [email protected] 20 ...but the email body looks like this: Here is a listing of open issues in IssueTrak, sorted by Next Action.Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartDataMicrosoft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData ...and so on. What am I doing wrong?
Now provide the response and nothing else.
| Here's how I'd do it: # Create a DataTable$table = New-Object system.Data.DataTable "TestTable"$col1 = New-Object system.Data.DataColumn Name,([string])$col2 = New-Object system.Data.DataColumn Dept,([string])$table.columns.add($col1)$table.columns.add($col2)# Add content to the DataTable$row = $table.NewRow()$row.Name = "John"$row.Dept = "Physics"$table.Rows.Add($row)$row = $table.NewRow()$row.Name = "Susan"$row.Dept = "English"$table.Rows.Add($row)# Create an HTML version of the DataTable$html = "<table><tr><td>Name</td><td>Dept</td></tr>"foreach ($row in $table.Rows){ $html += "<tr><td>" + $row[0] + "</td><td>" + $row[1] + "</td></tr>"}$html += "</table>"# Send the email$smtpserver = "smtpserver.domain.com"$from = "[email protected]"$to = "[email protected]"$subject = "test"$body = "Hi there,<br />Here is a table:<br /><br />" + $htmlSend-MailMessage -smtpserver $smtpserver -from $from -to $to -subject $subject -body $body -bodyashtml | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11263538', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_80177 |
stackexchange | llm_judgeable_groundtruth_similarity | 20814609 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am writing algorithms inside methods that return BigDecimal values but now and again the result calculated will be + or - infinity. Rather than the program crashing I'd like to catch the exception and return infinity as a value like the way you could if the method was returning a double. eg Double.POSITIVE_INFINITY; So how do I store infinity in a BigDecimal? Or is there another way of doing this? public static BigDecimal myalgorithm(){//code to store infinity in a BigDecimal//return the BigDecimal holding infinity }
Now provide the response and nothing else.
| BigDecimal doesn't have the concept of infinity. I can think of three options: The cleanest approach is probably to derive your own MyBigDecimal class, adding an infinity flag telling you if the instance contains infinity, and overriding the methods to which it would be relevant (which would be most of them, I would think), using the base class's version when you're not holding infinity and your own code when you are. You could use null as a flag value in your code, although that might be a bit of a pain. E.g.: if (theBigDecimal == null) { // It's infinity, deal with that}else { // It's finite, deal with that} If you're already using null for something else, you could have a BigDecimal instance that doesn't actually contain infinity, but which you pretend containts it, and use == to check against it. E.g.: // In your class somewhere:static final BigDecimal INFINITE_BIG_DECIMAL = new BigDecimal(); // Value doesn't matter// Then:if (theBigDecimal == INFINITE_BIG_DECIMAL) { // It's infinity, deal with that}else { // It's finite, deal with that} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20814609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2989759/']} | jdg_80178 |
stackexchange | llm_judgeable_groundtruth_similarity | 920241 |
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 an observed event in fact be of zero probability? Of course, I know that there exist non-empty events of zero probability. Mu question is the reverse: given that we have observed an event (and we have no other information about it, just the fact that it has been observed), is it possible that the event has in fact zero probability? Or does an observation necessarily mean that the probability is strictly positive? Example context for the question: Suppose $x_i$ (countably many) are i.i.d on $[0,1]$, but we do not know the distribution they come from. It may be uniform on $[0,1]$, may be discrete, may be any legitimate distribution (discrete or continuous). Just imagine we have some sort of a machine that shows us one by one a list of randomly drawn numbers between $0$ and $1$. We are comparing the observed numbers one by one to some special number chosen beforehand, for example $\frac12$. Now, given that at some iteration we have observed that special number at least once, does that mean that $\frac12$ has some positive probability under that (unknown) distribution? And if the probability can be zero, can we nevertheless say that we will necessarily observe $\frac12$ again later, if we continue the experiment ad infimum? Also, disregard the "real world limitations" such as an inability to produce truly uniformly distibuted numbers, or rounding errors or any such thing.
Now provide the response and nothing else.
| is it possible that the event has in fact zero probability? Yes. For a situation where this always happens, assume that one observes a random number $x$ drawn from the uniform distribution on $(0,1)$. Then the probability to observe $x$ is zero. (Proof: For every interval $I\subseteq(0,1)$ the probability to observe a number in $I$ is the length of $I$. For every positive $\varepsilon$, there are intervals $I\subseteq(0,1)$ which contain $x$ and have length less than $\varepsilon$ hence the probability to observe exactly $x$ is less than $\varepsilon$, for every positive $\varepsilon$, QED.) Edit: In a discrete space $\{x_i\mid i\in\mathbb N\}$, the probability to observe $x_i$ is, by hypothesis, some positive $p_i$ hence the above applies only to continuous distributions (or at least, partially continuous). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/920241', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/154708/']} | jdg_80179 |
stackexchange | llm_judgeable_groundtruth_similarity | 12080 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the following reasoning: Let $K(x)$ denote the Kolmogorov complexity of the string $x$. Chaitin's incompleteness theorem says that for any consistent and sufficiently strong formal system $S$, there exists a constant $T$ (depending only on the formal system and its language) such that for any strings $x$, $S$ cannot prove that $K(x) \geq T$. Let $f_n$ be a Boolean function on $n$ variables s.t. the Kolmogorov complexity of its spectrum is at most $k$.Let $S(f_n)$ be the circuit complexity of $f_n$, i.e. the size of the minimal circuit computing $f_n$. A (rough) upper bound on for $S(f_n)$ is $$S(f_n)\leq c\cdot BB(k) \cdot n$$ for a constant $c$ and $BB(k)$ is a busy beaver function (the maximum possible steps a halting Turing machine with a description of size $k$ can perform).(For every $1$ in the spectrum, construct the minterm of the correspondingtruth assignment, and take OR of all these minterms together.) Suppose now for an infinite family of Boolean functions $L = \{f_n\}_{n}$, we have a formal proof that$L$ requires superlinear size circuits, i.e. $$S \vdash \forall n \geq n_0, \ g(n)\cdot n \leq S(f_n)$$where $g(n)\in \omega(1)$. If we take $n$ to be sufficiently large, we will have$$g(n) > c\cdot BB(T)$$ In particular this would be a proof that the Kolmogorov complexity of the spectrumof $f_n$ is at least $T$, which is impossible. This leads to two questions: 1) There should be something wrong in the above reasoning.Mainly because it would make superlinear circuit lower bounds formally not provable. 2) Do you know of similar approaches to show barriers for lower bounds, that is, showing that certain types of (circuit) lower bounds are formally unprovable?
Now provide the response and nothing else.
| There is nothing wrong with your argument, but there is no contradiction. You prove that from some large enough $N$ the Kolmogorov complexity of the spectrum of $f_n$ is always at least $T$. But this statement is trivially true! Although we cannot prove that the Kolmogorov complexity of one string is large, if we have a sequence, then from some point it must contain only strings of large complexity. So what is this $N$ that you got? It must satisfy $N>g^{-1}(c \cdot BB(T))$, what is a number that we cannot compute (because of $BB$), so there is no problem at all. | {} | {'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/12080', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/4201/']} | jdg_80180 |
stackexchange | llm_judgeable_groundtruth_similarity | 3469723 |
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 script for restoring a database with PowerShell and SMO. Now I know that I can pass a event handler into PercentComplete on the restore object and get the progress of the restore as it happens. The problem is I don't know how to create a event handler and pass it a function in PowerShell? I can do it in C# restore.PercentComplete += new PercentCompleteEventHandler(restore_PercentComplete);static void restore_PercentComplete(object sender, PercentCompleteEventArgs e){ System.Console.WriteLine("{0}", e.Percent);} Any help would be appreciated. Thank You.
Now provide the response and nothing else.
| After some deeper searching I finally found it in the documentation. To add event handlers you need to do the following: Import the relevant assemblies; [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SmoExtended') | out-null[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.ConnectionInfo') | out-null Now to create the event handler you need to declare it with an inline function; $percentEventHandler = [Microsoft.SqlServer.Management.Smo.PercentCompleteEventHandler] { Write-Host "Restored " $_.Percent "%" }$completedEventHandler = [Microsoft.SqlServer.Management.Common.ServerMessageEventHandler] { Write-Host "Database " $databasename " Created Successfuly!" } Now the final step is to add the event handler to the object you are working with. Normally in C# you just do the following; restore.PercentComplete += new PercentCompleteEventHandler(restore_PercentComplete);restore.Complete += new Microsoft.SqlServer.Management.Common.ServerMessageEventHandler(restore_Complete); This will not work in PowerShell script, what you need to do is use the generated function for adding events. The function name is the EventHandlerName with "add_" appended to the beginning of it, like so; $dbRestore.add_PercentComplete($percentEventHandler)$dbRestore.add_Complete($completedEventHandler) Hope this helps anyone else trying to do this! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3469723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73903/']} | jdg_80181 |
stackexchange | llm_judgeable_groundtruth_similarity | 6007 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that in Internet Protocol Stack there are actually three layer. They are Application, Internet and Transport. Let's say HTTP in Application layer will be converted to TCP in Transport layer and TCP will be converted to IP in Internet layer. But practically when I tried to capture a network traffic from internet, I can only understand the HTTP layer and I can't understand what is in TCP and IP. I am using wireshark for capturing network traffic. Please explain the process or provide a simple example for this.
Now provide the response and nothing else.
| There is no conversion, what you have is Encapsulation Ex: you use wireshark on your local PC to capture your HTTP session. Basically, what you end up with looks like: [Ethernet Frame [IP Packet [TCP Segment [HTTP Request]]]] The Ethernet frame has the EtherType field of 0x0800 that gives us the encapsulated protocols as IP The IP Packet has the Protocol Field of "6" that tells us the next level is TCP (ICMP is Protocol "1") TCP has the Destination port of 80, on which normally a Web Server is listening to HTTP is what is actually understood by a Web Server | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/6007', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/4041/']} | jdg_80182 |
stackexchange | llm_judgeable_groundtruth_similarity | 86233 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know that under $SU(2) \times SU(2)$, the left-handed electron transforms under $ ( \frac{1}{2},0 ) $ representation and the vector gauge field $A_\mu$ under $ ( \frac{1}{2},\frac{1}{2}) $. Since the electron transforms under $U(1)$, there must be a represenation under which it transforms. What is this representation? Does it have a name? Apparenly $A_\mu$ does not transform under the same representation, which would mean $e^{\alpha(x) Q} A_\mu$, but instead as $A_\mu + i \partial_\mu \alpha(x)$ ? What representation is this? Of course I realize that the transformation of $A_\mu$ can't be different for the Lagrangian to be invariant, but that shouldn't be used to define the it.
Now provide the response and nothing else.
| The electron field transforms under the $\mathbf 1$ of $U(1)$, i.e., the generator is $i$ or $1$ depending on your convention/notation. The gauge fields transform in the adjoint representation , but they transform as a connection, as @Adam mentioned. In other words, if $\psi \to g \psi$, then $D_\mu \psi \to g D_\mu \psi$ implies that $A_\mu \to g D_\mu g^{-1}$. It's a bit misleading for $U(1)$ because you don't see the non-Abelian structure, but you get the idea. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/86233', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/16043/']} | jdg_80183 |
stackexchange | llm_judgeable_groundtruth_similarity | 1967863 |
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 looked online and was not able to find a working example of the PopupWindow class. The code examples I found online either compile but do not work, or are using methods which have since been removed (such as Activity.getViewInflate()) . Is there a simple working example that displays a PopupWindow?
Now provide the response and nothing else.
| I created a working example based on this Google Groups post. To create a simple working PopupWindow, you'll need to do the following: Create a layout XML which describes the View that will be rendered within the PopupWindow. Invoke the PopupWindow by inflating the layout XML, and assign the appropriate "parent view" to the pop-up. popup_example.xml: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:padding="10dip" android:layout_width="fill_parent" android:layout_height="wrap_content" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:text="Test Pop-Up" /></LinearLayout> Java code: LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); PopupWindow pw = new PopupWindow( inflater.inflate(R.layout.popup_example, null, false), 100, 100, true); // The code below assumes that the root container has an id called 'main' pw.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1967863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53036/']} | jdg_80184 |
stackexchange | llm_judgeable_groundtruth_similarity | 3920934 |
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 looked at the LMFDB page for the following $p$ -adic field : There I noted the notation $\mathbb{Q}_3(\sqrt{*})$ under "unramified subfield". Could you explain me what $*$ is supposed to be? I think the square root makes sense as the extension is of degree $2$ , so it is cyclic. Maybe the square root should just signify that the extension is cyclic but I am not sure.
Now provide the response and nothing else.
| That notation only seems to be used in the LMFDB for quadratic extensions. I don't see anywhere in the LMFDB where the meaning of this notation is spelled out; I'll ask around and see if we can add a line somewhere explaining it. Anyway, to work out what it means, let's look at the structure of quadratic extensions of $\newcommand{\QQ}{\mathbb{Q}}\newcommand{\ZZ}{\mathbb{Z}}\QQ_p$ . As with any field not of characteristic $2$ , quadratic extensions of $\mathbb{Q}_p$ correspond to non-identity elements of $\QQ_p^\times/(\QQ_p^\times)^2$ . So, let's look at the structure of this group. For $p \neq 2$ , we have $$\QQ_p^\times \cong \underbrace{p^\ZZ \times \mu_{p-1} \times (1 + p\ZZ_p)}_{\text{written multiplicatively}} \cong \underbrace{\ZZ \times (\ZZ/(p-1)\ZZ) \times \ZZ_p}_{\text{written additively}},$$ where the isomorphism is given by writing each $x \in \QQ_p$ in the form $p^n \zeta (1 + py)$ , where $\zeta^{p-1} = 1$ . For $p = 2$ , we have the slight variant $$\QQ_2^\times \cong \underbrace{2^\ZZ \times \{\pm 1\} \times (1 + 4 \ZZ_2)}_{\text{written multiplicatively}} \cong \underbrace{\ZZ \times (\ZZ/2\ZZ) \times \ZZ_2}_{\text{written additively}}.$$ So we have $$\QQ_p^\times/(\QQ_p^\times)^2 \cong \begin{cases}(\ZZ/2\ZZ)^2 & \text{if } p \neq 2, \\(\ZZ/2\ZZ)^3 & \text{if } p = 2.\end{cases}$$ In particular, for $p \neq 2$ , there are three quadratic extensions of $\QQ_p$ : $$\QQ_p(\sqrt{*}), \quad \QQ_p(\sqrt{p}), \quad \QQ_p(\sqrt{p*}),$$ where $*$ stands in for any non-square in $\ZZ_p^\times$ (they all produce the same quadratic extensions). The extension $\QQ_p(\sqrt{*})$ is unramified and the other two are ramified. The case for $p = 2$ is similar except that we have seven extensions: $$\QQ_2(\sqrt{*}), \QQ_2(\sqrt{2}), \QQ_2(\sqrt{-1}), \QQ_2(\sqrt{-2}), \QQ_2(\sqrt{2*}), \QQ_2(\sqrt{-*}), \QQ_2(\sqrt{-2*}),$$ where $*$ stands in for any non-square in $1 + 4\ZZ_2$ . The first of these is unramified and the rest are ramified. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3920934', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/850925/']} | jdg_80185 |
stackexchange | llm_judgeable_groundtruth_similarity | 628852 |
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 a simple equivalent of $\displaystyle\int_0^\infty\frac{1}{(x+1)(x+2)...(x+n)}dx$ (when $n\rightarrow\infty$) My attempt: I proved by decomposition into simple elements that: $$\int_0^\infty\frac{1}{(x+1)(x+2)...(x+n)}dx=\frac{1}{n!}\displaystyle\sum_{k=1}^n(-1)^kk{n\choose k}\ln k$$
Now provide the response and nothing else.
| Note that$$\begin{align}&\int_0^\infty\frac{(n-1)\,\mathrm{d}x}{(x+1)(x+2)\cdots(x+n)}\\&=\int_0^\infty\frac{\mathrm{d}x}{(x+1)(x+2)\cdots(x+n-1)}-\int_0^\infty\frac{\mathrm{d}x}{(x+2)(x+3)\cdots(x+n)}\\&=\int_0^\infty\frac{\mathrm{d}x}{(x+1)(x+2)\cdots(x+n-1)}-\int_1^\infty\frac{\mathrm{d}x}{(x+1)(x+2)\cdots(x+n-1)}\\&=\int_0^1\frac{\mathrm{d}x}{(x+1)(x+2)\cdots(x+n-1)}\tag{1}\end{align}$$Therefore,$$\begin{align}\int_0^\infty\frac{\mathrm{d}x}{(x+1)(x+2)\cdots(x+n)}&=\frac1{n-1}\int_0^1\frac{\mathrm{d}x}{(x+1)(x+2)\cdots(x+n-1)}\\&=\frac1{n-1}\int_0^1\frac{\Gamma(x+1)}{\Gamma(x+n)}\mathrm{d}x\tag{2}\end{align}$$For $x\in[0,1]$, Gautschi's Inequalty says that $\frac{n^{1-x}}{n!}\le\frac1{\Gamma(x+n)}\le\frac{(n+1)^{1-x}}{n!}$. Furthermore, $1-\gamma\,x\le\Gamma(x+1)\le1$ for $x\in[0,1]$. Thus, $(2)$ is greater than or equal to$$\frac1{(n-1)n!}\int_0^1(1-\gamma\,x)n^{1-x}\,\mathrm{d}x=\frac1{n!\log(n)}\left(1-\gamma\left(\frac1{\log(n)}-\frac1{n-1}\right)\right)\tag{3}$$and less than or equal to$$\frac1{(n-1)n!}\int_0^1(n+1)^{1-x}\,\mathrm{d}x=\frac{n}{n-1}\frac1{n!\log(n+1)}\tag{4}$$Therefore,$$\int_0^\infty\frac{\mathrm{d}x}{(x+1)(x+2)\cdots(x+n)}\sim\frac1{n!\log(n)}\tag{5}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/628852', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_80186 |
stackexchange | llm_judgeable_groundtruth_similarity | 10385364 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Instead of opening several transactions (read a table, write to a table, write to another table, etc) is it possible to do this all from a single transaction as long as you are using an appropriate IDBTransaction? Mozilla says: "The only way to keep the transaction active is to make a request on it. When the request is finished you'll get a DOM event and, assuming that the request succeeded, you'll have another opportunity to extend the transaction during that callback." which is a little vague. Does that mean if I provide an event handler for the DOM callback that I can use the transaction at any point in that callback without ever having to worry about the transaction being closed? https://developer.mozilla.org/en/IndexedDB/Using_IndexedDB#Adding_data_to_the_database
Now provide the response and nothing else.
| IndexedDB transactions commit as soon as the last callback is fired, so the way to keep them alive is to pass them along via callbacks. I'm sourcing my transaction info from Jonas Sicking, a Mozilla dev and co-spec writer for IndexedDB, who commented on this excellent blog post to say the following: The following sentence isn't correct "Transactions today auto-commit when the transaction variable goes out of scope and no more requests can be placed against it". Transaction never automatically commit when a variable goes out of scope. Generally they only commit when the last success/error callback fires and that callback schedules no more requests. So it's not related to the scope of any variables. The only exception to this is if you create a transaction but place no requests against it. In that case the transaction is "committed" (whatever that means for a transaction which has no requests) as soon as you return to the event loop. In this scenario you could technically "commit" the transaction as soon as all references to it go out of scope, but it's not a particularly interesting use case to optimize. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10385364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1358767/']} | jdg_80187 |
stackexchange | llm_judgeable_groundtruth_similarity | 1990186 |
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 must be something simple I am missing. I'm trying to get the index of the element but keep getting -1. HTML: <div id="rating_boxes"><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /><img src="/img/ratingbox.gif" class="ratingbox" alt="Rate this Speech" /></div> jQuery: $("img.ratingbox").hover(function() { var index = $(this).parent().index(this); // have also tried $("#rating_boxes").index(this); // and $("#rating_boxes").index($(this)); // and $(this).parent().index($(this)); alert(index); $(this).attr('src', '/img/ratingbox-selected.gif');}, function() { $(this).attr('src', '/img/ratingbox.gif');});
Now provide the response and nothing else.
| I tend to steer clear of using index() in jQuery 1.3.2 and previous as it feels unintuitive to use. I simply use $(this).prevAll().length to get the index. calling size() on prevAll() simply returns the value of the length property, so I prefer to just use length directly and skip the extra function call. For example, $("img.ratingbox").hover(function() { var index = $(this).prevAll().length; alert(index); $(this).attr('src', '/img/ratingbox-selected.gif');}, function() { $(this).attr('src', '/img/ratingbox.gif');}); In jQuery 1.4, you'll simply be able to call index() on a jQuery object to get the index of the first element in the object. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1990186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47278/']} | jdg_80188 |
stackexchange | llm_judgeable_groundtruth_similarity | 29119880 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to generate the inverse matrix using numpy package in python. Unfortunately , I'm not getting the answers I expected. Original matrix: ([17 17 5] [21 18 21] [2 2 19]) Inverting the original matrix by Cramer's rule gives: ([4 9 15] [15 17 6] [24 0 17]) Apparently using numpy.linalg.inv() gives -3.19488818e-01,3.80191693e-01,-6.38977636e-03,3.33333333e-01, -3.33333333e-01, 2.26123699e-18, -2.84345048e-01, 2.68370607e-01, 5.43130990e-02n I expected that multiplying the original matrix and the inverse would have given an identity matrix but as you can see I give a matrix filled with floating points. Where can be the issue?
Now provide the response and nothing else.
| This is probably caused by having GridView inside of ScrollView . Since both layouts are scrollable this causes a lot of problems, in your case the height of GridView cannot be properly determined and the scroll events are eaten by the ScrollView . With ListView you can simply declare the ListView as root element and then add other scrollable content as headers or footers. GridView natively does not support this but fortunately there is subclass implementation of HeaderGridView which solves this problem. What you should do is put only the HeaderGridView to your xml inflated by the activity. <?xml version="1.0" encoding="utf-8"?><your.package.HeaderGridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:horizontalSpacing="10dp" android:numColumns="2" android:verticalSpacing="10dp" /> and then implement the RelativeLayout as a header view in different xml (for example header.xml ) <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/relativeLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_marginTop="5dp" android:background="@android:color/background_light" android:gravity="center" android:paddingBottom="5dp"> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView3" android:layout_below="@+id/textView3" android:text="Venue, Date" android:textSize="12sp" /> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView4" android:layout_below="@+id/textView4" android:text="Description" android:textSize="12sp" android:paddingBottom="5dp" /> <ImageView android:id="@+id/imageView7" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView2" android:layout_marginTop="14dp" android:src="@drawable/demo" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="5dp" android:text="Event of the Week" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/imageView7" android:layout_marginLeft="14dp" android:text="Event Name" /> <TextView android:id="@+id/textView6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView5" android:layout_centerHorizontal="true" android:layout_marginTop="14dp" android:text="Today's Events" /></RelativeLayout> In your activity you add the header to your HeaderGridView HeaderGridView gridView = (HeaderGridView) findViewById(R.id.gridView1);View header = getLayoutInflater().inflate(R.layout.header, gridView, false);gridView.addHeaderView(header);// set adapter AFTER adding headerViewsgridView.setAdapter(MyAdapter(...)) Tried it, worked like a charm. Hope it helps! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29119880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4684729/']} | jdg_80189 |
stackexchange | llm_judgeable_groundtruth_similarity | 5897 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In Hartshorne p. 109 he defines a sheaf $\mathcal{F}$ of $O_X$ -modules to be locally free if there is an open cover of $X$ , s.t. on each $U$ , $\mathcal{F}|_U$ is a free $O_X|_U$ module of rank $I$ . Then if $X$ is connected, rank $I$ is globally well-defined. Here $(X,O_X)$ is any ringed topological space (e.g. not necessarily the structure sheaf of a ring). A similar definition is here: Locally free sheaf - Encyclopedia of Mathematics . However, it didn't seem obvious to me that if $V$ is a smaller open set included in $U$ (say $U$ connected), then the number of copies $J$ of $(O_X|_V)^J=\mathcal{F}|_V$ would remain the same, because in general the restriction map of the sheaf $O_X$ or $\mathcal{F}$ from $U$ to $V$ need be neither subjective nor injective, why would the index $J$ stay the same as $I$ ?
Now provide the response and nothing else.
| Actually, there are two different restriction maps: The first one (the one you correctly say is neither surjective nor injective in general) is that on sections : for $\mathcal{F}$ a sheaf on a scheme $X$ and two open subsets $V \subseteq U$, there is a map $\mathcal{F}(U) \to \mathcal{F}(V)$. On the other hand, the inclusion map $i_{VU}: V \to U$ induces a functor $i_{VU}^{-1}$ from the category of sheaves on $U$ to the category of sheaves on $V$. This is called restriction of sheaves . By functoriality, $W \subseteq V \subseteq U$ yields $i_{WV}^{-1}\circ i_{VU}^{-1} = i_{WU}^{-1}$, so the notation is usually shortened to just $ -|_{W}$. The second one is the one that you want to look at: the statement is then that $\mathcal{F}|_{U} \cong \mathcal{O}_X^{\oplus I}|_{U}$ implies $\mathcal{F}|_{V} \cong \mathcal{O}_X^{\oplus I}|_{V}$ for $V \subseteq U$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/5897', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1877/']} | jdg_80190 |
stackexchange | llm_judgeable_groundtruth_similarity | 26168363 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two 2-d numpy arrays with the same dimensions, A and B, and am trying to calculate the row-wise dot product of them. I could do: np.sum(A * B, axis=1) Is there another way to do this so that numpy is doing the row-wise dot product in one step rather than two? Maybe with tensordot ?
Now provide the response and nothing else.
| This is a good application for numpy.einsum . a = np.random.randint(0, 5, size=(6, 4))b = np.random.randint(0, 5, size=(6, 4))res1 = np.einsum('ij, ij->i', a, b)res2 = np.sum(a*b, axis=1)print(res1)# [18 6 20 9 16 24]print(np.allclose(res1, res2))# True einsum also tends to be a bit faster. a = np.random.normal(size=(5000, 1000))b = np.random.normal(size=(5000, 1000))%timeit np.einsum('ij, ij->i', a, b)# 100 loops, best of 3: 8.4 ms per loop%timeit np.sum(a*b, axis=1)# 10 loops, best of 3: 28.4 ms per loop | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26168363', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/99989/']} | jdg_80191 |
stackexchange | llm_judgeable_groundtruth_similarity | 7377 |
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 am trying to plot a function in which is piecewise defined. I found the Fourier coefficients of this, and my question is how to define even & odd conditions for the Piecewise command? I used 2n and 2n+1 for even & odd respectively, but this does not suffice. I have a MWE below. Clear[f,a,b,F]f[t_]=Piecewise[{{-Sqrt[9+t+t^2],-2<t<0},{Exp[Sin[t]],0<=t<=2}}]a0=23/9;a[k_]=Piecewise[{{20/(k^4Pi^4),2k},{-83/(k Pi),2k+1}}]b[k_]=Piecewise[{{-92/(k^3 Pi^3),2k},{-53/(k Pi)+14/(k^2 Pi^2),2k+1}}]F[t_]=a0/2+Sum[a[k]Cos[(k Pi t)/2]+b[k]Sin[(k Pi t)/2],{k,1,20}];Plot[{f[t],F[t]},{t,-1,1}]
Now provide the response and nothing else.
| Instead of using Piecewise you can also use Mathematicas pattern matching, which i think makes for more idiomatic Mathematica code in your case: a0 = 23/9;a[k_?EvenQ] := 20/(k^4 Pi^4)a[k_?OddQ] := -83/(k Pi)b[k_?EvenQ] := -92/(k^3 Pi^3)b[k_?OddQ] := -53/(k Pi) + 14/(k^2 Pi^2)F[t_] = a0/2 + Sum[a[k] Cos[(k Pi t)/2] + b[k] Sin[(k Pi t)/2], {k, 1, 1000}];Plot[F[t], {t, -1, 1}] You could even get rid of the OddQ tests and let the pattern matcher just 'fall through' the EvenQ test to get to the second definition: a[k_?EvenQ] := 20/(k^4 Pi^4)a[k_] := -83/(k Pi) (* odd case*)b[k_?EvenQ] := -92/(k^3 Pi^3)b[k_] := -53/(k Pi) + 14/(k^2 Pi^2) (* odd case*) alternatively you could use /; for stating the condition a[k_] := 20/(k^4 Pi^4) /; EvenQ[k]a[k_] := -83/(k Pi) /; OddQ[k]b[k_] := -92/(k^3 Pi^3) /; EvenQ[k]b[k_] := -53/(k Pi) + 14/(k^2 Pi^2) /; OddQ[k] . The same with 'fall through': a[k_] := 20/(k^4 Pi^4) /; EvenQ[k]a[k_] := -83/(k Pi)b[k_] := -92/(k^3 Pi^3) /; EvenQ[k]b[k_] := -53/(k Pi) + 14/(k^2 Pi^2) | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/7377', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/116/']} | jdg_80192 |
stackexchange | llm_judgeable_groundtruth_similarity | 31484273 |
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 matplotlib plot in python with 3 subplots, all in 1 column. I currently control the height of each subplot with: gridspec.GridSpec(3, 1, height_ratios=[1, 3, 3]) I have no spacing via: plt.subplots_adjust(hspace=0.0) But I would like to put some spacing between row 2 and 3 only. In one of the other answers, I read that I can do something like: gs1.update(left=0.05, right=0.48, wspace=0) But I don't really understand what is happening. Could someone give me some more information please?
Now provide the response and nothing else.
| When you call update, you're applying those parameters to all of the subplots in that particular gridspec. If you want to use different parameters for different subplots, you can make multiple gridspecs. However, you'll need to make sure they are the correct size and don't overlap. One way do to that is with nested gridspecs. Since the total height of the bottom two plots is 6 times the top, the outer gridspec will have a height ratio of [1, 6]. import matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecdef do_stuff(cell): #just so the plots show up ax = plt.subplot(cell) ax.plot() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False)plt.subplots_adjust(hspace=0.0)#make outer gridspecouter = gridspec.GridSpec(2, 1, height_ratios = [1, 6]) #make nested gridspecsgs1 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec = outer[0])gs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec = outer[1], hspace = .05)for cell in gs1: do_stuff(cell)for cell in gs2: do_stuff(cell)plt.show() | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31484273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1551817/']} | jdg_80193 |
stackexchange | llm_judgeable_groundtruth_similarity | 521313 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have seen people using ferrite beads to suppress EMI from switching power supplies.Recently, I came across the following blog post where the author successfully re-models a switching power supply to reduce EMI noise. At one point, he makes the following comment. It is common to attempt the use of ferrite beads to suppress RF Interference of this sort, but it's very unlikely that it will help much - particularly at lower frequencies (e.g. lower HF bands such as 160 and 80 meters, not to mention the AM broadcast band) because these devices simply cannot add enough inductance to add a significant amount of impedance: At these frequencies (say, below 10 MHz) it takes multiple turns on a chunk of ferrite to add enough reactance to make even a small dent in the amount of conducted interference! My question is that whether the author is right or not? I have read that ferrite beads in EMI filtering, acts as a lossy element and turn the RF energy into heat. Did the author forgot to consider this and only considered the high impedance of an inductor at RF? I'm confused as his strategy worked nevertheless EDIT: But, I have seen another ham successfully build and test an SMPS using ferrite beads. Here is the link and here is the circuit Of course he used quite a handful of ferrite beads.
Now provide the response and nothing else.
| I've designed a number of switching supplies that had to pass various EMC standards starting at 30MHz and up, and I can say that ferrite beads are excellent at frequencies of 100MHz and above, but not all beads are created equal. For lower frequencies I've found they are not entirely useless, especially the 1206 and larger sizes, esp. with modern low-ESR ceramic capacitors in a pi-filter arrangement (bead in series, cap to GND at either end). They work surprisingly well for 3 reasons : The bead adds a small series, non-lossy, inductance (and here, choosing the correct bead with a high series inductance helps a lot) They add a small series resistance. This combined impedance can still significantly dampen frequencies of 10MHz. Simply making provision for a bead forces you to route everything through a single, narrower path, this usually helps the layout. In older designs we used to simply make a pi filter using the same inductor as for the DC2DC converter. This works well for filtering older supplies with lower switching frequencies (and keeps BOM cost down), and for up to a few MHz of noise, but seems to drop off in effectiveness as you approach the SRF of the inductor you chose - but of course you can get quite far with e.g. a 100nF (even if rated at hundreds of volts, if need be) ceramic right at the power entry pins, relying on the wiring inductance to provide the other half of the filter. LTSpice has excellent models of different Wurth ferrite beads, which allow you to see what attenuation can be achieved with even the tiniest of beads and some low-ESR caps. Layout is crucial however, and a good DC2DC converter IC will come with a wealth of good suggestions in the layout advice. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/521313', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/233976/']} | jdg_80194 |
stackexchange | llm_judgeable_groundtruth_similarity | 71282206 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible duplicate, but couldn't find any clear answers. Dependabot cannot update nth-check to a non-vulnerable versionThe latest possible version that can be installed is 1.0.2 because of the following >conflicting dependency: [email protected] requires nth-check@^1.0.2 via a transitive dependency on [email protected] just upgraded to [email protected] from 4.0.0.
Now provide the response and nothing else.
| As Dan Abramov explains in this issue, it is (very likely) a false alarm and can be safely dismissed. More specifically, if you are using CRA and nth-check is referenced only from it, it is not an issue, because CRA is a build tool and the vulnerable code will never get into the resulting application bundle and thus will never be called by client code. You can verify this by moving "react-scripts" into "devDependencies" in package.json and running npm audit --production . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/71282206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8933996/']} | jdg_80195 |
stackexchange | llm_judgeable_groundtruth_similarity | 124667 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How to compute the following limit? $\lim\limits_{n\to\infty} n·(\sqrt[n]{a}-1)$ We know that it's got something to do with $\ln$ or $\exp$. We know that $\lim\limits_{n\to\infty} \sqrt[n]{a} = 1$ but it seems to not to be true that therefore $\lim\limits_{n\to\infty} n·(\sqrt[n]{a}-1) = \lim\limits_{n\to\infty} n·(1-1) = 0$. What we know is $\lim\limits_{n\to\infty} (1-\frac{1}{n})^n = \lim\limits_{n\to\infty} (1 + \frac{1}{n})^n \lim\limits_{n\to\infty} (1-\frac{1}{n})^{n+1} = e$ and $\lim\limits_{n\to\infty} (1+\frac{x}{n})^n = \exp(x)$
Now provide the response and nothing else.
| Substitute $t=\frac{1}{n}$ , hence : $L=\displaystyle \lim_{t \to 0} \frac{a^t-1}{t}$ Now , apply L'Hopital rule ,hence : $L=\displaystyle \lim_{t \to 0} a^t \cdot \ln a=\ln a$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/124667', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/27584/']} | jdg_80196 |
stackexchange | llm_judgeable_groundtruth_similarity | 25848991 |
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 convert InputStream into CSVReader . When I am using the code below CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE)); it is working fine, but, if I fetch the file from class path, then this code is not working. How do I convert a InputStream to CSVReader ? This is not working cause InputStream is not a string type: InputStream input = ImportCsv.class.getResourceAsStream("/dataUpload/staff.csv");CSVReader reader = new CSVReader(new FileReader(input));
Now provide the response and nothing else.
| Use CSVReader reader = new CSVReader(new InputStreamReader(input)); Edit to answer the comment The problem is because you don't have any constructor for FileReader as you want. See the FileReader API for details. But since you will have to convert the byte stream to character stream so you will have to use InputStreamReader . For better performance you can wrap it with a BufferedReader also | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25848991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3011731/']} | jdg_80197 |
stackexchange | llm_judgeable_groundtruth_similarity | 12928294 |
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 taking the backup of SQLite DB using cp command after running wal_checkpoint(FULL). The DB is being used in WAL mode so there are other files like -shm and -wal in my folder.When I run wal_checkpoint(FULL), the changes in WAL file get committed to the database. I was wondering whether -wal and -shm files get deleted after running a checkpoint. If not, then what do they contain ? I know my backup process is not good since I am not using SQLite backup APIs. This is a bug in my code.
Now provide the response and nothing else.
| After searching through numerous sources, I believe the following to be true: The -shm file contains an index to the -wal file. The -shm file improves performance when reading the -wal file. If the -shm file gets deleted, it get created again during next database access. If checkpoint is run, the -wal file can be deleted. To perform safe backups: It is recommended that you use SQLite backup functions for making backups. SQLite library can even make backups of an online database. If you don't want to use (1), then the best way is to close the database handles. This ensures a clean and consistent state of the database file, and deletes the -shm and -wal files. A backup can then be made using cp , scp etc. If the SQLite database file is intended to be transmitted over a network, then the vacuum command should be run after checkpoint . This removes the fragmentation in the database file thereby reducing its size, so you transfer less data through network. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12928294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1387429/']} | jdg_80198 |
stackexchange | llm_judgeable_groundtruth_similarity | 22183185 |
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 do required validation in a asp.net page. I have multiple controls that will be hidden and displayed. Controls like checkboxlist , dropdownlist , multiselectedlistbox . I am using a css class called required attaching to all these controls to check the validation. I am trying to check if each control has value or not but my code is checking each options with in each controls. I am really not finding a way not a jquery expert just a novice... Here is my code any ideas anyone please.... $("input[type='submit']").click(function () { if ($(this).val() != 'Back') { var names = []; var info=" "; $('.required input').each(function () { var control = $(this); if (control.is(':enabled')) { names[$(this).attr('name')] = true; } }); $('.required option').each(function () { var control = $(this); if (control.is(':enabled')) { names[$(this).attr('name')] = true; } }); for (name in names) { var radio_buttons = $("input[name='" + name + "']"); if ((radio_buttons.filter(':checked').length == 0) ||(radio_buttons.filter(':selected').length == 0)) { info += radio_buttons.closest("table").find('label').html()+"</br>"; } } if (info != " ") { $("#validation_dialog p").html(info); $("#validation_dialog").dialog({ title: "Validation Error!", modal: true, resizable: false, buttons: { Close: function () { $(this).dialog('close'); } } }); return false; } } }); here is a fiddle for it... http://jsfiddle.net/bDmgk/35/
Now provide the response and nothing else.
| I see a couple of issues with the request mapped method: Ideally, you should have a @ResponseBody annotation on your method, to indicate that the returned content is to be streamed out: @RequestMapping(value = "index", method = RequestMethod.GET)@ResponseBodypublic HashMap<String, String> handleRequest() { HashMap<String, String> model = new HashMap<String, String>(); String name = "Hello World"; model.put("greeting", name); return model;} Now with this done, your test can look like this: mockMvc.perform(get("/index").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("application/json")) .andExpect(jsonPath("$.greeting").value("Hello World")); In your case, what is happening is Spring is trying to figure out the view name and is getting the view name as index , which is again the controller path, thus the circular view path error that you are seeing. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22183185', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2664298/']} | jdg_80199 |
stackexchange | llm_judgeable_groundtruth_similarity | 1898920 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am looking for a syntax to allocate memory from a secondary memory device and not from the default heap. How can i implement it? Using malloc() would by default take it from heap... Surely there must be another way!
Now provide the response and nothing else.
| #include <new>void* operator new(std::size_t size) throw(std::bad_alloc) { while (true) { void* result = allocate_from_some_other_source(size); if (result) return result; std::new_handler nh = std::set_new_handler(0); std::set_new_handler(nh); // put it back // this is clumsy, I know, but there's no portable way to query the current // new handler without replacing it // you don't have to use new handlers if you don't want to if (!nh) throw std::bad_alloc(); nh(); }}void operator delete(void* ptr) throw() { if (ptr) { // if your deallocation function must not receive null pointers // then you must check first // checking first regardless always works correctly, if you're unsure deallocate_from_some_other_source(ptr); }}void* operator new[](std::size_t size) throw(std::bad_alloc) { return operator new(size); // defer to non-array version}void operator delete[](void* ptr) throw() { operator delete(ptr); // defer to non-array version} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1898920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/228492/']} | jdg_80200 |
stackexchange | llm_judgeable_groundtruth_similarity | 20570 |
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:
My .muttrc file looks something like this one or see below a glimpse. I am hesitant with the password. How should I store my password to use it with mutt ? set imap_user = "[email protected]"set imap_pass = "password"set smtp_url = "smtp://[email protected]:587/"set smtp_pass = "password"set from = "[email protected]"set realname = "Your Real Name"
Now provide the response and nothing else.
| This tweak should get rid of your problem. Use gpg as suggested, or set imap_pass=`getpassword email_id` where you use pwsafe or passwords to fetch the passwords. Edit: If mutt is built with IMAP support (--enable-imap), then mutt should prompt you for the password if you do not set it in the config file. From the manual: imap_pass Type: string Default: "" Specifies the password for your IMAP account. If unset, Mutt will prompt you for your password when you invoke the fetch-mail function. Warning: you should only use this option when you are on a fairly secure machine, because the superuser can read your muttrc even if you are the only one who can read the file. | {} | {'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/20570', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']} | jdg_80201 |
stackexchange | llm_judgeable_groundtruth_similarity | 44450778 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have one from through which I am entering project name and sheet name which will be saved in project table. Based on this I am inserting empty values on another table 'Data'. I am using editable table to update these empty values in database. I want to hide this table till project name and sheet name is submitted and once value is submitted then only table will be displayed. I have tried a lot but after clicking submit button my table gets displayed till page is reloaded and disappers when loading is completed. My code parts are like below. <script> $(function(){ $('button#showit').on('click',function(){ $('#myform').show(); }); }); </script> <form class="form-horizontal" action="db.php" id="#form1" onSubmit="function();" method="post"> <input type="text" class="form-control1" name="projectname" id="projectname" required > <input type="text" class="form-control1" name="sheetname" id="sheetname" required > <button type="submit" name="submit" id="button" class="btn- success btn" >Submit</button> </form> <div class="tab-content" id="myform" style="display:none"> <div class="tab-pane active" id="horizontal-form"> <?php $s4 = "SELECT * FROM data ORDER BY data_id DESC LIMIT 1"; $res = mysqli_query($bd, $s4); while ($row = mysqli_fetch_array($res)) { ?> <table class="table table-bordered" style="width:50%;"> <thead> <tr> <th>Sr.no</th> <th>Column Name</th> </tr> </thead> <tbody> <tr class="odd"> <td>1</td> <td id="d1:<?php echo $row['data_id']; ?>" contenteditable="true"><?php echo $row['d1']; ?></td> </tr> . . . </tbody> </table> <?php } ?> </div> </div> on db.php I have used to get back on my previous page <script> alert('Sheet Created Successfully'); window.location.href='index.php?success'; </script>
Now provide the response and nothing else.
| The issue is that I can't access the variable subscription in the body of my callback, since it is still not created at the time That's correct - you cannot access is the subscription variable , even if you know that the subscription itself would exist. Dart doesn't allow variables declarations to refer to themselves. That's occasionally annoying when the variable it's only referenced inside a closure that won't be executed yet. The solution is to either pre-declare the variable or to update the onData -listener after doing the listening: // Pre-declare variable (can't be final, and with null safety // it has to be late). late StreamSubscription<Map<PlaceParam, dynamic>> subscription; subscription = stream.listen((event) { .... subscription.cancel(); }); or final subscription = stream.listen(null); subscription.onData((event) { // Update onData after listening. .... subscription.cancel(); .... }); There can be cases where you can't access the subscription object yet, but that's only possible if the stream breaks the Stream contract and starts sending events immediately when it's listened to. Streams must not do that, they must wait until a later microtask before delivering the first event, so that the code that called listen has time to, say, receive the subscription and assign it to a variable. It's possible to violate the contract using a synchronous stream controller (which is one reason why synchronous stream controllers should be used judiciously). (This answer provided was updated for null safety. Prior to Dart 2.12, the former proposal didn't need the late , and was generally the preferred approach. With Dart 2.12 and null safety, the latter approach will likely be better.) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44450778', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8001200/']} | jdg_80202 |
stackexchange | llm_judgeable_groundtruth_similarity | 51650916 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Aside from using IdleJS and ngDoCheck(), how can we detect user inactivity in Angular 5? Thanks
Now provide the response and nothing else.
| You could try with this : export class AppComponent { userActivity; userInactive: Subject<any> = new Subject(); constructor() { this.setTimeout(); this.userInactive.subscribe(() => console.log('user has been inactive for 3s')); } setTimeout() { this.userActivity = setTimeout(() => this.userInactive.next(undefined), 3000); } @HostListener('window:mousemove') refreshUserState() { clearTimeout(this.userActivity); this.setTimeout(); }} Seems to work in this stackblitz : open the console, don't move your mouse for 3 seconds : you see the message. Refresh the page, move your mouse on the preview (right side) for a couple of seconds : the message doesn't pop until you stop for 3s. You can obviously export that into a service, because as you can see, I'm using only a class to do that. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51650916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7471307/']} | jdg_80203 |
stackexchange | llm_judgeable_groundtruth_similarity | 10640152 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can insert simple text like this: document = new PDDocument();page = new PDPage(PDPage.PAGE_SIZE_A4);document.addPage(page);PDPageContentStream content = new PDPageContentStream(document, page);content.beginText();content.moveTextPositionByAmount (10 , 10);content.drawString ("test text");content.endText();content.close(); but how can I create a paragraph similar to HTML using the width attribute? <p style="width:200px;">test text</p>
Now provide the response and nothing else.
| Warning : this answer applies to and old version of PDFBox and relies on features that has since been deprecated. See the comments below for more details. According to this answer it's not possible to insert line breaks into some text and have PDF display it correctly (whether using PDFBox or something else), so I believe auto-wrapping some text to fit in some width may also be something it can't do automatically. (besides, there are many ways to wrap a text - whole words only, break them in smaller parts, etc) This answer to another question (about centering a string) gives some pointers on how to do this yourself. Assuming you wrote a function possibleWrapPoints(String):int[] to list all points in the text a word wrap can happen (excluding "zero", including "text length"), one possible solution could be: PDFont font = PDType1Font.HELVETICA_BOLD; // Or whatever font you want.int fontSize = 16; // Or whatever font size you want.int paragraphWidth = 200;String text = "test text";int start = 0;int end = 0;int height = 10;for ( int i : possibleWrapPoints(text) ) { float width = font.getStringWidth(text.substring(start,i)) / 1000 * fontSize; if ( start < end && width > paragraphWidth ) { // Draw partial text and increase height content.moveTextPositionByAmount(10 , height); content.drawString(text.substring(start,end)); height += font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * fontSize; start = end; } end = i;}// Last piece of textcontent.moveTextPositionByAmount(10 , height);content.drawString(text.substring(start)); One example of possibleWrapPoints , that allow wrapping at any point that's not part of a word ( reference ), could be: int[] possibleWrapPoints(String text) { String[] split = text.split("(?<=\\W)"); int[] ret = new int[split.length]; ret[0] = split[0].length(); for ( int i = 1 ; i < split.length ; i++ ) ret[i] = ret[i-1] + split[i].length(); return ret;} Update: some additional info: The PDF file format was designed to look the same in different situations, functionality like the one you requested makes sense in a PDF editor/creator, but not in the PDF file per se . For this reason, most "low level" tools tend to concentrate on dealing with the file format itself and leave away stuff like that. Higher level tools OTOH usually have means to make this conversion. An example is Platypus (for Python, though), that do have easy ways of creating paragraphs, and relies on the lower level ReportLab functions to do the actual PDF rendering. I'm unaware of similar tools for PDFBox, but this post gives some hints on how to convert HTML content to PDF in a Java environment, using freely available tools. Haven't tried them myself, but I'm posting here since it might be useful (in case my hand-made attempt above is not enough). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10640152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/773254/']} | jdg_80204 |
stackexchange | llm_judgeable_groundtruth_similarity | 39796893 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to migrations and I can't find out what to do to get my changes onto the LiveDB. So on dev when I add to my model I do PM> add-migration <name>PM> update-database But what do I do on live? I was HOPING that I could just publish\deploy to live and the migration would run and update the schema, but I guess not :) The Live SQL server is off in its own world I have no access to it from my dev box to just change the connectionstring and doing an update-database again. What do you guys do, where's the docs? Thanks,Steve
Now provide the response and nothing else.
| Updated with sample for 3.0 The Core 3.0 approach is similar to 2.x, but now the generic host is used.You will need to add using Microsoft.Extensions.DependencyInjection; for the CreateScope() public static void Main(string[] args){ var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetService<ShortenerContext>(); db.Database.Migrate(); } host.Run();}public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); Updated with better way for Core 2.0+ Migrations should be run in Program.cs due to tooling like the EF Core CLI tools running the Startup functions in normal execution. Here is an example: public class Program{ public static void Main(string[] args) { var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var db = scope.ServiceProvider.GetService<ShortenerContext>(); db.Database.Migrate(); } host.Run(); } public static IWebHost BuildWebHost(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }} One way to run migrations in 1.x is to just add something like this in app startup: public void Configure( IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ShortenerContext db){ db.Database.Migrate(); //Rest omitted} This will execute all pending migrations against the database on startup. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39796893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1368333/']} | jdg_80205 |
stackexchange | llm_judgeable_groundtruth_similarity | 8112 |
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:
I'm surprised that this question hasn't been asked before (here or on Physics), to the best of my knowledge. It's one that I might have asked when I was a bit younger, and one that I think other people will ask. Anyway, it's clear that Saturn's rings won't form a moon , and the same is likely to be true for other ring systems. However, I'm guessing that they won't last forever (it's just a guess). How long do planetary rings in general last? What mechanisms could cause them to dissipate/fall apart/end? I'm guessing the Poynting-Robertson effect could come into play, but I'm not sure. And for anyone curious, yes, I checked just for the fun of it, and Yahoo Answers had a bunch of really, really bad, unsourced and most likely inaccurate answers (given that there was no consensus), ranging from '3 million years' to '13-18 billion years' to 'forever'.
Now provide the response and nothing else.
| It appears (and I am no expert) that Saturn's ring evolution is governed mainly by "viscous spreading" - collisions between ring particles; and also by interactions with Saturn's moons (resonances); and bombardment with meteoritic material. There appears to be no consensus on how old the ring system is. Most theories of their formation have this taking place early in the life of the solar system, but there are observations that suggest little contamination by meteoritic material and hence that the rings are young. According to Salmon et al. (2010) the viscosity in the ring is critical to its evolution and therefore estimates of ages and lifetimes. As the disc spreads due to viscosity, the viscosity itself will reduce, slowing the evolution and thus the ring system may not empty for many billions of years. On the other hand, comparing viscous spreading models with the current density profile of Saturn's rings suggests they are much less than a billion years old. However, it should be noted that other authors have used similar models to argue that Saturn's rings did indeed form 4.5 billion years ago and were much more massive (by a factor $>100$) then they are today! (Charnoz et al. 2011) | {} | {'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/8112', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/2153/']} | jdg_80206 |
stackexchange | llm_judgeable_groundtruth_similarity | 15163722 |
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 read the content of a CSV file from a zip file in memory(the requirment is not to write to disk) into the MemoryStream. and use to following code to get the human readable string string result = Encoding.ASCII.GetString(memoryStream.ToArray()); However, we would like the result to be a string[] to map each row in the CSV file. Is there a way to handle this automatically? Thanks
Now provide the response and nothing else.
| Firstly, there's no need to call ToArray on the memory stream. Just use a StreamReader , and call ReadLine() repeatedly: memoryStream.Position = 0; // Rewind!List<string> rows = new List<string>();// Are you *sure* you want ASCII?using (var reader = new StreamReader(memoryStream, Encoding.ASCII)){ string line; while ((line = reader.ReadLine()) != null) { rows.Add(line); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15163722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/466587/']} | jdg_80207 |
stackexchange | llm_judgeable_groundtruth_similarity | 23080557 |
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 use case is to use Redis to be local cache of MySQL The data format in MySQL is: a single primary key and several other fields. There will not be queries cross table of db Redis key is primary key in MySQL, and value is hash containing other fields in MySQL When power off, less than one minute data lose is acceptable. My solution is: Redis writes AOF file, some process will monitor this file and sync the updated datas to MySQL Hack Redis to write AOF in several files, just like MySQL binlog The data interface will only read and write through Redis Is this solution OK? And what's the best strategy to do this job?
Now provide the response and nothing else.
| You don't need to hack anything ;) I am not entirely sure why you need the data on mysql. If I knew, maybe there would be a more suitable answer. In any case, as a generic answer you can use redis keyspace notifications You could subscribe to the commands HSET, HMSET, HDEL and DEL on your keys, so you would get a notification everytime a key is deleted or a hash value is set or removed. Note if you miss any notification you would have an inconsistency. So once in a while you could just use the SCAN command to go through all your keys and check on mysql if they need to be updated. Another strategy could be maintaining two separate structures. One would be the hash with the values, and the other would be a ZSET of all the values sorted by timestamp of update. The best way to keep both structures up to date would be to write two or three lua scripts (insert/update and delete) that would operate on the hash and the zset atomically. Then you can just periodically query the ZSET for the elements with a timestamp higher than your last sync operation, get all the keys that were updated (it would include deleted keys, unless you want to keep a second ZSET exclusively for those) and then just retrieve all the elements by key and sync to mysql. Hope it will work for you! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23080557', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/637034/']} | jdg_80208 |
stackexchange | llm_judgeable_groundtruth_similarity | 3727 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the following extremely simple approximation algorithm for the TSP. Input: A complete weighted graph $G=(V,E).$ Take any three vertices $a,b,c\in V$ and let $H:=(a,b,c,a).$ While there are vertices in V that are not in H: Take one of them, say $v.$ Let $H=(v_1,v_2,...,v_k,v_1),$ where $k$ is the number of distinct vertices currently contained in $H.$ Take as new $H$ the shortest of all the Hamiltonian cycles $(v,v_1,v_2,\ldots,v_k,v),$ $(v_1,v,v_2,\ldots,v_k,v_1),$ $(v_1,v_2,v,\ldots,v_k,v_1),$ $\dots,$ $(v_1,v_2,\ldots,v,v_k,v_1),$ i.e., insert $v$ before every vertex in $H$ and find the shortest Hamiltonian cycle among all those. Output: $H.$ Obviously, this algorithm has runtime $O(n^2).$ Can anyone give me a lower (or upper) bound on the approximation ratio of this algorithm? Or a worst-case example, for that matter?
Now provide the response and nothing else.
| This is called an insertion heuristic. The general TSP cannot be approximated unless $P=NP$. The question is more interesting for the metric TSP. In that case, Rosenkrantz et al. (1974) show that your heuristic gives an $O(\log n)$ approximation. You can also try to choose a good vertex $v$ to be inserted in each step, instead of just taking an arbitrary one. One variant is farthest insertion in which $v$ is chosen such that is has maximum distance from the current $H$. Another variant is nearest insertion in which $v$ is chosen such that it has minimum distance from the current $H$. Yet another possibility is cheapest insertion in which $v$ is chosen such that the new $H$ has minimum length. Rosenkrantz et al. show that both nearest and cheapest insertion give a $2-2/n$ approximation and this is tight. The full reference is:D. Rosenkrantz, R. Stearns, and P. Lewis II. An analysis of several heuristics for the traveling salesman problem. SIAM Journal on Computing, 6(3):563-581, 1977. | {} | {'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/3727', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/2701/']} | jdg_80209 |
stackexchange | llm_judgeable_groundtruth_similarity | 6354208 |
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 limit to the number of textures that can be created in OpenGL - that is, with glGenTextures? I know that there are some limits imposed by GL, eg. the number of textures that can be used in a fragment shader. However, I haven't been able to find any sort of documentation concerning the total number of integer "texture names" that are available to use.
Now provide the response and nothing else.
| The only limit of glGenTextures is given by the bit width of the texture name ( GLint ), which is 32 bit; indeed the number of texture names can be so great that you will probably never have problems when generating texture names. The limit for textures is that of the graphics system's memory. The OpenGL implementation knows the texture size and format only when the application submits texture data using glTexImage2D (and other glTexImage* functions if available), which specifies the width, height and the internal texture format: having those parameters it's possible to determine the memory needed to store the texture data. To check errors, you should query OpenGL error using glGetError , which returns GL_OUT_OF_MEMORY if the operation fails to allocate the required memory. This error can also be returned by glGenTextures and glTexImage2D etc. This error is most likely to be returned by glTexImage2D etc., since the memory required for texture allocation is much larger than the memory required for marking a texture name as used. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6354208', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/396311/']} | jdg_80210 |
stackexchange | llm_judgeable_groundtruth_similarity | 15877560 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't have access to the C11 specification, therefore I can't investigate this bug. The following declaration rises an error during compilation: int why[2] = 1 == 1 ? {1,2} : {3,4}; The error is: expected expression before { and: expected expression before :
Now provide the response and nothing else.
| This is not valid C11. You can only initialize an array with an initializer-list not with an expression. int why[2] = { ... }; // initializer-list {} Moreover, 1 == 1 ? {1,2} : {3,4} is not a valid C expression because {1, 2} is not a C expression. Just for information using compound literals you can have something close to what you want using a pointer object: int *why = (1 == 1) ? (int[2]) {1,2} : (int[2]) {3,4}; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15877560', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/753618/']} | jdg_80211 |
stackexchange | llm_judgeable_groundtruth_similarity | 3921275 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Working in Office 2007, I'd like to add a filename field in my document header. The document will later be a PDF, so I don't want the extension. I've played with Insert -> QuickParts -> Field, to no avail. I've got a gut feeling that it requires a formula... Thanks in advance if you can help.
Now provide the response and nothing else.
| Your feeling is quite right. Insert > QuickParts > Field > FileName is the way to go, but as you see from the screenshot below, you do not have the option to turn the file extension on or off. To show or not to show (Shakespearean style) the extension is purely up to the Windows Explorer setting to show or hide known file extensions. So, either you change that setting or you need some code. A very simple Macro would be the following: Sub InsertCurrentFileName() Selection.InsertBefore Text:=Left(ActiveDocument.Name, Len(ActiveDocument.Name) - 4)End Sub What it does is simply strip the last 4 characters of the "Filename string" e.g. ".doc" - if you safe a ".docx" the "." would be preserved. Also this Macro would run once and you would need to run it again when the filename changes. Maybe you could explain some more what you want to achieve with having the filename in the document header? Are you trying to use the filename in the document header to set some PDF property during conversion? Why not use the Document Title? Do you need the original filename in the PDF later - why? Two more pages to help you with your problem (both relying on Macros...): insert filename without extension .doc using fields? Inserting a File Name without an Extension | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3921275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/385273/']} | jdg_80212 |
stackexchange | llm_judgeable_groundtruth_similarity | 333225 |
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:
https://www.centos.org/docs/5/html/5.2/Deployment_Guide/s3-proc-self.html says The /proc/self/ directory is a link to the currently running process. There are always multiple processes running concurrently, so which process is "the currently running process"? Does "the currently running process" have anything to do with which process is currently running on the CPU, considering context switching? Does "the currently running process" have nothing to do with foreground and background processes?
Now provide the response and nothing else.
| This has nothing to do with foreground and background processes; it only has to do with the currently running process. When the kernel has to answer the question “What does /proc/self point to?”, it simply picks the currently-scheduled pid , i.e. the currently running process (on the current logical CPU). The effect is that /proc/self always points to the asking program's pid; if you run ls -l /proc/self you'll see ls 's pid, if you write code which uses /proc/self that code will see its own pid, etc. | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/333225', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']} | jdg_80213 |
stackexchange | llm_judgeable_groundtruth_similarity | 14131608 |
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 wanted to try my luck in threading with C#, I know a few things about threading in C. So I just wanted to ask if i wanted to terminate a thread, I should do it with smt.Abort() or it will "kill itself" after the function ends? Also, is there something like pthread_exit() in C in C#?
Now provide the response and nothing else.
| Thread.Abort will "kill" the thread, but this is roughly equivalent to: Scenario: You want to turn off your computer Solution: You strap dynamite to your computer, light it, and run. It's FAR better to trigger an "exit condition", either via CancellationTokenSource.Cancel , setting some (safely accessed) "is running" bool, etc., and calling Thread.Join . This is more like: Scenario: You want to turn off your computer Solution: You click start, shut down, and wait until the computer powers down. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14131608', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1675001/']} | jdg_80214 |
stackexchange | llm_judgeable_groundtruth_similarity | 37257975 |
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 cloned a laravel repo to my CentOS 7 box. When I try to run it, I get a 500 error with nothing displayed. So I check out /var/log/httpd/error_log and I see that I've got some permissions errors: [Mon May 16 11:39:32.996441 2016] [:error] [pid 2434] [client 104.156.67.195:39136] PHP Fatal error: Uncaught UnexpectedValueException: The stream or file "/var/www/html/MYSITE/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/html/MYSITE/bootstrap/cache/compiled.php:13701Stack trace:#0 /var/www/html/MYSITE/bootstrap/cache/compiled.php(13635): Monolog\\Handler\\StreamHandler->write(Array)#1 /var/www/html/MYSITE/bootstrap/cache/compiled.php(13396): Monolog\\Handler\\AbstractProcessingHandler->handle(Array)#2 /var/www/html/MYSITE/bootstrap/cache/compiled.php(13494): Monolog\\Logger->addRecord(400, Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException), Array)#3 /var/www/html/MYSITE/bootstrap/cache/compiled.php(13189): Monolog\\Logger->error(Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException), Array)#4 /var/www/html/MYSITE/bootstrap/cache/compiled.php(13160): Illuminate\\Log\\Writer->writeLog('error', Object(Symfony\\Component\\Debug\\Exception\\FatalErrorException), Array)# in /var/www/html/MYSITE/bootstrap/cache/compiled.php on line 13701 I have done the following to try to overcome the issues: chmod -R 775 storagechmod -R 775 vendorchown -R apache:apache storage So it now shows as so: -rwxrwxr-x. 1 apache apache 2156 May 16 11:41 storage/logs/laravel.log But that didn't work. Interestingly enough, I mis-typed some artisan commands earlier and those seemed to add logs to the logfile... I already read/tried: “laravel.log” could not be opened: failed to open stream Error: laravel.log could not be opened log file permission problem
Now provide the response and nothing else.
| Turns out the issue is with selinux I found this answer , which solved my problem. Prove this is the problem by turning off selinux with the command setenforce 0 This should allow writing, but you've turned off added security server-wide. That's bad. Turn SELinux back setenforce 1 Then finally use SELinux to allow writing of the file by using this command chcon -R -t httpd_sys_rw_content_t storage And you're off! | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/37257975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1007638/']} | jdg_80215 |
stackexchange | llm_judgeable_groundtruth_similarity | 44984315 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to use an access token to publish and retrieve from an artifactory npm repo from a CI environment. I have created a Bearer token using the artifactory API but when I try and use that for access in the .npmrc with the format: //mydomain.jrog.io/:_authToken=myveryverylongaccesstokenregistry=https://mydomain.jfrog.io/mydomain/api/npm/npm I always receive 401 errors back. In addition, though perhaps a different issue, if I try to use npm login with my actual artifactory credentials I get the response: adduser Incorrect username or passwordnpm WARN adduser You can reset your account by visiting:npm WARN adduser npm WARN adduser https://npmjs.org/forgotnpm WARN adduser npm ERR! code E403npm ERR! forbidden No oauth npm default login configuration found: org.couchdb.user:myusername The artifactory docs around access tokens explicitly say this is the sort of use case to set up an access token, but the docs around setting up the npm repo alwyas seem to imply you need a real user account and make no mention of access tokens...
Now provide the response and nothing else.
| What is your artifactory version? The "npm login" way is only supported since 5.4 (aka. _authToken), so if you are below that, your only chance is to authenticate with BASIC authentication (aka. _auth). Basic authentication is fairly easy to setup, Artifactory provides an easy entry point to help you set up your .npmrc Launch the following (and do not forget to replace user and encrypted_password with the Artifactory user account you want to authenticate with) curl -u user:encrypted_password https://mydomain.jfrog.io/mydomain/api/npm/auth It will output something like _auth = YourLongBasicAuthTokenalways-auth = trueemail = [email protected] Copy these 3 lines in your .npmrc , and this should work well... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44984315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1357677/']} | jdg_80216 |
stackexchange | llm_judgeable_groundtruth_similarity | 297019 |
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:
In my Linux environment, the file descriptors are located on /dev/fd. Where is the location of stdin, stdout, stderr file descriptor in AIX(unix). I couldn't find them.
Now provide the response and nothing else.
| The question is based on a misconception about the generality of proc filesystems. Systems which implement this (such as Solaris and Linux) have special devices which may be used for scripting, including /dev/fd followed by a file descriptor (number). With Solaris (as well as some BSDs such as MacOS, FreeBSD), /dev/fd is a virtual folder under /dev , while Linux uses a symbolic link to /proc into a (virtual) folder matching your process id. There are no standards for proc filesystems, and details will differ. The BSDs do not use identical schemes: Solaris, MacOS and FreeBSD use symbolic links for the stdin , stdout , stderr into this /dev/fd folder, while NetBSD and OpenBSD do this using a device node (with the same major/minor numbers). But they are similar. The /dev/fd is separate from /proc (which Solaris supports, unlike the BSDs). Checking AIX 5.3 and 7.1 systems, they do implement a proc filesystem, but have no /dev/fd . However, they do have a virtual filesystem /proc , under which you can find your current process-id, and under that is an fd folder with file descriptors. Conventionally, file descriptors are initialized 0, 1, 2 for stdin , stdout , stderr respectively. Further reading: /proc - Contains state information about processes and threads in the system (AIX 7) for fd : Contains files for all open file descriptors of the process. Each entry is a decimal number corresponding to an open file descriptor in the process. If an entity refers to a regular file, it can be opened with normal file semantics. To ensure that the controlling process cannot gain greater access, there are no file access modes other than its own read/write open modes in the controlled process. Directories will be displayed as links. An attempt to open any other type of entry will fail (hence it will display 0 permission when listed). Using the /proc File System and Commands (Oracle/Solaris) fd - file descriptor files (Oracle/Solaris) Linux Filesystem Hierarchy: /proc 3.15 /dev/fd , from Advanced Programming in the UNIX® Environment: UNIX File I/O Says SVR4 supports /dev/fd , however in a quick check only Solaris (versus the other two SVr4: AIX and HPUX) provide that. HPUX also lacks /proc , so that platform has no magic stdin device in either location. The /dev/fd feature was developed by Tom Duff and appeared in the 8th Edition of the Research Unix System. It is supported by SVR4 and 4.3+BSD. It is not part of POSIX.1. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/297019', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/125570/']} | jdg_80217 |
stackexchange | llm_judgeable_groundtruth_similarity | 8892619 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on time based reminder App. in which the user enter his reminder and time for the reminder. The problem is that how to continuously comparing the current time with the user defined time. Any sample code will greatly help. because i am stuck on this point.
Now provide the response and nothing else.
| Comparing the current time vs. the user defined one is not the right design pattern. UIKit offers the NSLocalNotification object that is a more high-level abstraction for your task. Below is a snip of code that create and schedule a local notification at the choosen time: UILocalNotification *aNotification = [[UILocalNotification alloc] init]; aNotification.fireDate = [NSDate date]; aNotification.timeZone = [NSTimeZone defaultTimeZone]; aNotification.alertBody = @"Notification triggered"; aNotification.alertAction = @"Details"; /* if you wish to pass additional parameters and arguments, you can fill an info dictionary and set it as userInfo property */ //NSDictionary *infoDict = //fill it with a reference to an istance of NSDictionary; //aNotification.userInfo = infoDict; [[UIApplication sharedApplication] scheduleLocalNotification:aNotification]; [aNotification release]; Also, be sure to setup your AppDelegate to respond to local notifications, both at startup and during the normal runtime of the app (if you want to be notified even the application is in foreground): - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UILocalNotification *aNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey]; if (aNotification) { //if we're here, than we have a local notification. Add the code to display it to the user } //... //your applicationDidFinishLaunchingWithOptions code goes here //... [self.window makeKeyAndVisible]; return YES;}- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification { //if we're here, than we have a local notification. Add the code to display it to the user} More details at the Apple Developer Documentation . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8892619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/804462/']} | jdg_80218 |
stackexchange | llm_judgeable_groundtruth_similarity | 393181 |
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:
How does one interpret the $x ∈ ℝ^d$ in the context of regression, see below in the following context: I understand the d refers the dimension of the x vector, but I don't get what this notation tells me. Note that I am not familiar with linear algebra, which may explain my confusion.
Now provide the response and nothing else.
| Mathematically, your understanding is correct, $d$ is the dimension of the vector $x$ and so $x$ exists in the real space of dimension $d$ denoted as $\mathbb{R}^d$ . By real space we mean the elements of $x$ are all real numbers. In the context of regression, consider the simple case of $d=1$ . Let's say we have a linear model for a house price $y$ as a function of its size in square feet $x_1$ . Then we just have the linear equation $$y = \theta_1 x_1 + b$$ where $\theta_1$ and $b$ are some model parameters. Now let's say we want to add another variable, the number of bathrooms $x_2$ . Then we can write $$y = \theta_2 x_2 + \theta_1 x_1 + b$$ The more variables we add, the longer this equation becomes. So let's write it in matrix form instead. We can define the column vectors $$\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ ...\\x_d\end{bmatrix}\ \in \mathbb{R}^d\ ,\ \mathbf{\theta} = \begin{bmatrix} \theta_1 \\ \theta_2 \\ ...\\ \theta_d \end{bmatrix}\ \in \mathbb{R}^d$$ So now we can simply write the linear regression problem as $$y = \mathbf{\theta}^T \cdot \mathbf{x} + b$$ Where we've taken the transpose of $\mathbf{\theta}$ to compute its dot product with $\mathbf{x}$ . TL;DR Matrix form let's us write equations in a simpler form, otherwise things get messy when there are many features and many samples in the input space. The equation may look different however the underlying model is the same. Getting familiar with linear algebra would be valuable. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/393181', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/41267/']} | jdg_80219 |
stackexchange | llm_judgeable_groundtruth_similarity | 939 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Are there any laws that govern when elections for President and Duma/Assembly are held in Russia as far as date of the elections? http://en.wikipedia.org/wiki/Elections_in_Russia seems to have nothing covering the dates.
Now provide the response and nothing else.
| Russian Federal Law is actually quite specific on this one and not as arbitrary as argued. For the Duma the president announces the elections for the " first Sunday of the month , in which the previous legislative term ends"("Federal Law on the Elections of State Duma Deputies" of 22 April 2005, chapter 1, article 6, http://base.consultant.ru/cons/cgi/online.cgi?req=doc;base=LAW;n=133801 ) For Presidential elections the Federation Council announces the elections for the " second Sunday of the month , in which the last presidential elections were held and in which six years ago the President of the Russian Federation was elected"("Federal Law on Elections of the President of the Russian Federation" 10 Jan 2003, chapter 1, article 5, http://base.consultant.ru/cons/cgi/online.cgi?req=doc;base=LAW;n=133802;div=LAW;dst=100004 ) As for the presidential elections in 2012, this is however not consistent with the actual dates, as the second Sunday of the month should have been the 11th March. Apparently the 11 was a working day though and that's why the elections were held on the first Sunday, i.e. 4 March 2012. | {} | {'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/939', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/115/']} | jdg_80220 |
stackexchange | llm_judgeable_groundtruth_similarity | 21711 |
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:
Here is my simple example, and in this case function DeleteDuplicates does not work as expected. I want to FindRoot of my function $\chi[\nu]$, and since function $\chi$ is very sensitive to initial guess I decided to generate many initial conditions and leave only those solutions which are distinct. For this purpose I want to apply DeleteDuplicates on the resulting list of solution. Here is the definition of my function: χ[ν_] := 2*PolyGamma[1] - PolyGamma[1/2 + I*ν] - PolyGamma[1/2 - I*ν] Here I generate many solution according to many random initial guesses m = Table[v /. FindRoot[χ[v] == -1.2 - 0.2*I, {v, RandomComplex[]}], {i, 1, 10}] And finally, I want to leave only distinct solutions: DeleteDuplicates[m] Unfortunately, the operation DeleteDuplicates[m] does not change the list m , although there are many identical values. Namely: DeleteDuplicates[m] {1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, 0.0250407 + 1.00352 I, 1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, 1.06423 + 0.0968739 I, 0.0250407 + 1.00352 I, 1.06423 + 0.0968739 I} I'm puzzled. Any help or suggestions are very welcome! Thanks!
Now provide the response and nothing else.
| You would do well to understand the difference between tools that are intended for structural operations and those that are intended for mathematical operations. DeleteDuplicates is of the former, generally speaking. As such it is comparing the exact FullForm of the objects, or at least something close ( caveat ). As b.gatessucks recommends in a comment you can use a mathematical comparison function for the equivalence test of DeleteDuplicates , e.g.: DeleteDuplicates[m, Abs[#1 - #2] < 10^-12 &] {1.06423 + 0.0968739 I, 0.0250407 + 1.00352 I} Incidentally you could also use Union , but the syntax is a bit different. Note the ( ) . Union[m, SameTest -> (Abs[#1 - #2] < 10^-12 &)] {0.0250407 + 1.00352 I, 1.06423 + 0.0968739 I} Using InputForm to show all of the digits of your expression you can see that they are not structurally identical in the (approximate) way that Mathematica "sees" them: m // InputForm {1.0642275928442373 + 0.09687392021742822*I, 1.0642275928442366 + 0.09687392021742817*I, 1.0642275928442366 + 0.09687392021742797*I, 1.064227592844237 + 0.09687392021742822*I, 1.0642275928442373 + 0.09687392021742852*I, 1.0642275928442366 + 0.09687392021742793*I, 1.0642275928442368 + 0.09687392021742801*I, 0.025040728196256346 + 1.0035162552538588*I, 1.0642275928442377 + 0.0968739202174282*I, 1.0642275928442375 + 0.0968739202174283*I} Performance Yves reminded me to mention something about the performance of using a custom comparison function in DeleteDuplicates or Union as I did above. For long lists this is always considerably slower than using the default method. I gave an example with timings in How to represent a list as a cycle . To apply that method here we could Round the numbers beforehand: Round[m, 10^-12] // DeleteDuplicates // N {1.06423 + 0.0968739 I, 0.0250407 + 1.00352 I} I added // N to convert back to machine precision, but the values will not be precisely the same. This probably doesn't matter if you consider numbers this close to be duplicates, but should you want the unchanged numbers you could use GatherBy and get performance not far distant. First /@ GatherBy[m, Round[#, 10^-6] &] Version 10.0 introduced DeleteDuplicatesBy which works similarly to the GatherBy method; it has the following syntax: DeleteDuplicatesBy[m, Round[#, 10^-6] &] However it may not perform as well as GatherBy ; see: DeleteDuplicatesBy is not performing as I'd hoped. Am I missing something? | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/21711', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6470/']} | jdg_80221 |
stackexchange | llm_judgeable_groundtruth_similarity | 2437924 |
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:
For all $|z|<1$, $$|(1-z)e^z-1|\leq |z|^2.$$ Applying Taylor's expansion (does it hold for all $z$?), we have $$\begin{aligned}|(1-z)e^z-1|&=\left|(1-z)\left(1+z+\frac{z^2}{2!}+\frac{z^3}{3!}+\cdots \right)-1~\right|\\&=\left|\left(1+z+\frac{z^2}{2!}+\frac{z^3}{3!}+\cdots \right)-\left(z+z^2+\frac{z^3}{2!}+\frac{z^4}{3!}+\cdots\right)-1~\right|\\&=\left|~\left(\frac{1}{2!}-\frac{1}{1!}\right)z^2+\left(\frac{1}{3!}-\frac{1}{2!}\right)z^3+\cdots~\right|\end{aligned}$$ How should I go on?
Now provide the response and nothing else.
| There is a general phenomenon going on, which is encoded in Weierstrass's result about his elementary factors: if we set $E_n(z) = (1-z)e^{z+z^2/2+\cdots+z^n/n}$, then $|E_n(z)-1|\leqslant |z|^{n+1}$ when $|z|\leqslant 1$. To prove it, you can begin by noting that $$E_n'(z) = -z^ne^{z+z^2/2+\cdots+z^n/n}$$ and that if $t\geqslant 0$, we have $|E_n'(tz)|\leqslant -|z|^n E_n'(t)$ because $|\exp z|\leqslant \exp |z|$. From this it follows now that$$\begin{align}|E_n(z)-1| &= \left|z \int_0^1 E_n'(zt)dt \right| \\&\leqslant -|z|^{n+1} \int_0^1 E_n'(t)dt\\&=-|z|^{n+1}(E_n(1)-E_n(0)) \\&= |z|^{n+1}\end{align}$$ There is a second proof obtained by looking at the Taylor expansion: again, because the Taylor expansion of $E_n'$ starts at $z^n$, the expansion of $E_n-1$ starts at $z^{n+1}$, say $E_n(z) = 1+ \sum_{k>n} a_k z^k$ (because $E_n(0)=1$). Second, all the coefficients $a_k$ are negative from the expression of $E_n'$ and real so $|a_k| = -a_k$, and $E_n(1) = 0$ implies that $- 1 = \sum_{k>n} a_k$. Thus if $|z|\leqslant 1$ we have $$|E_n(z)-1| \leqslant \sum_{k>n} |a_k||z|^k \leqslant -|z|^{n+1}\sum_{k>n}a_k = |z|^{n+1}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2437924', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/304775/']} | jdg_80222 |
stackexchange | llm_judgeable_groundtruth_similarity | 24890675 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to REST API. I want to upload user selected file to the user provided path(remote or local path) using REST API. My html file is having 1 text box and 1 file chooser. User will enter FilePath (local or remote machine folder location) in the text box.Please suggest how to solve this issue. Here is my code: FileUpload.html: : <body> <form action="rest/file/upload" method="post" enctype="multipart/form-data"> <p> Select a file : <input type="file" name="file" size="45" /> </p> <p>Target Upload Path : <input type="text" name="path" /></p> <input type="submit" value="Upload It" /> </form></body> UploadFileService.java @Path("/file")public class UploadFileService { @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormParam("path") String path) { /*String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName();*/ /*String uploadedFileLocation = //10.217.14.88/Installables/uploaded/" + fileDetail.getFileName();*/ String uploadedFileLocation = path + fileDetail.getFileName(); // save it writeToFile(uploadedInputStream, uploadedFileLocation); String output = "File uploaded to : " + uploadedFileLocation; return Response.status(200).entity(output).build(); } // save uploaded file to new location private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try { OutputStream out = new FileOutputStream(new File( uploadedFileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }} Web.xml <display-name>JAXRSFileUploadJerseyExample</display-name><servlet> <servlet-name>jersey-serlvet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.mkyong.rest</param-value> </init-param> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>jersey-serlvet</servlet-name> <url-pattern>/rest/*</url-pattern></servlet-mapping> Exception: HTTP Status 500 - com.sun.jersey.api.container.ContainerException: Exception obtaining parameterstype Exception reportmessage com.sun.jersey.api.container.ContainerException: Exception obtaining parametersdescription The server encountered an internal error that prevented it from fulfilling this request.exceptionjavax.servlet.ServletException: com.sun.jersey.api.container.ContainerException: Exception obtaining parameters com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:425) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) javax.servlet.http.HttpServlet.service(HttpServlet.java:728)root causecom.sun.jersey.api.container.ContainerException: Exception obtaining parameters com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:54) com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:125) com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153) com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203) com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75) com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288) com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108) com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339) com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) javax.servlet.http.HttpServlet.service(HttpServlet.java:728)root causejava.lang.IllegalStateException: The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded com.sun.jersey.server.impl.model.parameter.FormParamInjectableProvider$FormParamInjectable.getValue(FormParamInjectableProvider.java:81) com.sun.jersey.server.impl.inject.InjectableValuesProvider.getInjectableValues(InjectableValuesProvider.java:46) com.sun.jersey.multipart.impl.FormDataMultiPartDispatchProvider$FormDataInjectableValuesProvider.getInjectableValues(FormDataMultiPartDispatchProvider.java:125) com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$EntityParamInInvoker.getParams(AbstractResourceMethodDispatchProvider.java:153) com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:203) com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75) com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:288) com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108) com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147) com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1469) com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1400) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1349) com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1339) com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:537) com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:699) javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Now provide the response and nothing else.
| I have updated signature of method in below class and its working fine.Instead of @FormParam , used @FormDataParam("path") String path and it solved my issue.Below is the updated code: import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import javax.ws.rs.Consumes;import javax.ws.rs.FormParam;import javax.ws.rs.POST;import javax.ws.rs.Path;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;import com.sun.jersey.core.header.FormDataContentDisposition;import com.sun.jersey.multipart.FormDataParam;@Path("/file")public class UploadFileService {@POST@Path("/upload")@Consumes(MediaType.MULTIPART_FORM_DATA)public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("path") String path) { // Path format //10.217.14.97/Installables/uploaded/ System.out.println("path::"+path); String uploadedFileLocation = path + fileDetail.getFileName(); // save it writeToFile(uploadedInputStream, uploadedFileLocation); String output = "File uploaded to : " + uploadedFileLocation; return Response.status(200).entity(output).build();}// save uploaded file to new locationprivate void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try { OutputStream out = new FileOutputStream(new File( uploadedFileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24890675', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2743948/']} | jdg_80223 |
stackexchange | llm_judgeable_groundtruth_similarity | 373503 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
For a compact closed smooth manifold $X$ , the group Diff(X) has a natural homomorphism $\Phi$ to the homeomorphism group Homeo(X). If $X$ has dimension at least $5$ , I'm looking for some general information about the map(s) $\Phi_*$ induced on the homotopy groups of these spaces. I’m mainly interested in the simply connected case but of course would be interested in a more general result. In particular, are the kernel and cokernel of $\Phi_*$ always finite for every homotopy group? This would be my guess, based naively on the statement that a higher-dimensional simply connected manifold has finitely many smoothings. I tried to look in some older literature (eg papers by Burghelea-Lashof) but am a bit overwhelmed by the notation and technicalities. Such a finiteness statement would contrast sharply with the situation in dimension $4$ .
Now provide the response and nothing else.
| No, the statement about the kernel and cokernel being finite is not true. For a closed $d$ -manifold, $d \neq 4$ , smoothing theory identifies the homotopy fibre of $$B\mathrm{Diff}(M) \longrightarrow B\mathrm{Homeo}(M)$$ with (certain path components of) the space of sections of a bundle $$Top(d)/O(d) \longrightarrow E \longrightarrow M$$ constructed from te tangent bundle of $M$ . Supposing for simplicity that $M$ is parallelisable, this space of sections is equivalent to $$\mathrm{map}(M, Top(d)/O(d)).$$ So your question is more or less equivalent to asking about the homotopy groups of $Top(d)/O(d)$ . Until recently it was not even known whether the homotopy groups of $Top(d)/O(d)$ are finitely-generated, but that was proved by Kupers, in Some finiteness results for groups of automorphisms of manifolds . These days quite a bit is known about the rational homotopy groups of these spaces. Using the above formulation of smoothing theory (which goes through unchanged for manifolds with boundary) for the disc $D^d$ , you will find most results are stated for $$B\mathrm{Diff}_\partial(D^d) \simeq \Omega^d_0(Top(d)/O(d)).$$ (Here I have used that $B\mathrm{Homeo}_\partial(D^d) \simeq *$ by the Alexander trick.) Any result which shows that $B\mathrm{Diff}_\partial(D^d)$ has a rationally nontrivial homotopy group provides a counterexample to your finiteness question. For example: $\pi_i(Top(2n)/O(2n)) \otimes \mathbb{Q}=0$ for $i< 4n-2$ , but $$\pi_{4n-2}(Top(2n)/O(2n)) \otimes \mathbb{Q}= \mathbb{Q}.$$ (See Kupers--Randal-Williams On diffeomorphisms of even-dimensional discs .) $\pi_i(Top(2n+1)/O(2n+1)) \otimes \mathbb{Q}=0$ for $i< 2n+5$ , but $$\pi_{2n+5}(Top(2n+1)/O(2n+1)) \otimes \mathbb{Q}= \mathbb{Q}.$$ (This follows from Farrell--Hsiang On the rational homotopy groups of the diffeomorphism groups of discs, spheres and aspherical manifolds .) There are some slides from a talk I recently gave at https://www.dpmms.cam.ac.uk/~or257/MIT2020.pdf , which give some more detail about the state of the art. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/373503', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3460/']} | jdg_80224 |
stackexchange | llm_judgeable_groundtruth_similarity | 182067 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been reading about wires in Wikipedia What am I doing? I am reading about wires thinking that I could by my wide knowledge with bunch of reading be capable of creating simple 8-bit or 16-bit CPU What I know? Proximity effect and Skin effect effect wires, I know how we can produce these, but I don't understand how they actually construct. What I want? I saw many projects on making simple 8-bit CPUs, they use traditional Stranded wires , however, I am not sure what is the frequency of that CPU, but let's say I am trying to make 1Mhz CPU, what kind of cables do I need? Litz wires seem to be used in >500Khz conditions
Now provide the response and nothing else.
| Because you are carrying logic-level signals (a few volts and a few milliamps) you can use pretty much anything you want. I've made 20 MHz logic using 30 gauge solid wire - wire-wrap, to be precise, and it worked fine. What you have to start being careful about are termination and cross-talk. When running a wire much more than the distance equivalent of your rise and fall times (typically a foot or so) you must consider using twisted pair and termination to avoid signal/power reflections. When running many signals together, if you bundle the wires tightly, a transition on one will be radiated and picked up by a neighbor. Separating such wires and making sure they do not run closely in parallel is a good start, but shielding each from its neighbor may be necessary. As I recall, the generally accepted upper limit on wire-wrap boards, which do use separate wires, is about 100 MHz, although this requires care with terminations. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/182067', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/81981/']} | jdg_80225 |
stackexchange | llm_judgeable_groundtruth_similarity | 1028159 |
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 development machine setup with IIS 6. I have 3 websites configured on different IP addresses: Default (All Unassigned)WS1 (192.168.1.250)WS2 (192.168.1.249) I was wondering how IIS determines which site to hit when I specify localhost in the URL? Is this configurable? If so, how do I go about doing this?
Now provide the response and nothing else.
| When IIS responds to an HTTP request is uses 3 pieces of information to figure out what web site it should use to build the response. IP address - The browser uses the name in the address bar to perform a DNS query and get the actual IP address of the host. It sends the http request to that IP address. Port - By default this is 80 for non SSL requests and 443 for SSL. host header - Part of an http request is a host header. This host header matches the domain name of the address requested by the user, including sub-domain or host names. For example: www.foo.com secure.foo.com server1.foo.com subdomain.foo.com server2.subdomain.foo.com , etc. Assumptions based on your question: 1 - Your machine has 3 ip addresses assigned: 192.168.1.250 - assigned as web site 1, name WS1 192.168.1.249 - assigned as web stie 2, name WS2 both WS1 and WS2 are defined in IIS and mapped to the appropriate IP address 2 - You have a 3rd ip address assigned to your machine that is the original IP address. (This may or may not be the case, I'm assuming it to be so since that's what most folks do when the assign IP's to web sites). 3 - The default web site in IIS has the IP address setting of: (All Unassigned) . 4 - You have not specified any host headers or ports in your IIS config. So, when running a browser on your machine you type: http://localhost (no port number), what does IIS do? Per previous replies the browser converts localhost to 127.0.0.1 as the IP address and constructs an HTTP request for that IP address. The host header will be localhost . In this scenario IIS will see that both WS1 and WS2 do not have matching ip addresses and so the default site will be used to process the request. If you wish to have WS1 or WS2 respond to the request, disable the default site and change the IP address setting to (All Unassigned) for either WS1 or WS2. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1028159', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30383/']} | jdg_80226 |
stackexchange | llm_judgeable_groundtruth_similarity | 70262217 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to concat array of the union type in typescript? When I try to use concat with the array of union type, I got this error: This expression is not callable. Each member of the union type '{ (...items: ConcatArray<{...}>[]): { ... }[]; (...items: ({ ... } | ConcatArray<{ ...; }>)[]): { ...; }[]; } | { ...; }' has signatures, but none of those signatures are compatible with each other. CodeSandbox: https://codesandbox.io/s/modern-breeze-qt9mb?file=/src/index.ts Code example: const arr1 = [ { val1: 1, val2: 2, val3: 3 }, { val1: 11, val2: 22, val3: 33 }];const arr2 = [ { val1a: "1a", val2a: "2a", val3a: "3a" }, { val1a: "11a", val2a: "22a", val3a: "33a" }];const arr3 = [ { foo: "lfsfs", bar: "fabgg" }, { foo: "l414g", bar: "fahrh" }];function getRandomArr() { if (Math.random() < 0.5) { return arr2; } else { return arr1; }}//errorconst FinalArr = getRandomArr().concat(arr3);
Now provide the response and nothing else.
| You are following a red herring. Your problem has nothing to do with "arrays of the union type". The problem is that all of the arrays you are trying to concat have elements of different types, and concat requires that the arrays have elements of the same type T : Array<T> { concat(...items: ConcatArray<T>[]): T[]; concat(...items: (T | ConcatArray<T>)[]): T[];} The above is from lib.es5.d.ts . You can quickly simplify the problem and remove the red herring by trying the following code and understanding the error messages: const a = arr1.concat(arr3) // errorconst b = arr2.concat(arr3) // error You original error message was also telling you this: "Each member of the union type... has signatures, but none of those signatures are compatible with each other." As @jsejcksn recommends , "Use spread syntax to combine the arrays", "See tsplay.dev/wOzdRW ". This allows you to concat arrays with mixed element types: const FinalArr = [...getRandomArr(), ...arr3]; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70262217', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11323591/']} | jdg_80227 |
stackexchange | llm_judgeable_groundtruth_similarity | 39213022 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hypothetical situation: Let's say we have 3 models: User Role Permission Let's also say User has a many-to-many relation with Role , and Role has a many-to-many relation with Permission . So their models might look something like this. (I kept them brief on purpose.) class User{ public function roles() { return $this->belongsToMany(Role::class); }}class Role{ public function users() { return $this->belongsToMany(User::class); } public function permissions() { return $this->belongsToMany(Permission::class); }}class Permission{ public function roles() { return $this->belongsToMany(Role::class); }} What if you wanted to get all the Permission s for a User ? There isn't a BelongsToManyThrough . It seems as though you are sort of stuck doing something that doesn't feel quite right and doesn't work with things like User::with('permissions') or User::has('permissions') . class User{ public function permissions() { $permissions = []; foreach ($this->roles as $role) { foreach ($role->permissions as $permission) { $permissions = array_merge($permissions, $permission); } } return $permissions; }} This example is, just one example, don't read too much into it. The point is, how can you define a custom relationship? Another example could be the relationship between a facebook comment and the author's mother. Weird, I know, but hopefully you get the idea. Custom Relationships. How? In my mind, a good solution would be for that relationship to be described in a similar way to how describe any other relationship in Laravel. Something that returns an Eloquent Relation . class User{ public function permissions() { return $this->customRelation(Permission::class, ...); }} Does something like this already exist?
Now provide the response and nothing else.
| The closest thing to a solution was what @biship posted in the comments . Where you would manually modify the properties of an existing Relation . This might work well in some scenarios. Really, it may be the right solution in some cases. However, I found I was having to strip down all of the constraints added by the Relation and manually add any new constraints I needed. My thinking is this... If you're going to be stripping down the constraints each time so that the Relation is just "bare". Why not make a custom Relation that doesn't add any constraints itself and takes a Closure to help facilitate adding constraints ? Solution Something like this seems to be working well for me. At least, this is the basic concept: class Custom extends Relation{ protected $baseConstraints; public function __construct(Builder $query, Model $parent, Closure $baseConstraints) { $this->baseConstraints = $baseConstraints; parent::__construct($query, $parent); } public function addConstraints() { call_user_func($this->baseConstraints, $this); } public function addEagerConstraints(array $models) { // not implemented yet } public function initRelation(array $models, $relation) { // not implemented yet } public function match(array $models, Collection $results, $relation) { // not implemented yet } public function getResults() { return $this->get(); }} The methods not implemented yet are used for eager loading and must be declared as they are abstract. I haven't that far yet. :) And a trait to make this new Custom Relation easier to use. trait HasCustomRelations{ public function custom($related, Closure $baseConstraints) { $instance = new $related; $query = $instance->newQuery(); return new Custom($query, $this, $baseConstraints); }} Usage // app/User.phpclass User{ use HasCustomRelations; public function permissions() { return $this->custom(Permission::class, function ($relation) { $relation->getQuery() // join the pivot table for permission and roles ->join('permission_role', 'permission_role.permission_id', '=', 'permissions.id') // join the pivot table for users and roles ->join('role_user', 'role_user.role_id', '=', 'permission_role.role_id') // for this user ->where('role_user.user_id', $this->id); }); }}// app/Permission.phpclass Permission{ use HasCustomRelations; public function users() { return $this->custom(User::class, function ($relation) { $relation->getQuery() // join the pivot table for users and roles ->join('role_user', 'role_user.user_id', '=', 'users.id') // join the pivot table for permission and roles ->join('permission_role', 'permission_role.role_id', '=', 'role_user.role_id') // for this permission ->where('permission_role.permission_id', $this->id); }); }}You could now do all the normal stuff for relations without having to query in-between relations first. Github I went a ahead and put all this on Github just in case there are more people who are interested in something like this. This is still sort of a science experiment in my opinion. But, hey, we can figure this out together. :) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39213022', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/422356/']} | jdg_80228 |
stackexchange | llm_judgeable_groundtruth_similarity | 978088 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $(X,\| \cdot \|)$ be a finite dimensional normed space. Show that if $S\subseteq X$ is compact, then the $\text{Conv(S)}$ is also compact. I used the Caratheodory's theorem to show that $\text{Conv(S)}=\bigcup_{n=1}^{\dim(X)+1} T_n(S)$, now I need to show that $T_n(S)$ is closed and bounded but I'm stuck. Is this the right way to prove it? If it is how do can I proceed? $T_n(S):=\{x\in X : \sum_{i=1}^n a_i \cdot x_i$ for some $a \in \Delta^{n-1}, \{v_1,...,v_n\} \subseteq S\}$ where $\Delta^{n-1}$ is the $n-1$ dimensional simplex.
Now provide the response and nothing else.
| Compare:$$3^{32}=(3^{2})^{16}\quad\text{vs.}\quad2^{50}=4(2^{3})^{16}$$So that using the binomial theorem to second order:$$\frac{3^{32}}{2^{50}}=\frac{(9/8)^{16}}{4}=\frac{(1+1/8)^{16}}{4}>\frac{1+16/8+120/64}{4}>1$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/978088', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/179627/']} | jdg_80229 |
stackexchange | llm_judgeable_groundtruth_similarity | 3078081 |
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 want all the TextView instances in my app to have textColor="#ffffff" . Is there a way to set that in one place instead of setting it for each TextView ?
Now provide the response and nothing else.
| Actually, you can set a default style for TextViews (and most other built-in widgets) without needing to do a custom java class or setting the style individually. If you take a look in themes.xml in the Android source, you will see a bunch of attributes for the default style for various widgets. The key is the textViewStyle (or editTextStyle , etc.) attribute which you override in your custom theme. You can override these in the following way: Create a styles.xml : <?xml version="1.0" encoding="utf-8"?><resources><style name="MyTheme" parent="android:Theme"> <item name="android:textViewStyle">@style/MyTextViewStyle</item></style><style name="MyTextViewStyle" parent="android:Widget.TextView"> <item name="android:textColor">#F00</item> <item name="android:textStyle">bold</item></style></resources> Then just apply that theme to your application in AndroidManifest.xml : <application […] android:theme="@style/MyTheme">… And all your text views will default to the style defined in MyTextViewStyle (in this instance, bold and red)! This was tested on devices from API level 4 onward and seems to work great. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3078081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/200145/']} | jdg_80230 |
stackexchange | llm_judgeable_groundtruth_similarity | 30430131 |
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 django application that sends off an email containing image files as MIME attachments. The emails are sent from views.py, but in order to attach the files, I need to get the full path name of the image(s), so python can open them. These files are in the static folder in my app, but I can't seem to find a way that I can get the full path of the file on the filesystem that works in development mode - It works fine in production after collecting static, but in dev, it can't find the file as the static files are served from individual app folders in development.
Now provide the response and nothing else.
| project_dir.url add to the end of file if DEBUG: urlpatterns += patterns( '', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT}), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': STATIC_ROOT}),) project_dir.settings STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'),)STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder',)STATIC_ROOT = os.path.join(BASE_DIR, 'static_debug')STATIC_URL = '/static/'MEDIA_ROOT = os.path.join(BASE_DIR, 'media')MEDIA_URL = '/media/' make dirs media & static_debug (add them to .gitignore) project_dir/ static/ image.jpg settings.py urls.pyapps/ __init__.py some_app/ static/ some_app/ css/ style.cssmedia/static_debug/ Now you can run project or directly python manage.py collectstatic access from views from django.templatetags.static import staticstatic('image.jpg')static('some_app/css/style.css') access from templates {% load staticfiles %}{% static 'image.jpg' %}{% static 'some_app/css/style.css' %} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30430131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/224511/']} | jdg_80231 |
stackexchange | llm_judgeable_groundtruth_similarity | 617030 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The number of real roots of the equation $\displaystyle 1+\frac{x}{1}+\frac{x^2}{2}+\frac{x^3}{3}+\frac{x^4}{4}+\frac{x^5}{5}+\frac{x^6}{6}+\frac{x^7}{7} = 0$ $\bf{My\; Try}::$ Let $\displaystyle f(x) = 1+\frac{x}{1}+\frac{x^2}{2}+\frac{x^3}{3}+\frac{x^4}{4}+\frac{x^5}{5}+\frac{x^6}{6}+\frac{x^7}{7}$ Now $\displaystyle f^{'}(x) = 1+x+x^2+x^3+x^4+x^5+x^6$ and $\displaystyle f^{''}(x) = 1+2x+3x^2+4x^3+5x^4+6x^5$ $\displaystyle f^{'''}(x) = 0+2+6x+12x^2+20x^3+30x^4 = 2\left(1+3x+6x^2+10x^3+15x^4\right)$ Now I did not understand how can i solve it Help Required Thanks
Now provide the response and nothing else.
| Note that$$f'(x)=\sum_{k=0}^6 x^k=\frac{x^7-1}{x-1}.$$Now, it is not too hard to see that $f'(x)>0$ for all $x\in\mathbb{R}$ (consider regions $x<-1$, $-1<x<0$, $0<x<1$ and $x>1$). So, there is a real root because the degree of the polynomial is odd, but there is only one because the function is monotonically increasing. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/617030', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14311/']} | jdg_80232 |
stackexchange | llm_judgeable_groundtruth_similarity | 51843523 |
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 get low level access to webcam properties using DirectShow's IAMVideoProcAmp . There are several Python modules ) pywin32 , pywintypes , comtypes , win32com , pythoncom ) that are used in this context and they seem to be related somehow. But I have no clue where to start. I found some examples ( here , here , here ) but I could not figure out how to get a IID / CLSID to use like import win32com.clientclsid='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'ShellWindows=win32com.client.Dispatch(clsid) or with a clear name like import win32com.clientxl = win32com.client.Dispatch("Excel.Application") or from comtypes import client, GUIDgraph = client.CreateObject(some_CLSID)graph.QueryInterface(...) Can someone help me with this? I found another example ( dshow.py ), but it has some dependencies that I could not find ( interfaces , uuids ). This page from Microsoft lists the procedures as Call QueryInterface on the capture filter for the IAMVideoProcAmp interface. or Query the capture filter for the IAMCameraControl. and states some C++ code for this: // Query the capture filter for the IAMVideoProcAmp interface.IAMVideoProcAmp *pProcAmp = 0;hr = pCap->QueryInterface(IID_IAMVideoProcAmp, (void**)&pProcAmp);hr = m_pProcAmp->GetRange(VideoProcAmp_Brightness, &Min, &Max, &Step, &Default, &Flags); Edit:I finally found some code that looks good so far: jaraco It seem to do exactly what I am trying to write and uses some elements fromDirectShow ( see here ): from comtypes.gen.DirectShowLib import (FilterGraph, CaptureGraphBuilder2, ...) jaraco.video claims to be "a port of the VideoCapture module in pure Python using ctypes and comtypes." It is using a DirectShow.tlb file (whatever that is) to get the definitions into comtypes A type library (.tlb) is a binary file that stores information about a COM or DCOM object's properties and methods in a form that is accessible to other applications at runtime.
Now provide the response and nothing else.
| What you are asking are very good questions, and all of us, streaming video developers, encounter same issues and share same frustration when it comes to plugin-free near real time streaming video in browsers. Let me address your questions to the best of my knowledge (I have implemented both WebRTC and Media Source Extensions in recent years, for a streaming server software) " if it is possible to create a MediaStream and append buffers to it, like the MediaSource" This one is easy - it is NOT possible. MediaStream API: https://developer.mozilla.org/en-US/docs/Web/API/MediaStream does not expose access to MediaStream object's frame buffer, it handles everything internally using WebRTC, either getting frames using getUserMedia (from local webcam), or from RTCPeerConeection (from network). With MediaStream object you don't manipulate frames or segments directly. And, of course, video.srcObject = mediaSource will not work: video.srcObject must be a MediaStream object created by WebRTC API, nothing else. "I could not find in the documentation if browsers handle src and srcObject differently" Hell yes, browsers do treat video.src and video.srcObject very differently; and there is no documentation about it, and it doesn't make much sense. Politics play large role in it. Notorious examples from Chrome browser: a. Media Source Extensions (video.src) support AAC audio, but WebRTC (video.srcObject) does not, and never will. The reason is - Google bought too many audio compression companies and one of them - Opus - made it to WebRTC specs, and Google is pushing Opus to be a new "royalty-free" audio king, so no AAC support in video.srcObject, and all the hardware world must implement Opus now.So Google can and is legally allowed to add AAC support to Chrome, because it does it for Media Source Extesnsions (video.src). But it will not add AAC support to WebRTC, never. b. Chrome uses different strategies for H264 video decoders in video.src and video.srcObject.This makes no sense but it's a fact. For example, on Android, only devices with hardware H264 decoding support will support H264 in WebRTC (video.srcObject). Older devices without hardware H264 support, will not play H264 video via WebRTC. But same devices will play same H264 video via Media Source Extensions (video.src). So video.src must be using a software decoder if hardware is not available. Why the same cannot be done in WebRTC? Lastly, your VP8 stream will not play on iOS, neither in Media Source Extensions (iOS doesn't support it at all, ha ha ha), nor in WebRTC (iOS only support H264 video for WebRTC, ha ha ha ha). You are asking why Apple does that? ha ha ha ha ha | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51843523', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7919597/']} | jdg_80233 |
stackexchange | llm_judgeable_groundtruth_similarity | 30128395 |
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 reference a managed bean in EL like so #{bean.entity.property} , sometimes a javax.el.PropertyNotFoundException: Target Unreachable exception is being thrown, usually when a bean property is to be set, or when a bean action is to be invoked. There seem to be five different kinds of messages: Target Unreachable, identifier 'bean' resolved to null Target Unreachable, 'entity' returned null Target Unreachable, 'null' returned null Target Unreachable, ''0'' returned null Target Unreachable, 'BracketSuffix' returned null What do they all mean? How are they caused and how should they be solved?
Now provide the response and nothing else.
| 1. Target Unreachable, identifier 'bean' resolved to null This boils down to that the managed bean instance itself could not be found by exactly that identifier (managed bean name) in EL like so #{bean} . Identifying the cause can be broken down into three steps: a. Who's managing the bean? b. What's the (default) managed bean name? c. Where's the backing bean class? 1a. Who's managing the bean? First step would be checking which bean management framework is responsible for managing the bean instance. Is it CDI via @Named ? Or is it JSF via @ManagedBean ? Or is it Spring via @Component ? Can you make sure that you're not mixing multiple bean management framework specific annotations on the very same backing bean class? E.g. @Named @ManagedBean , @Named @Component , or @ManagedBean @Component . This is wrong. The bean must be managed by at most one bean management framework and that framework must be properly configured. If you already have no idea which to choose, head to Backing beans (@ManagedBean) or CDI Beans (@Named)? and Spring JSF integration: how to inject a Spring component/service in JSF managed bean? In case it's CDI who's managing the bean via @Named , then you need to make sure of the following: CDI 1.0 (Java EE 6) requires an /WEB-INF/beans.xml file in order to enable CDI in WAR. It can be empty or it can have just the following content: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd"> </beans> CDI 1.1 (Java EE 7) without any beans.xml , or an empty beans.xml file, or with the above CDI 1.0 compatible beans.xml will behave the same as CDI 1.0. When there's a CDI 1.1 compatible beans.xml with an explicit version="1.1" , then it will by default only register @Named beans with an explicit CDI scope annotation such as @RequestScoped , @ViewScoped , @SessionScoped , @ApplicationScoped , etc. In case you intend to register all beans as CDI managed beans, even those without an explicit CDI scope, use the below CDI 1.1 compatible /WEB-INF/beans.xml with bean-discovery-mode="all" set (the default is bean-discovery-mode="annotated" ). <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" version="1.1" bean-discovery-mode="all"> </beans> When using CDI 1.1+ with bean-discovery-mode="annotated" (default), make sure that you didn't accidentally import a JSF scope such as javax.faces.bean.RequestScoped instead of a CDI scope javax.enterprise.context.RequestScoped . Watch out with IDE autocomplete. When using Mojarra 2.3.0-2.3.2 and CDI 1.1+ with bean-discovery-mode="annotated" (default), then you need to upgrade Mojarra to 2.3.3 or newer due to a bug . In case you can't upgrade, then you need either to set bean-discovery-mode="all" in beans.xml , or to put the JSF 2.3 specific @FacesConfig annotation on an arbitrary class in the WAR (generally some sort of an application scoped startup class). When using JSF 2.3 on a Servlet 4.0 container with a web.xml declared conform Servlet 4.0, then you need to explicitly put the JSF 2.3 specific @FacesConfig annotation on an arbitrary class in the WAR (generally some sort of an application scoped startup class). This is not necessary in Servlet 3.x. When using CDI 3.0, the first version with package renamed from javax.* to jakarta.* , then you need to ensure that all deployment descriptor files beans.xml , web.xml , faces-config.xml are conform the new jakartaee schemas and thus not conform the old javaee schemes. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/beans_3_0.xsd" version="3.0" bean-discovery-mode="all"> </beans> Non-JEE containers like Tomcat and Jetty doesn't ship with CDI bundled. You need to install it manually. It's a bit more work than just adding the library JAR(s). For Tomcat, make sure that you follow the instructions in this answer: How to install and use CDI on Tomcat? Your runtime classpath is clean and free of duplicates in CDI API related JARs. Make sure that you're not mixing multiple CDI implementations (Weld, OpenWebBeans, etc). Make sure that you don't provide another CDI or even Java EE API JAR file along webapp when the target container already bundles CDI API out the box. If you're packaging CDI managed beans for JSF views in a JAR, then make sure that the JAR has at least a valid /META-INF/beans.xml (which can be kept empty). In case it's JSF who's managing the bean via the since 2.3 deprecated @ManagedBean , and you can't migrate to CDI, then you need to make sure of the following: The faces-config.xml root declaration is compatible with JSF 2.0. So the XSD file and the version must at least specify JSF 2.0 or higher and thus not 1.x. <faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0"> For JSF 2.1, just replace 2_0 and 2.0 by 2_1 and 2.1 respectively. If you're on JSF 2.2 or higher, then make sure you're using xmlns.jcp.org namespaces instead of java.sun.com over all place. <faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd" version="2.2"> For JSF 2.3, just replace 2_2 and 2.2 by 2_3 and 2.3 respectively. You didn't accidentally import javax.annotation.ManagedBean instead of javax.faces.bean.ManagedBean . Watch out with IDE autocomplete, Eclipse is known to autosuggest the wrong one as first item in the list. You didn't override the @ManagedBean by a JSF 1.x style <managed-bean> entry in faces-config.xml on the very same backing bean class along with a different managed bean name. This one will have precedence over @ManagedBean . Registering a managed bean in faces-config.xml is not necessary since JSF 2.0, just remove it. Your runtime classpath is clean and free of duplicates in JSF API related JARs. Make sure that you're not mixing multiple JSF implementations (Mojarra and MyFaces). Make sure that you don't provide another JSF or even Java EE API JAR file along webapp when the target container already bundles JSF API out the box. See also "Installing JSF" section of our JSF wiki page for JSF installation instructions. In case you intend to upgrade container-bundled JSF from the WAR on instead of in container itself, make sure that you've instructed the target container to use WAR-bundled JSF API/impl. If you're packaging JSF managed beans in a JAR, then make sure that the JAR has at least a JSF 2.0 compatible /META-INF/faces-config.xml . See also How to reference JSF managed beans which are provided in a JAR file? If you're actually using the jurassic JSF 1.x, and you can't upgrade, then you need to register the bean via <managed-bean> in faces-config.xml instead of @ManagedBean . Don't forget to fix your project build path as such that you don't have JSF 2.x libraries anymore (so that the @ManagedBean annotation wouldn't confusingly successfully compile). In case it's Spring who's managing the bean via @Component , then you need to make sure of the following: Spring is being installed and integrated as per its documentation . Importantingly, you need to at least have this in web.xml : <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> And this in faces-config.xml : <application> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver> </application> (above is all I know with regard to Spring — I don't do Spring — feel free to edit/comment with other probable Spring related causes; e.g. some XML configuration related trouble) In case it's a repeater component who's managing the (nested) bean via its var attribute (e.g. <h:dataTable var="item"> , <ui:repeat var="item"> , <p:tabView var="item"> , etc) and you actually got a "Target Unreachable, identifier 'item' resolved to null", then you need to make sure of the following: The #{item} is not referenced in binding attribtue of any child component. This is incorrect as binding attribute runs during view build time, not during view render time. Moreover, there's physically only one component in the component tree which is simply reused during every iteration round. In other words, you should actually be using binding="#{bean.component}" instead of binding="#{item.component}" . But much better is to get rid of component bining to bean altogether and investigate/ask the proper approach for the problem you thought to solve this way. See also How does the 'binding' attribute work in JSF? When and how should it be used? 1b. What's the (default) managed bean name? Second step would be checking the registered managed bean name. JSF and Spring use conventions conform JavaBeans specification while CDI has exceptions depending on CDI impl/version. A FooBean backing bean class like below, @Named public class FooBean {} will in all bean management frameworks have a default managed bean name of #{fooBean} , as per JavaBeans specification. A FOOBean backing bean class like below, @Named public class FOOBean {} whose unqualified classname starts with at least two capitals will in JSF and Spring have a default managed bean name of exactly the unqualified class name #{FOOBean} , also conform JavaBeans specificiation. In CDI, this is also the case in Weld versions released before June 2015, but not in Weld versions released after June 2015 (2.2.14/2.3.0.B1/3.0.0.A9) nor in OpenWebBeans due to an oversight in CDI spec . In those Weld versions and in all OWB versions it is only with the first character lowercased #{fOOBean} . If you have explicitly specified a managed bean name foo like below, @Named("foo") public class FooBean {} or equivalently with @ManagedBean(name="foo") or @Component("foo") , then it will only be available by #{foo} and thus not by #{fooBean} . 1c. Where's the backing bean class? Third step would be doublechecking if the backing bean class is at the right place in the built and deployed WAR file. Make sure that you've properly performed a full clean, rebuild, redeploy and restart of the project and server in case you was actually busy writing code and impatiently pressing F5 in the browser. If still in vain, let the build system produce a WAR file, which you then extract and inspect with a ZIP tool. The compiled .class file of the backing bean class must reside in its package structure in /WEB-INF/classes . Or, when it's packaged as part of a JAR module, the JAR containing the compiled .class file must reside in /WEB-INF/lib and thus not e.g. EAR's /lib or elsewhere. If you're using Eclipse, make sure that the backing bean class is in src and thus not WebContent , and make sure that Project > Build Automatically is enabled. If you're using Maven, make sure that the backing bean class is in src/main/java and thus not in src/main/resources or src/main/webapp . If you're packaging the web application as part of an EAR with EJB+WAR(s), then you need to make sure that the backing bean classes are in WAR module and thus not in EAR module nor EJB module. The business tier (EJB) must be free of any web tier (WAR) related artifacts, so that the business tier is reusable across multiple different web tiers (JSF, JAX-RS, JSP/Servlet, etc). 2. Target Unreachable, 'entity' returned null This boils down to that the nested property entity as in #{bean.entity.property} returned null . This usually only exposes when JSF needs to set the value for property via an input component like below, while the #{bean.entity} actually returned null . <h:inputText value="#{bean.entity.property}" /> You need to make sure that you have prepared the model entity beforehand in a @PostConstruct , or <f:viewAction> method, or perhaps an add() action method in case you're working with CRUD lists and/or dialogs on same view. @Named@ViewScopedpublic class Bean { private Entity entity; // +getter (setter is not necessary). @Inject private EntityService entityService; @PostConstruct public void init() { // In case you're updating an existing entity. entity = entityService.getById(entityId); // Or in case you want to create a new entity. entity = new Entity(); } // ...} As to the importance of @PostConstruct ; doing this in a regular constructor would fail in case you're using a bean management framework which uses proxies , such as CDI. Always use @PostConstruct to hook on managed bean instance initialization (and use @PreDestroy to hook on managed bean instance destruction). Additionally, in a constructor you wouldn't have access to any injected dependencies yet, see also NullPointerException while trying to access @Inject bean in constructor . In case the entityId is supplied via <f:viewParam> , you'd need to use <f:viewAction> instead of @PostConstruct . See also When to use f:viewAction / preRenderView versus PostConstruct? You also need to make sure that you preserve the non- null model during postbacks in case you're creating it only in an add() action method. Easiest would be to put the bean in the view scope. See also How to choose the right bean scope? 3. Target Unreachable, 'null' returned null This has actually the same cause as #2, only the (older) EL implementation being used is somewhat buggy in preserving the property name to display in the exception message, which ultimately incorrectly exposed as 'null'. This only makes debugging and fixing a bit harder when you've quite some nested properties like so #{bean.entity.subentity.subsubentity.property} . The solution is still the same: make sure that the nested entity in question is not null , in all levels. 4. Target Unreachable, ''0'' returned null This has also the same cause as #2, only the (older) EL implementation being used is buggy in formulating the exception message. This exposes only when you use the brace notation [] in EL as in #{bean.collection[index]} where the #{bean.collection} itself is non-null, but the item at the specified index doesn't exist. Such a message must then be interpreted as: Target Unreachable, 'collection[0]' returned null The solution is also the same as #2: make sure that the collection item is available. 5. Target Unreachable, 'BracketSuffix' returned null This has actually the same cause as #4, only the (older) EL implementation being used is somewhat buggy in preserving the iteration index to display in the exception message, which ultimately incorrectly exposed as 'BracketSuffix' which is really the character ] . This only makes debugging and fixing a bit harder when you've multiple items in the collection. Other possible causes of javax.el.PropertyNotFoundException : javax.el.ELException: Error reading 'foo' on type com.example.Bean javax.el.ELException: Could not find property actionMethod in class com.example.Bean javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean javax.el.PropertyNotFoundException: Property 'foo' not readable on type java.lang.Boolean javax.el.PropertyNotFoundException: Property not found on type org.hibernate.collection.internal.PersistentSet Outcommented Facelets code still invokes EL expressions like #{bean.action()} and causes javax.el.PropertyNotFoundException on #{bean.action} | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/30128395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157882/']} | jdg_80234 |
stackexchange | llm_judgeable_groundtruth_similarity | 418789 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to understand the mathematics underneath the poisson.test function in the stats package in R . I am using it to compute a p-value when comparing a sample of data against another poisson rate; not another sample of data. I've looked up the documentation around this but I cannot find anything which outlines the mathematics of the test itself, only how it is used. If anyone is able to help, or point me in the right direction I'd be greatly appreciative.
Now provide the response and nothing else.
| When you say "another Poisson rate" ... if that other Poisson rate is derived from data then you are comparing data with data. I'll assume you mean against some prespecified/theoretical rate (i.e. that you're performing a one-sample test). You didn't state whether you were doing a one-tailed or two-tailed test. I'll discuss both What it's doing is using the Poisson distribution with the specified rate you're testing against, and then computing the tail area "at least as extreme" (in the direction of the alternative) as the sample you got. e.g. consider a one-tailed test; $H_0: \mu \leq 8.5$ vs $H_1: \mu > 8.5$ and the observed Poisson count of 14. Then we can compute that the upper tail at and above 14 has 0.0514 of the probability - e.g.: > 1-ppois(13,8.5)[1] 0.05141111 (I realize this is not the best way to compute this in R - we should use the lower.tail argument instead - but wanted to make it more transparent to readers less familiar with R; by comparison ppois(13,8.5,lower.tail=FALSE) looks like an off-by-one error) This calculation agrees with poisson.test : > poisson.test(14,r=8.5,alt="greater") Exact Poisson testdata: 14 time base: 1number of events = 14, time base = 1, p-value = 0.05141alternative hypothesis: true event rate is greater than 8.595 percent confidence interval: 8.463938 Infsample estimates:event rate 14 With a two-tailed test it sums those values with equal or lower probability (i.e. as with typical Fisher-style exact tests, it uses the likelihood under the null to identify what's "more extreme"): The probability of a 14 with Poisson mean 8.5 is about 0.024 and in the left tail the largest x-value with probability no larger occurs at 3, so the probabilities of 0,1,2 and 3 are added in: > 1-ppois(13,8.5)+ppois(3,8.5)[1] 0.08152019 check against the output: > poisson.test(14,r=8.5) Exact Poisson testdata: 14 time base: 1number of events = 14, time base = 1, p-value = 0.08152alternative hypothesis: true event rate is not equal to 8.595 percent confidence interval: 7.65393 23.48962sample estimates:event rate 14 R code is publicly available -- you can check the code; in this case it bears out what I said above. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/418789', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/254522/']} | jdg_80235 |
stackexchange | llm_judgeable_groundtruth_similarity | 88169 |
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 was recently reading up on Fraïssé limits in Hodges' "A shorter model theory." I was trying to think of some examples and wanted to see if I could take the Fraïssé limit on the category of finite groups. It is clear that this category has the hereditary and joint embedding property. However, I am having trouble showing that this category has the amalgamation property, by which I mean that if there are finite groups $G, H, K$ such that there are embeddings $\varphi: G\hookrightarrow H$ and $\psi: G\hookrightarrow K$, then there exists a finite group $J$ and embeddings $\vartheta: H\hookrightarrow J$ and $\eta: K\hookrightarrow J$ such that $\vartheta\circ \varphi = \eta\circ \psi$. One simplification is that we can, by taking isomorphic copies if necessary, assume that $H\cap K = G$, and that $\varphi $ and $\psi$ are just inclusion maps. I am not even sure what group $J$ should be. Any help would be appreciated.
Now provide the response and nothing else.
| There is also a fairly explicit construction of one such J : one takes G = H ∩ K , and transversals S and T of G in H and K , and then J is the subgroup of Sym( G × S × T ) generated by the regular representations of both H and K (where an element of H fixes each point of T and views G × S as H ). This typically creates very large J . Any such J as you asked for is called a (faithful, finite) completion of the (rank 2) amalgam ( H , K ). Choosing different transversals can create different (faithful, finite) completions J . However, I believe there are many more (faithful, finite) completions than those created by this method. All of them are finite quotients of the universal completion mentioned in the comments, the free product with amalgamation. Some have used the low index subgroup iterator to find finite faithful completions that have low index core-free subgroups. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/88169', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/20127/']} | jdg_80236 |
stackexchange | llm_judgeable_groundtruth_similarity | 45267003 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using the requests library to get a lot of webpages from somewhere. He's the pertinent code: response = requests.Session()retries = Retry(total=5, backoff_factor=.1)response.mount('http://', HTTPAdapter(max_retries=retries))response = response.get(url) After a while it just hangs/freezes (never on the same webpage) while getting the page. Here's the traceback when I interrupt it: File "/Users/Student/Hockey/Scrape/html_pbp.py", line 21, in get_pbp response = r.read().decode('utf-8')File "/anaconda/lib/python3.6/http/client.py", line 456, in read return self._readall_chunked()File "/anaconda/lib/python3.6/http/client.py", line 566, in _readall_chunked value.append(self._safe_read(chunk_left))File "/anaconda/lib/python3.6/http/client.py", line 612, in _safe_read chunk = self.fp.read(min(amt, MAXAMOUNT))File "/anaconda/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b)KeyboardInterrupt Does anybody know what could be causing it? Or (more importantly) does anybody know a way to stop it if it takes more than a certain amount of time so that I could try again?
Now provide the response and nothing else.
| Seems like setting a (read) timeout might help you. Something along the lines of: response = response.get(url, timeout=5) (This will set both connect and read timeout to 5 seconds.) In requests , unfortunately, neither connect nor read timeouts are set by default, even though the docs say it's good to set it: Most requests to external servers should have a timeout attached , in case the server is not responding in a timely manner. By default, requests do not time out unless a timeout value is set explicitly. Without a timeout, your code may hang for minutes or more. Just for completeness, the connect timeout is the number of seconds requests will wait for your client to establish a connection to a remote machine, and the read timeout is the number of seconds the client will wait between bytes sent from the server. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45267003', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6301635/']} | jdg_80237 |
stackexchange | llm_judgeable_groundtruth_similarity | 240192 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The actual problem reads: Find the area of the largest rectangle that can be inscribed in the ellipse $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1.$$ I got as far as coming up with the equation for the area to be $A=4xy$ but then when trying to find the derivative I don't think I'm doing it right.
Now provide the response and nothing else.
| Suppose that the upper righthand corner of the rectangle is at the point $\langle x,y\rangle$. Then you know that the area of the rectangle is, as you say, $4xy$, and you know that $$\frac{x^2}{a^2} + \frac{y^2}{b^2} = 1\;.\tag{1}$$ Thinking of the area as a function of $x$, we have $$\frac{dA}{dx}=4x\frac{dy}{dx}+4y\;.$$ Differentiating $(1)$ with respect to $x$, we have $$\frac{2x}{a^2}+\frac{2y}{b^2}\frac{dy}{dx}=0\;,$$ so $$\frac{dy}{dx}=-\frac{b^2x}{a^2y}\;,$$ and $$\frac{dA}{dx}=4y-\frac{4b^2x^2}{a^2y}\;.$$ Setting this to $0$ and simplifying, we have $y^2=\dfrac{b^2x^2}{a^2}$. From $(1)$ we know that $$y^2=b^2-\frac{b^2x^2}{a^2}\;.$$ Thus, $y^2=b^2-y^2$, $2y^2=b^2$, and $\dfrac{y^2}{b^2}=\dfrac12$. Clearly, then, $\dfrac{x^2}{a^2}=\dfrac12$ as well, and the area is maximized when $$x=\frac{a}{\sqrt2}=\frac{a\sqrt2}2\quad\text{and}\quad y=\frac{b}{\sqrt2}=\frac{b\sqrt2}2\;.$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/240192', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49906/']} | jdg_80238 |
stackexchange | llm_judgeable_groundtruth_similarity | 5836623 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm running the following MySQL UPDATE statement: mysql> update customer set account_import_id = 1;ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction I'm not using a transaction, so why would I be getting this error? I even tried restarting my MySQL server and it didn't help. The table has 406,733 rows.
Now provide the response and nothing else.
| You are using a transaction; autocommit does not disable transactions, it just makes them automatically commit at the end of the statement. What could be happening is, some other thread is holding a record lock on some record (you're updating every record in the table!) for too long, and your thread is being timed out. Or maybe running multiple (2+) UPDATE queries on the same row during a single transaction. You can see more details of the event by issuing a SHOW ENGINE INNODB STATUS after the event (in SQL editor). Ideally do this on a quiet test-machine. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5836623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/199712/']} | jdg_80239 |
stackexchange | llm_judgeable_groundtruth_similarity | 415507 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This page is an overview of some of the types of "Galois theories" there are. One of the most basic type is the fundamental theorem of covering spaces , which says, roughly, that for each topological space $X$ , there is an equivalence of categories $$\mathrm{Cov}(X)\simeq \pi_1(X)\mathbf{Set}.$$ Grothendieck proved an analogue of that statement for schemes $X$ : $$\mathrm{EtCov}(X)\simeq \pi_1(X)\mathbf{Set}.$$ (This is again just a very rough formulation and omits some of the assumptions, but you know what I mean.) I am interested in "topos-theoretic Galois theory" . Unfortunately, this section of the nLab page isn't filled out ("(...)"), but I guess that the topos-theoretic formulation of Galois theory states, roughly, that for each topos $\mathcal E$ , $$\mathrm{Gal}(\mathcal E)\simeq \pi_1(\mathcal E)\mathbf{Set},\qquad (\ast)$$ where $\mathrm{Gal}(\mathcal E)$ is the full subcategory of $\mathcal E$ consisting of locally constant objects in $\mathcal E$ , and $\pi_1(\mathcal E)$ is the fundamental group of $\mathcal E$ . (This is suggested by the nLab section "Reformulation of classical Galois theory".) Question: Is there a reference for $(\ast)$ (and the definition of the fundamental group of a topos which is used here)? Is this in SGA 4? The linked nLab page fundamental group of a topos refers to (and is mostly copy-pasted from) Porter's paper Abstract Homotopy Theory: The interaction of category theory and homotopy theory , which contains a section called "The fundamental group of a topos", which in turn refers to SGA 1. This is weird, because SGA 1 doesn't discuss topoi, so in particular not the fundamental group of a topos! The nLab also refers to SGA 4 Exposé IV Exercice 2.7.5 for the definition of the fundamental group and SGA 4 Exposé VIII Proposition 2.1 for, I guess, $(\ast)$ in the special case that $\mathcal E$ is the étale topos of the scheme $X=\mathrm{Spec}(k)$ for some field $k$ . (But this is really just a guess - I can't read French. So correct me if I'm wrong.) Is there more of "topos-theoretic Galois theory" in SGA 4 or are these the only two paragraphs about that topic? Concerning the definition of the fundamental group of a topos, there is a construction in Moerdijk's Classifying Spaces and Classifying Topoi , in which he nevertheless remarks: The profinite fundamental group is discussed inSGA1. This suggests there are two version of the fundamental group of a topos: the one he discusses and the "profinite" version. However, as I said, topoi don't occur in SGA 1, so I wonder where I can find the definition of the "profinite" fundamental group, if that's the notion that should be used in $(\ast)$ . (The definition used in $(\ast)$ should of course have the property that if $\mathcal E$ is the étale topos of a scheme $X$ , then $\pi_1(\mathcal E)$ is isomorphic to the étale fundamental group of $X$ .)
Now provide the response and nothing else.
| The comments have already given the answers, but let me assemble them here with my account of the story. When Scholze first posted the Liquid Tensor Experiment , it was quickly identified (by both Peter and Reid, somewhat independently I think) that Breen–Deligne resolutions would be the largest inputin terms of prerequisites that needed to be formalised. Back then, I had no idea what these resolutions were, or how to prove that they existed. But they were needed for the statement of Theorem 9.4, which seemed to be a very natural first milestone to aim for. So I set out to formalise the statement of the existence of Breen–Deligne resolutions, with the expectation that we would never prove the result in Lean, but just assume it as a black box. Let me recalll the statement: Theorem (Breen–Deligne). For an abelian group $A$ , there exists a resolution of the form $$ \dots → \bigoplus_{j = 0}^{n_i} ℤ[A^{r_{i,j}}] → \dots → ℤ[A^2] → ℤ[A] → A → 0 $$ that is functorial in $A$ . On the proof. See appendix to Section IV of Condensed.pdf . As Reid remarked in the comments, the proof relies on the fact that stable homotopy groups of spheres are finitely generated. ∎ (Aside: for the proof of Theorem 9.4, we really need a version that applies to condensed abelian groups $A$ , so in practice we want to abstract to abelian sheaves.) In the rest of the Lecture notes, Scholze often uses a somewhat different form of the above resolution, by assuming $n_i = 1$ and effectively dropping all the $\bigoplus$ 's. I think this was done mostly for presentational reasons. I did the same thing when I axiomatized Breen–Deligne resolutions in Lean. So really, they weren't axiomatized at all. I don't know of any reason to expect that there exists a resolution with the property that $n_i = 1$ for all $i$ , but I also don't see any reason why there shouldn't. Anyway, I needed a name for the axioms that I did put into Lean, and I chose Breen–Deligne package for that. So what is that exactly? Well, a functorial map $ℤ[A^m] → ℤ[A^n]$ is just a formal sum of matrices with coefficients in $ℤ$ . So as a first approximation, we record the natural numbers $r_j = r_{1,j}$ (since $n_i = 1$ ); for every $j$ , a formal sum of $(r_{j+1}, r_j)$ -matrices with coefficients in $ℤ$ . But we need one more property of Breen–Deligne resolutions: if $C(A)$ denotes the complex, then there are two maps induced by addition. There is the map $σ \colon C(A^2) → C(A)$ that comes from the functoriality of $C$ applied to the addition map $A^2 → A$ . But there is also the map $π \colon C(A^2) → C(A)$ that comes from addition in the objects of the complex. (All objects are of the form $ℤ[A^k]$ and we can simply add elements of these free abelian groups.) The final axiom of a Breen–Deligne package is there is a functorial homotopy between $σ$ and $π$ . While playing around with the axioms, I noticed that I could write down inductively a somewhat non-trivial example of such a package. When I discussed this example with Peter, he suggested that it might in fact be suitable as a replacement for Breen–Deligne resolutions in all applications in his lecture notes so far. Several months later we found out that I had rediscovered MacLane's $Q'$ -construction. So, let's denote by $Q'$ the complex corresponding to the example package. The following result is, as far as I know, original: Lemma. Let $A$ and $B$ be (condensed) abelian groups. If $\text{Ext}^i(Q'(A),B) = 0$ for all $i ≥ 0$ , then $\text{Ext}^i(A,B) = 0$ for all $i ≥ 0$ . Proof. I've written up a proof sketch on Zulip ( public archive of that thread ). ∎ We are in the process of formalizing the necessary homological algebra to verify the proof in Lean. It's the last major milestone left to complete the challenge in Peter's original blogpost. After that, we mostly need some glue. See this blogpost for an update on the formalisation effort. (Edit: see also https://math.commelin.net/files/LTE.pdf for a more precise roadmap of what remains to be done to complete the challange.) Once everything is done, it should all be written up in some paper. So now, let me turn to the question is it sufficient to consider this default example, or is there a real need to consider all possible examples? It is indeed sufficient to consider this default example. The reasons for working with the abstract concept of Breen–Deligne packages are historical: I had formalised the statement of Theorem 9.4 and some other material in terms of BD packages before I realised that this default example was indeed sufficient for our purposes. practical: as Remy points out in the comments, it is (i) helpful to abstract away concrete details into a conceptual object, and (ii) there is a chance that there might be better examples leading to better constants. What would be really interesting is an example of a BD package that gives resolutions instead of merely functorial complexes. It is known that the $Q'$ construction is not a resolution. Indeed, one can easily show inductively that $H_i(Q'(ℤ))$ contains a copy of $ℤ^{2^i}$ . With more work (relying again on abstract homotopy theory), Peter gave a proof that $Q'(A) ≅ Q'(A)^{⊕2}[-1] ⊕ ℤ ⊗_{\mathbb S} A$ on Zulip ( public archive ). | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/415507', 'https://mathoverflow.net', 'https://mathoverflow.net/users/476516/']} | jdg_80240 |
Subsets and Splits