source
list
text
stringlengths
99
98.5k
[ "stackoverflow", "0030488838.txt" ]
Q: How to get a value of a CheckBox from td (table), JavaScript? I have a table with text data but in one cell I have a checkbox. I can extract data from td, but I can't figure out how to extract the checkbox value Here's what I've tried (see attached picture!) $('#tableData tbody tr:eq('+row+')').find('td:eq(8)').eq(0).value https://drive.google.com/file/d/0BxKM9sqBGY28cXp5ZzVCc0dRc28/view?usp=sharing A: $('#tableData tbody tr:eq('+row+')').find('td:eq(8) input').is(':checked')
[ "stackoverflow", "0008041537.txt" ]
Q: How to reference style attributes from a drawable? I want to have 2 selectable themes for my application. In order to do that, I defined some attributes, like this: <attr format="color" name="item_background" /> Then, I created both themes, like this: <style name="ThemeA"> <item name="item_background">#123456</item> </style> <style name="ThemeB"> <item name="item_background">#ABCDEF</item> </style> This method works great, allowing me to create and modify several themes easily. The problem is that it seems that it can be used only in Views, and not in Drawables. For example, referencing a value from a View inside a layout works: <TextView android:background="?item_background" /> But doing the same in a Drawable doesn't: <shape android:shape="rectangle"> <solid android:color="?item_background" /> </shape> I get this error when running the application: java.lang.UnsupportedOperationException: Can't convert to color: type=0x2 If instead of ?item_background I use a hardcoded color, it works, but that doesn't allow me to use my themes. I also tried ?attr:item_background, but the same happens. How could I do this? And why does it work in Views but not in Drawables? I can't find this limitation anywhere in the documentation... A: In my experience it is not possible to reference an attribute in an XML drawable. In order to make your theme you need to: Create one XML drawable per theme. Include the needed color into you drawable directly with the @color tag or #RGB format. Make an attribute for your drawable in attrs.xml. <?xml version="1.0" encoding="utf-8"?> <resources> <!-- Attributes must be lowercase as we want to use them for drawables --> <attr name="my_drawable" format="reference" /> </resources> Add your drawable to your theme.xml. <style name="MyTheme" parent="@android:style/Theme.NoTitleBar"> <item name="my_drawable">@drawable/my_drawable</item> </style> Reference your drawable in your layout using your attribute. <TextView android:background="?my_drawable" /> A: Starting with lollipop (API 21) this feature is supported, see https://code.google.com/p/android/issues/detail?id=26251 However, if you're targeting devices without lollipop, don't use it, as it will crash, use the workaround in the accepted answer instead. A: Although it's not possible to reference style attributes from drawables on pre-Lollipop devices, but it's possible for color state lists. You can use AppCompatResources.getColorStateList(Context context, int resId) method from Android Support Library. The downside is that you will have to set those color state lists programmatically. Here is a very basic example. color/my_color_state.xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:color="?colorControlActivated" /> <item android:color="?colorControlNormal" /> </selector> A widget that needs a color state list: <RadioButton android:id="@+id/radio_button" android:text="My Radio" /> And the most important: ColorStateList csl = AppCompatResources.getColorStateList(context, R.color.my_color_state); RadioButton r = (RadioButton) findViewById(R.id.radio_button); r.setTextColor(csl); Well, not the most elegant or shortest way, but this is what Android Support Library does to make it work on older versions (pre-Lollipop) of Android. Unfortunately, the similar method for drawables doesn't work with style attributes.
[ "stackoverflow", "0023535189.txt" ]
Q: How to open save dialog box instead of file getting opened in browser for my Sharepoint site My site is developed in SharePoint 2010. In my Testing site, <a href="file.pdf" target="_blank">Download File</a> when click on the above a tag, file opens directly in browswer(IE/Chrome/FireFox) But same a tag is used in my Live site where it ask to save file(In IE) or gets downloaded(in Chrome). A: For link on file use standard SharePoint download.aspx page. <a href="http://yourSite/_layouts/download.aspx?SourceUrl=http://pathToFile" target="_blank">Download File</a> Download.aspx will read the content of the file you send as the SourceUrl, and render it back to you on the HTTP response. Hope that helps
[ "stackoverflow", "0053369030.txt" ]
Q: R: Why can't use dimnames() to assign dim names fg = read.table("fungus.txt", header=TRUE, row.names=1);fg names(dimnames(fg)) = c("Temperature", "Area");names(dimnames(fg))#doesn't work dimnames(fg) = list("Temperature"=row.names(fg), "Area"=colnames(fg));dimnames(fg) #doesn't work You can look at the picture of data I used below: Using dimnames() to assign dim names to the data.frame doesn't work. The two R command both do not work. The dimnames of fg didn't change, and the names of dimnames of fg is still NULL. Why does this happen? How to change the dimnames of this data.frame? A: Finally I found change the data frame to matrix works well. fg = as.matrix(read.table("fungus.txt", header=TRUE, row.names=1)) dimnames(fg) = list("Temp"=row.names(fg), "Isolate"=1:8);fg And got the output: Isolate Temp 1 2 3 4 5 6 7 8 55 0.66 0.67 0.43 0.41 0.69 0.63 0.46 0.52 60 0.82 0.81 0.80 0.79 0.85 0.91 0.53 0.66 65 0.91 1.09 0.81 0.86 0.95 0.93 0.64 1.10 70 1.02 1.22 1.03 1.08 1.10 1.13 0.80 1.17 75 1.06 1.17 0.89 1.02 1.06 1.29 0.94 1.01 80 0.80 0.81 0.73 0.77 0.80 0.79 0.59 0.95 85 0.26 0.40 0.36 0.53 0.67 0.53 0.57 0.18 Reply to the comments: if you do not know anything about the code, then do not ask me why I post such a question.
[ "stackoverflow", "0040472540.txt" ]
Q: Understanding Azure CloudTableClient: Forbidden(403) Exception Read access through Azure Storage Explorer or regular browser works for the on-hand SAS token. Console access is throwing a Forbidden (403) exception. Code as below for the referenced appconfig: <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <appSettings> <add key="SASToken" value="sv=[REMOVED]&amp;tn=[REMOVED]&amp;sig=[REMOVED]&amp;se=[REMOVED]&amp;sp=r" /> </appSettings> </configuration> Code as below for the console app: StorageCredentials accountSAS = new StorageCredentials(CloudConfigurationManager.GetSetting("SASToken")); CloudStorageAccount accountWithSAS = new CloudStorageAccount(storageCredentials: accountSAS, accountName: "acccount-name", endpointSuffix: "core.windows.net", useHttps: true); CloudTableClient tableClient = accountWithSAS.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("TableName"); if (table.Exists() == true) { Console.WriteLine("Table Exists."); } else Console.WriteLine("Table Does not Exist."); A: From my experience, 403 error indicates that it has no permission to do that. It means that with Service (table) SAS that has no permission to check whether the table is existing. If we want to check if the table is existing, we need storage Account level SAS but not the Service (table) SAS. More info please refer to types of shared access signatures. Although we don’t have the permission to check whether table is existing, we still have the access that SAS assigned. we also can use table query to retrieve the table records. e.g. var result = table.ExecuteQuery(new TableQuery {TakeCount =5}); It will get the similar result with the regular browser does.
[ "stats.stackexchange", "0000229730.txt" ]
Q: Histogram equalization for vision task preprocessing I'm interested in performing image pre-processing for various computer vision tasks, and have a question about histogram equalization. As I understand it, histogram equalization is a non-linear function applied to the image with the intention of increasing contrast. This is generally applied per-image, using the YCbCr color space (equalize using the Y channel), and is either done to match a normally distributed histogram (Gaussian) or uniformly distributed histogram (flat). My question is, which is preferred for vision tasks such as image recognition? My intuition is that a Gaussian histogram would amplify less noise given its flat tails (and so would be preferred), but I am interested in a more theoretical or at least empirical reason. It would be also helpful if there was a good metric for the "flatness" or distribution of a histogram. This would be very helpful when expressing the behavior of my equalization function. A: Unfortunately, the answer to this question is a great big "it depends". If the images you are working with tend to be pretty flat with no large humps, then a uniform distribution might be for you. If it has a single peak, a Gaussian could be good. However, it may also be the case that normalization using either of these methods could cause you to lose signal. There was a paper out of Stanford looking at image processing in pathology that found that many of the commonly used methods in the field actually caused a loss of signal. If you want to use a histogram normalization method, your most important first step should be looking at a bunch of your image histograms. If, for example, your histograms look bimodal, those two peaks could be characterizing unique elements of your data, so squeezing them into either a uniform or a Gaussian distribution could remove a lot of signal. For this reason, some histogram equalization methods will choose their target distribution to be one of the images in the sample set so that the basic shape remains intact. One peice of advice I would give is to look into an adaptive histogram equalization methods like AHE or even better CLAHE. These methods normalize each pixel based on the pixels in their local neighborhood, so they have less of a tendency to distort the image based on outlier tails, and they keep more of the shape of the original histogram while still moving the image into a normalized space. Also in my experience with these methods, the choice of the target distribution tends to matter much less than in non adaptive methods (though I generally find a Rayleigh distribution to do well). In the end, I feel that when it comes to normalization methods the the proof of the pudding is in the eating. Try a couple of different things and see how it effects your outcome. Gather a few of your images that should have the same properties but have different lighting artifacts and see if features you want to collect from them are more similar after normalization (the Stanford paper has examples of metrics for this). The thing you should not do is visually inspect the images to see which seem more "normalized" to you because computers look at very different things than humans do. Computers "see" texture very well, and humans are particularly awful at seeing texture, so your visual analysis will likely miss everything the computer is using to characterize the images. Finally, as for tests for histogram "flatness", your best bet would be a Chi Squared test with your target being a discrete uniform distribution. However, I would note that like many tests for fit of theoretical distributions, for larger values of N, you almost always will reject the null hypothesis. The theoretical distributions are "perfect" so it doesn't take much deviance from that to call for rejection. These aren't tests for "uniformish" data, so perfectly uniform data except for a small outlier on the tail will be all you need for rejection. While less quantitative, a Q-Q plot can often be more useful in determining how well your data fit a distribution.
[ "stackoverflow", "0028509709.txt" ]
Q: OpenCV: Draw Lines from Canny I'm a complete novice when it comes to OpenCV, so this is probably a dumb question. I'm just trying to get something basic up and running- I want to draw the edges detected by the Canny algorithm directly on the image coming in. I currently have this: I'm displaying the edge data from Canny directly, but now I want to get rid of the black and just show the white, on the image being processed. I've tried googling things like "using binary image as alpha mask", but after a day of reading tutorials and trying everything I can find, I'm still not sure I know what's going on. OpenCV seems very powerful, so this is probably a pretty easy thing to do, so I'm hoping somebody can point me in the right direction. Here's the code I'm using, most of which has been copied from the examples: public Mat onCameraFrame(CvCameraViewFrame inputFrame) { Mat rgba = inputFrame.rgba(); org.opencv.core.Size sizeRgba = rgba.size(); Mat rgbaInnerWindow; int rows = (int) sizeRgba.height; int cols = (int) sizeRgba.width; int left = cols / 8; int top = rows / 8; int width = cols * 3 / 4; int height = rows * 3 / 4; //get sub-image rgbaInnerWindow = rgba.submat(top, top + height, left, left + width); //create edgesMat from sub-image Imgproc.Canny(rgbaInnerWindow, edgesMat, 100, 100); //copy the edgesMat back into the sub-image Imgproc.cvtColor(edgesMat, rgbaInnerWindow, Imgproc.COLOR_GRAY2BGRA, 4); rgbaInnerWindow.release(); return rgba; } Edit: I've also posted this question on the OpenCV forums here. A: I've not used Java in more than a decade, and have not used Java with OpenCV at all, but I'm going to try to lay out how I would do this. I'm doing my best to write it in this language, but if I'm not quite getting it right I expect you'll be able to make those minor changes to get it working. As I see it your order of operations after running Canny should be thus: Copy your edgesMat and convert that to BGRA. ( call it colorEdges) Replace the white in colorEdges with the color of your choice (the color you want drawn on the video feed) using edgesMat as a mask. Then drop colorEdges back on rgbaInnerWindow using edgesMat as a mask. The code: //step 1 Mat colorEdges; edgesMat.copyTo(colorEdges); Imgproc.cvtColor(colorEdges, colorEdges, COLOR_GRAY2BGRA); //step 2 newColor = new Scalar(0,255,0); //this will be green colorEdges.setTo(newColor, edgesMat); //step 3 colorEdges.copyTo(rgbaInnerWindow, edgesMat); //this replaces your current cvtColor line, placing your Canny edge lines on the original image That oughta do it. :) copyTo (Mat m) cvtColor (Mat src, Mat dst, int code) setTo (Mat value, Mat mask) copyTo (Mat m, Mat mask)
[ "stackoverflow", "0042264788.txt" ]
Q: Using conditional Sub-Arrays using VueJS I would like to know how to use Vuejs to output a conditional sublist. In this example, not all topics have a subtopic. new Vue ({ el: '#maincontainer', data: { topics: [ { topicname: 'Introduction' }, { topicname: 'First Chapter', subtopics: [ {subtopicname: 'Test'} ] }, ] } }); My HTML so far looks like this: <li v-for="topic in topics" id="item-{{$index}}"> {{ topic.topicname }} <ul> <li v-for="subtopic in subtopics"> {{ subtopic.subtopicname }} </li> </ul> </li> How might I have the list optionally add a sublist if there is one in the data? A: v-if is the directive to be used for conditional rendering. Here you could use v-if='topic.subtopic' too (as long as the value of the expression evaluates to a truthy boolean value if subtopic existed.) <li v-for="topic in topics" id="item-{{$index}}"> {{ topic.topicname }} <ul v-if='Array.isArray(topic.subtopic)'> <li v-for="subtopic in topic.subtopics"> {{ subtopic.subtopicname }} </li> </ul> </li> You might also be interested in v-else
[ "math.stackexchange", "0000730392.txt" ]
Q: Nontechnical(!) Proof for Relative Closure Nontechnical(!) Proof: $\overline{A}^X\subseteq S\Rightarrow\overline{A}^S=\overline{A}^X$ ...while $A\subseteq S\subseteq X$ Background: $\overline{A}^S\subseteq S\nRightarrow\overline{A}^S=\overline{A}^X$ ...while $A\subseteq S\subseteq X$ Moreover, just for fun, can u proof: $\overline{A}^S\subseteq\overline{A}^X$ ...while $A\subseteq S\subseteq X$ (I did that, but using construction of closure as smallest closed set containing it.) I need this for parts of the construction of partition of unit... A: Proposition: Let $X$ a topological space, and $A \subset S \subset X$. Then $\overline{A}^S = S\cap \overline{A}^X$. Proof: $S\cap \overline{A}^X$ is a relatively closed subset of $S$ containing $A$, hence $\overline{A}^S \subset S\cap \overline{A}^X$. On the other hand, $\overline{A}^S$ is a relatively closed subset of $S$, hence there is a closed (in $X$) subset $F$ with $\overline{A}^S = S\cap F$. Since $A\subset \overline{A}^S$, it follows that $A\subset F$ and hence $\overline{A}^X\subset F$, whence $S\cap \overline{A}^X \subset S\cap F = \overline{A}^S$.
[ "stackoverflow", "0045794563.txt" ]
Q: Vectorise R code to randomly select 2 columns from each row Does anyone have suggestions of how I could vectorise this code or otherwise speed it up? I'm creating a matrix, potentially very large. In each row, I want to select 2 columns at random, and flip them from 0 to 1. I cannot select the same row and column number, i.e. the diagonal of the matrix will be zero hence the (1:N)[-j] in sample(). Because this changes with each row, I can't see a way to do this by using vectorisation, but parallelisation could be an option here? I use library(Matrix) for sparse matrix functionality. library(Matrix) N <- 100 m <- Matrix(0, nrow = N, ncol = N) for(j in 1:N) { cols <- sample((1:N)[-j], 2) #Choose 2 columns not equal to the m[j, cols] <- 1 } Any ideas? A: library(Matrix) N <- 7 desired_output <- Matrix(0, nrow = N, ncol = N) set.seed(1) for(j in 1:N) { cols <- sample((1:N)[-j], 2) #Choose 2 columns not equal to the desired_output[j, cols] <- 1 } # 7 x 7 sparse Matrix of class "dgCMatrix" # # [1,] . . 1 . . . 1 # [2,] . . . . 1 1 . # [3,] . 1 . . . 1 . # [4,] . . . . 1 . 1 # [5,] 1 . . 1 . . . # [6,] 1 1 . . . . . # [7,] . 1 . . 1 . . res <- Matrix(0, nrow = N, ncol = N) set.seed(1) ind <- cbind(rep(1:N, each = 2), c(sapply(1:N, function(j) sample((1:N)[-j], 2)))) res[ind] <- 1 all.equal(res, desired_output) # [1] TRUE Quick bench: microbenchmark::microbenchmark( OP = { desired_output <- Matrix(0, nrow = N, ncol = N) set.seed(1) for(j in 1:N) { cols <- sample((1:N)[-j], 2) #Choose 2 columns not equal to the desired_output[j, cols] <- 1 } }, Aurele = { res <- Matrix(0, nrow = N, ncol = N) set.seed(1) ind <- cbind(rep(1:N, each = 2), c(sapply(1:N, function(j) sample((1:N)[-j], 2)))) res[ind] <- 1 } ) # Unit: milliseconds # expr min lq mean median uq max neval cld # OP 10.240969 10.509384 11.065336 10.804949 11.044846 14.903377 100 b # Aurele 1.185001 1.258037 1.392021 1.363503 1.434818 4.553614 100 a
[ "stackoverflow", "0040222029.txt" ]
Q: Bind dynamically set ng-model attribute for text field After searching around for hours I am still unable to find an answer to my problem. I am populating a dynamic form with text fields based on values from a database, but am unable to successfully bind the fields to my model. Here's the scenario: I've got a "project" model in my controller containing lots of project related information (name, start date, participants, category etc), but let's just focus on the "project.name" property for now. In the database I configure "forms" with a number of associated fields, where each field has a property that points to which property it corresponds to in my view model (e.g. "project.name"). At runtime I add these fields to an HTML form dynamically and attempt to set the ng-model attribute to the "modelBinding" value, in this case "project.name". <div ng-repeat="formField in form.formFields"> <input ng-model="formField.modelBinding" /></div> This will result in a text box being added to my form, with ng-model="formField.modelBinding" and the textbox value = 'project.data'. What I am trying to achieve is to set ng-model = 'project.data', in other words replace formField.modelBinding with the value of formField.modelBinding. One approach that seemed logical was <input ng-model = "{{formField.modelBinding}}" /> but this is obviously not going to work. I've tried to insert the HTML tags with ng-bind-html but this seems to only work with ng-bind, not ng-model. Any suggestions? A: Assuming that you are trying to bind a value to a model from a name that you have within the formField you can create a directive (aka ngModelName) to bind your model by name from this value. Observation: My first thought was using a simple accessor like model[formField.modelBinding] which would simple bind the formField.modelBinding into a model member on scope. However, I didn't use the property accessor because it would create a property named by formField.modelBinding value and not the correct object hierarchy expected. For example, the case described on this question, project.data would create an object { 'project.data': 'my data' } but not { 'project': { data: 'my data'}} as it should. angular.module('myApp', []) .directive('ngModelName', ['$compile', function ($compile) { return { restrict: 'A', priority: 1000, link: function (scope, element, attrs) { scope.$watch(attrs.ngModelName, function(ngModelName) { // no need to bind a model if (attrs.ngModel == ngModelName || !ngModelName) return; element.attr('ng-model', ngModelName); // remove ngModel if it's empty if (ngModelName == '') { element.removeAttr('ng-model'); } // clean the previous event handlers, // to rebinded on the next compile element.unbind(); //recompile to apply ngModel, and rebind events $compile(element)(scope); }); } }; }]) .controller('myController', function ($scope) { $scope.form = { formFields: [ { modelBinding: 'model.project.data' } ] }; $scope.model = {}; }); angular.element(document).ready(function () { angular.bootstrap(document, ['myApp']); }); <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-controller="myController"> <div ng-repeat="formField in form.formFields"> <input ng-model-name="formField.modelBinding" placeholder="{{ formField.modelBinding }}" /> </div> <div> <pre>{{ model | json }}</pre> </div> </div>
[ "stackoverflow", "0016578708.txt" ]
Q: Show Collection Data in View In Backbone.js I am new to backbone.js. I have 2 javascript files. 1 for collection and 1 for view. **collection.js** var colle = Backbone.Collection.extend({ initialize: function () { var data = [ { Name: "a", Image: "path1" }, { Name: "b", Image: "path2" }, ]; } }); and my view.js is var View = Backbone.View.extend({ initialize: function () { this.collection = colle; }, render:function(){ //How can I access that data here ? } }); var view1 = new View(); How can I access my Collection data in View ? Thank you. A: First, you need an instance of your collection - currently you've defined colle as a constructor for a Backbone collection when what you need now is an instance: var myCollection = new colle(); // convention is to use uppercase when defining your constructor then, pass a reference to your collection when you instantiate your view: var view1 = new View({ collection: myCollection }); then, inside your view you can reference your collection using this.collection: render: function () { // reference your collection using this.collection here } If you can be more specific about what you want to do with your collection, I can expand the example to demonstrate something more useful.
[ "stackoverflow", "0045336960.txt" ]
Q: "full join" method for lists Lets say we have a two lists Seq[A] and Seq[B] of certain objects and want to join them on a certain condition (A, B) => Boolean. It might be like for one element from the first list there are several matching elements from the second one. If speaking about full join, we mean we want to know also for which elements for both list there is no corresponding pair. So the signature would be: def fullJoin[A, B](left: Seq[A], right: Seq[B], joinCondition: (A, B) => Boolean): (Seq[A], Seq[B], Seq[(A, B)]) Or if we take advantage of Cats' Ior type: def fullJoin[A, B](left: Seq[A], right: Seq[B], joinCondition: (A, B) => Boolean): Seq[Ior[A, B]] The example: scala> fullJoin[Int, Int](List(1,2), List(3,4,4), {_ * 2 == _ }) res4: (Seq[Int], Seq[Int], Seq[(Int, Int)]) = (List(1),List(3),List((2,4), (2,4))) The idea is exactly the same as the idea of joining tables in SQL. The question is whether there are any similar utility methods in the standard library. If not, let's discuss an elegant solution - at first, with performance not being a problem (a quadratic complexity is fine, as for Nested Loop). A: Here's a solution that leverages built-in scala library functionality to be a bit more concise: def fullJoin[A, B](left: Seq[A], right: Seq[B], joinCondition: (A, B) => Boolean): (Seq[A], Seq[B], Seq[(A, B)]) = { val matched = for (a <- left; b <- right if joinCondition(a, b)) yield (a, b) val matchedLeft = matched.map(_._1).toSet val matchedRight = matched.map(_._2).toSet (left.filterNot(matchedLeft.contains), right.filterNot(matchedRight.contains), matched) }
[ "stackoverflow", "0050433590.txt" ]
Q: virtual box installation causes error while launching The virtual machine 'cloudera-quickstart-vm-5.12.0-0-virtualbox' has terminated unexpectedly during startup with exit code 1 (0x1). More details may be available in 'C:\Users\Sri Dhanasheelan\VirtualBox VMs\cloudera-quickstart-vm-5.12.0-0-virtualbox\Logs\VBoxHardening.log'. Result Code: E_FAIL (0x80004005) Component: MachineWrap Interface: IMachine {b2547866-a0a1-4391-8b86-6952d82efaa0} I have installed JDK ,visual studio-2015 in my windows10 system . But still get the error that the session to open virtual machine has been failed. A: Download latest virtual box and try to re install.It will solve the problem.
[ "math.stackexchange", "0003001239.txt" ]
Q: Branching processes - applications Let's consider the population of parrots that come from the same female, where each female give birth to $n$ daughters with probability $p_n=\frac{2}{3^{n+1}}, \;n=0,1,...$ (a)Find the probability of ultimate extinction, (b)Find the probability, that extinction will exactly happen in 7th generation, (c)Find the mean amount of females in $k$-th generation, (d)Prove the formula for generating function of random variable $Z_k$, which is the amount of females in $k$-th generation I need help with above-mentioned exercise. According (a) and (b) I know, that I need to find a generating function $G(s)= \sum_{k=0}^{\infty} P(Z_1=k)s^k$, but I'm not sure what I have to do with that knowledge. According to (c) and (d), I don't really know what am I supposed to do. Any help will be much appreciated. A: The process you are looking at is a special type of the well known Galton Watson Process and the probability of extinction is characterized by the smallest fixpoint $\eta$ of $G(s) = s$, where $s\in [0,1]$. a) Solve $G(\eta) = \eta$. b) By evaluating the equation of d) at $0$ we get $\Bbb P (Z_n = 0) = \underbrace{G \circ \ldots \circ G} _{n \text{ times}}(0)$. c) Also well known : $\Bbb E [Z_k] = (\Bbb E [Z_1])^k$ (can be proved by induction) d) Prove by induction: $\underbrace{G \circ \ldots \circ G} _{n \text{ times}} (s) = G_n(s):= \sum_{k=0}^\infty \Bbb P (Z_n = k) s^k$ The statements above are true for general Galton Watson Processes, but especially a) can be hard to solve. In your special case your can calculate $G$ explicitly: Assuming your definition of $p_n$ is a typo (otherwise this would not be a probability distribution) you can calculate the probability generating function as follows: $$G(s) = \sum_{k=0}^{\infty} \Bbb P (Z_1 = k) s^k = \sum_{k=0}^\infty \frac 2 {3^{k+1}} s^k = \frac 2 3 \sum_{k=0}^\infty (\frac s 3)^k = \frac 2 3 \frac 1 {1 - \frac s 3} = \frac 2 {3 -s}.$$
[ "stackoverflow", "0015815372.txt" ]
Q: Postgres database create if not exists Is there an analog to CREATE TABLE IF NOT EXISTS for creating databases? Background: I am writing a script to automatically set up the schema in PostgreSQL on an unknown system. I am not sure if the database (or even part of the schema) was already deployed, so I want to structure my code to not fail (or ideally even show errors) if some of the structure already exists. I want to differentiate the errors that prevent me from creating a database (so abort future schema changes since they will not work) from this error. A: No but you could query the pg_catalog.pg_database table to see if it exists.
[ "stackoverflow", "0039012815.txt" ]
Q: Projection matrix that has y-axis facing forward I would like to switch the second and third column of the projection matrix, to have it look down the y-axis and have z facing upwards. Can I change GL_PROJECTION_MATRIX this way? A: No. Swapping two columns is not a rotation (it changes the determinant). It is better to set up a rotation matrix (from an axis and an angle) and rotate that way.
[ "windowsphone.stackexchange", "0000000069.txt" ]
Q: Finding Eduroam WiFi Certifications I need certificate to connect to WiFi. If I visit webpage where I can download certificate I can easily install it, but I have downloaded wrong certificate. I t seems impossible to find certificates anywhere in settings or Internet Explorer? I need certificates for well known wifi system Eduroam. A: Currently there is no option to remove certificates. The only way to fix this is resetting your phone. settings -> about -> reset your phone There is a feature request posted here asking to provide a way to remove certificates so Microsoft knows about the issue. The only other option is to wait until they implement it but guess that is not an option.
[ "stackoverflow", "0035467233.txt" ]
Q: map function for n-ary tree in Scheme the definition for a map function for binary trees is: (define (binary-tree-map proc tree) (cond ((null? tree) null) ((not (pair? tree)) (proc tree)) (else (cons (binary-tree-map proc (car tree)) (binary-tree-map proc (cdr tree)))))) what does a map function for n-ary trees look like? tried: (define (n-tree-map proc tree) (cond ((null? tree) null) ((not (pair? tree)) (proc tree)) (else (apply map append (lambda (p)(n-tree-map proc (cdr tree))))))) A: Every n-ary tree made with cons (known as tree structure) will have a mirror binary tree equivalent. Mapping over the tree keeps the structure and thus all the cons in the exact same relationship so the result of running your binary-tree-map over a n-ary tree as if it were a n-ary map should yield the same result. (1 2 (3 4)) can be interpreted as: /|\ 1 2 |\ 3 4 But as a binary tree it would be: /\ 1 /\ 2 /\ /\ nil 3 /\ 4 nil Lets try it! (binary-tree-map (lambda (x) (+ x 1)) '(1 2 (3 4))) ; ==> (2 3 (4 5)) Now if you would have created a tree differently. Eg. with records so that a node is not a pair or if you need to keep track of the depth, then you would need a different procedure for it. #!r6rs (import (rnrs)) (define-record-type (tree make-tree tree?) (fields (immutable children tree-children))) (define (tree-map proc tr) (cond ((not (tree? tr)) (proc tr)) (else (make-tree (map (lambda (x) (tree-map proc x)) (tree-children tr)))))) (define test-tree (make-tree (list '(1 2 3) '(2 3 4) '(3 4 5) (make-tree '((7 8 9) (10 11 22)))))) (tree-map cdr test-tree) ; ==> (#tree (list '(2 3) '(3 4) '(4 5) (#tree '((8 9) (11 22))))) Notice how lists now can be leafs since a list doesn't mean node. It's possible to do this with list structure too by using a tag to identify nodes: (define tree-tag (vector 'tree)) (define (tree? tr) (and (pair? tr) (eq? tree-tag (car tr)))) (define (make-tree children) (cons tree-tag children)) (define tree-children cdr) (tree-map cdr test-tree) ; ==> '(#(tree) (2 3) (3 4) (4 5) (#(tree) (8 9) (11 22)))
[ "stackoverflow", "0021529677.txt" ]
Q: Add/remove multiple inputs jquery i have the code below $(document).ready(function(){ var input = '<p><input type="text" name="alternativas[]" /> <a href="#" class="remove"><img src="images/ico_excluir.gif" /></a></p>'; $("input[name='add']").click(function( e ){ $('#inputs').append( input ); }); $('#inputs').delegate('a','click',function(){ $( this ).parent('p').remove(); }); }); and i have a lot of forms in the same page <table width="100%" border="0" cellspacing="10" cellpadding="0" div="alter"> <form action="/teste/fono2014/admin/pesquisa_editar.php" method="get" enctype="multipart/form-data"> <tr> <td colspan="2" align="center"><h3>QUESTION 1</h3></td> </tr> <tr> <td width="30%" align="right">Question:</td> <td><input type="text" value="Where are you from?" /></td> </tr> <tr> <td align="right">Sequence:</td> <td><input name="ordem_pergunta" type="text" value="1" onkeypress='return SomenteNumero(event)' /></td> </tr> <tr> <td align="right">Alternatives:</td> <td><input type="button" name="add" value="Add" /> <div id="inputs"> <p><input type="text" name="alternativas[]" value="Brazil" /> <a href="#" class="remove">Remove</a></p> <p><input type="text" name="alternativas[]" value="EUA" /> <a href="#" class="remove">Remove</a></p> <p><input type="text" name="alternativas[]" value="Mexico" /> <a href="#" class="remove">Remove</a></p> </div> </td> </tr> <tr> <td align="right">More than one?</td> <td><input name="inserir_varios" type="radio" value="S" checked> Yes <input name="inserir_varios" type="radio" value="N" > No</td> </tr> </form> <form action="/teste/fono2014/admin/pesquisa_editar.php" method="get" enctype="multipart/form-data"> <tr> <td colspan="2" align="center"><h3>QUESTION 2</h3></td> </tr> <tr> <td align="right">Question:</td> <td><input name="pergunta" type="text" value="How old are you?" /></td> </tr> <tr> <td align="right">Sequence:</td> <td><input name="ordem_pergunta" type="text" value="2" onkeypress='return SomenteNumero(event)' /></td> </tr> <tr> <td align="right">Alternatives:</td> <td><input type="button" name="add" value="Add" /> <div id="inputs"> <p><input type="text" name="alternativas[]" value="&lt; 18" /> <a href="#" class="remove">Remove</a></p> <p><input type="text" name="alternativas[]" value="&gt; 18" /> <a href="#" class="remove">Remove</a></p> </div> </td> </tr> <tr> <td align="right">More than one?</td> <td><input name="inserir_varios" type="radio" value="S" checked> Yes <input name="inserir_varios" type="radio" value="N" > No</td> </tr> </form> <form action="/teste/fono2014/admin/pesquisa_editar.php" method="get" enctype="multipart/form-data"> <tr> <td colspan="2" align="center"><h3>QUESTION 3</h3></td> </tr> <tr> <td align="right">Question:</td> <td><input name="pergunta" type="text" value="Where do you live?" /></td> </tr> <tr> <td align="right">Sequence:</td> <td><input name="ordem_pergunta" type="text" value="3" onkeypress='return SomenteNumero(event)' /></td> </tr> <tr> <td align="right">Alternatives:</td> <td><input type="button" name="add" value="Add" /> <div id="inputs"> <p><input type="text" name="alternativas[]" value="New York" /> <a href="#" class="remove">Remove</a></p> <p><input type="text" name="alternativas[]" value="San Diego" /> <a href="#" class="remove">Remove</a></p> </div> </td> </tr> <tr> <td align="right">More than one?</td> <td><input name="inserir_varios" type="radio" value="S" > Yes <input name="inserir_varios" type="radio" value="N" checked> No</td> </tr> </form> </table> When i click add the code just add the new input on the first div. What can i do ? i have no ideia what i can do, i don't know jquery very well. i thought to put a random variable on id to each form and the button "Add" get this id, but i dont know how to do it. A: Try using a class instead of the id #inputs. Ids are only meant to exist one time in the page. Jquery uses document.getElementById() to retrieve the dom element which will return the first element containing that id. You are allowed to use the same class name multiple times. if you added the class inputs to the divs and used the selector .inputs you should get the desired result. You can change your jquery to append to the correct div as follows (it looks like the add button is always right before the div you are adding to): $("input[name='add']").click(function( e ){ $(this).next().append( input ); }); This way, you wont even need a class to reference. It will add the input to the div after the add button.
[ "tex.stackexchange", "0000101112.txt" ]
Q: Removing footnotes from pdf bookmarks I have \section{My Title\footnote{ My Footnote 1}\footnote{My Footnote 2}} . Both pdfLatex and Latex automatically creates bookmarks from my section headers. That's what I want. But they also include the footnotes. So an example of bookmark is "My Title My foootnote 1 My Footnote 2" . But I want only "My Title" How do I achieve this? A: Assuming your using hyperref you can disable the \footnote command for all pdf-strings by adding the following to your preabmle: \pdfstringdefDisableCommands{% \def\footnote#1{}% } Complete example: \documentclass{article} % \footnote is a fragile command so can cause troubles in moving % arguments like in \section. Let's make it robust: \usepackage{etoolbox} \robustify{\footnote} % load hyperref and disable the \footnote command in bookmarks: \usepackage{hyperref} \pdfstringdefDisableCommands{% \def\footnote#1{}% } \begin{document} \section{My Title\footnote{ My Footnote 1}\footnote{My Footnote 2}} \end{document} A: You can easily use the optional argument of \section for a different title text in the TOC and in bookmarks: \section[My Title]{My Title\footnote{ My Footnote 1}\footnote{My Footnote 2}}
[ "stackoverflow", "0013444185.txt" ]
Q: The use of getPixels() of Android's Bitmap class and how to use it I'm trying to do some image processing in Android. I need to get a chunk of pixel information of a bitmap. So I tried to use one of the Bitmap class method getPixels(). However, it seems like I'm not using it correctly or I misunderstood of the sole purpose of the method's behaviour. For example, I'm doing the following in order to get pixel information of a 10 by 10 region of a bitmap from an arbitrary location(bitmap coordinate) x, y. Bitmap bitmap = BitmapFactory.decodeFile(filePath); int[] pixels = new int[100]; bitmap.getPixels(pixels, 0, bitmap.getWidth(), x, y, 10, 10); And I'm getting ArrayIndexOutOfBoundsException. I've been Googling around to see what I'm doing wrong, but I'm clueless. Most of the examples or questions regarding the use of getPixels() are usually for the case of extracting pixel information of the entire image. Hence the size of the int array is usually bitmap.getWidth()*bitmap.getHeight(), x and y values are 0, 0, and the width, height is bitmap's width and height. Is Bitmap's getPixels() not designed for the purpose of my use(getting a chunk of pixel information of a sub-region of the bitmap)? Or am I using it incorrectly? Is there an alternative way to do this, perhaps using a different class? I would appreciate it if anyone has something to say about this. Thanks. A: getPixels() returns the complete int[] array of the source bitmap, so has to be initialized with the same length as the source bitmap's height x width. Using like so, bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, 10, 10); does actually grab the desired pixels from the bitmap, and fills the rest of the array with 0. So with a 10 x 10 subset of a bitmap of 100 x 10, starting at 0,0 the first 100 values would be the desired int value, the rest would be 0. You could always try using Bitmap.createBitmap() to create your subset bitmap, then use getPixels() on your new Bitmap to grab the complete array. A: Most guys want to use getPixels() getting a specific region pixels, but actually it returned a full size of the origin bitmap. Valid region is placed left corner and others are translucent colors. I suggest you use Android Studio debug mode to see the visual pixels by creating a bitmap. And the following is my version of getPixels() to get specific region pixels: public class BitmapHelper { public static int[] getBitmapPixels(Bitmap bitmap, int x, int y, int width, int height) { int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()]; bitmap.getPixels(pixels, 0, bitmap.getWidth(), x, y, width, height); final int[] subsetPixels = new int[width * height]; for (int row = 0; row < height; row++) { System.arraycopy(pixels, (row * bitmap.getWidth()), subsetPixels, row * width, width); } return subsetPixels; } }
[ "stackoverflow", "0048935204.txt" ]
Q: React | Virtual DOM element click event not triggering I'm using Ant Design and React js for my Project. Problem I have a button in Popover and having click event for that button. The problem is button click event is not triggering. JS Code const content = ( <div className="RecurringPopover"> <button onClick={this.handleClick}> Popover Button </button> </div> ); Full Code with scenario in stackblitz A: You have defined content outside the class and then supplying this.handleClick as a click handler to it. However outside class, this does not point to the class. You should define content inside class and use this.content to access that. handleClick() { alert('test'); } // put it inside class content = ( <div className="RecurringPopover"> <button onClick={this.handleClick}> Popover Button </button> </div> ); render() { return ( <div> <Row> <Col span={12}> // Use this.content instead of just content <Popover content={this.content} title="Title"> <span type="primary">Hover me (Popover Button)</span>
[ "stackoverflow", "0033419437.txt" ]
Q: Swift 2.1, convert string to [String] (not [Character]), how to do that? I have a string var a = "abcd" and I want to get an array of one-character-string ["a", "b", "c", "d"]. I've tried Array(a.characters) but that only gives me [Character] not [String]. How to do that? A: var str = "abcd" let strArr = str.characters.map { String($0) }
[ "stackoverflow", "0037275742.txt" ]
Q: Jinja List Issue I am getting a weird problem in Jinja, I have a list endpoints, which contains dictionary for every endpoint. In each dictionary, there is a key tags which is a list. Every item in tags is itself a dictionary where the key value gives the label of a tag. endpoint may have similar tags. A sample abstract representation of an endpoints object can be: [ {"tags":[{"value":"car"},{"value":"place"}]} , {"tags":[{"value":"van"},{"value":"place"}]} ] what I want is to simple display unique tags in a div. It is simple, keeping a list of all displayed tags and upon getting a tag, checking if it is already in the list, and if not display it and add it to the list. Weirdly, it's not working. The codes are: {% set tagValues = [] %} {% for endpoint in endpoints %} {% for tag in endpoint["tags"]%} {% set tagValue = tag["tag"]["value"] %} {% if tagValue not in tagValues %} {% set tagValues = tagValues + [tagValue] %} <span >{{ tagValue }}</span></a> {% endif %} {% endfor %} {% endfor %} it is not working, for example, for the enpoints list above, I am getting the following output: car place van place is there any problem with the codes ? A: I recommend creating a distinct list of tags in your View. e.g. distinctTags = list(set([tag for endpoint in endpoints for tag in endpoint])) and passing that to your template {% for tag in distinctTags %} <span >{{ tagValue }}</span></a> {% endfor %} this has the advantage of the distinct tag code being reusable and the code being less procedural.
[ "stackoverflow", "0017223410.txt" ]
Q: How can I keep the product option based on the menu/user language in PHP I'm working on the php code of someone else and have a problem with the user/menu language. This is the code of the page with the dynamic price list for banner ads on this website. Depending on the selected menu language, the user can see the price of the banner ads which are for each menu language different. Whenever the user is coming to this page the active banner ads price should be for the users menu language. Right now it's fixed on russian language and I don't know how to make it dynamicly or at least change/fix it to english. Please have a look and let me konw if you might see a solution. Thanks! <?php class reklama_content { private $db; private $cms; private $valid; private $data; private $tools; public function __construct() { $reg = Registry::getInstance(); $this->db = $reg->get('db'); $this->cms = $reg->get('cms'); $this->valid = $reg->get('Validate'); $this->data = $reg->get('methodData'); $this->tools = $reg->get('tools'); } public function get_reklama_content() { $lang = language::getLang(); if ($_GET['ryb']) $ryb = $_GET['ryb']; else $ryb = 'banners'; if ($ryb == 'banners') $ret = $this->getBanner($lang); elseif ($ryb == 'classifieds') $ret = $this->getClassifieds($lang); return $ret; } public function getClassifieds($lang) { $contetn = $this->db->selectArray($this->db->Select('*', 'block', "`name` = 'classifieds_content'")); $ret = $contetn['content_' . $lang]; return $ret; } public function getBanner($lang) { $header = array(); $top = array(); $center = array(); $bottom = array(); $banners = $this->db->selectAssoc($this->db->Select('*', 'banners', false, 'page_id', false, true)); $contetn_top = $this->db->selectArray($this->db->Select('*', 'block', "`name` = 'reklams_baner_top'")); $contetn_bottom = $this->db->selectArray($this->db->Select('*', 'block', "`name` = 'reklams_baner_bottom'")); foreach ($banners as $x => $y) { if ($y['position'] == 'header') $header[$x] = $y; elseif ($y['position'] == 'top') $top[$x] = $y; elseif ($y['position'] == 'center') $center[$x] = $y; elseif ($y['position'] == 'bottom') $bottom[$x] = $y; } $ret = $contetn_top['content_' . $lang]; $langs = ($this->tools->getAllLang(true)); $ret .= ' <hr style="width: 100%; margin: 40px 0;" /> <div class="rek_banner_conteiner header_conteiner"> <span class="ban_title">' . l::top_banner1() . '</span> <img src="styles/them_01/img/banner_468x60.jpg" class="header_example" /> <div class="lang_menu">' . l::menu_language1() . '<br />'; $ret .= '<span id="eng_header" >' . l::english() . '</span>'; $ret .= '<span id="de_header" >' . l::german() . '</span>'; $ret .= '<span id="rus_header" >' . l::russian() . '</span>'; $ret .= '<span id="tr_header" >' . l::turkish() . '</span>'; $ret .= '</div>'; foreach ($langs as $z => $g) { $ret .= ' <div id="' . $g['name'] . '_header_box" class="hide"> <table> <tr class="order_table_title"> <td class="order_table_position">' . l::location() . '</td> <td class="order_table_size">' . l::size1() . '</td> <td class="order_table_date">' . l::fee_per_month() . '</td> </tr> '; foreach ($header as $z => $f) { $page = $this->db->selectArray($this->db->Select('title_' . $lang, 'pages', "`id` = '" . $f['page_id'] . "'")); $ret .= '<tr> <td>' . $page['title_' . $lang] . '</td> <td>' . $f['size'] . '</td> '; if ($f['price' . '_header_' . $g['name']]) $ret .= '<td>$ ' . $f['price' . '_header_' . $g['name']] . '</td>'; else $ret .= '<td></td>'; $ret .= ' </tr>'; } $ret .= ' </table> </div> '; } $ret .= '</div>'; $ret .= $contetn_bottom['content_' . $lang]; return $ret; } } ?> A: I have code in an answer about language detection here. It contains a cool little easily modifiable snippet I use to check who's coming from where based on their browser preferences for language. In short, you'll need to either detect the language from $_SERVER['HTTP_ACCEPT_LANGUAGE'] or detect a user preference (eg. ?lang=de ) to override their default language preference in their browser. That's if you're not using a custom URL like tr.example.com. Then you can do a switch(). Right now it looks like you're concatenating all of the language <span> tags together. switch($lang){ case "ru": //Russian $ret .= '<span id="rus_header" >' . l::russian() . '</span>'; break; case "de": //German $ret .= '<span id="de_header" >' . l::german() . '</span>'; break; case "tr": //Turkish $ret .= '<span id="tr_header" >' . l::turkish() . '</span>'; break; default: //English $ret .= '<span id="eng_header" >' . l::english() . '</span>'; } As my other post says (there's a video from Google). Ideally it's best if you have the content all in one language on a specific URL for that language. Then all of this magical language translation stuff happens without the user having to make a selection or guess if they're clicking the correct link in a language they're not familiar with.
[ "magento.stackexchange", "0000015922.txt" ]
Q: Add database field to model and make it editable using Varien_Data_Form I have a model in an extension. I want to add a new database attribute and make this value editable through Magento admin using Varien_Data_Form. I have added the field to the database through installer script, the field is displayed on the admin, but I don't know how to save it. The form data is posted and saved to a $data variable, the model is loaded and has a setData($data) called, and after that the model is saved, but to no avail. Dumping $data just before the setData() call shows the variable is fine. Saving occurs inside a try block, no errors are thrown/catched. ... $model = Mage::getModel('cmspro/category'); $model->setData($data)->setId($this->getRequest()->getParam('id')); ... try { ... $model->save(); ... } catch (Exception $e) { ... } A: After changing the structure of a table clear the cache. Delete the contents of var/cache. Even if the cache is disabled the table schema is still cached by Zend Framework.
[ "stackoverflow", "0003360160.txt" ]
Q: How do I create an COM visible class in C#? I using Visual Studio 2010 (.NET 4). I need to create a COM object (in C#) and have no idea how to get started (what type of project to use,etc.) A: OK I found the solution and I'll write it here for the common good. Start VS2010 as administrator. Open a class library project (exmaple - MyProject). Add a new interface to the project (see example below). Add a using System.Runtime.InteropServices; to the file Add the attributes InterfaceType, Guid to the interface. You can generate a Guid using Tools->Generate GUID (option 4). Add a class that implement the interface. Add the attributes ClassInterface, Guid, ProgId to the interface. ProgId convention is {namespace}.{class} Under the Properties folder in the project in the AssemblyInfo file set ComVisible to true. In the project properties menu, in the build tab mark "Register for COM interop" Build the project now you can use your COM object by using it's ProgID. example: the C# code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace Launcher { [InterfaceType(ComInterfaceType.InterfaceIsDual), Guid("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")] public interface ILauncher { void launch(); } [ClassInterface(ClassInterfaceType.None), Guid("YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYY"), ProgId("Launcher.Launcher")] public class Launcher : ILauncher { private string path = null; public void launch() { Console.WriteLine("I launch scripts for a living."); } } } and VB script using the COM: set obj = createObject("PSLauncher.PSLauncher") obj.launch() and the output will be: I launch scripts for a living A: Creation Steps Start Visual Studio 2013 as administrator Install Visual Studio extension Microsoft Visual Studio Installer Projects Create a class library project (WinFormActivex) Create your example window form (MainWindow) Create a new component interface(ILauncher) Create a new security interface (IObjectSafety) Create the component control (Launcher) that implement interfaces and launch the window. Check that all GUIDs are generated by you Check that the project is marked for COM Create the setup project (LauncherInstaller) with the primary output of WinFormActivex with the property Register = vsdrpCOM Install LauncherInstaller Run your test page in explorer (test.html) MainWindow You can create a normal Form, here is pre-generated. public partial class MainWindow : Form { public MainWindow() { InitializeComponent(); } /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(42, 23); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 20); this.textBox1.TabIndex = 0; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(42, 65); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(100, 20); this.textBox2.TabIndex = 0; // // MainWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Name = "MainWindow"; this.Text = "MainWindow"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; } ILauncher using System.Runtime.InteropServices; namespace WinFormActivex { [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("94D26775-05E0-4B9C-BC73-C06FE915CF89")] public interface ILauncher { void ShowWindow(); } } IObjectSafety [ComImport()] [Guid("51105418-2E5C-4667-BFD6-50C71C5FD15C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IObjectSafety { [PreserveSig()] int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions); [PreserveSig()] int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions); } Launcher Please generate your GUID here. [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] [Guid("D100C392-030A-411C-92B6-4DBE9AC7AA5A")] [ProgId("WinFormActivex.Launcher")] [ComDefaultInterface(typeof(ILauncher))] public class Launcher : UserControl, ILauncher, IObjectSafety { #region [ ILauncher ] public void ShowWindow() { var f = new MainWindow(); f.StartPosition = FormStartPosition.Manual; f.Location = Screen.AllScreens[0].Bounds.Location; f.WindowState = FormWindowState.Normal; f.WindowState = FormWindowState.Maximized; f.ShowInTaskbar = false; f.Show(); } #endregion #region [ IObjectSafety ] public enum ObjectSafetyOptions { INTERFACESAFE_FOR_UNTRUSTED_CALLER = 0x00000001, INTERFACESAFE_FOR_UNTRUSTED_DATA = 0x00000002, INTERFACE_USES_DISPEX = 0x00000004, INTERFACE_USES_SECURITY_MANAGER = 0x00000008 }; public int GetInterfaceSafetyOptions(ref Guid riid, out int pdwSupportedOptions, out int pdwEnabledOptions) { ObjectSafetyOptions m_options = ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_CALLER | ObjectSafetyOptions.INTERFACESAFE_FOR_UNTRUSTED_DATA; pdwSupportedOptions = (int)m_options; pdwEnabledOptions = (int)m_options; return 0; } public int SetInterfaceSafetyOptions(ref Guid riid, int dwOptionSetMask, int dwEnabledOptions) { return 0; } #endregion } test.html Please check that your CLSID match (Launcher) GUID. <html> <head> <objectname="activexLauncher" style='display:none' id='activexLauncher' classid='CLSID:D100C392-030A-411C-92B6-4DBE9AC7AA5A' codebase='WinFormActivex'></object> <script language="javascript"> <!-- Load the ActiveX object --> var x = new ActiveXObject("WinFormActivex.Launcher"); alert(x.GetText()); </script> </head> <body> </body> </html> References Stack Overflow question I always use as reference Activex tag you should read Old Microsoft guide Article on creating the acrivex control with security options Article about creating the window A: You could use a class library project. Declare a type with methods that will be exposed as a COM object. Make sure that the assembly has been made COM-visible: And finally register it using regasm.exe: regasm.exe /codebase mylib.dll Now the assembly is exposed as a COM object and the type you declared can be consumed by any client that supports COM.
[ "stackoverflow", "0037539789.txt" ]
Q: Hibernate and Postgres : function st_buffer(bytea, numeric) is not unique I'm working with Hibernate 5.1.0 in a Java application. I'm connecting both to a Postgres 9.5 with Postgis extensions and Oracle databases. I need to find all the geometries in my database that intersect with a given geometry to which I apply a buffer, such as : Query query = session .createQuery("select b from Block b where intersects(b.geom, buffer(:geometry, " + bufferDistance + ")) = " + UtilsHelper.getTrueBooleanValue(em)); query.setParameter("geometry", geom); List<Block> blocks = query.list(); That works in Oracle, but in Postgres I will get the error : Caused by: org.postgresql.util.PSQLException: ERROR: function st_buffer(bytea, numeric) is not unique Hint: Could not choose a best candidate function. You might need to add explicit type casts. Position: 243 at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270) This makes sense, as it will not be able to choose between one of the following functions : geometry ST_Buffer(geometry g1, float radius_of_buffer); geography ST_Buffer(geography g1, float radius_of_buffer_in_meters); The UtilsHelper.getTrueBooleanValue(em) will just get the right boolean value depending on the entity manager, that is, 0/1 for Oracle and true/false for Postgres. One obvious solution would be to drop one of the functions. Other than that, is there any way I can fix this? A: I won't claim to know much about Hibernate, but it seems that a simple fix is to explicitly cast the bytea with CAST(:geometry AS geometry), and modernize the rest query to add a "ST_" prefix, which is used with newer PostGIS versions. More importantly, you should never write a query with the form: SELECT b FROM Block b WHERE ST_Intersects(b.geom, ST_Buffer(CAST(:geometry AS geometry), :bufferDistance)) = TRUE; Using a buffer to select a region is slower and imperfect than using a distance-based ST_DWithin function to find the geometries that are within a distance. ST_DWithin can also use a spatial index, if available. And a boolean operator does not need to have the = + UtilsHelper.getTrueBooleanValue(em) part (i.e. TRUE = TRUE is TRUE). Just remove it. Try to write a function that looks more like: SELECT b FROM Block b WHERE ST_Dwithin(b.geom, CAST(:geometry AS geometry), :distance); (using two parameters :geometry and :distance)
[ "stackoverflow", "0043972834.txt" ]
Q: Android. Do I need to dispose Maybe inside onBindViewHolder? I'm executing a heavy request inside MayBe observable in my adapter. @Override public void onBindViewHolder(MyViewHolder holder, int position) { final RealmArticle obj = getItem(position); int idTask = obj.getIdTask(); Disposable mayBeCount = Maybe.fromCallable(()-> { Realm bgInstance = Realm.getInstance(Realm.getDefaultInstance().getConfiguration()); return bgInstance.where(RealmArticle.class).findAll().where().equalTo("idTask", idTask).equalTo("completed", true).count() }) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(res->{ holder.row_count.setText(res); this.notifyItemChanged(position); }, throwable -> Log.e(TAG, String.format("%s, %s", "Can not get items count", throwable.getMessage()))); } The question is: Should I dispose the mayBeCount? If so, in what life cycle moment is it better to do this? A: You can use onViewDetachedFromWindow to cancel the operation hopefully. Therefore I would add the Disposable as an attribute to your viewholder. @Override public void onViewDetachedFromWindow(MyViewHolder holder) { holder.mayBeCount.dispose(); }
[ "travel.stackexchange", "0000034345.txt" ]
Q: Exchanging a Motorhome (RV) between USA and Australia We are planning to visit USA in October and November 2014 and would like to arrange a swap for the Motorhome we have in Australia for one in USA. Does anyone have any contacts we might try. We would also be interested to hear any experiences others may have had. A: You're not the first to wonder, and there are already websites set up for such plans! RVWorldWide has an exchange/swap program, and indeed there are Aussie and American listings on there. It would be worth a post. MotorhomeHolidaySwap is growing, it only has 1700 members, but these are actively trying to swap for holidays around the world, so does sound exactly like what you're looking for.
[ "stackoverflow", "0009500027.txt" ]
Q: JavaMail with tomcat6 server Iam new to java mail. my requirement is , i need to add email services to my web application that is developing using servlets and my web server is apache tomcat6 ..so any body would help me, how would i go through? any suggestions appriciated... A: You need to use Java Mail API. Please have a look at tutorial - Fundamentals of the JavaMail API.
[ "stackoverflow", "0019576538.txt" ]
Q: Import KPI from Analysis Service to Dashboard Designer directly without using Scorecard wizard I am using SharePoint Designer 2010. When I create a new scorecard, Dashboard Designer gives option to import existing KPIs from Analysis Service. So if I make any changes to these KPIs in Analysis Service, then I create new scorecard and import the KPI. Is there any way to import the KPIs directly to Dashboard Designer without creating new scorecard. Thanks in Advance, Merin A: Create a new blank KPI --> Change the KPI data mapping to your SSAS data source --> Use a custom MDX tuple formula to reference your SSAS KPI's. The tuple formulas you can use to get KPI data are KPIValue("[kpi name]"), KPITarget("[kpi name]"), KPIGoal("[kpi name"]), KPITrend("[kpi name"]).
[ "stackoverflow", "0011007797.txt" ]
Q: Faster Way For Graphics In Visual Studios? In Visual Studios, using the Graphics class, if you try to clear the screen and draw graphics afterwards it won't be able to keep up and will cause a terrible flicker. Is there a faster way to do this? I want to be able to draw graphics on the screen and clear them fast enough to keep up with movement. Kind of like how OpenGL works. A: You want to use double buffering. Basically you draw the next image off screen in advance and then move it into view to avoid the flickering effect. C# has a BufferedGraphics class. This will probably help too.
[ "stackoverflow", "0003262867.txt" ]
Q: One big checkin or several smaller ones? Yesterday when i checked out the latest version of our internal tool i saw about 30+ new versions. This got me curious since i thought that somebody finally fixed those annoying bugs and added that feature i was waiting for so long... and guess what? None of this happened, someone just thought it would be nice to update some headers and do a minor adjustment of two or three functions. Everything in a separate commit. Great. This raised a discussion in our team - should this be considered ok, or should we prohibit such "abuse"? Arguably this really could fit in one or two commits, but 30 seems to much. How should this be handled - what is the best practice? A: You should be committing any time you make a change and are about to move on to the next one. You shouldn't commit anything that stops the project from building. You should be filling in the commit message so people know what changes have been made. That'll do for me.. I don't assume something has been done unless I see it in the commit message... A: Generally I think a commit should relate to one logical task, e.g. fixing bug #103 or adding a new print function. This could be one file or several, that way you can see all changes made for a particular task. It is also easier to roll back the change if necessary. If each file is checked in one by one, it is not easy to see the changes made for a particular update / task. Also if multiple tasks are completed in one commit, it is not easy to see what changes belong to which task.
[ "salesforce.stackexchange", "0000011006.txt" ]
Q: Including a Read Me in a Managed Package? I'm creating an app that requires Users to validate a few things in their Org so that the app functions correctly. Is there a way to include this on the "Success" page after they install the app? It's a very short 3 step list. A: A couple of communication routes to consider... Default Landing Tab. I've seen a few apps include a Welcome tab and ensure its the default tab on the Application. This ensures the user sees it first when selecting your app from the application drop down. You can read more here about setting one of these up. Welcome Email. You may also want to consider a post install script that sends an email with your read me text in it (and perhaps a link to the welcome page). You can read more about this here. Configuration Checking: You certainly should make sure your app fails gracefully if this config is needed for it to function. Make sure you choose carefully the location to make this check, since Force.com native apps can be interacted with in various ways, least of which your VF pages. If its really vital you may want to put prechecks into your triggers.
[ "stackoverflow", "0000427837.txt" ]
Q: How do I manage the ClassPath in WebSphere I have a problem with my web module classpath in Websphere v6.1. In my WEB-INF/lib I have a largish number of jar files which include xercesImpl.jar and xmlparserv2.jar. I need both jars to be present, but they appear to confict with each other. Specifically, each jar contains a META-INF/services directory so, when we try to get an instance of a DocumentBuilderFactory via JAXP, which instance we get depends upon the order in which these two jars appear in the classpath. I always want to use the xerces instance of the DocumentBuildFactory, so I want to push xercesImpl.jar to the front of the classpath. I've tried to do this by specifying a Class-Path section in the Manifest file for the war file, but the class path that I actually get in my WAS Module Compound CLass Loader in is very strange. I seem to get some standard stuff that WAS puts on, followed by the contents of WEB-INF lib in alphabetical order, followed by the classpath specified by the Manifest file. If I don't put a manifest file into the war at all, I get the standard stuff followed by the contents of WEB-INF/lib but in an arbitrary order. What am I missing? Is there a way in which I can set the class path up to be exactly what I want? Dave A: I assume by WebSphere, you mean the regular J2EE Application Server (and not something like Community Edition; WebSphere is a brand name applied to a number of IBM products). I think your options are limited. Since the dependencies look quite explicit, I would prefer a programmatic approach rather than relying on the vagaries of the classpath (like creating factory instances explicitly rather than relying on the SPI). If that isn't an option, you might want to look at making one of your dependencies an EAR project utility JAR and configure MODULE classloading with a PARENT_LAST classloading policy on the WAR. This can be configured via the browser admin console (or via the RAD tooling if you use it). Another thing I'd look at is the WAS Shared Libraries feature (under Environment in the browser admin console). These can be associated with servers or applications. The downside is that this requires more configuration. A: In IBM Websphere Application Server 6.1, web modules have their own class loaders that are usually used in the PARENT_FIRST mode. This means that the web module class loaders attempt to delegate class loading to the parent class loaders, before loading any new classes. If you wish to have the Xerces classes loaded before the XML parser v2 (I'm assuming Oracle XML v2 parser) classes, then the Xerces classes will have to be loaded by a parent class loader - in this case, preferably the application class loader. This can be done by placing the Xerces jar in the root of the EAR file (if you have one) or prepare the EAR file with xerces.jar and your WAR file in the root. The xmlparserv2 jar should then be placed in WEB-INF\lib. You could also attempt creating an Xerces shared library for usage by your application. You can find more information about this in the IBM WebSphere Application Server V6.1: System Management and Configuration. Details are available in Chapter 12.
[ "sharepoint.stackexchange", "0000172136.txt" ]
Q: Office 365 & Azure AD We are using SharePoint Online (Plan 1) at the moment and we have not used any AD services before so all the users and licenses have been managed through O365/SPO admin portals. Now we noticed that there is an option to sign up for Azure AD. We have learned that it should be free because we have a paid plan and we would love to sign up and see what's it about and get familiar with it. Before that we wanted to make sure that if we sign up for it, will it initially make any changes or break anything on our current setup? We do not want to risk breaking anything at the moment (O365/SPO users and licenes etc.). Thank you! A: An Azure AD instance is already setup in the background for each Office 365 tenant. Essentially what's meant with Signing Up is getting an Azure account so that you can access to further settings of Azure AD (such as customizing you Office 365 login page).
[ "stackoverflow", "0062512176.txt" ]
Q: Split array struct to single value column Spark scala I have a dataframe with single array struct column where I want to split the nested values and added as a comma separated string new column(s) Example dataframe: tests {id:1,name:foo},{id:2,name:bar} Expected result dataframe tests tests_id tests_name [id:1,name:foo],[id:2,name:bar] 1, 2 foo, bar I tried the below code but got an error df.withColumn("tests_name", concat_ws(",", explode(col("tests.name")))) Error: org.apache.spark.sql.AnalysisException: Generators are not supported when it's nested in expressions, but got: concat_ws(,, explode(tests.name AS `name`)); A: Depends on the Spark version you are using. Assuming the dataframe scheme as below root |-- test: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- id: long (nullable = true) | | |-- name: string (nullable = true) Spark 3.0.0 df.withColumn("id", concat_ws(",", transform($"test", x => x.getField("id")))) .withColumn("name", concat_ws(",", transform($"test", x => x.getField("name")))) .show(false) Spark 2.4.0+ df.withColumn("id", concat_ws(",", expr("transform(test, x -> x.id)"))) .withColumn("name", concat_ws(",", expr("transform(test, x -> x.name)"))) .show(false) Spark < 2.4 val extract_id = udf((test: Seq[Row]) => test.map(_.getAs[Long]("id"))) val extract_name = udf((test: Seq[Row]) => test.map(_.getAs[String]("name"))) df.withColumn("id", concat_ws(",", extract_id($"test"))) .withColumn("name", concat_ws(",", extract_name($"test"))) .show(false) Output: +--------------------+---+-------+ |test |id |name | +--------------------+---+-------+ |[[1, foo], [2, bar]]|1,2|foo,bar| |[[3, foo], [4, bar]]|3,4|foo,bar| +--------------------+---+-------+
[ "stackoverflow", "0055195876.txt" ]
Q: Get difference of 2 dates in years, months, days, but answer is always off by a couple days/months So I am trying to make a simple counter. I essentially want to find the difference between Jun 5, 2011 00:00:00 date and now. Then display this date in the format of Years Months Days Hours Minutes Seconds. I went to timeanddate.com to calculate the difference. This website is very reliable and it tells me the difference is 7 years, 9 months, 11 days, 20 hours, 38 minutes, 4 seconds. But my code tells me its 7 years, 9 months, 13 days. What am I doing wrong & how can I fix it? Is there now function that calculate all this for me? <html> <body> <p id="demo"></p> <script> // Date to start on var startDate = new Date("Jun 5, 2011 00:00:00").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get todays date and time var now = new Date().getTime(); // Find how long its been since the start date and now var distance = (now - startDate); // Time calculations var years = Math.floor(distance / 31536000000); var months = Math.floor((distance % 31536000000)/2628000000); var days = Math.floor(((distance % 31536000000) % 2628000000)/86400000); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = years + " years, " + months + " months, " + days + " days "; }, 1000); </script> </body> </html> A: A year does not always have 365 days. Compared to the web site you refer to, there is also another difference: Usually when people speak of "today it is exactly 1 month ago", they mean it was on the same month-date. So 14 March comes exactly 1 month after 14 February, and 14 April comes exactly 1 month after 14 March. This means the length of what a "month" is, depends on what your reference point is. In the example, the first difference is 28 days (in non-leap years), while the second is 31 days. A solution that comes close to the results you get on the web site, can be achieved with this code: function dateDiff(a, b) { // Some utility functions: const getSecs = dt => (dt.getHours() * 24 + dt.getMinutes()) * 60 + dt.getSeconds(); const getMonths = dt => dt.getFullYear() * 12 + dt.getMonth(); // 0. Convert to new date objects to avoid side effects a = new Date(a); b = new Date(b); if (a > b) [a, b] = [b, a]; // Swap into order // 1. Get difference in number of seconds during the day: let diff = getSecs(b) - getSecs(a); if (diff < 0) { b.setDate(b.getDate()-1); // go back one day diff += 24*60*60; // compensate with the equivalent of one day } // 2. Get difference in number of days of the month let days = b.getDate() - a.getDate(); if (days < 0) { b.setDate(0); // go back to (last day of) previous month days += b.getDate(); // compensate with the equivalent of one month } // 3. Get difference in number of months const months = getMonths(b) - getMonths(a); return { years: Math.floor(months/12), months: months % 12, days, hours: Math.floor(diff/3600), minutes: Math.floor(diff/60) % 24, seconds: diff % 60 }; } // Date to start on var startDate = new Date("Jun 5, 2011 00:00:00"); // Update the count every 1 second setInterval(function() { const diff = dateDiff(startDate, new Date); const str = Object.entries(diff).map(([name, value]) => value > 1 ? value + " " + name : value ? value + " " + name.slice(0, name.length-1) : "" ).filter(Boolean).join(", ") || "0 seconds"; document.getElementById("demo").textContent = str; }, 1000); <div id="demo"></div> Some thoughts This variable notion of month may lead to unexpected results when instead of the end date, you increase the start date one day at a time: the distance between Feb 28, 2019 and April 1, 2019 is reported as 1 month, 4 days. But when you add 1 day to the first date, the difference is reported as 1 month exactly. Where did those 3 days go? ,-) So this solution (and the one on the referenced web site) works well when varying the end date. For situations where you would want to vary the start date with "logical" steps in the output, you would need a slightly different algorithm. But then you'll get such "jumps" when varying the end date. For instance: 28 Feb 2019 - 1 April 2019. Is the difference 1 month + 1 day or 1 month + 4 days? If you think you have the answer, move one of those dates one day closer to the other... there is just no way to have a consistent output that also jumps with 1 day each time one of either dates is moved with 1 day.
[ "stackoverflow", "0009066417.txt" ]
Q: How to Display The Description of my Unit Test on TeamCity WebUI? I'm using NUnit and TeamCity and I have written some system tests with descriptions. /// <summary> /// Should send the password reminder and... /// </summary> [Test] public void ShouldSendPasswordReminder() { } On Teamcity, after a test has run, it displays only the Status, Test Method Name, Test Class Name and Duration; however, I'd like to have the "Description" of the test to be displayed on the TeamCity WebUI as well. How would that be possible? Thanks, A: I would consider making the name of the unit test method self descriptive, as described by Roy Osherove: http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html This is also described in his book,The Art of Unit Testing, here: http://artofunittesting.com/
[ "stackoverflow", "0020458217.txt" ]
Q: HtmlAgilityPack getting tags I'm trying to use HTMLAgilityPack in order to parse an html page and get atom:links in which are contained in item tags . Here's a sample of the html : <item><atom:link href="http://www.nytimes.com/2013/12/09/world/asia/justice-for-abused- afghan-women-still-elusive-un-report-says.html?partner=rss&amp;emc=rss" rel="standout" /> I've trying to get only the atom:link in item tags by doing the following : List<string> urlList = new List<string>(); HtmlAgilityPack.HtmlWeb nytRssPage = new HtmlAgilityPack.HtmlWeb(); HtmlAgilityPack.HtmlDocument nytRssDoc = new HtmlAgilityPack.HtmlDocument(); nytRssDoc = nytRssPage.Load(rssUrl); var items = nytRssDoc.DocumentNode.Descendants("item").ToList();// list of <item> tags foreach (var item in items) { var atomLink = item.SelectSingleNode("atom:link"); string articleUrl = atomLink.InnerText; urlList.Add(articleUrl); } The urlList is empty and I guess I've done something wrong. It would be great if anyone could point me to the solution, thanks in advance. A: To parse an xml, you don't need HtmlAgilityPack var url = "http://www.nytimes.com/services/xml/rss/nyt/International.xml"; var xDoc = XDocument.Load(url); XNamespace atom = "http://www.w3.org/2005/Atom"; var items = xDoc.Descendants("item") .Select(item => new { Title = (string)item.Element("title"), Url = item.Element(atom + "link") != null ? (string)item.Element(atom + "link").Attribute("href") : (string)item.Element("link") }) .ToList(); Alternatively, you can use SyndicationFeed class too var url = "http://www.nytimes.com/services/xml/rss/nyt/International.xml"; var xDoc = XDocument.Load(url); SyndicationFeed feed = SyndicationFeed.Load(xDoc.CreateReader()); Now you can loop feed.Items .
[ "stackoverflow", "0029400756.txt" ]
Q: Shell script self-incremental count as the array index below is a simple shell script code iterating an income file and save the line into an array. But shouldn't the line#4 be like: cusips[$i] rather than cusips[i]? or it doesn't matter? seems both worked. Thanks, john i=0 #line1 while read line # Read a line #line2 do #3 cusips[i]=$line # Put it into the array #line4 i=$(($i + 1)) #line5 done < $1 #line6 A: The difference is in whether or not the value will be substituted before the evaluation of the arithmetic expression. For example, these are all the same: array=(1 1 2 3 5) i=0 echo "${array[i]}" # Look up the variable i echo "${array[$i]}" # Substitute the value of i: look up the value 0 echo "${array[0]}" # Look up the value 0, just like above However, it makes a difference when you start doing operations on variables rather than values: echo "${array[i++]}" # Increment variable i echo "${array[$i++]}" # 0++: syntax error: operand expected echo "${array[0++]}" # Makes no sense, just like above Since you can increment a variable but not a number (i++ works but 0++ doesn't), you can not substitute the variable for its contents before evaluating it with $. The same is true for all other syntax that evaluates as arithmetic expressions, like $((..)). You can replace yours with (( i++ )) but not (( $i++ )). Note that if you use associative arrays, the index will be evaluated as a string and not an arithmetic expression, so ${array[i]} would look up the letter i while ${array[$i]} would look up the number 0.
[ "stackoverflow", "0005598983.txt" ]
Q: Namespace 'Smo' not found, although the reference is added I have added Microsoft.SqlServer.Management.Smo.dll reference to my project, but it still gives me the error below. The referenced dll is in C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies path. Error 25 The type or namespace name 'Smo' does not exist in the namespace 'Microsoft.SqlServer.Management' (are you missing an assembly reference?) All the classes that I use such as Restore, Serer class under the Smo namesapce also throws the error. Please advise. A: Where are you consuming this from? Any chance you're using the client profile (under project properties -> Application -> Target Framework)? I've been caught out a number of times by that. If that's the case, it's usually as simple as selecting a non-client profile framework version. Anyway, can we get some more detail about what kind of solution this is? A: I have had the same problem, I noticed my project was targeting framework 3. Changing to 3.5 or 4 helped solve the problem. My reference are to Microsoft.SqlServer.ConnectionInfo Microsoft.SqlServer.Smo Microsoft.SqlServer.Management.Sdk.Sfc
[ "stackoverflow", "0025795541.txt" ]
Q: Task Monitor Servlet - concurrency issue The Setup: I'm trying to show the progress of a scheduled task in my servlet response. I have a simple test setup that uses three classes to "increment state" of a task for 20 seconds (at 4 second intervals on the minute): Scheduler: import javax.annotation.PostConstruct; import javax.ejb.Schedule; import javax.ejb.Singleton; @Singleton public class TaskScheduler { private Task task; @PostConstruct public void init() { task = new Task(); } @Schedule(hour="*", minute="*", second="0") public void run() { (task = new Task()).run(); // no new Thread, this runs in-line } public String getState() { return task.getState(); } } Task: import java.util.Date; public class Task implements Runnable { private volatile String state = String.format("%s: %s\n", Thread.currentThread().getName(), new Date()); public String getState() { return state; } @Override public void run() { long end = System.currentTimeMillis() + 20000; while (System.currentTimeMillis() < end) { String s = Thread.currentThread().getName(); try { Thread.sleep(4000); } catch (InterruptedException ex) { s = ex.getMessage(); } state += String.format("%s: %s\n", s, new Date()); } } } Servlet: import java.io.IOException; import java.util.Date; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/simple") public class SimpleServlet extends HttpServlet { private static final long serialVersionUID = 1L; @EJB private TaskScheduler scheduler; private String prefix = String.format("%s constructed at %s\n", Thread.currentThread().getName(), new Date()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { prefix += String.format("%s served at %s\n", Thread.currentThread().getName(), new Date()); String s = String.format("%s%s", prefix, scheduler.getState()); resp.getOutputStream().write(s.getBytes()); } } The Problem: While the task is idle, doGet returns immediately with appropriate timestamps/etc but while the task is in progress it is delayed, as if blocking on access to the task's state. Here's some actual sample output I copied from my browser during a delay: http-listener-1(3) constructed at 2014-09-11 17:01:36.600 http-listener-1(3) inited at 2014-09-11 17:01:36.601 http-listener-1(3) served at 2014-09-11 17:01:36.601 http-listener-1(1) served at 2014-09-11 17:01:56.174 http-listener-1(2) served at 2014-09-11 17:01:57.541 http-listener-1(4) served at 2014-09-11 17:01:58.558 http-listener-1(3) served at 2014-09-11 17:01:59.444 http-listener-1(3): 2014-09-11 17:01:36.603 and here's the output that came (all at once) after the delay: http-listener-1(3) constructed at 2014-09-11 17:01:36.600 http-listener-1(3) inited at 2014-09-11 17:01:36.601 http-listener-1(3) served at 2014-09-11 17:01:36.601 http-listener-1(1) served at 2014-09-11 17:01:56.174 http-listener-1(2) served at 2014-09-11 17:01:57.541 http-listener-1(4) served at 2014-09-11 17:01:58.558 http-listener-1(3) served at 2014-09-11 17:01:59.444 http-listener-1(5) served at 2014-09-11 17:02:00.502 __ejb-thread-pool2: 2014-09-11 17:02:00.004 __ejb-thread-pool2: 2014-09-11 17:02:04.005 __ejb-thread-pool2: 2014-09-11 17:02:08.006 __ejb-thread-pool2: 2014-09-11 17:02:12.006 __ejb-thread-pool2: 2014-09-11 17:02:16.006 Things I've tried: removing the "volatile" keyword on Task's "state" adding `@Lock(LockType.READ)` to the Scheduler's getState method adding `@Asynchronous` to the Scheduler's run method I'm deploying to a local Glassfish server (version 4.0, to match my target environment). I got the gist of how to use the @Schedule annotation from this SO question and the gist of Lock annotations from this SO question. The Resolution: Singleton classes default to @ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) and all their methods default to @Lock(LockType.WRITE). When execution enters a LockType.WRITE method it causes the execution of any other methods to wait. You can override this at the class level with @ConcurrencyManagement(ConcurrencyManagementType.BEAN) or by annotating all methods that are suitable for concurrent access with @Lock(LockType.READ). A: Using threads explicitly is generally no good in a EJB environment. They populate/polute the server and might come out of control, causing problems for the server, because they are not controlled by the EJB container. A better solution is to use the @Asynchronous annotation on a method of the singleton for example. With this you can start asynchronous tasks without problems for the server. Edit: Reason, why the doGet() method is blocking: When the Scheduler invokes the EJB's run() method, it will lock the Singleton EJB as a whole, as write protection is the default behavior. After entering run() the Task object's run() method will be called invoking Thread.sleep(...). Meanwhile the EJB's getState() method will be blocked until sleeping is finished, thus blocking the doGet() method of the WebServlet. As the OP says in a later comment, this situation can be overcome by using an annotation @Lock(LockType.READ) above the Singleton's run() method (and above getState()).
[ "scifi.stackexchange", "0000095772.txt" ]
Q: What does Eowyn call Theoden? Theoden calls Eowyn sister-daughter. I assume this is because she is, literally, the daughter of his sister. He also refers to Eomer as his sister-son at one point. What does Eowyn call Theoden in return? A: As far as I can tell, in the books, Eowyn referred to Theoden by any title only three times. She was very quiet in the Two Towers. She only spoke twice: Once when offering Theoden wine after his recovery, and once when Theoden appointed her as guardian of Edoras as he departed. Neither of those times did she use any address other than his name. In Return of the King, she only spoke to him a couple of times. On his arrival at Dunharrow: 'Hail, Lord of the Mark!' she cried. 'My heart is glad at your returning.' and later: He pointed away along the darkening lines of stones towards the Dwimorberg. 'Of the Paths of the Dead?' 'Yes, lord,' said Éowyn. 'And he has passed into the shadows from which none have returned. I could not dissuade him. He is gone.' Sadly, in the books, Theoden died on the Pelennor Fields before he knew Eowyn was there. She mentioned him once when she awoke in the Houses of Healing: ' I am strangely weary,' she said. 'I must rest a little. But tell me, what of the Lord of the Mark? Alas! Do not tell me that that was a dream for I know that it was not. He is dead as he foresaw.' This isn't particularly surprising -- in the real world, even the family of British royalty are expected to greet Royalty by "Your Majesty" (and lower nobility by their titles, including "My Lord"). The Queen, however, can call you whatever she damn well pleases. A: This is probably a linguistics question. The Rohirric language created by Tolkien has the specific family naming features of Old English that modern english has dropped. E.G. https://www.umanitoba.ca/faculties/arts/anthropology/tutor/kinterms/oldenglish.html If it's not in the texts, I would speculate Tolkien would have made it 'Éam', which is what I think you're asking. In the books, his role as ruler is primary and calling him 'uncle' in public would probably be disrespectful. This might be helpful. https://en.wikipedia.org/wiki/Rohirric As a counterpoint, most cultures of India make even less distinction of familial roles. 'Uncle' means someone of about my father's age, whether they are related or not.
[ "stackoverflow", "0056709674.txt" ]
Q: How do you search through a directory and take actions? I am looking to make a batch file which will sift through a directory full of computer backups. The file format is "computername-date." Since I know the computer name is static, I need to find and take that directory so I can restore it's contents. I never realized that for loops are so foreign from what I play with in other languages, so I find myself getting nowhere anytime soon. REM First mount the drive that contains the backed up files net use P: \\DC1\Shared\1Backups REM Get the computer's name so we know what PC backup to use. set SaveDirectory=%computername% REM For each folder in the directory, do this when the computer name is found. FOR /R "P:\" %%G in (%SaveDirectory%*) DO ( REM Restore files echo found it. REM Copy subdirectories into User Folder mkdir P:\UGH ) REM Dismount drive The problem with what I have now is that when I run the code, the DO never runs. It should find that there is a folder called "INTERN-6.21.2019" by searching "INTERN*" My impression of the for statement may be wrong. I need it to search through the P:/ Directory, not the subfolders. Compare the folder names to the SavedDirectory, then do something when they match. What am I doing wrong? A: I've normally had good results with using CALL statements to invoke a subroutine rather than running items inside ( ). The trick here is that you need to pass arguments to the the subroutine. Typically you'd pass the variable(s) you use in your FOR statement. These are referenced using %1 (or %1 %2 %3 if you have multiple things to pass) because these act like command line arguments. To exit the subroutine you then jump to EOF which then returns control to your FOR loop. After your FOR loop, don't forget to jump over your subroutine or you'll execute it again. In the example below I jump to :end, but you certainly could jump to somewhere else to do more things. So using this methodology, your code might be like this: set SaveDirectory=%computername% FOR /R "P:\" %%G in (%SaveDirectory%*) DO CALL :process %%G Goto :end :process REM Processing goes here goto :end :end Hope this helps
[ "stackoverflow", "0041406986.txt" ]
Q: How do I constrain texts and elements inside a div I am creating a webpage using only CSS & HTML Everything looks fine until I zoom in. Once I zoom in the letters start to flow out of the div. How do I fix this ? A: Your problem has to do with responsive webdesign. By default people create there website for there own screens. But not everyone has the same screen resolution or viewport etc as you have. The solution: Media queries: With media queries you can alter you css code when the user has a different resolution/viewport or is resizing there screen. @media (max-width: 979px) { .h2 { font-size: 10px; } } This will change the font of a the h2 tag to 10px when the screen width of the user is smaller then 979px. I will provide you with a link to a w3Schools page so you can see what kind of attributes the @media rule has. Media queries w3cschools tip: You can see your resolution by opening the chrome developer tools and resizing your browser.(left top corner) If you have any future questions please let me know I will explain some more about media queries.
[ "ethereum.stackexchange", "0000027281.txt" ]
Q: Ether stolen from contracts Can anyone explain what is exactly the point of this claim https://medium.com/@rtaylor30/how-i-snatched-your-153-037-eth-after-a-bad-tinder-date-d1d84422a50b A: The author mentions on his update below that this was a fictional post, but based on what actually happened in the parity hack. He points out technically the vulnerability in the contracts and how simply it could be exploited. I would think the point is to make people aware of the hacks and the vulnerabilities so that developers can avoid them in the future. Since the language and ecosystem are so new, and we're in a completely different kind of programming where all code is immutable and public (complete open book to any would-be hacker), the community is fairly quick to respond, support, and educate others.
[ "bicycles.stackexchange", "0000041766.txt" ]
Q: securing disk brakes against theft in a low-visibility locked bike room I have once again had my disk brake stolen on my bike in my apartment building. Being a high rise they forbid us taking bikes up in the elevator (and I don't really have the space to store it anyway). But they don't put any camera in the locked bike room. So, people from the building can just go in at night and take out the brakes. The first time (different building), it was the whole wheel and the brake. This time, they left the wheel alone, but took out the brake handle, cable and the clamp. It's incredibly annoying to replace a $150 part every time some loser decides to steal in his own building. What are some possible strategies to deter that? Locking the wheel would be an option, using an extra lock. But I don't think it would stop someone from just removing the brake components. I have had a suggestion for non-standard fixation bolts. Also, Deterrents against partial (component) theft they suggest gluing the parts together. Or soldering in the head of the bolts. It's a nice, but old-ish bike that I don't intend to sell - I don't mind scuffing it up a bit to secure the brakes. Any suggestions? Keeping in mind that it should stop someone from easily ripping off the brakes in a 15-30 minute time frame, using regular tools. i.e. just get the loser to steal from another unsecured bike. Another would be to install a spy camera and catch the person in the act. That might work, but they could also steal the camera if they see it. And it's a 400-500 person building, no guarantee they are easily recognizable. Or a sound alarm. But the bike can easily be jostled by someone just trying to get at his own bike in the next rack over. In any case, the solution only really needs to work in my building, so it can be fairly heavy, as long as I can just leave it on my assigned bike rack. A: Realistically there's nothing you can do to stop a thief who has regular, unsupervised access to your bike from stealing parts of it. You can only have nothing he wants to steal, or not put your bike there. But you can make it more annoying for him (at the risk of vandalism, either accidentally when trying to steal stuff, or deliberately out of frustration). There is a whole world of "secure" bolts out there, and a matching world of drivers for those bolts. At best it's "security through obscurity" but in reality someone who wants to steal your bike parts can buy a $20 set of "200 different security drivers" and remove 99% of those very easily. We've had a question about those closed as too broad, which really translates to "impossible to answer". Most of the solutions I've seen just add time and tools to the removal process, which doesn't really help when the thief can check up on what you do then come back a few days later with different tools. Using ball bearings in the heads, or hose clamps over them, is unlikely to work for that reason. One fairly easy approach is to buy a roll of stainless steel wire and a crimping tool. They're not too expensive and the wire is lightweight. Once you have one they turn out to be quite useful, and with ~2mm wire you can tie components to your bike. It's relatively easy to cut the wire with decent side-cutters or cable cutters, but hard to cut with bolt cutters because it's too thin. It's also harder for a thief caught in the act or on camera to argue that it's their bike they're working on... because if everything is tied on, where is their replacement wire and crimping tool? (both via SWR.com) One problem is that you don't know whether it was a one-off theft by someone who wanted the brakes for themselves, or a theft for sale. If the latter I'd expect more stuff to go missing on an ongoing basis, which means you reporting the theft is important. The sooner building management know there's a problem the sooner they can act.
[ "stackoverflow", "0059367202.txt" ]
Q: Swift Combine: Buffer upstream values and emit them at a steady rate? Using the new Combine framework in iOS 13. Suppose I have an upstream publisher sending values at a highly irregular rate - sometimes seconds or minutes may go by without any values, and then a stream of values may come through all at once. I'd like to create a custom publisher that subscribes to the upstream values, buffers them and emits them at a regular, known cadence when they come in, but publishes nothing if they've all been exhausted. For a concrete example: t = 0 to 5000ms: no upstream values published t = 5001ms: upstream publishes "a" t = 5002ms: upstream publishes "b" t = 5003ms: upstream publishes "c" t = 5004ms to 10000ms: no upstream values published t = 10001ms: upstream publishes "d" My publisher subscribed to the upstream would produce values every 1 second: t = 0 to 5000ms: no values published t = 5001ms: publishes "a" t = 6001ms: publishes "b" t = 7001ms: publishes "c" t = 7001ms to 10001ms: no values published t = 10001ms: publishes "d" None of the existing publishers or operators in Combine seem to quite do what I want here. throttle and debounce would simply sample the upstream values at a certain cadence and drop ones that are missing (e.g. would only publish "a" if the cadence was 1000ms) delay would add the same delay to every value, but not space them out (e.g. if my delay was 1000ms, it would publish "a" at 6001ms, "b" at 6002ms, "c" at 6003ms) buffer seems promising, but I can't quite figure out how to use it - how to force it to publish a value from the buffer on demand. When I hooked up a sink to buffer it seemed to just instantly publish all the values, not buffering at all. I thought about using some sort of combining operator like zip or merge or combineLatest and combining it with a Timer publisher, and that's probably the right approach, but I can't figure out exactly how to configure it to give the behavior I want. Edit Here's a marble diagram that hopefully illustrates what I'm going for: Upstream Publisher: -A-B-C-------------------D-E-F--------|> My Custom Operator: -A----B----C-------------D----E----F--|> Edit 2: Unit Test Here's a unit test that should pass if modulatedPublisher (my desired buffered publisher) works as desired. It's not perfect, but it stores events (including the time received) as they're received and then compares the time intervals between events, ensuring they are no smaller than the desired interval. func testCustomPublisher() { let expectation = XCTestExpectation(description: "async") var events = [Event]() let passthroughSubject = PassthroughSubject<Int, Never>() let cancellable = passthroughSubject .modulatedPublisher(interval: 1.0) .sink { value in events.append(Event(value: value, date: Date())) print("value received: \(value) at \(self.dateFormatter.string(from:Date()))") } // WHEN I send 3 events, wait 6 seconds, and send 3 more events passthroughSubject.send(1) passthroughSubject.send(2) passthroughSubject.send(3) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(6000)) { passthroughSubject.send(4) passthroughSubject.send(5) passthroughSubject.send(6) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(4000)) { // THEN I expect the stored events to be no closer together in time than the interval of 1.0s for i in 1 ..< events.count { let interval = events[i].date.timeIntervalSince(events[i-1].date) print("Interval: \(interval)") // There's some small error in the interval but it should be about 1 second since I'm using a 1s modulated publisher. XCTAssertTrue(interval > 0.99) } expectation.fulfill() } } wait(for: [expectation], timeout: 15) } The closest I've gotten is using zip, like so: public extension Publisher where Self.Failure == Never { func modulatedPublisher(interval: TimeInterval) -> AnyPublisher<Output, Never> { let timerBuffer = Timer .publish(every: interval, on: .main, in: .common) .autoconnect() return timerBuffer .zip(self, { $1 }) // should emit one input element ($1) every timer tick .eraseToAnyPublisher() } } This properly attunes the first three events (1, 2, and 3), but not the second three (4, 5, and 6). The output: value received: 1 at 3:54:07.0007 value received: 2 at 3:54:08.0008 value received: 3 at 3:54:09.0009 value received: 4 at 3:54:12.0012 value received: 5 at 3:54:12.0012 value received: 6 at 3:54:12.0012 I believe this is happening because zip has some internal buffering capacity. The first three upstream events are buffered and emitted on the Timer's cadence, but during the 6 second wait, the Timer's events are buffered - and when the second set ups upstream events are fired, there are already Timer events waiting in the queue, so they're paired up and fired off immediately. A: This is an interesting problem. I played with various combinations of Timer.publish, buffer, zip, and throttle, but I couldn't get any combination to work quite the way you want. So let's write a custom subscriber. What we'd really like is an API where, when we get an input from upstream, we also get the ability to control when the upstream delivers the next input. Something like this: extension Publisher { /// Subscribe to me with a stepping function. /// - parameter stepper: A function I'll call with each of my inputs, and with my completion. /// Each time I call this function with an input, I also give it a promise function. /// I won't deliver the next input until the promise is called with a `.more` argument. /// - returns: An object you can use to cancel the subscription asynchronously. func step(with stepper: @escaping (StepEvent<Output, Failure>) -> ()) -> AnyCancellable { ??? } } enum StepEvent<Input, Failure: Error> { /// Handle the Input. Call `StepPromise` when you're ready for the next Input, /// or to cancel the subscription. case input(Input, StepPromise) /// Upstream completed the subscription. case completion(Subscribers.Completion<Failure>) } /// The type of callback given to the stepper function to allow it to continue /// or cancel the stream. typealias StepPromise = (StepPromiseRequest) -> () enum StepPromiseRequest { // Pass this to the promise to request the next item from upstream. case more // Pass this to the promise to cancel the subscription. case cancel } With this step API, we can write a pace operator that does what you want: extension Publisher { func pace<Context: Scheduler, MySubject: Subject>( _ pace: Context.SchedulerTimeType.Stride, scheduler: Context, subject: MySubject) -> AnyCancellable where MySubject.Output == Output, MySubject.Failure == Failure { return step { switch $0 { case .input(let input, let promise): // Send the input from upstream now. subject.send(input) // Wait for the pace interval to elapse before requesting the // next input from upstream. scheduler.schedule(after: scheduler.now.advanced(by: pace)) { promise(.more) } case .completion(let completion): subject.send(completion: completion) } } } } This pace operator takes pace (the required interval between outputs), a scheduler on which to schedule events, and a subject on which to republish the inputs from upstream. It handles each input by sending it through subject, and then using the scheduler to wait for the pace interval before asking for the next input from upstream. Now we just have to implement the step operator. Combine doesn't give us too much help here. It does have a feature called “backpressure”, which means a publisher cannot send an input downstream until the downstream has asked for it by sending a Subscribers.Demand upstream. Usually you see downstreams send an .unlimited demand upstream, but we're not going to. Instead, we're going to take advantage of backpressure. We won't send any demand upstream until the stepper completes a promise, and then we'll only send a demand of .max(1), so we make the upstream operate in lock-step with the stepper. (We also have to send an initial demand of .max(1) to start the whole process.) Okay, so need to implement a type that takes a stepper function and conforms to Subscriber. It's a good idea to review the Reactive Streams JVM Specification, because Combine is based on that specification. What makes the implementation difficult is that several things can call into our subscriber asynchronously: The upstream can call into the subscriber from any thread (but is required to serialize its calls). After we've given promise functions to the stepper, the stepper can call those promises on any thread. We want the subscription to be cancellable, and that cancellation can happen on any thread. All this asynchronicity means we have to protect our internal state with a lock. We have to be careful not to call out while holding that lock, to avoid deadlock. We'll also protect the subscriber from shenanigans involving calling a promise repeatedly, or calling outdated promises, by giving each promise a unique id. Se here's our basic subscriber definition: import Combine import Foundation public class SteppingSubscriber<Input, Failure: Error> { public init(stepper: @escaping Stepper) { l_state = .subscribing(stepper) } public typealias Stepper = (Event) -> () public enum Event { case input(Input, Promise) case completion(Completion) } public typealias Promise = (Request) -> () public enum Request { case more case cancel } public typealias Completion = Subscribers.Completion<Failure> private let lock = NSLock() // The l_ prefix means it must only be accessed while holding the lock. private var l_state: State private var l_nextPromiseId: PromiseId = 1 private typealias PromiseId = Int private var noPromiseId: PromiseId { 0 } } Notice that I moved the auxiliary types from earlier (StepEvent, StepPromise, and StepPromiseRequest) into SteppingSubscriber and shortened their names. Now let's consider l_state's mysterious type, State. What are all the different states our subscriber could be in? We could be waiting to receive the Subscription object from upstream. We could have received the Subscription from upstream and be waiting for a signal (an input or completion from upstream, or the completion of a promise from the stepper). We could be calling out to the stepper, which we want to be careful in case it completes a promise while we're calling out to it. We could have been cancelled or have received completion from upstream. So here is our definition of State: extension SteppingSubscriber { private enum State { // Completed or cancelled. case dead // Waiting for Subscription from upstream. case subscribing(Stepper) // Waiting for a signal from upstream or for the latest promise to be completed. case subscribed(Subscribed) // Calling out to the stopper. case stepping(Stepping) var subscription: Subscription? { switch self { case .dead: return nil case .subscribing(_): return nil case .subscribed(let subscribed): return subscribed.subscription case .stepping(let stepping): return stepping.subscribed.subscription } } struct Subscribed { var stepper: Stepper var subscription: Subscription var validPromiseId: PromiseId } struct Stepping { var subscribed: Subscribed // If the stepper completes the current promise synchronously with .more, // I set this to true. var shouldRequestMore: Bool } } } Since we're using NSLock (for simplicity), let's define an extension to ensure we always match locking with unlocking: fileprivate extension NSLock { @inline(__always) func sync<Answer>(_ body: () -> Answer) -> Answer { lock() defer { unlock() } return body() } } Now we're ready to handle some events. The easiest event to handle is asynchronous cancellation, which is the Cancellable protocol's only requirement. If we're in any state except .dead, we want to become .dead and, if there's an upstream subscription, cancel it. extension SteppingSubscriber: Cancellable { public func cancel() { let sub: Subscription? = lock.sync { defer { l_state = .dead } return l_state.subscription } sub?.cancel() } } Notice here that I don't want to call out to the upstream subscription's cancel function while lock is locked, because lock isn't a recursive lock and I don't want to risk deadlock. All use of lock.sync follows the pattern of deferring any call-outs until after the lock is unlocked. Now let's implement the Subscriber protocol requirements. First, let's handle receiving the Subscription from upstream. The only time this should happen is when we're in the .subscribing state, but .dead is also possible in which case we want to just cancel the upstream subscription. extension SteppingSubscriber: Subscriber { public func receive(subscription: Subscription) { let action: () -> () = lock.sync { guard case .subscribing(let stepper) = l_state else { return { subscription.cancel() } } l_state = .subscribed(.init(stepper: stepper, subscription: subscription, validPromiseId: noPromiseId)) return { subscription.request(.max(1)) } } action() } Notice that in this use of lock.sync (and in all later uses), I return an “action” closure so I can perform arbitrary call-outs after the lock has been unlocked. The next Subscriber protocol requirement we'll tackle is receiving a completion: public func receive(completion: Subscribers.Completion<Failure>) { let action: (() -> ())? = lock.sync { // The only state in which I have to handle this call is .subscribed: // - If I'm .dead, either upstream already completed (and shouldn't call this again), // or I've been cancelled. // - If I'm .subscribing, upstream must send me a Subscription before sending me a completion. // - If I'm .stepping, upstream is currently signalling me and isn't allowed to signal // me again concurrently. guard case .subscribed(let subscribed) = l_state else { return nil } l_state = .dead return { [stepper = subscribed.stepper] in stepper(.completion(completion)) } } action?() } The most complex Subscriber protocol requirement for us is receiving an Input: We have to create a promise. We have to pass the promise to the stepper. The stepper could complete the promise before returning. After the stepper returns, we have to check whether it completed the promise with .more and, if so, return the appropriate demand upstream. Since we have to call out to the stepper in the middle of this work, we have some ugly nesting of lock.sync calls. public func receive(_ input: Input) -> Subscribers.Demand { let action: (() -> Subscribers.Demand)? = lock.sync { // The only state in which I have to handle this call is .subscribed: // - If I'm .dead, either upstream completed and shouldn't call this, // or I've been cancelled. // - If I'm .subscribing, upstream must send me a Subscription before sending me Input. // - If I'm .stepping, upstream is currently signalling me and isn't allowed to // signal me again concurrently. guard case .subscribed(var subscribed) = l_state else { return nil } let promiseId = l_nextPromiseId l_nextPromiseId += 1 let promise: Promise = { request in self.completePromise(id: promiseId, request: request) } subscribed.validPromiseId = promiseId l_state = .stepping(.init(subscribed: subscribed, shouldRequestMore: false)) return { [stepper = subscribed.stepper] in stepper(.input(input, promise)) let demand: Subscribers.Demand = self.lock.sync { // The only possible states now are .stepping and .dead. guard case .stepping(let stepping) = self.l_state else { return .none } self.l_state = .subscribed(stepping.subscribed) return stepping.shouldRequestMore ? .max(1) : .none } return demand } } return action?() ?? .none } } // end of extension SteppingSubscriber: Publisher The last thing our subscriber needs to handle is the completion of a promise. This is complicated for several reasons: We want to protect against a promise being completed multiple times. We want to protect against an older promise being completed. We can be in any state when a promise is completed. Thus: extension SteppingSubscriber { private func completePromise(id: PromiseId, request: Request) { let action: (() -> ())? = lock.sync { switch l_state { case .dead, .subscribing(_): return nil case .subscribed(var subscribed) where subscribed.validPromiseId == id && request == .more: subscribed.validPromiseId = noPromiseId l_state = .subscribed(subscribed) return { [sub = subscribed.subscription] in sub.request(.max(1)) } case .subscribed(let subscribed) where subscribed.validPromiseId == id && request == .cancel: l_state = .dead return { [sub = subscribed.subscription] in sub.cancel() } case .subscribed(_): // Multiple completion or stale promise. return nil case .stepping(var stepping) where stepping.subscribed.validPromiseId == id && request == .more: stepping.subscribed.validPromiseId = noPromiseId stepping.shouldRequestMore = true l_state = .stepping(stepping) return nil case .stepping(let stepping) where stepping.subscribed.validPromiseId == id && request == .cancel: l_state = .dead return { [sub = stepping.subscribed.subscription] in sub.cancel() } case .stepping(_): // Multiple completion or stale promise. return nil } } action?() } } Whew! With all that done, we can write the real step operator: extension Publisher { func step(with stepper: @escaping (SteppingSubscriber<Output, Failure>.Event) -> ()) -> AnyCancellable { let subscriber = SteppingSubscriber<Output, Failure>(stepper: stepper) self.subscribe(subscriber) return .init(subscriber) } } And then we can try out that pace operator from above. Since we don't do any buffering in SteppingSubscriber, and the upstream in general isn't buffered, we'll stick a buffer in between the upstream and our pace operator. var cans: [AnyCancellable] = [] func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let erratic = Just("A").delay(for: 0.0, tolerance: 0.001, scheduler: DispatchQueue.main).eraseToAnyPublisher() .merge(with: Just("B").delay(for: 0.3, tolerance: 0.001, scheduler: DispatchQueue.main).eraseToAnyPublisher()) .merge(with: Just("C").delay(for: 0.6, tolerance: 0.001, scheduler: DispatchQueue.main).eraseToAnyPublisher()) .merge(with: Just("D").delay(for: 5.0, tolerance: 0.001, scheduler: DispatchQueue.main).eraseToAnyPublisher()) .merge(with: Just("E").delay(for: 5.3, tolerance: 0.001, scheduler: DispatchQueue.main).eraseToAnyPublisher()) .merge(with: Just("F").delay(for: 5.6, tolerance: 0.001, scheduler: DispatchQueue.main).eraseToAnyPublisher()) .handleEvents( receiveOutput: { print("erratic: \(Double(DispatchTime.now().rawValue) / 1_000_000_000) \($0)") }, receiveCompletion: { print("erratic: \(Double(DispatchTime.now().rawValue) / 1_000_000_000) \($0)") } ) .makeConnectable() let subject = PassthroughSubject<String, Never>() cans += [erratic .buffer(size: 1000, prefetch: .byRequest, whenFull: .dropOldest) .pace(.seconds(1), scheduler: DispatchQueue.main, subject: subject)] cans += [subject.sink( receiveCompletion: { print("paced: \(Double(DispatchTime.now().rawValue) / 1_000_000_000) \($0)") }, receiveValue: { print("paced: \(Double(DispatchTime.now().rawValue) / 1_000_000_000) \($0)") } )] let c = erratic.connect() cans += [AnyCancellable { c.cancel() }] return true } And here, at long last, is the output: erratic: 223394.17115897 A paced: 223394.171495405 A erratic: 223394.408086369 B erratic: 223394.739186984 C paced: 223395.171615624 B paced: 223396.27056174 C erratic: 223399.536717127 D paced: 223399.536782847 D erratic: 223399.536834495 E erratic: 223400.236808469 F erratic: 223400.236886323 finished paced: 223400.620542561 E paced: 223401.703613078 F paced: 223402.703828512 finished Timestamps are in units of seconds. The erratic publisher's timings are, indeed, erratic and sometimes close in time. The paced timings are always at least one second apart even when the erratic events occur less than one second apart. When an erratic event occurs more than one second after the prior event, the paced event is sent immediately following the erratic event without further delay. The paced completion occurs one second after the last paced event, even though the erratic completion occurs immediately after the last erratic event. The buffer doesn't send the completion until it receives another demand after it sends the last event, and that demand is delayed by the pacing timer. I've put the the entire implementation of the step operator in this gist for easy copy/paste. A: EDIT There's an even simpler approach to the original one outlined below, which doesn't require a pacer, but instead uses back-pressure created by flatMap(maxPublishers: .max(1)). flatMap sends a demand of 1, until its returned publisher, which we could delay, completes. We'd need a Buffer publisher upstream to buffer the values. // for demo purposes, this subject sends a Date: let subject = PassthroughSubject<Date, Never>() let interval = 1.0 let pub = subject .buffer(size: .max, prefetch: .byRequest, whenFull: .dropNewest) .flatMap(maxPublishers: .max(1)) { Just($0) .delay(for: .seconds(interval), scheduler: DispatchQueue.main) } ORIGINAL I know this is an old question, but I think there's a much simpler way to implement this, so I thought I'd share. The idea is similar to a .zip with a Timer, except instead of a Timer, you would .zip with a time-delayed "tick" from a previously sent value, which can be achieved with a CurrentValueSubject. CurrentValueSubject is needed instead of a PassthroughSubject in order to seed the first ever "tick". // for demo purposes, this subject sends a Date: let subject = PassthroughSubject<Date, Never>() let pacer = CurrentValueSubject<Void, Never>(()) let interval = 1.0 let pub = subject.zip(pacer) .flatMap { v in Just(v.0) // extract the original value .delay(for: .seconds(interval), scheduler: DispatchQueue.main) .handleEvents(receiveOutput: { _ in pacer.send() // send the pacer "tick" after the interval }) } What happens is that the .zip gates on the pacer, which only arrives after a delay from a previously sent value. If the next value comes earlier than the allowed interval, it waits for the pacer. If, however, the next value comes later, then the pacer already has a new value to provide instantly, so there would be no delay. If you used it like in your test case: let c = pub.sink { print("\($0): \(Date())") } subject.send(Date()) subject.send(Date()) subject.send(Date()) DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { subject.send(Date()) subject.send(Date()) } DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) { subject.send(Date()) subject.send(Date()) } the result would be something like this: 2020-06-23 19:15:21 +0000: 2020-06-23 19:15:21 +0000 2020-06-23 19:15:21 +0000: 2020-06-23 19:15:22 +0000 2020-06-23 19:15:21 +0000: 2020-06-23 19:15:23 +0000 2020-06-23 19:15:22 +0000: 2020-06-23 19:15:24 +0000 2020-06-23 19:15:22 +0000: 2020-06-23 19:15:25 +0000 2020-06-23 19:15:32 +0000: 2020-06-23 19:15:32 +0000 2020-06-23 19:15:32 +0000: 2020-06-23 19:15:33 +0000
[ "stackoverflow", "0033640301.txt" ]
Q: How can I adjust the size of an imported PNG file in SAS RTF output? The response to the question Is it possible to import a PNG file into SAS to include in RTF output? gave a way to use an external PNG file in SAS ODS RTF output. In order for the provided solution to work, it requires text to follow the insertion of the image file. One way that I used to make it work even when I didn't have text that followed the image was to insert underscores following the image which would serve has a bottom border prior to the footnotes; however, this does not conform to the other outputs that are created for this project, so I'm looking for a way to import a PNG that maintains the essential formatting. Additionally, I would like to be able to adjust the display size of the image. Currently, I have to make sure that the image size is exactly right when it is created so that it doesn't overrun the borders, but this creates an image that is more pixelated than I would like. I would like to be able to force it to be the exactly the desired size from SAS, so that I can have some flexibility in the size when I create the image and produce an image that is high enough quality in the RTF file. While this may seem like separate questions, it seems to me that the solution to one problem will likely address both, as you'll see below. Here is some code to produce a minimal example: /* Create test data */ data test; drop i; call streaminit(1579); do i = 1 to 200; u = rand("Normal"); output; end; run; /* Create a PNG file to bring into the RTF -- the PNG will actually be created outside of SAS but is included here for convenience */ proc sgplot data=test; density u / type=kernel; run; /* Set options for RTF output */ option nodate nonumber; ods rtf file = "test.rtf" nogtitle nogfoot ods escapechar='~'; /* Titles and footnotes */ title 'Title'; /* Border line at the start of the footnote section */ footnote height=2pt '~R"\brdrb\brdrs\brdrw30'; footnote2 j=l 'Footnote'; /* Import the image and output into the RTF */ ods text='~S={preimage="SGPlot1.png"}'; ods rtf close; The above code produces a document that looks like this: That thin vertical line in the body is the image. If I drag the handles to the right, the full image appears. I would like to be able to create the equivalent of the following code without creating the image in SAS: /* Set options for RTF output */ option nodate nonumber; ods rtf file = "test1.rtf" nogtitle nogfoot; ods escapechar='~'; /* Titles and footnotes */ title 'Title'; /* Border line at the start of the footnote section */ footnote height=2pt '~R"\brdrb\brdrs\brdrw30'; footnote2 j=l 'Footnote'; ods graphics / height=9in width=7in; /* Import the image and output into the RTF */ proc sgplot data=test; density u / type=kernel; run; ods rtf close; This code produces the following: Notice that I've enlarged the image (SAS will automatically adjust pixels etc. when creating the image, but this is not necessary since the PNG file will already be created). Notice also that the image is actually displayed when the RTF is produced and doesn't require any post processing. Is this possible? A: After some investigation I found there are two parts to this answer. Making the image show up at all instead of having no width can be done by adding width=100% to the style as follows: ods text='~S={width=100% preimage="SGPlot1.png"}'; Adjusting the dimensions of the image is a little more hack-ish, but it can be done by reading the file in as text and replacing the rtf control words pichgoalN and picwgoalN with the desired height and width in twips (a twip is 1/1440 inch). Here's how I did it: data edit; infile "test.rtf" dlm='09'x dsd lrecl=32767 missover; format var $200. varout $200.; input var $; varout = prxchange("s/pichgoal\d+/pichgoal12960/",-1,var); varout = prxchange("s/picwgoal\d+/picwgoal10080/",-1,varout); run; data _null_ ; set edit ; FILE 'test1.rtf'; PUT varout; run ;
[ "stackoverflow", "0027616142.txt" ]
Q: polymer - simple JS to open an overlay I'm looking at the code for core-overlay demo and trying to extract what I need to open an overlay from JS. I'm really looking for the equivalent of $("#overlay").toggle() I created an overlay and gave it an ID, but i think maybe that's a naive approach. html <core-overlay id='overlay'> <h2>Dialog</h2> <input placeholder="say something..." autofocus> <div>I agree with this wholeheartedly.</div> <button core-overlay-toggle>OK</button> </core-overlay> the docs page gives the markup info and there is a "toggle" event that would open the overlay: Toggle Toggle the opened state of the overlay https://www.polymer-project.org/docs/elements/core-elements.html#core-overlay however, how do I get at the actual overlay object to send this event to it? the demo page is extremely verbose. there is this: Polymer('x-container', { tapHandler: function() { this.$.dialog.toggle(); } } but i'm not sure what the this.$.dialog is in that case. does all Polymer related events have to be declaratively setup within it's own little Polymer('x-blahblahblah') block or can i just send events to objects from my own JS code? Update: this works: overlay = document.getElementByID("overlay") overlay.open() but I'm leaving the question open as I'm sure this is not the "right" way to use polymer. However the examples code seems also extremely verbose, obviously to sit in with some type of auto-generation of demos for their docs. It would be nice to see a lean-and-mean simple JS + polymer demo. A: to call a method of a polymer element that in inside another polymer element you would use this.$.id.method(); example <polymer-element name="example-element"> <template> <paper-buton on-tap="{{method1}}">Call Method</paper-button> <core-overlay id='overlay'> <h2>Dialog</h2> <input placeholder="say something..." autofocus> <div>I agree with this wholeheartedly.</div> <button core-overlay-toggle>OK</button> </core-overlay> </template> <script> Polymer({ method1: function () { this.$.overlay.toggle(); } }); </script> </polymer-element> then to call method1 from your main JS file you would use document.querySelector('example-element').method1(); you could also replace example-element with a id #id calling the method from main page JS with click handler could look something like document.querySelector('#button').addEventListener('click', function () { document.querySelector('example-element').method1(); }); the #button id is just a generic id could be anything
[ "stackoverflow", "0005790215.txt" ]
Q: Can a GridView have a footer and header just like ListView? A quick question: In ListView I use this code: list.addHeaderView(headerView); How to deal with it when working on gridview? Thanks. A: There is no support for header or footer views with GridView, sorry. A: There is a quite good implementation of GridView with header support in Google Photos application, as it's OSS code you can use it as is or take it as a reference for your own implementation: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android-apps/4.3_r2.1/com/android/photos/views/HeaderGridView.java Basic idea is quite simple - WrapperAdapter creates an fake row by increasing number of items by number of columns and then return a header view for the item. A: You can use this. The footer appears/hides at the bottom of the grid when you reach/leave the last number of items. It does not actually scroll, but I hardly notice the difference. In your activity/fragment's onCreate/onCreateView you add an OnScrollListener to the GridView: .... GridView gridview = (YMAnimatedGridview) v.findViewById(R.id.my_gridview); gridview.setAdapter(adapter); final View footerView = mainView .findViewById(R.id.my_grid_footer_view); gridview.setOnScrollListener(new GridView.OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (firstVisibleItem + visibleItemCount == totalItemCount) { // last item in grid is on the screen, show footer: footerView.setVisibility(View.VISIBLE); } else if (footerView.getVisibility() != View.GONE) { // last item in grid not on the screen, hide footer: footerView.setVisibility(View.GONE); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } }); Your layout should look something like the below. Notice the layout_weight (and layout_height) parameter in the gridview, it is needed to make the correct space for the footer when it becomes visible. <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <GridView android:id="@+id/my_gridview" android:layout_width="match_parent" android:layout_height="0dp" android:columnWidth="160dp" android:gravity="center_horizontal" android:horizontalSpacing="12dp" android:numColumns="auto_fit" android:layout_weight="1" android:stretchMode="columnWidth" android:verticalSpacing="6dp" /> <TextView android:id="@+id/my_grid_footer_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:layout_marginBottom="8dp" android:orientation="horizontal" android:visibility="gone" android:text="footer text here" > </TextView> </LinearLayout>
[ "stackoverflow", "0044317204.txt" ]
Q: Trying to append child to all elements with same class name I am trying to use the appendChild() method to add a document.createElement("div") element to multiple <div> elements with the same class name. I have tried this way: const childElement = document.createElement("div"); childElement.className = "second"; const parentObject = document.getElementsByClassName("first"); [...parentObject].map(parent => parent.appendChild(childElement)) Which didnt work, so I tried: for(let i = 0; i < parentObject.length; i++){ parentObject[i].appendChild(childElement); } The only way it worked was if I wrote the html element myself and then added it to the innerHTML of each parent: [...parentObject].map(parent => parent.innerHTML = "<div class='second'></div>") But since I am generating all different kind of HTML element tags, like IMG, DIV, SPAN I need the convenience of calling the createElement() method. Has anyone any experience with this? A: An element can only exist in one place in the DOM. What you need to do is create a new element to append to each parent: const parentObject = document.getElementsByClassName('first'); [...parentObject].forEach((parent, i) => { const childElement = document.createElement('div'); childElement.className = 'second'; childElement.innerHTML = `second ${i}`; parent.appendChild(childElement) }); div { padding: 5px; } .first { background-color: pink; display: inline-block; } .second { background-color: lightblue; } <div class="first">first</div> <div class="first">first</div> <div class="first">first</div> <div class="first">first</div>
[ "stackoverflow", "0040216639.txt" ]
Q: mongodb connection timed out error I have used mongodb database and node.js v12.0.10 for connecting and updating mongodb collection. connection code is the following: async.parallel({ RE5: function (cb) { MongoClient.connect(config.riskEngineDB, function (err, r5DB) { cb(err, r5DB); }) }, MDB: function (cb) { MongoClient.connect(config.monitoringDB, function (err, mDB) { cb(err, mDB); }) } }, function (err, DBs) { assert.equal(null, err); console.log("Connected correctly to Dbs"); // ..doing updates.. }) after some time running, script printed the following error: { [MongoError: connection 39 to 127.0.0.1:27017 timed out] name: 'MongoError', message: 'connection 39 to 127.0.0.1:27017 timed out' } For your information, I used different options of connections of mongodb but it didn't make sense. A: I had a similar experience, due to a query which took too much time to reply you have 2 configurable timeouts in node mongo driver: connectTimeoutMS and socketTimeoutMS, both defaulting to 30sec ( http://mongodb.github.io/node-mongodb-native/2.2/reference/connecting/connection-settings/ ) if your query takes longer than 30sec to send its first result, it'll end with a connection timed out error. if your query takes more than 30sec between two results, it'll probably end with that connection closing due to pool shrinking. You may want to increase timeouts, or make sure your query is fast enough ( create an index for example). I advise to speed up query, since increasing timeouts may have performances downsides. A: I wanted to provide this answer as it came up in a mongodb exam question for the free online mongodb university. It's thorough and provides documentation. I have figured it out and will clean up some confusion mainly caused by a lack of explanation in the lessons. I am not being critical but further explanation is required to properly answer this question. First, when connecting to mongodb through an application you will be using a driver. This driver has barriors it must pass through in order to do anything with the mongodb server. When you understand this barrior concept you will then understand this question. Every connection that is ultimately made a list of things have to occur in order to pass throuh the barriers and ultimately conduct a write or read operaton. Visually you can think of it like this: IO / write request occurs ==> || 1st barrier --> (server selection - (err -> serverSelectionTimeoutMS ) ) ==> || 2nd barrier --> connection to server - (err -> 'connectionTimeoutMS') ==> || 3rd barrier --> socket connection - (err -> 'socketTimeoutMS') ==****Write Concern Options Barriers**==> || 4th barrier --> 'write concern specification { w: <value>, j: <boolean>, wtimeout: <number> }' ==> || 5th barrier --> a successful write / read operation *****Note**: Anywhere along this pipeline a falure occurs based on your logic a successful write / read operation may not occur. We can think of barriers 1 - 3 as network barriers of connectivity. If the network is down or having issues these are the problems one would notice through timeouts and exception handling of those timeouts. What one has to understand is that you can't perform a write operation with write concerns if you can't connect to the server in the first place. The lesson could have illustrated these points. The first set of barriers to a write or read operation are to have an established connection to the server... This is illustrated above by barries 1 - 3. Then, after you have a server connection via a cluster and or replica set of clusters then you can define write concerns. After we have an established connection a write may not happen for reasons other than network connectivity. These can be collisions of data or an extreme allotment of writes due to DDOS or hacking or in general not enough server space for the data be written to the server. Point is, something else can cause a reaction to the write concern and hence the control through options to handle write concern errors. I hope this helps because it made me understand the question and the right answer accordingly. Mostly, we weren't really taugh this so I hope this helps others learn and understand this feedback loop. Here are some articles I read to help me get to this answer / conclusion. If someone has a better or improvement on my explanation please feel free to provide feedback. https://scalegrid.io/blog/understanding-mongodb-client-timeout-options/ https://scalegrid.io/blog/mongodb-write-concern-3-must-know-caveats/ https://docs.mongodb.com/manual/reference/write-concern/ https://www.mongodb.com/blog/post/server-selection-next-generation-mongodb-drivers
[ "stackoverflow", "0044465466.txt" ]
Q: Will hash_equals ever return true for two different strings? Is there any situation where two different strings passed into hash_equals() would return true? Are "hash collisions" an issue with hash_equals? A: hash_equals just appears to be poorly named. It strictly does a string comparison and does not involve hashing (thus no possibility of hash collisions). I believe the name comes from a common use case for a timing-attack safe string comparison function, which is to compare two strings representing hashes.
[ "stackoverflow", "0023458475.txt" ]
Q: Is there alternative to inner join Is there something different between this two codes select a.firstname, a.lastname, b.salary, b.designation from table a, table b where a.id = b.id and select a.firstname, a.lastname, b.salary, b.designation from table a inner join table b on a.id = b.id A: Functionally, no, these specific queries are the same. The second is using ANSI join syntax, which has been the standard since SQL-92, and available in Oracle since 9i. Although both still work, there are some things you need to use ANSI syntax for when working with outer joins. The new style is generally preferred, partly because the old style makes it possible to accidentally introduce cartesian products by omitting a join condition - which you can't do with join syntax (accidentally; you can still do a cross join if you really want to do that on purpose) and it arguably makes your join/filter intentions clearer. Many find it easier to read, but that's a matter of opinion so that aspect is off-topic. Oracle recommend you use ANSI joins, at least for outer joins. You can see from plans and traces that Oracle actually still translates ANSI syntax into its old format internally, so as long as your query is correct (i.e. no missing conditions) then there is no performance difference; and the optimiser can still choose to use indexes based on the where clause, not just the on clauses. Many people here would recommend that you use ANSI syntax from the start if you're new to Oracle. Of course, not everyone agrees; there's a reference here to a dissenting voice, for example.
[ "stackoverflow", "0058324600.txt" ]
Q: How to restart count midway through a string of input? I'm trying to write a function that recieves any length string of positive or negative whole numbers and adds each number to the total, as long as the value doesn't go below zero. (It returns 0 for any invalid or empty input.) I'm having trouble writing a loop that re-sets the count to zero when it becomes negative and continutes adding from where it left off. e.g. input: 1, 2, -4, 1, 1 output: 2 Here's my code: def sum_earnings(): values = input("Enter a string of pos &/or neg numbers separated by commas (e.g. 1,-3,0,-4): ").split(',') earnings = 0 try: for i in values: earnings += int(i) while earnings >= 0: earnings += int(i) else: earnings = 0 continue print(earnings) except ValueError: print(0) return A: Seems overly complicated. Try the following: earnings = 0 for i in values: try: earnings = max(0, earnings + int(i)) # resets to 0 for negative intermediate sum except ValueError: earnings = 0 break # this will end the loop for invalid input print(earnings)
[ "stackoverflow", "0012300953.txt" ]
Q: Android JSON parsing , can't connect to service i m trying to write a method for calling service and get JSON data back in Android application. assume all necessary gloable variables are declared already... these are the lib i m using: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; here is my code: public class JSONParser { String url = "http://gdata.youtube.com/feeds/api/users/eon/uploads?&v=2&max- results=50&alt=jsonc"; JSONObject jObj = null; JSONArray ja = null; String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(String url){ try { URL urlGetter = new URL(url); URLConnection tc = urlGetter.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( tc.getInputStream(), "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = in.readLine()) != null) { sb.append(line + "\n"); } json = sb.toString(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jObj; } it just dose not work, i tried to run in debug mode, when it run to this line: BufferedReader in = new BufferedReader(new InputStreamReader( tc.getInputStream(), "iso-8859-1"), 8); it complains about : java.net.UnknownHostException: gdata.youtube.com i don't know how to solve this problem... any suggestions? thanks by the way, in my android manifest, i have permit internet already: if you look up the url in browser, you can see the json format of ti ...and it can be connected...but my code just complaining about unknowhostexception...."http://gdata.youtube.com/feeds/api/users/eon/uploads?&v=2&max- results=50&alt=jsonc"; A: Please put the permissions in your androidManifest.xml <uses-permission android:name="android.permission.INTERNET"/>
[ "stackoverflow", "0011001840.txt" ]
Q: How to draw a touch straight line in HTML5 canvas I'm trying to create a drawing tool set for the iPad and so far I've done the square, but I'm not sure how I would go about coding a straight line? Here's the code for my finished square, maybe it'll be a help. I would like to know how to code a straight line. After that, what if I wanted to draw circles as well? What in this code would I need to change? Here's the code: JavaScript (Square/Rectangle) // "Draw Rectangle" Button function rect(){ var canvas = document.getElementById('canvasSignature'), ctx = canvas.getContext('2d'), rect = {}, drag = false; function init() { canvas.addEventListener("touchstart", touchHandler, false); canvas.addEventListener("touchmove", touchHandler, false); canvas.addEventListener("touchend", touchHandler, false); } function touchHandler(event) { if (event.targetTouches.length == 1) { //one finger touche var touch = event.targetTouches[0]; if (event.type == "touchstart") { rect.startX = touch.pageX; rect.startY = touch.pageY; drag = true; } else if (event.type == "touchmove") { if (drag) { rect.w = touch.pageX - rect.startX; rect.h = touch.pageY - rect.startY ; draw(); } } else if (event.type == "touchend" || event.type == "touchcancel") { drag = false; } } } function draw() { ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "orange"; } init(); } A: Just substitute this: ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h); ctx.clearRect(0, 0, canvas.width, canvas.height); with something like this: ctx.fillLine(rect.startX, rect.startY, rect.w, rect.h); ctx.clearLine(0, 0, canvas.width, canvas.height); this is of course not 100% valid code, but the concept should work and you'll get the point
[ "stackoverflow", "0015955084.txt" ]
Q: How do I restart computer using C# on EC2 Ubuntu Server? I am running a C# Console Application on AWS EC2 instance with Ubuntu. I want to restart the computer from my Application using C#. Is there is any way that I can execute sudo reboot from C#? Thanks in advance. A: It works using the below code. Process process = new Process(); process.StartInfo.FileName = "/usr/bin/sudo"; process.StartInfo.Arguments = "/sbin/shutdown -r now"; process.Start();
[ "stackoverflow", "0041191552.txt" ]
Q: What do curly braces around a variable in a function parameter mean I saw this code on a package: const SortableList = SortableContainer(({items}) => { return ( <ul> {items.map((value, index) => <SortableItem key={`item-${index}`} index={index} value={value} /> )} </ul> ); }); What is happening to items by putting curly braces around it in the function parameters? A: This is destructuring assignment syntax. As another example, the following two lines of code are equal: const { items } = args const items = args.items Simply put, it is a simplified way of accessing specific field of a given variable for further use in that scope. In your original example, it is declaring a variable items for use in the function body that is the items field of that first argument. const SortableList = SortableContainer(({items}) => { // do stuff with items here is equal to const SortableList = SortableContainer((input) => { const items = input.items // do stuff with items here
[ "stackoverflow", "0041768763.txt" ]
Q: JPEG2000 : Can number of tiles in X direction be zero? According to JPEG2000 specs, Number of tiles in X and Y directions is calculated by following formula: numXtiles =  (Xsiz − XTOsiz)/ XTsiz & numYtiles =  (Ysiz − YTOsiz)/ YTsiz But it is not mentioned about the range of numXtiles or numYtiles. Can we have numXtiles=0 while numYtiles=250 (or any other value) ? A: In short, no. You will always need at least one row and one column of tiles to place your image in the canvas. In particular, the SIZ marker of the JPEG 2000 stream syntax does not directly define the number of tiles, but rather the size of each tile. Since the tile width and height are defined to be larger than 0 (see page 453 of "JPEG 2000 Image compression fundamentals, standards and practice", by David Taubman and Michael Marcellin), you will always have at least one tile. That said, depending on the particular implementation that you are using, there may be a parameter numXtiles that you can set to 0 without crashing your program. In that case, the parameter is most likely being ignored or interpreted differently.
[ "pm.stackexchange", "0000011783.txt" ]
Q: Methodology to Predict Future Workload I am working on a prediction of future growth of a workshop (50 – 100 manual workers). The idea is to develop how and in what way we would like to grow this facility. I am looking for a methodology or conceptual framework that would put me on rails, something that would give me a direction in developing this plan. Our company is a manufacturing company and we are using a form of Kanban so if you know any approach that is connected to this methodology then even better. I welcome any level of approach, from basic to complex. A: TL;DR You should continuously inspect-and-adapt your entire system as an integral part of running a successful Kanban implementation. To successfully manage growth, you will need to make changes to your processes if you expect to reduce (rather than increase) lead time as your input queues grow. Workload as Empirical Data Kanban is a great framework for estimating lead time, throughput, or cycle time. However, in the Kanban framework, "workload" is an empirical datum rather than a prediction. If we agree to define workload as the volume of stuff to be done within a given time frame, you can then measure the queue sizes within that time frame. For example, you could: Average the length of an input queue. Find the median of all input queues. Identify the minimum or maximum lengths of each queue. Predicting Workload In Kanban, you might predict future workload (e.g. queue size) by graphing queue growth over time. You might also simply make planning assumptions, such as "Workload will grow at a rate of 15% per quarter over the next 18 months." Either way, you would project the growth rate onto the size of your queues. In a pull system, growth of input queues increases lead time, but shouldn't directly affect your cycle time or throughput. Therefore, if you expect growth but do not want to increase lead time, you should examine your processes in light of your growth projections to determine if: You can add more labor to increase work-in-progress (WIP) limits. You can add additional queues to reduce lead time for a given sub-process. You can improve throughput (by reducing waste, not by management fiat) in order to meet your lead-time targets. You might also find other ways to manage the work. As long as you are continuously inspecting and adapting your processes, and making optimal use of the metrics your framework provides, then you are more likely to successfully absorb the additional work into your processes. There is no silver bullet.
[ "scifi.stackexchange", "0000072172.txt" ]
Q: What was the fate of Hitler and the non-HYDRA Nazi party in the MCU? The MCU Wiki article about HYDRA says that the organization, under the command of Johann Schmidt, broke away from Nazi leadership in 1943. (We see a scene related to this in Captain America: The First Avenger, when Red Skull comments that "HYDRA could grow no further in Hitler's shadow" and attacks Nazi officers with one of his newly-created weapons.) From that point on, in the movies and Agents of SHIELD flashbacks, HYDRA seems not only incredibly powerful, but increasingly so for at least part of the war. (That is, there was a "HYDRA Renaissance" after breaking away from Hitler, before the Allies started turning the tide.) Are there any works related to the MCU, or Marvel works in general that we might assume influenced the MCU, that comment on the fate of the non-HYDRA Nazi party? Was there a period of civil war in Germany, where HYDRA and Wehrmacht/SS forces were in open conflict? Was Hitler deposed immediately, or even killed, mid-way through the war? Were there any attempts by the Nazis to offer a cease-fire with the Allies, so they could deal with Schmidt's rebellion? By the end of the war, was there anything left of the independent Nazi party, or had HYDRA completely taken over the Nazi war machine? A: The history of HYDRA and the Nazi Party in the MCU does not conform to the history of the war seen elsewhere. We are led to believe that, unless stated otherwise, historical events in the MCU align more or less with actual history in our universe. Just to cover the bases, though, I'll outline what happened in the comics: Earth-616 (Main Continuity) In the main Marvel continuity, HYDRA is a modern terrorist organization that did not exist during WWII. After the fall of the Nazi Party at the end of the war, and Hitler's death at the hands of the original Human Torch (more on that later), several of the party's top members went into hiding from Allied forces. One of these men, Baron Wolfgang von Strucker, later formed HYDRA using his own personal funds. The organization was loosely based on a secret cabal that had existed in the ancient world but disappeared during the Rennaissance Period. Strucker and his allies - some of who were also involved with The Hand in Japan - saw HYDRA as a counter-balance to the growing popularity of capitalism & democracy in the world. They combined their belief in Facism, Socialism, and other systems to form what would become a constant thorn in the world of superheroes - HYDRA and its various offshoots. In this continuity, Hitler was physically killed at the end of WWII but his consciousness was saved. That consciousness was later placed into clones of his original body, and he was resurrected as the Marvel villain Hate-Monger. Earth-1610 (Ultimate Continuity) The other continuity which the MCU draws heavily upon is the Ultimate one. In the Ultimate continuity, HYDRA is a modern terrorist organization with nowhere near the influence, resources, or power seen in either the 616 or MCU continuities. However, HYDRA in the MCU is largely based on a secret faction of Nazis in the Ultimate universe who were, in fact, Chitauri (the Ultimate version of the Skrull). The Chitauri faction remained loyal to their Nazi allies right up to the time that the Nazis lost the war. Their mission, however, was actually to prepare the Earth for a Chitauri invasion that was decades to come. Following the fall of the Nazi Party, the Chitauri continued to work from the shadows, eventually infiltrating S.H.I.E.L.D. itself. This arc - seen in Ultimates #1 - #15 - is largely the basis for the MCU storyline of HYDRA taking over S.H.I.E.L.D. from within. In the Ultimate continuity, we are left to assume that Hitler apparently killed himself just like in real life. Decades later the Chitauri commander, Kleiser, commented to Captain America that Hitler was a fool and never really controlled the war at all. Earth-199999 (MCU Continuity) In the MCU continuity, HYDRA is originally a division of the Nazi Party specializing in science & technology and led by the Red Skull. As you stated, we see in the film how it splinters off into its own organization in Captain America: The First Avenger, plus we see in AoS and Captain America: The Winter Soldier what happened to HYDRA after the war. The ultimate fate of the Nazi Party in the MCU, however, is neither shown on-screen nor mentioned in any supporting materials released so far. Given the "real world" approach taken by the MCU, we may have to assume that following the events of Captain America: The First Avenger, the remainder of the war played out more or less like we know of from history. Under that assumption, Hitler committed suicide as the Allies took Berlin in 1945. That said, the upcoming "Agent Carter" series will be centered around the formation of the SSR and the remainder of the WWII era. It's logical to assume that we'll get more information on both HYDRA and the Nazis in general from that source.
[ "stackoverflow", "0009309681.txt" ]
Q: how to define epsilon interval in matlab? Given the double number p and an epsilon e, how effectively we can check whether the given decimal number x lies in the interval (p-e/2,p+e/2) without using if and else condition. A: Or abs(x-p) < e/2 now some more characters to go over the 30 character minimum for posts
[ "stackoverflow", "0002849750.txt" ]
Q: SQL Server cluster install issue I am going to install SQL Server 2008 Enterprise cluster on Windows Server 2008. I am wondering whether I have to setup a Windows domain (or active directory) in order to install SQL Server cluster? thanks in advance, George A: Some great articles here: http://msdn.microsoft.com/en-us/library/ms179410.aspx http://msdn.microsoft.com/en-us/library/ms189134.aspx http://www.mssqltips.com/tip.asp?tip=1687
[ "stackoverflow", "0059981188.txt" ]
Q: How to use typescript in electron without having to compile? So it looks like with newer electrons you can just start it off in typescript right away with electron main.ts Though you can't do electron ./main and you'd still need to require('./file.ts'). And I noticed that when I build it the .exe still complains that it needs a main.js file. How can I solve these two issues without going with a compiler (just load typescript directly)? A: Electron is not supposed to execute TypeScript code directly so you have to convert it to Javascript before to be able to use it in electron. By the way here a useful link to refer: https://www.electronjs.org/blog/typescript Please refer also to this question: How to add my own typescript classes in Electron project
[ "stackoverflow", "0040285694.txt" ]
Q: How to write to .txt file with left align text in python? I'm trying to write data to a txt file in a for loop using the code [python]: f = open('top_5_predicted_class.txt', 'w') f.write('Predicted Classes' + '\t\t' + ' Class Index' + '\t' + ' Probability' + '\n\n') for i in range(0, 5): f.write("%s \t \t %s \t \t %s \n" % (labels[top_k][i], top_k[i], out['prob'][0][top_k][i]) ) f.close() But the output that I got was not what I was expecting. I want to have class index all left aligned as well as the probabilities. Any idea of how can I do this? I guess the problem exists because the length of the predicted classes is not fixed. A: You shouldn't use tabs for this kind of alignment, since the behavior is unpredictable when your inputs are of different length. If you know what the maximum length of each column is, you can use the format function to pad with spaces. In my example, I use 15 spaces: >>> for a,b,c in [('a','b','c'), ('d','e','f')]: ... print ("{: <15} {: <15} {: <15}".format(a, b, c)) ... a b c d e f This is purely about display though. If you are concerned about storing the data, it would be much better to use CSV format, such as with Python's csv module.
[ "law.stackexchange", "0000000411.txt" ]
Q: Do you need to obey an obstructed traffic sign? If a traffic sign is obstructed (for example, due to being overgrown by kudzu or because a telephone pole was placed in front of it) to the point of unreadability, do you still need to obey it? What if the sign is so obstructed that there is no longer any indication that the sign even exists? A: It depends, but you should do it, just to be safe. Let's say you live in a town with one main road. The town council has decided that every road that has an intersection with this main road must have a stop sign placed on it. The idea catches on among the townspeople, and after the signs are placed accordingly, the accident rate goes down, and everyone is satisfied. Even out-of-towners catch to the pattern pretty quickly. One day, you - a law-abiding citizen of the town - drive down a side street towards the main road. The stop sign is no longer visible because of all of the kudzu on it. It's nearly impossible to tell that there's anything there besides a lot of kudzu. You ignore the stop sign and go out into the main road, in full sight of everyone, including a police officer. The officer charges you with a moving violation for not stopping at the stop sign. You argue against this, saying that the sign could not be seen. The case - assuming you challenge the officer's decision - could rest on mistake of fact. Basically, if you had reasonable cause to not think that there was a stop sign there, the charges could be dropped, because there was nothing there alluding to the sign's existence. However, in this situation, such a defense would not be legitimate, because given how obvious and widely-known the policy is, there's no reason why you would think that a stop sign would not be there. Each situation differs. A solid defense uses the concept of mistake of fact. If a sign was placed somewhere designating that cars have to slow down within that area (for some unclear reason), and the sign was not easily visible - or recognizable at all - then perhaps the defense could be used, because there would be no reason to think that there would be a sign there. In short, it varies. The scenarios differ in each case, so there's no overarching policy. A: No. The law would be void for vagueness. Connally v. General Construction Co., 269 U.S. 385, 391 (1926): [T]he terms of a penal statute [...] must be sufficiently explicit to inform those who are subject to it what conduct on their part will render them liable to its penalties… and a statute which either forbids or requires the doing of an act in terms so vague that men of common intelligence must necessarily guess at its meaning and differ as to its application violates the first essential of due process of law. The example of the "well known but hidden stop sign" appears to allow for arbitrary prosecution and should also be void.
[ "stackoverflow", "0012154086.txt" ]
Q: Spring Internationalization Support What are the different ways to resolve UI messages and provide internalization support in an web application using spring framework? We use property files and ResourceBundleMessageSource to resolve messages in Spring. Spring's implementation causes an high cpu usage in our application. There are two problems with ResourceBundleMessageSource implementation. Locking contention - getResourceBundle() and getMessageFormat() are both synchronized. MissingResourceException - Resolving a message involves looping through all the resource bundles defined in the application and calling bundle.getString(key). bundle.getString(key) method call throws an MissingResourceException if the key is not found. Searching for the key until we find the message for the given key. Since exception construction is a slow process and could eat up the CPU (which is what I observed in our load tests) this looks like a bottleneck. Though there are workarounds for both of the above problems (by extending the class and overridding the behavior) I wanted to know if there are other ways in spring framework to provide internationalization support to a web application. Thanks in advance A: You can use the ReloadableResourceBundleMessageSource instead. It provides some internal caching. If that does not work, I would advise implementing your own MessageSource (It's fairly straight forward). Spring provides AbstractMessageSource which may be helpful to start with. From there, you can implement some caching. More than likely, your localizations are not being updated frequently. You can read here on using the new Cacheable annotations in Spring 3.1 spring 3.1 @Cacheable example I have done this already with success in applications that allow admins to override locales in the database. Your particular implementation however would obviously be very different.
[ "stackoverflow", "0024658974.txt" ]
Q: Recognize Facebook-Activity in onActivityResult Good afternoon. I've implemented the Facebook API (v3) in my Android app so users can share achievements etc. When the Facebook Activity is finished then onActivityResult is called in the parent Activity. How can I recognize if the onActivityResult was called from a Facebook-Activity? Can I define the requestCode Facebook should use? Any help is highly appreciated. Update Am I right that the requestCode of Facebook is always 64206? A: You can set your own request code. You'll need to create a Session.OpenRequest or Session.NewPermissionsRequest, but there is a setRequestCode method in both of those classes: https://developers.facebook.com/docs/reference/android/current/class/Session.OpenRequest https://developers.facebook.com/docs/reference/android/current/class/Session.NewPermissionsRequest
[ "english.stackexchange", "0000022372.txt" ]
Q: “Push” is to “pushable” as “enable”/"disable" are to what? If you can push something you could say it is pushable. What do you say about something which you can enable and about something which you can disable? A: Going way back to one of the earliest machine parts designs, you have the toggle switch, which gives rise nicely to the intransitive verb usage of toggle To alternate between two or more electronic, mechanical, or computer-related options, usually by the operation of a single switch or keystroke: toggled back and forth between two windows on the screen. This has a past-tense toggled and a present tense toggleing and apparently an adjective form togglable or toggleable 1. Able to be toggled. That button is togglable. (And no, I did not add that to Wiktionary just now.) A toggle is generally recognized as being a binary condition, one or the other. I think it is a nice fit for capable of being enabled and disabled. You could also use switchable, but it does not have as strong of a connotation for binary states and would cause more confusion. A: Capable of being enabled and capable of being disabled, and for something which you can troll, you can say capable of being trolled.
[ "stackoverflow", "0040193901.txt" ]
Q: Map JSON file to MySQL Im parsing one website and want to write to MySQL. There is 11 field needs to parse each url under specific field. from bs4 import BeautifulSoup import requests import urllib.request import csv import pymysql con = pymysql.connect(host = 'localhost',user = 'root',passwd = 'root',db = 'micro') with open(r"C:\Users\New folder\url_list.txt") as f: urls = [u.strip('\n') for u in f.readlines()] page = 0 while page < 1000: try: soup = BeautifulSoup(requests.get(urls[page]).content, "html.parser") text = soup.select("head script[type=text/javascript]")[-1].text start = text.find('dataLayer =') + len('dataLayer =') end = text.rfind(';') rows = text[start:end].strip().split('\n') except: pass for d in rows: print(d) page = page + 1 print(page) Here is my JSON file [{ 'page':'ProductPage', 'OAM':'False', 'storeNum':'029', 'brand':'ASUS', 'productPrice':'199.99', 'SKU':'576181', 'productID':'443759', 'mpn':'RT-AC3200', 'ean':'886227780914', 'category':'Wireless Routers', 'isMobile':'False' }] [{ 'page':'ProductPage', 'OAM':'False', 'storeNum':'029', 'brand':'Linksys', 'productPrice':'79.99', 'SKU':'244129', 'productID':'432549', 'mpn':'EA6350', 'ean':'745883644780', 'category':'Wireless Routers', 'isMobile':'False' }] How can i map this JSON into MYSQL. Here is the output what i need. Here is what i need Thanks in advance. A: This is one crude way that you can populate a SQL insert statement with the data you have. rows=[ [{ 'page':'ProductPage', 'OAM':'False', 'storeNum':'029', 'brand':'ASUS', 'productPrice':'199.99', 'SKU':'576181', 'productID':'443759', 'mpn':'RT-AC3200', 'ean':'886227780914', 'category':'Wireless Routers', 'isMobile':'False' }], [{ 'page':'ProductPage', 'OAM':'False', 'storeNum':'029', 'brand':'Linksys', 'productPrice':'79.99', 'SKU':'244129', 'productID':'432549', 'mpn':'EA6350', 'ean':'745883644780', 'category':'Wireless Routers', 'isMobile':'False' }] ] for d in rows: sql = "insert into tableName \n( " recordInfo=d[0] sql += ' '. join ([field for field in recordInfo] ) sql += ') \nvalues ( ' sql += ('***, '*len(recordInfo))[:-2] sql += ') **** \n(' sql += ', '.join (["'%s'" % recordInfo[field] for field in recordInfo]) sql += ')' print (sql) #~ con.execute(sql.replace('****', '%').replace('***',"'%s'"))
[ "stackoverflow", "0048897118.txt" ]
Q: Regex with required text matches in the string I'm trying to the smtp relay from the sendmail logs and to make it reliable I need to require multiple strings in the log entry. An example of a log file entry would be like this: 2018-02-20T19:35:35+00:00 mx01.example.org sendmail[12345]: v1k82343VJ8K: to=<[email protected]>, delay=00:00:01, xdelay=00:00:01, mailer=esmtp, tls_verify=OK, relay=mailserver1.foobar.com. [1.1.1.1], dsn=2.0.0, stat=Sent I can't just key in on "relay=" because the particular relay name I need only appears in the log entry line that contains "to=" with it. How do I write my regex so that: The words "sendmail", followed by "to=", then followed by "relay=" all appear in the same log entry. After "relay=" I match any letter, digit, and character until the comma. The end result should be: mailserver1.foobar.com. [1.1.1.1] A: See regex in use here ^.*\bsendmail\b.*\bto=.*relay=\K[^,]* ^ Assert position at the start of the line .* Match any character any number of times \b Assert position as a word boundary sendmail Match this literally \b Assert position as a word boundary .* Match any character any number of times \b Assert position as a word boundary to= Match this literally .* Match any character any number of times relay= Match this literallyl \K Resets the starting point of the match. Any previously consumed characters are no longer included in the final match [^,]* Match any character except , any number of times Result: mailserver1.foobar.com. [1.1.1.1]
[ "stackoverflow", "0054259763.txt" ]
Q: Scala Error: java.sql.SQLException: No suitable driver found for jdbc:calcite: I created a jar of a Scala application using maven-assembly-plugin. Now when I execute the jar with java -jar path\to\jar\myapp.jar it throws the following error: Exception in thread "main" Exception in thread "Timer-0" java.lang.RuntimeException: java.sql.SQLException: No suitable driver found for jdbc:calcite: at org.apache.calcite.tools.Frameworks.withPrepare(Frameworks.java:159) at org.apache.calcite.tools.Frameworks.withPlanner(Frameworks.java:114) Caused by: java.sql.SQLException: No suitable driver found for jdbc:calcite: at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.apache.calcite.tools.Frameworks.withPrepare(Frameworks.java:153) ... 17 more java.lang.RuntimeException: java.sql.SQLException: No suitable driver found for jdbc:calcite: at org.apache.calcite.tools.Frameworks.withPrepare(Frameworks.java:159) at org.apache.calcite.tools.Frameworks.withPlanner(Frameworks.java:114) at java.util.TimerThread.mainLoop(Unknown Source) at java.util.TimerThread.run(Unknown Source) Caused by: java.sql.SQLException: No suitable driver found for jdbc:calcite: at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.apache.calcite.tools.Frameworks.withPrepare(Frameworks.java:153) ... 8 more When I run the application through an IDE (IntelliJ) it works fine. Can anyone tell me why this is happening? EDIT1: I opened the jar file and saw that the calcite-core jar is present in org/apache/calcite jar. EDIT2: I tried changing the version of calcite-core. I was using 1.15.0 earlier and now I'm using 1.18.0 but the error is still there. A: Although I still haven't found a solution to the calcite-core driver problem, I managed to find another way to execute the jar. I added the following two plugins to my pom.xml. The maven-dependency-plugincopies all the relevant dependency jars into a lib folder and the maven-jar-plugin makes a single executable jar file. <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> <excludeTransitive>false</excludeTransitive> <stripVersion>false</stripVersion> </configuration> <executions> <execution> <id>copy-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>com.example.MainClass</mainClass> </manifest> </archive> </configuration> </plugin> Note: Adding <mainClass>com.example.MainClass</mainClass> will make manifest.mf aware of what the main class is.
[ "stackoverflow", "0042119265.txt" ]
Q: When uploading image in codeigniter the image is not saved into the path folder When I upload an image in Codeigniter its name is saved to the database but not in the default folder. I'am using Ajax to submit the image My "view" profile <div id="timelineBackground"> <?php { $image_properties = array('src' => base_url("uploads/" . $timeline_image),'width' => '1000px','height'=> '400px','id'=>'coverimg', 'title' => 'That was quite a night','rel' => 'lightbox'); //echo img($image_properties); ?> <div id="timelineselector"> <?php echo form_open_multipart('',["id"=>"form_cover"]); ?> <input type="hidden" name="email" value="<?php echo $email ;?>" > <?php echo form_upload(["name"=>"timelineimage"]); ?> <?php echo form_submit(["name"=>"submit","value"=>"Submit"]); ?> <?php echo form_close(); ?> </div><?php } ?></div> here is my ajax code jQuery('#form_cover').submit(function(e){ e.preventDefault(); var formData = new FormData(this); var url= '<?php echo base_url("user/coverimage"); ?>'; formData.value jQuery.ajax({ type: "POST", url:url, data: formData, cache: false, contentType: false, processData: false, success: function(data) { $('#coverimg').attr('src',data); }, error: function(data){ //error function } }); }); my controller "user" public function coverimage(){ $config = [ 'upload_path' => './uploads/', 'allowed_types' => 'jpg|gif|png|jpeg', 'max_size' => 10000000000000, 'max_width' => 1024000000, 'max_height' => 7680000000, ]; $this->load->library('upload', $config); if(!$this->upload->do_upload('timelineimage') ) { $post = $this->input->post(); unset($post['submit']); $upload_data = $this->upload->data(); $file_name=$_FILES['timelineimage']; $this->load->model('Pmodel'); $this->Pmodel->timeline_upload_model($post,$file_name); $image_properties = array( 'src' => base_url("./uploads/" . $file_name['name']), 'width' => '200px', 'height'=> '200px', 'title' => 'That was quite a night', 'rel' => 'lightbox' ); // echo img($image_properties); echo base_url("uploads/" . $file_name['name']); exit(); }else { $upload_error = $this->upload->display_errors(); $this->load->view('admin/add_article',compact('upload_error')); } } my model "Pmodel" public function timeline_upload_model($arr,$arra) { $email=$arr['email']; $image=$arra['name']; $data=array('timelineimage'=>$image); $query=$this->db->where('email',$email)->update('user_data',$data); return $query; } Why does it only show the name but not the image? A: I found the answer and posted the code, in case anyone else wants to look at this... the 'view' <div id="timelineBackground"> <?php { $image_properties = array('src' => base_url("uploads/" . $timeline_image),'width' => '1000px','height'=> '400px','id'=>'coverimg', 'title' => 'That was quite a night','rel' => 'lightbox'); echo img($image_properties); ?> <div id="timelineselector"> <?php echo form_open_multipart('user/coverimage',["id"=>"form_cover"]); ?> <input type="hidden" name="id" value="<?php echo $id ;?>" > <?php echo form_upload(["name"=>"timelineimage"]); ?> <?php echo form_submit(["name"=>"submit","value"=>"Submit"]); ?> <?php echo form_close(); ?> </div><?php } ?></div> 'ajax' jQuery('#form_cover').submit(function(e){ e.preventDefault(); var formData = new FormData(this); var url= '<?php echo base_url("user/coverimage"); ?>'; formData.value jQuery.ajax({ type: "POST", url:url, data: formData, cache: false, contentType: false, processData: false, success: function(data) { $('#coverimg').attr('src',data); }, error: function(data){ //error function } }); }); and the controller: public function coverimage() { print_r($_POST); print_r($_FILES); $config = [ 'upload_path' => './uploads/', 'allowed_types' => 'jpg|gif|png|jpeg', 'max_size' => 10000000000000, 'max_width' => 1024000000, 'max_height' => 7680000000, ]; $this->load->library('upload', $config); $this->upload->initialize($config); $timelineimage="timelineimage"; if(!$this->upload->do_upload($timelineimage)) { $upload_error = $this->upload->display_errors(); $this->load->view('dashboard/profile',compact('upload_error')); } else { $post = $this->input->post(); unset($post['submit']); //print_r($post); $upload_data = $this->upload->data(); //print_r($upload_data); $file_name=$_FILES['timelineimage']; $this->load->model('Pmodel'); $this->Pmodel->timeline_upload_model($post,$file_name); $image_path= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']); //echo base_url("uploads/" . $file_name['name']); } }
[ "travel.stackexchange", "0000081714.txt" ]
Q: Problems associated with booking flights inside another set of flights? I am planning two trips back to the UK from Australia, one over Christmas and one in the late Spring. I have found that booking the tickets differently can reduce the price I have to pay: Type 1: Australia - London - 15th December London - Australia - 2nd January Australia - London - 15th April London - Australia - 15th July This is the regular way I would book all my flights with each flight containing the way and way back. The thing is, if I book my flights like this, the price is much less: Australia - London - 15th December London - Australia - 15th July London - Australia - 2nd January Australia - London - 15th April As you can see the first flight encompasses the entire trip with the middle bit being a return flight from London. The reason that this is less is because there are less English who want to fly from the UK to Australia after Christmas and more Australians who want to return from England then. I am wondering if there are any problems with booking flights like this? In my head it feels that it should be ok (eg: if I wanted to pop back in the middle of a trip for a funeral) but it also feels strange leaving the country on a different ticket than that which I came in on. It is worth noting that I have a British passport and a valid Australian visa meaning that there shouldn't be any issue with me coming in and out of either country. A: This is quite normal, I often structure my itineraries like this, or even in more complicated ways such as four or five ticket deep nesting. You should have the details of the other ticket to hand in case you need it, but I have never found anyone who questioned me about it. I don't actually believe that the immigration people get access to the ticket information unless you provide it to them. A: There is a technical term for what you are doing: back-to-back ticketing. There is nothing wrong from an immigration point of view, except that you may get more questions. However, there are airlines that don't exactly like this. The practice is listed under "booking ploys" on Wikipedia. Some airlines, such as American Airlines prohibit this practice. But there are few reports of travellers who were asked for a surcharge after they have been "caught". A: The only problems I can see with this are: Each time you check in for your flight from London to Australia, the airline agent will not see your return itinerary right away, and might ask when and how you plan to leave Australia. If this happens, you'll need to show the other booking. This could happen on both flights. Each time you enter Australia, the immigration officer will see the details of the ticket you are currently travelling on, and won't see your return itinerary (or it will appear to be much farther away than your allowed 3 months stay). You may be asked the same questions, about when and how you plan to leave Australia, and again will need to show the other booking.
[ "stackoverflow", "0039891859.txt" ]
Q: PHP Fatal error: Class 'External\\xBBCode\\Xbbcode\\Xbbcode' not found I have real troubles with PHP namespaces =_= So, project place is /home/hosting//htdocs/ File /home/hosting//htdocs/Components/News.php is like: <?php namespace Components; use \External\xBBCode\Xbbcode as Xbbcode; class News extends \Components\ComponentHelper { const NEWS_DEFAULT_LIMIT = 39; // news per page const NEWS_ON_PAGE_LIMIT = 10; // news per page public function __construct() { return true; } public static function desc_sort ($a, $b) { return (int)$a < (int)$b; } public static function Run($_config) { /* data for routing */ $routeData = $_config['route_data']; $routeDataCount = count($routeData); $newsData = false; $newsList = false; $db = new \Engine\DB($_config); $tpl = new \Engine\Template\Engine($_config); $parser = new Xbbcode\Xbbcode(); $newsYear = 0; $newsMonth = 0; $newsID = 0; $newsFriendlyTitle = ''; $template = ''; And I have needed files: /home/hosting/<proj_title>/htdocs/External/xBBCode/Xbbcode/Xbbcode.php /home/hosting/<proj_title>/htdocs/External/xBBCode/Xbbcode/Attributes.php /home/hosting/<proj_title>/htdocs/External/xBBCode/Xbbcode/Tag/ /home/hosting/<proj_title>/htdocs/External/xBBCode/Xbbcode/resources/ I have an error in string $parser = new Xbbcode\Xbbcode(); But file /home/hosting/<proj_title>/htdocs/External/xBBCode/Xbbcode/Xbbcode.php is exist and start like: <?php namespace Xbbcode; use Xbbcode\Tag\Tag; /** * Class Xbbcode */ class Xbbcode { And I use own autoloader, which placed in htdocs dir, code of it: <?php /** * Файл с автозагрузчиком файлов * * PHP Version 5 * * @category Class */ /** * Автозагрузчик классов * * @category Class */ class Autoloader { private static $_loadFile; /** * Загрузчик * * @param string $className - имя класса * * @return resuorce */ public static function loadPackages($className) { $pathParts = explode('\\', $className); self::$_loadFile = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $pathParts) . '.php'; if (file_exists(self::$_loadFile) && is_readable(self::$_loadFile)) { require_once self::$_loadFile; } else { throw new Exception('File "' . self::$_loadFile . '" is not found!'); } } /** * Загрузчик с логированием * * @param unknown $className - имя класса * * @return resuorce */ public static function loadPackagesAndLog($className) { try { self::loadPackages($className); printf("<p>%s: class %s was loaded from %s</p>\n", __METHOD__, $className, self::$_loadFile); } catch (Exception $e) { printf("<p>%s return exception: %s</p>\n", __METHOD__, $e->getMessage()); } } } spl_autoload_register(array('Autoloader', 'loadPackages')); // spl_autoload_register(array('Autoloader', 'loadPackagesAndLog')); ?> Please someone say, what I do wrong. A: You're loading the class file correctly, but it exists in the Xbbcode namespace. This is incorrect. It should be (in Xbbcode.php): namespace External\xBBCode\Xbbcode; class Xbbcode { ... Generally, you want your namespaces to represent where in your project files that the class lies.
[ "stackoverflow", "0007738899.txt" ]
Q: SelectionChanged Event of WPF comboBox is not firing if it has same items in it if i m using following type of code then SelectionChanged Event of WPF comboBox is not firing cmbFunctionsList.Items.Add("sameItem"); cmbFunctionsList.Items.Add("sameItem"); cmbFunctionsList.Items.Add("sameItem"); cmbFunctionsList.Items.Add("sameItem"); cmbFunctionsList.Items.Add("sameItem"); Is there any work around of this. A: WPF Combo Boxes will not change the selected item if the currently selected item and the new one that selected are considered equal by the object.Equals() method called on the newly selected object (i.e newlyslected.Equals(currentlySelected)). In this case the string.Equals method is returning true since the values of strings are equal A: Try doing this: ComboBoxItem newItem = new ComboBoxItem(); newItem.Content = "same item"; cmbFunctionsList.Items.Add(newItem); Idea taken from here
[ "stackoverflow", "0062895209.txt" ]
Q: How To Create Feature Discovery Using Xamarin Forms I want to create a tutorial page after launching the app to give the user an overview of the features in the application and how to use it. For example the tutorial page ↓ in anydesk app So, How to create this page using XF? What is the term or key should i use to find examples about this on google such as "Onboarding Pages"? Update I have tried to add this feature on android and it's working fine Now The question is How to do that on Ios? A: After reading many resources, I ended up using Custom Renderers In the Shared Project 1- Create a Xamarin.Forms custom control. public class FeatureDiscoveryTarget : View { public Element Target { get; set; } public string Title { get; set; } public string Description { get; set; } } public class FeatureDiscoverySequence : View { public IList<FeatureDiscoveryTarget> Targets { get; } public Action ShowAction { get; set; } public FeatureDiscoverySequence() { Targets = new List<FeatureDiscoveryTarget>(); } public void ShowFeatures() { ShowAction?.Invoke(); } } 2- Consuming the Custom Control from Xamarin.Forms. .XAML <StackLayout Orientation="Vertical" Padding="3"> <Button x:Name="BtnTest" Text="Test Feature Discovery" Clicked="Button_Clicked"/> <Button x:Name="Btn1" Text="Feature 1" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/> <StackLayout Orientation="Horizontal" > <Button x:Name="Btn2" Text="Feature 2" /> <Button x:Name="Btn3" Text="Feature 3" HorizontalOptions="EndAndExpand" /> </StackLayout> <Button x:Name="Btn4" Text="Feature 4" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" /> <local:FeatureDiscoverySequence x:Name="TapTargetSequence"> <local:FeatureDiscoverySequence.Targets> <local:FeatureDiscoveryTarget Target="{x:Reference Name=Btn1}" Title="Feature 1" Description="Details.... " /> <local:FeatureDiscoveryTarget Target="{x:Reference Name=Btn2}" Title="Feature 2" Description="Details.... " /> <local:FeatureDiscoveryTarget Target="{x:Reference Name=Btn3}" Title="Feature 3" Description="Details.... " /> <local:FeatureDiscoveryTarget Target="{x:Reference Name=Btn4}" Title="Feature 4" Description="Details.... " /> </local:FeatureDiscoverySequence.Targets> </local:FeatureDiscoverySequence> </StackLayout> .Cs private void Button_Clicked(object sender, EventArgs e) { TapTargetSequence.ShowFeatures(); } In Android Project 1- Add this library to android project only 2- Create a new instance of MainActivity Class public static MainActivity Instance { get; private set; } protected override void OnCreate(Bundle savedInstanceState) { // ... LoadApplication(new App()); Instance = this; } 3- Create the custom renderer for the control. using System; using Xamarin.Forms; using Android.Views; using Android.Widget; using Android.Content; using View = Android.Views.View; using System.Collections.Generic; using Com.Getkeepsafe.Taptargetview; using Xamarin.Forms.Platform.Android; using Color = Android.Resource.Color; [assembly: ExportRenderer(typeof(FeatureDiscoverySequence), typeof(SequenceRenderer))] namespace YourNameSpace.Droid { class SequenceRenderer : Xamarin.Forms.Platform.Android.AppCompat.ViewRenderer<FeatureDiscoverySequence, View> { public SequenceRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<FeatureDiscoverySequence> e) { base.OnElementChanged(e); e.NewElement.ShowAction = new Action(ShowFeatures); } private void ShowFeatures() { var targets = new List<Com.Getkeepsafe.Taptargetview.TapTarget>(); foreach (var target in Element.Targets) { var formsView = target.Target; string title = target.Title; string description = target.Description; var renderer = Platform.GetRenderer((Xamarin.Forms.View) formsView); var property = renderer?.GetType().GetProperty("Control"); var targetView = (property != null) ? (View) property.GetValue(renderer) : renderer?.View; if (targetView != null) { targets.Add ( TapTarget .ForView(targetView, title, description) .DescriptionTextColor(Color.White) .DimColor(Color.HoloBlueLight) .TitleTextColor(Color.Black) .TransparentTarget(true) .TargetRadius(75) ); } } new TapTargetSequence(MainActivity.Instance).Targets(targets).Start(); } } } In Ios Project ...Todo The Result on Android For More Information For Android For IOS KeepSafe/TapTargetView Github Xamarin.Forms Custom Renderers
[ "stackoverflow", "0011893233.txt" ]
Q: Navigation bar center position I am currently working with a bottom navigation bar for a test site. The problem is that the navigation bar does not center properly. I have added the .left attribute to keep each block list beside each other. How can I get this bottom navigation bar to center automatically(no matter the amount of lists added)? Example CSS related to bottom navigation <style> .bottomnavControls { padding-top:10px; padding-bottom:10px; padding-right:0; text-decoration:none; list-style:none; } #footer { position: absolute; width: 100%; bottom: 0; background: #7a7a7a; border-bottom: 15px solid #000; } .left { float: left; } .right { float: right; } </style> HTML <div id="footer"> <div class="bottomNav"> <ul class="bottomnavControls left"> <li style="padding-bottom:5px;"><b>Home</b></li> <li><a href="" class="footer">Login</a></li> </ul> <ul class="bottomnavControls left"> <li style="padding-bottom:5px;"><b>Category</b></li> <li><a href="" class="footer">Games</a></li> </ul> <ul class="bottomnavControls left"> <li style="padding-bottom:5px;"><b>About</b></li> <li><a href="" class="footer">Who We Are</a></li> </ul> <ul class="bottomnavControls left"> <li style="padding-bottom:5px;"><b>Links</b></li> <li><a href="www.google.com" target="_new" class="footer">Google</a></li> </ul> <ul class="bottomnavControls left"> <li style="padding-bottom:5px;"><b>Other Stuff</b></li> <li><a href="" class="footer">Stuff</a></li> </ul> </div> </div> My current Bottom navigation: My desired outcome: A: Instead of float, you should use display: inline-block here. This way, you can easily center them by putting text-align: center on the container. .bottomNav { text-align: center; } .bottomnavControls { display: inline-block; } and remove left class. Note: display: inline-block works fine in modern browsers, but it needs a hack in IE7.
[ "stackoverflow", "0013831755.txt" ]
Q: UIGestureRecognizers not responding I have a a number of pop up views saved as properties of a view controller. They are only added to the view when they are presented, and are removed from the view when they are hidden. Everything was working but i changed my code to simplify things and it's no longer working. Here is an example of how I create and add my gesture recognizers: UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidePopUpView:)]; [self.totalPowerPopUpView addGestureRecognizer:tapGestureRecognizer]; [self.co2PopUpView addGestureRecognizer:tapGestureRecognizer]; The views are presented by a selector triggered by pressing a UIButton (there is normally other code in the if statements setting the custom view properties, but I cut it out for simplicity): - (void)showPopUpView:(UIButton*)sender { CGRect endFrame = CGRectMake(10, 10, 300, 400); UIView *popUpView; if (sender == self.totalPowerInfoButton) { [self.view addSubview:self.totalPowerPopUpView]; popUpView = self.totalPowerPopUpView; } if (sender == self.co2LevelInfoButton) { [self.view addSubview:self.co2PopUpView]; popUpView = self.co2PopUpView; } [UIView animateWithDuration:0.5 animations:^ { popUpView.alpha = 1.0; popUpView.frame = endFrame; }]; } The popUpView's present, but the gesture recognizer selector doesn't get called when I tap them. Why not? A: Does this work: UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidePopUpView:)]; [self.totalPowerPopUpView addGestureRecognizer:tapGestureRecognizer]; tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidePopUpView:)]; [self.co2PopUpView addGestureRecognizer:tapGestureRecognizer];
[ "stackoverflow", "0053565949.txt" ]
Q: Does Spring Security OAuth2 support Authorization Code Flow with PKCE for browser (Angular) clients? Browser applications auth used to be managed using the Implicit grant of the Authorization Server. I successfully implemented this using Spring Security Oauth. This approach has several drawbacks: Refresh tokens are not supported, so when the token expires we need to reauthenticate with the Authorization server. This grant is not recommended due to its security concerns (see https://oauth.net/2/grant-types/implicit/ and https://tools.ietf.org/html/draft-parecki-oauth-browser-based-apps-01). Currently the recommended option is using Authorization code flow with PKCE for browser applications. How could this be implemented in a Spring Boot Authorization Server with spring boot oauth? A: No, it does not yet support PKCE, though there is a ticket for it. Note also that Spring Security's OAuth support is in a bit of a transition phase right now while it is migrated into Spring Security proper. Feel free to follow this feature matrix to see where progress is at.
[ "stackoverflow", "0048155034.txt" ]
Q: Recursive view that sum value from double tree structure SQL Server First sorry for numerous repost of my question, I'm new around and getting used to properly and clearly asking questions. I'm working on a recursive view that sum up values from a double tree structure. I have researched around and found many questions about recursive sums but none of their solutions seemed to work for my issue specifically. As of now I have issues aggregating the values in the right cells, the logic being i need the sum of each element per year in it's parent and also the sum of all the years for a given element. Here is a fiddle of my tables and actual script: SQL Fiddle And here is a screenshot of the output I'm looking for: My question is: How can I get my view to aggregate the value from child to parent in this double tree structure? A: If I understand your question correctly, you are trying to get an aggregation at 2 different levels to show in a single result set. Clarification Scenario: Below is an over-simplified sample data set for what I believe you are trying to achieve. create table #agg_table ( group_one int , group_two int , group_val int ) insert into #agg_table values (1, 1, 6) , (1, 1, 7) , (1, 2, 8) , (1, 2, 9) , (2, 3, 10) , (2, 3, 11) , (2, 4, 12) , (2, 4, 13) Given the sample data above, you want want to see the following output: +-----------+-----------+-----------+ | group_one | group_two | group_val | +-----------+-----------+-----------+ | 1 | NULL | 30 | | 1 | 1 | 13 | | 1 | 2 | 17 | | 2 | NULL | 46 | | 2 | 3 | 21 | | 2 | 4 | 25 | +-----------+-----------+-----------+ This output can be achieved by making use of the group by grouping sets (example G. in the link) syntax in SQL Server as shown in the query below: select a.group_one , a.group_two , sum(a.group_val) as group_val from #agg_table as a group by grouping sets ( ( a.group_one , a.group_two ) , ( a.group_one ) ) order by a.group_one , a.group_two What that means for your scenario, is that I believe your Recursive-CTE is not the issue. The only thing that needs to change is in the final select query from the entire CTE. Answer: with Temp (EntityOneId, EntityOneParentId, EntityTwoId, EntityTwoParentId, Year, Value) as ( SELECT E1.Id, E1.ParentId, E2.Id, E2.ParentId, VY.Year, VY.Value FROM ValueYear AS VY FULL OUTER JOIN EntityOne AS E1 ON VY.EntityOneId = E1.Id FULL OUTER JOIN EntityTwo AS E2 ON VY.EntityTwoId = E2.Id ), T (EntityOneId, EntityOneParentId, EntityTwoId, EntityTwoParentId, Year, Value, Levels) as ( Select T1.EntityOneId, T1.EntityOneParentId, T1.EntityTwoId, T1.EntityTwoParentId, T1.Year, T1.Value, 0 as Levels From Temp As T1 Where T1.EntityOneParentId is null union all Select T1.EntityOneId, T1.EntityOneParentId, T1.EntityTwoId, T1.EntityTwoParentId, T1.Year, T1.Value, T.Levels +1 From Temp AS T1 join T On T.EntityOneId = T1.EntityOneParentId ) Select T.EntityOneId, T.EntityOneParentId, T.EntityTwoId, T.EntityTwoParentId, T.Year, sum(T.Value) as Value from T group by grouping sets ( ( T.EntityOneId, T.EntityOneParentId, T.EntityTwoId, T.EntityTwoParentId, T.Year ) , ( T.EntityOneId, T.EntityOneParentId, T.EntityTwoId, T.EntityTwoParentId ) ) order by T.EntityOneID , T.EntityOneParentID , T.EntityTwoID , T.EntityTwoParentID , T.Year FYI - I believe the sample data did not have the records necessary to match the expected output completely, but the last 20 records in the SQL Fiddle match the expected output perfectly.
[ "stackoverflow", "0054085050.txt" ]
Q: Split and Append "AND" between values how to split below value and append AND between values ? I cannot Split with Space as there is spaces between words "\"Mark John\" \"Tina Roy\"" as "\"Mark John\" AND \"Tina Roy\"" In the end it should look like - "Mark John" AND "Tina Roy" Any help is appreciated. string operatorValue = " AND "; if (!string.IsNullOrEmpty(operatorValue)) { foreach (string searchVal in SearchRequest.Text.Split(' ')) { if (!string.IsNullOrEmpty(searchVal)) searchValue += searchVal + operatorValue; } } int index = searchValue.LastIndexOf(operatorValue); if (index != -1) { outputSearchValue = searchValue.Substring(0, index); } A: Try var result = str.Replace("\" \"","\" And \""); If you have more than one name, or there is a possibility that you could have more than one whitespace between two names, you could opt for Regex. var result = Regex.Replace(str,"\"\\s+\"","\" And \""); Example, var str = "\"Mark John\" \"Tina Roy\" \"Anu Viswan\""; var result = Regex.Replace(str,"\"\\s+\"","\" And \""); Output "Mark John" And "Tina Roy" And "Anu Viswan" A: Or use Regular Expressions: var test = "\"John Smith\" \"Bill jones\" \"Bob Norman\""; Console.WriteLine(Regex.Replace(test, "\" \"", "\" AND \""));
[ "stackoverflow", "0005816078.txt" ]
Q: Inserting a name with ' in a MySQL table First time with this trouble when dealing with a MySQL table. I'm inserting bar names in a table. If the bar is called "Tim's Bar" and I insert it straight away I get an error and the data is not inserted. How do you instert properly the ' in the table? A: Use mysql_real_escape_string(): http://php.net/manual/en/function.mysql-real-escape-string.php A: Use PDO with prepared statements. $query = $pdo->prepare('INSERT INTO bars (name) VALUES (?)'); $query->execute("Tim's Bar"); It's superior (and safer) than using the mysql(i)_* family of functions directly.
[ "stackoverflow", "0017544566.txt" ]
Q: SQL and number combination search I have table with 10 number fields (let's say F1, F2... F10). Now I have 4 numbers (N1, N2, N3, N4). I have to find if those 4 numbers appear anywhere in the above table. For example, if F2=N4 and F1=N2 and Fx=N3 and Fy=N1 (any order, any combination). I was wondering is there quick way to do it via SQL or is it only way to write looooong combination of selects (I am not sure I will be able even finish that in this life time). A: Here is SQLFiddel Demo Below is the sample Query select * from Temp where 'N1' in (F1,F2,F3,F4,F5,F6,F7,F8,F9,F10) and 'N2' in (F1,F2,F3,F4,F5,F6,F7,F8,F9,F10) and 'N3' in (F1,F2,F3,F4,F5,F6,F7,F8,F9,F10) and 'N4' in (F1,F2,F3,F4,F5,F6,F7,F8,F9,F10)
[ "stackoverflow", "0053244100.txt" ]
Q: angular assign different observable to template with async based on condition (any memory leak ?) I need to render data from different ngrx stores based on some flag. Both stores gives same type of data. Approach 1 <ng-contaier *ngIf="flag$ | async; else anotherStoreData"> <ng-container *ngIf="store1$ | async as store1"> <div>{{ store1?.prop1 }}</div> <div>{{ store1?.prop2 }}</div> </ng-container> </ng-contaier> <ng-template #anotherStoreData> <ng-container *ngIf="store2$ | async as store2"> <div>{{ store2?.prop1 }}</div> <div>{{ store2?.prop2 }}</div> </ng-container> </ng-template> flag$: Observable<boolean> store1$: Observable<Store> store2$: Observable<Store> ngInit() { flag$ = streamService.userNewStore(); store1$ = this.store.select(<someselector1>); store2$ = this.store.select(<someselector2>); } Approach 2 <ng-container *ngIf="store$ | async as store"> <div>{{ store?.prop1 }}</div> <div>{{ store?.prop2 }}</div> </ng-container> store$: Observable<Store> ngInit() { streamService.userNewStore() .pipe(takeUntil(this.ngUnsubscribe)) .subscribe((flag) => { store$ = flag ? this.store.select(<someselector1>) : this.store.select(<someselector2>); }); } In Approach1 I am duplicating template, which is fine for small template - but if it is big then i am thinking about Approach 2. In Approach2 streamService can change the flag at any time, in that case what will happen to the previous subscription in the template with async pipe. Will it lead any memory leak? Is there any other alternatives that I can use, please suggest. A: Having just checked the source code for the Async pipe, it appears that it will unsubscribe if the Observable changes. You can see this in line 100 of the file: if (obj !== this._obj) { this._dispose(); return this.transform(obj as any); } If the value being passed in is not the one currently held in memory, it calls this.dispose, which in turn unsubscribes. With that in mind, I would definitely prefer the 2nd approach
[ "stackoverflow", "0001938340.txt" ]
Q: Error: Incompatible types in initialization? (iPhone,Objective-C) I'm getting the error on "float pos = [sender value];"...sender should be a UISlider that I set up in Interface Builder. ButtonViewController.m - (IBAction)slide: (id)sender { float pos = [sender value]; loadValue.progress = pos; } ButtonViewController.h @interface Button_Fun4ViewController : UIViewController { IBOutlet UIProgressView *loadValue; } - (IBAction)slide: (id)sender; THANKS. A: While sender "should" be a UISlider, the compiler doesn't know that. All it sees is id, which it binds to the first matching method signature it can find; probably one that returns something other than a float (and as a final guess, the compiler will assume it returns an id). You'll need to typecast this over to UISlider in this case: - (IBAction)slide: (id)sender { float pos = [(UISlider *)sender value]; loadValue.progress = pos; } Using NSAssert() or an if() to double-check that this is fact a UISlider wouldn't be a bad idea, but isn't strictly necessary.
[ "stackoverflow", "0008759721.txt" ]
Q: How can I unset the MAX_ROWS table option on a MyISAM table? I have a table defined as such: CREATE TABLE `_debug_log` ( ... ) ENGINE=MyISAM AUTO_INCREMENT=896692 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci MAX_ROWS=100000 ROW_FORMAT=COMPRESSED; I'd like to drop the MAX_ROWS option as it isn't necessary for this table, but I do need to keep the existing data. Is there a way to unset this table option via an ALTER statement, or will I need to export the data, rebuild the table and then import the data back in? I checked the MySQL docs on MAX_ROWS, but it only says it requires a positive integer value and doesn't say what the default value is or what a value of 0 might do. A: For what it is worth: CREATE TABLE `_debug_log` ( id int unsigned primary key auto_increment ) ENGINE=MyISAM AUTO_INCREMENT=896692 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci MAX_ROWS=100000 ROW_FORMAT=COMPRESSED; SHOW CREATE TABLE _debug_log; gives: CREATE TABLE `_debug_log` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=896692 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci MAX_ROWS=100000 ROW_FORMAT=COMPRESSED then: alter table _debug_log max_rows = 0; SHOW CREATE TABLE _debug_log; gives: CREATE TABLE `_debug_log` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=896692 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPRESSED I tried inserting some data before running the ALTER and after running the ALTER and it did not seem to be affected. Furthermore, if you create the same table with the same options but exclude the MAX_ROWS option, insert the same data and then take a look at the resulting data in information_schema.tables the data is pretty much identical (obvious differences aside):
[ "stackoverflow", "0009824577.txt" ]
Q: Grouping many to many choices by type in form I have a Sandbox which contains plenty of items composed of one or more attributes. Each attribute belongs to a particular attribute type (such as color, shape, etc) I am at loss on how to render the form with Attributes grouped together with their AttributeTypes. Models class Sandbox(models.Model): item = models.ForeignKey('Item') class Item(models.Model): name = models.CharField() sandbox = models.ForeignKey(Sandbox) attributes = models.ManyToManyField('Attribute') class Attribute(models.Model): name = models.CharField() type = models.ForeignKey('AttributeType') class AttributeType(models.Model): name = models.CharField() class ItemAttribute(models.Model): # intermediary model to hold references item = models.ForeignKey(Item) type = models.ForeignKey(AttributeType) attribute = models.ForeignKey(Attribute) ModelForm class Sandbox(ModelForm): class Meta: model = Sandbox There can only be one choice per attribute type. For instance, something can only have one color or one shape. AttributeType Attribute Users choice color red blue [x] green shape shape triangular squared [x] spherical This is were I get stuck. How do I group these attributes together in the form and how can I use radio buttons to select only one attribute per type? Perhaps my original idea of having a simple model representation falls short here? I have tried documentation, StackOverflow and Google but no luck. Any tips and ideas are welcome. My solution I built up a solution which satisfies my needs. @bmihelac pointed me in a good direction to this article on how to create a factory method for creating a custom form. [see below] def make_sandbox_form(item): def get_attributes(item): item_attributes = ItemAttribute.objects.filter(item=item) # we want the first attribute type _attr_type = item_attributes[0].attribute.all()[0].attribute_type choices = [] # holds the final choices attr_fields = {} # to hold the final list of fields for item_attrs in item_attributes.all(): attributes = item_attrs.attribute.all().order_by('attribute_type') for attr in attributes: print attr.attribute_type, ' - ' , _attr_type if attr.attribute_type == _attr_type: choices.append( ( attr.pk, attr.value ) ) else: d = {u'%s' % _attr_type : fields.ChoiceField(choices=choices, widget=RadioSelect)} attr_fields = dict(attr_fields.items() + d.items() ) # set the _attr_type to new type and start over with next attribute type _attr_type = attr.attribute_type choices = [] return attr_fields form_fields = { 'item' : fields.IntegerField(widget=HiddenInput), } form_fields = dict(form_fields.items() + get_attributes(item).items()) return type('SandboxForm', (forms.BaseForm, ), { 'base_fields' : form_fields}) Invoke the form my calling this factory method as: form = make_sandbox_form() http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ (Wish I could upvote all but being a StackOverflow rookie I lack the reputation to do so.) A: I would create dynamic form, creating one choice field for every AttributeType. Then, you can easily replace widget with radio buttons. This article could be helpful: http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/
[ "stackoverflow", "0008577470.txt" ]
Q: Black Berry emulator for Windows Mobile Say I want to develop applications for BlackBerry, but I only have a phone with Windows Mobile and for whatever reason I cannot switch to BlackBerry or buy a new phone. Is there any BlackBerry emulator for Windows Mobile that would allow me to run apps on Windows Mobile 6? I have HTC HD2. P.S. I'm not interested in emulators for any other platform. A: There is no Blackberry emulator that you can run on a Windows Mobile device. RIM does provide Blackberry simulators for most of its devices that you can run on a Windows PC in companionship with your development environment, though.
[ "askubuntu", "0000574852.txt" ]
Q: Ubuntu Software Center Crashing I recently installed an upgrade for Ubuntu, however due to a mis-click, I accidentally aborted the update installation in between. Since then my software center has stopped working. It just keeps on crashing. I tried several commands, tried uninstalling and reinstalling the software center as well. However when I run software-center from the terminal, it gives this output: nrbhyagrwl@nrbhyagrwl-Ubuntu:~$ software-center /usr/share/software-center/softwarecenter/ui/gtk3/SimpleGtkbuilderApp.py:32: Warning: The property GtkImage:stock is deprecated and shouldn't be used anymore. It will be removed in a future version. self.builder.add_from_file(path) /usr/share/software-center/softwarecenter/ui/gtk3/SimpleGtkbuilderApp.py:32: Warning: The property GtkImageMenuItem:use-stock is deprecated and shouldn't be used anymore. It will be removed in a future version. self.builder.add_from_file(path) /usr/share/software-center/softwarecenter/ui/gtk3/SimpleGtkbuilderApp.py:32: Warning: The property GtkImageMenuItem:image is deprecated and shouldn't be used anymore. It will be removed in a future version. self.builder.add_from_file(path) /usr/share/software-center/softwarecenter/ui/gtk3/SimpleGtkbuilderApp.py:32: Warning: The property GtkSettings:gtk-menu-images is deprecated and shouldn't be used anymore. It will be removed in a future version. self.builder.add_from_file(path) /usr/share/software-center/softwarecenter/ui/gtk3/SimpleGtkbuilderApp.py:32: Warning: The property GtkAlignment:top-padding is deprecated and shouldn't be used anymore. It will be removed in a future version. self.builder.add_from_file(path) /usr/share/software-center/softwarecenter/ui/gtk3/SimpleGtkbuilderApp.py:32: Warning: The property GtkAlignment:bottom-padding is deprecated and shouldn't be used anymore. It will be removed in a future version. self.builder.add_from_file(path) /usr/share/software-center/softwarecenter/ui/gtk3/SimpleGtkbuilderApp.py:32: Warning: The property GtkAlignment:left-padding is deprecated and shouldn't be used anymore. It will be removed in a future version. self.builder.add_from_file(path) /usr/share/software-center/softwarecenter/ui/gtk3/SimpleGtkbuilderApp.py:32: Warning: The property GtkAlignment:right-padding is deprecated and shouldn't be used anymore. It will be removed in a future version. self.builder.add_from_file(path) 2015-01-17 11:41:38,231 - softwarecenter.ui.gtk3.app - INFO - setting up proxy 'None' 2015-01-17 11:41:39,322 - softwarecenter.plugin - INFO - activating plugin '<module 'webapps_activation' from '/usr/share/software-center/softwarecenter/plugins/webapps_activation.pyc'>' 2015-01-17 11:41:39,461 - softwarecenter.db.pkginfo_impl.aptcache - INFO - aptcache.open() 2015-01-17 11:41:40,586 - softwarecenter.backend.reviews - WARNING - error creating bsddb: '(22, 'Invalid argument -- BDB0054 illegal flag combination specified to DB_ENV->open')' (corrupted?) 2015-01-17 11:41:40,587 - softwarecenter.backend.reviews - ERROR - trying to repair DB failed Traceback (most recent call last): File "/usr/share/software-center/softwarecenter/backend/reviews/__init__.py", line 358, in _save_review_stats_cache_blocking self._dump_bsddbm_for_unity(outfile, outdir) File "/usr/share/software-center/softwarecenter/backend/reviews/__init__.py", line 377, in _dump_bsddbm_for_unity 0600) DBInvalidArgError: (22, 'Invalid argument -- BDB0054 illegal flag combination specified to DB_ENV->open') /usr/lib/python2.7/dist-packages/gi/overrides/GLib.py:560: Warning: Source ID 74 was not found when attempting to remove it return super(MainContext, self).iteration(may_block) /usr/lib/python2.7/dist-packages/gi/overrides/GLib.py:560: Warning: Source ID 76 was not found when attempting to remove it return super(MainContext, self).iteration(may_block) /usr/share/software-center/softwarecenter/ui/gtk3/views/appdetailsview.py:95: Warning: The property GtkAlignment:xscale is deprecated and shouldn't be used anymore. It will be removed in a future version. Gtk.Alignment.__init__(self, xscale=1.0, yscale=1.0) /usr/share/software-center/softwarecenter/ui/gtk3/views/appdetailsview.py:95: Warning: The property GtkAlignment:yscale is deprecated and shouldn't be used anymore. It will be removed in a future version. Gtk.Alignment.__init__(self, xscale=1.0, yscale=1.0) /usr/share/software-center/softwarecenter/ui/gtk3/widgets/description.py:418: Warning: The property GtkImageMenuItem:accel-group is deprecated and shouldn't be used anymore. It will be removed in a future version. Gtk.STOCK_COPY, None) No bp log location saved, using default. [000:000] Cpu: 6.23.10, x2, 2200Mhz, 3918MB [000:000] Computer model: Not available No bp log location saved, using default. [000:000] Cpu: 6.23.10, x2, 2200Mhz, 3918MB [000:000] Computer model: Not available [000:000] Browser XEmbed support present: 1 [000:000] Browser toolkit is Gtk2. [000:001] Using Gtk2 toolkit [000:012] Warning(optionsfile.cc:30): Load: Could not open file, err=2 [000:012] No bp log location saved, using default. [000:012] Cpu: 6.23.10, x2, 2200Mhz, 3918MB [000:012] Computer model: Not available [000:002] Warning(optionsfile.cc:30): Load: Could not open file, err=2 [000:002] No bp log location saved, using default. [000:002] Cpu: 6.23.10, x2, 2200Mhz, 3918MB [000:002] Computer model: Not available [000:002] Browser XEmbed support present: 1 [000:002] Browser toolkit is Gtk2. [000:002] Using Gtk2 toolkit ** Gtk:ERROR:/build/buildd/gtk+3.0-3.15.3+git20150113.f26986a5/./gtk/gtkstylecontext.c:2929:_gtk_style_context_validate: assertion failed: (!gtk_style_context_is_saved (context)) Aborted (core dumped) How do I fix this? A: Finish doing the updates. Once that's done, uninstall and purge the Software Center by running: apt-get purge software-center And then restore it with: apt-get install software-center
[ "physics.stackexchange", "0000261144.txt" ]
Q: Thermodynamics compression work So I have a college homework problem that I have not been able to solve "A 4-L rigid rank contains 2 kg of saturated liquid-vapor mixture of water at 50 degrees celsius. The water is now slowly heated until it exists in a single phase. At the final state, will the water be in the liquid phase or the vapor phase? What will your answer be if the volume of the tank were 10L instead of 4L?" In this problem, I did not understand how to find the pressure from the water vapor, the mass of the water vapor, and the volume occupied by the liquid water. I also do not understand the relationship between saturation pressure and temperature. I have tried my lecture notes, googling, khanacademy, and other questions on the physics stack exchange but I can't quite understand how to apply the topics mentioned to this problem. Could someone give me some insight on how to solve this problem? A: Since the mass and volume are constant, the specific volume is constant. In the first case it is 0.002 m³/kg (0.004/2), in the second case it's 0.005 m³/kg. The region under the curve in the T-v diagram is the vapor+liquid region. The region to the left is the liquid region, to the right is the vapor region. The state of the system in case one is somewhere on the vertical line corresponding to a specific volume of 0.002 m³/kg. Heating the system will move that point upward, but it will remain on that vertical line. That line crosses the curve to the left of the critical point, in other words, it crosses the saturated liquid line. The vertical line representing a specific volume of 0.005 m³/kg crosses the curve to the right of the critical point: it crosses the saturated vapor line. So the answer in case one (4 liter tank) is liquid phase, in case two (10 liter tank) the answer is vapor phase.
[ "stackoverflow", "0023807084.txt" ]
Q: I don't get this recursion Given this code: void recursion(int x) { if (x > 0) { recursion(x-1); printf("%d", x); } } Using: recursion(5); Why does it print 12345? I logically follow the function I would think it would print 43210 EDIT: sorry if this might look super stupid to you but I'm still learning. A: Just follow through the steps the code goes through (use a debugger to see it happen in real-time): recursion(5); if (5 > 0) recursion(4); if (4 > 0) recursion(3); if (3 > 0) recursion(2); if (2 > 0) recursion(1); if (1 > 0) recursion(0); if (0 > 0) { // false, so if body skipped and function simply returns} printf("%d", 1); // The next statement after the call recursion(0) printf("%d", 2); // The next statement after the call recursion(1) printf("%d", 3); // The next statement after the call recursion(2) printf("%d", 4); // The next statement after the call recursion(3) printf("%d", 5); // The next statement after the call recursion(4)
[ "stackoverflow", "0004106367.txt" ]
Q: HTML Generator, Gallery Generator or Templating? SMALL VERSION OF THE QUESTION: " I need a lib for python or program (pref. for Linux) that receives a list of urls for images and gives me the hmtl for a table (maybe easy to configure(rows and look)) LONG VERSION OF THE QUESTION: I have and array with a list of url's for images, and I want to make a table (I don't know if this is the best practice, but I think it's the easiest). I don't care if the thumbs are the same file as the big one (just forced to be small). And I don't need to copy the images to anywhere. I use the following code( d= ["http://.....jpg","http://.....jpg","http://.....jpg","http://.....jpg"]): def stupidtable(d): d = list(set(d)) antes=' <tr> <td><a href="' dp11='"><img src="' dp12= '" width="100%" /></a></td> <td><a href="' dp21= '"><img src="' dp22='" width="100%" /></a></td>' bb=['<table border="0"> '] ii=len( d) i=0 while i<ii-1: bb.append(antes) bb.append(d[i]) bb.append(dp11) bb.append(d[i]) bb.append(dp12) bb.append(d[i+1]) bb.append(dp21) bb.append(d[i+1]) bb.append(dp22) i=i+2 return bb (I know the code is shady and it skips the last one if it's an odd number... but it's caffeine fueled code and I just needed to get it done... nothing I'm proud of:) I know there must be a better way(and prettier.. 'cus this looks really ugly), and a way that I can specify the number of columns, and other options. I couldn't find a gallery generator for my case (all I tested copied the files to new directory). Should I learn a templating lang? Is it worth it? Or Should I use an HTML Generator? Or should I look into better coding HTML? What Would you do if you had my problem? This is the solution I came up with (after adpting the code from kind Mr MatToufoutu): from jinja2 import Template my_template = Template(""" <html> <style type="text/css"> img {border: none;} </style> <body> <table border="0" cellpadding="0" and cellspacing="0"> <tr> {% for url in urls %} <td><a href="{{ url }}"><img width="100%" src="{{ url }}"/></td> {% if loop.index is divisibleby cols %} </tr><tr> {% endif %} {% endfor %} </tr> </table> """) cols=3 urls =["./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg","./a.jpg"] html = my_template.render(cols=cols,urls=urls) A: I think the easiest way to achieve this would be to use a template language like Mako, Cheetah or Jinja. Personally i'd choose Jinja, because it is very similar to the Django template language, but they are all very powerful. A very simple example of what you want, using Jinja, would look like this: from jinja2 import Template my_template = Template(""" <html> <body> <table border="0"> <tr> {% for url in urls %} <td><a href="{{ url }}">{{ url }}</td> {% endfor %} </tr> </table> """) urls = ["http://.....jpg","http://.....jpg","http://.....jpg","http://.....jpg"] rendered_html = my_template.render(urls=urls) Which is way more readable than building the html by hand like you did.
[ "math.stackexchange", "0001993698.txt" ]
Q: Find a power series of $f(x)=\frac{x}{(1-x)(1-x^2)}$ around the center $0$ and determine its interval of convergence. Can anyone give me a detailed step to get the power series representation for $f(x)=\frac {x}{(1-x)(1-x^2)}$? A: We can use this: $$\frac { 1 }{ 1-x } \sum _{ n=0 }^{ \infty }{ { a }_{ n }{ x }^{ n } } =\sum _{ n=0 }^{ \infty }{ \left( { a }_{ 0 }+{ a }_{ 1 }+\cdots +{ a }_{ n } \right) { x }^{ n } } $$ Expand $\frac {1}{1-x^2}$, $$\frac { 1 }{ 1-{ x }^{ 2 } } =\sum _{ n=0 }^{ \infty }{ { x }^{ 2n } } =\sum _{ k=0 }^{ \infty }{ \frac { 1+{ \left( -1 \right) }^{ k } }{ 2 } { x }^{ k } } $$ Therefore, $$\frac { 1 }{ 1-x } \sum _{ k=0 }^{ \infty }{ \frac { 1+{ \left( -1 \right) }^{ k } }{ 2 } { x }^{ k } } =\sum _{ k=0 }^{ \infty }{ \left( k+1 \right) { \left( { x }^{ 2k }+{ x }^{ 2k+1 } \right) } } $$ Finally multiply a $x$, we get, $$\frac { 1 }{ 1-x } \frac { x }{ 1-{ x }^{ 2 } } =\sum _{ k=0 }^{ \infty }{ \left( k+1 \right) { \left( { x }^{ 2k+1 }+{ x }^{ 2k+2 } \right) } }=\sum _{ n=1 }^{ \infty }{ n{ \left( { x }^{ 2n-1 }+{ x }^{ 2n } \right) } } $$ The even term and odd term of the expansion is kind of different. I don't know if I write like above is ok. That's the most difficult part, how to express it. The expansion is in this pattern: $$x+x^2+2x^3+2x^4+3x^5+3x^6+4x^7+4x^8+...$$
[ "stackoverflow", "0010758028.txt" ]
Q: Kindle Fire and GlSurfaceView.getHeight() Im developing a game for the kindle fire, the game always run with the bar hidden. Only when the user enters to the pause menu the bar should appear , I only want that the bar shows up over the game. But it seems that when the bar show up GlSurfaceView.getHeight() changes from 600 to 580, and my game resizes, but I dont want that behavior, I just want that the bar shows up over the game and my game doesnt move , I've already tried with GlSurfaceView.setMinimumHeight(600); but the kindle simply ignores that. this is how my game always runs : and when i activate the bar this happens : instead of this : you know a way to avoid this? Thanks! To create the GlSurfaceView i do the following: OnCreate() { s_activity.m_view = new GameGLSurfaceView(s_activity.getApplication(), true, pixelSize,depthSize, stencilSize); } public GameGLSurfaceView(Context context, boolean translucent,int pixelSize, int depth, int stencil) { super(context); mRenderer = new GameRenderer(context, this); setRenderer(mRenderer); } to Hide and show the bar i use this function private static final int AMAZON_FLAG_NOSOFTKEYS = 0x80000000; private static final int FLAG_SUPER_FULLSCREEN = AMAZON_FLAG_NOSOFTKEYS | WindowManager.LayoutParams.FLAG_FULLSCREEN; public static void toggleKindleBar(final int toDo) { if( s_activity != null) s_activity.runOnUiThread(new Runnable() { public void run() { s_activity.getWindow().clearFlags( toDo!=1? WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN : FLAG_SUPER_FULLSCREEN); s_activity.getWindow().addFlags( toDo!=1? FLAG_SUPER_FULLSCREEN:WindowManager.LayoutParams.FLAG_FULLSCREEN); } }); } A: possible solutions: try this on the onCreate() method of the activity: getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); do note that according to my experience , the kindle fire has some weird problems with some views when they are used while this code runs , so even if it works , please do some extensive testing . try to set the manifest to have some flags for the configChanges, but i didn't tested it and i don't have the kindle fire anymore .