text
stringlengths
64
81.1k
meta
dict
Q: CSS banner image, doesn't scale beyond the parent element I'm trying to style a typcial banner image for a site, so that for narrower viewports the vertical height is maintained and the image effectively stays the same size by going beyond the parent element horizontally. (I think this is fairly typical banner image behaviour - but feel free to correct me if I'm wrong). (browser target is ie10 and up). The below incorrectly keeps the image ratio and at 100% width so that if fails to match the height of the parent. The current html is just an img inside a div tag <div class="banner"> <img class="img-fluid" src="somepic.jpg" /> </div> Where the css classes used are: .banner { content: ""; position: absolute; width: 100%; top: 0; left: 0; height: 780px; } and img-fluid is a bootstrap(4) class with img-fluid { max-width: 100%; height: auto; } A: Use a background-image instead, there are a couple interesting behaviours that can be used to achieve different results. Here's my take: .banner { content: ""; position: absolute; width: 100%; top: 0; left: 0; height: 780px; background-image:url('somepic.jpg'); background-size:cover; } The key here is background-size:cover;, it will make sure the image stretches to cover the full width and height while keeping its ratio. That means on very wide screens, it will be made larger, cutting some height. But on thinner resolutions you'll get the desired output.
{ "pile_set_name": "StackExchange" }
Q: How to vertically center Wordpress navigation bar I have a navigation bar at following wordpress site: http://tarjom.ir/demo/pwp I have two major issues with this navigation bar: 1- I can't vertically align it at the middle. 2- There is a div wrapper as the parent of the <ul> tag that I can't remove it. However I have already set 'container' => '', but it does not work. <!-- Navigation bar--> <div id='wp_nav_section' class='grid-100 black-gray-bg font-roya' style='min-height: 100px; display: block;height:100%;'> <?php wp_nav_menu(array("container" => 'nav')); ?> </div> <!-- End of navigation bar. --> Here is my wordpress navigation code: Here is all my CSS related to the wordpress navigation: .menu { height: 65px; min-height: 60px; padding: 0px; text-align: right; background-color: #111; margin-bottom: 10px; } .menu ul { direction: rtl; width: 70%; margin-right: auto; margin-left: auto; overflow: hidden; height: auto; padding-top: 0px; } .menu li { padding: 0px 0px; display: inline-block; } .menu li a { color: white; text-decoration: none; display: block ; height: 45px; background-color: black; border-right: 2px #333 solid; padding: 16px 7% 3px 3%; box-sizing: border-box; width: 100px; margin: 0px 0px; font-size: 110%; } .menu li a:hover { background-color: #333; border-right: 2px #F90 solid; } I need the <ul> tag to be centered vertically in the <div> wrapper. Thanks in advanced. A: Remove height from .menu{} class. this will solved your vertical align issue.
{ "pile_set_name": "StackExchange" }
Q: Zooming in and out on an image not working as it should i have a map image that i want to zoom in and out on with the scrollwheel. This works perfectly while zooming in or out only, but when i change direction (from to have zoomed in to zoom out) the shit starts. If i scrolled 3 times zoom in and then change direction to zoom out it takes as many scrolls -1 before it starts zooming out and meanwhile it keeps zooming in making the ctx.scale go bananas. Thank you for any replys <3 var scaleY = 1; var scaleX = 1; //function to draw the map function loader(){ //load background var canvas = document.getElementById("mycanvas"); var ctx = canvas.getContext("2d"); var background = new Image(); background.src = "map2.png"; background.onload = function(){ ctx.clearRect(0,0,1375,850); ctx.scale(scaleY,scaleX); ctx.drawImage(background,0,0); ctx.font = "15px arial"; ctx.fillText(scaleY,25,pos); } } function userActions(){ var canvas = document.getElementById("mycanvas"); //detect scroll activity canvas.addEventListener("wheel", zoom); //function to decide if the scroll si up or down function zoom(e){ if (e.deltaY < 0){ //change the scale scaleY = Math.round((scaleY + 0.1) * 10) / 10; scaleX = Math.round((scaleX + 0.1) * 10) / 10; loader(scaleY, scaleX); } if(e.deltaY > 0){ //change the scale scaleY = Math.round((scaleY - 0.1) * 10) / 10; scaleX = Math.round((scaleX - 0.1) * 10) / 10; loader(scaleY, scaleX); } } } A: scale is not absolute, but multiplies the scale factors onto the current transformation matrix. You should reset it after every draw call. This can be done via: ctx.setTransform(1, 0, 0, 1, 0, 0); var scaleY = 1; var scaleX = 1; var canvas = document.getElementById("mycanvas"); var ctx = canvas.getContext("2d"); var background = new Image(); background.src = "https://www.gravatar.com/avatar/c35af79e54306caedad37141f13de30c?s=128&d=identicon&r=PG"; background.onload = draw; //function to draw the map function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.scale(scaleY, scaleX); ctx.drawImage(background, 0, 0); // reset current transformation matrix to the identity matrix ctx.setTransform(1, 0, 0, 1, 0, 0); } //function to decide if the scroll si up or down function zoom(e) { if (e.deltaY < 0) { //change the scale scaleY = Math.round((scaleY + 0.1) * 10) / 10; scaleX = Math.round((scaleX + 0.1) * 10) / 10; draw(); } if (e.deltaY > 0) { //change the scale scaleY = Math.round((scaleY - 0.1) * 10) / 10; scaleX = Math.round((scaleX - 0.1) * 10) / 10; draw(); } e.preventDefault(); } canvas.addEventListener("wheel", zoom); <canvas id="mycanvas" height="200" width="200"/>
{ "pile_set_name": "StackExchange" }
Q: Store value to variable from segmented control I have a segmented control for the user to select whether a driver is male/female. How do i store the string "male" or "female" to a variable, dependant on what the user selects on the segmented control? A: If your segmented control is set up correctly to respond to the control event UIControlEventValueChanged, you can access the index of the selected segment with selectedSegmentIndex The default value is UISegmentedControlNoSegment (no segment selected) until the user touches a segment. Once they do, calling selectedSegmentIndex: will return a NSInteger. From there you can store the string male or female depending on the index. Example: NSString *gender = @"unknown"; NSInteger *selectedIndex = yoursegmentcontrol.selectedSegmentIndex; if (selectedIndex == 0) gender = @"male"; else gender = @"female";
{ "pile_set_name": "StackExchange" }
Q: How can I show array results using jQuery conditional statement? I am trying to pull store locations using conditional statements. When I search for Dealer, Wholesale, or retail respectively from select option menu, the results are displayed. However, I cannot display all the location if All is selected. If I remove &&(locationData['category']=== 'Dealer' || 'Wholesale' ||'Retail'), I can show All the locations, but I can't display store locations based on each category. How can I set up a conditional statement? This is what I have in HTML: <select id="category" name="category"> <option value="" selected>All</option> <option value="Dealer">Wholesale &amp;Retail</option> <option value="Wholesale">Wholesale</option> <option value="Retail">Retail</option> </select> This is what I have in js if(settings.maxDistance === true && firstRun !== true){ if((locationData['distance'] < maxDistance)&&(locationData['category']=== 'Dealer' || 'Wholesale' ||'Retail')) { locationset[i] = locationData; } else { return; } } else { locationset[i] = locationData; } i++; }); } A: I'm not entirely sure what question you're asking so I'll answer several things that are going on in your question. If you want to know how to get the value from the select object, you can do that like this: $("#category").val() If you want to know how to detect the "All" choice, then you should change your HTML to this (set a value for the "All" item): <select id="category" name="category"> <option value="All" selected>All</option> <option value="Dealer">Wholesale &amp;Retail</option> <option value="Wholesale">Wholesale</option> <option value="Retail">Retail</option> </select> And you can check for it with a conditional like this: if ($("#category").val() === "All") { // All is selected } I also see in your code that you have an error in your conditional. You can't compare to multiple things like this: &&(locationData['category']=== 'Dealer' || 'Wholesale' ||'Retail') You have to compare to each one separately: && (locationData['category']=== 'Dealer' || locationData['category'] === 'Wholesale' || locationData['category'] === 'Retail') Or, using a temporary variable to hold the comparison value, your code could look like this: if (settings.maxDistance && !firstRun) { var item = locationData['category']; if((locationData['distance'] < maxDistance) && (item === 'Dealer' || item === 'Wholesale' || item === 'Retail')) { locationset[i] = locationData; } else { return; } } else { locationset[i] = locationData; } If you do this a lot, sometimes, it's useful to make a static object that you can use as a lookup table: var categories = {Dealer: true, Wholesale: true, Retail: true}; if (settings.maxDistance && !firstRun) { if((locationData['distance'] < maxDistance) && (categories.hasOwnProperty(locationData['category'])) { locationset[i] = locationData; } else { return; } } else { locationset[i] = locationData; }
{ "pile_set_name": "StackExchange" }
Q: differences in python 3.5 vs 3.6 when print() unicode charcters? My python file: print('Amanhã') I am using the integrated terminal in VSCode 1.28.1, on Windows 10 Pro. When I activate a Python 3.6-based virtual environment then run this script, it executes as expected and I see Amanhã in the terminal. But when I activate a Python 3.5-based virtual environment then run this script, it fails with a UnicodeEncodeError: UnicodeEncodeError: 'charmap' codec can't encode character '\xe3' in position 5: character maps to <undefined> If I run set PYTHONIOENCODING=utf8 in the 3.5-based environment, then execute the script, the Unicode error is gone but the output is not exactly as expected: Amanh├ú How can I see Amanhã in the 3.5-based venv? (I replicated this in the normal Windows terminal (cmd.exe), not inside VSCode -- exact same result. I also will note that sys.getdefaultencoding() returns utf-8 both before and after the set PYTHONIOENCODING=utf8 command) A: Based on the incorrect output, your terminal is using cp437, which doesn't support the character ã. Pre-Python 3.6, Python encodes Unicode to the encoding of the terminal on Windows. As of Python 3.6, Python uses Unicode Win32 APIs when writing to the terminal and, as you have found, works much better. If you must use Python 3.5, check out win-unicode-console.
{ "pile_set_name": "StackExchange" }
Q: Statistical test to determine if a relationship is linear? What is the best statistical test to use if I measure the value of $Y$ (e.g. pH) for specific values of $X$ e.g. $X=0,10,20,30,...,100$ (e.g. temperature) and I want to test weather the relationship between $X$ and $Y$ is linear? (i.e. $H_0$: The relationship between $X$ and $Y$ is linear, $H_1$: The relationship between $X$ and $Y$ is not linear). My thoughts I was thinking of either a Pearson's rank test, however on further reading it appears this cannot in fact be used to test linearity or a model misspecification test but I think the data set would be to small for any reasonable progress to be made with such a test. A: Any rank test will only test for monotonicity, and a highly nonlinear relationship can certainly be monotone. So any rank-based test won't be helpful. I would recommend that you fit a linear and a nonlinear model and assess whether the nonlinear model explains a significantly larger amount of variance via ANOVA. Here is a little example in R: set.seed(1) xx <- runif(100) yy <- xx^2+rnorm(100,0,0.1) plot(xx,yy) model.linear <- lm(yy~xx) model.squared <- lm(yy~poly(xx,2)) anova(model.linear,model.squared) Analysis of Variance Table Model 1: yy ~ xx Model 2: yy ~ poly(xx, 2) Res.Df RSS Df Sum of Sq F Pr(>F) 1 98 1.27901 2 97 0.86772 1 0.41129 45.977 9.396e-10 *** --- Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 In this particular case, the ANOVA correctly identifies nonlinearity. Of course, you can also look at higher orders than squares. Or use splines instead of unrestricted polynomials. Or harmonics. It really depends on what specific alternatives you have in mind, which will in turn depend on your specific use case. A: I like a lot the ANOVA-based answer by Stephan Kolassa. However, I would also like to offer a slightly different perspective. First of all, consider the reason why you're testing for nonlinearity. If you want to test the assumptions of ordinary least squares to estimate the simple linear regression model, note that if you then want to use the estimated model to perform other tests (e.g., test whether the correlation between $X$ and $Y$ is statistically significant), the resulting test will be a composite test, whose Type I and Type II error rates won't be the nominal ones. This is one of multiple reasons why, instead than formally testing the assumptions of linear regression, you may want to use plots in order to understand if those assumptions are reasonable. Another reason is that the more tests you perform, the more likely you are to get a significant test result even if the null is true (after all, linearity of the relationship between $X$ and $Y$ is not the only assumption of the simple linear regression model), and closely related to this reason there's the fact that assumption tests have themselves assumptions! For example, following Stephan Kolassa's example, let's build a simple regression model: set.seed(1) xx <- runif(100) yy <- xx^2+rnorm(100,0,0.1) plot(xx,yy) linear.model <- lm(yy ~ xx) The plot function for linear models shows a host of plots whose goal is exactly to give you an idea about the validity of the assumptions behind the linear model and the OLS estimation method. The purpose of the first of these plots, the residuals vs fitted plot, is exactly to show if there are deviations from the assumption of a linear relationship between the predictor $X$ and the response $Y$: plot(linear.model) You can clearly see that there is a quadratic trend between fitted values and residuals, thus the assumption that $Y$ is a linear function of $X$ is questionable. If, however, you are determined on using a statistical test to verify the assumption of linearity, then you're faced with the issue that, as noted by Stephan Kolassa, there are infinitely many possible forms of nonlinearity, so you cannot possibly devise a single test for all of them. You need to decide your alternatives and then you can test for them. Now, if all your alternatives are polynomials, then you don't even need ANOVA, because by default R computes orthogonal polynomials. Let's test 4 alternatives, i.e., a linear polynomial, a quadratic one, a cubic one and a quartic one. Of course, looking at the residual vs fitted plot, there's not evidence for an higher than degree 2 model here. However, we include the higher degree models to show how to operate in a more general case. We just need one fit to compare all four models: quartic.model <- lm(yy ~ poly(xx,4)) summary(quartic.model) Call: lm(formula = yy ~ poly(xx, 4)) Residuals: Min 1Q Median 3Q Max -0.175678 -0.061429 -0.007403 0.056324 0.264612 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 0.33729 0.00947 35.617 < 2e-16 *** poly(xx, 4)1 2.78089 0.09470 29.365 < 2e-16 *** poly(xx, 4)2 0.64132 0.09470 6.772 1.05e-09 *** poly(xx, 4)3 0.04490 0.09470 0.474 0.636 poly(xx, 4)4 0.11722 0.09470 1.238 0.219 As you can see, the p-values for the first and second degree term are extremely low, meaning that a linear fit is insufficient, but the p-values for the third and fourth term are much larger, meaning that third or higher degree models are not justified. Thus, we select the second degree model. Note that this is only valid because R is fitting orthogonal polynomials (don't try to do this when fitting raw polynomials!). The result would have been the same if we had used ANOVA. As a matter of fact, the squares of the t-statistics here are equal to the F-statistics of the ANOVA test: linear.model <- lm(yy ~ poly(xx,1)) quadratic.model <- lm(yy ~ poly(xx,2)) cubic.model <- lm(yy ~ poly(xx,3)) anova(linear.model, quadratic.model, cubic.model, quartic.model) Analysis of Variance Table Model 1: yy ~ poly(xx, 1) Model 2: yy ~ poly(xx, 2) Model 3: yy ~ poly(xx, 3) Model 4: yy ~ poly(xx, 4) Res.Df RSS Df Sum of Sq F Pr(>F) 1 98 1.27901 2 97 0.86772 1 0.41129 45.8622 1.049e-09 *** 3 96 0.86570 1 0.00202 0.2248 0.6365 4 95 0.85196 1 0.01374 1.5322 0.2188 For example, 6.772^2 = 45.85998, which is not exactly 45.8622 but pretty close, taking into account numerical errors. The advantage of the ANOVA test comes into play when you want to explore non-polynomial models, as long as they're all nested. Two or more models $M_1,\dots,M_N$ are nested if the predictors of $M_i$ are a subset of the predictors of $M_{i+1}$, for each $i$. For example, let's consider a cubic spline model with 1 interior knot placed at the median of xx. The cubic spline basis includes linear, second and third degree polynomials, thus the linear.model, the quadratic.model and the cubic.model are all nested models of the following spline.model: spline.model <- lm(yy ~ bs(xx,knots = quantile(xx,prob=0.5))) The quartic.model is not a nested model of the spline.model (nor is the vice versa true), so we must leave it out of our ANOVA test: anova(linear.model, quadratic.model,cubic.model,spline.model) Analysis of Variance Table Model 1: yy ~ poly(xx, 1) Model 2: yy ~ poly(xx, 2) Model 3: yy ~ poly(xx, 3) Model 4: yy ~ bs(xx, knots = quantile(xx, prob = 0.5)) Res.Df RSS Df Sum of Sq F Pr(>F) 1 98 1.27901 2 97 0.86772 1 0.41129 46.1651 9.455e-10 *** 3 96 0.86570 1 0.00202 0.2263 0.6354 4 95 0.84637 1 0.01933 2.1699 0.1440 Again, we see that a quadratic fit is justified, but we have no reason to reject the hypothesis of a quadratic model, in favour of a cubic or a spline fit alternative. Finally, if you would like to test also non-nested model (for example, you would like to test a linear model, a spline model and a nonlinear model such as a Gaussian Process), then I don't think there are hypothesis tests for that. In this case your best bet is cross-validation.
{ "pile_set_name": "StackExchange" }
Q: Packaging up a project for deployment - Java I have a Java application (a quite large one with many external .jar dependencies as well as dependencies on images) and I need to package it up so that someone can double click to run, for example. Or something easy like that. It uses Java Persistence, so it requires a sql connection which is specified in the Persistence.xml file in the Java Project. How can I package this up? I was thinking: the installation process should validate that the user has MySQL installed and if not, direct them to install it the installation process could ask the user to enter credentials for any database and then I could update the Persistence.xml at run time These were two ideas I had...but I wasn't sure if there was a known solution to this problem. Any help would be much appreciated! A: I think you should take a look at embedded database solutions, like H2. Also, you can package your application using maven's shadowing or jar plugin, having the jar-with-dependencies profile activated. This will nicely rid you of checking for database servers running on the client machine, and also will give you the proper means of bundling the application in one nice JAR, albeit a little large. Maven is a build ecosystem and toolset especially designed for building Java applications and executing the code -- and generally doing whatever else you can imagine that's possible to do with and to your code. It has a rich API for developing plugins and many developers have exploited this feature. There are numerous plugins for building -- and launching -- and packaging your application as well as helping you manage your applications dependencies. Maven's shadowing comes in the form of maven-shade-plugin, available here. What it does is that it helps you create a single JAR file from all your dependencies. Also, there is the maven-jar-plugin which offers a profile jar-with-dependencies. It is also accessible from here. H2, on the other hand is a full-fledged RDBMS. This is the website: http://www.h2database.com/html/main.html, and here is a tutorial. You can find information on embedding the database here: How to embed H2 database into jar file delivered to the client? Embedding the Java h2 database programmatically h2 (embedded mode ) database files problem I would also suggest you use a combination of H2/Hibernate/Spring which is a very easy setup and provides you with really rich features and an easy-to-use API. I hope this helps you :)
{ "pile_set_name": "StackExchange" }
Q: How can I achieve very bright light? I'm not sure if this is right site for this, but couldn't find better. I've been given an task to create something that has light intensity like police beacon. I need it to be cheap, so I'm looking at dealextreme.com LED emitters , but there aren't any good user experience videos. I don't know if the LEDs are right for this and how should I pick right one from these LEDs. A: Maximising brightness: Brightness is a function of amount of light and area illuminated. More light = more brightness. Less area = more brightness. So For more light obtain as many lumens as you can afford. For less illuminated area use LEDs with low "radiation angle" or "cone angle". Lenses: If that is not bright enough you can use a lens or reflector. Many companies provide lenses for LEDs. Deal Extreme have a range here Effect of colour: Note also that brightness is related to eye response to colour - yukky yellow green is about the best colour for optimum eye perceived brightness - but if you want a specific colour this is not much help in optimising brightness. Related: Mind plasticity add on for the ever young: Lime Green is close - Lime Green Fire Engine from here - BUT more recent studies suggest that familiarity is more important than visibility for emergency vehicles. A: It sounds like you would be better of with an of the shelf high-brigtness LED lamp rather than individual LEDs for which you need to make a circuit.
{ "pile_set_name": "StackExchange" }
Q: DataSvcUtil.exe and generating a custom namespace I am using DataSvcUtil and I wanted to generate a custom namespace for my generated class but this does not seem to be allowed. Is there a reason for this? A: DataSvcUtil.exe is a fairly thin wrapper over the System.Data.Services.Design.EntityClassGenerator class, which has support for using a custom namespace prefix, but not arbitrarily customizing the namespaces. I don't know of a specific reason this support was not provided, there may not have been a compelling enough scenario for it at the time. If you need more flexible code generation, I strongly suggest you take a look at the T4 template the team released some time ago. It is very likely that code generation for WCF Data Services will more towards using T4 rather than DataSvcUtil/EntityClassGenerator.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET Core 2.2. Razor Pages - How to populate a form control based on another field I have a form control "ConnectorType" which I turned into a dropdown list with pre-defined values (just 3qty currently) When the user selects and item from this dropdown list, depending on the value selected I then want to populate another text box form control underneath. To better explain, please see image below: Example, if TCP Server IN is selected then the form control underneath (textbox)should automatically say "Inbound" Ideally this text box should also have an attribute/configuration that prevents the user from entering their own text, grayed out perhaps. Once the create form is submitted, the textbox that contains this value "Inbound" will then be added to the SQL Table using Enitity Framework. The solution requires that this field dynamically changes each time a new item is selected from the list. Current code for the drop down list: Page Model Class: public IEnumerable<SelectListItem> ConnectorTypeList { get; private set; } // temp public IActionResult OnGet() { // prepare the list in here ConnectorTypeList = new SelectListItem[] { new SelectListItem ("TCP Server IN", "TCP Server IN"), new SelectListItem ("TCP Server OUT", "TCP Server OUT"), new SelectListItem ("SMTP Server IN", "SMTP Server IN") }; return Page(); } Page View: <div class="form-group"> <label asp-for="ConnectorModel.ConnectorType" class="control-label"></label> <select asp-for="ConnectorModel.ConnectorType" class="form-control" asp-items="@Model.ConnectorTypeList"></select> <span asp-validation-for="ConnectorModel.ConnectorType" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="ConnectorModel.DataFlow" class="control-label"></label> <input asp-for="ConnectorModel.DataFlow" class="form-control" /> <span asp-validation-for="ConnectorModel.DataFlow" class="text-danger"></span> </div> Note the current form-control I'm wanting to modify is the "ConnectorModel.DataFlow" in the above page view code. At the moment it's just a simple textbox that the user can enter their own choice of text. I'm going round in circles having read up on page handlers etc. It seems there is a onchange event but unsure how to implement this and somehow link it back to the page model class, run a method then postback the result. I'm not looking for a JQuery script as it seems this should not be required in the newer framework, not sure I just don't want a complicated long solution given I will be using a lot of these throughout the app. Thanks in advance... A: The easiest way is to use onchange() on your <select> tag and assign data to input using js.(Add id attribute for <select> and <input> before) If you would like to prevent the user from entering their own text, just use readonly attribute for you input. <input asp-for="DataFlow" id="dataFlow" class="form-control" readonly/> The Sample Page View: <div class="row"> <div class="col-md-4"> <form method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="form-group"> <label asp-for="ConnectorModel.ConnectorType" class="control-label"></label> <select asp-for="ConnectorModel.ConnectorType" id="connectorTypeList" class="form-control" asp-items="@Model.ConnectorTypeList" onchange="assignData()"> <option>Select ConnectorType</option> </select> <span asp-validation-for="ConnectorModel.ConnectorType" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="ConnectorModel.DataFlow" class="control-label"></label> <input asp-for="ConnectorModel.DataFlow" id="dataFlow" class="form-control" readonly /> <span asp-validation-for="ConnectorModel.DataFlow" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="Create" class="btn btn-primary" /> </div> </form> </div> </div> @section Scripts{ <script> function assignData() { var contentType = $("#connectorTypeList").val(); if (contentType == "TCP Server IN") { $("#dataFlow").val("Inbound"); } } </script> }
{ "pile_set_name": "StackExchange" }
Q: What are these seemingly incorrect sentences called? I sometimes stumble upon phrases such as This command not executed. This widget property of B.C. This page intentionally left blank. The verb is missing here, isn't it? I see these types of sentence so much, and to my knowledge, they are just wrong. Is there a name for this type of sentence? Also, why are they used? I mean, inserting an "is" in there is not that much effort, is it? A: As far as I know (my grammatical knowledge is not extensive), these sentences are referred to as minor sentences. As Wikipedia states: A major sentence is a regular sentence; it has a subject and a predicate, e.g. "I have a ball.". In this sentence, one can change the persons, e.g. "We have a ball.". However, a minor sentence is an irregular type of sentence that does not contain a main clause, e.g. "Mary!", "Precisely so.", "Next Tuesday evening after it gets dark.". Other examples of minor sentences are headings (e.g. the heading of this entry), stereotyped expressions ("Hello!"), emotional expressions ("Wow!"), proverbs, etc. These can also include nominal sentences like "The more, the merrier". These mostly omit a main verb for the sake of conciseness, but may also do so in order to intensify the meaning around the nouns. The final, italicised part of the quote should answer your second question of the purpose of these sentences. A: "Computer grammar checkers often highlight incomplete sentences. If the context is clear from the rest of the paragraph, however, an incomplete sentence may be considered perfectly acceptable English." https://en.wikipedia.org/wiki/Sentence_clause_structure#Incomplete_sentence These are good examples of when the meaning is clear despite the lack of a verb. They work because they are terse and concise; the addition of a verb would make them less so. A: Everyone else has adequately explained what is going on and why and how this structure is used, but have gotten the name wrong. These are called Nominal Sentences: Nominal sentence is a linguistic term that refers to a nonverbal sentence (i.e. a sentence without a finite verb). As a nominal sentence does not have a verbal predicate, it may contain a nominal predicate, an adjectival predicate, an adverbial predicate or even a prepositional predicate. (Wikipedia) The examples are in line with the ones in other answers: Nominal sentences in English are relatively uncommon, but may be found in non-finite embedded clauses such as the one in, "I consider John intelligent," where to be is omitted from John to be intelligent. They can also be found in newspaper headlines, such as "Jones Winner" where the intended meaning is with the copular verb, "Jones is the Winner". Other examples are proverbs ("More haste, less speed"); requests ("Scalpel!"); and statements of existence ("Fire in the hole!"), which are often warnings. A sentence such as "What a great day today!" is for example considered nominal because it doesn't have a verb. (Wikipedia)
{ "pile_set_name": "StackExchange" }
Q: Prove that $G$ is $k$-edge-connected. Let $G$ be an $n$-vertex graph with minimum degree $k$ that contains at least $\binom{n-k-1}{2}+\binom{k+1}{2}+k$ edges. Prove that $G$ is $k$-edge-connected. I had already proved that; A disconnected graph on $n$ vertices with no components of size less than $k$ has at most $\binom{n-k}{2}+\binom{k}{2}$ edges. Can I use this result replacing $k$ by $k+1$ ? A: Suppose $G$ is not $k$-edge connected, then suppose the minimum number of edges required to disconnect $G$ be $m$, of course, $m<k$, so after removing $m$ edges from $G$, the graph becomes disconnected. Let this disconnected graph be $H$. Also now the disconnected graph $H$ has $\binom{n-k-1}{2}+\binom{k+1}{2}+(k-m)$ edges, hence by the result you proved it must contain a component $M$ of size less than $(k+1)$, say it's size is $p$, where $1\leq p\leq k$. Hence degree of each vertex in that component $M$ of $H$ is at most $p-1$, whereas the degree of each vertex of $M$ in the original graph $G$ was at least $k$. Note that if there was an edge $e$ between any two vertices $u$, $v$ of $M$ in the original graph $G$, that edge was not removed to get $H$, as the graph $M$ is connected, removing that edge $e$ would not help to disconnect $G$, In other words if $e$ does not belong to the edge set of $H$, then if we add $e$ to $H$, the new graph would still be disconnected, hence contradicting the minimality of $m$. Hence at least $(k-(p-1))\times p$ edges has been removed from the orginal graph $G$. Now $[(k-(p-1))\times p]-k=kp-k-p^2+p=(k-p)(p-1) \geq 0$. Hence $(k-(p-1))\times p\geq k$. But we know we have removed $m$ edges from the original graph $G$ to obtain $H$ and $m<k$, hence a contradiction. So we have proved that $G$ is $k$-edge connected.
{ "pile_set_name": "StackExchange" }
Q: Создание HashMap в методе Подскажите пожалуйста, как применить метод createMap() в main. Пробовал различные варианты, но никак не могу создать HashMap через метод. Ошибка при применении метода createMap() "HashMap m = createMap();" public class Solution { public static HashMap<String, Date> createMap() throws ParseException { DateFormat df = new SimpleDateFormat("MMMMM d yyyy", Locale.ENGLISH); HashMap<String, Date> map = new HashMap<String, Date>(); map.put("Stallone", df.parse("JUNE 1 1980")); map.put("Stallone1", df.parse("JUNE 1 1980")); map.put("Stallone2", df.parse("JULE 1 1980")); map.put("Stallone3", df.parse("AUGUST 1 1980")); map.put("Stallone4", df.parse("SEPTEMBER 1 1980")); map.put("Stallone5", df.parse("OCTOBER 1 1980")); map.put("Stallone6", df.parse("NOVEMBER 1 1980")); map.put("Stallone7", df.parse("DECEMBER 1 1980")); map.put("Stallone8", df.parse("JANUARY 1 1980")); map.put("Stallone9", df.parse("FEBRUARY 1 1980")); return map; } public static void removeAllSummerPeople(HashMap<String, Date> map) { } public static void main(String[] args) { HashMap<String,Date> m = createMap(); } } A: Уверен, проблема не при запуске, а при компиляции, т.к. createMap может выбросить исключение, а автор его не ловит (и в его main не указано что то исключение может быть выброшено): public static void main(String[] args) { try { HashMap<String, Date> m = createMap(); System.out.println(m); } catch (Exception e) { e.printStackTrace(); } } PS. После этой правки код скомпилируется, но будет исключение, т.к. формат даты не совпадает с тем, что парсится: java.text.ParseException: Unparseable date: "JULE 1 1980" at java.text.DateFormat.parse(DateFormat.java:366) т.к. название месяца неправильно написано, должно быть JULY
{ "pile_set_name": "StackExchange" }
Q: Combine Philips Hue, HomeKit and Music (iTunes or Spotify) First time using HomeKit here. I have Philips Hue and using Siri (HomeKit) I activate different scenes/ambients with my voice, which is really cool. I'd like to go one step further... In WWDC I see that regarding HomeKit we can use termostats, fans, lights, doors, curtains, swithches, alarms, sensors... But I see a key element to create ambient is missing: Music. I know using Hue it is possible to create ambients, like a beach sunset, using red and orange colors for lights, but at the same time I would like to play a specific playlist, for example sea or waves sounds, or just hawaiian music. The possibilities could be endless and super cool. What do I have to do? Do I have to create my own app that uses HomeKit and Spotify API or Apple Music API? My idea is to start the ambient using Siri (that is, lights and music), but I don't know if what I want is technically possible. Any suggestion? That would be awesome. A: You can pretty easily do this with AppleScript (if you use a Macintosh, that is...) Here's some sample AppleScript code you could start with. (Paste this code into a Script Editor window.) -- define baseUrl to point to your Hue hub address and one of the keys in your whitelist set baseUrl to " http://YOUR-HUB-IP/api/YOUR-WHITELIST-ENTRY" -- read the info about light 1 set lightJson to do shell script "curl " & baseUrl & "/lights/1" -- define some JSON to set a light state set lightStateOn to the quoted form of " {\"on\": true,\"bri\": 254,\"hue\": 8000,\"sat\": 254} " -- send the JSON to set a light state (on and with specified hue, saturation, and brightness) do shell script "curl --request PUT --data " & lightStateOn & baseUrl & "/lights/1/state/" tell application "Spotify" play track "spotify:track:3AhXZa8sUQht0UEdBJgpGc" end tell set lightStateOff to the quoted form of "{\"on\": false}" do shell script "curl --request PUT --data " & lightStateOff & baseUrl & "/lights/1/state/" Edit the baseUrl to include the real IP of your hub and one of the keys in the whitelist (users) from your hub's JSON file. Then script the curl command to get or send JSON to the hub, which changes your lights. Finally, both Spotify and iTunes are scriptable, so you can tell them to play songs, playlists, etc. See http://dougscripts.com/ to learn more about scripting iTunes. You can do this in other languages and platforms also, depending on what your hardware and skill are. The syntax will be different, but the strategy will be similar: send the commands to control the hue hub and then send other commands to control the music player.
{ "pile_set_name": "StackExchange" }
Q: Are subtitles supported in any of the native video controls? I'm writing an application with some embedded video content, it's Android 2.2 that I'm targetting. I need to show localized subtitles for the video content. The video content can be mp4 or 3gp video, played from the SD card. There are some third party video players out there that already support subtitles, but I haven't seen any open source ones I can bundle, or examine the code for. So, are there any subtitle enabled controls or are there any open source video player projects which include subtitles? What options are there for this scenario? A: This should solve the problem. Something I came across on xda-devs http://forum.xda-developers.com/showthread.php?t=890761 Mplayer was recently ported to Android. The source for MPlayer is here http://www.mplayerhq.hu/design7/dload.html Best of luck!
{ "pile_set_name": "StackExchange" }
Q: Inserting an object having a non copyable field into an std::vector I understand that the following code does not compile since the move constructor of A is deleted because the mutex is not movable. class A { public: A(int i) {} private: std::mutex m; }; int main() { std::vector<A> v; v.emplace_back(2); } But if I want my A to be stored in an std container how should I go about this? I am fine with A being constructed "inside" the container. A: std::vector::emplace_back may need to grow a vector's capacity. Since all elements of a vector are contiguous, this means moving all existing elements to the new allocated storage. So the code implementing emplace_back needs to call the move constructor in general (even though for your case with an empty vector it would call it zero times). You wouldn't get this error if you used, say, std::list<A>.
{ "pile_set_name": "StackExchange" }
Q: Find global minimum of the following The global minimum value of $$|\cot x – 1| + |\cot x – 2| + |\cot x – 31| + |\cot x – 32| + |\cot x – 24| + |\cot x – 5| + |\cot x – 6| + |\cot x – 17| + |\cot x – 8| + |\cot x – 9| + |\cot x – 10| + |\cot x – 11| + |\cot x – 12| $$ Then find $x=\operatorname{arcsec}(\alpha/\beta )$ where it is occurring. A: The minimum is achieved when $\cot x$ is the median of the constants, i.e. $10$. If $\cot x=10$ then $\sec x=\dfrac{\sqrt{101}}{10}$, which is not a rational number.
{ "pile_set_name": "StackExchange" }
Q: Can I install both Ubuntu-Server and Desktop on my computer Can I install both of them on my machine or is there any problem with that? And if it is possible can you tell me how, please? A: Ubuntu Server and Desktop are two different installers for the same operating system. The difference is in the packages they install by default: Ubuntu Desktop installs a desktop environment by default, and Ubuntu Server doesn't. Once you have installed Ubuntu the distinction between Desktop and Server does not remain, just the selection of packages that have been installed. You can install the same packages regardless of which installer you used initially. If you want to be able to use your Ubuntu installation as a server but have a desktop environment as well, you can just use the Ubuntu Desktop installer. Or, having installed Ubuntu without a desktop environment you can add one by installing the ubuntu-desktop package.
{ "pile_set_name": "StackExchange" }
Q: How to reboot a virtual machine using Softlayer Python API I cannot find where using SoftLayer Python API VSManager to reboot or power-off/on a virtual machine instance. The operations are described in the XMLRPC API at: http://developer.softlayer.com/reference/services/SoftLayer_Virtual_Guest but I can't find equivalent at: http://softlayer-python.readthedocs.org/en/latest/api/managers/vs.html A: Indeed the manager does not have that implementation you have to make api calls for that here some examples: """ Power off Guest The scripts will look for a VSI which has an specific hostname and the it powers off the VSI by making a single call to the SoftLayer_Virtual_Guest::powerOff method. Important manual pages: http://sldn.softlayer.com/reference/services/SoftLayer_Acount/ http://sldn.softlayer.com/reference/services/SoftLayer_Acount/getVirtualGuests http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/setTags License: http://sldn.softlayer.com/article/License Author: SoftLayer Technologies, Inc. <[email protected]> """ import SoftLayer """ # Your SoftLayer API username and key. # # Generate an API key at the SoftLayer Customer Portal: # https://manage.softlayer.com/Administrative/apiKeychain """ username = 'set me' key = 'set me' # The name of the machine you wish to power off virtualGuestName = 'rctest' # Declare a new API service object client = SoftLayer.Client(username=username, api_key=key) try: # Getting all virtual guest that the account has: virtualGuests = client['SoftLayer_Account'].getVirtualGuests() except SoftLayer.SoftLayerAPIError as e: """ If there was an error returned from the SoftLayer API then bomb out with the error message. """ print("Unable to retrieve hardware. " % (e.faultCode, e.faultString)) # Looking for the virtual guest virtualGuestId = '' for virtualGuest in virtualGuests: if virtualGuest['hostname'] == virtualGuestName: virtualGuestId = virtualGuest['id'] try: # Power off the virtual guest virtualMachines = client['SoftLayer_Virtual_Guest'].powerOff(id=virtualGuestId) print ("powered off") except SoftLayer.SoftLayerAPIError as e: """ If there was an error returned from the SoftLayer API then bomb out with the error message. """ print("Unable to power off the virtual guest" % (e.faultCode, e.faultString)) -- """ Reboot Virtual Guest. It reboots a SoftLayer Virtual Guest Important manual pages: http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/rebootDefault License: http://sldn.softlayer.com/article/License Author: SoftLayer Technologies, Inc. <[email protected]> """ # So we can talk to the SoftLayer API: import SoftLayer # From pprint import pprint as pp # For nice debug output from pprint import pprint as pp # Your SoftLayer API username and key. API_USERNAME = 'set me' API_KEY = 'set me' # If you don't know your server id you can call getVirtualGuests() in the # SoftLayer_Account API service to get a list of Virtual Guests serverId = 10403817 # Create a connection to API service. client = SoftLayer.Client( username=API_USERNAME, api_key=API_KEY ) # Reboot the Virtual Guest try: result = client['Virtual_Guest'].rebootDefault(id=serverId) pp(result) except SoftLayer.SoftLayerAPIError as e: pp('Unable to reboot the server faultCode=%s, faultString=%s' % (e.faultCode, e.faultString)) Regards
{ "pile_set_name": "StackExchange" }
Q: Powershell folder creation from variables Here's what I have working so far: $extensions = '*.xls*', '*.doc*', '*.txt', '*.pdf', '*.jpg', '*.lnk', '*.pub', '*.pst', '*.pps', '*.ppt' Get-Content C:\computers.txt | % { $ComputerName = $_ $dst = "\\Server\share\$ComputerName" $src = "\\$ComputerName\c$\Documents and Settings\**\Desktop", "\\$ComputerName\c$\Documents and Settings\**\My Documents" New-Item -ItemType Directory $dst Get-Childitem $src -Include $extensions -Recurse -Force | Copy-Item -Destination $dst\ } My goal is to back up specific file types from a list of machines. These machines have approx 10-20 profiles on them. Would it be possible to arrange these files in a directory under the computer name directory from the profile they came from? Such as creating a profile name directory under the created computer name directory then dump the targeted files in their appropriate folder. Example: \\server\share\computername1\profile1\document.doc \\server\share\computername2\Profile2\document.doc A: You can't use wildcards in your source paths if you want to use part of the path (well, technically you can, but it'd be a pain in the rear). Use an inner loop instead: $extensions = '*.xls*', '*.doc*', ... Get-Content C:\computers.txt | % { $ComputerName = $_ Get-ChildItem "\\$ComputerName\c$\Documents and Settings" | ? { $_.PSIsContainer } | % { $dst = Join-Path "\\Server\share\$ComputerName" $_.Name New-Item -ItemType Directory $dst # no need to create $dst first, b/c New-Item will auto-create missing # parent folders $src = (Join-Path $_.FullName 'Desktop'), (Join-Path $_.FullName 'My Documents') Get-Childitem $src -Include $extensions -Recurse -Force | Copy-Item -Destination $dst\ } }
{ "pile_set_name": "StackExchange" }
Q: Template function specialization for template class Is it possible to write something like this in C++11/14? #include <iostream> #include <vector> template <typename T> T Get(); template <typename T> struct Data { std::vector<T> data; }; template <> template <typename T> Data<T> Get<Data<T>>() { return Data<T>{{T{}, T{}}}; } template <> template <typename T> std::vector<T> Get<std::vector<T>>() { return std::vector<T>(3); } int main() { std::cout << Get<Data<int>>().data.size() << std::endl; // expected output is 2 std::cout << Get<std::vector<int>>().size() << std::endl; // expected output is 3 return 0; } Overloading won't help in this case, since call to Get<...>() will be ambiguious (see): template <typename T> Data<T> Get() { return Data<T>{{T{}, T{}}}; } template <typename T> std::vector<T> Get() { return std::vector<T>(3); } Any direction on how to overcome this are welcome. A: There is workaround, that gives you something like this: do not specialize - overload: #include <iostream> #include <vector> #include <string> using namespace std; template <typename T> size_t Get(const T& data) { return 444; } template <typename T> struct Data { std::vector<T> data; }; template <typename T> size_t Get(const Data<T>& data) { return data.data.size(); } int main() { std::cout << Get<>(0) << std::endl; // expected output is 444 std::cout << Get<>(Data<int>{}) << std::endl; // expected output is 0 return 0; } Output: 444 0 Note, that size_t Get(const Data<T>& data) is not a specialization - it is completely "different" Get(), that is called for argument of type Data<T> for any T. Here you can see working sample. EDIT I see you changed your question completely. However, I will still try to answer it. There is a standard workaround for lack of partial function specialization - using delegation to structs/classes. Here is what you need: #include <iostream> #include <vector> using namespace std; template <typename T> struct GetImpl; template <typename T> struct Data { std::vector<T> data; }; template <typename T> struct GetImpl< Data<T> > { static Data<T> Get() { return Data<T>{ {T{}, T{}} }; }; }; template <typename T> struct GetImpl< std::vector<T> > { static std::vector<T> Get() { return std::vector<T>(3); }; }; int main() { std::cout << GetImpl< Data<int> >::Get().data.size() << std::endl; // expected output is 2 std::cout << GetImpl< std::vector<int> >::Get().size() << std::endl; // expected output is 3 return 0; } Output: 2 3 Working sample can be found here. If you don't like the syntax, you can make it a little bit shorter, by changing static function Get() to function call operator: template <typename T> struct Get< Data<T> > { Data<T> operator()() { return Data<T>{ {T{}, T{}} }; }; }; template <typename T> struct Get< std::vector<T> > { std::vector<T> operator()() { return std::vector<T>(3); }; }; And then: Get< Data<int> >()().data.size(); Get< std::vector<int> >()().size(); You have only two extra characters - (). This is the shortest solution I can think of. A: As Columbo mentioned in his comment, you should apply the standard workaround for lack of partial specialization support for functions: delegation to a partially specialized class: template <typename T> struct GetImpl; template <typename T> T Get() { return GetImpl<T>::Do(); } and now use partial specialization on struct GetImpl<T> { static T Do(); } instead of Get<T>() A: But it would be impossible for compiler to distinguish Get<Data<int>> from Get<Data<Data<int>>>. It's not impossible. If that's something you need to do, we can add separate overloads: template <typename T> size_t Get(const Data<T>& data); template <typename T> size_t Get(const Data<Data<T>>& data); // preferred for Data<Data<int>> Or if what you want is to only overload for the non-nested case, we can add a type trait and use SFINAE: template <typename T> struct is_data : std::false_type { }; template <typename T> struct is_data<Data<T>> : std::true_type { }; template <typename T> enable_if_t<!is_data<T>::value, size_t> Get(const Data<T>& data); That way, the call with Data<Data<int>> would call the generic Get(const T&). Or, if you want that case to not compile at all: template <typename T> size_t Get(const Data<T>& data) { static_assert(!is_data<T>::value, "disallowed"); ... } So overloading gives you lots of options. Specialization gives you none, since it's disallowed anyway.
{ "pile_set_name": "StackExchange" }
Q: why does bss segment contain initial 4 bytes when no uninitialised global or static variable is there in code I have this simple code. #include<stdio.h> int main() { return 0; } running the size command on the executable show the following output text data bss dec hex filename 1053 276 4 1333 535 a.out My question is , even though i don't have any unintialised global or static variable, why does bss has 4 bytes? A: You link your code against the standard C library. Specifically, you link against code that runs before main() starts and again after main() returns. That code has data and bss requirements. If you want to avoid those requirements, you can try linking without the standard library: $ gcc -nostartfiles -nostdlib -nodefaultlibs x.c $ size a.out text data bss dec hex filename 118 0 0 118 76 a.out Of course, then you'll need to make other (significant!) changes to your program: $ cat x.c void _start() { __asm("mov $1, %eax; mov %eax,%ebx; int $0x80"); } References: http://www.muppetlabs.com/~breadbox/software/tiny/teensy.html http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html#Link-Options
{ "pile_set_name": "StackExchange" }
Q: Estrutura banco de dados contestação de notas Tenho um sistema de atribuição de notas onde é permitido contestação, réplica e/ou tréplica, qual a melhor forma de armazenar no banco de dados? Criar três tabelas (contestacao, replica, treplica) Criar uma tabela com os 3 campos Criar uma tabela com o campo tipo A: Depende do que você quer. Criar três tabelas (contestacao, replica, treplica) Isto permite que sejam inseridas várias contestações, réplicas e tréplicas para cada nota (o que acredito que não é seu objetivo). O controle pelo sistema é maior, visto que são 3 tabelas, e se for o caso de trazer os registros em uma única consulta, pode forçar o sistema a fazer uso de unions, o que não é bom para o desempenho. Ótimo para os casos em que interessar acessar apenas uma tabela de cada tipo de cada vez. Criar uma tabela com os 3 campos Para o escopo de negócio, creio que seja o mais adequado, considerando que cada nota pode ter apenas uma contestação, uma réplica e uma tréplica. É também o mais simples de obter e de atualizar, mas não serve para múltiplos registros de contestações, réplicas e tréplicas. Criar uma tabela com o campo tipo Este caso é interessante quando se deseja economizar em número de consultas e minimizar a quantidade de joins usadas pelo sistema. Também é para o caso de o seu sistema permitir uma quantidade variável de contestações, réplicas e tréplicas. Pode ser necessário adicionar um índice por tipo, o que torna a tabela maior no banco de dados.
{ "pile_set_name": "StackExchange" }
Q: Do we need propTypes with TypeScript? My new react-native project which is setup now uses typescript. So, is it required to use propTypes for type validations since TS already solves this problem? For me, I think use of propTypes will not add any value with since TS handles the type casting issues. Is it correct or should I use propTypes? If so, what are the advantages? A: propTypes is just Reacts form of typechecking, if you are already using a static type-checking library like TypeScript then no, you won't need to use propType validation. React make it clear in their documentation that propTypes are an option to those who aren't already using a form of type-checking: As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like Flow or TypeScript to typecheck your whole application. But even if you don’t use those, React has some built-in typechecking abilities.
{ "pile_set_name": "StackExchange" }
Q: Bernoulli differential equation proving As we know, the differential equation in the form is called the Bernoulli equation $ \frac {dy}{dx} + p(x)y = q(x)y^n $ How do i show that if $y$ is the solution of the above Bernoulli equation and $ u = y^{1-n} $, then u satisfies the linear differential equation $ \frac{du}{dx} +(1-n)p(x)u = (1-n)q(x) $ I can use the substituion to use solve differential equations like $y' + xy = xy^2$ but have no idea how to prove this question . Can someone please help? Thanks in advance A: Hint. One may observe that from $u=y^{1-n}$, by the chain rule, we get $$ \frac{du}{dx}=(1-n)\cdot\frac{dy}{dx}\cdot y^{-n}\qquad \text{or} \qquad \frac{dy}{dx}=\frac1{(1-n)}\cdot y^{n}\cdot\frac{du}{dx} $$ then plugging it into $$ \frac {dy}{dx} + p(x)y = q(x)y^n $$ using $y=y^n u$ gives $$ \frac1{(1-n)}\cdot y^{n}\cdot\frac{du}{dx}+p(x)\cdot y^n u= q(x)y^n $$ or equivalently $$ \frac{du}{dx} +(1-n)p(x)u = (1-n)q(x) $$ as desired.
{ "pile_set_name": "StackExchange" }
Q: Confusing overload resolution failure regarding number of type arguments In C#, I can write: Enumerable.Range(1, 20).Select(i => i) And I can also specify the two type parameters to Select explicitly: Enumerable.Range(1, 20).Select<int, int>(i => i) In VB, the equivalent of the first snippet works fine: Enumerable.Range(1, 20).Select(Function(i) i) But when I try to specify the type parameters, it fails: Enumerable.Range(1, 20).Select(Of Integer, Integer)(Function(i) i) The error I'm getting is: BC32087 Overload resolution failed because no accessible '[Select]' accepts this number of type arguments. I don't understand: there is an overload of extension method named Select with two type parameters. What am I doing wrong? A: Give this a try : Enumerable.Range(1, 20).Select(Of Integer)(Function(i) i) The reason that your previous example wasn't working was because the overload that you referenced was actually an extension method for Enumerable objects and thus the first parameter is actually the object that is triggering the call. You can see an example of this being used here and working as expected.
{ "pile_set_name": "StackExchange" }
Q: Outlets are nil? I've created (and linked) some outlets to labels in my storyboard, and when I attempt to modify the text, my application throws an exception and freezes, because they are apparently nil. Code: import UIKit class QuoteView : UITableViewController { @IBOutlet var quoteCategory: UILabel! @IBOutlet var quoteTitle: UILabel! @IBOutlet var quoteAuthor: UILabel! @IBOutlet var quoteContent: UILabel! @IBOutlet var quoteTimestamp: UILabel! } I'm attempting to set them in the prepareForSegue method of previous view controller, like so: overide func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "indivQuoteSegue") { let svc = segue.destinationViewController as! QuoteView let quote = quoteArray[(tableView.indexPathForSelectedRow?.row)!]; svc.quoteTitle.text = quote.getQuoteTitle() svc.quoteAuthor.text = quote.getQuoteAuthor() svc.quoteContent.text = quote.getQuoteContent() svc.quoteCategory.text = quote.getCategory() svc.quoteTimestamp.text = quote.getQuoteTimestamp() } } A: In prepareForSegue you outlets have not been initialized yet, so you can not set properties of them. You should create String properties and set those instead, or better yet just pass your quote object. For example: overide func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "indivQuoteSegue") { let svc = segue.destinationViewController as! QuoteView let quote = quoteArray[(tableView.indexPathForSelectedRow?.row)!]; svc.quoteTitleString = quote.getQuoteTitle() svc.quoteAuthorString = quote.getQuoteAuthor() svc.quoteContentString = quote.getQuoteContent() svc.quoteCategoryString = quote.getCategory() svc.quoteTimestampString = quote.getQuoteTimestamp() } } Then in the viewDidLoad of QuoteView set your labels' text override func viewDidLoad(){ self.quoteTitle.text = self.quoteTitleString etc... } A: Stepping back a little from the "why it doesn't work" question about trying to set a view controller's outlets from outside the view controller, I give you a flat rule: "Don't do that." You should treat another view controllers outlets as private and not try to manipulate them. That violates the principle of encapsulation, and important idea in OO design. Imagine this: I have a control panel object for a piece of stereo equipment. The control panel has a bunch of control UI objects on it that let the user set equalization, noise reduction, etc. Then it has a public API that it uses to interface with the other software components of the system. If other other objects reach into my control panel and do things like change the value of the equalization sliders, then I can't go back later and replace the UI elements for equalizers to use dials, or numeric inputs, or some other UI element, without breaking the rest of the app. I have tightly coupled other objects in my program to things that should be part of the private implementation of my control panel object. In your case, it flat doesn't work because in prepareForSegue the destination view controller's views haven't yet been loaded. Even in cases where it would work, you still should not do that. Instead, you should create public properties of your view controller that let an outside object specify values for settings. Then the view controller's viewWillAppear method should apply the values in those properties to the UI. When you do it that way, if you later make changes to the UI, all you have to do is to make sure the public properties still work as expected. @beyowulf and @harshitgupta gave detailed examples of how to do it the right way. (Although I would argue that the code to install the properties into the UI should in viewWillAppear, not viewDidLoad. That way, in cases where a view controller is shown, covered by another view controller that changes its values, then uncovered, it updates the changed values on-screen when it gets shown again.)
{ "pile_set_name": "StackExchange" }
Q: non-finite finite-difference value, many data become inf and NA after exponential I'm going to find the parameters for a rank-logit model. But the error always shows that there are non-finite finite-difference value. If I change the "b0<-rep(0,5)" to "b0<-rep(-1,5)", the number after non-finite finite-difference value changes from 2 to 1. If you need the dataset, I will send it to you by email. cjll <- function(b){ U <- X%*%b lSU <- csm%*%exp(U) lSU <- (lSU!=0)*lSU+(lSU==0) LL <- sum(Ccsm%*%U-log(lSU)) return(LL) } b0 <- rep(0,5) res <- optim(b0,cjll,method="BFGS",hessian=TRUE,control=list(fnscale=-1)) #Error in optim(b0, cjll, method = "BFGS", hessian = TRUE, control = list(fnscale = -1)) : # non-finite finite-difference value [2] b <- res$par #Error: object 'res' not found A: BFGS requires the gradient of the function being minimized. If you don't pass one it will try to use finite-differences to estimate it. Looking at your likelihood function, it could be that the fact that you "split" it by elements equal to 0 and not equal to 0 creates a discontinuity that prevents the numerical gradient from being properly formed. Try using method = "Nelder-Mead" and setting Hessian to FALSE and see if that works. If it does, you can then use the numDeriv package to estimate the gradient and Hessian at the point of convergence if you need them.
{ "pile_set_name": "StackExchange" }
Q: Constructors and destructor must be virtual? Exists some differences between a constructor or destructor be virtual or not? In this case, what should be done class A { public: A(); ~A(); } or class A { public: virtual A(); virtual ~A(); } Have isocpp fot this case? Thanks... A: You cannot have Virtual constructor in C++ why no virtual Constructor. Virtual destructors are useful when you can delete an instance of a derived class through a pointer to base class. Refer to When to use Virtual Destructor.
{ "pile_set_name": "StackExchange" }
Q: ¿Cuándo debo marcar una publicación como "Muy baja calidad" (MBC)? Entre las opciones para reportar una publicación se encuentra "Muy baja calidad" (MBC de aquí en adelante). ¿Cuándo debo utilizar ese tipo de reporte? Esta pregunta viene motivada por el hecho de que, en general, considero que se está abusando de los reportes MBC en el sitio (son de lejos los reportes que mas se reciben). Con ella espero clarificar que se considera "muy baja calidad" y, posiblemente, reducir algo este tipo de reportes A: El reporte de una publicación como MBC debe reservarse exclusivamente a publicaciones que no tienen ningún sentido, y que no pueden salvarse de ninguna manera mediante su edición. Una publicación que sólo contiene código es una publicación de baja calidad, pero no de muy baja calidad, por ejemplo. Cuando un usuario reporta una publicación como MBC, lo que está pidiendo es su inmediata eliminación, bien por los usuarios con privilegios de moderación en esa cola, bien por los moderadores. Si la publicación se puede salvar mediante su edición, no debería reportarse como MBC. En general, si hablamos de respuestas, debe usarse solo en casos de repuestas que no tengan absolutamente ningún sentido, o tal vez si la respuesta es simplemente un enlace sin ningún contenido más (incluso en esos casos, yo preferiría un comentario al autor pidiendo que agregara las partes relevantes del enlace en su respuesta para salvar la publicación). No debe usarse para respuestas incorrectas, cortas, o que solo responden parcialmente a la pregunta planteada. Esta respuesta esta basada en las respuestas de esta pregunta de meta en Stack Overflow y en mis propias opiniones. Está abierta a discusión y a edición para mejorarla o ampliarla A: ¿Qué pasa cuando un usuario levanta un reporte MBC? El reporte aparece en la cola de reportes de los moderadores diamantados. Este es el único efecto que es seguro que tenga un reporte MBC. Sin embargo, hay un pequeño retraso (no he encontrado el tiempo exacto en caso de Stack Overflow en español, pero creo que es de 1 hora) antes de que los moderadores la veamos, para permitir que sea la propia comunidad la que se encargue del tema. Si una publicación nunca ha estado en la cola de MBC, levantar el reporte la colocará en dicha cola. Si la publicación ya tuvo un reporte previo del mismo tipo que fue resuelto descartándolo, volver a reportar por la misma razón no lo llevará a la cola MBC, pero sí que aparecerá en la cola de moderadores para que podamos hacernos cargo de ella.
{ "pile_set_name": "StackExchange" }
Q: Angularjs $location is not triggered the first time and uses old values the next time I use angular-ui slider to select a desired range: HTML <div ng-init="sizeRange.val = [10, 80]"> <div ui-slider="sizeRange.options" min="10" max="80" step="5" ng-model="sizeRange.val"></div> <input type="number" ng-model="sizeRange.val[0]"> <input type="number" ng-model="sizeRange.val[1]"> </div> When user moves the slider to the desired number and stops, the following function is triggered that appends the selected range to URL query string: app.controller('MainCtrl', ['$scope', '$location', function ($scope, $location) { $scope.sizeRange= { 'options': { range: true, stop: function (event, ui) { $scope.filterUpdate($scope.sizeRange.val); } } }; $scope.filterUpdate = function (size) { console.log(size); $location.search({"sizeRange": size}); }; } So when I move the slider the first time, the $location.search() is not triggered and no URL string is appended, however the function itself seems to be called successfully, because I can see the log and correct selected values in my console called from within the function. When I move the slider the second time, the URL string is now appended, but it contains old data from the first time I moved the slider. So every time I move it, the $location.search() updates URL string with data from previous move. What can be interfering with the $location.search() to prevent it to work correctly? A: $location.search() or $location.url() functions don't always trigger on the current $digest cycle. You can either do - $timeout(function() { $location.search({"sizeRange": size}); }); Another thread talking about the same problem - $location.search is not updated imediatly
{ "pile_set_name": "StackExchange" }
Q: R - adding values for one column based on a function using another column I have a dataset that looks like this head(dataset) Distance Lag time Kurtosis 7.406100 10 144.1700 1 77.31800 1 81.15400 1 4.249167 6 I want to add values to the kurtosis column. To calculate kurtosis I need to group the Distances by Lag time (i.e., all distances for Lag time 1 will give me one value for kurtosis etc.). To get kurtosis I usually use the package "psych" and function describe() Is there a kind of loop I could add to do this? A: Since describe produces a dataframe as output and what you want is just one column (also named kurtosis) you'll need to subset the describe output library(dplyr) library(psych) df %>% group_by(Lag_Time) %>% mutate(Kurtosis = describe(Distance)[1,"kurtosis"]) Distance Lag_Time Kurtosis <dbl> <dbl> <dbl> 1 7.41 10 NA 2 144. 1 -2.33 3 77.3 1 -2.33 4 81.2 1 -2.33 5 4.25 6 NA
{ "pile_set_name": "StackExchange" }
Q: Dividing by $\sqrt n$ Why is the following equality true? I know I should divide by $\sqrt n$ but how is it done exactly to get the RHS? $$ \frac{\sqrt n}{\sqrt{n + \sqrt{n + \sqrt n}}} = \frac{1}{\sqrt{1 + \sqrt{\frac{1}{n} + \sqrt{\frac{1}{n^3}}}}}$$ A: Alternate form: $$\frac{\frac{\sqrt{n}}{ \sqrt{n}}}{\frac{\sqrt{n+\sqrt{n+\sqrt{n}}}}{\sqrt{n}}}=\frac{1}{\sqrt{\frac{n+\sqrt{n+\sqrt{n}}}{n}}}=\frac{1}{\sqrt{1+ \frac{\sqrt{n+\sqrt{n}}}{n}}}=\frac{1}{\sqrt{1+ \frac{\sqrt{n+\sqrt{n}}}{\sqrt{n} \sqrt{n}}}}=\frac{1}{\sqrt{1+ \frac{1}{\sqrt{n}} \frac{\sqrt{n+\sqrt{n}}}{ \sqrt{n}}}}=\frac{1}{\sqrt{1+\frac{1}{\sqrt{n}} \sqrt{\frac{n+\sqrt{n}}{n}}}}=\frac{1}{\sqrt{1+\frac{1}{\sqrt{n}} \sqrt{1+\frac{1}{\sqrt{n}}}}} $$ A: Suppose that $n>0$. $$\frac{\sqrt{n}}{ \sqrt{n+\sqrt{n+\sqrt{n}}} } = \frac{1}{ \frac{1}{\sqrt{n}} \left( \sqrt{n+\sqrt{n+\sqrt{n}}} \right) } = \frac{1}{ \sqrt{1+ \frac{1}{n} \left( \sqrt{n + \sqrt{n}} \right) } } = \frac{1}{\sqrt{1+ \sqrt{ \frac{1}{n} + \frac{1}{n^2} \sqrt{n} } } } = \frac{1}{\sqrt{1+ \sqrt{ \frac{1}{n} + \sqrt{ \frac{1}{n^3}} } } } $$. A: I find this easier to visualize if I write this problem in terms of powers: $$\dfrac{n^{1/2}}{\left[n + \left(n + n^{1/2}\right)^{1/2}\right]^{1/2}}\text{.} $$ Division by $n^{1/2}$ for both the numerator and denominator turns the numerator into $1$ and the denominator into $$\begin{align*} \dfrac{\left[n + \left(n + n^{1/2}\right)^{1/2}\right]^{1/2}}{n^{1/2}} &= \left[\dfrac{n + \left(n + n^{1/2}\right)^{1/2}}{n}\right]^{1/2}\quad \text{ since }\dfrac{a^c}{b^c} = \left(\dfrac{a}{b}\right)^{c} \\ &= \left[\dfrac{n}{n} + \dfrac{\left(n+n^{1/2}\right)^{1/2}}{n}\right]^{1/2} \quad \text{ since }\dfrac{a+b}{c} = \dfrac{a}{c} + \dfrac{b}{c} \\ &= \left[1 + \dfrac{\left(n+n^{1/2}\right)^{1/2}}{n}\right]^{1/2} \\ &= \left[1 + \dfrac{\left(n+n^{1/2}\right)^{1/2}}{\left(n^{2}\right)^{1/2}}\right]^{1/2} \\ &= \left[1 + \left(\dfrac{n+n^{1/2}}{n^{2}}\right)^{1/2}\right]^{1/2} \text{ since }\dfrac{a^c}{b^c} = \left(\dfrac{a}{b}\right)^{c} \\ &= \left[1 + \left(\dfrac{n}{n^2}+\dfrac{n^{1/2}}{n^2}\right)^{1/2}\right]^{1/2} \text{ since }\dfrac{a+b}{c} = \dfrac{a}{c} + \dfrac{b}{c} \\ &= \left[1 + \left(\dfrac{1}{n}+\dfrac{1}{n^{3/2}}\right)^{1/2}\right]^{1/2} \text{ since }\dfrac{a^b}{a^c} = a^{b-c} \\ &= \left\{1 + \left[\dfrac{1}{n}+\dfrac{1^{1/2}}{(n^{3})^{1/2}}\right]^{1/2}\right\}^{1/2} \\ &= \left\{1 + \left[\dfrac{1}{n}+\left(\dfrac{1}{n^3}\right)^{1/2}\right]^{1/2}\right\}^{1/2} \\ &= \sqrt{1+\sqrt{\dfrac{1}{n}+\sqrt{\dfrac{1}{n^3}}}}\text{.} \end{align*}$$
{ "pile_set_name": "StackExchange" }
Q: Python for loop with small steps How can I make an for loop in python with steps of 0.01? I tried this but it doesn't work: for X0 in range (-0.02, 0.02, 0.01): for Y0 in range (-0.06, 0.09, 0.01): it says TypeError: range() integer end argument expected, got float. A: [x * 0.01 for x in xrange(10)] will produce [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09] A: The python range only takes integers as the error message indicates. If you want to use float steps, you can either use numpy's arange or just divide a integer range: >>> import numpy as np >>> print np.arange(-0.02, 0.02, 0.01) array([-0.02, -0.01, 0. , 0.01]) in your example: for X0 in np.arange(-0.02, 0.02, 0.01): for Y0 in np.arange(-0.06, 0.09, 0.01): or: >>> print [a/0.01 - 0.02 for a in range(4)] [-0.02, -0.01, 0.0, 0.009999999999999998] A: If you don't want to use a library: def float_range(a,b,c): while a < b: yield a a += c for X0 in float_range (-0.02, 0.02, 0.01): for Y0 in float_range (-0.06, 0.09, 0.01): print X0, Y0
{ "pile_set_name": "StackExchange" }
Q: Generate topological information from STL file What would be the best way to generate topological information for an object loaded from a STL file (STL stores just 3 vertices for each face). As a result I would like a winged-edge data structure or something similar. A: Main issue is to find all unique point positions, so that triangles can be represent as list of point ids (indices) instead as list of coordinates. To do that some nearest neighbour data structure is used. In this case, I think best are space partition data structures. With that you can get list of unique point positions, and list of triangles that are represented as triple of indices in the list of points. To create winged edge data structure or similar 'connectivity' structure, you have to find all different edges (pairs of points that are in some triangle) and store connectivity data that you need (in which triangles is edge used, for a point in which edges and/or triangles is used, ...)
{ "pile_set_name": "StackExchange" }
Q: points border color and line color is different between legend box and whole plot box when pch=21 ENV MACOSX 10.9.4 R 3.3.1 My problem The border color of point in legend is green4. But the border color of points for whole plot is black. See the figure above, in the plot box there are three points and line color is green4, the point border is black and the points background is red. However, in the legend box which is on topright the line color is green4, the point background is red, the point border color is not black which is green4 same with the line in legend box. If you add col in legend, the point border color in legend box is changed and at the same time the line color in legend box is changed either. MY current code is below: initial.dir<-getwd() setwd("/works/bin") sink("r.o") pk <- read.table("2017.info") rownames(pk)<-c("k","pk") d.f <- data.frame(t(pk)) pdf(file="5000-max.pdf") plot( d.f$k, d.f$pk, type = "n", log = "xy", main = "Degree distribution", xlab = "k", ylab = "p(k)", xlim = c( 10^0, 10^2), ylim = c( 0.00001, 1), xaxt="n", yaxt="n", xaxs="i", yaxs="i", ) lines( d.f$k, d.f$pk, col = "green4", lty = "solid") points( d.f$k, d.f$pk, bg = "red", pch = 21 ) legend("topright", inset=.05, c("p(k)"), lty="solid", pch=21, col=c("green4"), pt.bg="red") axis(side = 1, at = 10^(0:2), labels = expression(10^0, 10^1, 10^2)) axis(side = 2, at = 10^(-5:0), labels = expression(10^-5, 10^-4, 10^-3, 10^-2, 10^-1, 10^0)) abline(h=outer((1:10),(10^(-5:-1))), col="#00000033", lty=2) abline(v=outer((1:10),(10^(0:1))), col="#00000033", lty=2) box() dev.off sink() setwd(initial.dir) What I expected is The line color, points border color, points background color in the plot should be same with the legend. How should I changed my code? Thanks. A: In order to change the color of point borders in the chart, I would change points( d.f$k, d.f$pk, bg = "red", pch = 21 ) to points( d.f$k, d.f$pk, bg = "red", col = "green4",pch = 21 ) To change the color in the legend just change legend("topright", inset=.05, c("p(k)"), lty="solid", pch=21, col=c("green4"), pt.bg="red") To legend("topright", inset=.05, c("p(k)"), lty="solid", pch=21, col=c"black", pt.bg="red")
{ "pile_set_name": "StackExchange" }
Q: Which attacks can be avoided by the use of OFB instead of ECB? For a file encryption program, I was told to use Output Feedback mode (OFB) instead of ECB (Electronic code book) mode. Which attacks can I avoid by this choice? A: OFB is a mode of operation to ensure confidentiality of messages a) longer than the block size of the encryption algorithm, and b) that can be re-broadcast. The motivation for these kinds of modes it to avoid the weaknesses that come from using plain ECB mode. To be precise, the typical attack on ECB mode involves analyzing the ciphertext and looking for repeated blocks. Repeated ciphertext blocks mean repeated plaintext blocks, and knowing about repeated plaintext can help the attacker analyze the captured ciphertext. (Meaning that ECB is not semantically secure.) In some cases, this is enough for the attacker to learn all, or almost all, of the plaintext. OFB mode prevents this from happening by using randomized encryption to ensure that repeated plaintext within the message does not cause repeated ciphertext. OFB is resistant to ciphertext errors in that if the ciphertext has bits modified in error, only the bits of the plaintext that directly correspond to the ciphertext are modified. Because it OFB mode works like a stream cipher, it has the typical weakness that allows known plaintext to be easily modified by an attacker. (Ie, if OFB mode produces a keystream $K$, then the ciphertext $C$ is defined as $C_i := P_i \oplus K_i$, so if $P_i$ is known to the attacker then so is $K_i$, so they can create a new ciphertext $C'_i := P'_i \oplus K_i$ where $P'_i := P_i \oplus X$ and $X$ is a value chosen to produce the desired modified plaintext $P'_i$.) But since message confidentiality (the goal of OFB) does not encompass message integrity, this is not necessarily a big deal. A: Wikipedia has an excellent visual demonstration of the insecurity of ECB mode when applied to (potentially) repetitive data: Here, the first picture on the left shows a simple cartoon image (Tux the Penguin). The second image is the same, but with the (raw, uncompressed RGB) image data encrypted using ECB mode. While details of the image are scrambled, the outline is still clearly visible because identical input blocks (found mainly in the areas with solid color) produce identical output in ECB mode. The third image shows the result of the same encryption process using a different mode that lacks this weakness, such as CBC, CFB, OFB or CTR. Of course, if one used ECB mode to encrypt a compressed image, or some other data that lacks such obvious redundancies, then the patterns in the output would not be so obvious either. Still, many real-world files do contain redundancies — if they didn't, compression programs would be useless — and it's hard to be sure that those cannot be used by an attacker to compromise ECB mode encryption. (To make the other modes secure even if the same key is used for more than one message, one also needs to include a suitable random IV or nonce. Presumably, the IV has been omitted from the example output here to make it match the length of the input.)
{ "pile_set_name": "StackExchange" }
Q: BigQuery creat repeated record field from query Is it possible to create a repeated record column in BigQuery? For example, for the following data: | a | b | c | ------------- | 1 | 5 | 2 | ------------- | 1 | 3 | 1 | ------------- | 2 | 2 | 1 | Is the following possible? Select a, NEST(b, c) as d from *table* group by a To produce the following results | a | d.b | d.c | ----------------- | 1 | 5 | 2 | ----------------- | | 3 | 1 | ----------------- | 2 | 2 | 1 | A: With introduction of BigQuery Standard SQL we've got easy way to deal with records Try below, Don't forget to uncheck Use Legacy SQL checkbox under Show Options WITH YourTable AS ( SELECT 1 AS a, 5 AS b, 2 AS c UNION ALL SELECT 1 AS a, 3 AS b, 1 AS c UNION ALL SELECT 2 AS a, 2 AS b, 1 AS c ) SELECT a, ARRAY_AGG(STRUCT(b, c)) AS d FROM YourTable GROUP BY a A: One of the way to go around NEST() limitation of "nesting" just one field is to use BigQuery User-Defined Functions. They are extremely powerful yet still have some Limits and Limitations to be aware of. And most important from my prospective to have in mind - they are quite a candidates for being qualified as expensive High-Compute queries Complex queries can consume extraordinarily large computing resources relative to the number of bytes processed. Typically, such queries contain a very large number of JOIN or CROSS JOIN clauses or complex User-defined Functions. So, below is example that "mimic" NEST(b, c) from example in questino: SELECT a, d.b, d.c FROM JS(( // input table SELECT a, NEST(CONCAT(STRING(b), ',', STRING(c))) AS d FROM ( SELECT * FROM (SELECT 1 AS a, 5 AS b, 2 AS c), (SELECT 1 AS a, 3 AS b, 1 AS c), (SELECT 2 AS a, 2 AS b, 1 AS c) ) GROUP BY a), a, d, // input columns "[{'name': 'a', 'type': 'INTEGER'}, // output schema {'name': 'd', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [ {'name': 'b', 'type': 'STRING'}, {'name': 'c', 'type': 'STRING'} ] } ]", "function(row, emit){ // function var c = []; for (var i = 0; i < row.d.length; i++) { x = row.d[i].toString().split(','); t = {b:x[0], c:x[1]} c.push(t); }; emit({a: row.a, d: c}); }" ) It is relatively straightforward. I hope you will be able to walk through it and get an idea Still - remember: No matter how you create record with nested/repeated fields - BigQuery automatically flattens query results, so visible results won't contain repeated fields. So you should use it as a subselect that produces intermediate results for immediate use by the same query. As FYI, you can prove for yourself that above returns only two records (not three as it is looks like when it is flattened) by running below query SELECT COUNT(1) AS rows FROM ( <above query here> ) Another important NOTE: This is a known that NEST() is not compatible with UnFlatten Results Output and mostly is used for intermediate result in subquery. In contrast, above solution can be easily saved directly to table (with unchecked Flatten Results)
{ "pile_set_name": "StackExchange" }
Q: Efficiency Curve of Buck Regulator Below is the efficiency curve for the TI TPS53513(datasheet). Can someone explain what causes this characteristic efficiency curve? It seems to be similar to the one for other regulators as well. Why is the curve parabolic with a peak efficiency? Why is there a "discontinuity" in the curve at the low current ratings around 750mA where the curve jumps up and then down? A: The non-monotonic behavior appears in curves that have auto-skip mode enabled, so that's probably the culprit. The efficiency of any SMPS regulator is zero at very low current, because the circuitry takes some power to operate. It also will drop at high currents, as the switch conduction losses and I^2R losses in the inductor increase. At a level in the middle, where the designer has optimized things, you'll get a maximum efficiency. For a given circuit or chip that optimum can be moved around a bit (sometimes a lot, if it's just a controller chip) by using different inductors or different MOSFETs (if that's an option).
{ "pile_set_name": "StackExchange" }
Q: How to add a dimension to a numpy array in Python I have an array that is size (214, 144). I need it to be (214,144,1) is there a way to do this easily in Python? Basically the dimensions are supposed to be (Days, Times, Stations). Since I only have 1 station's data that dimension would be a 1. However if I could also make the code flexible enough work for say 2 stations that would be great (e.g. changing the dimension size from (428,288) to (214,144,2)) that would be great! A: You could use reshape: >>> a = numpy.array([[1,2,3,4,5,6],[7,8,9,10,11,12]]) >>> a.shape (2, 6) >>> a.reshape((2, 6, 1)) array([[[ 1], [ 2], [ 3], [ 4], [ 5], [ 6]], [[ 7], [ 8], [ 9], [10], [11], [12]]]) >>> _.shape (2, 6, 1) Besides changing the shape from (x, y) to (x, y, 1), you could use (x, y/n, n) as well, but you may want to specify the column order depending on the input: >>> a.reshape((2, 3, 2)) array([[[ 1, 2], [ 3, 4], [ 5, 6]], [[ 7, 8], [ 9, 10], [11, 12]]]) >>> a.reshape((2, 3, 2), order='F') array([[[ 1, 4], [ 2, 5], [ 3, 6]], [[ 7, 10], [ 8, 11], [ 9, 12]]])
{ "pile_set_name": "StackExchange" }
Q: Creating a Counter for number of times someone draw a polygon using GPS and Android I created a program in android where the user can select any title he wants using list-view which will show the next subtitle , and a button for GPS where it enables the user to find their location. until now things run smoothly, after doing lots of research about the issue i faced, I couldn't find the answer to begin with, I want the mobile to detect user's location, and starts from this point where the user presses on that button, the user will move in circles or polygon about 9 to 10 times, I want the mobile to tell the user that he has finished the first circle and will start with the next to count how many circles the user did ,depending on the first point. UPDATE: I will provide you with example to specify what I need, lets say I am in point(xx, ll) which is the coordination I got from GPS location founder, now I will move in circle or polygon around the building and start the counter from 0, when I reach the end where I made a circle or polygon, the counter increases by 1, and keep moving like this until I reach counter number 10, how to achieve that in android? Please I want your advice A: It seems that you want to check if the user made a full lap and not just moved forward 50 meters then went back to the same location to count as a lap. To check for laps no matter what is the shape you need check points in that path. The more checkpoints the better confirmation that the user followed the path. The user does not have to exactly pass through the check point he/she has to pass within 10 meters for example. So to actually count laps you need a predefined path with checkpoints and if the user passes through all or most of the points the lap is counted.
{ "pile_set_name": "StackExchange" }
Q: How to display the 3 most common occurrences of an attributed array in Rails I have a movie app that's comprised of the following models: Actor, Movies, Genre. I've created a many-to-many association where actors have and belong to many movies, vice versa. class Actor < ActiveRecord::Base has_many :movies, through: :actor_movies has_many :actor_movies end class ActorMovie < ActiveRecord::Base belongs_to :actor belongs_to :movie end class Movie < ActiveRecord::Base belongs_to :genre has_many :actors, through: :actor_movies has_many :actor_movies end I also made it so that each movie has their own genre: class Genre < ActiveRecord::Base has_many :movies end On the actor's show page I'd like to display the 3 most common genres of movie's they've starred in. This would obviously be based off their movie genres. What I'm trying to figure out is how to put these movies (with their associated genres) in some sort've array and performing an action to produce the prior mentioned result. Controller def show @actor = Actor.find(params[:id] @movies = @actor.movies end So for instance I have an actor that's been in movies with genres ranging from Action, Comedy, Drama, Thriller, Sci-Fi, etc. While doing some research I found the Rubular way to create a hash from arrays using inject from the second answer of this post. Would I do something similar in this rails project? A: How about something like this: class Actor < ActiveRecord::Base # rest of your code has_many :genres, through: :movies def common_genres(limit=3) genres .group("genres.id") .order("count(genres.id) DESC") .limit(limit) end end You can use it like: actor = Actor.first actor.common_genres.each do |genre| p genre.name end With method as provided, you can fetch as many Genres as you need with: actor.common_genres(5) Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: How to write many rows in text file? I write/read file text with C#. My method is: public static void Save(List<DTOSaveFromFile> Items) { File.WriteAllLines(dataPath, (from i in Items select i.Serialize()).ToArray(), Encoding.Default); } This always overrides data and only insert 1 rows. How to insert many rows and don't override before rows. A: Try the File.AppendAllLines method: public static void Save(List<DTOSaveFromFile> Items) { File.AppendAllLines(dataPath, (from i in Items select i.Serialize()).ToArray(), Encoding.Default); } From MSDN: Appends lines to a file, and then closes the file. So, this will prevent the file getting overwritten.
{ "pile_set_name": "StackExchange" }
Q: Python generating all nondecreasing sequences I am having trouble finding a way to do this in a Pythonic way. I assume I can use itertools somehow because I've done something similar before but can't remember what I did. I am trying to generate all non-decreasing lists of length L where each element can take on a value between 1 and N. For example if L=3 and N=3 then [1,1,1],[1,1,2],[1,1,3],[1,2,2],[1,2,3], etc. A: You can do this using itertools.combinations_with_replacement: >>> L, N = 3,3 >>> cc = combinations_with_replacement(range(1, N+1), L) >>> for c in cc: print(c) (1, 1, 1) (1, 1, 2) (1, 1, 3) (1, 2, 2) (1, 2, 3) (1, 3, 3) (2, 2, 2) (2, 2, 3) (2, 3, 3) (3, 3, 3) This works because c_w_r preserves the order of the input, and since we're passing a nondecreasing sequence in, we only get nondecreasing tuples out. (It's easy to convert to lists if you really need those as opposed to tuples.)
{ "pile_set_name": "StackExchange" }
Q: Using trimbox with ImageMagick I have a PDF-file with the following dimensions; mediabox: 23.08 x 31.78 cm cropbox: 23.08 x 31.78 cm trimbox: 21 x 29.7 cm I'm using ImageMagick to try and get the trimbox value using Imagemagick's trimbox function. identify -format "%[fx:(w/72)*2.54]x%[fx:(h/72)*2.54]" -define pdf:use-trimbox=true foo.pdf This line of code gives me 23.08x31.78 cm which is the size of the media/crop-box. If I check the values of these boxes with Adobe Acrobat Reader I get the values I just posted in the top of this very post. Acrobat Reader/Photoshop/In Design tells me that the trimbox is 21x29.7 cm but ImageMagick just doesn't read the same value. My guess is that ImageMagick can't interpret the trimbox correctly and then returns the cropbox values instead. Does anyone know how to get the trimbox value from a correctly formated PDF-file or did anyone have the same problem? Imagemagick states that this function should work, but some of the forums threads beg to differ. A: convert -resize 50% -define pdf:use-cropbox=true 1.pdf 1.jpg
{ "pile_set_name": "StackExchange" }
Q: best way to show some text in textbox in Window application i need to write a list of url in a textbox in a window apps but when i write it he was mixed like http://google.comhttp://google.comhttp://google.comi but i want to show clearly i already used "\n\r" method but he not worked are any sollution for it A: yes First you need to set the multiline property to True and better to use Environment.NewLine to set the new line. Or in stringBuilber.AppedLine("") Hope this will helpo you :)
{ "pile_set_name": "StackExchange" }
Q: On the homomorphism of the Lorentz algebra representation (1/2, 0) I was reading this answer and I don't quite understand how the $\rho$ homomorphism works. The generators of the two copies of $\mathfrak{su}(2)$ in $\mathfrak{su}(2)\oplus\mathfrak{su}(2)$ are given by $N_i^+ = \frac{1}{2}(J_i+\mathrm{i}K_i)$ , $N_i^- = \frac{1}{2}(J_i-\mathrm{i}K_i)$ respectively. The $J_i$'s are the generators corresponding to rotations in $SO^+(1,3)$ and $K_i$'s are the generators corresponding to boosts in $SO^+(1,3)$. This is the excerpt where it is defined. "You are given the $(1/2,0)$ representation $\rho : \mathfrak{su}(2)\oplus\mathfrak{su}(2)\to\mathfrak{gl}(\mathbb{C}^2)$. Since $\rho$, as a representation, is a Lie algebra homomorphism, you know that $\rho(N_i^-) = 0$ implies $\rho(J_i) = \mathrm{i}\rho(K_i)$. Here, all matrices $N_i^-,J_i,K_i,0$ matrices are two-dimensional matrices on $\mathbb{C}^2$. You know that $\rho(N_i^-) = 0$ as two-dimensional matrices because of how the $(s_1,s_2)$ representation is defined: Take the individual representations $\rho^+ : \mathfrak{su}(2)\to\mathfrak{gl}(\mathbb{C}^{2s_1+1})$ and $\rho^- : \mathfrak{su}(2)\to\mathfrak{gl}(\mathbb{C}^{2s_2+1})$ and define the total representation map by $$ \rho : \mathfrak{su}(2)\oplus\mathfrak{su}(2)\to\mathfrak{gl}(\mathbb{C}^{2s_1+1}\otimes\mathbb{C}^{2s_2+1}), h\mapsto \rho^+(h)\otimes 1 + 1 \otimes \rho^-(h)$$ where I really mean the tensor product of vector spaces with $\otimes$. For $s_1 = 1/2,s_2 = 0$, this is a two-dimensional representation where $\rho^-$ is identically zero - and the zero is the two-dimensional zero matrix in the two-by-two matrices $\mathfrak{gl}(\mathbb{C}^2)$." 1) If $h = N_i ^+$, $\rho ( N_i ^+) = \rho ^+ (N_i^+)\otimes1 + 1 \otimes \rho^-(N_i^+)$ , why is $\rho^-$ defined on $N_i^+$? My guess of how it ends: $\rho (N_i^+) = (\sigma_i /2)\otimes1 + 1 \otimes {0} = \sigma_i /2$ 2)If $h = N_i ^-$, $\rho ( N_i ^-) = \rho ^+ (N_i^-)\otimes1 + 1 \otimes \rho^-(N_i^-)$ , same, why is $\rho^+$ defined on $N_i^-$? I guess $\rho^+(N_i^-) = 0$ so that $\rho (N_i^-) = 0\otimes1 + 1 \otimes {0} = 0$ , but I am not sure why. Thanks in advance. A: The total representation map would look less confusing if we express $h \in su_1(2)\oplus su_2(2)$ in terms of the basis $\{N_1^+, N_2^+, N_3^+, N_1^-,N_2^-,N_3^-\}$ of $su_1(2)\oplus su_2(2)$. We recall $\{N_1^+, N_2^+, N_3^+\}$ is the basis of $su_1(2)$ and $\{N_1^-,N_2^-,N_3^-\}$ the basis of $su_2(2)$. $h=a_1N_1^+ + a_2N_2^+ + a_3N_3^+ +b_1 N_1^-+ b_2N_2^-+ b_3N_3^-$, where $a_i, b_i \in C$ Moreover, let $h=X+Y$ such that $X=a_1N_1^+ + a_2N_2^+ + a_3N_3^+$ $Y=b_1 N_1^-+ b_2N_2^-+ b_3N_3^-$. (Notice $X\in su_1(2)$ and $Y\in su_2(2)$) Also $su_1(2)\cong su_C (2)$ and similarly $su_2(2)\cong su_C (2)$, where $su_C (2)$ is the complexification of the real Lie algebra $su(2)$. Therefore, complex-linear representations of $su_C(2)$ have one-to-one correspondence with complex-linear representations of $su_1(2)$ and $su_2(2)$. This means both $\rho^+$ and $\rho^-$ are complex-linear, where $\rho^+ : \mathfrak{su_1}(2)\to\mathfrak{gl}(\mathbb{C}^{2s_1+1})$ and $\rho^- : \mathfrak{su_2}(2)\to\mathfrak{gl}(\mathbb{C}^{2s_2+1})$ So $$ \rho : \mathfrak{su_1}(2)\oplus\mathfrak{su_2}(2)\to\mathfrak{gl}(\mathbb{C}^{2s_1+1}\otimes\mathbb{C}^{2s_2+1}) $$ $$h\mapsto \rho^+(X)\otimes I_{2s_2 +1} + I_{2s_1+1} \otimes \rho^-(Y).$$ OBS: $\rho$ is complex-linear as a consequence of $\rho ^+$ and $\rho^-$ being complex-linear. Now, 1) If $h = N_i ^+$, for $s1=1/2$, $s2=0$ $\rho ( N_i ^+) = \rho ^+ (N_i^+)\otimes I_1 + I_2 \otimes \rho^-(0) = (\sigma_i /2)\otimes I_1 + I_2 \otimes {0} = \sigma_i /2$ 2) If $h = N_i ^-$ $\rho ( N_i ^-) = \rho ^+ (0)\otimes I_1 + I_2 \otimes \rho^-(N_i^-) = 0 \otimes I_1 + I_2 \otimes {0} = 0$
{ "pile_set_name": "StackExchange" }
Q: How to Change 404 page title i have try many methods after searching on internet but unable to ramove Nothing Found from my 404 page title how to do it please help me even i have us this in my 404 page header if( is_404() ) echo '404 message goes here | '; else wp_title( '|', true, 'right' ); i also ramove php title function and five their my own header but still not changing why ? A: I would use the wp_title filter hook: function theme_slug_filter_wp_title( $title ) { if ( is_404() ) { $title = 'ADD 404 TITLE TEXT HERE'; } // You can do other filtering here, or // just return $title return $title; } // Hook into wp_title filter hook add_filter( 'wp_title', 'theme_slug_filter_wp_title' ); This will play nicely with other Plugins (e.g. SEO Plugins), and will be relatively forward-compatible (changes to document title are coming soon). EDIT If you need to override an SEO Plugin filter, you probably just need to add a lower priority to your add_filter() call; e.g. as follows: add_filter( 'wp_title', 'theme_slug_filter_wp_title', 11 ); The default is 10. Lower numbers execute earlier (e.g. higher priority), and higher numbers execute later (e.g. lower priority). So, assuming your SEO Plugin uses the default priority (i.e. 10), simply use a number that is 11 or higher.
{ "pile_set_name": "StackExchange" }
Q: ‎Access Denied, Due to organizational policies, you can't access this resource from this untrusted device I can't view my SharePoint page and SharePoint admin center. I think I was changing some policies at sharepoint admin center, but I can't remember which one I changed. Other admin centers like OneDrive opens without any issue. Even as a admin I can't open SharePoint Admin Center. It says Access Denied, Due to organizational policies, you can't access this resource from this untrusted device. I've cleared my browser's cache and switched different browser but nothing works. A: After contacting Microsoft support and no response from them, I've tried solving this on my own. Here is how I solved it. Install the SharePoint Powershell from here After installing run these steps on SharePoint Powershell(Admin) to remove access blocks, Connect-SPOService -Url https://contoso-admin.sharepoint.com Set-SPOTenant -IPAddressEnforcement 1 Set-SPOTenant -IPAddressAllowList (Your current IP address), after running these command you will be able to access sharepoint without any issue. Now open SharePoint Admin center and Policies--> Access Control--> Unmanaged Devices and select Allow full access and save.
{ "pile_set_name": "StackExchange" }
Q: Is there an analog of class field theory over an arbitrary infinite field of algebraic numbers? Recently, I found a paper by Schilling http://www.jstor.org/pss/2371426, which mentions that for certain infinite field of algebraic numbers there is an analog of class field theory. By infinite field of algebraic number we mean an infinite extension of $\mathbb{Q}$. The paper cite a previous paper by Moriya which was the origin of the idea. I could not read the later since it is in German. Since the first paper is quite old (1937), I believe there must have been a lot of development in the mean time. My question: Do we have an analog of class field theory over an arbitrary infinite field of algebraic number? An even more general question: Do we have an analog of class field theory over an arbitrary field. This seems a bit greedy, but since we know that an algebraic closed field of characteristic 0 is totally characterized by its trancendence degree so if the answer to the previous question is positive the answer to this is perhaps not too far. Am I making sense? A: Iwasawa theory studies abelian extensions of fields $K$ where $K$ is a $\mathbb{Z}_p$-extension of $\mathbb{Q}$, that is the Galois group of $K/\mathbb{Q}$ is $\mathbb{Z}_p$. The corresponding Galois groups (of extensions of $K$) and class groups (of really subfields) of $K$, suitably interpreted, become $\mathbb{Z}_p$-modules and there are interesting relations between these modules and $p$-adic $L$-functions. It is a vast subject. Washington's book, Introduction to Cyclotomic Fields, is a good entry point.
{ "pile_set_name": "StackExchange" }
Q: Number of buildings between two points I am using QGIS 2.18.13. I have a polygon layer with building footprints, and a point layer with a given number of points. I would like to draw lines (randomly) between two points and see how many buildings the line crosses. How I can do that with QGIS? A: One approach is through Virtual Layers / SpatiaLite syntax. An example with 12 building and three points. For illustration purpose add connecting lines between points with the Virtual Layer SQL: select p1.id as id1, p2.id as id2, MakeLine(p1.geometry, p2.geometry) as geometryline from point p1 cross join point p2 where p1.id <> p2.id Use the Add / Edit Virtual Layer button: In the QGIS Create a virtual layer dialog it looks like: It will give you: Add another virtual layer doing the complete query. Remember to rename the layer so you won't overwrite the first virtual layer: with crossinglines(geometry) as ( select distinct MakeLine(p1.geometry, p2.geometry) as geometry from point p1 cross join point p2 ) select distinct b.geometry from building b inner join crossinglines cl on st_crosses(cl.geometry, b.geometry) In the layer control context menu Show feature count for the last virtual layer - showing the number of buildings with a line crossing. The lines of the first SQL are doubled. This is handled in the second SQL. Notice that the virtual layers are dynamic to their base layers. Adding a point will recalculate the virtual layers when they are refreshed with the QGIS refresh button. UPDATE: Now for adding the building id to the building being crossed add a new virtual layer with the following SQL. select v2.geometry, b.osm_id from virtual_layer2 v2 inner join building b on st_equals(b.geometry, v2.geometry) Where virtual_layer2 is you joined building layer that crosses the lines. Change the column name osm_id to your building id.
{ "pile_set_name": "StackExchange" }
Q: In what order should I write acknowledgments? In (pure?) mathematics, the order of the authors for a given paper is almost exclusively always alphabetical. This leads me to believe that there may be a similar convention when writing acknowledgements. In what order should acknowledgments be written in a math paper? By order of importance (increasing or decreasing), by alphabetical order, or something else? Does it not matter? A: It generally doesn't matter much (though I wouldn't suggest using in increasing order of helpfulness), but if some people deserve special thanks they should be singled out. I'll often write acknowledgements in this sort of format: I thank Prof A for encouraging me to think about this problem and Prof B for the realization that it could be approached by X ("chronological order"). I also thank C, D and E (alphabetical order) for useful discussions and feedback. This work was partially supported by Grant 12345. If it's a co-authored paper you can separate sentences/phrases for specific thanks from each author. Generally my advice on questions like this is just to look at a bunch of other papers, see what they do, and learn from that.
{ "pile_set_name": "StackExchange" }
Q: adobe air push notifications I am using push notifications extension and getting an error : ReferenceError: Error #1065: Variable com.freshplanet.nativeExtensions::PushNotification is not defined. These are the simple steps I followed so far: 1) added the extension in the properties/actionscript build path/native extensions . it is with a green flag and the .ane is located in my libs folder 2) added the extensionid to my app.xml file <extensions> <extensionID>com.freshplanet.AirPushNotification</extensionID> </extensions> 3) registered in the app constructor : PushNotification.getInstance().registerForPushNotification(); 4) Do the following steps, which use Flash Builder 4.5.1: Change the filename extension of the ANE file from .ane to .swc. This step is necessary so that Flash Builder can find the file. Select Project > Properties on your Flash Builder project. Select the Flex Build Path in the Properties dialog box. In the Library Path tab, select Add SWC.... Browse to the SWC file and select Open. Select OK in the Add SWC... dialog box. The ANE file now appears in the Library Path tab in the Properties dialog box. Expand the SWC file entry. Double-click Link Type to open the Library Path Item Options dialog box. In the Library Path Item Options dialog box, change the Link Type to External. Now you can compile your application using, for example, Project > Build Project. This is all done on iPad Thanks for the help :-) A: Well the problem was resolved by opening the project properties panel , in the actionscript build packaging selecting Apple ios, there under the native extensions tab select package for all the extensions needed in the project. The confusing part here for me was that there are 2 places than need to add the native extensions, one is the actionscript build path and the second is the actionscript build packaging. The step of renaming the package to .swc and adding it to the build is not need from what I understand.
{ "pile_set_name": "StackExchange" }
Q: iOS: Is it possible to detect if a track exists in music library? I'm working on an app for a band and they'd like certain features to unlock if their album or singles are in the user's music library. Is it possible to scan the library for a specific title?(and possibly check duration as well?) A: Here is a working search. This checks for a track that matches both the title and the artist name. MPMediaPropertyPredicate *titlePredicate = [MPMediaPropertyPredicate predicateWithValue:@"Sleep The Clock Around" forProperty:MPMediaItemPropertyTitle comparisonType:MPMediaPredicateComparisonEqualTo]; MPMediaPropertyPredicate *artistPredicate = [MPMediaPropertyPredicate predicateWithValue:@"Belle & Sebastian" forProperty:MPMediaItemPropertyArtist comparisonType:MPMediaPredicateComparisonEqualTo]; MPMediaQuery *trackSearch = [[MPMediaQuery alloc] initWithFilterPredicates:[NSSet setWithObjects:titlePredicate,artistPredicate, nil]]; if(trackSearch.items.count > 0) NSLog(@"we found the track!");
{ "pile_set_name": "StackExchange" }
Q: Has the theoretical explanation of Compressed Sensing been simplified since 2005/2006? Is the theoretical explanation of compressed sensing given in the Candes, Romberg, and Tao papers from 2005 / 2006 still the simplest and most clear explanation available? Are these original papers still the best resource for learning the theory behind compressed sensing? Which paper or textbook is the best starting point for understanding compressed sensing theory? A: A little late to the question, but there are a couple of good resources I found which were extremely useful in getting a good understanding of the field. Aside from the seminal papers you listed, I encourage you to take a look at the texts below. Note that CS is vast field, and there are countless papers on this subject, so do tailor your study to whatever objective you have. $\textbf{1)}$ Holger Rauhut's text, "Compressive Sensing and Structured Random Matrices". This text is available online for free when you do a google search of it. The first 100 pages give a very good overview of the different approaches in compressive sensing. It discusses popular conditions for uniform recovery of all s-sparse vectors through the RIP property and also mentions some other conditions which guarantee $l_0-l_1$ minimization equivalence. In addition, the first 100 pages also go into detail on non-uniform recovery via random sampling, which is an integral part of compressive sensing. $\textbf{2)}$ "The Restricted Isometry Property and Its Implications for Compressed Sensing" by Emmanuel Candes This short paper gives a very quick overview of Candes/Tao's seminal paper on RIP in compressive sensing. I find this to be very concise if you do not want to delve into the original paper, which is much longer. I think this is a good read for anyone interested in the field because RIP conditions are not only integral to the field, but the proofs to these elegant theorems can be understood with elementary mathematical knowledge. $\textbf{3)}$ "RIPless theory of Compressive Sensing" by Candes/Plan This paper contains more recent results to compressive sensing via random sampling. The field itself has moved quite a lot from 2005-2006, and this paper contains an overarching theory for when s-sparse vectors can be recovered exactly from $l_1$-minimization.
{ "pile_set_name": "StackExchange" }
Q: how to select table from a different server having backslash in the name I am trying to query a table that exists in a different server/ database etc. select top 1 * from 'serverdd\foobar'.mydatabase.mytable My problem is that I have a backslash in the server name.. So how do I write the query for this kind of server name. I did enclose it with single quote but it did not work. I get "an incorrect" syntax error. A: First you need to add the "linked server". Here is a link: https://msdn.microsoft.com/en-gb/library/ms190479.aspx Probably it will look something like this (though I usually use the GUI): EXEC sp_addlinkedserver @server=N'serverdd_foobar', @srvproduct=N'', @provider=N'SQLNCLI', @datasrc=N'serverdd\foobar'; When you link a server you give it a friendly name. In the above example I named it without the backslash. You can access the server using this name: SELECT * FROM serverdd_foobar.database.schema.table If any of these elements contain invalid characters (like a backslash) you will want to enclose that element in square brackets. Double quotes usually works too, but that can be turned off; single quotes will never work.
{ "pile_set_name": "StackExchange" }
Q: How can I retrieve Xcode product informations using AppleScript? I'm trying to create a custom generic Xcode behaviour, that once invoked will launch a script to generate AppleDoc documentation related to the current project opened in the ide. I initially asked this question: Xcode 4: custom behavior does not execute my sh script? which helped me to understand what I was missing: it's not possible to use Xcode variables in external scripts! So, my new question is: how can I use AppleScript to retrieve the informations I need (Project name, company, paths...)? I'm pretty sure that this is possible, since Xcode is highly "scriptable", but so far I was able to retrieve only the name of the xcode project file: tell application "Xcode" tell active project document name end tell end tell The code above returns "MyProject.xcodeproj". I'm a totally newbie when it comes to AppleScript and it's hard for me to understand the reference in Xcode.sdef (the hierarchy seems pretty simple, but I'm unable to create the right script to retrieve what I want). Can you give some hints or point me to a newbie-proof tutorial about AppleScript + Xcode? (I didn't find nothing but "hello world" for Finder examples :P) A: The easiest thing to do is get properties of an item. So for example run this to get the properties of the frontmost project. tell application "Xcode" tell first project return properties end tell end tell You will see the properties are a "record". To access the items of a record you get them by their name. For example you can get the "real path" of the project... tell application "Xcode" tell first project return real path end tell end tell Finally, when you look at the sdef file you do that using Applescript Editor application. Under the file menu chosse "open dictionary" and choose the application. Once the dictionary is open it's useful to use the search field. For example search for "project" and then highlight the result corresponding to the "class". This will show you what you can get from a project. So you see we have a few ways to find out what information we can get from an application.
{ "pile_set_name": "StackExchange" }
Q: Unknown segmentation fault involving vtable lookup So I messing around with virtual functions, trying to find a way to mitigate their cost, and I encountered an entirely unknown error. My entire code follows; #include <iostream> #include <cmath> class Base { public: virtual void func() = 0; }; class Der1 : public Base { public: virtual void func(); }; void Der1::func(){std::cout << "I am Der1\n";} class Der2 : public Base { public: virtual void func(); }; void Der2::func(){std::cout << "I am Der2\n";} void myFornction(Base* B){ std::cout << "Within Fornction " << B << '\n'; for (int i = 0; i < 10; i++) B->func(); } using namespace std; int main() { Der2* B; std::cout << "Actual Address " << B << '\n'; myFornction(B); return 0; } this was compiled with the GCC compiler that was included with codeblocks (unfortunately the version is unlisted), and here is the assembly of the function at fault; 24 void myFornction(Base* B){ 0x00401373 push %ebp 0x00401374 mov %esp,%ebp 0x00401376 sub $0x28,%esp 25 std::cout << "Within Fornction " << B << '\n'; 0x00401379 movl $0x46e03a,0x4(%esp) 0x00401381 movl $0x477860,(%esp) 0x00401388 call 0x468e68 <std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)> 0x0040138D mov 0x8(%ebp),%edx 0x00401390 mov %edx,(%esp) 0x00401393 mov %eax,%ecx 0x00401395 call 0x449524 <std::ostream::operator<<(void const*)> 0x0040139A sub $0x4,%esp 0x0040139D movl $0xa,0x4(%esp) 0x004013A5 mov %eax,(%esp) 0x004013A8 call 0x468f44 <std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char)> 26 for (int i = 0; i < 10; i++) 0x004013AD movl $0x0,-0xc(%ebp) 0x004013B4 jmp 0x4013c5 <myFornction(Base*)+82> 0x004013C2 incl -0xc(%ebp) 0x004013C5 cmpl $0x9,-0xc(%ebp) 0x004013C9 setle %al 0x004013CC test %al,%al 0x004013CE jne 0x4013b6 <myFornction(Base*)+67> 27 B->func(); 0x004013B6 mov 0x8(%ebp),%eax 0x004013B9 mov (%eax),%eax 0x004013BB mov (%eax),%eax /// The program fails with a segmentation fault here 0x004013BD mov 0x8(%ebp),%ecx 0x004013C0 call *%eax 28 } 0x004013D0 leave 0x004013D1 ret The program exits with a segmentation fault when run, looking at the assembly I can tell that the seg fault happens during look up, but I cannot think of a reason or resolution for this. Also, it is kind of random that this happens now, as I have been working with some of my own virtual classes for sometime now with no problems. Why now? And why would this specific code generate a fault? A: You should initialize B in main() before passing it, because it doesn't point anywhere. Der2* B = new Der2();
{ "pile_set_name": "StackExchange" }
Q: Clicking on a div placed over an image in IE I have an image which may have some divs over it (specifying certain selections within that image). These divs are supposed to be clickable. Something like that: #divOuter { width: 500px; height: 500px; border: 2px solid #0000FF; position: relative; } #divInner { width: 100px; height: 100px; border: 2px solid #00FF00; position: absolute; cursor: pointer; top: 20px; left: 20px; } <div id="divOuter"> <img src="SomeImage.jpg" /> <div id="divInner"></div> </div> $("#divOuter").click(function() { alert("divOuter"); }); $("#divInner").click(function() { alert("divInner"); }); In chrome and FF it works as expected (pointer appears over the div, and clicking it alerts "divInner" and then "divOuter"). However, in IE8 it didn't - I got the same behavior only when hovering/clicking on the inner div borders. When clicking inside that div, only "divOuter" was alerted. How can this be fixed? A: Here's a hack: add an CHAR like "O" to the inner div, and then give it an enormous font size(depends on the area you want to span over): #divInner { /* ... */; font-size: 1000px; color: transparent; } (Also set "overflow: hidden" I think.) IE likes there to be something there in the container for the click to affect. If it's just completely empty, it ignores clicks. a fiddle: https://jsfiddle.net/cbnk8wrk/1/ (watch in IE!) A: I had the same problem with an unordered list, see Getting unordered list in front of image slide-show in IE8, IE7 and probably IE6 The solution : give the div a background color and make it transparent with a filter.
{ "pile_set_name": "StackExchange" }
Q: detect natural line breaks javascript When I type in a non-resizeable text area something like hello world, this is a demo and the text area is small enough, it will look like this: hello world, this is a demo This is not caused by a \n or something. How can I detect this natural line break in a text area? A fiddle can be found here: http://jsfiddle.net/yx6B7/ As you can see, there is a line break, but javascript just says that it's one big line without any line-breaks in it. A: Finally I found this script on the internet: function ApplyLineBreaks(strTextAreaId) { var oTextarea = document.getElementById(strTextAreaId); if (oTextarea.wrap) { oTextarea.setAttribute("wrap", "off"); } else { oTextarea.setAttribute("wrap", "off"); var newArea = oTextarea.cloneNode(true); newArea.value = oTextarea.value; oTextarea.parentNode.replaceChild(newArea, oTextarea); oTextarea = newArea; } var strRawValue = oTextarea.value; oTextarea.value = ""; var nEmptyWidth = oTextarea.scrollWidth; var nLastWrappingIndex = -1; for (var i = 0; i < strRawValue.length; i++) { var curChar = strRawValue.charAt(i); if (curChar == ' ' || curChar == '-' || curChar == '+') nLastWrappingIndex = i; oTextarea.value += curChar; if (oTextarea.scrollWidth > nEmptyWidth) { var buffer = ""; if (nLastWrappingIndex >= 0) { for (var j = nLastWrappingIndex + 1; j < i; j++) buffer += strRawValue.charAt(j); nLastWrappingIndex = -1; } buffer += curChar; oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length - buffer.length); oTextarea.value += "\n" + buffer; } } oTextarea.setAttribute("wrap", ""); document.getElementById("pnlPreview").innerHTML = oTextarea.value.replace(new RegExp("\\n", "g"), "<br />"); } Which is working fine.
{ "pile_set_name": "StackExchange" }
Q: What CWinThread::PumpMessage does While I debugging a windows application developed in C++, I found this function call CWinThread::PumpMessage(). I have read in MSDN and, a few other forum posts to understand. But still not sure what it does. Can someone help me with the usability of this function? A: That's a handy function which prevents window from locking up. It's usage in MFC application is as follows: void PumpWaitingMessages(){ MSG msg; while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)){ if (!AfxGetThread()->PumpMessage()) return; } } For example, consider this function in a dialog box: void CMyDialog::OnOK(){ for (int i = 0; i < 50; i++){ PumpWaitingMessages(); Sleep(100); //do some lengthy calculations } MessageBox("done"); CDialog::OnOK(); } If you call the above function the program should lock the thread for 5 seconds. But PumpWaitingMessages(); will allow the program to respond keyboard and mouse input. But becareful because for example if you click the OK button twice in a row then the program will close the dialog box twice...
{ "pile_set_name": "StackExchange" }
Q: C#: Declaring a constant variable for datatype to use Is it possible somehow to define a constant that says what datatype to use for certain variables, similar to generics? So in a certain class I would have something like the following: MYTYPE = System.String; // some other code here MYTYPE myVariable = "Hello"; From the principle it should do the same as generics but I don't want to write the datatype every time the constructor for this class is called. It should simply guarantee that for two (or more) variables the same datatype is used. A: Well, you can use a using directive: using MYTYPE = System.String; However, that isn't really like a typedef - in particular, this code is now perfectly valid: MYTYPE x = "hello"; string y = "there"; x = y; The compiler knows they're still the same type. It's not really clear what you're trying to achieve, particularly here: I don't want to write the datatype every time the constructor for this class is called. What do you mean? Note that using directives are specific to a source file, not to a whole project. A: You can do that with a using alias: using MyType = System.String; however, only on a per-file basis. Frankly, it is useful for making a short alias to some complex composite generic type (I'm thinking of "Owin" etc), but other than that, generics are more versatile.
{ "pile_set_name": "StackExchange" }
Q: c++03 null pointer versus null object pattern: performance implications I have some library code which sometimes needs to be run multithreaded, but more usually single threaded. It's a set of small routines which are called very frequently. Previous experience and profiling indicates that extra delays may be detrimental to performance, so I want to avoid unnecessary overheads. I can't provide a separate instance of the library for single and multithreaded use, nor can I provide a thread safe wrapper the single threaded version. Both these restrictions are due to the design of the library. My preferred way of protecting the routines when run multithreaded is to use a scoped mutex. My initial thought was along the lines of this SO answer. However most of the time the routines are run single threaded, and I don't like the overhead of the null pointer check. This is run on a very slow ARM9 processor and every cycle counts. In practice I'll probably go with the null pointer check and profile to see what it costs, but I'm wondering whether there's a better way. For example the null object pattern, or having the library call a callback. A: I feel like there is some information lacking here to really give the best answer, but I don't really see any reason to use pointers here at all. Presumably you are calling some library code, let's say it's a function called void foo(int). You can't change this code, and it's not thread safe. But you can change your code, right? Instead of calling your code, call a wrapper around foo: template <class M> void foo_wrapper(M& mutex, int x); { std::lock_guard(mutex); foo(x); } Now, you can simply write a trivial no-op mutex: struct NoMutex { void lock() {} bool try_lock() { return true; } void unlock() {} }; std::mutex m1; NoMutex m2; foo_wrapper(m1, 0); // thread safe foo_wrapper(m2, 0); // thread unsafe Because the types are known to the compiler, the second call to foo_wrapper will not have any overhead whatsoever.
{ "pile_set_name": "StackExchange" }
Q: Algebraically determine the x-intercept of $y=2^{x+2}-3$ Algebraically determine the $x$-intercept of $y=2^{x+2}-3$ Any help would be much appreciated... looking at the question it is clear to me that there are no real intercepts for $x$ but there is for $y$. If I look on the graph I can point out that there is a X:INT of $x$=-0.415- A: You want $$2^{x+2}-3=0$$ so $$2^{x+2}=3$$ which means $$x+2=\log_2 3$$ and finally $$x=\log_23-2$$
{ "pile_set_name": "StackExchange" }
Q: Figure in a figure in a figure I'm experimenting with matplotlib to draw figures in figures in figures. Since squares are the most straight-forward to draw, I started with those. In the end I want to write a generator for polygons with a certain width. In the given example, this would be a 4-corner polygon with straight angles and width 1. My current code plots the following, which is as expected and almost as desired. Note there is a line between 2,2 and 2,3 which I think can be removed if this is done with a correct algorithm instead of the current code. A summary of the above is a square boxed in two boxes with an amplitude increasing with 1, assuming the the larger boxes are 'behind' the rest of the boxes. The method of which I wrote the code producing the above is, well, not really a function. It's a darn ugly collection of points which happen to resemble hollow squares. import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt fig, ax = plt.subplots() INNER_AMPLITUDE = 1.0 OUTER_AMPLITUDE = 3.0 Path_in = mpath.Path path_in_data = [ (Path_in.MOVETO, (INNER_AMPLITUDE, -INNER_AMPLITUDE)), (Path_in.LINETO, (-INNER_AMPLITUDE, -INNER_AMPLITUDE)), (Path_in.LINETO, (-INNER_AMPLITUDE, INNER_AMPLITUDE)), (Path_in.LINETO, (INNER_AMPLITUDE, INNER_AMPLITUDE)), (Path_in.CLOSEPOLY, (INNER_AMPLITUDE, -INNER_AMPLITUDE)), ] codes, verts = zip(*path_in_data) path_in = mpath.Path(verts, codes) patch_in = mpatches.PathPatch(path_in, facecolor='g', alpha=0.3) ax.add_patch(patch_in) x, y = zip(*path_in.vertices) line, = ax.plot(x, y, 'go-') Path_out = mpath.Path path_out_data = [ (Path_out.MOVETO, (OUTER_AMPLITUDE, -OUTER_AMPLITUDE)), (Path_out.LINETO, (-OUTER_AMPLITUDE, -OUTER_AMPLITUDE)), (Path_out.LINETO, (-OUTER_AMPLITUDE, OUTER_AMPLITUDE)), (Path_out.LINETO, (OUTER_AMPLITUDE, OUTER_AMPLITUDE)), (Path_out.LINETO, (OUTER_AMPLITUDE, OUTER_AMPLITUDE-INNER_AMPLITUDE)), (Path_out.LINETO, (-(OUTER_AMPLITUDE-INNER_AMPLITUDE), OUTER_AMPLITUDE-INNER_AMPLITUDE)), (Path_out.LINETO, (-(OUTER_AMPLITUDE-INNER_AMPLITUDE), -(OUTER_AMPLITUDE-INNER_AMPLITUDE))), (Path_out.LINETO, (OUTER_AMPLITUDE-INNER_AMPLITUDE, -(OUTER_AMPLITUDE-INNER_AMPLITUDE))), (Path_out.LINETO, (OUTER_AMPLITUDE-INNER_AMPLITUDE, OUTER_AMPLITUDE-INNER_AMPLITUDE)), (Path_out.LINETO, (OUTER_AMPLITUDE, OUTER_AMPLITUDE-INNER_AMPLITUDE)), (Path_out.CLOSEPOLY, (OUTER_AMPLITUDE, OUTER_AMPLITUDE-INNER_AMPLITUDE)), ] codes, verts = zip(*path_out_data) path_out = mpath.Path(verts, codes) patch_out = mpatches.PathPatch(path_out, facecolor='r', alpha=0.3) ax.add_patch(patch_out) plt.title('Square in a square in a square') ax.grid() ax.axis('equal') plt.show() Do note I consider this off-topic for Code Review since I'm looking for extending my functionality, not just a re-write which is up to best-practices. I feel like I'm doing it completely the wrong way. First things first. How should I draw polygons with a certain width using matplotlib, assuming the polygon will be surrounded on the outside with a band of the same form and at least the same width and completely filled on the inside? A: Handling polygons purely in matplotlib can be quite tedious. Luckily there is a very nice library for these kind of operations: shapely. For your purposes the parallel_offset function is the way to go. The bounds of the polygons which you're interested in, are defined by ring1, ring2 and ring3: import numpy as np import matplotlib.pyplot as plt import shapely.geometry as sg from descartes.patch import PolygonPatch # if I understood correctly you mainly need the difference d here INNER_AMPLITUDE = 0.1 OUTER_AMPLITUDE = 0.2 d = OUTER_AMPLITUDE - INNER_AMPLITUDE # fix seed, for reproducability np.random.seed(11111) # a function to produce a "random" polygon def random_polygon(): nr_p = np.random.randint(7,15) angle = np.sort(np.random.rand(nr_p)*2*np.pi) dist = 0.3*np.random.rand(nr_p) + 0.5 return np.vstack((np.cos(angle)*dist, np.sin(angle)*dist)).T # your input polygon p = random_polygon() # create a shapely ring object ring1 = sg.LinearRing(p) ring2 = ring1.parallel_offset(d, 'right', join_style=2, mitre_limit=10.) ring3 = ring1.parallel_offset(2*d, 'right', join_style=2, mitre_limit=10.) # revert the third ring. This is necessary to use it to procude a hole ring3.coords = list(ring3.coords)[::-1] # inner and outer polygon inner_poly = sg.Polygon(ring1) outer_poly = sg.Polygon(ring2, [ring3]) # create the figure fig, ax = plt.subplots(1) # convert them to matplotlib patches and add them to the axes ax.add_patch(PolygonPatch(inner_poly, facecolor=(0,1,0,0.4), edgecolor=(0,1,0,1), linewidth=3)) ax.add_patch(PolygonPatch(outer_poly, facecolor=(1,0,0,0.4), edgecolor=(1,0,0,1), linewidth=3)) # cosmetics ax.set_aspect(1) plt.axis([-1.5, 1.5, -1.5, 1.5]) plt.grid() plt.show() Result:
{ "pile_set_name": "StackExchange" }
Q: How to check if Remote API is enabled in your Confluence installation without admin rights Is there a way to find out if the Remote API is enabled on our Confluence installation if I do not have admin rights to our confluence I can see the WSDSL, but while testing with this downloaded client I keep timing out on login. I can not contact my administrators without going through god knows how many channels so I'm hoping there's another way to know if the Remote API is enabled. A: To check if the confluence API is enabled without admin access: Try accessing http://<your-confluence-server>/rpc/xmlrpc If the API is enabled, you will simply get a blank page. If the API is disabled, you will get an error "HTTP Status 403 - Remote API is not enabled on this server. Ask a site administrator to enable it." This is at least applicable in my Confluence 3.2 environment.
{ "pile_set_name": "StackExchange" }
Q: How to understand @Configuration I'm new to Java config. I have a code like this. SomeDao has its own dependency, shouldn't we set the dependencies since we are doing new? Can someone please help me understand this code? @Configuration public class DAOConfiguration { @Bean(name = "someDao") public SomeDao someDao() { return new SomeDao(); } A: Are you familiar with how this is done in xml? It is extremely similar to that. Here is an example of SomeDao being configured with Dep1 (via constructor injection) and Dep2 (via setter injection) in xml: <bean id="someDao" class="com.example.SomeDao"> <constructor-arg ref="dep1"/> <property name="dep2" ref="dep2"/> </bean> <bean id="dep1" class="com.example.Dep1" /> <bean id="dep2" class="com.example.Dep2" /> This same example in JavaConfig would be configured as such: @Configuration public class DAOConfiguration { @Bean(name = "someDao") public SomeDao someDao() { final SomeDao someDao = new SomeDao(dep1()); someDao.setDep2(dep2()); return someDao; } @Bean(name="dep1") public Dep1 dep1() { return new Dep1(); } @Bean(name-"dep2") public Dep2 dep2() { return new Dep2(); } } All three beans are still registered with the ApplicationContext too, so you can have all three of these beans autowired into another class, like so: @Controller public class MyController { @Autowired private SomeDao someDao; @Autowired private Dep1 dep1; //...some methods }
{ "pile_set_name": "StackExchange" }
Q: Google Sheets how to write multiple things in a cell Is there and easy ways to make things like this work: =IF(TRUE, " " " ", " ") Or with a method in it: =IF(TRUE, " This is the Name " VLOOKUP(NAME_ID, NAME!$A$4:$B, 2 FALSE), " ") A: try: =IF(A1=B1, "This is the Name "&VLOOKUP(NAME_ID, NAME!A4:B, 2, 0), ) or: =IF(A1<>B1,, "This is the Name "&VLOOKUP(NAME_ID, NAME!A4:B, 2, 0)) or if you want it in two cells: =IF(A1<>B1,, {"This is the Name", VLOOKUP(NAME_ID, NAME!A4:B, 2, 0)})
{ "pile_set_name": "StackExchange" }
Q: Why does my code not work; Translating a pic Consider the following code. \documentclass[border=5mm]{standalone} \usepackage{tikz} \usetikzlibrary{calc} \usetikzlibrary{backgrounds} \usepackage{pgfplots} \pgfplotsset{compat=1.13} \usepgfplotslibrary{fillbetween} \usetikzlibrary{patterns} \pgfplotsset{ticks=none} \newcommand{\newvar}{\pgfmathsetmacro} \begin{document} \begin{tikzpicture}[scale=1, transform shape] \newvar{\num}{5} \newvar{\val}{\num-1} \coordinate (A) at (0, 0); \coordinate (B) at (1, 0); \coordinate (C) at (0, 1); \coordinate (D) at (0, 2); \coordinate (E) at (1, 2); \tikzset{ square/.pic={ \draw[line width=1mm, pic actions] (0, 0) -- (1, 0) -- (1, 1) -- (0, 1) -- cycle; } } \tikzset{ tile1/.pic={ \foreach \i in {(A), (B), (C), (D), (E)}{ \draw \i pic {square} ; } } } \begin{scope}[scale=1] \foreach \i in {0,...,\num}{ \foreach \j in {0,...,\val}{ \path (3*\j+\i, -\j+3*\i) pic {tile1}; } } \end{scope} \end{tikzpicture} \end{document} First I have defined square/.pic which is just the outline of the unit square. Then I have defined the coordinates (A), (B), (C), (D), and (E). These are defined in such a manner that if the unit square is placed at each of these coordinates, then the resulting figure is a C-shaped tile. This is carried out in tile1/.pic. At the end of the code one can see two for loops, which were supposed to place various translations of tile1/.pic on the plane, achieving a tessellation. However, the output I get is the measly: PS: Please feel free to offer any general coding advice. A: One cannot translate symbolic coordinates like this, and here is no need to use these. (Also I would not use your command \newvar. It sort of works accidentally. And I removed packages and libraries that are not in use.) The following works. \documentclass[border=5mm]{standalone} \usepackage{tikz} \newcommand{\newvar}{\pgfmathsetmacro} \begin{document} \begin{tikzpicture}[scale=1, transform shape] \pgfmathtruncatemacro{\num}{5} \pgfmathtruncatemacro{\val}{\num-1} \tikzset{ square/.pic={ \draw[line width=1mm, pic actions] (0, 0) -- (1, 0) -- (1, 1) -- (0, 1) -- cycle; } } \tikzset{ tile1/.pic={ \foreach \i in {(0, 0),(1, 0),(0, 1),(0, 2),(1, 2)}{ \draw \i pic {square} ; } } } \begin{scope}[scale=1] \foreach \i in {0,...,\num}{ \foreach \j in {0,...,\val}{ \path (3*\j+\i, -\j+3*\i) pic {tile1}; } } \end{scope} \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: How to pass imageInByte in an intent and convert it? In main activity I select an image from gallery with the below code Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); useally I insert it to sqlite db directly in my main_activity with the below code Bitmap yourImage = extras2.getParcelable("data"); // convert bitmap to byte ByteArrayOutputStream stream = new ByteArrayOutputStream(); yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream); byte imageInByte[] = stream.toByteArray(); Log.e("output before conversion", imageInByte.toString()); // Inserting Contacts Log.d("Insert: ", "Inserting .."); db.addContact(new Contact("Android", imageInByte)); .. but I want to pass the image to another activity to add discreption to it. I am receiving the intent in another activity like this Intent intent = getIntent(); Bundle extras = getIntent().getExtras(); DBhelper db = new DBhelper(this); db.addContact(new Contact("add", intent)); so I want to be pass imageInByte through an intent. but my problem in the another activity I cannot insert intent type. how to fix that ? A: If you want to get the Bitmap in another activity, then do this byte[] byteArray = getIntent().getByteArrayExtra("image"); Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length); Also, don't forget to pass the byteArray from your first activity Intent intent = new Intent(this, AnotherActivity.class); intent.putExtra("image",imageInByte);
{ "pile_set_name": "StackExchange" }
Q: Should I expect search engines (particularly Google) to crawl EPUB and MOBI files? Some of our content we are publishing as EPUB and MOBI ebook format files. Will search engines crawl and index these in the same way as PDFs currently are? If the answer is yes, could you point me to some sample results page that shows how they appear? A: Those aren't document types that search engines index and return in their search results.
{ "pile_set_name": "StackExchange" }
Q: jstring return in JNI program This is JNI code. Java code: public class Sample1 { public native String stringMethod(String text); public static void main(String[] args) { System.loadLibrary("Sample1"); Sample1 sample = new Sample1(); String text = sample.stringMethod("world"); System.out.println("stringMethod: " + text); } } Cpp Method for stringMethod function: JNIEXPORT jstring JNICALL Java_Sample1_stringMethod (JNIEnv *env, jobject obj, jstring string) { const char *name = env->GetStringUTFChars(string, NULL);//Java String to C Style string char msg[60] = "Hello "; jstring result; strcat(msg, name); env->ReleaseStringUTFChars(string, name); puts(msg); result = env->NewStringUTF(msg); // C style string to Java String return result; } When running my java code. I got the result below. stringMethod: world But I appended the string "world" with "Hello ". I'm also returning here the appended string. But why I'm getting only "world" not "Hello World". Really I confused with this code. What should I do to get the result with appended string? A: this should be the way to do it.... JNIEXPORT jstring JNICALL Java_Sample1_stringMethod (JNIEnv *env, jobject obj, jstring string) { const char *name = (*env)->GetStringUTFChars(env,string, NULL); char msg[60] = "Hello "; jstring result; strcat(msg, name); (*env)->ReleaseStringUTFChars(env,string, name); puts(msg); result = (*env)->NewStringUTF(env,msg); return result; }
{ "pile_set_name": "StackExchange" }
Q: Replacing the homework policy 1: what existing questions should be on/off topic? TL;DR: post examples of current questions which are edge cases for the new policy, look through the list, and vote answers UP if you think they should be ON TOPIC vote answers DOWN if you think they should be OFF TOPIC Also, if you feel motivated, fill out this questionnaire about the answers. When we last left the ongoing examination of our homework policy, the community had come to something of a consensus that certain low-effort questions asking for calculations should be off topic. In addition, I've been watching actual question closures over the past couple months since we had that discussion, and I see more and more questions getting closed for displaying unacceptably low effort, whether using the existing homework-like close reason, or a custom reason written in a comment. I think it's time we start formulating a new policy. This new policy, along with one or two associated close reasons, will prescribe how we should decide whether questions are off topic for being low-effort and/or being calculation requests. It will replace the current homework policy, and in the future, we will use the associated close reason(s) for homework questions, instead of using the existing homework-like close reason (which will no longer be active). What I have in mind is a process in 4 steps, of which this is the first: Collect examples of questions that should be on topic or off topic under the new policy. Prepare and edit a draft of the new policy that implements the consensus on the examples as well as possible. This may take a while. Decide on the wording of one or two new close reasons that will be associated with the new policy. Two reasons would be an option in case we want both low-effort questions and calculation requests to be off topic and we can't come up with one reason to cover them both. Make an official faq post with the content of the new policy, deprecate the current homework policy, and swap the new close reasons in for the existing homework-like close reason. This is the easy part. 1. Collecting examples of on/off-topic questions In order to guide the development of a new policy, I think it will help to have many examples of questions that should be on topic or off topic. So I'm making this post to solicit these examples from the community. Here's how it will work: each answer should contain a link to one question that is currently on the site. Vote up each answer if you would like to see that question be on topic under the new policy (that we are going to write), and vote down if you think the question should be off topic under the new policy. Please vote based on how the question is currently written, not based on how you think it could be written if it were improved. It doesn't matter so much whether the question is currently open or closed. If you have feedback arguing one way or another for a particular link, leave it in the comments on that answer. For a lot of questions, the decision is obvious. We don't really need to post those. What I'm most interested in are "interesting" cases, such as questions which are currently on topic but which you'd like to see be off topic under the new policy, or vice versa. Borderline questions, which are not clearly on-topic or off-topic, are also good candidates for posting here. For inspiration, you can look at our previous discussions on this topic: Generalizing the homework policy Should we rename the homework policy? Homework - the view from the chat session What's the current status of the homework policy? Banning homework: vote and documentation Chat session on homework close reason Closing "Insufficient Effort" questions Does "insufficient effort" cover previous SE questions? Questions that show insufficient effort by the OP What is the meaning of **effort** that Phys.SE wants in homework questions? and so on, e.g. linked and related questions in those. The consensus that emerged from the last meta question is represented by rob's answer, which suggested the following: Questions which attempt to outsource tedious calculations to the community, without any broader context, are off-topic. I recognize that a key word here ("tedious") implies a value judgement, and there's a bias in writing these guidelines towards "objective", judgement-free criteria. That bias is flawed, which is why we have human moderators and the opportunity to discuss some decisions with them. Use this as a starting point to help judge which questions are likely to be edge cases and how you would vote on them. A: Sound pitch of glass with water This is not a homework or homework-like question, it's not a calculation request, it's completely conceptual, but the question doesn't show any prior research, or any evidence that the poster has made an effort to figure out the answer themselves. You might think that's perfectly fine. On the other hand, if you believe the poster should have shown more effort, what would you expect them to have done? (You can address this in the comments on this answer if you like.) Vote up if you think this question should be on topic under the new policy, or vote down if you think it should be off topic under the new policy. A: Mutual $E$ force due to charged coaxial rings I think this is probably homework because it's really just asking how to solve a problem. However you could argue it's conceptual in the sense that it's asking about how to approach this sort of problem for arbitrary geometries. A belated footnote: the simplest approach I've seen to doing this requires the use of the reciprocity theorem, and specifically that the potential energy of a quadrupole charge distribution in the electrostatic potential from a monopole is the same as the potential energy of a monopole in an electrostatic potential from a quadrupole. Wouldn't answering aalong these lines count as conceptual? Vote up if you think this should be on topic under the new policy, or vote down if you think it should be off topic under the new policy. A: Three dimensional isotropic harmonic oscilator Hamiltonian This is an advanced question (on quantum mechanics) that shows detailed effort. It could be argued that it doesn't actually ask anything beyond "what am I doing wrong?", though. Vote up if you think this should be on topic under the new policy, or vote down if you think it should be off topic under the new policy.
{ "pile_set_name": "StackExchange" }
Q: how to ELSE out the "skip"? here is my code: IF EXIST "D:\Windows\\." IF EXIST "D:\Program Files\\." ( IF NOT EXIST "D:\TP\\." ( MD "D:\TP\" MD "D:\TP\ver 5.1\" ) MOVE "app.exe" "D:\TP\ver 5.1\" ) ELSE ( SHIFT ) IF EXIST "C:\Windows\\." IF EXIST "C:\Program Files\\." ( IF NOT EXIST "C:\TP\\." ( MD "C:\TP\" MD "C:\TP\ver 5.1\" ) MOVE "app.exe" "C:\TP\ver 5.1\" ) ELSE ( SHIFT ) IF EXIST "E:\......... for rest of available drives xD what I'm trying to achieve is to skip whole commands if they are not matching my criteria. what do I do wrong? A: SOLVED (thx to Henrik's comment) IF EXIST "D:\Windows\" IF EXIST "D:\Program Files\" ( IF NOT EXIST "D:\TP\" ( MD "D:\TP\ver 5.1\" ) MOVE "app.exe" "D:\TP\ver 5.1\" ) IF EXIST "C:\Windows\" IF EXIST "C:\Program Files\" ( IF NOT EXIST "C:\TP\" ( MD "C:\TP\ver 5.1\" ) MOVE "app.exe" "C:\TP\ver 5.1\" ) BUT then, witchcraft came to place (thx to Stephan's leadership) and solved this again MD "%systemdrive%\TP\ver 5.1\" MOVE "app.exe" "%systemdrive%\TP\ver 5.1\"
{ "pile_set_name": "StackExchange" }
Q: How many points necessary for standard deviation? First off, I'm not a mathematician, and never took statistics in college, what I know about standard deviation I've learned in the past few weeks, so be gentle... I'm working on a piece of software that calculates the standard deviation of the concentration of oxygen in a sample of water over time. I'm using a rolling numerical array of 600 doubles taken at 1 second intervals (10 minutes of data). By rolling array I mean that over time as the array fills, I increment a counter until it hits the limit of the array (600 elements), and then I reset the counter to zero to begin overwriting previous elements in the array. In this manner, as the percent oxygen settles out, the standard deviation drops over time. When the σ gets to the required level, the oxygen sensor takes a reading on the concentration of oxygen and then moves on to the next gas point. My question is: am I taking too many points? It can take a very long time for the σ to drop to the level requested for the experiment before taking a calibration reading at that gas point. Because it takes so long, I'm actually allowing the software to move to the next point when the σ is an order of magnitude greater than requested (σ = 0.02 vs σ = 0.002). If I reduce the number of elements in the array, I think the calculation would move much faster because there are simply fewer elements to calculate and the resultant dataset is smaller to manipulate. The software doesn't care what size the array is, it just calculates whatever size array is passed to it. Would reducing the number of elements in the array reduce the accuracy of the calculation significantly? Basically trading accuracy for speed? For the piece of software I'm using to calculate standard deviation, you can find it here: http://www.devx.com/vb2themax/Tip/19007. It's been slightly modified from this example, but not very much: Function ArrayStdDev(arr As Variant, Optional SampleStdDev As Boolean = True, _ Optional IgnoreEmpty As Boolean = True) As Double Dim sum As Double Dim sumSquare As Double Dim value As Double Dim count As Long Dim Index As Long ' evaluate sum of values ' if arr isn't an array, the following statement raises an error For Index = LBound(arr) To UBound(arr) value = arr(Index) ' skip over non-numeric values If value <> 0 Then ' add to the running total count = count + 1 sum = sum + value sumSquare = sumSquare + value * value End If Next ' evaluate the result ' use (Count-1) if evaluating the standard deviation of a sample If count < 2 Then ArrayStdDev = -9.99999 ElseIf SampleStdDev Then ArrayStdDev = Sqr((sumSquare - (sum * sum / count)) / (count - 1)) Else ArrayStdDev = Sqr((sumSquare - (sum * sum / count)) / count) End If End Function I hope I've asked an answerable question and appreciate any insight offered. A: Based on the various suggestions in the comments above, I reduced the number of elements in the array from 600 to 200. Empirical testing showed me that anything below 200 and the calculation spanned too short of a sample and the accurate sensor would be triggered too soon (before the ml/L of oxygen measured σ had settled enough for it to be an accurate measurement). This cascaded into modifying a number of other parameters for the water bath to accommodate the changes. This wasn't unexpected, we are after all, in the experimental stages of this new type of calibration. Thanks to the suggestions provided by you guys we're now in the tweaking part of the experiment, instead of the "why isn't this working right part". So the answer to my question seems to be "200". I was hoping for 42...
{ "pile_set_name": "StackExchange" }
Q: Can any one tell me how to set NSPredicate for NSArray having NSDictionary in Objective C? I have Structure as : [ { "time": { "td": 3036 }, "creditCardType": { "cardType": "MasterCard", "default": false }, "transactionid": { "transactionReferenceNo": "xyz", "amount": 11.62, "transactionStatus": "SUCCESS" } }, { "time": { "td": 3037 }, "creditCardType": { "cardType": "MasterCard", "default": false }, "transactionid": { "transactionReferenceNo": "xyp", "amount": 13.62, "transactionStatus": "SUCCESS" } } ] in this i have to remove duplicates with respect to transactionReferenceNo, for that i set Predicate is as: NSDictionary *transactionDict = [dict valueForKey:@"transactionid"]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY %K.%K CONTAINS[c] %@", @"transactionid", @"transactionReferenceNo",[transactionDict valueForKey:@"transactionReferenceNo"]];` this will crashes my app and gives me error: The left hand side for an ALL or ANY operator must be either an NSArray or an NSSet. what wrong m doing.. Thanks in advance. A: NSArray *arr = @[ @{ @"time": @{ @"td": @3036 }, @"creditCardType": @{ @"cardType": @"MasterCard", @"default": @NO }, @"transactionid": @{ @"transactionReferenceNo": @"xyz", @"amount": @(11.62), @"transactionStatus": @"SUCCESS" } }, @{ @"time": @{ @"td": @3037 }, @"creditCardType": @{ @"cardType": @"MasterCard", @"default": @NO }, @"transactionid": @{ @"transactionReferenceNo": @"xyp", @"amount": @(13.62), @"transactionStatus": @"SUCCESS" } } ]; NSPredicate *predicate = [NSPredicate predicateWithFormat: @"transactionid.transactionReferenceNo CONTAINS[c] %@", @"xyp"]; NSArray *arr2 = [arr filteredArrayUsingPredicate:predicate]; NSLog(@"arr2 = %@", arr2); In your case the predicate should be like this: NSPredicate *predicate = [NSPredicate predicateWithFormat: @"transactionid.transactionReferenceNo CONTAINS[c] %@", transactionDict[@"transactionReferenceNo"]];
{ "pile_set_name": "StackExchange" }
Q: Convert the language of the page Does anyone have an idea why my code is not working? I get English strings everywhere. Note that is not an ASP.NET project but an actual WinForms project. I have set up a windows forms project to use localization so that it will support Arabic and English languages. Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); Admin admin = new Admin(); this.Close(); admin.Show(); Thread.CurrentThread.CurrentUICulture = new CultureInfo("ar-KW"); Admin admin = new Admin(); this.Close(); admin.Show(); and I try this ; Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); this.Controls.Clear(); this.RightToLeftLayout = false; InitializeComponent(); Properties.Settings.Default["lang"] = "en-US"; Properties.Settings.Default.Save(); Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ar-KW"); this.Controls.Clear(); InitializeComponent(); Properties.Settings.Default["lang"] = "ar-KW"; Properties.Settings.Default.Save(); It works when I test it by starting to debug but when I set up the application it stops working. A: If your application works in debug mode and you can switch languages, then check the "bin\debug" folder and copy/deploy the language folder "ar" or "ar-KW" along with your EXE file on other machines Go to your debug folder and copy everything including all folders (except the .pdb) files to your target machine.
{ "pile_set_name": "StackExchange" }
Q: What are "$PATH" and "~/bin"? How can I have personal scripts? What is $PATH? How can I have commands/programs which are only available for me? I have seen this path ~/bin mentioned before, but what is it used for, and how do I use it? A: $PATH is an environment variable used to lookup commands. The ~ is your home directory, so ~/bin will be /home/user/bin; it is a normal directory. When you run "ls" in a shell, for example, you actually run the /bin/ls program; the exact location may differ depending on your system configuration. This happens because /bin is in your $PATH. To see the path and find where any particular command is located: $ echo $PATH /home/user/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:... $ which ls # searches $PATH for an executable named "ls" /bin/ls $ ls # runs /bin/ls bin desktop documents downloads examples.desktop music pictures ... $ /bin/ls # can also run directly bin desktop documents downloads examples.desktop music pictures ... To have your own private bin directory, you only need to add it to the path. Do this by editing ~/.profile (a hidden file) to include the below lines. If the lines are commented, you only have to uncomment them; if they are already there, you're all set! # set PATH so it includes user's private bin if it exists if [ -d "$HOME/bin" ]; then PATH="$HOME/bin:$PATH" fi Now you need to create your ~/bin directory and, because .profile is run on login and only adds ~/bin if it exists at that time, you need to login again to see the updated PATH. Let's test it out: $ ln -s $(which ls) ~/bin/my-ls # symlink $ which my-ls /home/user/bin/my-ls $ my-ls -l ~/bin/my-ls lrwxrwxrwx 1 user user 7 2010-10-27 18:56 my-ls -> /bin/ls $ my-ls # lookup through $PATH bin desktop documents downloads examples.desktop music pictures ... $ ~/bin/my-ls # doesn't use $PATH to lookup bin desktop documents downloads examples.desktop music pictures ... A: Regarding ~/bin and commands/programs only available to your user Recent Ubuntu versions include the ~/bin directory in your $PATH, but only if the ~/bin directory exists. If it does not exist: Ensure that your ~/.profile contains the following stanza (the default ~/.profile already does): # set PATH so it includes user's private bin if it exists if [ -d "$HOME/bin" ] ; then PATH="$HOME/bin:$PATH" fi Create the ~/bin directory: mkdir -p ~/bin Either reboot your computer, or force bash to re-read ~/.profile: exec -l bash
{ "pile_set_name": "StackExchange" }
Q: Structuring a firestore database to filter by what is not in the array? I have am building collection that will contain over a million documents. Each document will contain one token and a history table. A process retrieves a token, it stores the process id in the history table inside the document so it can never be used again by the same process. The tokens are reusable by different processes. I want to make each process pull a document/token and never be able to pull that same document/token again. My approach is to have a stored history table in each document with the processes that have used the token. That is why you need to query for what is not in the array. Firestore does not have a condition where you can search for what is not in an array. How would I perform a query like such below where array-does-not-contain being a placeholder to search through an array where 'process-001' is not in the history array? db.collection('tokens').where('history', 'array-does-not-contain', 'process-001').limit(1).get(); Below is how I'm planning to structure my collection, My actual problem, I have a multiple processes running and I only want each process to pull documents from firebase that it's never seen before. The firebase collection will be over a million documents and growing. A: Firestore is not very well suited for queries that need to look for things that don't exist. The problem is that the indexes it uses are only meant to tell you if things exist. The universe of strings that don't exist would be impossible to efficiently quantify for indexing. The only want to make this happen is to know the names of all the processes ahead of time, and create values for them in the index. You would do this with a map type object, not an array: - token: "1234" - history: { "process-001": false, "process-002": false, "process-003": false } This document can be queried to find out if "history.process-001" has a value of false, then updated to true when the process uses it. But again, without all the process names known ahead of time and populated in each document, the query is not possible. See also: Firestore get documents where value not in array? How to query Cloud Firestore for non-existing keys of documents
{ "pile_set_name": "StackExchange" }
Q: Apache with Require to exempt certain Files I setup a .htaccess file to require authentication for a directory. I would like to exempt certain files (csv) to avoid some issues with downloading. I can limit the authentication to the files by doing: <files ~ "\.csv$"> require valid-user </files> But how can I negate(!) them so ALL files except csv files require authentication? A: This should work: <files ~ "\..*(?<!csv)$"> require valid-user </files> I've tested this on my local server (Apache 2.2.14) and it works fine. All files except .csv files require authentication before downloading. Edit Sorry about all the edits. These sort of regular expressions are always tricky :)
{ "pile_set_name": "StackExchange" }
Q: ignore missing files in loop - data did not show up I have thousands of files as you can see the year range below. Some of the dates of the files are missing so I want to skip over them. But when I tried the method below, and calling data_in, the variable doesn't exist. Any help would be truly appreciated. I am new to python. Thank you. path = r'file path here' DataYears = ['2012','2013','2014', '2015','2016','2017','2018','2019', '2020'] Years = np.float64(DataYears) NumOfYr = Years.size DataMonths = ['01','02','03','04','05','06','07','08','09','10','11','12'] daysofmonth=[31,28,31,30,31,30,31,31,30,31,30,31] for yy in range(NumOfYr): for mm in range (12): try: data_in = pd.read_csv(path+DataYears[yy]+DataMonths[mm]+'/*.dat', skiprows=4, header=None, engine='python') print('Reached data_in') # EDIT a=data_in[0] #EDIT except IOError: pass #print("File not accessible") EDIT: Error added Traceback (most recent call last): File "Directory/Documents/test.py", line 23, in <module> data_in = pd.read_csv(path+'.'+DataYears[yy]+DataMonths[mm]+'/*.cod', skiprows=4, header=None, engine='python') File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 676, in parser_f return _read(filepath_or_buffer, kwds) File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 448, in _read parser = TextFileReader(fp_or_buf, **kwds) File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 880, in __init__ self._make_engine(self.engine) File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 1126, in _make_engine self._engine = klass(self.f, **self.options) File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/parsers.py", line 2269, in __init__ memory_map=self.memory_map, File "/opt/anaconda3/lib/python3.7/site-packages/pandas/io/common.py", line 431, in get_handle f = open(path_or_buf, mode, errors="replace", newline="") FileNotFoundError: [Errno 2] No such file or directory: 'Directory/Documents/201201/*.dat' A: You can adapt the code below to get a list of your date folders: import glob # Gives you a list of your folders with the different dates folder_names = glob.glob("Directory/Documents/") print(folder_names) Then with the list of folder, you can iterate through there contents. If you just want a list of all .dat files can do something like: import glob # Gives you a list of your folders with the different dates file_names = glob.glob("Directory/Documents/*/*.dat") print(file_names) The code above searches the contents of your directories so you bypass your problem with missing dates. The prints are there so you can see the results of glob.glob().
{ "pile_set_name": "StackExchange" }
Q: Open my app through Email Is there any way i can open my app through the email like suppose User A sends an xml file to User B through Email and when USer B click on it it open my app to extrat the tags from that xml file and show it to the User B. Please answer this question, as i am middle of completing my app. Thanks, A: You can create a custom URL scheme that your app responds to.
{ "pile_set_name": "StackExchange" }
Q: Como, usando java, deixar em negrito determinadas partes de uma TextView? Gostaria de saber como fazer para que uma determinada parte de um texto que será exibido em uma TEXTVIEW ficasse em negrito: Gostaria que o texto exibido ficasse assim: Valor total => R$ 1100. Activity: package genesysgeneration.stackall; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView tvValor; private Button btnMais100; int valor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvValor=(TextView)findViewById(R.id.tvValor); btnMais100=(Button)findViewById(R.id.btnMais100); valor=0; btnMais100.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { valor+=100; tvValor.setText(String.valueOf("Valor total => R$ " + valor + ".")); } }); } } Sei que poderia criar uma outra TextView, mas não me serve. Sei também que poderia fazer isso no .xml da TextView, mas é inviável, pois o texto é dinâmico (não tanto no exemplo, mas no meu real projeto onde quero usar isso). A: Use a classe SpannableString, ela permite anexar objectos de markup a partes especificas de um texto. TextView textView = (TextView)findViewById(R.id.textView); String label = "Valor total => "; String valor = "R$ 1100"; SpannableString textoNegrito = new SpannableString(label + valor); textoNegrito.setSpan(new StyleSpan(Typeface.BOLD), label.length(), textoNegrito.length(), 0); textView.setText(textoNegrito);
{ "pile_set_name": "StackExchange" }
Q: How to make a list in Python that ends with a trailing comma? When using mechanize to change the state of an item in a form, I need to make a list in Python like this one: ['2009', '2008', '2007', '2006', '2005', '2004',] The list must end with the trailing comma, or else it won't work. For instance, the following code works: br = mechanize.Browser() br.select_form(nr=0) br['ctl03'] = ['2009', '2008', '2007',] However, the following code does not work: br = mechanize.Browser() br.select_form(nr=0) br['ctl03'] = ['2009', '2008', '2007'] this is the error message I get when I don't use the trailing comma: Traceback (most recent call last): File "C:/Users/Renato/PycharmProjects/Agrolink/faostat.py", line 43, in <module> br['ctl03$DesktopThreePanes1$ThreePanes$ctl01$TMyears'] = ['2009', '2008', '2007'] File "C:\Python26\lib\site-packages\mechanize\_form.py", line 2782, in __setitem__ control.value = value File "C:\Python26\lib\site-packages\mechanize\_form.py", line 1977, in __setattr__ self._set_value(value) File "C:\Python26\lib\site-packages\mechanize\_form.py", line 1985, in _set_value raise TypeError("ListControl, must set a sequence") TypeError: ListControl, must set a sequence Process finished with exit code 1 Well, after dealing with this problem for an entire afternoon, I learned that this is how I could get it to do what I needed WITHOUT the trailing comma: mylist = ['2009', '2008', '2007'] br.set_value(mylist, name="ctl03") A: This doesn't make much sense - the comma is a formatting thing put in when representing the list as a string, the comma holds no value to the list itself. Do you want to change the output of the list as a string, or do something else here? If you want to have an extra 'empty' item, then you could append None to the list, for example, to emulate that. To make a string formatted with an extra comma like that, you will want to do something like this: "["+", ".join(mylist)+",]" Update for your edit: The two lines you have listed mean the exact same thing in Python - there is no way that one works and the other doesn't. The trailing comma is syntactic sugar that allows you to be lazy about writing out list literals. >>> ['2009', '2008', '2007',] == ['2009', '2008', '2007'] True Edit again: It's an actual impossibility that the trailing comma affects your code. If we disassemble the byte-code python produces: import dis def test1(): ['2009', '2008', '2007',] def test2(): ['2009', '2008', '2007'] dis.dis(test1) dis.dis(test2) Which gives us: 4 0 LOAD_CONST 1 ('2009') 3 LOAD_CONST 2 ('2008') 6 LOAD_CONST 3 ('2007') 9 BUILD_LIST 3 12 POP_TOP 13 LOAD_CONST 0 (None) 16 RETURN_VALUE 7 0 LOAD_CONST 1 ('2009') 3 LOAD_CONST 2 ('2008') 6 LOAD_CONST 3 ('2007') 9 BUILD_LIST 3 12 POP_TOP 13 LOAD_CONST 0 (None) 16 RETURN_VALUE We can see the byte code is exactly the same. The extra comma is not stored as information with the list. Given this, we can say that this is not what is affecting your code, so could you simplify your example to something we can test, with a reproducible error, we can see what the problem actually is. I cannot reproduce this behaviour: test.html: <form name="test"> <input type="checkbox" name="vehicle" value="Bike" /> I have a bike<br /> <input type="checkbox" name="vehicle" value="Car" /> I have a car </form> And then: >>> br.open("file:///path/to/test.html") <response_seek_wrapper at 0x1d74cf8 whose wrapped object = <closeable_response at 0x1f9be60 whose fp = <open file '/path/to/test.html', mode 'rb' at 0x221b9c0>>> >>> br.select_form(name="test") >>> br["vehicle"] = ["Bike", "Car",] >>> br["vehicle"] = ["Bike", "Car"] Both variants work without complaint.
{ "pile_set_name": "StackExchange" }
Q: Remove watch on YouTube logo on video I have looked around the internet for a method to remove the YouTube logo from their iFrame player. I am using <iframe width="550" height="314" src="https://www.youtube.com/embed/vidid?modestbranding=1&amp;rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe> which removes the 'watch on YouTube' button from the bottom actions panel however it adds the YouTube logo watermark to the bottom right of the video and when I hover over it says watch on YouTube. I have tried changing 'embed' to 'v' which removes it but then it doesnt work on iPad/phone. Any suggestions? A: As far as I know, the most you can do is to add the modestbranding=1 option to the URL, but this only gets rid of the title and youtube link on the top of the player. I don't think you can get rid of the bottom right one that appears when you hover. Source: https://developers.google.com/youtube/player_parameters#modestbranding
{ "pile_set_name": "StackExchange" }
Q: How to speed up file reading using SharePoint CSOM? I have created a function using the SharePoint CSOM to extract all files within a Document Collection (List) using the below code however it takes over 5 minutes to get a list of 3671 files. Is it possible to speed this up and if so How? I've seen other people use CAML Queries to extract files from a folder although I'm not 100% sure on how I would implement that static SharePointOnlineCredentials SPCreds = new SharePointOnlineCredentials("*********", new System.Net.NetworkCredential("", "*******").SecurePassword); static string sharepointURL = "https://********"; static string ListName = "Documents"; static string docuemntsStartWith = "Shared Documents"; static List<string> files = new List<string>(); static void Main(string[] args) { using (ClientContext clientContext = new ClientContext(sharepointURL)) { clientContext.Credentials = SPCreds; List list = clientContext.Web.Lists.GetByTitle(ListName); clientContext.Load(list); getFilesInFolder(clientContext, list.RootFolder); } Console.WriteLine("Extracted all " + files.Count + " files"); Console.Read(); foreach(string f in files) { Console.WriteLine(f); } Console.WriteLine("DONE"); Console.Read(); } public static void getFilesInFolder(ClientContext cc, SP.Folder SPFolder) { cc.Load(SPFolder); cc.Load(SPFolder.Folders); cc.Load(SPFolder.Files); cc.ExecuteQuery(); FolderCollection fcol = SPFolder.Folders; FileCollection filecol = SPFolder.Files; foreach (SP.File SPF in filecol) { files.Add(SPF.ServerRelativeUrl); } foreach (SP.Folder SPF in fcol) { getFilesInFolder(cc, SPF); } } A: Try below code this uses CAML query : using System; using Microsoft.SharePoint.Client; using SP = Microsoft.SharePoint.Client; namespace Microsoft.SDK.SharePointServices.Samples { class RetrieveListItems { static void Main() { string siteUrl = "http://gauti.sharepoint.com/sites/SP"; ClientContext clientContext = new ClientContext(siteUrl); SP.List oList = clientContext.Web.Lists.GetByTitle("NewBook"); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><Geq><FieldRef Name='ID'/>" + "<Value Type='Number'>19</Value></Geq></Where></Query><RowLimit>100</RowLimit></View>"; ListItemCollection collListItem = oList.GetItems(camlQuery); clientContext.Load(collListItem); clientContext.ExecuteQuery(); foreach (ListItem oListItem in collListItem) { Console.WriteLine("ID: {0} \nTitle: {1} \nBody: {2}", oListItem.Id, oListItem["Title"], oListItem["Body"]); } } } }
{ "pile_set_name": "StackExchange" }
Q: Recover data table I made an example of what I need at this link enter link description here retrieving the code var totalRows = $('#tblCatalogo tbody tr').length; for(var i=1; i<=totalRows;i++){ var rs = $('#tblCatalogo tbody tr').children().data('cod'); $('#result').append(rs); } A: $(function(){ $('#tblCatalogo tbody tr').find("span[data-cod]").each(function (){ $('#result').append($(this).data("cod")); }); }); http://jsfiddle.net/Q4qJy/10/
{ "pile_set_name": "StackExchange" }
Q: Перемещение объектов в рабочий поток Если создать рабочий поток в довесок к главному и переместить в него некий объект некоего класса, а этот перемещенный объект создаст в свою очередь другой объект другого класса, то в каком потоке будет этот второй объект? A: Будет в потоке своего "создателя"
{ "pile_set_name": "StackExchange" }
Q: Android Views Drawing In Canvas I am creating my own view and drawing a bitmap in the canvas.If I set it at say (100,100) it is fine on a 320*480 screen but on bigger 480*800 it does not show up in the same place. How can I get it to be at the same place.I have searched Google much but can't find a solution. Any tips? Tutorials? Thanks A: You can use this method in your custom view to get the exact size of the canvas. Then you can calculate the position and the size of the rectangle where you will draw you bitmap. @Override public void onSizeChanged (int w, int h, int oldw, int oldh){ super.onSizeChanged(w, h, oldw, oldh); canvasW = w; canvasH = h; } You can also resize your bitmaps within this method to accomodate the size of the canvas. Even though your canvas may take the full screen, in Android 3.0 there is a bar on the bottom which will take some space, hence onSizeChanged gives a real size of the canvas.
{ "pile_set_name": "StackExchange" }
Q: How to handle user inputs synchronously in Node.js I know this may come across as a 'Noob Question', and I apologize in advance for asking something so simple. But I haven't been able to find much on this topic when searching online. I'm trying to write a command line app in Node.js, however I haven't been able to figure out how to handle user input synchronously. I tried using async/await, but those seemed to have no effect. Instead I moved to promises, however the following code errors out with: TypeError: promise.resolve is not a function. Reading the MDN it shows the Promise API as being new Promise(resolutionFunc, rejectionFunc). With those functions being called on resolution and rejection respectively. I'm not quite sure what I'm doing wrong, but from what I understand it should only be executing the .then() after the previous promise is resolved. However that is not the case here: My Code: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); let numbs = []; function getInput(i) { let promise = new Promise((resolve) => { numbs[i] = resolve; }, (reject) => { // do nothing, shouldn't happen }); rl.question(`Input #${i+1}: `, (input) => { promise.resolve(Number.parseInt(input)); }); return promise; } getInput(0) .then(getInput(1)) .then(() => { console.log(numbs) /* rest of the program using those 2 inputs */ }) .catch((err) => { // do nothing, and exit }); Output: $ node .\file.js Input #1: Input #1: [path removed]/file.js:18 promise.resolve(Number.parseInt(input)); ^ TypeError: promise.resolve is not a function at [path removed]/file.js:18:17 at Interface._onLine (readline.js:335:5) at Interface._normalWrite (readline.js:482:12) at ReadStream.ondata (readline.js:194:10) at ReadStream.emit (events.js:315:20) at addChunk (_stream_readable.js:296:12) at readableAddChunk (_stream_readable.js:272:9) at ReadStream.Readable.push (_stream_readable.js:213:10) at TTY.onStreamRead (internal/stream_base_commons.js:186:23) A: There are several things wrong here: As you can see from the error, a regular promise does not have a .resolve() method and that isn't a correct way to wrap r1.question() in a promise. This isn't correct then(getInput(1)). You need to pass a function reference to .then() so it can be called later. Here's a way to fix those problems: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); function getInput(i) { return new Promise(resolve => { rl.question(`Input #${i+1}: `, (input) => { resolve(+input); }); }); } let nums = []; getInput(0).then(val => { nums.push(val); return getInput(1); }).then(val => { nums.push(val); console.log(nums) /* rest of the program using those 2 inputs */ }).catch((err) => { console.log(err); }); A simpler version uses async/await which are really convenient for serializing asynchronous operations: const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false }); function getInput(i) { return new Promise(resolve => { rl.question(`Input #${i+1}: `, (input) => { resolve(+input); }); }); } async function run() { let v1 = await getInput(0); let v2 = await getInput(1); console.log(v1, v2); } run().catch((err) => { console.log(err); }); Note, your code isn't detecting if the user entered something other than a number and your code doesn't terminate the readline stream.
{ "pile_set_name": "StackExchange" }
Q: Angular JS not a function , got undefined in ng-view When including angular scripts (e.g. Controller.js) not normal scripts in angular view it does not work (not a function, got undefined error) , while if i add them in the main view , it works , does any one know what's the problem A: You have to include all scripts in the main index.html file, not in a template loaded by ng-view or ui-view. The views get loaded dynamically, so it'll give you problems.
{ "pile_set_name": "StackExchange" }
Q: can we throw the exception object to calling method even after catching it in the catch block? Consider a sample code: public void someMethod() throws Exception{ try{ int x = 5/0; //say, or we can have any exception here } catch(Exception e){ if(counter >5){ // or any condition that depends on runtime inputs //something here to throw to the calling method, to manage the Exception } else System.out.println("Exception Handled here only"); } } So is something like this possible? if yes then how, what is to be out in place of "something here to throw to the calling method, to manage the Exception"... I.E. my question is can we conditionally manage like this , that we want to handle the exception here or not. A: Sure, you can throw in your catch block no problem. You can even layer in your own useful exception and maintain your exception causal chain using the Throwable(String message, Throwable cause) constructor. For example let's say you had a special RetryLimitReachedException, you could toss it out like so catch (Exception e) { if (counter > 5) { throw new RetryLimitReachedException("Failed to do X, retried 5 times", e); } .... } In your stacktrace you'll be able to clearly see that this class was unable to handle it, and so passed it back up. And you'll be able to see what exactly caused the unhandleable exception condition in the Caused By. . . line(s) of the stacktrace.
{ "pile_set_name": "StackExchange" }
Q: Typescript drop unknown[] or never? I am trying to make tuple of A and B or only B if A is unknown[] (or alternativately never) type X<A, B> = A extends unknown[] ? [B] : [A, B]; type Y = X<unknown[], {}>; // should be [{}] but isn't variation: type X<A, B> = A extends never ? [B] : [A, B]; type Y = X<never, {}>; // should be [{}] but isn't this only works: type X<A, B> = A extends null ? [B] : [A, B]; type Y = X<null, {}>; // it is [{}] A: Take a look how unknown and never types behave in relation to other types: type ExtendsUnknown<X> = X extends unknown ? true : false; type YesUnknown = ExtendsUnknown<number>; // true type YesUnknown2 = ExtendsUnknown<object>; // true type YesUnknown3 = ExtendsUnknown<[number]>; // true type YesUnknown4 = ExtendsUnknown<unknown>; // true type ExtendsNever<X> = X extends never ? true : false; type NoNever = ExtendsNever<number>; // false type NoNever2 = ExtendsNever<object>; // false type NoNever3 = ExtendsNever<[number]>; // false type OhMyGodNever = ExtendsNever<never>; // we get never och man! Types like any never unknown are unsound types. It means that they do not behave in the same way as standard types, they behavior can be against the logic which derives other types. What I mean by this logic is for example: if A extends B extends C implies that A extends C if A extends B and B extends A implies A equals B above rules are only guaranteed for sound types That is why for your case, u should use sound types, and I would propose here undefined type. // undefined behaves correctly type ExtendsUndefined<X> = X extends undefined ? true : false; type NoUndefined = ExtendsUndefined<number>; // false type NoUndefined2 = ExtendsUndefined<object>; // false type NoUndefined3 = ExtendsUndefined<number>; // false type YesUndefined4 = ExtendsUndefined<undefined>; // true - yep that works type X<A, B> = A extends undefined ? [B] : [A, B]; type Y = X<undefined, {}>;
{ "pile_set_name": "StackExchange" }
Q: How far do I need to move to break Nether Portal link? I've built a Nether Portal near my residence, but after going through it, I find myself on top of a small floating island above a lake of lava. There's no way to get to the main land area. I've tried going far far away from my original Portal and creating a new one, but it still keeps linking back to the original and I find myself on the same island. Once, another end Portal was created on the same island. My question is, how far away (how many blocks) do I need to get from my first portal to finally get onto the main land? Any help is appreciated. If it helps, here are my coordinates from my main home: x: 570 y: 64 z: 72.83 A: The distance that your new portal needs to be away from the old one isn't terribly large, only 128 blocks, but it's measured in terms of the destination world; every block in the Nether is worth eight in the overworld, meaning you'll need to move around 1024 blocks or so away to keep a new portal from joining the one that already exists in the Nether. I say "around 1024 blocks or so", because the existing portal on the nether side may already be some distance away from the location that would best match up with the existing Overworld portal. There are, however, a few other options. You could try building a bridge across the lava on the Nether side. Painful and awkward, but once across, you could build a new Nether portal on that end, destroy the Nether-side one that exists (just punching it to turn it off should suffice), and hope that the new Nether-side portal successfully connects to your existing one. Alternatively, you might be able to make a suicide run through the portal, destroy the island so it's no longer a valid spot (and also destroy the portal on that side, too), then once you die and respawn on the Overworld side, a quick trip through should trigger the creation of a whole new Nether-side portal, which might not be in such a poor location. A: According to the Minecraft Wiki's entry on Nether Portals: First, the game converts the entry coordinates into destination coordinates as above: The entry X- and Z-coordinates are floored, then multiplied or divided by 8 (or 3) depending on direction of travel. The Y-coordinate is not changed. Starting at these destination coordinates, the game looks for the closest active portal. It searches a bounding area of 128 horizontal blocks from the player, and the full map height (128 for the Nether, 256 for the Overworld). This gives a search area of 257 blocks by 257 blocks, at the full height of the dimension being traveled to. An active portal for this purpose is defined as a portal block which does not have another portal block below it, thus only the 2 lowest portal blocks in the obsidian frame are considered. A single portal block spawned in and placed using server commands would be a valid location. If a candidate portal is found, then the portal will teleport the player to the closest one as determined by the distance in the new coordinate system (including the Y coordinate, which can cause seemingly more distant portals to be selected). Note that this is Euclidian distance, not taxicab distance. Note that a portal above Y=128 in the Overworld will generally not be found unless there are no lower portals nearby. The distance computation between portals in range is a straight-line distance calculation, and the shortest path will be chosen, counting the Y difference. Distance is calculated in the dimension that you are going to, you you need to multiply by 8. 128*8=1024. Because the portal might have been adjusted, you need to go even further away, say 1100 blocks. This will spawn you somewhere else in the Nether. Another thing to consider is that you could make a minecart system in the Nether, which will take you to the main land in a considerably short amount of time. The same could be done with a bridge for horses and the like.
{ "pile_set_name": "StackExchange" }
Q: rails5 `filter_parameters` doesn't work I have the following in my config/initializers/filter_parameter_logging.rb # Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password, :reset_password_token, :confirmation_token, :unlock_token, :two_step_auth_token] But when I execute and update for two_step_auth_token column the log is not filtered, even though I restarted the server: UPDATE `users` SET `two_step_auth_token` = 'tb0437', `two_step_auth_token_sent_at` = '2017-04-29 20:12:49', `two_step_auth_token_confirmed_at` = NULL, `updated_at` = '2017-04-29 20:12:49' WHERE `users`.`id` = 1 What is wrong and how can I fix it? A: You can filter out sensitive request parameters from your log files, not a sql queries. ref
{ "pile_set_name": "StackExchange" }
Q: How to prove: If $n \in N$, then $n^2=2\binom{n}{2} + \binom{n}{1}$ Prove using a direct proof method: If $n \in N$, then $n^2=2\binom{n}{2} + \binom{n}{1}$. I would assume that the proof uses the Binomial Theorem, however I don't know how to apply it in this context. Perhaps it is something in regard to: $$n^2 = (2n-n)^2$$ $$n^2 = \binom{n}{0}(2n)^n(-n)^0 + \binom{n}{1}(2n)^{n-1}(-n) + \binom{n}{2}(2n)^{n-2}n^2$$ $$n^2 = (2n)^n - n^2(2n)^n \frac{1}{(2n)} + \frac{n^3(n+1)}{2}(2n)^n \frac{1}{(2n)^2} $$ $$...$$ A: Use the fact that $2\binom n2=2\frac{n(n-1)}2=n^2-n.$
{ "pile_set_name": "StackExchange" }
Q: Why my Update sql Command don't work? i have problems with a sql command in mysql. I have a asp.net applcation and use a mysql database as database. I want to built a class that can insert,update,delete and select the records in the database. I have problems with the update command. In phpmyadmin it works but in my class not :/ Here is my code public void UpdateRecord(string title, string firstname, string lastname, string company, string timefrom, string timeto) { connection = new MySqlConnection(); try { MySqlCommand command = connection.CreateCommand(); //for testing string sql = "UPDATE 'tb_gast' SET FIRSTNAME='test' WHERE ID=270"; command.CommandText = sql; connection.Open(); command.ExecuteNonQuery(); } catch (Exception) { } finally { connection.Close(); } } this command work in phpmyadmin UPDATE `tb_gast` SET FIRSTNAME='uu', LASTNAME='uu', COMPANY='uu' WHERE ID=270 A: You are using single quote around the tablename, instead of backticks. The backtick could be typed using the key combination ALT+096 UPDATE `tb_gast` SET FIRSTNAME = 'test' WHERE ID=270 EDIT: Looking at your question more in deep. Noticed that you declare a MySqlConnection and initialize it WITHOUT any connection strings. If this is your real code no wonder that it doesn't work This is how your code should be using(connection = new MySqlConnection(GetConnectionString()) { connection.Open(); using(MySqlCommand command = connection.CreateCommand(); { //for testing string sql = "UPDATE `tb_gast` SET FIRSTNAME='test' WHERE ID=270"; command.CommandText = sql; command.ExecuteNonQuery(); } } where GetConnectionString() should be some method that returns your connection string from some permanent storage like a configuration file
{ "pile_set_name": "StackExchange" }
Q: .htaccess mod_rewrite subdirectory to URL parameter I hope this was not asked over and over again before, but I didn't get further to an answer using google, w3schools and so on. So here is my question: I'm writing a script that creates kind of an index of projects that I have on my homepage and makes a nice list with images and teaser text based on an info file. I mostly have my projects on github and the readme is in markdown so I thought I could dynamically generate the HTML from the markdown of the latest blob from github on demand using PHP so it gets updated automatically. My directory structure looks like this: projects project1 .remoteindex .info project2 .remoteindex .info index.php .htaccess So when just domain.tld/projects/ is requested I get the info from .info and make a nice index of all projects. But if domain.tld/projects/project1/ is request it, I want to internally redirect it to domain.tld/projects/?dir=project1 to do my markdown parsing and so on. But domain.tld/projects/project1/image.png should not be redirected. This is what I tried: .htaccess RewriteEngine on RewriteRule ^([^/]+)/?$ index.php?dir=$1 [R,L] I made it redirect instead of rewrite so that I can see what the error is because I just got an 404. The URL that I get redirected to is domain.tld/home/www/web310/html/projects/index.php?dir=project1 so obviously there is something going wrong with the internal structure of the web server an paths an whatever. I hope you can understand my problem an I would be very pleased if someone could help me, because I'm totally lost on .htaccess anyway. Edit: See my answer below for the used .htaccess. The strange thing is that if I have an index.html in on of the subdirectories, my local web server (Apache with XAMPP for Mac OS X 1.7.3) does not rewrite and the index.html gets displayed, without one it works correctly.But on my real web server that serves my homepage it rewrites both with and without index.html (which is what I want). Any hints on that? A: Thanks for all the help so far! You guys are just awesome! I figured out that a symbiosis of both of your solutions works well for me: RewriteEngine on RewriteBase /projects RewriteCond %{SCRIPT_FILENAME} !-f RewriteCond %{SCRIPT_FILENAME} -d RewriteRule ^([^/]+)/?$ index.php?dir=$1 [QSA,L] Of course only without [R], this was my fault. (See my question edit for another question please).
{ "pile_set_name": "StackExchange" }
Q: I want to find the correct way for using object oriented in php why this code does not print the value. class Test{ var $i; function Test($i){ $this->i=$i; } function func1(){ echo $i; } } $ob1=new Test(4); $ob1->func1(); ?> Here I am using object oriented concept A: You should echo $this->i not $i function func1() { echo $this->i; } Output 4 A: Replace function func1(){ echo $i; } with function func1(){ echo $this->i; } and will work fine try to learn using http://php.net/manual/en/language.oop5.php http://www.tutorialspoint.com/php/php_object_oriented.htm
{ "pile_set_name": "StackExchange" }