text
stringlengths
64
81.1k
meta
dict
Q: Find range of values for p in equation of circle Can somebody please check my working with the following question: Given the equation ${x^2 + y^2 - 2px - 4py + 3p + 2 = 0}$ represents a circle, determine a range of values for p. I don't think I can use the discriminant because there are y values so I can use: ${g^2 + f^2 - c > 0}$ g = -p f = -2p c = 3p + 2 ${(-p)^2 + (-2p)^2 - 3p + 2 > 0}$ => ${p^2 +4p^2 -3p + 2 > 0}$ => ${5p^2 -3p + 2 > 0}$ I thought I would then find values for p and display them like ${p_1 < p < p_2}$ I was going to use the quadratic formula: => ${{3 \pm \sqrt{(-3)^2 - 4(5)(2)}}\over 5}$ But the discriminant is a negative number so I don't think I am on the right path. A: It should be $-3p-2$ rather than just $-3p+2$ and you are on right path.
{ "pile_set_name": "StackExchange" }
Q: Noticing a Lack of Iron In My Diet I've been using a program (MyFitnessPal) to track my diet and have noticed a slightly disconcerting trend: it always says I am below 100% of my daily recommendation of iron. My current diet regiment has 2 rules: 130+ g/day of protein and no more than 2k calories (even on heavy (1-2 hours) cardio days). The reason for the latter is I am in a cutting phase, aiming for a single digit body fat percentage. What can I do to up my iron intake? Are pills going to be required? Do I need to start eating round steaks again? Beans... seriously, beans? A: Let's note that you are not, to our knowledge, experiencing a physiological iron deficiency. Your program is reporting a deficiency of iron in your diet. These are distinct issues, and the latter does not yet suggest a need for supplementation. The first and easiest steps are: Increase your dietary intake of animals, such as with meat and milk and eggs Use iron cookware NB: the latter will, I expect, not be recorded by your program. NIH's Office of Dietary Supplements notes the difference between heme and nonheme iron: Heme iron is derived from hemoglobin, the protein in red blood cells that delivers oxygen to cells. Heme iron is found in animal foods that originally contained hemoglobin, such as red meats, fish, and poultry. Iron in plant foods such as lentils and beans is arranged in a chemical structure called nonheme iron [9]. This is the form of iron added to iron-enriched and iron-fortified foods. Heme iron is absorbed better than nonheme iron, but most dietary iron is nonheme iron [8]. They then present tables comparing heme and non-heme iron derived from various foods. It's also interesting to keep in mind the amount of iron you actually use is different from the amount you ingest, due to the body's autoregulation. Per Wikipedia: The amount of iron absorbed compared to the amount ingested is typically low, but may range from 5% to as much as 35% depending on circumstances and type of iron. The efficiency with which iron is absorbed varies depending on the source. Generally the best-absorbed forms of iron come from animal products. Absorption of dietary iron in iron salt form (as in most supplements) varies somewhat according to the body's need for iron, and is usually between 10% and 20% of iron intake. Absorption of iron from animal products, and some plant products, is in the form of heme iron, and is more efficient, allowing absorption of from 15% to 35% of intake.
{ "pile_set_name": "StackExchange" }
Q: File sharing on Windows Home Server I have recently added a Windows Home Server (WHS) to my network. One of the PC's on my network has directories called Photos, Music, Video etc. This PC is backed up to the WHS. Now my question is: Can I somehow mark those backed up directories as shared directories and make them available as network shares to other PC's on the network? Or do I have to copy or move the media folders to the WHS? A: You have to copy the data to the shared folders if you want to access them from other computers in your house. One of the benefits of this is you can VPN to your home server and access or even stream anything from those folders should you choose. I sync my music and photos etc using synctoy
{ "pile_set_name": "StackExchange" }
Q: Open a second Form with a textbox i open about my Button "ProtokollToolStripMenuItemClick" my second Form! The name of the second Form is INPUTBOX! This second Form has two text boxes and one Button! Now i would like to put in my name and my mobile phone number in the two text boxes and close the window with my button. This two entries i would like to put down in my excel application.(But i don´t now how to get the text box entries). How can i do this? public partial class MainForm { public void ProtokollToolStripMenuItemClick(object sender, EventArgs e) { INPUTBOX _Input = new INPUTBOX(); _Input.Show(); //Here I want to put in my new code //Declaration Excel.Application ExcelApplication; Excel._Workbook ExcelWorkbook; Excel._Worksheet ExcelWorksheet; try { //Start Excel ExcelApplication = new Excel.Application(); ExcelApplication.Visible = true; //New Workbook ExcelWorkbook = (Excel._Workbook)(ExcelApplication.Workbooks.Add(Missing.Value)); ExcelWorksheet = (Excel._Worksheet)ExcelWorkbook.ActiveSheet; //et cetera A: Open the input box with ShowDialog instead of Show, to ensure that your code pauses until the window has been closed. In your INPUTBOX, create a public property for each of the values you want to return. In your button click handler, copy the values from the text boxes to the public properties. Afterwards, in the code shown in your question, you can access the values by accessing _input.NameOfTheNewProperty.
{ "pile_set_name": "StackExchange" }
Q: BlockUI jquery plugin keeps page blocked after "back" button. Opera/FireFox I use jquery blockUI plugin (v2) and call $.blockUI when user submits a form. Web page smoothly fades out and new page appears. That's ok. But when user presses "back" button in opera/fire fox he observes fade out page with hourglass mouse cursor that is completely blocked. Chrome/IE visualize page ok. What would you suggest? Thank you in advance! A: Finally I found workaround. $(window).unload(function() { $.unblockUI(); })
{ "pile_set_name": "StackExchange" }
Q: CSS. Ghost style of button in mobile device Below 2 versions of the same page. There is a submit button, which has an orange style and it appears correctly in desktop. On the second screen button has gradient and completely different style. This magic appears only on mobile devices. I look through whole css and didn't find any kind of style. Chrome mobile emulator displays it correctly. So my question: how to debug and fix this style? Some thech details: magnific popup plugi for modal, the style of button: .form .btn, .beeline-custom .form input.btn { padding: 0; border: none; background: none; display: block; width: 100%; max-width: 239px; margin: 0 auto; padding: 16.5px 10px; text-align: center; background: #fec81e !important; -webkit-border-radius: 40px; border-radius: 40px; -webkit-transition: 0.3s ease; transition: 0.3s ease; color: #000000; text-transform: uppercase; font-weight: 700; font: 17px/1.2 'Roboto-Regular',sans-serif; } UPD Problem fixed by BenM's comment: -webkit-appearance: none to button css A: You can override any browser defaults by using the appearance CSS property. Set it to none and you should be good to go: -webkit-appearance: none; -moz-appearance: none; appearance: none;
{ "pile_set_name": "StackExchange" }
Q: Find node in Zookeeper I want to know if there is a way to walk the Zookeeper's (ZK) in memory database and find if any particular node exists. Something similar to find . -name file inside ZK I am logged in to ZK using zkCli. A: Once you have your ZK cluster running, you can connect to a node and query the cluster. For example: $ZK_HOME/bin/zkCli.sh -server localhost List of nodes: ls / List of commands: ?
{ "pile_set_name": "StackExchange" }
Q: form is not reset after submit- react js My form is not reset after submit. Whats wrong ?? I am trying to set the state properties to null after submit.But the input values are not set to null. Iam not getting whats wrong with my code.Help me to solve this issue. class AddNinja extends Component { state = { id: null, name: null, age: null, belt: null }; handleChange = e => { this.setState({[e.target.id]: e.target.value }); }; handleSubmit = e => { e.preventDefault(); this.props.addNijna(this.state); this.setState({id: null, name: null, age: null, belt: null }); }; render() { return ( <div> <h4>Add Ninja</h4> <form onSubmit={this.handleSubmit}> <label htmlFor="name">id : </label> <input type="text" id="id" onChange={this.handleChange} /> <label htmlFor="name">Name : </label> <input type="text" id="name" onChange={this.handleChange} /> <label htmlFor="age">Age : </label> <input type="text" id="age" onChange={this.handleChange} /> <label htmlFor="belt">Belt : </label> <input type="text" id="belt" onChange={this.handleChange} /> <button type="submit" className="btn btn-secondary btn-sm m-2"> Submit </button> </form> </div> ); } } export default AddNinja; A: You need your inputs to be controlled, meaning they get their value from state and onChange since the state is changed it is reflected in your component. Also set the values to an empty string instead of null to avoid switching from uncontrolled to controlled components at runtime. You can learn more about about controlled inputs here: https://reactjs.org/docs/forms.html As for your code what you need to do is: class AddNinja extends Component { state = { id: null, name: null, age: null, belt: null }; handleChange = e => { this.setState({[e.target.id]: e.target.value }); }; handleSubmit = e => { e.preventDefault(); this.props.addNijna(this.state); this.setState({id: null, name: null, age: null, belt: null }); }; render() { const {id, name, age, belt} = this.state; return ( <div> <h4>Add Ninja</h4> <form onSubmit={this.handleSubmit}> <label htmlFor="name">id : </label> <input value={id} type="text" id="id" onChange={this.handleChange} /> <label htmlFor="name">Name : </label> <input value={name} type="text" id="name" onChange={this.handleChange} /> <label htmlFor="age">Age : </label> <input value={age} type="text" id="age" onChange={this.handleChange} /> <label htmlFor="belt">Belt : </label> <input value={belt} type="text" id="belt" onChange={this.handleChange} /> <button type="submit" className="btn btn-secondary btn-sm m-2"> Submit </button> </form> </div> ); } } export default AddNinja;
{ "pile_set_name": "StackExchange" }
Q: C++ regex_search capture retrieval fails at runtime I'm following an example in Stroustrup's Tour of C++ - section 7.3.1 (page 79). This code compiles on VS 2013 Update 3 but fails at runtime: regex pat {R"(\w{2}\s+(\d{5}))"}; smatch matches; if (regex_search(string{"CA 90210"}, matches, pat)) { if ((matches.size() > 1) && matches[1].matched) { cout << matches[1] << endl; } } Any idea what is going on? It fails on matches[1] where I'm trying to output the capture group result to stdout. The runtime assertion I see is "string iterators incompatible". A: smatch object contains iterators into the string you searched with the regular expression. Said string is a temporary in your example, and is dead by the time you are trying to inspect the matches. All those iterators are dangling. Make it string s = "CA 90210"; if (regex_search(s, matches, pat)) {...}
{ "pile_set_name": "StackExchange" }
Q: Find $\int_{\mathbb{R}^n}e^{-\frac{\| x- a\|^2+\| x- b\|^2}{2}} dx$ How to integrate \begin{align} \int_{\mathbb{R}^n}e^{-\frac{\| x- a\|^2+\| x- b\|^2}{2}} dx \end{align} where $\| \cdot \|$ is the euclidean distance. I did this for the case of $n=1$ (scalar} and got \begin{align} \int_{\mathbb{R}}e^{-\frac{ ( x- a)^2+ ( x- b)^2}{2}} dx=\sqrt{\pi} e^{-\frac{(a-b)^2}{4}} \end{align} However, I am having trouble doing this for any $n$. A: HINT: Note the kernel is separable with $$\begin{align} e^{\frac12\left(\|x-a\|^2+\|x-b\|^2\right)}&=\prod_{i=1}^ne^{\frac12\left((x_i-a_i)^2+(x_i-b_i)^2\right)}\\\\ &=\prod_{i=1}^ne^{x_i^2-(a_i+b_i)x_i+\frac12\left(a_i^2+b_i^2\right)}\\\\ &=\prod_{i=1}^ne^{\left(x_i-\frac12\left(a_i+b_i\right)\right)^2+\frac14(a_i-b_i)^2}\\\\ \end{align}$$ A: The problem seems to be completing the square. In $n$ dimensions it works pretty much the same. Here we go (tell me if there is anything that is unclear): $$ \begin{aligned} \frac{\|x-a\|^2+\|x-b\|^2}{2}&=\|x\|^2- a\cdot x-b\cdot x+\frac{\|a\|^2+\|b\|^2}{2}\\ &=\Bigl\|x-\frac{a+b}{2}\Bigr\|^2-\Bigl\|\frac{a+b}{2}\Bigr\|^2+\frac{\|a\|^2+\|b\|^2}{2}\\ &=\Bigl\|x-\frac{a+b}{2}\Bigr\|^2+\Bigl\|\frac{a-b}{2}\Bigr\|^2 \end{aligned} $$ Next, use the fact that the integral is translation invariant, so you get $$ \begin{aligned} \int_{\mathbb R^n}\exp\Bigl(-\frac{\|x-a\|^2+\|x-b\|^2}{2}\Bigr)\,dx &= \exp\Bigl(-\Bigl\|\frac{a-b}{2}\Bigr\|^2\Bigr) \int_{\mathbb R^n}\exp\Bigl(-\Bigl\|x-\frac{a+b}{2}\Bigr\|^2\Bigr)\,dx\\ &= \exp\Bigl(-\Bigl\|\frac{a-b}{2}\Bigr\|^2\Bigr) \int_{\mathbb R^n}\exp(-\|y\|^2)\,dy. \end{aligned} $$ I assume you can take it from here.
{ "pile_set_name": "StackExchange" }
Q: Winapi get string width in pixels I'm trying to create a method that gives me the width of a string in pixels. My code so far: inline void getTextWidth(HWND hwnd char* text) { SIZE textSize; GetTextExtentPoint32(GetDC(hwnd), text, strlen(text), &textSize); return ?; } I know that I should use LPtoDP (MSDN), but at wants points as parameters and not the SIZE that GetTextExtentPoint32 returns. How do I convert this? A: The SIZE structure contains both a height and a width. Since you only care about the width, you apparently want LPtoDP(textSize.cx);.
{ "pile_set_name": "StackExchange" }
Q: VerifyCommitted - Transaction has not been committed error on plugin I am writing a plugin for Dynamics 2017 on premise using C#. The plugin is supposed to run synchronously post operation on the win of an opportunity. When I mark an opportunity as won, I receive the following error: <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <s:Fault> <faultcode>s:Client</faultcode> <faultstring xml:lang="en-US">VerifyCommitted - Transaction has not been committed</faultstring> <detail> <OrganizationServiceFault xmlns="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <ActivityId>11be55c4-321a-4b84-b9b7-f2451579bc67</ActivityId> <ErrorCode>-2147220910</ErrorCode> <ErrorDetails xmlns:a="http://schemas.datacontract.org/2004/07/System.Collections.Generic"/> <Message>VerifyCommitted - Transaction has not been committed</Message> <Timestamp>2018-07-05T18:37:53.9996395Z</Timestamp> <ExceptionRetriable>false</ExceptionRetriable> <ExceptionSource i:nil="true"/> <InnerFault i:nil="true"/> <OriginalException i:nil="true"/> <TraceText i:nil="true"/> </OrganizationServiceFault> </detail> </s:Fault> </s:Body> </s:Envelope> I've tried profiling the plugin so I can debug what is happening here, but it doesn't appear that the plugin is successfully profiling the action. Why am I receiving this error and why is my plugin not profiling correctly? private void ExecutePostOpportunityWin(LocalPluginContext localContext) { if (localContext == null) { throw new ArgumentNullException("localContext"); } try { IPluginExecutionContext context = localContext.PluginExecutionContext; Entity wonOpportunityEntity = context.InputParameters.Contains("OpportunityClose") ? (Entity)context.InputParameters["OpportunityClose"] : throw new InvalidPluginExecutionException("Unable to load OpportunityClose Input Parameter. Please try again in a few minutes. If the problem persists please contact IT Support."); EntityReference wonOpportunityReference = wonOpportunityEntity.Attributes.Contains("opportunityid") ? (EntityReference)wonOpportunityEntity.Attributes["opportunityid"] : throw new InvalidPluginExecutionException("Unable to load opportunityid. Please try again in a few minutes. If the problem persists please contact IT Support."); IOrganizationService service = localContext.OrganizationService; if (wonOpportunityReference != null) { Opportunity wonOpportunity = (Opportunity)service.Retrieve( "opportunity", new Guid(wonOpportunityReference.Id.ToString()), new ColumnSet(new String[] { "customerid", "ownerid", "ccseq_salesleadid", "description", "ccseq_newcontract", "ccseq_newclient", "ccseq_clientid", "ccseq_contractid", "name" }) ); if (wonOpportunity != null) { Boolean isNewClient = wonOpportunity.NewClient == true; Boolean isNewContract = wonOpportunity.NewContract == true; if (isNewClient && isNewContract) { Client newClient = CreateClient(wonOpportunity, service); Contract newContract = CreateContract(wonOpportunity, newClient, service); AssociateOpportunityToContract(wonOpportunity.Id, newContract.Id, service); wonOpportunity.Client = newClient; wonOpportunity.Contract = newContract; wonOpportunity.Save(service); } else if (isNewClient && !isNewContract) { Client newClient = CreateClient(wonOpportunity, service); AssociateOpportunityToContract(wonOpportunity.Id, wonOpportunity.Contract.Id, service); wonOpportunity.Client = newClient; wonOpportunity.Save(service); } else if (!isNewClient && isNewContract) { Entity entity = service.Retrieve( "ccseq_client", wonOpportunity.Client.Id, new ColumnSet(new String[] { "ccseq_clientid", "ccseq_masterclientid" }) ); Client newClient = (Client)entity; if (newClient.MasterClient != null) { entity = service.Retrieve( "ccseq_client", newClient.Id, new ColumnSet(new String[] { "ccseq_clientid", "ccseq_masterclientid" }) ); newClient = (Client)entity; } Contract newContract = CreateContract(wonOpportunity, newClient, service); AssociateOpportunityToContract(wonOpportunity.Id, newContract.Id, service); wonOpportunity.Contract = newContract; wonOpportunity.Save(service); } else if (!isNewClient && !isNewContract) { AssociateOpportunityToContract(wonOpportunity.Id, wonOpportunity.Contract.Id, service); } else { throw new InvalidPluginExecutionException("Unable to process Client and Contract Information. Please try again in a few minutes. If the problem persists please contact IT Support."); } } else { throw new InvalidPluginExecutionException("Unable to load Opportunity. Please try again in a few minutes. If the problem persists please contact IT Support."); } } else { throw new InvalidPluginExecutionException("Unable to load Opportunity. Please try again in a few minutes. If the problem persists please contact IT Support."); } } catch (Exception e) { throw new InvalidPluginExecutionException(e.Message); } } private void AssociateOpportunityToContract(Guid opportunityID, Guid contractID, IOrganizationService service) { service.Associate( "ccseq_contract", contractID, new Relationship("ccseq_ccseq_contract_opportunity_ContractID"), new EntityReferenceCollection( new EntityReference[] { new EntityReference("opportunity", opportunityID) } ) ); } private Contract CreateContract(Opportunity opportunity, Client clientGroup, IOrganizationService service) { Contract newContract = new Contract(); newContract.ApprovingPartner = opportunity.SalesLead; newContract.Preparer = opportunity.SalesLead; newContract.Description = opportunity.Topic; newContract.Executed = false; newContract.ContractStatus = Contract.eContractStatus.Draft; newContract.ClientGroup = clientGroup; newContract.Id = newContract.Save(service); ContractLine newContractLine = new ContractLine(); newContractLine.Contract = newContract; newContractLine.Id = newContractLine.Save(service); ContractRevenue newContractRevenue = new ContractRevenue(); newContractRevenue.Contract = newContract; newContractRevenue.Id = newContractRevenue.Save(service); ContractRevenueByContractLine newContractRevenueByContractLine = new ContractRevenueByContractLine(); newContractRevenueByContractLine.ContractLine = newContractLine; newContractRevenueByContractLine.ContractRevenue = newContractRevenue; newContractRevenueByContractLine.Id = newContractRevenueByContractLine.Save(service); ContractJob newContractJob = new ContractJob(); newContractJob.ContractLine = newContractLine; newContractJob.Id = newContractJob.Save(service); return newContract; } private Client CreateClient(Opportunity opportunity, IOrganizationService service) { Client newClient = new Client(); newClient.Name = opportunity.AssociationOrContact.Name; newClient.Originator = opportunity.Originator; newClient.Preparer = opportunity.SalesLead; newClient.ClientPartner = opportunity.SalesLead; newClient.ClientStatus = Client.eClientStatus.Draft; if (opportunity.AssociationOrContact != null) { if (opportunity.AssociationOrContact.LogicalName == "account") { Association association = null; association = (Association)service.Retrieve( "account", opportunity.AssociationOrContact.Id, new ColumnSet(new String[] { "ownershipcode", "industrycode", "ccseq_fiscalyearendmonth", "ccseq_naicscode", "address1_line1", "address1_line2", "address1_line3", "address1_city", "address1_stateorprovince", "address1_postalcode", "address1_country" }) ); if (association != null) { newClient.Association = association; newClient.FiscalYearEndMonth = association.FiscalYearEndMonth != null ? (Client.eMonthOfYear)association.FiscalYearEndMonth : (Client.eMonthOfYear?)null; //client.ClientType = (Client.eClientType)association.EntityType; // These two option sets are different newClient.SameAsClientAddress = true; newClient.Address1 = association.Address1_Street1; newClient.Address2 = association.Address1_Street2; newClient.Address3 = association.Address1_Street3; newClient.City = association.Address1_City; newClient.State = association.Address1_State_Province; newClient.Zip = association.Address1_ZIP_PostalCode != null ? Convert.ToInt32(association.Address1_ZIP_PostalCode) : (int?)null; newClient.Country = association.Address1_County; newClient.BillingAddress1 = association.Address1_Street1; newClient.BillingAddress2 = association.Address1_Street2; newClient.BillingAddress3 = association.Address1_Street3; newClient.BillingCity = association.Address1_City; newClient.BillingState = association.Address1_State_Province; newClient.BillingZip = association.Address1_ZIP_PostalCode != null ? Convert.ToInt32(association.Address1_ZIP_PostalCode) : (int?)null; newClient.BillingCountry = association.Address1_County; } } else { Contact contact = (Contact)service.Retrieve( "contact", opportunity.AssociationOrContact.Id, new ColumnSet(new String[] { "firstname", "lastname", "emailaddress1" }) ); if (contact != null) { newClient.Name = contact.LastName + " Household"; newClient.BillingContactName = contact.FirstName + " " + contact.LastName; newClient.BillingContactEmail = contact.PrimaryEmail; // Address Information doesn't quite line up } } } newClient.Id = newClient.Save(service); return newClient; } Plugin Configuration A: As @HenkvanBoeijen said in the comments on this question the issue was that I was trying to update the opportunity record that had been locked by the system. When I made this plugin a pre-operation plugin and set the values I needed in the target the error went away.
{ "pile_set_name": "StackExchange" }
Q: R: ifelse conditioning -> replace with last value for which condition is true Lets say I have this input: input=data.frame(x=c(2,3,4,5,6,7), y=c(5,5,4,4,3,5)) x y 1 2 5 2 3 5 3 4 4 4 5 4 5 6 3 6 7 5 Now I want to replace value of x if y < 5. In this case I want to take the last x value for which y => 5 Something like this: attach(input) xnew=ifelse(y < 5, "last x value for which y=> 5", x) For the example, the output should look like this: xnew y 1 2 5 2 3 5 3 3 4 4 3 4 5 3 3 6 7 5 What do I have to replace "last x value for which y=> 5" with for this to work? Thanks in advance! A: indx <- input$y[tail(which(input$y <5),1)] input$x[input$y <5] <- indx input # x y #1 2 5 #2 3 5 #3 3 4 #4 3 4 #5 3 3 #6 7 5 Or using data.table library(data.table) setDT(input)[y <5, x:= y[max(which(y <5))]] Update Using the new dataset: input=data.frame(x=c(2,3,4,5,6,7,8,9,10,11,12), y=c(5,5,4,4,3,5,3,5,3,3,5)) indx <- which(c(0,diff(input$y<5))==1) indx1 <- cumsum(which(input$y <5) %in% indx) input$x[which(input$y <5)]<- input$x[indx-1][indx1] input # x y #1 2 5 #2 3 5 #3 3 4 #4 3 4 #5 3 3 #6 7 5 #7 7 3 #8 9 5 #9 9 3 #10 9 3 #11 12 5 A: I would try na.locf from the zoo package. Using your input from the comments input=data.frame(x=c(2,3,4,5,6,7,8,9,10,11,12), y=c(5,5,4,4,3,5,3,5,3,3,5)) input[input$y < 5, "x"] <- NA library(zoo) input$x <- na.locf(input$x) input # x y # 1 2 5 # 2 3 5 # 3 3 4 # 4 3 4 # 5 3 3 # 6 7 5 # 7 7 3 # 8 9 5 # 9 9 3 # 10 9 3 # 11 12 5
{ "pile_set_name": "StackExchange" }
Q: Solve recurrence relation $T(n) = n\cdot T(n/2)^2 $ How would you solve the recurrence $T(n) = n\cdot T(n/2)^2$? Could you use the master method? Or do you have to use iteration? A: We have $$4nT(n) = \left(4\frac{n}{2}T(n/2)\right)^2$$ so that $$F(n) = F(n/2)^2 $$ where $F(n) = 4nT(n).$ Then take logs $$\ln(F(n)) = 2\ln(F(n/2)) $$ so that we have $$ G(n) = 2G(n/2)$$ where $G(n) = \ln(F(n)).$ The solution to this is obvious: when $n$ doubles, so does $G.$ Thus it is a linear function $$ G(n) = an.$$ Unwinding the transformations gives $F(n) = e^{an}$ and $T(n) = \frac{e^{an}}{4n}.$ As for your question about whether the master method works, I'm only familiar with that as a theorem about asymptotics, but when you take logs of the initial equation it immediately becomes a recurrence of that type and you can conclude that the log of the solution is $\Theta(n).$
{ "pile_set_name": "StackExchange" }
Q: Separate UITableView Controller/Delegate Reference Quandary I've been following the guide in the following (StackOverflow question), which has been very helpful, and by completing the steps I've managed to successfully have a UITableView with a separate controller and delegate/datasource. However, even though everything is working, I'm unable to reference or change anything instance of the UITableview. For example: let's say the UIViewController for the table is TableViewController and the separate delegate/datasource class is TableDelegate. I have everything hooked up in interface builder as in the previous SO question. In TableDelegate.m, within viewDidLoad, I put the following: self.navigationItem.leftBarButtonItem = self.editButtonItem; And nothing changes in the UITableView as it should. This includes pushing UIViewControllers, which also has no effect as if the code wasn't even there, although when I NSLog(), it appears it is being run. The odd part, however, is that even though that doesn't work, if I set the table's alpha property to 0, it works. Thanks for any help in advance, let me know if you need any more information to solve the problem. A: From your comments, it looks like both TableViewController and TableDelegate are subclasses of UIViewController. If this is the case, make sure both are being added to the navigation stack by pushing them onto a UINavigationController or adding them to a UITabBarController: otherwise, viewDidLoad may not be called. As an aside, I don't think it's a good idea to have your UITableViewDataSource be a UIViewController subclass when you've already got a UITableViewController to handle that table view.
{ "pile_set_name": "StackExchange" }
Q: Scikits-learn svm SVC simple issue I have a problem which I solved, but I want to know if i am right. on scikit's learn documentation regarding SVM SVC, there is an example to manage unbalanced data by using weights in classes. they put an example where the classes weight are informed in svm.SVC() wclf = svm.SVC(kernel='linear', class_weight={1: 10}) but if a reproduce this command on source code, i get the following error: wclf = svm.SVC(kernel='linear', class_weight={1: 10}) TypeError: __init__() got an unexpected keyword argument 'class_weight' But if put the classes_weight on fit() function the problem is solved: wclf.fit(X, y, class_weight={1: 10}) am I right about this? did anybody ever had this problem? A: The keyword 'class_weight' is not yet implemented in your sklearn version for SVC, but it is for SVC.fit(). sklearn updates their functions sometimes slower than you think, and the documentation you are reading may be /dev/ or /stable/ instead of your version.
{ "pile_set_name": "StackExchange" }
Q: How to destroy session and log out I have a login page and a main page. On the login page I am asking for Username and Password and on the main page I m displaying some values from the database. Problem is with the logout function. I am doing it like this: login.php Page <?php session_start(); if (isset($_POST['submit'])) { //log in code and to go to main.php } if (isset($_REQUEST['logstate'])) { session_destroy(); } ?> main.php Page <a href="login.php?logstate=logout"><img src="logout.png" id="Logout"></a> Now when I click on the log out image, it ends the session, but returns me with the URL: xxxxx.com/login.php?logstate=logout I want it to return me the url: xxxxx.com/login.php A: You can try to redirect <?php session_start(); if (isset($_POST['submit'])) { //log in code and to go to main.php } if (isset($_REQUEST['logstate'])) { session_destroy(); header("Location: xxxxx.com/login.php"); } ?>
{ "pile_set_name": "StackExchange" }
Q: Which one is correct: "was/were dead" or "is/are dead" years ago? What are the differences between “was/were dead” and “is/are dead”? For example, Osama is/was dead years ago. Are they interchangeable? A: Actually the construction "was/is dead years ago" doesn't make sense. The correct way of saying that is: Osama's dead, he died many years ago. A: Edit - "Osama was dead years ago" is fine. "Osama is dead years ago" is NOT fine, as it uses the present tense in a past context. However, the normal way of saying this is Osama has been dead for many years.
{ "pile_set_name": "StackExchange" }
Q: Help with getting started on my own jquery plugin Im making my own little timepicker, calling it xxxtimepicker. Ill paste some code belowe, but the problem is that nothing happens. Any tips/tricks and help when making a addon that works like datepicker? (function($){ var popupname = "timepickerpopup"; function OpenWindow(parentObj) { var popup = $('<div id="'+popupname+'" style="">POPUP</div>'); var offset = $(parentObj).offset(); offset.top += 20; $(popup).offset( offset ); $("body").append(popup); $("body").append('<script>$("#timepickerpopup").dialog({autoOpen: false});</script>'); } function CloseWindow() { $("#"+popupname).remove(); } $.fn.extend({ xxxtimepicker: function() { var defaults = { varname: "val", var2name: "val" }; var options = $.extend(defaults, options); return this.each(function() { var o = options; var obj = $(this); obj.bind("focus", OpenWindow(this)); obj.bind("blur", CloseWindow); }); } }); })(jQuery); A: Put functions OpenWindow() & CloseWindow() inside xxxtimepicker function. Tip: don't use global variables like popupname it creates problems for multiple xxxtimepicker on one page.
{ "pile_set_name": "StackExchange" }
Q: htaccess regex to match all parts of HTTP_HOST If you want to read my question without the explanation, skip to the big bold header below. Ok folks, here we go. First, the code I have: AddType text/x-server-parsed-html .html .htm RewriteEngine On RewriteBase / # checking to see if it's a secure request, then set environment var "secure" to either "s" or "" # RewriteCond %{SERVER_PORT}s ^(443(s)|[0-9]+s)$ [NC] RewriteRule ^(.+)$ - [env=secure:%2] [NC] # Gets the value of the subdomain and puts it into environment variable "sub" # RewriteCond %{HTTP_HOST} ^([^\.]*)(\.)?example.com [NC] RewriteRule ^(.*)$ - [env=sub:%1] [NC] # Determines if the sub domain is blank, w, or ww, then redirects w/301 to www... # RewriteCond %{ENV:sub} ^(w|ww|)$ RewriteRule ^(.*)$ http%{ENV:secure}://www.example.com/$1 [R=301,L] # Gets the highest sub domain and adds it as a top subdirectory to each request # RewriteCond %{REQUEST_URI}:example/%{ENV:sub} !^/([^/]+)[^:]*:\1 [NC] RewriteRule ^(.*)$ /example/%{ENV:sub}/$1 [L] #ErrorDocument 404 /pagenotfound RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?url=$1&%{QUERY_STRING} [PT] So, everything works exactly as desired as it is, except I have to set the domain explicitly, I can't figure out the regex to get it so it will work the same with different domains. Here's how it works: It first determines if the request is secure, and saves that for later. Next, it does a 301 redirect for a request to example.com that either has "w","ww" or "" as a subdomain to www.example.com, thus forcing all requests for the site to use www.example.com, unless you are specifying a sub domain other than (w|ww|www), like "test" or "dev" or whatever is set up. Next, it gets the value of the subdomain (which will always be present, because you've either requested something like "dev.example.com" or it has been redirected to "www.example.com"), and rewrites (not redirects) the request to a subdirectory two levels down. As this is set up, this would be the "www" directory under "example" in the root. Lastly it rewrites (not redirects) the URI to be pretty, no problem there, it's working how I like it. The directory structure is as follows: in the root, there is a directory for every site hosted here (example, anothersite, thirdsite). They are all completely unrelated for the purposes of this htaccess file. Within each directory, there are at least two directories, "www" and "dev". The production site files are in "www" and the development files are in "dev". One could also have a directory here of "test" for a testing environment, or whatever else you wanted, this is just how I'm setting it up. So, what I want is something like: Rewritecond %{HTTP_HOST} ^(match sub domain).(match domain).(match TLD) [NC] RewriteRule ^(.*)$ -[env=sub:%1,env=domain:%2,env=tld:%3] [NC] I know that line two of this works correctly, it's just the regex of line one I can't figure out. Keep in mind, there may or may not be a sub domain specified, and there may or may not be a period preceding the domain. This would allow the entire script to handle any of the sites hosted in the root directory as described by allowing me to rewrite line 23 like: RewriteRule ^(.*)$ http%{ENV:secure}://www.%{ENV:domain}.%{ENV:tld}/$1 [R=301,L] And line 29 like: RewriteCond %{REQUEST_URI}:%{ENV:domain}/%{ENV:sub} !^/([^/]+)[^:]*:\1 [NC] So, I think I've very clearly explained what I have, what I'm trying to do, and what I hope to achieve. Can anyone help with the regex for line 15? A: I know that line two of this works correctly, it's just the regex of line one I can't figure out. Keep in mind, there may or may not be a sub domain specified, and there may or may not be a period preceding the domain. Your regex will look something like this: Rewritecond %{HTTP_HOST} ^(([^\.]+)\.)?([^\.]+)\.([^\.]+)$ [NC] RewriteRule ^(.*)$ - [env=sub:%2,env=domain:%3,env=tld:%4] Which will change the rule line as well (you were missing a space after the "-"), because %1 now backreferences the dot as well.
{ "pile_set_name": "StackExchange" }
Q: What happens when you use string interpolation in ruby? I thought that ruby just call method to_s but I can't explain how this works: class Fake def to_s self end end "#{Fake.new}" By the logic this should raise stack level too deep because of infinity recursion. But it works fine and seems to call #to_s from an Object. => "#<Fake:0x137029f8>" But why? ADDED: class Fake def to_s Fake2.new end end class Fake2 def to_s "Fake2#to_s" end end This code works differently in two cases: puts "#{Fake.new}" => "#<Fake:0x137d5ac4>" But: puts Fake.new.to_s => "Fake2#to_s" I think it's abnormal. Can somebody suggest when in ruby interpreter it happens internally? A: Short version Ruby does call to_s, but it checks that to_s returns a string. If it doesn't, ruby calls the default implementation of to_s instead. Calling to_s recursively wouldn't be a good idea (no guarantee of termination) - you could crash the VM and ruby code shouldn't be able to crash the whole VM. You get different output from Fake.new.to_s because irb calls inspect to display the result to you, and inspect calls to_s a second time Long version To answer "what happens when ruby does x", a good place to start is to look at what instructions get generated for the VM (this is all MRI specific). For your example: puts RubyVM::InstructionSequence.compile('"#{Foo.new}"').disasm outputs 0000 trace 1 ( 1) 0002 getinlinecache 9, <is:0> 0005 getconstant :Foo 0007 setinlinecache <is:0> 0009 opt_send_simple <callinfo!mid:new, argc:0, ARGS_SKIP> 0011 tostring 0012 concatstrings 1 0014 leave There's some messing around with the cache, and you'll always get trace, leave but in a nutshell this says. get the constant Foo call its new method execute the tostring instruction execute the concatstrings instruction with the result of the tostring instruction (the last value on the stack (if you do this with multiple #{} sequences you can see it building up all the individual strings and then calling concatstrings once on all consuming all of those strings) The instructions in this dump are defined in insns.def: this maps these instructions to their implementation. You can see that tostring just calls rb_obj_as_string. If you search for rb_obj_as_string through the ruby codebase (I find http://rxr.whitequark.org useful for this) you can see it's defined here as VALUE rb_obj_as_string(VALUE obj) { VALUE str; if (RB_TYPE_P(obj, T_STRING)) { return obj; } str = rb_funcall(obj, id_to_s, 0); if (!RB_TYPE_P(str, T_STRING)) return rb_any_to_s(obj); if (OBJ_TAINTED(obj)) OBJ_TAINT(str); return str; } In brief, if we already have a string then return that. If not, call the object's to_s method. Then, (and this is what is crucial for your question), it checks the type of the result. If it's not a string it returns rb_any_to_s instead, which is the function that implements the default to_s
{ "pile_set_name": "StackExchange" }
Q: How to have the json output sorted in my case This is the command I am using on Ubuntu to extract data from the original json file: cat results.json | jq -s -c 'sort_by(.name) | .[]' And these are the output I got: {"name":"I-1","node_id":"458d3d44-9d70-473d-87ae-9cd419277c92","console":5005} {"name":"I-10","node_id":"c655c49b-083e-46e7-8866-08020761ffac","console":5023} {"name":"I-11","node_id":"5f62ce93-48ff-420e-9876-e92c01e3d1df","console":5025} {"name":"I-12","node_id":"af9000dd-0653-4c5d-91ae-def37a95d0fb","console":5027} {"name":"I-13","node_id":"5ad2301d-688d-4d70-9d35-07b421f4f893","console":5029} {"name":"I-14","node_id":"2f1fcc75-e642-496a-a822-0d6d0cb46376","console":5031} {"name":"I-15","node_id":"720c786c-8a38-4c0c-93b7-33850160837c","console":5033} {"name":"I-16","node_id":"20516282-7cad-43d8-999b-3c20b1e6c3bd","console":5035} {"name":"I-17","node_id":"e33fa2c1-d36e-4933-ab92-0dad99e2a276","console":5037} {"name":"I-18","node_id":"4215fe76-1b6b-457d-8a38-85e51b4c53ec","console":5039} {"name":"I-19","node_id":"351f85c2-7c9c-4847-b15c-43d35d5bdbcd","console":5041} {"name":"I-2","node_id":"49253898-e628-4ed8-9268-69e6a0b01105","console":5007} {"name":"I-20","node_id":"0575b79c-4060-4ded-ad69-e5da6bcd4d8b","console":5043} {"name":"I-21","node_id":"4ba799eb-e48b-49f3-8bb1-65605be85061","console":5045} ... How may I have the output sorted in numerically way by this "name" value ? Thanx. -Jack A: An only-jq solution: < results.json jq -s -c ' sort_by(.name|sub("I-";"") | tonumber) | .[]'
{ "pile_set_name": "StackExchange" }
Q: Is there a way to switch distributions without losing any data (settings, applications, home folder)? Yes, I know. This might be a duplicate. However, this time it's a bit different. I'm considering of switching from Lubuntu 18.04.1 LTS to Xubuntu (exact same version). I could try the "Something else" option at the "Installation type" screen and not lose any data in the /home folder, however, this deletes the /var, /etc, /lib folders and others, as the popup that appears after the confirmation says. (could not find any image, sorry for that. If an editor can add this, proceed.) So, I was wondering, can I do a distribution switch without losing these folders? Or should I do an upgrade from 18.04 to 18.10 (like this site says) and become a "daredevil" until 20.04 LTS is released? (I mean hopping releases frequently.) Because, although I have created a script which does the job for me (package reinstallation and system updates), I do not want to wait several hours for the PPA addition, package download and system update processes to complete. (I do not really care about settings, nor the default theme/icons. The Xubuntu installation must change these or there will be a conflict. The thing I care the most (besides data in the /home folder) is the packages that I have downloaded over several months.) Can anyone help me? A: I'm considering of switching from Lubuntu 18.04.1 LTS to Xubuntu (exact same version). The only difference between Lubuntu and Xubuntu is the default desktop environment. To install the Xubuntu desktop environment, simply run sudo apt install xubuntu-desktop This will install the Xubuntu desktop. Log out, and select XFCE on the login screen. To remove Lubuntu's desktop, run sudo apt remove lubuntu-desktop && sudo apt autoremove
{ "pile_set_name": "StackExchange" }
Q: get the parent url of iframe in PHP I am creating a widget that would load in a IFrame and users will be able to place the widget on their own website. How would I get the URL of the website that is using the IFrame in javascript and/or PHP? The IFrame loads a php file. I have tried "parent.top.location.href" and "parent.document.referrer" in the IFrame page but that is undefined. I have also tried to echo "$_Server[referrer]" in the IFrame page and that did return the IFrame parent URL, but how easy is it for someone to manipulate the referrer variable? I dont want to get misleading information. The Goal: I created a widget and want to allow registered users to use that widget on their site. I want to be able to find out who is using the widget and if a un-registered user is using it on their site, then the widget would not display A: I have also tried to echo "$_Server[referrer]" in the IFrame page and that did return the IFrame parent URL, but how easy is it for someone to manipulate the referrer variable? Pretty easy, but so is disabling JavaScript! However, if a web site uses your <iframe> it will be a little difficult for them to fake the referrer in their visitor's UA. (They could also proxy your content if they really insist on hiding the fact that they're using your content. In that case your only choice is not to publish it in the first place.) In order to present content for "partners" only you could consider providing them with a token (like Twitter/Google/... APIs). If no (or an invalid) token is used, present an error. If a valid token is used but the referrer is suspicious you should investigate further. A: Try with: parent.location.href; or parent.document.URL
{ "pile_set_name": "StackExchange" }
Q: Extracting data from Wikipedia I am creating a Spring application and I have the need to integrate with Wikipedia. In particular, I would like to extract data on a given (large) set of Cities, e.g. country, website and coordinates. I am trying to understand which libraries or frameworks can be useful, but the big issue I am dealing with is that there is no reference structure for the pages I would like to extract information from. The main problem is not that some information is missing, which would be totally acceptable, but rather the city representation changes from city to city. E.g. the DBPedia ontology (e.g. http://dbpedia.org/ontology/City) does not reflect what I can extract via SPARQL query from dbpedia.org/sparql. This way, I don't know how to extract the data I need systematically (i.e. for my entire set). Is there any technology that can support my task of extracting data on a predefined set of cities? One solution could be to put in place some Natural Language Processing in order to seek for the required info in the entire Wikipedia page, but that requires a lot of effort, if I have to write it on my own. Another solution could be leveraging a source of structured data that pre-processed Wikipedia for me and gave some structure to the contained information, but I could not find one. On third solution could be trying to make different queries to Wikipedia, but I cannot figure out a way to extract the information I need via those Wikipedia APIs. A: Data from Wikipedia is being transfered to Wikidata. Using their API you could get what you want. If you want a shortcut you could use the Wikidata query tool: http://wdq.wmflabs.org/api_documentation.html
{ "pile_set_name": "StackExchange" }
Q: jQuery, array form radio button name problem <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>click div to select hidden options</title> <script type="text/javascript" src="jquery-1.4.4.js"></script> <style type="text/css"> .clickDiv { width:50px; height:50px; cursor:crosshair; } .red {border:1px #000 solid;} .green {border:1px #000 solid;} .redBG {background:#F00;} .greenBG {background:#0F0;} </style> <script type="text/javascript"> $(function() { $('div.clickDiv.red').click(function(){ var secilenMadde=$(this).attr('madde'); $('div#write').text(secilenMadde); $('input[name='+secilenMadde+'][value=red]').attr('checked', 'checked'); $('div.clickDiv.red[madde='+secilenMadde+']').addClass('redBG'); $('div.clickDiv.green[madde='+secilenMadde+']').removeClass('greenBG'); }); $('div.clickDiv.green').click(function(){ var secilenMadde=$(this).attr('madde'); $('div#write').text(secilenMadde); $('input[name='+secilenMadde+'][value=green]').attr('checked', 'checked'); $('div.clickDiv.green[madde='+secilenMadde+']').addClass('greenBG'); $('div.clickDiv.red[madde='+secilenMadde+']').removeClass('redBG'); }); }); </script> </head> <body> <div id="write"></div> <form id="formId" name="formName" method="post"> <table> <tr> <td><div class="clickDiv red" madde="line1"></div></td> <td><div class="clickDiv green" madde="line1"></div></td> </tr> <tr> <td><div class="clickDiv red" madde="line2"></div></td> <td><div class="clickDiv green" madde="line2"></div></td> </tr> </table> <label for="line1red"><input id="line1red" type="radio" name="line1" value="red" /> Red</label> <label for="line1green"><input id="line1green" type="radio" name="line1" value="green" /> Green</label><br /> <label for="line2red"><input type="radio" name="line2" value="red" /> Red</label> <label for="line2green"><input type="radio" name="line2" value="green" /> Green</label> </form> </body> </html> This works. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>click div to select hidden options</title> <script type="text/javascript" src="jquery-1.4.4.js"></script> <style type="text/css"> .clickDiv { width:50px; height:50px; cursor:crosshair; } .red {border:1px #000 solid;} .green {border:1px #000 solid;} .redBG {background:#F00;} .greenBG {background:#0F0;} </style> <script type="text/javascript"> $(function() { $('div.clickDiv.red').click(function(){ var secilenMadde=$(this).attr('madde'); $('div#write').text(secilenMadde); $('input[name='+secilenMadde+'][value=red]').attr('checked', 'checked'); $('div.clickDiv.red[madde='+secilenMadde+']').addClass('redBG'); $('div.clickDiv.green[madde='+secilenMadde+']').removeClass('greenBG'); }); $('div.clickDiv.green').click(function(){ var secilenMadde=$(this).attr('madde'); $('div#write').text(secilenMadde); $('input[name='+secilenMadde+'][value=green]').attr('checked', 'checked'); $('div.clickDiv.green[madde='+secilenMadde+']').addClass('greenBG'); $('div.clickDiv.red[madde='+secilenMadde+']').removeClass('redBG'); }); }); </script> </head> <body> <div id="write"></div> <form id="formId" name="formName" method="post"> <table> <tr> <td><div class="clickDiv red" madde="line[1]"></div></td> <td><div class="clickDiv green" madde="line[1]"></div></td> </tr> <tr> <td><div class="clickDiv red" madde="line[2]"></div></td> <td><div class="clickDiv green" madde="line[2]"></div></td> </tr> </table> <label for="line1red"><input id="line1red" type="radio" name="line[1]" value="red" /> Red</label> <label for="line1green"><input id="line1green" type="radio" name="line[1]" value="green" /> Green</label><br /> <label for="line2red"><input type="radio" name="line[2]" value="red" /> Red</label> <label for="line2green"><input type="radio" name="line[2]" value="green" /> Green</label> </form> </body> </html> This doesn't. I need input names as an array but it breaks my script. Why? The propose of the script is selecting radio buttons by clicking divs. A: OK, I've put your two examples on JSFiddle. Example 1: http://jsfiddle.net/ryKjc/1/ Example 2: http://jsfiddle.net/aN6g9/ Edit: Alright, I finally figured out what you're doing here. In the first example, your secilenMadde variable is either line1 or line2. In the second one, you're using HTML's form arrays and naming the radio button groups line[1] and line[2]. The problem is in your selectors. When you make a selection like this in the second example: $('input[name='+secilenMadde+'][value=red]'); You're doing this: $('input[name=line[1]][value=red]'); Those brackets throw jQuery's selector for a loop, so you must wrap it in double quotes like this: $('input[name="'+secilenMadde+'"][value=red]'); Do this for any place you use the input[name] selector in conjunction with inner angle brackets and it should work. Proof here: http://jsfiddle.net/aN6g9/1/
{ "pile_set_name": "StackExchange" }
Q: Software for testing graph homomorphism I have graphs $G_k$ and $H_k$ with $|\mathcal{V}(G_k)|=|\mathcal{V}(H_k)|^{2k}=n^{2k}$ with $k\in\Bbb N$ that pass sanity checks such as no-homomorphism lemma. Are there free and easy to use tools to test graph homomorphism from $G$ to $H$? A: The best way (in terms of laziness) is to use the freely available tool Sage which has the best support for graph theory. Example sage: G = graphs.PetersenGraph() sage: G.has_homomorphism_to(graphs.CycleGraph(5)) False sage: G.has_homomorphism_to(graphs.CompleteGraph(5)) {0: 0, 1: 1, 2: 0, 3: 1, 4: 2, 5: 1, 6: 0, 7: 2, 8: 2, 9: 1} A: One approach would be to use a SAT solver. Introduce a boolean variable $x_{t,v}$ for each vertex $t$ from $G$ and each vertex $v$ from $H$. The intuition is that $x_{t,v}$ will be true if the homomorphism maps $t \mapsto v$. (Of course, if you have a smaller candidate set of vertices that $t$ could map to -- maybe narrowed down using degree considerations or other local criteria -- then you can reduce the number of boolean variables accordingly. This kind of preprocessing might improve the efficiency of this approach significantly.) Next, add two kinds of clauses/constraints: Add some clauses to require that this mapping forms a graph homomorphism. In particular, for each edge $(t,u) \in E(G)$, add the constraint $$\bigvee_{(v,w) \in E(H)} (x_{t,v} \land x_{u,w}).$$ (You can convert this to 3CNF using the standard Tseitin transform.) Add some clauses to require that each vertex $t$ from $G$ maps to exactly one vertex $v$ from $H$. There are a number of standard methods for encoding this constraint. One simple way is, for each vertex $t \in V(G)$, add the clause $$\bigvee_{v \in V(H)} x_{t,v}$$ and the clause $$\bigwedge_{v,w \in V(H)} (\neg x_{t,v} \lor \neg x_{t,w}).$$ Then, you can use any standard SAT solver. I don't know how well it will work in practice, but you could give it a try and see how it works out. In the research literature, the graph homomorphism problem has been studied extensively for graphs with special properties (e.g., where $H$ is a clique, whre $H$ has bounded treewidth, and so on). If you know something special about the structure of your graphs, it may be possible to find better algorithms for your problem. For general graphs, this problem is known to be NP-hard.
{ "pile_set_name": "StackExchange" }
Q: dynamically select dataframe columns for groupby in python I have a pandas dataframe named Incoming_Tags I can do groupby on the dataframe by mentioning the column names as input to groupby: Example: Incoming_Tags.groupby([ 'Domain','Tag_Name', 'Tag_hierarchy', 'html_attributes']) I want to select columns dynamically for doing groupby. Dynamically means by names. Instead of mentioning the columns names each time in groupby. I have defined a function group_by, which does the following: def group_by(df,myList= [],*args): Incoming_tag_groupby = df.groupby(myList).agg({'char_cnt': np.mean,'line_cnt':np.mean,'digit_cnt':np.mean,'sp_chr_cnt':np.mean,'word_cnt':np.mean}) return Incoming_tag_groupby A: If want aggregate all numeric columns, non numeric are excluded by default: def group_by(df,myList= [],*args): return df.groupby(myList).mean() Or with c list of columns for specify columns for aggregating: def group_by(df,myList= [],*args): c = ['char_cnt','line_cnt','digit_cnt','sp_chr_cnt', 'word_cnt'] return df.groupby(myList)[c].mean()
{ "pile_set_name": "StackExchange" }
Q: Distinguishing between ImmutableJS and native JS data structures? I'm writing a React component that I intend to make public, and I'd like to have it play nice either with JS arrays/objects, or immutable.js equivalents (Map/List). What's the best way to identify an Immutable.js Map or List? I don't want to simply use Array.isArray, because I do want to enforce that it is either an Array or a List, for example. I could just check for some of the Immutable.js properties, like _origin or __ownerID, but I don't want to depend on internal APIs that are subject to change in minor versions. A: I would very much recommend the suggestions given by @robg and @joseph-the-dreamer. However, just for the sake of answering your exact need, for every Immutable.Type there is a Immutable.Type.isType() static function which you can use to determine if a given object is of that type. E.g. Map docs - var im = require("immutable"); if (im.Map.isMap(someObjectWhichMayBeMap)){ ... }
{ "pile_set_name": "StackExchange" }
Q: A certain solution to the 1988 IMO question 6. I recently looked into the 1988 IMO 6, and found a direct proof that I took a liking to, found here: http://hkumath.hku.hk/~mks/MathematicsCompetitions_MKSiu_2012.pdf, on page 5, in the middle of the page. However, I do not understand the part, right before that whole long line of math, the sentence that says that d' can not be positive. If someone would care to explain this to me, as well as possibly share some other relatively easily understood direct proofs, that would be great! A: Although it's a little ambiguous, I think "Proceed as before" implies we are still assuming: $a+b$ is minimal among pairs $(a,b)$ with $a,b>0$ and $a^2+b^2=k(ab+1)$. Since the pair $(d',c)$ also satisfies the equation and has $c>0$ and $d'+c<a+b$, it must fail the remaining condition $d'>0$.
{ "pile_set_name": "StackExchange" }
Q: What is this medieval fantasy TV show? I remember seeing a TV show in the 90s (I am not sure when it was first aired). It...: Has a medieval setting Has a handful of heroes, all young men and women (ie: mid to high teens) à la Power Rangers The protagonists use weapons/powers based on the classical elements: Fire, Water, Earth, Air/Wind Does anyone know what the name of the show? A: Could it have been the Mystic Knights of Tir Na Nog? That was very much like Power Rangers.
{ "pile_set_name": "StackExchange" }
Q: VISUDO: passwordless sudo does not work for user I've altered my /etc/sudoers file with sudo visudo as follows (showing only uncommented lines, the entire file can be found here): $ grep -v '^#[^i]' /etc/sudoers/ | grep . root ALL=(ALL) ALL %wheel ALL=(ALL) NOPASSWD:ALL #includedir /etc/sudoers.d Basically, I have just uncommented one line, which should disable sudo password entry for all members of the wheel group. My user is part of the wheel group as shown in the output of groups [username]: sys lp wheel network video optical storage scanner power ruben However, it is not working, since I have to enter a password every time I open a new terminal window. I've rebooted a couple of times already. What am I missing? EDIT1: id command returns: uid=1000(ruben) gid=1000(ruben) groups=1000(ruben),3(sys),7(lp),10(wheel),90(network),91(video),93(optical),95(storage),96(scanner),98(power) A: As Gilles pointed out there is a file /etc/sudoers.d/10-installer containing %wheel ALL=(ALL) ALL. The 10-installer file is included in /etc/sudoers, after the change I made. This inclusion overwrites my change to the /etc/sudoers file.
{ "pile_set_name": "StackExchange" }
Q: insert Element at specific position I started Prolog (just for my own) and i am struggling with recursion. I want a "method", that inserts an element at a specific position within a list. What i tried so far is : insertAt(Element,Position,List,ResultList) insertAt(Element,0,L,[Element|L]). insertAt(Element,Pos,[E|L],ZL):- Pos1 is Pos-1, insertAt(Element,Pos1,L,ZL), append(E,ZL1,ZL). I find i quite complicated, since i cant understand how the recursion exactly works... Maybe someone can help me out. A: There are several features of your code that make it hard to understand for beginners. In particular, the use of moded, low-level arithmetic is a severe impediment when interacting with the program in a playful (and in fact also in a serious) way. For example, to understand a relation, it is useful to start with the most general query. This only asks "Is there any solution at all, and if so, what does a solution look like?". In your specific example, the most general query looks like: ?- insertAt(E, Pos, Ls0, Ls). and this almost immediately yields an instantiation error due to the non-declarative arithmetic predicates you are using: ?- insertAt(E, Pos, Ls0, Ls). Pos = 0, Ls = [E|Ls0] ; ERROR: insertAt/4: Arguments are not sufficiently instantiated In addition, you are impeding a nice declarative reading by using an imperative name ("insert..."). This makes it unnecessarily hard to develop a feeling for relational programming. Therefore, I recommend you: (1) Use a more declarative predicate name, and (2) use a symbolic representation of natural numbers that makes the predicate easier to understand and more general. I will use the number 0 to represent zero, and the term s(X) to represent the successor of the number X. See successor-arithmetics for more information about this representation. With these changes, the code becomes: element_at(E, 0, [_|Ls], [E|Ls]). element_at(E, s(X), [L|Ls0], [L|Ls]) :- element_at(E, X, Ls0, Ls). To understand this program, we read it declaratively: The first clause is true if the position is 0, and the head of the final list is E, and the tail ... etc. The second clause is true if element_at(E, X, Ls0, Ls) holds, and the head of ... etc. Nicely, the most general query now works much better: ?- element_at(E, Pos, Ls0, Ls). Pos = 0, Ls0 = [_G1071|_G1072], Ls = [E|_G1072] ; Pos = s(0), Ls0 = [_G1073, _G1079|_G1080], Ls = [_G1073, E|_G1080] ; Pos = s(s(0)), Ls0 = [_G1073, _G1081, _G1087|_G1088], Ls = [_G1073, _G1081, E|_G1088] . Notice though that there is something unfair going on here: Where are answers for remaining positions? For fairer enumeration, we use length/2, stating in advance the length of the lists we are considering one after another: ?- length(Ls0, _), element_at(E, Pos, Ls0, Ls). Ls0 = [_G1124], Pos = 0, Ls = [E] ; Ls0 = [_G1124, _G1127], Pos = 0, Ls = [E, _G1127] ; Ls0 = [_G1124, _G1127], Pos = s(0), Ls = [_G1124, E] . And now it is clearer how the different arguments interact, because you already see various examples of terms that are described by your predicate. In fact, to reduce the number of arguments and variable names we need to keep track of, I often use DCG notation when describing lists, and I would like to show you this alternative version too: element_at(Element, 0, [_|Ls]) --> [Element], list(Ls). element_at(Element, s(X), [L|Ls]) --> [L], element_at(Element, X, Ls). list([]) --> []. list([L|Ls]) --> [L], list(Ls). ?- length(Ls0, _), phrase(element_at(E, Pos, Ls0), Ls). Ls0 = [_G1148], Pos = 0, Ls = [E] ; Ls0 = [_G1148, _G1151], Pos = 0, Ls = [E, _G1151] ; Ls0 = [_G1148, _G1151], Pos = s(0), Ls = [_G1148, E] . Once you read up on dcg notation, this version will become clear to you. At last, you may say "Well, that's nice, but s(X) notation still seems quite strange", and you may want to use the more widely used Hindu-Arabic notation for integers in your programs. For this, we can simply take either version from above and replace s(X) notation by declarative integer arithmetic with CLP(FD) constraints. For example, with the first version: :- use_module(library(clpfd)). element_at(E, 0, [_|Ls], [E|Ls]). element_at(E, X, [L|Ls0], [L|Ls]) :- X #> 0, X #= X0 + 1, element_at(E, X0, Ls0, Ls). This also works in all directions, exactly as we expect from a nicely declarative and general predicate: ?- length(Ls0, _), element_at(E, Pos, Ls0, Ls). Ls0 = [_G2095], Pos = 0, Ls = [E] ; Ls0 = [_G2095, _G2098], Pos = 0, Ls = [E, _G2098] ; Ls0 = [_G2095, _G2098], Pos = 1, Ls = [_G2095, E] . Please see clpfd for more information, and I hope this post encourages you to think more relationally about your Prolog code, try it in all directions, and read it declaratively. (What is being described?)
{ "pile_set_name": "StackExchange" }
Q: How do you know death is near for a person as per scriptures? Is there any reference? I have seen an old man suffering for long where as healthy young man died. So is there any mention in scriptures or any indication of a man dying? I have googled around and found few answers which contradict any scripture. Where can I refer? A: Some signs, which foretell that death is nearing, are given in this Linga PurAna chapter: Suta Maha Muni indicated certain premonitions of untoward tidings and of death when human beings ought to intensify virtuous deeds as the last breathing might arrive. The visions of Arundhati, Dhruva and the Celestial routes would mean that a person concerned might not last more than a year. Vision of Surya without rays and Agni with rays might indicate an eleven month end ahead; Mutra and Pureesha as gold and silver indicates that the end might approach within ten months; seeing a Golden Tree, or visit of a Gandharva Nagari or visions of Preta-Piscachas might allow a further life of nine months more; dream of a very huge monster or a skeletal figure could forewarn an eight month ahead; image of dust storm or muddy rain could indicate the end within seven months; a dream of a crow, or a kite or dove or any other meat-eating bird on a person’s head might presume death within six months; Straight lined crows flying on the sky could indicate death within the next four five months; thunders on a cloudless and clear sky or rainbow seen in a water body or a distorted image of one’s own self that the end might be within a couple of months; death is stated to be destined within a month when the person concerned would vision the self without head; an experience of the smell of a dead body or of unbearably rotten food could imagine that death might be withi some twenty five days; monkey dance while riding a chariot towards South might sign-post already; a black robed woman leading a person towards South, vision of a headless body , a naked Sanyasi dancing, red face and yellow cheeks are signs of death. .......................................... The following part is added by user Tamas. So, credit goes to him. On connecting on shadow also one can predict according to Swara yoga. See the pic. A: Some signs, which foretell that death is nearing, are given in 43rd chapter of Markandeya Purana (Sanskrit shlokas and Hindi Translation) 19th chapter of Vayu Purana (Sanskrit shlokas and Hindi Translation) The English Translation is given Vayu Purana unabridged English translation Markandeya Purana abridged English translation Vayu Purana abridged English translation Vayu Purana - CHAPTER NINETEEN : Evil Omen Foreboding Death Vayu said: Henceforth I shall explain the evil omens. Know that by seeing them one can foresee one's death. He who cannot see the Arundhati star, the Pole star, the shadow of the moon and the Mahdipatha does not survive a year thereafter. He who sees the sun bereft of rays and the fire with rays (radiating from it) will not survive the eleventh month. He who vomits urine, cow-dung, gold or silver either while awake or in dream, will not survive ten months. He whose feet crack either in front or at the back, or become dusty or marshy, lives only for seven months. If a crow, a dove, a vulture or any other bird of prey settles on his head, he does not survive six months. He who is obstructed by rows of crows or by a dust storm, lives only for four or five months. He who sees lightning without clouds, in the southern direction, or water or the rainbow (without the existence of clouds) lives only for two or three months. He who does not see his reflection either in water or in a mirror or who sees his reflection without the head does not survive a month. If the body smells like a corpse or like burning fat, death is imminent. He lives only for a fortnight. If a biting wind seems to pierce the vulnerable points of one's body or if no sensation is experienced after touching water, death is imminent for him. If he dreams that he is singing and proceeding to the south on a chariot to which bears and monkeys are yoked, it shall be known as a sign of imminent death. If he dreams that he is being led to southern direction by a dark singing woman wearing black garment, he does not survive long. If he dreams that he wears black rags or that his ear is broken, it shall be known as a sign of imminent death. If he dreams that he is immersed in a marshy sea upto the head, he does not survive long after seeing the dream. He who sees (in dream) ashes, burning coals, hair, dry river and serpents will not survive ten nights. If he dreams that he is being beaten by hideous dark skinned men with weapons and stones in their hands, he dies soon. If a howling vixen rushes directly at him early in the morning at sunrise, his death is imminent. If he feels acute pain in the chest and morbid senstitiveness in the teeth immediately after taking bath, his death is immiment. If he gasps for breath during night or day and is unable to discern the smell of a oil lamp, know that his death is imminent. If he were to see the rain-bow at night and the cluster of stars during the day, and if he is unable to see his reflection in others' eyes, he does not live long. He, one of whose eyes begins to water, whose ears are dislodged from their places and whose nose becomes crooked (and curved) should be known as approaching death. Death is imminent to him whose tongue is black and rough and whose face appears muddy and whose cheeks are ruddy and flattened. A man who (in dream) goes to the southern direction with hair dishevelled, laughing, singing and dancing, meets with the imminent end of life. He who perspires frequently, the sweatdrops being like white mustard seeds, dies very soon. He who in dream, goes to the south in a chariot to which camels or donkeys are yoked does not live long.' These are two extermely ill omens, viz. he does not hear loud noise with his ears and does not see bright light with his eyes. If he sees in dream that he has fallen in a ditch and that there is no door to escape through and that he is unable to stand up from the ditch, that marks the end of his life. One is definitely in difficult situation if the eye moves upward without steadiness, becomes red and begins to whirl round, if the mouth becomes hot, if the umbilicus is porous and the urine is very hot. If a man is directly hit during the day or night and sees the attacking man (in dream), the man so hit does not live long. If a man dreams that he is entering fire but does not remember the details after waking up, that marks the end of his life. Death is imminent to the man who sees his white covering cloth as red or black in dream. The effects of these symptoms can be minimized: A wise man should eschew fear and dejection when death approaches him as indicated by the ill omens. He should then start from his house and walk to the east or to the north. With a pure mind he should sit in a level spot isolated and devoid of crowds. He should perform Acamana and sit facing north or east. He should sit in the Stastika posture. After bowing down to Lord Siva he should keep his body, head and neck straight. His posture is comparable to a lamp in a windless place where it is steady (not flickering)'. He should practise Yoga in a spot sloping to the east or north. He shall perform Dhirand in the vital breath, eyes, skin, ears, mind, intellect and chest. He shall take particular delight in keeping Dhdragd in the vital breath. After realizing the advent of death and the groups (of ill omens) he shall perform Yoga-Dharanás in the parts of the bodies twelve times. He shall perform hundred or hundred and eight Dharands on the head. Without Dharanás in the Yoga, the breath does not function properly (goes anywhere). Then with a purity of mind, he should fill the body with Omkara. Thus full of Omkara, he does not perish. He becomes imperishable.
{ "pile_set_name": "StackExchange" }
Q: Vertical align text with icon with shaded box and corner on top only I've a button already created and this is how HTML appear as below: <div class="blue_text"><button class="blue_small" id="blue_small"></button> View this video instead.</div> CSS as below. The text to align vertically without changing the existing markup: #blue_text{ color:#48c4d2; font-size:15px; font-family:opensansitalic;} Used this to vertical align the button without changing the existing mark up. ​button { vertical-align:middle; } The button CSS in total: .blue_small { height: 40px; width: 40px; margin-left:16px; margin-bottom:1px; background-color:#fff; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; border: 3px solid #fff; background:url(../images/index_video_small2.svg) no-repeat 5px 7px; -webkit-box-shadow: 0px 2px 6px rgba(64,80,85,0.8); -moz-box-shadow: 0px 2px 6px rgba(64,80,85,0.8); box-shadow: 0px 2px 6px rgba(64,80,85,0.8); color:#48c4d2; font-size:15px; font-family:opensansitalic;} I'd like to combine all of the above into CSS as below with cyan colour shading box? I've never tried this. align top http://www.kerrydeaf.com/shade2.png UPDATE: I have this < div >< /div > at the bottom of another container but there is gap visible and tried to close the gap without success? I'm using a current < div >< /div > as below. <div class="blue_text"><button class="blue_small" id="blue_small"></button> View this video instead.</div> This is a gap visible as below: align top http://www.kerrydeaf.com/shade4.png I'm hoping to use this < div class="blue_text" > View this video instead.< /div > to close the gap as below with margin '0'. align top http://www.kerrydeaf.com/shade3.png UPDATE FRIDAY 2pm: Thank you it worked a treat. It went to a bottom of a browser window. I'm hoping that the blue box to close in between DIV tags for example with this DIV tag as below. This div class="toogle_wrap" is one DIV container where I've highlighted a gap to close as below. There will be at least five div class="toogle_wrap", this is one div class="toogle_wrap" below so the gap need to close on each of them. <div class="toogle_wrap"> <div class="trigger"><a href="#"><span class="trig">1.</span> Deaf person's attention</a></div> <div class="toggle_container"> <ul class="lists"> <li>Learn <span class="bold">how to get</span> a Deaf person's attention.</li> <li>Take a step-by-step process.</li> <li>Approaching a Deaf and your approach may suggest your intention to communicate.</li> <li>You can also <span class="bold">wave</span> to get eye contact or <span class="bold">tap</span> the person gently on the shoulder.</li> <!--<li><span class="bold">Watch a video instead:</span> <span class="typicons">Z</span> <span class="typicn"<h5>Z</h5></span> </li>--> </ul> <div class="blue_text"><button class="blue_small" id="blue_small"></button> Available in video.</div> <<<<<<<<<< The gap is here to close here >>>>>>>>. <<<<<<<<<< The gap is here to close here >>>>>>>>. <<<<<<<<<< The gap is here to close here >>>>>>>>. <<<<<<<<<< The gap is here to close here >>>>>>>>. <<<<<<<<<< The gap is here to close here >>>>>>>>. </div> </div> UPDATE Friday 10pm. Here is the example of DIV. Which DIV is position: relative should go in? align top http://www.kerrydeaf.com/div.png A: See my WORKING example here: http://jsfiddle.net/2x6ub/3/ div.toggle_container { position: relative; // this makes the blue_text div being able to align to bottom border: 1px solid #000; height: 300px; // this is just to test, remove or adjust } .blue_text{ background:#48c4d2; color:#fff; font-size:20px; font-family:opensansitalic; width:400px; font-style:italic; padding:20px; border-top-left-radius:20px; border-top-right-radius:20px; -moz-border-top-left-radius:20px; -moz-border-top-right-radius:20px; -webkit-border-top-left-radius:20px; -webkit-border-top-right-radius:20px; /* to align to bottom of parent container */ position: absolute; bottom: 0px; }
{ "pile_set_name": "StackExchange" }
Q: R: How to take the min and max or other functions of every n rows I have a dataframe of which I put one variable into a vector. From this vector, I would like to calculate for every 5 values mean, min and max value. I have managed to calculate the means in this way: means <- colMeans(matrix(df$values, nrow=5)) I know I can calculate the min and max like this: max <- max(df$values[1:5]) min <- min(df$values[1:5]) How do I repeat this for every five values? Edit: Aditionally, how can I get statistic and p-value from a 1-sample t-test for each n-row? A: 1) tapply Below g is a grouping variable consisting of fives ones, fives twos and so on. range provides the minimum and maximum resulting in a list output from tapply and then simplify2array reduces that to an array. Omit the simlify2array if you want a list output. out[1, ] would be the minima and out[2, ] would be the maxima. values <- 1:100 # test input n <- length(values) g <- rep(1:n, each = 5, length = n) out <- simplify2array(tapply(values, g, range)) giving: > out 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 [1,] 1 6 11 16 21 26 31 36 41 46 51 56 61 66 71 76 81 86 91 96 [2,] 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 2) aggregate This would also work: ag <- aggregate(values, list(g = g), range) giving this data.frame where the first column is g and the second column is the transpose of the matrix in (1). Here ag[[2]][, 1] is the minima and ag[[2]][, 2] is the maxima. If you want to flatten ag try do.call(data.frame, ag) or do.call(cbind, ag) depending on whether you want a 3 column data frame or matrix. > ag g x.1 x.2 1 1 1 5 2 2 6 10 3 3 11 15 4 4 16 20 5 5 21 25 6 6 26 30 7 7 31 35 8 8 36 40 9 9 41 45 10 10 46 50 11 11 51 55 12 12 56 60 13 13 61 65 14 14 66 70 15 15 71 75 16 16 76 80 17 17 81 85 18 18 86 90 19 19 91 95 20 20 96 100 A: You can use sapply and split for this: sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), mean) sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), min) sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), max) If you want the outputs in a matrix you can use what @lmo proposed in the comments: sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), function(x) c(mean=mean(x), min=min(x), max=max(x))) Update How to get statistic and p-value from a sample t-test for each n-row: This would be a bit harder to implement. Look below; #mu=3 for sample t-test t_test_list <- sapply(split(df$value, rep(1:(nrow(df)/5), each=5)), t.test, mu=3) p_value_list <- lapply(as.data.frame(t_test_list),function(x) x$p.value) statistic_list <- lapply(as.data.frame(t_test_list),function(x) x$statistic) p_value_list and statistic_list are p.value and statistic for each 5 rows.
{ "pile_set_name": "StackExchange" }
Q: Simple Bash backup script - follow-up As a follow up to a previous question, linked here, I have revised the code and developed what I believe to be a better solution. In summary, the script should backup all files in a particular directory, and assign them to a particular zip file based on their modification dates. This should only occur for files modified yesterday and older, and skip files with the ".zip" extension. Please let me know if their are any improvements that you would make? From testing the code, it has been working with no issues: #!/bin/bash yestdayend=$(date --date="yesterday" +"%Y-%m-%d 23:59:59") path=/path/to/dir filelist=$(find $path -maxdepth 1 ! \( -name "*.zip" \) -type f ! -newermt "$yestdayend") for file in $filelist do moddate=$(stat -c %y $file | cut -d " " -f 1) if zip -rv $path/"logbackup-"$moddate.zip $file; then rm $file fi done A: Saving the output of find in a variable and looping over it is not a good idea in general: filenames with white-space (space, tab, newline) will be split, so the loop will not work on them. It would be a little bit better to use a while loop instead: find ... | while read file do # ... done But this is still not great, as it won't protect you from newlines. But for your use case, it might be good enough. For a more robust solution, see this other post. The \( ... \) is pointless here: find $path -maxdepth 1 ! \( -name "*.zip" \) -type f ! -newermt "$yestdayend" This is the same, but shorter and simpler: find $path -maxdepth 1 ! -name "*.zip" -type f ! -newermt "$yestdayend" It's a bit odd to quote "logbackup-" here: if zip -rv $path/"logbackup-"$moddate.zip $file; then Literal strings like that don't need quoting in Bash. On the other hand, it would be good to quote $path: if zip -rv "$path"/logbackup-$moddate.zip $file; then
{ "pile_set_name": "StackExchange" }
Q: Mouse Hover trigger not working after changing background color programmatically I have a project where I introduced a trigger for a button that changed the background color of the button when the mouse hovers it. This is what it looks like: <Window.Resources> <Style x:Key="ButtonStyleDefault" TargetType="{x:Type Button}"> <Setter Property="Background" Value="White"/> <Setter Property="Margin" Value="1.8"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="Focusable" Value="False"/> <Setter Property="IsTabStop" Value="False"/> <Setter Property="FontWeight" Value="DemiBold"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Border Background="{TemplateBinding Background}" BorderThickness="1" BorderBrush="DarkGray"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Background" Value="LightGray"/> </Trigger> </Style.Triggers> </Style> </Window.Resources> I have no issues with this and it works as expected. These buttons are part of a numpad, so the same effect should happen when I press the number key on the keyboard. This is the function that is reponsible for applying that effect on the button private async void HandleButtonEffects(Button button) { if (button is null) { return; } button.Background = new SolidColorBrush(Colors.LightGray); await Task.Delay(80) .ConfigureAwait(true); button.Background = new SolidColorBrush(Colors.LightGray); } This also works fine. The problem is, the trigger stops working and hovering the button will have no effect. My assumption is that the trigger is somehow a child of the Background property and, by overriding it, I am overriding the trigger as well. I might be able to derive from button and create a public function that simulates the hovering and call that from the HandleButtoneEffect function? But I would like to avoid this as much as possible How can I solve this? A: button.Background = new SolidColorBrush(Colors.LightGray); - this line assigns local value to dependecy property. Local value has high precedence and trigger cannot override it. You can call ClearValue to restore style effect: private async void HandleButtonEffects(Button button) { if (button is null) { return; } button.Background = new SolidColorBrush(Colors.LightGray); await Task.Delay(80).ConfigureAwait(true); button.ClearValue(Button.BackgroundProperty); }
{ "pile_set_name": "StackExchange" }
Q: Guard always return true I have two pretty similar guards in angular app. First of them checking is User logged in: // isUser guard export class isUser implements CanActivate { constructor( private fireAuth: AngularFireAuth, private router: Router ) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.fireAuth.authState.pipe( take(1), map(authState => !!authState), tap(auth => !auth ? this.router.navigate(['/']) : true) ) } } And this one work properly: when user is not logged in it's not allow him to open protected page. The next guard is almost the same, but it check if user in not logged in: export class isGuest implements CanActivate { constructor( private fireAuth: AngularFireAuth, private router: Router ) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.fireAuth.authState.pipe( take(1), map(authState => !!authState), tap(auth => auth ? this.router.navigate(['/']) : true) ) } } The difference only is: !auth ? this.router.navigate(['/']) vs auth ? this.router.navigate(['/']). But isUser guard work good, and isGuest always allow page for user. What I did wrong, and why it's can not work? A: The value emitted by both observables is the same: !!authState, but they shouldn't since one is supposed to emit true only when the user is authenticated, and the other is supposed to emit true only when the user is NOT authenticated. map() and tap() do different things. map() tranforms the emitted event into something else. tap() produces a side effect and leaves the emitted event as is.
{ "pile_set_name": "StackExchange" }
Q: Relation between associated primes and primary decomposition for non-finite modules Theorem 6.8(ii) p.41 in Matsumura's Commutative Ring Theory, says that if $A$ is a Noetherian ring, $M$ a finite $A$-module and $N=N_1 \cap \cdots \cap N_s$ an irredundant primary decomposition of a proper submodule $N$ with $Ass(M/N_i) = \left\{P_i \right\}$, then $Ass(M/N) = \left\{P_1, \cdots, P_s \right\}$, where $Ass(\cdot)$ stands for "associated primes". According to my understanding, the proof does not use the fact that $M$ is a finite $A$-module. I would like to confirm that the statement of theorem 6.8(ii) is valid even if $M$ is not finite over $A$ (however $A$ must still be Noetherian). A: $\DeclareMathOperator{\Ass}{Ass}$ Everything follows from two facts. The first is the "short exact sequence property" of associated primes. That is, given a short exact sequence of $A$-modules, the $\Ass$ of the left module is contained in the $\Ass$ of the middle, and the $\Ass$ of the middle is contained in the union of the $\Ass$'es of the two sides. The second is the fact that any nonzero $A$-module has an associated prime (which in turn requires that $A$ be Noetherian). First, to simplify notation, we may mod out by $N$ to assume that $N=0$, so that what you really have is an irredundant primary decomposition of the zero module. Next, there is a natural homomorphism $$M \hookrightarrow \bigoplus_{i=1}^s M/N_i$$ that is injective since its kernel is $\bigcap_{i=1}^s N_i = 0$, and hence $\Ass M \subseteq \Ass \left(\bigoplus_{i=1}^s M/N_i\right) = \bigcup_{i=1}^s \Ass(M/N_i) = \{P_1, \ldots, P_s\}$ (where the first equality follows from induction on the short exact sequence property). For the reverse containment, by symmetry it is enough to show that $P_1 \in \Ass M$. Consider the following composition of natural homomorphisms: $$ N_2 \cap \cdots \cap N_s \hookrightarrow M \twoheadrightarrow M/N_1. $$ This composition is an injection. Hence, $\Ass (N_2 \cap \cdots \cap N_s) \subseteq \Ass(M/N_1) = \{P_1\}$. But $N_2 \cap \cdots \cap N_s \neq 0$ (by irredundancy) and since any nonzero $A$-module has an associated prime, $\Ass (N_2 \cap \cdots \cap N_s) = \{P_1\}$. But since $N_2 \cap \cdots \cap N_s$ is a submodule of $M$, it follows that $P_1 \in \Ass M$.
{ "pile_set_name": "StackExchange" }
Q: Effect of diagonal orthogonal matrices Let $\{U_i\}$ be the set of orthogonal matrices that are diagonal. The diagonal elements of any $U_i$ are all therefore $\pm 1$. We also have $1\leq i\leq 2^d$, where $d$ is the dimension of the matrix. Let $\rho$ be any positive semidefinite matrix with unit trace (I'm not sure if these properties are important). Let $\rho_i = U_i\rho U^{-1}_i$. It is claimed that the average $\rho_i$ over all $i$ is $\rho_D$, the matrix obtained by dropping the off diagonal terms from $\rho$ and only keeping the diagonal entries. I'm not really sure how to prove this. Can anyone help? A: Let $U$ be an orthogonal diagonal matrix and $A$ any matrix. Then the $i,j$-th entry of $UAU^{-1}$ is given by $$(UAU^{-1})_{ij}=u_{ii}u_{jj}a_{ij}.$$ Hence $i,j$-th entry of the average of all conjugates of $A$ over diagonal orthogonal matrices is $$\left[\frac{1}{2^d}\sum_{k=1}^{2^d}U_kAU_k^{-1}\right]_{ij} =\frac{1}{2^d}\sum_{k=1}^{2^d}(U_kAU_k^{-1})_{ij}=\frac{1}{2^d}\sum_{k=1}^{2^d}(u_k)_{ii}(u_k)_{jj}a_{ij},$$ where $(u_k)_{ii}$ denotes the $i$-th diagonal entry of $U_k$. This expression already shows that the diagonal of the average is precisely the diagonal of $A$; if $i=j$ then $(u_k)_{ii}=(u_k)_{jj}$ for all $k$ and hence $(u_k)_{ii}(u_k)_{jj}=1$, so $$\frac{1}{2^d}\sum_{k=1}^{2^d}(u_k)_{ii}(u_k)_{ii}a_{ii}=\frac{1}{2^d}\sum_{k=1}^{2^d}a_{ii}=a_{ii}.$$ On the other hand, $i\neq j$ then for each $k$ let $V_k$ be the matrix obtained from $U_k$ by changing the sign of the $i$-th diagonal entry. This splits the set of diagonal orthogonal matrices into pairs $(U_k,V_k)$ satisfying $$(v_k)_{ii}(v_k)_{jj}=-(u_k)_{ii}(u_k)_{jj},$$ from which it follows that $$\frac{1}{2^d}\sum_{k=1}^{2^d}(u_k)_{ii}(u_k)_{jj}a_{ii} =\frac{1}{2^d}\sum_{k=1}^{2^{d-1}}((u_k)_{ii}(u_k)_{jj}+(v_k)_{ii}(v_k)_{jj})a_{ij}=0.$$ This shows that the off-diagonal entries of the average are all $0$, which concludes the proof.
{ "pile_set_name": "StackExchange" }
Q: Failed to execute goal org.codehous.mojo:exec-maven-plugin:1.4.0:java I've been trying to run this Maven program all day but to no avail. I keep getting this error: [ERROR] Failed to execute goal org.codehous.mojo:exec-maven-plugin:1.4.0:java (default-cli) on project get-with-jersey: The parameters ‘mainClass’ for goal org.codehaus.mojo:exec-maven-plugin:1.4.0:java are missing or invalid After running mvn exec:java. mvn clean install works fine and builds, but running the program fails. I downloaded and placed the plugin for 1.4.0 where I believe Maven lets all it's plugins exist, but I can't figure out why it keeps crashing. Here is my pom.xml. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bridge.rest.jersey</groupId> <artifactId>get-with-jersey</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Get Request with Jersey</name> <repositories> <repository> <id>maven2-repository.java.net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2/</url> <layout>default</layout> </repository> </repositories> <dependencies> <!-- <dependency> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> </dependency> --> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-client</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-json</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>org.hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>2.0.0</version> </dependency> </dependencies> Thanks for your help, looking forward to your answers! A: You have not specified the main class to run: mvn exec:java -Dexec.mainClass=foo.bar.MainClass http://www.mojohaus.org/exec-maven-plugin/java-mojo.html
{ "pile_set_name": "StackExchange" }
Q: Is there a way to ensure two arguments passed to a function are treated as the first and third argument in C++? Suppose there is a function with the following prototype: void fun (int = 10, int = 20, int = 30, int = 40); If this function is called by passing 2 arguments to it, how can we make sure that these arguments are treated as first and third, whereas, the second and the fourth are taken as defaults. A: // three and four argument version void fun (int a, int b, int c, int d = 40) { ... } // two argument version void fun (int a, int c) { fun(a, 20, c, 40); } // one and zero argument version void fun(int a = 10) { fun(a, 20, 30, 40); } But really my advice would be don't. A: You can define the Args structure like: struct Args { int a = 10; int b = 20; int c = 30; int d = 40; }; and then you would have the following: void fun(Args); fun({.a=60, .c=70}); // a=60, b=20, c=70, d=40 Besides this approach, you can use NamedType library that implements named arguments in C++. For more usage info, check here. UPDATE Designated initializers feature is available by GCC and CLANG extensions and, from C++20, it is available by C++ standard.
{ "pile_set_name": "StackExchange" }
Q: Missing Template though routing seems to work When I generate a new controller, under a subfolder, it now cannot find the templates, even though other controllers in the same 'structure' are working: I have the following controller which sits in app/members/group_controller.rb (created by a rails g controller Members::Group command) class Members::GroupController < ApplicationController def index render :layout => 'dashboard' end end I have a template in views/members/group/index.html.erb I have the following relevant line in routes.rb (ie leaving out some others for clarity): namespace :members do match '/group' => 'group#index' end rake routes shows me the following relevant line: members_group /members/group(.:format) members/group#index When I type the url http://127.0.0.1:3000/members/group, I get the Template Missing error as follows: Template is missing Missing template members/group/index, application/index with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :arb, :coffee]}. Searched in: * "/Users/mitch/Documents/Development/TME/app/views" * "/Users/mitch/.rvm/gems/ruby-1.9.2-p290/bundler/gems/active_admin-7c3e25f30224/app/views" * "/Users/mitch/.rvm/gems/ruby-1.9.2-p290/gems/kaminari-0.13.0/app/views" * "/Users/mitch/.rvm/gems/ruby-1.9.2-p290/gems/devise-2.0.0/app/views" The routing is working to the index method, because I can eg put in a redirect and it gets acted upon, but I cannot get the template to display. Why so? Thanks (Rails 3.1) A: This seems to be linked to how I generate the controller in the first place. I used upper case as follows: rails g controller Members::Group (and tried a few other test controllers similarly, destroying them and recreating them) When I destroyed the controller and ran the lower case equivelant: rails g controller members::group all works fine and the templates can be found I can't find any info elsewhere to support this though...
{ "pile_set_name": "StackExchange" }
Q: How to delete all tables in Oracle XE 11.2 using Application Express? I installed Oracle Express Edition 11.2, and have created an outline. Using SQL Developer, SQL to practice, the problem is that every time you create a workspace, sample tables are created. How I can delete those tables that are automatically created? The tables are in the red box are those that are automatically created each time you create a workspace. A: The tables you listed in your screenshot are created automatically by Application Express when the workspace is created. Some of them can be avoided by setting Create demonstration objects in new workspaces and Create Websheet objects in new workspaces to No (under Manage Instance -> Feature Configuration). They are generally safe to drop - but note that the demo application will no longer work, and since the APEX$.. tables are used by Websheets, you won't be able to create Websheet applications in that workspace. This is the script I used on my last project where we didn't need any of this stuff (adapt to your list as required): DROP SEQUENCE DEPT_SEQ; DROP SEQUENCE EMP_SEQ; DROP TABLE DEPT PURGE; DROP TABLE EMP PURGE; DROP TABLE APEX$_ACL PURGE; DROP TABLE APEX$_WS_FILES PURGE; DROP TABLE APEX$_WS_HISTORY PURGE; DROP TABLE APEX$_WS_LINKS PURGE; DROP TABLE APEX$_WS_NOTES PURGE; DROP TABLE APEX$_WS_ROWS PURGE; DROP TABLE APEX$_WS_TAGS PURGE; DROP TABLE APEX$_WS_WEBPG_SECTIONS PURGE; DROP TABLE APEX$_WS_WEBPG_SECTION_HISTORY PURGE; Use of this script is at your risk :)
{ "pile_set_name": "StackExchange" }
Q: Assigning data frame column values probabilistically I am trying to create a data frame named "students" with four variables: Gender, Year (Freshman, Sophomore, Junior, Senior), Age, and GPA. The idea is to have a data frame that illustrates the four levels of measurement: nominal, ordinal, interval, and ratio. At this point it looks something like this: ID Gender Year Age GPA 1 Male Sophomore 0 3.9 2 Male Junior 0 3.3 3 Female Junior 0 3.6 4 Male Freshman 0 3.1 5 Female Senior 0 2.9 I'm having a problem with Age. I would like Age to be assigned based on a probability. For example, if a student is a Freshman, I'd like Age to be assigned along something like the following lines: Age Probability 14 .47 15 .48 16 .05 I have a function to do that set up like this: 1: Age <- function(df) { 2: for (i in 1:nrow(df) { 3: if (df[i, 2] == "Freshman") { 4: df[i, 3] = 15 5: } else if { 6: continue through the years 7: } 8: } 9: } My thinking is that I want to change the right side of the assignment in Line 4 to something that will assign the age probabilistically. That's what I cannot figure out how to do. On a related note, if there's a better way to do it than what I'm considering, I'd be appreciative of hearing that. And on a final note, I've Googled the web at large, queried the R forums on Reddit and Talk Stats, and searched the R tags on this site, all to no avail. I can't believe I'm the first person who's ever wanted to do something like this, so it occurs to me that maybe I'm phrasing the query wrong. If that's the case, any guidance there would also be appreciated. A: Use sample function like this: sample(14:16, size=1,prob=c(0.47, 0.48, 0.05)) ## [1] 14 sample(14:16, size=10,rep=TRUE,prob=c(0.47, 0.48, 0.05)) ## [1] 14 14 15 14 15 16 15 15 15 15
{ "pile_set_name": "StackExchange" }
Q: RSA decryption with large keys My problem: I already know the private and public key of an RSA system and I have an encrypted message but I can't decrypt it, because my private exponent is about 1024 bit. My data is following if it is needed for details but the question is how to decrypt a message with long keys on a simple home PC. N = 0xb197d3afe713816582ee988b276f635800f728f118f5125de1c7c1e57f2738351de8ac643c118a5480f867b6d8756021911818e470952bd0a5262ed86b4fc4c2b7962cd197a8bd8d8ae3f821ad712a42285db67c85983581c4c39f80dbb21bf700dbd2ae9709f7e307769b5c0e624b661441c1ddb62ef1fe7684bbe61d8a19e7 e = 65537 p = 0xc315d99cf91a018dafba850237935b2d981e82b02d994f94db0a1ae40d1fc7ab9799286ac68d620f1102ef515b348807060e6caec5320e3dceb25a0b98356399 q = 0xe90bbb3d4f51311f0b7669abd04e4cc48687ad0e168e7183a9de3ff9fd2d2a3a50303a5109457bd45f0abe1c5750edfaff1ad87c13eed45e1b4bd2366b49d97f d = 0x496747c7dceae300e22d5c3fa7fd1242bda36af8bc280f7f5e630271a92cbcbeb7ae04132a00d5fc379274cbce8c353faa891b40d087d7a4559e829e513c97467345adca3aa66550a68889cf930ecdfde706445b3f110c0cb4a81ca66f8630ed003feea59a51dc1d18a7f6301f2817cb53b1fb58b2a5ad163e9f1f9fe463b901 c = 0x58ae101736022f486216e290d39e839e7d02a124f725865ed1b5eea7144a4c40828bd4d14dcea967561477a516ce338f293ca86efc72a272c332c5468ef43ed5d8062152aae9484a50051d71943cf4c3249d8c4b2f6c39680cc75e58125359edd2544e89f54d2e5cbed06bb3ed61e5ca7643ebb7fa04638aa0a0f23955e5b5d9 where c is ciphertext, N is module, e and d are public and private exponents respectively and p and q are primes (I suppose so, but it is hard to check). I already tried to use online services like this and several others. Also on my PC I have used python rsa library but it fails with errors. I suppose the following formula is used everywhere (suppose m stands for plaintext): m = c**d % N or m = 1 for i in xrange(d): m = (m * c) % N So maybe there is a more clever way from a mathematical point of view to calculate this m faster, or an online service that can solve it, or a library. Or it is possible only for supercomputers to calculate 1024 bit exponent RSA decryption? Data is taken from CTF context picoctf. A: First of all, I really hope that (a) this isn't important information and (b) you're not going to ever use this key pair again, because I can now decrypt this ciphertext and any other encrypted message sent to you with it. We can decode the message in python (resulting in a hex-encoded string) as follows: m = hex(pow(c, d, N)).rstrip("L") Which gives 0x436f6e67726174756c6174696f6e73206f6e2064656372797074696e6720616e20525341206d6573736167652120596f757220666c6167206973206d6f64756c61725f61726974686d65746963735f6e6f745f736f5f6261645f61667465725f616c6c The builtin pow function uses exponentiation by squaring to efficently compute large powers modulo an integer. Without exponentiation by squaring and its variants, the use of any asymmetric key algorithm which relies on the Discrete Logarithm problem (which is most, but not all, of them) is infeasible. It's actually quite easy to implement, and I strongly recommend that you do so. Read the wikipedia article for more information.
{ "pile_set_name": "StackExchange" }
Q: Is Chrome's device toolbar bugged? I'm using Chromium Version 51.0.2704.63 (64-bit) <html> <head> <style> html, body { margin: 0; } div { background-color: black; height: 100px; width: 50vw; max-width: 100vw; min-width: 360px; } </style> <body> <div></div> </body> </html> Try pasting this markup into notepad, save as a .html file and run it. Go into Chrome's device toolbar and choose Lumia 950 2 things you'll notice: - In the developer tool's box model view, you'll see the dimensions are 490x100 - In the device toolbar, you'll see that the screen is 360x640 So what is going on here? So is 490 the new 180? A: You are missing <meta content="initial-scale=1.0, width=device-width" name="viewport"> In your <head>. Devtools is not broken, it's just simulating the the actual pixels you get on some of the mobile phones.
{ "pile_set_name": "StackExchange" }
Q: Using a normal JS librarary with Ionic2 + typescript I'm trying to use camanjs with my ionic2 + typescript project. I've also had a look at Ionic and Typings blog post by Mike, however it shows adding a library that is already in Typings Then I found this blog post from josh on adding goole maps that uses CDN method. By following both of them I've done following so far, added camanjs via CDN to the index.html file #index.html <script src="https://cdnjs.cloudflare.com/ajax/libs/camanjs/4.1.2/caman.full.js"></script> <script src="cordova.js"></script> ... Following is my ts file #home.ts import {Component} from '@angular/core'; import {NavController} from 'ionic-angular'; declare var Camanjs: any; @Component({ templateUrl: 'build/pages/home/home.html' }) export class HomePage { constructor(public navCtrl: NavController) { } addFilter(){ Camanjs("#image", function(){ this.sinCity(); this.render(); }) } } and my html file. (when the user click the button I want to apply the filter) #home.html <ion-header> <ion-navbar> <ion-title> Ionic Blank </ion-title> </ion-navbar> </ion-header> <ion-content padding> <button (click)="addFilter()">Filter</button> <img id='image' src="https://d339b5nop2tkmp.cloudfront.net/uploads/pet_photos/2016/7/13/469479_e76aa_340x340_af1c8.jpg"> </ion-content> but when I click addFilter() I'm getting the following error browser_adapter.js:84 ReferenceError: Camanjs is not defined at HomePage.addFilter (home.ts:14) at DebugAppView._View_HomePage0._handle_click_13_0 (HomePage.template.js:201) at view.js:375 at dom_renderer.js:254 at dom_events.js:27 at ZoneDelegate.invoke (zone.js:323) at Object.onInvoke (ng_zone_impl.js:53) at ZoneDelegate.invoke (zone.js:322) at Zone.runGuarded (zone.js:230) at NgZoneImpl.runInnerGuarded (ng_zone_impl.js:86) However I dont get any compiler errors via the IDE or in the compile time , any help would be much appreciated. Please note this the extended / more detailed version of my previous question A: Instead of using Camanjs... try with this: Caman('#my-image', function () { // ... }); So replacing Camanjs by just Caman should allow you to call the methods on that library.
{ "pile_set_name": "StackExchange" }
Q: How do the differences in the number of protons result in such great differences in elemental properties? I understand(I think) the mass and density aspect, i.e. the more protons you have, the more the element weighs, also the denser the atom is. What about everything else(color, for example)? Elements are not just masses and densities. A: Unfortunately, I have to disagree with trb456's answer. It is both the protons and the electrons that make up chemistry. (Neutrons are considered massive "spectators" though they are what keep protons (all + charged) together) Bonds are formed due to the attraction of electrons and protons. (cf. Slater, Bader, et al.) (The precise shape and nature of the electron density is additionally determined by constraints such as Pauli Exclusion and electron-electron repulsion.) So if you think about it, there is a very complex interplay upon mixing electrons up with protons. More positive charge in the nucleus tends to keep electrons drawn tight, but in some ways that is counter-balanced by electron-electron repulsion--and the fact that electrons are attacted to other nuclei as well. So although we ascribe color ("electronic transitions") and reactivity to electrons, this is only part of the story. The protons are also there, and they provide some governance (via Coulombic interaction) over what electrons are permitted to do.
{ "pile_set_name": "StackExchange" }
Q: How to prevent OSX popup for incoming connections for Python app? I am developing a simple python3 server app. I invoke it like this: python3 bbserver.py Each time after doing this I get the OSX popup: Do you want the application “Python.app” to accept incoming network connections? I've tried making an exception for python3 executable (there is no python3.app) in the firewall and have tried code signing with a codesign certificate thus: codesign -f -s mycodecert /Library/Frameworks/Python.framework/Versions/3.4/bin/python3 --deep No luck. A: If you are using a virtualenv or anything similar you could be signing the wrong version of python. sudo codesign --force --deep --sign - $(which python) To check the status of the certificate that was used to sign an app: codesign -dv /Library/Frameworks/Python.framework/Versions/3.4/bin/python3 codesign -dv $(which python) Example Unsigned: hostname ~ $ codesign -dv $(which python) /usr/local/bin/python: code object is not signed at all Example Signed: hostname ~ $ workon py27 (py27)hostname ~/py27 $ codesign -dv $(which python) Executable=/Users/me/.virtualenvs/py27/bin/python Identifier=python-555549446408a33553ca3f479122ce9278a9a269 Format=Mach-O universal (i386 x86_64) CodeDirectory v=20100 size=196 flags=0x2(adhoc) hashes=3+2 location=embedded Signature=adhoc Info.plist=not bound TeamIdentifier=not set Sealed Resources=none Internal requirements count=1 size=136
{ "pile_set_name": "StackExchange" }
Q: jquery - Undefined src when using attr() of image Just learning jQuery. What I want is to grab the src of the image and display it in a fixed division, kind of like a pop up, with the title of the image. But I'm stuck at getting the src of the image. When I tried using the .attr(), its giving me undefined. HTML: <div id="album"> <div class="pic"> </div> <div class="screen"> <h1 class="title">Photo 1</h1> <img src="images/1 png.png" class="image" /> <p class="description">This is a description</p> </div> <div class="screen"> <h1 class="title">Photo 1</h1> <img src="images/1 png.png" class="image" /> <p class="description">This is a description</p> </div> <span class="clear_left"></span> </div> css: .screen { border: 1px solid green; margin: 10px auto; float: left; cursor:pointer } .image { width: 300px; } .title { font-size: 30px; } .description { font-size: 25px; } .pic { width: 600px; position:fixed; } js: $(document).ready(function () { $(".pic").hide(); $(".screen").click(function () { display(); }); }); function display() { var source = $("img",this).attr("src"); alert("The souce of the image is " + source); } A: The problem is, the display() method does not have the context of the element being clicked. Hence it is showing undefined So, try this: $(document).ready(function () { $(".pic").hide(); $(".screen").click(function () { display($(this)); }); }); function display($this) { var source = $("img", $this).attr("src"); alert("The souce of the image is " + source); } Working demo
{ "pile_set_name": "StackExchange" }
Q: Is C4O5 possible? I have searched all over the internet and I have found no specific answer. I just want to know if C4O5 is possible and what would it be called. A: Tetracarbon pentoxide, $\ce{C4O5}$, does not appear to be known, but Wikipedia reports what has become a surprisingly large variety of oxocarbons. They include simple carbon monoxide and carbon dioxide, various extended linear structures, single and multiple rings, oligomers and polymers, even fullerene oxides. Some are surprisingly stable: mellitic anhydride, $\ce{C_{12}O9}$, can be melted at 161°C, and the powerful pi acceptor $\ce{C_{10}O8}$ is stable in dry air up to 140°C.
{ "pile_set_name": "StackExchange" }
Q: CakePHP pagination and the get parameters I have a problem with the pagination in my search page. When a user search something I have a url like domain.com/search/?s=keyword but paginator gives me links like domain.com/search/page:x, so in the next and prev and numbers page the get parameter is lost. I need to configure paginator to get links like domain.com/search/page:x/?s=keyword But I can't do this. I need to know how to configure $paginator->options(); $paginator->next(); $paginator->prev(); $paginator->numbers(); to get the needed efect. Thanx. A: create the options array $options = array( 'url'=> array( 'controller' => 'posts', 'action' => 'search', '?' => 'keyword='.$keyword ) ); set it to the helper $paginator->options($options) and then you can use the paginator helper while retaining the GET variables. hope that it helped :) to make it easier you can putl $paginator options in your view or .ctp file $this->Paginator->options['url']['?'] = $this->params['ur]; then put the value that you want :) A: To pass all URL arguments to paginator functions, add the following to your view: Plain Text View $paginator->options(array('url' => $this->passedArgs)); That's it. See http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html
{ "pile_set_name": "StackExchange" }
Q: Deleting account with all content Please delete my account including all posts (questions and answers) that I created. When I search for the instructions to delete it, it says: User deletion is irreversible! By sending this request, your votes will be revoked, and all of your content will be made anonymous. I don't want my content to be made anonymous. All posts should be deleted because they are my content. I'll have to talk to my lawyer if that is not possible. I tried to remove my posts but it doesn't allow me to do so. A: When you posted the content to SO you irrevocably licenced the content under the Creative Commons Wiki licence, giving everyone in the world the right to publish the content, or created derived works from it, so long as you are cited for it. The site may choose to delete your content if it feels that it's not valuable to us to host it, but you do not have the right to demand it be taken down. You only have the right to have your name no longer associated with that content.
{ "pile_set_name": "StackExchange" }
Q: JasperReport... What do you do First Compile or fill using parameters? I need to send parameters to my JasperReport. Do I compile it first using compileReport and then call the fillReport passing the parameters or do I need to do things in the opposite order? A: Compiling and filling report are two different things. About compiling Jasper reports is normally developed using IDE tools like iReport or JasperSoft Studio (you can also use a notepad), the report is saved in a file with the extension .jrxml, before running the .jrxml you need to compile it into a .jasper file (you can also compile on run time and only keep the JasperReport object) It can be compared with the .java file that need's to be compiled into .class files before you can run the program. For more information see: How do I compile jrxml to get jasper? About filling Filling is when you like to fill your report design with data, the data can come from a JRDatasource or a database Connection (query in report) and a Map<String,Object> parameter map. When report is filled you get a JasperPrint object (even this can be saved to file, to avoid filling same report multiple times) About export The final process in report generation is the export process, where you export the JasperPrint to your desired format pdf, excel, html etc. So lets get back to your original question. Do I compile it first using compileReport? You can if you like to but you do not need to if you have already compiled your report, in this case just load the compiled report which is faster. JasperReport jasperReport = (JasperReport) JRLoader.loadObject(inputStream);
{ "pile_set_name": "StackExchange" }
Q: Do the limits of a Force.com license extend with purchase of additional licenses? (see description) An example better explains my question. Force.com licenses have a Per User Limit of 10 custom objects. If there are two Force.com licenses, and you made two profiles, each with this license, would it be 10 custom objects across the whole org, or could one profile have 10 custom objects and primarily have access to those, and then the other have an additional 10 with exclusive access to those objects? Or would it be 10 total? My assumption is that if there are 2 licenses, you get 20 custom objects, but I want to be sure. A: From the documentation it would seem that it would be possible to have 1 profile having access to 10 custom objects and another profile with access to a different 10 custom objects, but this would not grant access to all 20 custom objects to users on both profiles. A Force.com Light App has up to 10 custom objects and 10 custom tabs, has read-only access to accounts and contacts, and supports object-level and field-level security. A Force.com Light App can’t use the Bulk API or Streaming API. A Force.com Enterprise App has up to 10 custom objects and 10 custom tabs. In addition to the permissions of a Force.com Light App, a Force.com Enterprise App supports record-level sharing, can use the Bulk API and Streaming API, and has read/write access to accounts and contacts. The platform licence seems to be able to access a great deal more of Salesforce and does not have an explicit limit on the number of custom objects that can be accessed specified on the documentation. With Community licences it is possible to grant access to more custom objects than the basic 10, this is a chargeable option where access to additional custom objects can be bought in batches of 10. This may also be possible with Force.com licences but you would need to talk to your Account Executive.
{ "pile_set_name": "StackExchange" }
Q: wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object If I have a notebook with three spreadsheet widgets, what is the best way to have changes to the spreadsheet update a dictionary (or maybe an sqlite file?). Do all wx grid objects come with a built in dictionary related to the SetNumberRows and SetNumberCols? Basically I am looking for guidance on how to work with the user-input data from a spreadsheet widget, as in this example adapted from the tutorial on python.org: class ExSheet(wx.lib.sheet.CSheet): def __init__(self, parent): sheet.CSheet.__init__(self, parent) self.SetLabelBackgroundColour('#CCFF66') self.SetNumberRows(50) self.SetNumberCols(50) class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title) nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM) self.sheet1 = ExSheet(nb) self.sheet2 = ExSheet(nb) self.sheet3 = ExSheet(nb) nb.AddPage(self.sheet1, "Sheet1") nb.AddPage(self.sheet2, "Sheet2") nb.AddPage(self.sheet3, "Sheet3") self.sheet1.SetFocus() self.StatusBar() A: Use a wxGrid with a wxGridTableBase instead Here is a simple example: import wx, wx.grid class GridData(wx.grid.PyGridTableBase): _cols = "a b c".split() _data = [ "1 2 3".split(), "4 5 6".split(), "7 8 9".split() ] def GetColLabelValue(self, col): return self._cols[col] def GetNumberRows(self): return len(self._data) def GetNumberCols(self): return len(self._cols) def GetValue(self, row, col): return self._data[row][col] def SetValue(self, row, col, val): self._data[row][col] = val class Test(wx.Frame): def __init__(self): wx.Frame.__init__(self, None) self.data = GridData() grid = wx.grid.Grid(self) grid.SetTable(self.data) self.Bind(wx.EVT_CLOSE, self.OnClose) self.Show() def OnClose(self, event): print self.data._data event.Skip() app = wx.PySimpleApp() app.TopWindow = Test() app.MainLoop()
{ "pile_set_name": "StackExchange" }
Q: How to declare a Font variable properly? I would have a quick question : Could anyone tell me what is wrong with this line : Font ^printFont = gcnew System::Drawing::Font("Arial", 10); My compiler says "Identifier 'printFont' is unidentified". I also have the namespaces and the dll file included : #using <System.Drawing.dll> using namespace System; using namespace System::Drawing; using namespace System::Drawing::Text; using namespace System::Drawing::Printing; PS. Sorry for not pro coding, but I did not take any University level programming in C++/CLR. Edited : private: System::Void testCorrection_PrintPage_1(System::Object^ sender, System::Drawing::Printing::PrintPageEventArgs^ e) { float linesPerPage = 0; float yPos = 0; int count = 0; float leftMargin = (float)e->MarginBounds.Left; float topMargin = (float)e->MarginBounds.Top; String^ line = nullptr; Font ^printFont = gcnew System::Drawing::Font("Arial", 10); // error is :" IntelliSense:identifier 'PrintFont' is undefined " SolidBrush ^myBrush = gcnew SolidBrush(Color::Black); StreamReader^ streamToPrint; // Calculate the number of lines per page. linesPerPage = e->MarginBounds.Height / printFont->GetHeight(e->Graphics); line = streamToPrint->ReadLine(); // Iterate over the file, printing each line. while (count < linesPerPage && ((line = streamToPrint->ReadLine()) != nullptr)) { yPos = topMargin + (count * printFont->GetHeight(e->Graphics)); e->Graphics->DrawString(line, printFont, myBrush, leftMargin, yPos, gcnew StringFormat); count++; line = streamToPrint->ReadLine(); } } A: As you have directive using namespace System::Drawing; then you can write simply Font ^printFont = gcnew Font("Arial", 10); I think the problem is that you did not add reference to System.Drawing to the project
{ "pile_set_name": "StackExchange" }
Q: How do I get a list of TFS Collections over REST? I'm working with the REST API for Team Foundation Server and Visual Studio Online. I am looking for a rest call which will tell me what collections the user has access to. I cannot find a REST call which will allow me to view this information. Is there a REST call that will let me view this information for an authenticated user? A: Try this: [tfs url]/_api/_common/GetJumpList?showTeamsOnly=false&__v=5&navigationContextPackage={}&showStoppedCollections=false You can capture the request by using developer tool: Using Windows Internet Explorer Developer Tools Network Capture
{ "pile_set_name": "StackExchange" }
Q: Spring jpa, how to generate event on insert? I have an application and it is deployed on four different container (jboss eap 6.2). I want that: when an instance of this application do an insert on a specific table all other applications should notify this insert to all connected user. I prefer to avoid direct connection from instance (ejb for example). It's possible using Spring data to osservare a table and to generate an event when someone do a insert? I need something like trigger? Can I have a equivalent full write java?. (DBMS: Oracle 12c) A: Spring data itself does not have a mechanism to be notified of inserts made by another process to a database. You need either a trigger on the database as you suggest, or a distributed event / caching framework, e.g. ehcache, whereby the container doing the insert would notify all the other containers of the insert.
{ "pile_set_name": "StackExchange" }
Q: Strange pjax behavior: GET request initiates after a pjax request The problem is, as soon as pjaxed request finishes, pjax also initiates a normal GET request. My codes are like this: $(document).on('pjax:end', function(event){ alert("end"); inpjax = false; }); $(document).on('pjax:timeout', function(event) { alert("timeout") event.preventDefault(); }); $(document).on('pjax:error', function() { alert("error"); }); $(document).on('pjax:success', function() { alert("success"); }); $(document).ready(function(e) { inpjax = false; $('.pj').click( function(e) { e.preventDefault(); if(!inpjax) { inpjax = true; $.pjax({ timeout: 5000, url: $(this).attr('href'), container: '#codeport' }); } }); }); As you can see, it should give me an alert on different stiuations, but I only get alert on pjax:end event, and after that alert, pjax initiates normal GET request, timing is like this: [17:36:02.002] GET http://localhost/abstract?_pjax=%23codeport [HTTP/1.1 200 OK 86 ms] [17:36:02.170] GET http://localhost/abstract [HTTP/1.1 200 OK 73 ms] I don't get timeout, error or success alert. What could be causing this? Please help... SOLUTION: The problem turned out to be that my serverside code was responding with a full page, and that was causing a second GET request. So if this problem happens to you too, make sure that your server side code responds correctly to PJAX requests. A: example: <!DOCTYPE html> <html> <head> <!-- styles, scripts, etc --> </head> <body> <h1>My Site</h1> <div class="container" id="pjax-container"> Download content from <a href="/page/2"> the other site </a>?. </div> </body> </html> Try to add pjax to an element which you want to get event messages from like $(document).pjax('a', '#pjax-container')
{ "pile_set_name": "StackExchange" }
Q: Proof of a Theorem in Gao's 'Invariant Descriptive Set Theory' Theorem 1.7.5 on p.35 of Gao's Invariant Descriptive Set Theory reads Theorem 1.7.5 (Kleene) If $A\subseteq X \times \omega^{\omega}$ is $\Pi^{1}_{1}$ and $$x \in B \Longleftrightarrow \exists y \in \Delta^{1}_{1}(x)\; (x,y) \in A,$$ then $B$ is also $\Pi^{1}_{1}$. Here $X = \omega^{m} \times (\omega^\omega)^n$ for some $m$ and $n$ (or equivalently, $X=\omega^\omega$, I suppose). Where can I find a proof of this result? Feel free to just prove it here. I checked the bibliography, and, though it seems impossible, there are no references to Kleene; it goes straight from "Kelly" to "Louveau". A: This is the Socalled Spector-Gandy's theorem. A proof can be found in higher recursion theory by Sacks or descriptive set theory by Moschovakis.
{ "pile_set_name": "StackExchange" }
Q: Getting the parent delimiters via RegEx I'm trying to get the parent delimiters in a string below using RegEx match colletion.; string value = "{line 1 {subline}$}{line 2}{line 3}"; So far here is my code; string value = "{line 1 {subline}$}{line 2}{line 3}"; var reg = new Regex(@"\{(.+?)\}"); MatchCollection properties = reg.Matches(value); and I am getting this; {{line 1 {subline}} {{line 2}} {{line 3}} But my expected result must be; {{line 1 {subline}$}} {{line 2}} {{line 3}} Anyone know how to ignore the child field from the string? Thank you! A: You could do this O(n) without regex. Given public static IEnumerable<string> GetTokens(string input) { var count = 0; var pos = -1; for (var i = 0; i < input.Length; i++) { if (input[i] == '{') count++; if (input[i] == '}') count--; if (count == 1 && pos == -1) pos = i; if (count != 0 || pos == -1) continue; yield return '{' + input[pos..(i + 1)] + '}'; // this would allocate less without the brackets pos = -1; } } Usage string value = "{line 1 {subline}$}{line 2}{line 3}"; foreach (var token in GetTokens(value)) Console.WriteLine(token); Output {{line 1 {subline}$}} {{line 2}} {{line 3}} Demo here Note : The only reason for this answer is because I wanted to use a range (don't judge me)
{ "pile_set_name": "StackExchange" }
Q: Detect System Shutdown with Powershell Hi i have a monitoring script (with a winforms gui) that is always running in the back. Unfortunately this annoys users when they try to manually shutdown the computer, cause it provokes the "this app is preventing windows shutdown"-screen. So i need a a reliable way to automatically close the script when a shutdown was initiated. I tried subscribing to the SessionEnding- and SessionEnded-event, but it did not work: $sysevent = [microsoft.win32.systemevents] Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnding" -Action { Exitfunction } UPDATE: Its like this at the moment: $sysevent = [microsoft.win32.systemevents] Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnding" -Action { [Windows.Forms.MessageBox]::Show("Shutdown!", "", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Warning)} Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnded" -Action { [Windows.Forms.MessageBox]::Show("Shutdown!", "", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Warning)} Register-WmiEvent -Class win32_computerShutdownEvent -Action { [Windows.Forms.MessageBox]::Show("Shutdown!", "", [Windows.Forms.MessageBoxButtons]::OK, [Windows.Forms.MessageBoxIcon]::Warning)} I added a messagebox to see if one of these events would in fact fire, but maybe the code executed by the action scriptblock was faulty. No luck. None of these events kick in when i try to shutdown a windows 8.1 system. There are no errors inside the events when i read them with get-job. The state is in all of them "not started". Any ideas why? A: OK the solution is: If a shutdown is initiated, Windows send a WM_QUIT-Message to all applications. If you subscribe to the onClosing-event, you can query the $eventargs if that event has been fired. It contains a CloseReason-property, which if it is WindowsShutdown can be used to initiate a proper cleanup and close down of the app. See the answer to this post for more info on how to do that.
{ "pile_set_name": "StackExchange" }
Q: Filter on Accounts that currently have one product but not another I need a report that will list out all of our Accounts currently under contract and use one product, but do not have another. I feel like there might be an easy way to do this and that I am possibly over thinking it. Let me explain in more detail... I need to show all Accounts that have a value of "Product Group A" for the Product Family field on the Asset Level, but do not have a value of "Product Group B" for Product Family with any other associated Assets. So to get more detailed... Company A has: Contract 1234 with Asset 1 - Product Family: Product Group A Asset 2 - Product Family: Product Group A etc Contract 2345 with Asset 3 - Product Family: Product Group B Asset 4 - Product Family: Product Group B etc Company B has: Contract 7654 with Asset 5 - Product Family: Product Group A Asset 6 - Product Family: Product Group A etc Contract 3456 with Asset 7 - Product Family: Product Group C Asset 8 - Product Family: Product Group C etc Company C Contract 9876 with Asset 11 - Product Family: Product Group D Asset 12 - Product Family: Product Group D etc Contract 2134 with Asset 13 - Product Family: Product Group C Asset 14 - Product Family: Product Group C etc The report would list Company B and not Company A and C Thanks A: If I understand the structure correctly, you should be able to do this using cross filters and a formula field on the Asset to get the Product Family. Create a report on Accounts and add two cross filters. 1. Accounts with Contracts where Assets Product Family = "Product Group A" 2. Accounts without Contracts where Assets Product Family = "Product Group B"
{ "pile_set_name": "StackExchange" }
Q: Powershell getting rid of newlines in function I'm trying to run a function that parses a large string that contains newlines, however whenever I pass this string into a function it gets rid of the new lines and makes it impossible to parse. Am I doing something wrong here? function parseString([string] $s) { $result = $s | Select-String -pattern "foo" return $result } If I type: $s | Select-String -pattern "foo" I get the correct result but using parseString $s returns the whole string with no newlines. Any suggestions? EDIT: Hmm after messing around a bit I got rid of the [string] so it's function parseString($s) This seems to work, but why? A: What is $s? If it is an array of string, then since you are saying that parseString takes in a string, the array of string is converted into a string. If on the other hand $s were a single string, it will work ( as shown below): function parseString([string] $s) { $result = $s | Select-String -pattern "foo" return $result } $s =@' first line second line with foo third line '@ parseString $s But if $s=@("first line","secondline with foo","third line"), the array of strings is first converted to a string ( by simply joining each string ) and hence you will lose the newline. If you have got $s, from Get-Content etc. this will be the case. Note that, most of the times, you won't need to specify the types in Powershell. Be it while assigning variables or in function paramaters. PS: If you did $ofs = "`n" parseString $s you will get the expected result in the function with [string].
{ "pile_set_name": "StackExchange" }
Q: How pause the thread while external function return value? (C#) There is an external library which has a function that returns a value with a certain delay (sleep for 200-1000ms), C++ code: __declspec( dllexport ) char ReadNextChar() { char OneChar[2]; while (Receive((char*)&OneChar)==-1) {Sleep(200);} return OneChar[0]; } In the main program running thread, C# code: public void Start() { thread = new Thread(ReadChar); thread.IsBackground = true; thread.Priority = ThreadPriority.BelowNormal; thread.Start() } char currentChar; [DllImport("reader.dll")] public extern char ReadNextChar(); private void ReadChar() { while(true) { currentChar=ReadNextChar(); } } It seems to me that this can be seriously optimised. What is the best way to do this task? (how does it really work while external function sleep?). Thanks. A: The typical way to do this on win32 would be to use an event and signal this event from the ReadNextChar function. This is how the Win32 ReadFile function works when using overlapped mode (http://msdn.microsoft.com/en-us/library/aa365467(v=vs.85).aspx) You can then use WaitForSingleObject to put the thread to sleep. It will become runnable again when the event is signalled. This would make your implementation more complicated and would additionally require modifications to the dll. Now, it is only really worth doing this if the read you are doing can actually be waited on - otherwise you will end up having to add another thread in your dll that polls and sets the event (not much point in doing this if you are doing this for optimization purposes as it will be a pessimistic optimization, to say the least). To be honest, since you are likely to be sleeping for at least 200ms, polling your read function is unlikely to cause any significant performance issues - don't optimize it for the sake of it. Clearly something that your code does not do is to make the thread exit-able without terminate()ing it. I would personally put the sleep in the c# code and return a read success code from the ReadNextChar function without spinning in a loop or having any sleeps in there. I expect your code is just an example though..
{ "pile_set_name": "StackExchange" }
Q: Application.StartupPath called in a DLL in GAC, where it will resolved to? I create an EXE ( let's call it a.exe), that calls a DLL (let's call it b.dll). Inside the b.dll there is this method public string GetStartupPath() { return Application.StartupPath; } I put the a.exe in C:\Program Files\My Company\My App folder. I install the b.dll in the GAC. Now my question is, if I launch C:\Program Files\My Company\My App\a.exe, what will the method GetStartupPath() in b.dll returns? I can do a simple sample to test, but I still decide to post this question here. Two reasons: I suspect that on different machines, different answer will return. For the benefit of other developers, canonical response based on the official documentation available on StackOverflow is very useful. A: From the official docs: Gets the path for the executable file that started the application, not including the executable name. https://msdn.microsoft.com/en-us/library/system.windows.forms.application.startuppath(v=vs.110).aspx So this means to me that it will give you the path where the exe lives.
{ "pile_set_name": "StackExchange" }
Q: Suppose $A$ is an $n \times n$ idempotent matrix and let $I$ be an $n \times n$ identity matrix. Prove that the matrix $I −A$ is an idempotent matrix A square matrix $A$ is called idempotent if $A^2 = A$. (a) Suppose $A$ is an $n × n$ idempotent matrix and let $I$ be the $n × n$ identity matrix. Prove that the matrix $I −A$ is an idempotent matrix. (b) Assume that $A$ is an $n×n$ non zero idempotent matrix. Then determine all integers $k$ such that the matrix $I − kA$ is idempotent. I need help. I didn't know what to do... All I know is that I need to show that $(I−A)^2=(I−A)$. I don't have any clue on how I should proceed. Thanks in advance A: An idempotent matrix $A$ by definition satisfies $A^2 = A; \tag 1$ from this we immediately have $(I - A)^2 = I^2 - 2A + A^2 = I - 2A + A = I - A, \tag 2$ that is, $I - A$ is also idempotent. Now if $I - kA$ is idempotent, then via (1) we find $I - kA = (I - kA)^2 = I - 2kA + k^2A^2 = I - 2kA + k^2A, \tag 3$ whence $(k^2 - k)A = 0; \tag 4$ since $A \ne 0$ this forces $k^2 - k = 0 \Longrightarrow k = 0, 1; \tag 5$ thus the only candidates for $I - kA$ are $I - kA = I, I - A. \tag 6$ .
{ "pile_set_name": "StackExchange" }
Q: Why I'm getting more than one on click event fire inside bootstrap modal I'm getting some problem here and need some help. I think this is easy but I just can't figure it out myself what's happening. Please see fiddle below: Fiddle When I only open the modal and clicks it for the first time. It works normally, but when I reopened it, there goes the problem. It fires the on click event more than once. HTML <button data-target="#mergeFieldsModal" data-toggle="modal" data-message-id="#message" class="btn btn-info">Open Modal</button> <div id="result"></div> <div id="mergeFieldsModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h3 class="modal-title"><span class="ss-shuffle ss-icon"></span> Merge Fields</h3> </div> <div class="modal-body"> <p>Click Add. After clicking add, open the modal again then click add again to see the problem.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button type="button" id="btnMergeField" class="btn btn-primary">Add</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> JS // Append merge field to message textarea $('#mergeFieldsModal').on('show.bs.modal', function(event) { var button = $(event.relatedTarget); var messageId = button.data('message-id'); var btnMergeField = $(this).find('#btnMergeField'); btnMergeField.on('click', function() { $('#result').append('<p>Fired!' + '</p>'); // Add to DOM $('#mergeFieldsModal').modal('hide'); // Hide Modal }); }); A: Since you are attaching new event every time modal dialog box is opening. You need to remove it before adding new. btnMergeField.off('click').on('click', function(){ Make the above change and it will work A: It is because your code defines click event each time user opens modal. You need to define click event outside of 'show.bs.modal'. Another approach, which you need to use only if you cannot use the first one, is to off() click event, when user closes modal. $('#mergeFieldsModal').on('show.bs.modal', function(event){ var button = $(event.relatedTarget); var messageId = button.data('message-id'); var btnMergeField = $(this).find('#btnMergeField'); btnMergeField.on('click', function(){ $('#result').append('<p>Fired!' + '</p>'); // Add to DOM $('#mergeFieldsModal').modal('hide'); // Hide Modal }); $(this).on('hide.bs.modal', function() { btnMergeField.off('click'); }); });
{ "pile_set_name": "StackExchange" }
Q: Complex Types support in Azure Search .Net SDK I want to know whether complex types are supported in the azure search sdk for .net? I already know that the azure team is providing a private preview of this feature. But the last information I have is that it can be accessed only directly via REST Api. Is there a .net sdk support for the same? A: Complex Types is now generally available and is supported in version 9 of the Azure Search .NET SDK
{ "pile_set_name": "StackExchange" }
Q: Limited splits without losing the rest of the string? Say I have: var str = "this is a string separated by spaces"; and I did: alert(str.split(" " , 1)); the outcome would be "this" Whereas I want the outcome to be "this,is a string separated by spaces" maybe split isn't the right method? What I'm trying to do is separate a string into parts based on semicolons, unless those semicolons are in quotes. For example, I would want randomnessstuff;morestuff;some more stuff to be in three parts, so I've been doing: var str = "randomnessstuff;morestuff;some more stuff"; var parts = str.split(";"); Which has been working fine, but if the semicolon is in quotes, I want it to NOT be separated into another part. for example, with: var str = "randomnessstuff;morestuff and a semicolon in quotes : ";";some more stuff"; I would want part 1 to be randomnessstuff , part 2 to be morestuff and a semicolon in quotes : ";" , and part 3 to be some more stuff of course, if I just did split with the semicolon again, it would make part 3 the quote. What I'm hoping to do is have a loop that checks the semicolons one by one to see if they're in quotes, and if not, to split with them. If this last bit didn't make any sense, then please just answer the first question, about using split without losing the rest of the string. A: The easy way to do this one is unfortunately manual. var r = "randomnessstuff;morestuff and a semicolon in quotes : \";\";some more stuff" var l = r.length var out = [] var inQuotes = false; function toggleQuotes(){ inQuotes = !inQuotes } var tmp = "" for(var i = 0; i < l; i++ ) { // examine character by character. var chr = r.charAt(i); // only handles one type of quote and no escapes currently if( chr == '"' ) toggleQuotes(); /* escape might look like this: if( chr == '"' && r.charAt(i-1) != '\' ) support for both types of quotes might be: if( chr == '"' || chr == "'" && r.charAt(i-1) != '\' ) toggleQuotes(chr); then toggleQuotes would be: function toggleQuotes(chr){ if(inQuotes == chr) inQuotes = false; else inQuotes = chr } */ if( !inQuotes && chr == ";" ) { out.push(tmp); // store temp string tmp = "" // reset strubg } else tmp += chr // append the temporary string } out.push(tmp) // the remainder needs to be added still. console.log(out) //["randomnessstuff", // "morestuff and a semicolon in quotes : ";"", // "some more stuff"]
{ "pile_set_name": "StackExchange" }
Q: DataGridTemplateColumn Sorting capabilities Telerik RadDataGrid Windows 8 Normally the Sorting capabilty ( little triangle in the column header + functionality on header click ) comes out of the box if you are using some "typed" column, just by setting the PropertyName to the property from your model. For example it does work for DataGridTextBoxColumn. But, if you have to use some custom columns enter DataGridTemplateColumn which does not have this PropertyName property. Question: how can you achieve "easy" sorting on such a column. It should be as easy as setting something like "SortingMemberPath" and that's it. Do I need to subclass a "typed" column and create my own DataGridCombBoxColumn, for example ? A: You can achieve the desired functionality by implementing the ColumnHeaderTapCommand and then adding / removing the necessary SortDescriptors manually. More information about DataGrid commands can be found here. The glyph in the column header can be shown through the Column.SortDirection property. Also, the suggested approach is very suitable and in the future we intend to extend the current logic to allow the SortDescriptors to use this mapping in the templated columns. Best regards, Ivaylo
{ "pile_set_name": "StackExchange" }
Q: How to tell what "features" are available per crate? Is there a standard way to determine what features are available for a given crate? I'm trying to read Postgres timezones, and this says to use the crate postgres = "0.17.0-alpha.1" crate's with-time or with-chrono features. When I try this in my Cargo.toml: [dependencies] postgres = { version = "0.17.0-alpha.1", features = ["with-time"] } I get this error: error: failed to select a version for `postgres`. ... required by package `mypackage v0.1.0 (/Users/me/repos/mypackage)` versions that meet the requirements `^0.17.0-alpha.1` are: 0.17.0, 0.17.0-alpha.2, 0.17.0-alpha.1 the package `mypackage` depends on `postgres`, with features: `with-time` but `postgres` does not have these features. Furthermore, the crate page for postgres 0.17.0 says nothing about these features, so I don't even know if they're supposed to be supported or not. It seems like there would be something on docs.rs about it? A: The only standard way to see what features are available is to look at the Cargo.toml for the crate. This generally means that you need to navigate to the project's repository, find the correct file for the version you are interested in, and read it. You are primarily looking for the [features] section, but also for any dependencies that are marked as optional = true, as optional dependencies count as an implicit feature flag. Good crates also document their feature flags either in the README or in their documentation. You may be interested in crates.io issue #465, which suggests placing the feature list on the page. See also: How do you enable a Rust "crate feature"? For the postgres crate, we can start at crates.io, then click "repository" to go to the repository. We then find the right tag (postgres-v0.17.0), then read the Cargo.toml: [features] with-bit-vec-0_6 = ["tokio-postgres/with-bit-vec-0_6"] with-chrono-0_4 = ["tokio-postgres/with-chrono-0_4"] with-eui48-0_4 = ["tokio-postgres/with-eui48-0_4"] with-geo-types-0_4 = ["tokio-postgres/with-geo-types-0_4"] with-serde_json-1 = ["tokio-postgres/with-serde_json-1"] with-uuid-0_8 = ["tokio-postgres/with-uuid-0_8"]
{ "pile_set_name": "StackExchange" }
Q: Set environment variable not working on Windows 8 I used this command to set environment variable but I don't know why it is not working D:\Developing tools\apache-tomcat-platform\bin>setx JAVA_HOME "C:\Program Files\ Java\jdk1.7.0_51" SUCCESS: Specified value was saved. D:\Developing tools\apache-tomcat-platform\bin>startup.bat Neither the JAVA_HOME nor the JRE_HOME environment variable is defined At least one of these environment variable is needed to run this program A: Just restarting the pc solve the problem :)
{ "pile_set_name": "StackExchange" }
Q: Weekly once scheduler job in c# I am new to C#. As to my present task. I suppose to execute a set logic once a week (i.e Every Sunday). How to do this C# . i known this can be done in php by "Cron job". A: You have the following options You create a windows service that takes an input from string . then parse the string and do the task using a timer. Use the quart.net service and proceed. Make use of windows task scheduler services. For Quartz.Net, you can refer to the cron trigger http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger
{ "pile_set_name": "StackExchange" }
Q: Using replace string in ASP I have a working function in JS function countWords(s){ s = s.replace(/(^\s*)|(\s*$)/gi,""); //modified trim function s = s.replace(/[ ]{2,}/gi," "); s = s.replace(/\n /,"\n"); return s.split(' ').length; } The problem is when i change to ASP, it seems not working: Sub formatText(a) a = Replace("/(^\s*)|(\s*$)/gi",a,"") a = Replace("/[ ]{2,}/gi",a,"") a = Replace("/\n /",a,"\n") return a End Sub It return nothing from the function, how to fix the problem? thanks Changed to 'regEx initialization Dim regEx set regEx = New RegExp 'Creates a regexp object regEx.IgnoreCase = True 'Set case sensitivity regEx.Global = True 'Global applicability 'trim input text Sub formatText(a) a = Replace("(^\s*)|(\s*$)",a,"") a = Replace("[ ]{2,}",a,"") regEx.IgnoreCase = False 'Set case sensitivity regEx.Global = False 'Global applicability a = Replace("\n ",a,"\n") return a End Sub still no luck please help.. A: You'll need to use a regex object, like so: 'regEx initialization Dim regEx set regEx = New RegExp 'Creates a regexp object regEx.IgnoreCase = True 'Set case sensitivity regEx.Global = True 'Global applicability regEx.Pattern = "<[^>]*>" 'Remove all HTML strTextToStrip = regEx.Replace(strTextToStrip, " ") Also remove the / from around the pattern. UPDATED 'trim input text Function formatText(a) Dim regEx set regEx = New RegExp 'Creates a regexp object regEx.IgnoreCase = True 'Set case sensitivity regEx.Global = True 'Global applicability regEx.Pattern = "(^\s*)|(\s*$)" a = regEx.Replace(a, "") regEx.Pattern = "[ ]{2,}" a = regEx.Replace(a, "") formatText = a End Function
{ "pile_set_name": "StackExchange" }
Q: jQuery hide or remove element based on attribute change I am working with my website and I am looking for some way in which I can use jQuery to show or add my element div#content1 when my #nav-home-tab is aria-selected=true and hide or remove the element if aria-selected=false This is my current attempt: /* This code below is Bootstrap Nav tabs that will show div#content1/2 if clicked(aria-selected=true) */ <nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Home</a> <a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false">Profile</a> <a class="nav-item nav-link" id="nav-contact-tab" data-toggle="tab" href="#nav-contact" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</a> </div> </nav> <div class="tab-content" id="nav-tabContent"> <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab"> <div id="content1"> //some content </div> </div> <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab"> <div id="content2"> //some content </div> </div> <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">...</div> </div> A: You can try a simple check on Jquery Ready function, $(document).ready(function(){ if($('a#nav-home-tab').attr('aria-selected') == "true") { $('div#content1').show(); } else { $('div#content1').hide(); } }); You can also see the JSFIDDLE here
{ "pile_set_name": "StackExchange" }
Q: Simple Find and Replace Script PHP/MySQL I've been plugging away at this simple script and think it's time I try and get some help. I am trying to make a PHP script to communicate with my database. I want to be able to write an array with all the words to find and all the words to replace them with. Example: array (find_word1,replace_word1,find_word2,replace_word2....etc) I also want to be able to specify the table to look in, I will change this manually as well. I will manually fill out all the words but I want to make it dynamic so it doesn't break if my array length changes. I have tried many things and here is what I have so far: <?php //set up variables and enter your credentials here $dbname = "name"; $dbhost = "localhost"; $dbpass = "password"; $dbuser = "user"; $tbl_name = "Chairs"; //set up your master array! Array goes in this or $mstr_array = array( "find1", "replace1", "find2", "replace2"); //connect to database $con = mysql_connect($dbhost, $dbuser, $dbpass) or die('no connection:' . mysql_error()); $db = mysql_select_db($dbname) or die ('cant select db: ' . mysql_error()); // reteive each column $sql = "SHOW COLUMNS FROM `{$tbl_name}`"; $res = mysql_query($sql) or die ('could not get columns: ' . mysql_error()); $find = 0; $replace = 1; while ($col = mysql_fetch_array($res)) { $sql = "UPDATE `{$tbl_name}` SET `{$col[0]}` = REPLACE(`{$col[0]}`, '{$mstr_array[$find]}' , '{$mstr_array[$replace]}')"; $find = $find + 2; $replace = $replace + 2; } ?> Any help would be greatly appreciated! Thanks A: The first thing that ups to my mind is that instead of using: $mstr_array = array( "find1", "replace1", "find2", "replace2"); use: $mstr_keys = array('find1', 'find2', ....); $mstr_values = array('replace1', 'replace2', ....); and then on the query you can simply use: $count = 0; $sql = "UPDATE `{$tbl_name}` SET `{$col[0]}` = REPLACE(`{$col[0]}`, '{$mstr_keys[$count]}' , '{$mstr_values[$count]}')"; $count++; I hope it's what you were looking for...
{ "pile_set_name": "StackExchange" }
Q: regex_match in CodeIgniter form_validation generates: Message: preg_match(): No ending delimiter '/' found I've been looking in other similar posts and the problem seemed to be an unescaped slash. However I'm escaping them. This is how the string should look: 23/12/2012 and this is how I'm declaring the validation rule: regex_match[/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)[0-9]{2}$/] The ending delimiter is there, and the two inbetween slashes for the date are being escaped with a backslash. I've also tried this which is slightly different, but I get the same error: regex_match[/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)\d\d$/] Where's the error? EDIT: Following your advice, I've tried using a callback function. This is the declaration, which is located within the controller class in which the form validation is being executed: function mach_date($date) { /* DEBUG */ echo 'Here I am!'; exit; // execution should stop here displaying the echo return (bool)preg_match('/^(0[1-9]|[12][0-9]|3[01])\/(0[1-9]|1[012])\/(19|20)\d\d$/', $date); } Validation rules in application/config/form_validation.php: $config = array( // other validation groups....., 'articles' => array( // other validated fields....., array( 'field' => 'date_p', 'label' => 'Publishing date', 'rules' => 'callback_match_date' ) ) ); A: When you set the validation rules you separate them with a | so the |'s in your regex is causing the validation rule to split at those and that is causing the error. Discussion here on the issue. It seems it's a limitation or bug in codeigniter. You can test it out by running a regex with and without |'s and see if the usage of pipes will cause an error. If that is the case then you may have to validate by regex by other means, maybe use a callback function as detailed on this page where your function will do a preg_match using the regex which needs to be inside the function of course and then return true/false.
{ "pile_set_name": "StackExchange" }
Q: ImageMagick command line character limit I'm using command line definitions for ImageMagick on Windows to add several hundred coloured rectangles to a blank image (histogram). The length of the commands exceeds the 8192 character limit. I have hundreds of these commands: -fill rgb(188,161,161) -draw "rectangle 1,106 4,19" The ImageMagick documentation says that several commands can be placed in a file, which is then read. When testing, these have to be the same command type, i.e. I'd ahve to create a file for the draw commands and one for the fill commands. However, the colouring won't work then, as the correct fill command isn't linked to the relevant draw command. magick -size 1920x108 xc:white -fill @fill.txt -draw @draw.txt hist.png Is anybody aware of a workaround or any other options? I thought having the commands in a windows batch file might work, but this also seems to be limited by the 8192 characters. A: Here is an excerpt from MS link: On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters. On computers running Microsoft Windows 2000 or Windows NT 4.0, the maximum length of the string that you can use at the command prompt is 2047 characters. So basically, it is a limitation of command line, not imagemagick. Is it possible that you split your task into two and then combine two images that was produced by these two steps onto one resulting image ?
{ "pile_set_name": "StackExchange" }
Q: Crawling sitemap.xml via python I am crawling a sitemap.xml and my objective is to find all the url's and the incremental count of them. Below is the structure of the xml <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>http://www.htcysnc.com/m/designer-sarees</loc> <lastmod>2014-09-01</lastmod> <changefreq>hourly</changefreq> <priority>0.9</priority> </url> <url> <loc>http://www.htcysnc.com/m/anarkali-suits</loc> <lastmod>2014-09-01</lastmod> <changefreq>hourly</changefreq> <priority>0.9</priority> </url> Below is my code from BeautifulSoup import BeautifulSoup import requests import gzip from StringIO import StringIO def crawler(): count=0 url="http://www.htcysnc.com/sitemap/sitemap_product.xml.gz" old_xml=requests.get(url) new_xml=gzip.GzipFile(fileobj=StringIO(old_xml.content)).read() #new_xml=old_xml.text final_xml=BeautifulSoup(new_xml) item_to_be_found=final_xml.findAll('loc') for i in item_to_be_found: count=count+1 print i print count crawler() My output is like this <loc>http://www.htcysnc.com/elegant-yellow-green-suit-seven-east-p63703</loc> 1 <loc>http://www.htcysnc.com/elegant-orange-pink-printed-suit-seven-east-p63705</loc> 2 Need the output as links without loc and /loc. Have tried replace command but that is throwing an error. A: Here every item in item_to_be_found list is a Tag type object so you can get the string inside <loc> tag using .text or .string on them. Though .text and .string have differences both will work same in this case. for loc in item_to_be_found: print item_to_be_found.index(loc) + 1, loc.text this will give you a result like 1 http://www.htcysnc.com/m/designer-sarees 2 http://www.htcysnc.com/m/anarkali-suits
{ "pile_set_name": "StackExchange" }
Q: How to make images change a little quicker? My code works just fine but for some reason when you click on the play button it takes a bit longer to switch over to the pause sign, and occasionally it takes a bit longer for the pause button to go to the play button. I also have one more question, when you click on the rain and beach icon there's a blue square border that I didn't remember putting, how do you remove it? Thanks, Love2code <!DOCTYPE html> <html> <head> <title>Meditation App</title> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> <style> *{ margin:0; padding:0; box-sizing:border-box; } .app{ height:100vh; display:flex; justify-content:space-evenly; align-items:center; } .time-select,.sound-picker,.player-container{ height:80%; flex:1; display:flex; flex-direction:column; justify-content:space-evenly; align-items:center; } .player-container{ position:relative; } .player-container svg{ position:absolute; height:50%; top:50%; left:50%; transform:translate(-50%,-50%); pointer-events:none; } .time-display{ position:absolute; bottom:10%; color:white; font-size:50px; } video{ position:fixed; top:0%; left:0%; width:100%; z-index:-10; } .time-select button, .sound-picker button{ color:white; width:30%; height:10%; background:none; border:2px solid white; cursor:pointer; border-radius:5px; font-size:20px; transition:all 0.5s ease; } .time-select button:hover{ color:black; background:white; } .sound-picker button{ border:none; height:120px; width:120px; border-radius:50%; } .sound-picker button:nth-child(1){ background:#4972a1; } .sound-picker button:nth-child(2){ background:#a14f49; } .sound-picker:focus{ outline: none; } </style> </head> <body> <div class="app"> <div class="vid-container"> <video Loop> <source src="https://www.dropbox.com/s/wkdu9elom9o4r5g/rain%20%281%29.mp4?raw=1"/> </video> </div> <div class="time-select"> <button data-time="120">2 Minutes</button> <button data-time="300">5 Minutes</button> <button data-time="600">10 Minutes</button> </div> <div class="player-container"> <audio class="song"> <source src="https://www.dropbox.com/s/jawlfpyyz83w2td/rain.mp3?raw=1"></source> </audio> <img src="https://www.dropbox.com/s/8unx3knosmefedk/download%20%281%29.svg?raw=1" class="play-container" alt=""> <svg class="track-outline" width="453" height="453" viewBox="0 0 453 453" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="226.5" cy="226.5" r="216.5" stroke="white" stroke-width="20"/> </svg> <svg class="moving-outline" width="453" height="453" viewBox="0 0 453 453" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="226.5" cy="226.5" r="216.5" stroke="#018EBA" stroke-width="20"/> </svg> <h3 class="time-display">0:00</h3> </div> <div class="sound-picker"> <button data-sound="https://www.dropbox.com/s/jawlfpyyz83w2td/rain.mp3?raw=1" data-video="https://www.dropbox.com/s/wkdu9elom9o4r5g/rain%20%281%29.mp4?raw=1"><img src="https://i.ibb.co/8BspYTV/rain-1.png"></button> <button data-sound="https://www.dropbox.com/s/6k9nauf2ffyvfuu/beach.mp3?raw=1" data-video="https://www.dropbox.com/s/tsdd86bxmax32jp/beach.mp4?raw=1"><img src="https://i.ibb.co/T0xw4k7/sun-umbrella.png"></button> </div> </body> <script> const app = () => { const song = document.querySelector(".song"); const play = document.querySelector(".play-container"); const outline = document.querySelector(".moving-outline circle"); const video = document.querySelector(".vid-container video"); //Sounds const sounds = document.querySelectorAll(".sound-picker button"); //Time Display const timeDisplay = document.querySelector(".time-display"); //Get length of the outside const outlineLength = outline.getTotalLength(); //Duration let fakeDuration = 600; outline.style.strokeDasharray = outlineLength; outline.style.strokeDashoffset = outlineLength; //play sounds play.addEventListener("click", () => { checkPlaying(song); }); //stop and play the sounds const checkPlaying = song =>{ if(song.paused){ song.play(); video.play(); play.src = 'https://www.dropbox.com/s/3zvnjkebwt1sjgq/download%20%283%29.svg?raw=1'; }else{ song.pause(); video.pause(); play.src = 'https://www.dropbox.com/s/8unx3knosmefedk/download%20%281%29.svg?raw=1'; } } }; app(); </script> </html> A: Because your SVGs are remotely sourced, it takes a bit of time to download them. I've created two hidden images with the remote sources. This will download these and have them ready in your cash for when you need them. I've also changed the sequence of when you switch the source path to come before you play the video. I've set all elements to have an outline of none to take away the blue border when clicking on the image. const app = () => { const song = document.querySelector(".song"); const play = document.querySelector(".play-container"); const outline = document.querySelector(".moving-outline circle"); const video = document.querySelector(".vid-container video"); //Sounds const sounds = document.querySelectorAll(".sound-picker button"); //Time Display const timeDisplay = document.querySelector(".time-display"); //Get length of the outside const outlineLength = outline.getTotalLength(); //Duration let fakeDuration = 600; outline.style.strokeDasharray = outlineLength; outline.style.strokeDashoffset = outlineLength; //play sounds play.addEventListener("click", () => { checkPlaying(song); }); //stop and play the sounds const checkPlaying = song => { if (song.paused) { play.src = 'https://www.dropbox.com/s/3zvnjkebwt1sjgq/download%20%283%29.svg?raw=1'; song.play(); video.play(); } else { play.src = 'https://www.dropbox.com/s/8unx3knosmefedk/download%20%281%29.svg?raw=1'; song.pause(); video.pause(); } } }; app(); * { margin: 0; padding: 0; box-sizing: border-box; outline: none; } .app { height: 100vh; display: flex; justify-content: space-evenly; align-items: center; } .time-select, .sound-picker, .player-container { height: 80%; flex: 1; display: flex; flex-direction: column; justify-content: space-evenly; align-items: center; } .player-container { position: relative; } .player-container svg { position: absolute; height: 50%; top: 50%; left: 50%; transform: translate(-50%, -50%); pointer-events: none; } .time-display { position: absolute; bottom: 10%; color: white; font-size: 50px; } video { position: fixed; top: 0%; left: 0%; width: 100%; z-index: -10; } .time-select button, .sound-picker button { color: white; width: 30%; height: 10%; background: none; border: 2px solid white; cursor: pointer; border-radius: 5px; font-size: 20px; transition: all 0.5s ease; } .time-select button:hover { color: black; background: white; } .sound-picker button { border: none; height: 120px; width: 120px; border-radius: 50%; } .sound-picker button:nth-child(1) { background: #4972a1; } .sound-picker button:nth-child(2) { background: #a14f49; } .sound-picker:focus { outline: none; } <img src="https://www.dropbox.com/s/3zvnjkebwt1sjgq/download%20%283%29.svg?raw=1" style="display:none;"> <img src="https://www.dropbox.com/s/8unx3knosmefedk/download%20%281%29.svg?raw=1" style="display:none;"> <div class="app"> <div class="vid-container"> <video Loop> <source src="https://www.dropbox.com/s/wkdu9elom9o4r5g/rain%20%281%29.mp4?raw=1"/> </video> </div> <div class="time-select"> <button data-time="120">2 Minutes</button> <button data-time="300">5 Minutes</button> <button data-time="600">10 Minutes</button> </div> <div class="player-container"> <audio class="song"> <source src="https://www.dropbox.com/s/jawlfpyyz83w2td/rain.mp3?raw=1"></source> </audio> <img src="https://www.dropbox.com/s/8unx3knosmefedk/download%20%281%29.svg?raw=1" class="play-container" alt=""> <svg class="track-outline" width="453" height="453" viewBox="0 0 453 453" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="226.5" cy="226.5" r="216.5" stroke="white" stroke-width="20"/> </svg> <svg class="moving-outline" width="453" height="453" viewBox="0 0 453 453" fill="none" xmlns="http://www.w3.org/2000/svg"> <circle cx="226.5" cy="226.5" r="216.5" stroke="#018EBA" stroke-width="20"/> </svg> <h3 class="time-display">0:00</h3> </div> <div class="sound-picker"> <button data-sound="https://www.dropbox.com/s/jawlfpyyz83w2td/rain.mp3?raw=1" data-video="https://www.dropbox.com/s/wkdu9elom9o4r5g/rain%20%281%29.mp4?raw=1"><img src="https://i.ibb.co/8BspYTV/rain-1.png"></button> <button data-sound="https://www.dropbox.com/s/6k9nauf2ffyvfuu/beach.mp3?raw=1" data-video="https://www.dropbox.com/s/tsdd86bxmax32jp/beach.mp4?raw=1"><img src="https://i.ibb.co/T0xw4k7/sun-umbrella.png"></button> </div>
{ "pile_set_name": "StackExchange" }
Q: Работа с циклами javascript Есть ситуация: поля на странице с именами типа field[] генерятся автоматом, количество заранее неизвестно. Нужно пройтись по всем полям с именами field[] и проверить не пустые ли они... В php все просто реализуется, а вот в javascript я как ни мучался, не смог понять что к чему. A: var els = document.getElementsByTagName('input'); for(var i = 0, il = els.length; i < il; ++i){ if(els[i].name == 'field[]'){ /* делаем что-то с els[i] если поля могут называться field[1], field[42] и т.п, то if(/field\[\d*\]/.test(els[i].name)) */ } } Обновлено. <script> function testForm(x){ var els = x.getElementsByTagName('input'); for(var i = 0, il = els.length; i < il; ++i){ if(els[i].name == 'field[]'){ if(els[i].value == ''){ alert('Заполните поле!'); els[i].focus() return false; } } } return true; } </script> <form onsubmit="return testForm(this);"> <input name="field[]"> <input name="field[]"> <input name="field[]"> <input type="submit"> </form>
{ "pile_set_name": "StackExchange" }
Q: Missing "Nice Answer" badge from non-deleted answers I realize it's possible that a "nice answer" badge will not be received if a previous nice answer has been removed; but in any case, the number of applicable, non-deleted answers in the profile page should match the number of badges, shouldn't it? Because my profile page on gaming lists 36 applicable answers but only 35 badges. I don't mean to be petty - some of those answers don't deserve those votes, anyway - I just want to point out a potential bug if it is one :) A: Your contribution for "What are some programming games that are out there?" is listed with 14 votes in your profile and therefore looks like it would qualify for a Nice Answer badge. But actually those votes come from two answers to the same question (indicated by the "(2)" after the question name in the profile). The individual answers have only 8 and 6 votes. So the badge count is accurate, it's only the profile that is a little confusing.
{ "pile_set_name": "StackExchange" }
Q: Is there a best practice to forward method overrides while enforcing method execution? Sometimes i have code along the lines of this: public abstract class A { protected abstract void DoSomething(); }   public abstract class B : A { /// <inheritdoc /> protected sealed override void DoSomething() { SpecialFunctionalityOfClassB(); DoSomethingInternal(); } private void SpecialFunctionalityOfClassB() { // execute functionality i don't want an overwriting class to be able to // break by not calling base.DoSomething() // redirect method execution to DoSomethingInternal } protected abstract void DoSomethingInternal(); }   public abstract class C : B { private void SpecialFunctionalityOfClassC() { // execute functionality i don't want an overwriting class to be able to // break by not calling base.DoSomething() // redirect method execution to DoSomethingInternal } /// <inheritdoc /> protected sealed override void DoSomethingInternal() { SpecialFunctionalityOfClassC(); this.DoSomethingElse(); } protected abstract void DoSomethingElse(); } Is there a technique i am not aware of to ensure an unbreakable method chain? If i were to not seal the methods, someone could overwrite a method and forget to call the base version of it. Right now i wouldnt know another way of making sure that whoever derives from D will have all functionality executed the way i want it to, without a subclass breaking that structure. A: One approach you could take is to make your DoSomething method final, and delegate to an overridable implementation method to perform the actual operation. It could then set a flag when its version of the implementation method is called, which it would check for when it returned to DoSomething and throw an exception if it hadn't happened. This approach is taken, for example, in the event handler methods of the Android API, to cause an exception if the implementor fails to call the superclass versions of onCreate etc.
{ "pile_set_name": "StackExchange" }
Q: IBM Cloud-Watson NLC - TypeError: __init__() got an unexpected keyword argument 'iam_apikey' I am currently trying to deploy an application from a repo. (https://github.com/IBM/nlc-icd10-classifier#run-locally) But it gives me this error: Traceback (most recent call last): File "app.py", line 34, in <module> iam_apikey=nlc_iam_apikey TypeError: __init__() got an unexpected keyword argument 'iam_apikey' I am on Python 3.6.8 app.py: load_dotenv(os.path.join(os.path.dirname(__file__), ".env")) nlc_username = os.environ.get("NATURAL_LANGUAGE_CLASSIFIER_USERNAME") nlc_password = os.environ.get("NATURAL_LANGUAGE_CLASSIFIER_PASSWORD") nlc_iam_apikey = os.environ.get("NATURAL_LANGUAGE_CLASSIFIER_IAM_APIKEY") classifier_id = os.environ.get("CLASSIFIER_ID") # Use provided credentials from environment or pull from IBM Cloud VCAP if nlc_iam_apikey != "placeholder": NLC_SERVICE = NaturalLanguageClassifierV1( iam_apikey=nlc_iam_apikey ) elif nlc_username != "placeholder": NLC_SERVICE = NaturalLanguageClassifierV1( username=nlc_username, password=nlc_password .env: CLASSIFIER_ID=<add_NLC_classifier_id> #NATURAL_LANGUAGE_CLASSIFIER_USERNAME=<add_NLC_username> #NATURAL_LANGUAGE_CLASSIFIER_PASSWORD=<add_NLC_password> NATURAL_LANGUAGE_CLASSIFIER_IAM_APIKEY="placeholderapikeyforstackoverflolw" A: It seems that you ran into an issue with the Watson SDK. Recently, with V4, they introduced a breaking change which I found in their release notes. There is a new, more abstract authentication mechanism that caters to different authentication types. You would need to slightly change the code for how NLC is initialized. This is from the migration instructions: For example, to pass a IAM apikey: Before from ibm_watson import MyService service = MyService( iam_apikey='{apikey}', url='{url}' ) After(V4.0) from ibm_watson import MyService from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('{apikey}') service = MyService( authenticator=authenticator ) service.set_service_url('{url}')
{ "pile_set_name": "StackExchange" }
Q: Is it “mat” or “matte” for the color around an image? We are writing a program to add a “matte” around an image but the developers aren't sure whether to name the method matte or mat. The Oxford American dictionary has mat as an alternative spelling of matte. In this case, we think mat is less ambiguous because matte when referring to a color could mean either the glossiness of the color or to its purpose as a framing element. Any advice? A: Why not call it a frame or border instead?
{ "pile_set_name": "StackExchange" }
Q: How to gracefully handle exceptions in a Sinatra API I'm trying to write an API in Sinatra that accepts a temporary CSV file as a parameter. I want to raise an exception if the filetype isn't text/csv or if the csv doesn't have an email column, and I wanted the confirmation page to simply display the error message. I imagined it to look something like this: if params[:recipients_file] raise ArgumentError, 'Invalid file. Make sure it is of type text/csv.' unless params[:recipients_file][:type] == "text/csv" recipients_csv = CSV.parse(params[:recipients_file][:tempfile].read, {headers: true}) raise ArgumentError, 'Invalid CSV. Make sure it has an "email" column' unless recipients_csv.headers.include?('email') recipients += recipients_csv.map {|recipient| recipient["email"]} end However, any time one of those conditions isn't met, I get really ugly error messages like NoMethodErrors etc. I just want the API to stop execution and to return the error message on the confirmation page. How do I do this? A: You should define an error block: error do env['sinatra.error'].message end See http://www.sinatrarb.com/intro.html#Error for more details, including how to set up different error handlers for different exception types, HTTP status codes, etc.
{ "pile_set_name": "StackExchange" }
Q: The date format in the CSV file reverts back to dd/mm/yyyy from set dd/mm/yy I'm using the following code (which is being executed on a .CSV file): ....code ws1.Range("E2:E300000").NumberFormat = "dd/mm/yy" ....code The problem is that even though the date format is defined (by the code above) as "dd/mm/yy", after saving and reopening the file date format reverts back to "dd/mm/yyyy". It seems it only happens with .CSV files (I've tried with xlsm and the format remained as "dd/mm/yy"). Any ideas how to preserve defined "dd/mm/yy" format? A: As @Scott_Craner mentioned CSV does not retain the format. It seems that the only sensible way to end this question is for me to post this statement. Thanks
{ "pile_set_name": "StackExchange" }
Q: How to include members with specific children in MDX query cross join? I'm new to MDX, and I have following scenario. I have to calculate revenue across specific department (product dimension), specific store (location dimension) and across specific time range. I have my cube levels as follows. Product <- Department <- Item Location <- Region <- Store Time <- Year <- Month <-Day Say if I have following members [Product].[Dairy].[Oak Farm] [Product].[Dairy].[GV] [Location].[US West].[LA] [Location].[US West].[CA] [Time].[2015].[01].[01] : [Time].[2015].[02].[01] Then I should get result as where in Product should include only GV and location should include only CA 2015-01-01 US West Dairy $100 2015-02-01 US West Dairy $100 Any help would be appreciated. A: Probably several ways depending on exact requirements. SELECT [Measures].[SomeCubeMeasure] ON 0, {[Time].[2015].[01].[01] : [Time].[2015].[02].[01]}* Exists ( [Location].[Region].MEMBERS ,[Location].[US West].[CA] )* Exists ( [Product].[Department].MEMBERS ,[Product].[Dairy].[GV] ) ON 1 FROM [yourCube]; Edit To create a measure that just looks at certain stores you could use something like this: WITH MEMBER [Measures].[Store1and2Measure] AS Aggregate ( { [Store][Region1][Store1] ,[Store][Region1][Store2] } ,[Measures].[SomeCubeMeasure] ) SELECT [Measures].[Store1and2Measure] ON 0, [Location].[US West].[LA] ON 1 FROM [yourCube];
{ "pile_set_name": "StackExchange" }
Q: Use javascript to get the style of an element from an external css file I have a html like this: <html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> alert(document.getElementById('test').style.display); </script> </body> </html> The style.css: div { display:none; } I expect the js would return "none", but it return an empty string instead. Is there any way to solve this problem? A: This would work for standards compliant browsers (not IE - currentStyle/runtimeStyle). <body> <div id="test">Testing</div> <script type="text/javascript"> window.onload = function() { alert(window.getComputedStyle(document.getElementById('test'),null).getPropertyValue('display')); } </script> </body> A: Since display is not set directly as a style property, you won't get that using the above code. You have to get the computed value. You can refer this page, Get styles To get the value var displayValue = getStyle("test", "display"); function getStyle(el,styleProp) { var x = document.getElementById(el); if (x.currentStyle) var y = x.currentStyle[styleProp]; else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp); return y; }
{ "pile_set_name": "StackExchange" }
Q: My awk program to change spaces into tabs doesn't work How to write a shell script which uses awk to read in the data file students.txt and output the data in the tabbed format as shown: Surname Forename MSc Stream Date of Birth Smith John IT 15.01.1986 Taylor Susan IT 04.05.1987 Thomas Steve MIT 19.04.1986 Do not worry if tabbed columns don’t line up. The distance between each of (Surname, Forename, MSc Stream and Date of Birth) column is one tab. Question: Why this bellow code doesn't work for me? awk 'BEGIN {IFS=" "} {OFS="\t"} {print $1,$2,$3,$4}' students.txt A: awk '{$1=$1}1' OFS="\t" students.txt Proof of Concept $ awk '{$1=$1}1' OFS="\t" students.txt Surname Forename MSc Stream Date of Birth Smith John IT 15.01.1986 Taylor Susan IT 04.05.1987 Thomas Steve MIT 19.04.1986 Explanation The reason it didn't work is because awk requires one of the fields to be changed before it applies the new output field separator. The workaround for this defect (IMHO) is to just set a field to itself, hence the $1=$1 For this simple type of change, you're better off using tr or sed tr -s ' \t' '\t*' < students.txt sed 's/[[:space:]]\+/\t/g' students.txt
{ "pile_set_name": "StackExchange" }
Q: What makes imaginary parts show up? If I define a function using alpha[y_, d_] := 2 ArcCos[1 - (2 y)/d] Then if $y$ and $d$ are equal, the result is $2\pi$ : alpha[x, x] and alpha[4, 4] are both evaluated as $2 \pi$ But when I use this in a table with: Table[alpha[y1, d1], {d1, 0.1, 5, 0.1}, {y1, 0, d1, 0.1}] Some imaginary parts (although very small) for example $6.28319 - 5.96046*10^-8 i$ appear. Am I doing something wrong? It seems like something basic that I am doing wrong because of not understanding a concept in MMA. A: Many thanks to @J.M. and @Artes I found out that the iterator 0.1 in the Table function was making this artifact, which is also version dependent. @J. M.'s solution worked perfectly: Table[N[alpha[y1, d1]], {d1, 1/10, 5, 1/10}, {y1, 0, d1, 1/10}]
{ "pile_set_name": "StackExchange" }
Q: NaCl - Rebus puzzle Solve the following rebus puzzle: NaCl * H2O H2O * NaCl ------------ CCCCCCC A: Answer Sailing (Saline), Sailing over the seven seas (Cs)
{ "pile_set_name": "StackExchange" }
Q: Type of solutions for the linear equation AX=B I have a problem and a proposed solution. Please tell me if I'm correct. Problem: For A,B real matrices, prove that if there is a solution in the complex numbers then there is also a real solution. Solution: A and B are real matrices. Therefore, they are not defined over the complex plane, and a solution in C is not possible for the system AX=B. Hence, the "if" part is false by default and the "then" part is always true, making the implication always true and rendering the problem statement as proven. Thanks! A: Let $X$ be a (possibly) complex solution to $AX=B$. Since $A$ and $B$ are real, then $\overline{X}$ (component-wise conjugate) is also a solution, so that $\frac{X+\overline{X}}{2}$ is solution but this a real matrix. In this way we have constructed a real solution starting from a complex one. A: The matrix equation boils down to a system of linear equations of the form $$a_1z_1+ a_2z_2 + \cdots a_nz_n=c,$$ where you're assuming the $a_i$ and $c$ are real numbers. There will typically be systems of such equations which must hold all at once and mention the same $z_i$. Now write each $z_k=x_k+iy_k$ and note that each equation above implies (by taking real parts) that if all the $y_k$ are replaced by $0$ the equation still holds, giving a real solution also.
{ "pile_set_name": "StackExchange" }
Q: How to use the elevator? The mission after the first boss includes one of those elevators. I wonder how to use them. There are two arrows (up/down). Going to these direction buttons has no effect. How do I trigger them when playing WASD or ArrowKeys? (With XBox360 controller it's the Y key) A: press c, just figured it out myself
{ "pile_set_name": "StackExchange" }
Q: smartgwt listgrid RestDataSource not populating Im new using this front end framework application... I recently started to work with smartgwt and i'm bulding a new application with a Spring MVC integration. I'm using a ListGrid with a RestDataSource (Consume the Rest service with mvc:annotation-driven for plain JSON) I can see that the servaice gets consuming properly perhaps my grid is never shown with the data in it. Can someone help me here ? Here's my ListGrid class public class ListGrid extends com.smartgwt.client.widgets.grid.ListGrid { private final SpringJSONDataSource springJSONDataSource; public ListGrid(List<DataSourceField> fields) { this(new PatientDataSource(fields)); } public ListGrid(SpringJSONDataSource springJSONDataSource) { this.springJSONDataSource = springJSONDataSource; init(); } private void init() { setAutoFetchData(true); setAlternateRecordStyles(true); setEmptyCellValue("???"); setDataPageSize(50); setDataSource(springJSONDataSource); } } Now there's the DataSource implmentation public abstract class SpringJSONDataSource extends RestDataSource { protected final HTTPMethod httpMethod; public SpringJSONDataSource(List<DataSourceField> fields) { this(fields, HTTPMethod.POST); } public SpringJSONDataSource(List<DataSourceField> fields, HTTPMethod httpMethod) { this.httpMethod = httpMethod; setDataFormat(DSDataFormat.JSON); addDataSourceFields(fields); setOperationBindings(getFetch()); addURLs(); } private void addURLs() { if(getUpdateDataURL() != null) setUpdateDataURL(getUpdateDataURL()); if(getRemoveDataURL() != null) setRemoveDataURL(getRemoveDataURL()); if(getAddDataURL() != null) setAddDataURL(getAddDataURL()); if(getFetchDataURL() != null) setFetchDataURL(getFetchDataURL()); } private void addDataSourceFields(List<DataSourceField> fields) { for (DataSourceField dataSourceField : fields) { addField(dataSourceField); } } protected abstract OperationBinding getFetch(); protected abstract OperationBinding getRemove(); protected abstract OperationBinding getAdd(); protected abstract OperationBinding getUpdate(); public abstract String getUpdateDataURL(); public abstract String getRemoveDataURL(); public abstract String getAddDataURL(); public abstract String getFetchDataURL(); } The class PatientDataSource that extends SpringJSONDataSource public class PatientDataSource extends SpringJSONDataSource { public PatientDataSource(List<DataSourceField> fields) { super(fields); setPrettyPrintJSON(true); } @Override protected OperationBinding getFetch() { OperationBinding fetch = new OperationBinding(); fetch.setOperationType(DSOperationType.FETCH); fetch.setDataProtocol(DSProtocol.POSTMESSAGE); DSRequest fetchProps = new DSRequest(); fetchProps.setHttpMethod(httpMethod.toString()); fetch.setRequestProperties(fetchProps); return fetch; } @Override public String getFetchDataURL() { return "/spring/fetchPatients"; } @Override protected OperationBinding getRemove() { return null; } @Override public String getRemoveDataURL() { return null; } @Override protected OperationBinding getAdd() { return null; } @Override public String getAddDataURL() { return null; } @Override protected OperationBinding getUpdate() { return null; } @Override public String getUpdateDataURL() { return null; } } My spring controller PatientControler @Controller public class PatienController { Logger logger = Logger.getLogger(PatienController.class); @Autowired private PatientServices patientServices; @RequestMapping(value = "/patientTest", method = RequestMethod.GET) @ResponseBody public Object getTest() { return patientServices.getAllPatients(); } @RequestMapping(value = "/fetchPatients", method = RequestMethod.POST) @ResponseBody public Object getAllPatients() { return patientServices.getAllPatients(); } } PatientServiceImpl public class PatientServicesImpl implements PatientServices { public List<Patient> getAllPatients() { List<Patient> patients = new ArrayList<Patient>(); Patient patient; for(int i = 0 ; i < 500 ; i++){ patient = new Patient(); patient.setDateOfBirth(new Date()); patient.setFirstName("Joe"); patient.setMiddleName("Moe"); patient.setLastName("Blow"); patient.setLastConsultation(new Date()); patient.setSex(Sex.M); patients.add(patient); } return patients; } } *Im Really stuck right now i've been looking for all type of answers .... but so far nothing worked when i tried to override the transformResponse from my RestDataSource impentation the parameter "data" as an OBJECT, returns me an array [object Object],[object Object],[object Object],[object Object],[object Object] * A: The Data which is transferred from the RestDataSource has a specific format which is described in the JavaDoc of the RestDataSource Your server must understand the request and send back a valid response. At the moment your example doesn't seem to honour the contract. To debug the traffic send to and from your server you can use the SmartClient-Console. You can open it by a browser bookmark like this: javascript:isc.showConsole() Of cause you need to deploy this console by adding the following module to your gwt.xml <inherits name="com.smartclient.tools.SmartClientTools"/> Now go to the RPC Tab and check Track-RPCs
{ "pile_set_name": "StackExchange" }
Q: What is the field of view(FOV) of the color camera in Kinect for Windows V2? Can't find it anywhere. The kinectforwindows site has the FOV for depth camera. I can't find it in the box either. A: @user1809923 is correct. I contacted the developer of the link: http://smeenk.com/kinect-field-of-view-comparison/ And he responded with this information: If I remember correctly these FOV values are part of the framedescriptions that you can retrieve with help of the Kinect SDK. Since other people asked for the same info I will update the my blog. I confirmed his findings by calling the frame's framedescription in the Kinect SDK code and printing the values to the screen.
{ "pile_set_name": "StackExchange" }