qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
12,925,401
I have created the following custom ValidationAttribute: ``` public class DateRangeAttribute : ValidationAttribute, IClientValidatable { public DateTime MinimumDate = new DateTime(1901, 1, 1); public DateTime MaximumDate = new DateTime(2099, 12, 31); public DateRangeAttribute(string minDate, string maxDate, string errorMessage) { MinimumDate = DateTime.Parse(minDate); MaximumDate = DateTime.Parse(maxDate); ErrorMessage = string.Format(errorMessage, MinimumDate.ToString("MM/dd/yyyy"), MaximumDate.ToString("MM/dd/yyyy")); } } ``` that I would like to use in my MVC4 view model as follows: ``` [DateRange(Resources.MinimumDate, Resources.MaximumDate, "Please enter a date between {0} and {1}")] ``` *Resources* is a generated resources class based on a set of options stored in a SQL database. A simplified version of the generated code for the above two resource properties is: ``` public class Resources { public const string MinimumDate = "PropMinimumDate"; public static string PropMinimumDate { get { return "12/15/2010" } } public const string MaximumDate = "PropMaximumDate"; public static string PropMaximumDate { get { return "12/15/2012" } } } ``` While I do not understand how it works, I do understand that typical usage of resources in ValidationAttributes will automatically map *Resources.MinimumDate* to *PropMinimumDate* and return the value "12/15/2010". What I am cannot figure out is how to manually make that programmatic leap myself so I can pass in the two date values into my custom ValidatorAttribute. As presently coded, *"PropMinimumDate"* and *"PropMaximumDate"* are the *minDate* and *maxDate* parameter values (respectively) passed into the constructor of the DateRangeAttribute. If I try ``` [DateRange(Resources.PropMinimumDate, Resources.PropMaximumDate, "Please enter a date between {0} and {1}")] ``` I receive the compile error: *An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type* Is there a way to accomplish this task, or am I attempting the impossible?
2012/10/17
[ "https://Stackoverflow.com/questions/12925401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/645258/" ]
You need to take the `Type` of the resource class as an argument and then use reflections to get the property value. ``` public class DateRangeAttribute : ValidationAttribute, IClientValidatable { public DateTime MinimumDate = new DateTime(1901, 1, 1); public DateTime MaximumDate = new DateTime(2099, 12, 31); private Type _resourceType; public DateRangeAttribute(string minDate, string maxDate, string errorMessage, Type resourceType) { _resourceType = resourceType; var minDateProp = _resourceType.GetProperty(minDate, BindingFlags.Static | BindingFlags.Public); var minDateValue = (string) minDateProp.GetValue((object) null, (object[]) null)); MinimumDate = DateTime.Parse(minDateValue); // similarly get the value for MaxDate ErrorMessage = string.Format(errorMessage, MinimumDate.ToString("MM/dd/yyyy"), MaximumDate.ToString("MM/dd/yyyy")); } } ``` Eg ``` [DateRange(Resources.MinimumDate, Resources.MaximumDate, "Please enter a date between {0} and {1}", typeof(Resources))] ```
You are not attempting the impossible, but you are going to have to work around the limitation just a tad. So, to comply with the compiler we have two options and the first is the most ideal, change the generated `Resources` class. ``` public class Resources { public const string PropMinimumDate = "12/15/2010"; public const string PropMaximumDate = "12/15/2012"; } ``` Now, if we can't do that then we'll go a different route, let's modify the class that the adorned property exists in and add a couple `const` fields to it like so. ``` public class EntityClass { private const string MinimumDate = "12/15/2010"; private const string MaximumDate = "12/15/2012"; [DateRange(MinimumDate, MaximumDate, "Please enter a date between {0} and {1}")] } ``` However, unless you can code generate the entity class the last option kind of violates your need to pull the values from the database. So, hopefully you can change the `Resources` class.
16,168
When using `VertexColors`, the docs state: > > The interior of the polygon is colored by interpolating between the colors specified by `VertexColors`. > > > It however doesn't say how this interpolation is carried out. I've seen at times that small quirks show up that I wouldn't expect, and I'm wondering if someone else has a clearer perspective on exactly why and when these show up. ``` aim = {Cos[2 π #], Sin[2 π #]} &; angles[n_] := Range[0, 0.5, 0.5/(n - 1)]; colors[n_] := Join[ConstantArray[Purple, n], ConstantArray[Orange, n]]; draw[n_, a_] := Graphics[{ Polygon[Join[aim /@ angles[n], a aim@# & /@ Reverse[angles[n]]], VertexColors -> colors[n] ]}] ``` Using this definition and `n = 5`, I don't see anything wrong when `a = 0.415`, but when `a = 0.414`, it looks like it's interpolating incorrectly, and when `n` is set larger, two such quirks appear which seem to always be present. This can be seen in the three calls: ``` GraphicsColumn[{draw[5, 0.415], draw[5, 0.414], draw[100, 0.415]}] ``` So the question is, why does this happen and is there a general way to avoid it, or test for when it's expected to happen? I know that for this particular example I can avoid it simply by splitting my single polygon into many smaller 4 point polygons, I'm not asking for code that just draws a shaded arc. I'm interested in the underlying problem. ![Graphics showing the appearance of the quirks](https://i.stack.imgur.com/dNwCF.png)
2012/12/12
[ "https://mathematica.stackexchange.com/questions/16168", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1194/" ]
The behavior you are seeing is, that OpenGL (which is most probably used) has to break your your polygon of many vertices into triangles. What you then see are artifacts of the linear interpolation of the colors. When you assign a random color to each vertex, you can observe the triangle structure ``` aim = {Cos[2 π #], Sin[2 π #]} &; angles[n_] := Range[0, 0.5, 0.5/(n - 1)]; colors[n_] := Join[ConstantArray[Purple, n], ConstantArray[Orange, n]]; draw[n_, a_] := Graphics[{ Polygon[Join[aim /@ angles[n], a aim@# & /@ Reverse[angles[n]]], VertexColors -> (RGBColor @@@ RandomReal[{0, 1}, {2 n, 3}])]}] Manipulate[draw[n, a], {a, 0.4, 0.5}, {n, 5, 20, 1}] ``` ![Mathematica graphics](https://i.stack.imgur.com/JeShR.png) To my knowledge, it is not possible to influence the process of breaking a polygon down to triangles and therefore ensure a satisfying colorization. What you **can** do of course is, give triangles as polygons and therefore ensure this manually. In your case this would be something like ``` points[n_, a_] := {#1, #2, #4, #3} & @@@ Partition[Flatten[Transpose[{a #, #}], 1], 4, 2] &@ Table[{Cos[φ], Sin[φ]}, {φ, 0, π, π/(n - 1)}]; Manipulate[ Graphics[Polygon[points[n, a], VertexColors -> ConstantArray[{Orange, Purple, Purple, Orange}, n - 1]]], {a, 0.4, 0.5}, {n, 5, 20, 1}] ``` ![Mathematica graphics](https://i.stack.imgur.com/fRulZ.png)
As stated in my answer, the problem for the arc was solved with just creating polygons such that they ended up without defects similar to how halirutan did it, which is a method to avoid these problems in specific cases. But in the general case this doesn't work out, so I also found a solution by triangulating the polygon using the Delaunay triangulation. This seems to work, and my intuition tells me it should work for all non-self-intersecting polygons (\* My intuition fails me, see update): ``` Needs["ComputationalGeometry`"] trisFromDelaunay[o_,l_]:=Sequence@@({o,Sequence@@#}&/@Partition[l,2,1]) triangulate[points_]:=trisFromDelaunay@@@DelaunayTriangulation[points] filter[indices_]:=Select[indices,Signature[#]==1&] polygonColoredTris[points_,VertexColors->colors_]:= Polygon[points[[#]]&/@#,VertexColors->colors[[#]]]&/@filter[triangulate[points]] ``` This seems to work nicely for my current uses. ``` n = 50; l = 0.3; u = 1.9; spiral = Join[#, Reverse[0.6 #]] &@(# aim[#] & /@ Range[l, u, (u - l)/(n - 1)]); spiralColors = Blend[{Purple, Orange}, #] & /@ Range[0, 1, 1/(n - 1)]; GraphicsRow@Table[ Graphics[{ testing[spiral, VertexColors -> colors[n]] }], {testing, {Polygon, polygonColoredTris}}] ``` ![New function tested on a spiral geometry](https://i.stack.imgur.com/p8AZi.png) **Update** Whoops, turns out this also only works under special conditions. Specifically, you aren't guaranteed that the original edges are actually present in the triangulation; I got by because I was looking at cases where they did. So I'm back to the drawing board.
16,168
When using `VertexColors`, the docs state: > > The interior of the polygon is colored by interpolating between the colors specified by `VertexColors`. > > > It however doesn't say how this interpolation is carried out. I've seen at times that small quirks show up that I wouldn't expect, and I'm wondering if someone else has a clearer perspective on exactly why and when these show up. ``` aim = {Cos[2 π #], Sin[2 π #]} &; angles[n_] := Range[0, 0.5, 0.5/(n - 1)]; colors[n_] := Join[ConstantArray[Purple, n], ConstantArray[Orange, n]]; draw[n_, a_] := Graphics[{ Polygon[Join[aim /@ angles[n], a aim@# & /@ Reverse[angles[n]]], VertexColors -> colors[n] ]}] ``` Using this definition and `n = 5`, I don't see anything wrong when `a = 0.415`, but when `a = 0.414`, it looks like it's interpolating incorrectly, and when `n` is set larger, two such quirks appear which seem to always be present. This can be seen in the three calls: ``` GraphicsColumn[{draw[5, 0.415], draw[5, 0.414], draw[100, 0.415]}] ``` So the question is, why does this happen and is there a general way to avoid it, or test for when it's expected to happen? I know that for this particular example I can avoid it simply by splitting my single polygon into many smaller 4 point polygons, I'm not asking for code that just draws a shaded arc. I'm interested in the underlying problem. ![Graphics showing the appearance of the quirks](https://i.stack.imgur.com/dNwCF.png)
2012/12/12
[ "https://mathematica.stackexchange.com/questions/16168", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1194/" ]
The behavior you are seeing is, that OpenGL (which is most probably used) has to break your your polygon of many vertices into triangles. What you then see are artifacts of the linear interpolation of the colors. When you assign a random color to each vertex, you can observe the triangle structure ``` aim = {Cos[2 π #], Sin[2 π #]} &; angles[n_] := Range[0, 0.5, 0.5/(n - 1)]; colors[n_] := Join[ConstantArray[Purple, n], ConstantArray[Orange, n]]; draw[n_, a_] := Graphics[{ Polygon[Join[aim /@ angles[n], a aim@# & /@ Reverse[angles[n]]], VertexColors -> (RGBColor @@@ RandomReal[{0, 1}, {2 n, 3}])]}] Manipulate[draw[n, a], {a, 0.4, 0.5}, {n, 5, 20, 1}] ``` ![Mathematica graphics](https://i.stack.imgur.com/JeShR.png) To my knowledge, it is not possible to influence the process of breaking a polygon down to triangles and therefore ensure a satisfying colorization. What you **can** do of course is, give triangles as polygons and therefore ensure this manually. In your case this would be something like ``` points[n_, a_] := {#1, #2, #4, #3} & @@@ Partition[Flatten[Transpose[{a #, #}], 1], 4, 2] &@ Table[{Cos[φ], Sin[φ]}, {φ, 0, π, π/(n - 1)}]; Manipulate[ Graphics[Polygon[points[n, a], VertexColors -> ConstantArray[{Orange, Purple, Purple, Orange}, n - 1]]], {a, 0.4, 0.5}, {n, 5, 20, 1}] ``` ![Mathematica graphics](https://i.stack.imgur.com/fRulZ.png)
Here's a triangulation approach that might work easily and more generally. Let's start with one of your problematic examples: ``` drawing = draw[5, 0.414] ``` ![bad example](https://i.stack.imgur.com/PegE1.png) Now, let's triangulate, after getting rid of `10^-17` type expressions. ``` Graphics`Mesh`MeshInit[]; pts = Chop[drawing[[1, 1, 1]]]; tri = PolygonTriangulate[pts] (* Out: {{6, 4, 5}, {4, 2, 3}, {1, 9, 10}, {8, 2, 4}, {9, 2, 8}, {2, 9, 1}, {4, 7, 8}, {4, 6, 7}} *) ``` Finally, we'll assemble it into a `GraphicsComplex`. ``` colors = VertexColors /. drawing[[1, 1, 2]]; newcolors = colors[[#]] & /@ tri; Graphics[GraphicsComplex[pts, Polygon[tri, VertexColors -> newcolors]]] ``` ![after triangulation](https://i.stack.imgur.com/JHuND.png) We can see the triangulation using `EdgeForm`, which might be useful to understand the colorization. ``` Graphics[GraphicsComplex[pts, {EdgeForm[Black], Polygon[tri, VertexColors -> newcolors]}]] ``` ![with edges indicated](https://i.stack.imgur.com/Z2TBv.png) which explains why it doesn't work so well here with `draw[100, 0.414]`: ![another bad example](https://i.stack.imgur.com/aFqq3.png) On the other hand we could use the following triangulation of your `draw[100, 0.414]` polygon (obtained from the `triangle` program as described in [this answer](https://mathematica.stackexchange.com/questions/3646/how-to-make-a-3d-globe/3695#3695)): ![fine triangulation](https://i.stack.imgur.com/oNfKa.png) We could then color the newly introduced vertices using linear interpolation between orange and purple. The result is: ![nicely colored](https://i.stack.imgur.com/SYccO.png) which is not too bad! I'd be glad to share more specific code, if you get the `triangle` command working, as described in the globe answer.
16,168
When using `VertexColors`, the docs state: > > The interior of the polygon is colored by interpolating between the colors specified by `VertexColors`. > > > It however doesn't say how this interpolation is carried out. I've seen at times that small quirks show up that I wouldn't expect, and I'm wondering if someone else has a clearer perspective on exactly why and when these show up. ``` aim = {Cos[2 π #], Sin[2 π #]} &; angles[n_] := Range[0, 0.5, 0.5/(n - 1)]; colors[n_] := Join[ConstantArray[Purple, n], ConstantArray[Orange, n]]; draw[n_, a_] := Graphics[{ Polygon[Join[aim /@ angles[n], a aim@# & /@ Reverse[angles[n]]], VertexColors -> colors[n] ]}] ``` Using this definition and `n = 5`, I don't see anything wrong when `a = 0.415`, but when `a = 0.414`, it looks like it's interpolating incorrectly, and when `n` is set larger, two such quirks appear which seem to always be present. This can be seen in the three calls: ``` GraphicsColumn[{draw[5, 0.415], draw[5, 0.414], draw[100, 0.415]}] ``` So the question is, why does this happen and is there a general way to avoid it, or test for when it's expected to happen? I know that for this particular example I can avoid it simply by splitting my single polygon into many smaller 4 point polygons, I'm not asking for code that just draws a shaded arc. I'm interested in the underlying problem. ![Graphics showing the appearance of the quirks](https://i.stack.imgur.com/dNwCF.png)
2012/12/12
[ "https://mathematica.stackexchange.com/questions/16168", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1194/" ]
As can be seen from the images presented, the interpolation being done under the hood by `VertexColors` depends on a prior triangulation of the polygon, thus resulting in visible triangular bands. The approaches presented thus far have all needed to perform a preliminary triangulation; I shall now present a method that avoids this preprocessing step. One particularly beautiful method I have encountered in the literature is the use of [Floater and Hormann's *mean value coordinates*](http://dx.doi.org/10.1145/1183287.1183295), which are a generalization of the classical barycentric coordinates for triangles. (There are other generalizations; if you are interested, have a look at their bibliography.) In fact, one of the applications presented in their paper is exactly this problem. Here, now, is a *Mathematica* routine for performing mean value interpolation over an arbitrary polygon: ``` MeanValueInterpolation[poly_ /; MatrixQ[poly, NumericQ], vals_ /; ArrayQ[vals, _, NumericQ], x_ /; VectorQ[x, NumericQ]] /; Dimensions[poly] == {Length[vals], Length[x]} := Module[{al, cq, edg, idx, k, ki, n, r, s, w}, s = # - x & /@ poly; r = Norm /@ s; idx = Position[r, w_ /; w == 0]; If[idx =!= {}, Return[Extract[vals, First[idx]]]]; cq = Boole[TrueQ[First[poly] == Last[poly]]]; edg = Partition[s/r, 2, 1, {1, 1 - 2 cq}]; n = Length[poly] - cq; r = Take[r, n]; al = Sign[Det /@ edg]; idx = Position[al, 0]; If[idx =!= {} && Negative[Dot @@ Extract[edg, First[idx]]], ki = Mod[idx[[1, 1]] + {0, 1}, n, 1]; Return[r[[ki]].vals[[Reverse[ki]]]/Total[r[[ki]]]]]; w = ListCorrelate[{1, 1}, al (Norm[Subtract @@ #]/Norm[Total[#]] & /@ edg), -1]/r; w.Take[vals, n]/Total[w]] ``` There are some slight differences in this implementation from the pseudocode presented in the paper; in particular, I elected to use a more stable method for computing the angle between two vectors due to Velvel Kahan. To use this for coloring a polygonal region, we will also use `RegionPlot[]` along with the undocumented [`InPolygonQ`[]](https://mathematica.stackexchange.com/a/9417) for testing if a point lies entirely within a polygon. ``` (* for older versions; use Graphics`PolygonUtils` instead in new Mathematica *) Graphics`Mesh`MeshInit[]; ``` I'll use my own examples first, and come to the example in the OP later. Here is a simplified outline of the United States, and a list of colors corresponding to the vertices: ``` usa = {{-2.151, 0.858}, {-1.562, 0.862}, {-1.414, 0.769}, {-1.243, 0.774}, {-1.083, 0.846}, {-1.052, 0.787}, {-1.378, 0.653}, {-1.433, 0.547}, {-1.42, 0.461}, {-1.605, 0.521}, {-1.715, 0.461}, {-1.881, 0.563}, {-2.04, 0.578}, {-2.138, 0.629}, {-2.2, 0.738}}; cols = ColorData["ThermometerColors"] /@ Range[0, 1, 1/14]; ``` Let's compare the mean value approach (left) and the built-in `VertexColors`: ``` GraphicsRow[{RegionPlot[InPolygonQ[usa, {x, y}], {x, -2.2, -1.1}, {y, 0.46, 0.87}, AspectRatio -> Automatic, BoundaryStyle -> None, ColorFunction -> (RGBColor @@ Clip[ MeanValueInterpolation[usa, List @@@ cols, {#1, #2}], {0, 1}] &), ColorFunctionScaling -> False], Graphics[Polygon[usa, VertexColors -> cols], Frame -> True]}] ``` ![colored USA outline; mean value vs. default](https://i.stack.imgur.com/fghaR.png) As a second example, here is a [bean-shaped polygon](http://nvlpubs.nist.gov/nistpubs/jres/58/jresv58n3p155_A1b.pdf) and a set of associated colors: ``` bean = {{0., 0.11}, {-0.05, 0.108}, {-0.1, 0.115}, {-0.16, 0.15}, {-0.22, 0.205}, {-0.32, 0.3}, {-0.4, 0.358}, {-0.5, 0.42}, {-0.55, 0.436}, {-0.6, 0.43}, {-0.644, 0.4}, {-0.66, 0.35}, {-0.655, 0.3}, {-0.635, 0.2}, {-0.595, 0.1}, {-0.552, 0.}, {-0.5, -0.105}, {-0.44, -0.2}, {-0.4, -0.25}, {-0.35, -0.3}, {-0.3, -0.344}, {-0.204, -0.4}, {-0.1, -0.436}, {0., -0.448}, {0.1, -0.442}, {0.23, -0.4}, {0.3, -0.35}, {0.353, -0.3}, {0.43, -0.2}, {0.477, -0.1}, {0.51, 0.}, {0.522, 0.1}, {0.52, 0.16}, {0.5, 0.24}, {0.456, 0.3}, {0.4, 0.33}, {0.36, 0.337}, {0.3, 0.32}, {0.25, 0.29}, {0.2, 0.245}, {0.15, 0.2}, {0.1, 0.16}, {0.05, 0.128}}; cols = {{0.834, 1., 0.}, {0.497, 1., 0.}, {0.172, 1., 0.}, {0., 1., 0.035}, {0., 1., 0.107}, {0., 1., 0.161}, {0., 1., 0.206}, {0., 1., 0.255}, {0., 1., 0.288}, {0., 1., 0.339}, {0., 1., 0.406}, {0., 1., 0.473}, {0., 1., 0.528}, {0., 1., 0.648}, {0., 1., 0.783}, {0., 1., 0.951}, {0., 0.834, 1.}, {0., 0.6, 1.}, {0., 0.457, 1.}, {0., 0.294, 1.}, {0., 0.137, 1.}, {0.126, 0., 1.}, {0.383, 0., 1.}, {0.612, 0., 1.}, {0.83, 0., 1.}, {1., 0., 0.887}, {1., 0., 0.714}, {1., 0., 0.571}, {1., 0., 0.332}, {1., 0., 0.133}, {1., 0.044, 0.}, {1., 0.207, 0.}, {1., 0.301, 0.}, {1., 0.43, 0.}, {1., 0.547, 0.}, {1., 0.64, 0.}, {1., 0.692, 0.}, {1., 0.745, 0.}, {1., 0.775, 0.}, {1., 0.789, 0.}, {1., 0.809, 0.}, {1., 0.853, 0.}, {1., 0.952, 0.}}; ``` Now, color the bean in two different ways: ``` GraphicsRow[{RegionPlot[InPolygonQ[bean, {x, y}], {x, -0.7, 0.6}, {y, -0.5, 0.5}, AspectRatio -> Automatic, BoundaryStyle -> None, ColorFunction -> (RGBColor @@ Clip[ MeanValueInterpolation[bean, cols, {#1, #2}], {0, 1}] &), ColorFunctionScaling -> False], Graphics[Polygon[bean, VertexColors -> (RGBColor @@@ cols)], Frame -> True]}] ``` ![behold the coloring of a bean](https://i.stack.imgur.com/c7H4q.png) Finally, here is the OP's example: ``` aim = {Cos[2 π #], Sin[2 π #]} &; angles[n_] := Range[0, 0.5, 0.5/(n - 1)]; sector[a_, n_] := Join[aim /@ angles[n], a aim@# & /@ Reverse[angles[n]]]; colors[n_] := Join[ConstantArray[Purple, n], ConstantArray[Orange, n]]; GraphicsRow[{RegionPlot[InPolygonQ[sector[0.414, 5], {x, y}], {x, -1, 1}, {y, 0, 1}, AspectRatio -> Automatic, BoundaryStyle -> None, ColorFunction -> (RGBColor @@ Clip[ MeanValueInterpolation[sector[0.414, 5], List @@@ colors[5], {#1, #2}], {0, 1}] &), ColorFunctionScaling -> False], RegionPlot[InPolygonQ[sector[0.4, 30], {x, y}], {x, -1, 1}, {y, 0, 1}, AspectRatio -> Automatic, BoundaryStyle -> None, ColorFunction -> (RGBColor @@ Clip[ MeanValueInterpolation[sector[0.4, 30], List @@@ colors[30], {#1, #2}], {0, 1}] &), ColorFunctionScaling -> False]}] ``` ![colored sectors](https://i.stack.imgur.com/oPQXs.png) In all cases, the mean value coloring did a much better job than the built-in `VertexColors`. Of course, you no longer have a simple polygon, since `RegionPlot[]` has broken your polygon up into tiny triangles, but if the coloring is needed, this might be a small price to pay.
As stated in my answer, the problem for the arc was solved with just creating polygons such that they ended up without defects similar to how halirutan did it, which is a method to avoid these problems in specific cases. But in the general case this doesn't work out, so I also found a solution by triangulating the polygon using the Delaunay triangulation. This seems to work, and my intuition tells me it should work for all non-self-intersecting polygons (\* My intuition fails me, see update): ``` Needs["ComputationalGeometry`"] trisFromDelaunay[o_,l_]:=Sequence@@({o,Sequence@@#}&/@Partition[l,2,1]) triangulate[points_]:=trisFromDelaunay@@@DelaunayTriangulation[points] filter[indices_]:=Select[indices,Signature[#]==1&] polygonColoredTris[points_,VertexColors->colors_]:= Polygon[points[[#]]&/@#,VertexColors->colors[[#]]]&/@filter[triangulate[points]] ``` This seems to work nicely for my current uses. ``` n = 50; l = 0.3; u = 1.9; spiral = Join[#, Reverse[0.6 #]] &@(# aim[#] & /@ Range[l, u, (u - l)/(n - 1)]); spiralColors = Blend[{Purple, Orange}, #] & /@ Range[0, 1, 1/(n - 1)]; GraphicsRow@Table[ Graphics[{ testing[spiral, VertexColors -> colors[n]] }], {testing, {Polygon, polygonColoredTris}}] ``` ![New function tested on a spiral geometry](https://i.stack.imgur.com/p8AZi.png) **Update** Whoops, turns out this also only works under special conditions. Specifically, you aren't guaranteed that the original edges are actually present in the triangulation; I got by because I was looking at cases where they did. So I'm back to the drawing board.
16,168
When using `VertexColors`, the docs state: > > The interior of the polygon is colored by interpolating between the colors specified by `VertexColors`. > > > It however doesn't say how this interpolation is carried out. I've seen at times that small quirks show up that I wouldn't expect, and I'm wondering if someone else has a clearer perspective on exactly why and when these show up. ``` aim = {Cos[2 π #], Sin[2 π #]} &; angles[n_] := Range[0, 0.5, 0.5/(n - 1)]; colors[n_] := Join[ConstantArray[Purple, n], ConstantArray[Orange, n]]; draw[n_, a_] := Graphics[{ Polygon[Join[aim /@ angles[n], a aim@# & /@ Reverse[angles[n]]], VertexColors -> colors[n] ]}] ``` Using this definition and `n = 5`, I don't see anything wrong when `a = 0.415`, but when `a = 0.414`, it looks like it's interpolating incorrectly, and when `n` is set larger, two such quirks appear which seem to always be present. This can be seen in the three calls: ``` GraphicsColumn[{draw[5, 0.415], draw[5, 0.414], draw[100, 0.415]}] ``` So the question is, why does this happen and is there a general way to avoid it, or test for when it's expected to happen? I know that for this particular example I can avoid it simply by splitting my single polygon into many smaller 4 point polygons, I'm not asking for code that just draws a shaded arc. I'm interested in the underlying problem. ![Graphics showing the appearance of the quirks](https://i.stack.imgur.com/dNwCF.png)
2012/12/12
[ "https://mathematica.stackexchange.com/questions/16168", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/1194/" ]
As can be seen from the images presented, the interpolation being done under the hood by `VertexColors` depends on a prior triangulation of the polygon, thus resulting in visible triangular bands. The approaches presented thus far have all needed to perform a preliminary triangulation; I shall now present a method that avoids this preprocessing step. One particularly beautiful method I have encountered in the literature is the use of [Floater and Hormann's *mean value coordinates*](http://dx.doi.org/10.1145/1183287.1183295), which are a generalization of the classical barycentric coordinates for triangles. (There are other generalizations; if you are interested, have a look at their bibliography.) In fact, one of the applications presented in their paper is exactly this problem. Here, now, is a *Mathematica* routine for performing mean value interpolation over an arbitrary polygon: ``` MeanValueInterpolation[poly_ /; MatrixQ[poly, NumericQ], vals_ /; ArrayQ[vals, _, NumericQ], x_ /; VectorQ[x, NumericQ]] /; Dimensions[poly] == {Length[vals], Length[x]} := Module[{al, cq, edg, idx, k, ki, n, r, s, w}, s = # - x & /@ poly; r = Norm /@ s; idx = Position[r, w_ /; w == 0]; If[idx =!= {}, Return[Extract[vals, First[idx]]]]; cq = Boole[TrueQ[First[poly] == Last[poly]]]; edg = Partition[s/r, 2, 1, {1, 1 - 2 cq}]; n = Length[poly] - cq; r = Take[r, n]; al = Sign[Det /@ edg]; idx = Position[al, 0]; If[idx =!= {} && Negative[Dot @@ Extract[edg, First[idx]]], ki = Mod[idx[[1, 1]] + {0, 1}, n, 1]; Return[r[[ki]].vals[[Reverse[ki]]]/Total[r[[ki]]]]]; w = ListCorrelate[{1, 1}, al (Norm[Subtract @@ #]/Norm[Total[#]] & /@ edg), -1]/r; w.Take[vals, n]/Total[w]] ``` There are some slight differences in this implementation from the pseudocode presented in the paper; in particular, I elected to use a more stable method for computing the angle between two vectors due to Velvel Kahan. To use this for coloring a polygonal region, we will also use `RegionPlot[]` along with the undocumented [`InPolygonQ`[]](https://mathematica.stackexchange.com/a/9417) for testing if a point lies entirely within a polygon. ``` (* for older versions; use Graphics`PolygonUtils` instead in new Mathematica *) Graphics`Mesh`MeshInit[]; ``` I'll use my own examples first, and come to the example in the OP later. Here is a simplified outline of the United States, and a list of colors corresponding to the vertices: ``` usa = {{-2.151, 0.858}, {-1.562, 0.862}, {-1.414, 0.769}, {-1.243, 0.774}, {-1.083, 0.846}, {-1.052, 0.787}, {-1.378, 0.653}, {-1.433, 0.547}, {-1.42, 0.461}, {-1.605, 0.521}, {-1.715, 0.461}, {-1.881, 0.563}, {-2.04, 0.578}, {-2.138, 0.629}, {-2.2, 0.738}}; cols = ColorData["ThermometerColors"] /@ Range[0, 1, 1/14]; ``` Let's compare the mean value approach (left) and the built-in `VertexColors`: ``` GraphicsRow[{RegionPlot[InPolygonQ[usa, {x, y}], {x, -2.2, -1.1}, {y, 0.46, 0.87}, AspectRatio -> Automatic, BoundaryStyle -> None, ColorFunction -> (RGBColor @@ Clip[ MeanValueInterpolation[usa, List @@@ cols, {#1, #2}], {0, 1}] &), ColorFunctionScaling -> False], Graphics[Polygon[usa, VertexColors -> cols], Frame -> True]}] ``` ![colored USA outline; mean value vs. default](https://i.stack.imgur.com/fghaR.png) As a second example, here is a [bean-shaped polygon](http://nvlpubs.nist.gov/nistpubs/jres/58/jresv58n3p155_A1b.pdf) and a set of associated colors: ``` bean = {{0., 0.11}, {-0.05, 0.108}, {-0.1, 0.115}, {-0.16, 0.15}, {-0.22, 0.205}, {-0.32, 0.3}, {-0.4, 0.358}, {-0.5, 0.42}, {-0.55, 0.436}, {-0.6, 0.43}, {-0.644, 0.4}, {-0.66, 0.35}, {-0.655, 0.3}, {-0.635, 0.2}, {-0.595, 0.1}, {-0.552, 0.}, {-0.5, -0.105}, {-0.44, -0.2}, {-0.4, -0.25}, {-0.35, -0.3}, {-0.3, -0.344}, {-0.204, -0.4}, {-0.1, -0.436}, {0., -0.448}, {0.1, -0.442}, {0.23, -0.4}, {0.3, -0.35}, {0.353, -0.3}, {0.43, -0.2}, {0.477, -0.1}, {0.51, 0.}, {0.522, 0.1}, {0.52, 0.16}, {0.5, 0.24}, {0.456, 0.3}, {0.4, 0.33}, {0.36, 0.337}, {0.3, 0.32}, {0.25, 0.29}, {0.2, 0.245}, {0.15, 0.2}, {0.1, 0.16}, {0.05, 0.128}}; cols = {{0.834, 1., 0.}, {0.497, 1., 0.}, {0.172, 1., 0.}, {0., 1., 0.035}, {0., 1., 0.107}, {0., 1., 0.161}, {0., 1., 0.206}, {0., 1., 0.255}, {0., 1., 0.288}, {0., 1., 0.339}, {0., 1., 0.406}, {0., 1., 0.473}, {0., 1., 0.528}, {0., 1., 0.648}, {0., 1., 0.783}, {0., 1., 0.951}, {0., 0.834, 1.}, {0., 0.6, 1.}, {0., 0.457, 1.}, {0., 0.294, 1.}, {0., 0.137, 1.}, {0.126, 0., 1.}, {0.383, 0., 1.}, {0.612, 0., 1.}, {0.83, 0., 1.}, {1., 0., 0.887}, {1., 0., 0.714}, {1., 0., 0.571}, {1., 0., 0.332}, {1., 0., 0.133}, {1., 0.044, 0.}, {1., 0.207, 0.}, {1., 0.301, 0.}, {1., 0.43, 0.}, {1., 0.547, 0.}, {1., 0.64, 0.}, {1., 0.692, 0.}, {1., 0.745, 0.}, {1., 0.775, 0.}, {1., 0.789, 0.}, {1., 0.809, 0.}, {1., 0.853, 0.}, {1., 0.952, 0.}}; ``` Now, color the bean in two different ways: ``` GraphicsRow[{RegionPlot[InPolygonQ[bean, {x, y}], {x, -0.7, 0.6}, {y, -0.5, 0.5}, AspectRatio -> Automatic, BoundaryStyle -> None, ColorFunction -> (RGBColor @@ Clip[ MeanValueInterpolation[bean, cols, {#1, #2}], {0, 1}] &), ColorFunctionScaling -> False], Graphics[Polygon[bean, VertexColors -> (RGBColor @@@ cols)], Frame -> True]}] ``` ![behold the coloring of a bean](https://i.stack.imgur.com/c7H4q.png) Finally, here is the OP's example: ``` aim = {Cos[2 π #], Sin[2 π #]} &; angles[n_] := Range[0, 0.5, 0.5/(n - 1)]; sector[a_, n_] := Join[aim /@ angles[n], a aim@# & /@ Reverse[angles[n]]]; colors[n_] := Join[ConstantArray[Purple, n], ConstantArray[Orange, n]]; GraphicsRow[{RegionPlot[InPolygonQ[sector[0.414, 5], {x, y}], {x, -1, 1}, {y, 0, 1}, AspectRatio -> Automatic, BoundaryStyle -> None, ColorFunction -> (RGBColor @@ Clip[ MeanValueInterpolation[sector[0.414, 5], List @@@ colors[5], {#1, #2}], {0, 1}] &), ColorFunctionScaling -> False], RegionPlot[InPolygonQ[sector[0.4, 30], {x, y}], {x, -1, 1}, {y, 0, 1}, AspectRatio -> Automatic, BoundaryStyle -> None, ColorFunction -> (RGBColor @@ Clip[ MeanValueInterpolation[sector[0.4, 30], List @@@ colors[30], {#1, #2}], {0, 1}] &), ColorFunctionScaling -> False]}] ``` ![colored sectors](https://i.stack.imgur.com/oPQXs.png) In all cases, the mean value coloring did a much better job than the built-in `VertexColors`. Of course, you no longer have a simple polygon, since `RegionPlot[]` has broken your polygon up into tiny triangles, but if the coloring is needed, this might be a small price to pay.
Here's a triangulation approach that might work easily and more generally. Let's start with one of your problematic examples: ``` drawing = draw[5, 0.414] ``` ![bad example](https://i.stack.imgur.com/PegE1.png) Now, let's triangulate, after getting rid of `10^-17` type expressions. ``` Graphics`Mesh`MeshInit[]; pts = Chop[drawing[[1, 1, 1]]]; tri = PolygonTriangulate[pts] (* Out: {{6, 4, 5}, {4, 2, 3}, {1, 9, 10}, {8, 2, 4}, {9, 2, 8}, {2, 9, 1}, {4, 7, 8}, {4, 6, 7}} *) ``` Finally, we'll assemble it into a `GraphicsComplex`. ``` colors = VertexColors /. drawing[[1, 1, 2]]; newcolors = colors[[#]] & /@ tri; Graphics[GraphicsComplex[pts, Polygon[tri, VertexColors -> newcolors]]] ``` ![after triangulation](https://i.stack.imgur.com/JHuND.png) We can see the triangulation using `EdgeForm`, which might be useful to understand the colorization. ``` Graphics[GraphicsComplex[pts, {EdgeForm[Black], Polygon[tri, VertexColors -> newcolors]}]] ``` ![with edges indicated](https://i.stack.imgur.com/Z2TBv.png) which explains why it doesn't work so well here with `draw[100, 0.414]`: ![another bad example](https://i.stack.imgur.com/aFqq3.png) On the other hand we could use the following triangulation of your `draw[100, 0.414]` polygon (obtained from the `triangle` program as described in [this answer](https://mathematica.stackexchange.com/questions/3646/how-to-make-a-3d-globe/3695#3695)): ![fine triangulation](https://i.stack.imgur.com/oNfKa.png) We could then color the newly introduced vertices using linear interpolation between orange and purple. The result is: ![nicely colored](https://i.stack.imgur.com/SYccO.png) which is not too bad! I'd be glad to share more specific code, if you get the `triangle` command working, as described in the globe answer.
308,658
Please advise and share your solution. **In 2008 R2** ``` DECLARE @ErrMsg varchar (25) SET @ErrMsg = 'Test Raiserror in 2008 R2' RAISERROR 50002 @ErrMsg ``` The above statement produces the following output. > > Msg 50002, Level 16, State 1, Line 4 Test Raiserror in 2008 R2 Completion time: 2022-03-12T20:12:20.1296499+03:00 > > > **In 2017** ``` DECLARE @ErrMsg varchar (25) SET @ErrMsg = 'Test Raiserror in 2017' RAISERROR 50002 @ErrMsg ``` The above statement produces the following output. > > Msg 102, Level 15, State 1, Line 4 Incorrect syntax near '50002'. Completion time: 2022-03-12T20:13:24.4256066+03:00 > > >
2022/03/12
[ "https://dba.stackexchange.com/questions/308658", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/249408/" ]
``` RAISERROR 50002 @ErrMsg ``` This form of `RAISERROR` syntax was deprecated many versions ago and removed from the product entirely in the SQL Server 2012 release. From the [Discontinued Database Engine Functionality in SQL Server 2012 page](https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2012/ms144262(v=sql.110)): > > Discontinued feature: RAISERROR in the format RAISERROR integer > 'string' is discontinued. > > > Replacement: Rewrite the statement using the current RAISERROR(…) > syntax. > > > As an alternative to the [current RAISERROR syntax](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/raiserror-transact-sql?view=sql-server-ver15), you could instead use [THROW](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/throw-transact-sql?view=sql-server-ver15) as below. This allows use of the same same user-defined error number without having to add message to sys.messages (which `RAISERROR` requires). Be sure to terminate the preceding statement with a semi-colon. ``` THROW 50002, @ErrMsg, 1; ```
You're missing a comma between the parameters of your `RAISERROR` call in `RAISERROR 50002 @ErrMsg`. It should actually be `RAISERROR 50002, @ErrMsg` to be syntactically correct. Per the docs on [`RAISERROR`](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/raiserror-transact-sql?view=sql-server-ver15): ``` RAISERROR msg_id, msg_str ``` Also please note that `RAISERROR` is a little bit deprecated in itself, as the docs caution: > > The RAISERROR statement does not honor SET XACT\_ABORT. New applications should use THROW instead of RAISERROR. > > > As recommended you should generally use the [`THROW`](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/throw-transact-sql?view=sql-server-ver15) keyword instead, e.g: ``` DECLARE @ErrMsg varchar (25) SET @ErrMsg = 'Test Raiserror in 2008 R2' ;THROW 50002, @ErrMsg, 0; ``` *Note the required preceding semicolon before the `THROW` keyword. Though you should generally terminate all statements with a semicolon anyway.*
14,246,524
I have a star rating system as defined like this: ``` <span class="rating_container"> <span class="star_container"> <a rel="nofollow" href="" class="star star_1" >1<span class="rating">Terrible</span></a> <a rel="nofollow" href="" class="star star_2" >2<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_3" >3<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_4" >4<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_5" >5<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_6" >6<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_7" >7<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_8" >8<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_9" >9<span class="rating">Excellent</span></a> <a rel="nofollow" href="" class="star star_10" >10<span class="rating">Excellent</span></a> </span> </span> ``` Each individual star is colored when a mouseover happens. How can I simulate this with jquery? For instance I'd like to mouseover star 5. This is what I've tried: ``` $('.star.star_5').addClass('active'); ``` What am I missing?
2013/01/09
[ "https://Stackoverflow.com/questions/14246524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849065/" ]
Try : ``` $(".star_5").trigger('mouseover'); ``` This will trigger the mouseover action whatever it happens to be, rather than emulating it, offering a measure of future-proofing against changes to the mouseover handler.
I think what you need is ``` $('.star.star_5').addClass('active'); ``` **Note** the no-space between `.star` and `.star_5` and the `_` in `star_5`. (Thanks [@wirey](https://stackoverflow.com/questions/14246524/how-can-i-simulate-a-mouseover-event-with-jquery/14246552#comment19768194_14246552))
14,246,524
I have a star rating system as defined like this: ``` <span class="rating_container"> <span class="star_container"> <a rel="nofollow" href="" class="star star_1" >1<span class="rating">Terrible</span></a> <a rel="nofollow" href="" class="star star_2" >2<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_3" >3<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_4" >4<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_5" >5<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_6" >6<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_7" >7<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_8" >8<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_9" >9<span class="rating">Excellent</span></a> <a rel="nofollow" href="" class="star star_10" >10<span class="rating">Excellent</span></a> </span> </span> ``` Each individual star is colored when a mouseover happens. How can I simulate this with jquery? For instance I'd like to mouseover star 5. This is what I've tried: ``` $('.star.star_5').addClass('active'); ``` What am I missing?
2013/01/09
[ "https://Stackoverflow.com/questions/14246524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849065/" ]
I think what you need is ``` $('.star.star_5').addClass('active'); ``` **Note** the no-space between `.star` and `.star_5` and the `_` in `star_5`. (Thanks [@wirey](https://stackoverflow.com/questions/14246524/how-can-i-simulate-a-mouseover-event-with-jquery/14246552#comment19768194_14246552))
In CSS (which is what jQuery selectors are based on), `.class1 .class2` means "an element with class2 that has an ancestor with class1". This is not what you want. You want `.class1.class2` which means "an element with both class1 and class2": ``` $('.star.star_5').addClass('active'); ```
14,246,524
I have a star rating system as defined like this: ``` <span class="rating_container"> <span class="star_container"> <a rel="nofollow" href="" class="star star_1" >1<span class="rating">Terrible</span></a> <a rel="nofollow" href="" class="star star_2" >2<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_3" >3<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_4" >4<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_5" >5<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_6" >6<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_7" >7<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_8" >8<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_9" >9<span class="rating">Excellent</span></a> <a rel="nofollow" href="" class="star star_10" >10<span class="rating">Excellent</span></a> </span> </span> ``` Each individual star is colored when a mouseover happens. How can I simulate this with jquery? For instance I'd like to mouseover star 5. This is what I've tried: ``` $('.star.star_5').addClass('active'); ``` What am I missing?
2013/01/09
[ "https://Stackoverflow.com/questions/14246524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849065/" ]
I think what you need is ``` $('.star.star_5').addClass('active'); ``` **Note** the no-space between `.star` and `.star_5` and the `_` in `star_5`. (Thanks [@wirey](https://stackoverflow.com/questions/14246524/how-can-i-simulate-a-mouseover-event-with-jquery/14246552#comment19768194_14246552))
In case you really want to simulate an event: You can trigger JavaScript events using parameterless forms of the corresponding jQuery functions. For example: ``` $('.star.star_5').mouseover(); ```
14,246,524
I have a star rating system as defined like this: ``` <span class="rating_container"> <span class="star_container"> <a rel="nofollow" href="" class="star star_1" >1<span class="rating">Terrible</span></a> <a rel="nofollow" href="" class="star star_2" >2<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_3" >3<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_4" >4<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_5" >5<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_6" >6<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_7" >7<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_8" >8<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_9" >9<span class="rating">Excellent</span></a> <a rel="nofollow" href="" class="star star_10" >10<span class="rating">Excellent</span></a> </span> </span> ``` Each individual star is colored when a mouseover happens. How can I simulate this with jquery? For instance I'd like to mouseover star 5. This is what I've tried: ``` $('.star.star_5').addClass('active'); ``` What am I missing?
2013/01/09
[ "https://Stackoverflow.com/questions/14246524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849065/" ]
Try : ``` $(".star_5").trigger('mouseover'); ``` This will trigger the mouseover action whatever it happens to be, rather than emulating it, offering a measure of future-proofing against changes to the mouseover handler.
In CSS (which is what jQuery selectors are based on), `.class1 .class2` means "an element with class2 that has an ancestor with class1". This is not what you want. You want `.class1.class2` which means "an element with both class1 and class2": ``` $('.star.star_5').addClass('active'); ```
14,246,524
I have a star rating system as defined like this: ``` <span class="rating_container"> <span class="star_container"> <a rel="nofollow" href="" class="star star_1" >1<span class="rating">Terrible</span></a> <a rel="nofollow" href="" class="star star_2" >2<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_3" >3<span class="rating">Bad</span></a> <a rel="nofollow" href="" class="star star_4" >4<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_5" >5<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_6" >6<span class="rating">OK</span></a> <a rel="nofollow" href="" class="star star_7" >7<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_8" >8<span class="rating">Good</span></a> <a rel="nofollow" href="" class="star star_9" >9<span class="rating">Excellent</span></a> <a rel="nofollow" href="" class="star star_10" >10<span class="rating">Excellent</span></a> </span> </span> ``` Each individual star is colored when a mouseover happens. How can I simulate this with jquery? For instance I'd like to mouseover star 5. This is what I've tried: ``` $('.star.star_5').addClass('active'); ``` What am I missing?
2013/01/09
[ "https://Stackoverflow.com/questions/14246524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/849065/" ]
Try : ``` $(".star_5").trigger('mouseover'); ``` This will trigger the mouseover action whatever it happens to be, rather than emulating it, offering a measure of future-proofing against changes to the mouseover handler.
In case you really want to simulate an event: You can trigger JavaScript events using parameterless forms of the corresponding jQuery functions. For example: ``` $('.star.star_5').mouseover(); ```
35,580
Is there any difference in meaning and usage between the two expressions below? * (me) voy de compras. * (me) voy a hacer compras. According to <https://forum.wordreference.com/threads/ir-de-compras-hacer-la-compra.140571/> , "ir de compras" implies that you're going from shop to shop, looking for what you want. Also, if I understood right, it is usually used for items like clothes/perfumes and not food/cleaning products. Notice that the second expression is "**hacer compras**", not "hacer la compra", which seemingly implies that you are buying food, cleaning products or other non-durable consumer goods.
2020/08/28
[ "https://spanish.stackexchange.com/questions/35580", "https://spanish.stackexchange.com", "https://spanish.stackexchange.com/users/22797/" ]
The meaning is the same as far as I can tell, but in actual usage I've only ever encountered “(me) voy de compras”. This is my personal experience, though. There's a difference between “voy de compras” and “voy a hacer compras” (with no reflexive pronoun) because the latter could conceivably be interpreted as “I'm going to shop for things; I will make purchases”, that is, with the verb “ir” being used as part of the periphrastic future. With “voy de compras” there's no such ambiguity: it's present tense and it always means “I'm leaving home to go shopping now”. Indeed, if you wanted to make it future, you would have to say “Voy a ir de compras”. “Voy hacer la compra” is what you would say when you've spoken about some purchase and now declare that you're indeed going to buy whatever it is you said you were to buy. Another possibility: my wife and I normally go once a month to a big supermarket and fill two shopping carts of stuff; to us this is “la compra del mes”. So “vamos a hacer la compra del mes” is a thing for us, and the expression is also readily understandable to others.
"Ir de compras" is the same that "Ir a hacer compras". The difference may be is that you say "voy de compras" when you are "shopping", you don't know what you want, you are mostly visiting shops, you are expending your time in shops. If you say "voy a hacer las compras de la semana" it means you know what you want buy, and you must use the article "las". Also you can use the article "unas", and it means that you need buy something, but you don't want to be specific. "Hacer la compra" is most used when you use visit the same place, each day, and buy the same stuff (bread, milk, etc), but it's colloquial, not many persons say that. First situation, "ir de compras" * W1: "Estoy de compras" (I'm in a mall visiting shops). * W2: "¿Has visto algo?" (Have you seen something interesting?). Second situation, "ir a hacer compras" "hacer compras" "ir a comprar" * M1: "Estoy haciendo las compras" (I'm in the supermarket buying our food). * W1: "No olvides los huevos" (Don't forget buy eggs).
7,701,193
I’ve been working on a cloud based (AWS EC2 ) PHP Web Application, and I’m struggling with one issue when it comes to working with multiple servers (all under an AWS Elastic Load Balancer). On one server, when I upload the latest files, they’re instantly in production across the entire application. But this isn’t true when using multiple servers – you have to upload files to each of them, every time you commit a change. This could work alright if you don’t update anything very often, or if you just have one or two servers. But what if you update the system multiple times in one week, across ten servers? What I’m looking for is a way to ‘commit’ changes from our dev or testing server and have it ‘pushed’ out to all of our production servers immediately. Ideally the update would be applied to only one server at a time (even though it just takes a second or two per server) so the ELB will not send traffic to it while files are changing so as not to disrupt any production traffic that may be flowing to the ELB . What is the best way of doing this? One of my thoughts would be to use SVN on the dev server, but that doesn’t really ‘push’ to the servers. I’m looking for a process that takes just a few seconds to commit an update and subsequently begin applying it to servers. Also, for those of you familiar with AWS , what’s the best way to update an AMI with the latest updates so the auto-scaler always launches new instances with the latest version of the software? There have to be good ways of doing this….can’t really picture sites like Facebook, Google, Apple, Amazon, Twitter, etc. going through and updating hundreds or thousands of servers manually and one by one when they make a change. Thanks in advance for your help. I’m hoping we can find some solution to this problem….what has to be at least 100 Google searches by both myself and my business partner over the last day have proven unsuccessful for the most part in solving this problem. Alex
2011/10/09
[ "https://Stackoverflow.com/questions/7701193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969352/" ]
We use scalr.net to manage our web servers and load balancer instances. It worked pretty well until now. we have a server farm for each of our environments (2 production farms, staging, sandbox). We have a pre configured roles for a web servers so it's super easy to open new instances and scale when needed. the web server pull code from github when it boots up. We haven't completed all the deployment changes we want to do, but basically here's how we deploy new versions into our production environment: 1. we use phing to update the source code and deployment on each web service. we created a task that execute a git pull and run database changes (dbdeploy phing task). <http://www.phing.info/trac/> 2. we wrote a shell script that executes phing and we added it to scalr as a script. Scalr has a nice interface to manage scripts. ``` #!/bin/sh cd /var/www phing -f /var/www/build.xml -Denvironment=production deploy ``` 3. scalr has an option to execute scripts on all the instances in a specific farm, so each release we just push to the master branch in github and execute the scalr script. We want to create a github hook that deploys automatically when we push to the master branch. Scalr has api that can execute scripts, so it's possible.
Have a good look at [KwateeSDCM](http://sdcm.kwatee.net). It enables you to deploy files and software on any number of servers and, if needed, to customize server-specific parameters along the way. There's a post about [deploying a web application](http://blog.kwatee.net/2011/05/deploy-web-application-on-multiple.html) on multiple tomcat instances but it's language agnostic and will work for PHP just as well as long as you have ssh enabled on your AWS servers.
13,075,090
I have three tables, **A**, **B**, and **C**. They all hold different data, but have some columns in common. If **A**, **B**, and **C** all have columns **C1** and **C2** then how can I look up a specific **C2** value using a **C1** value that could be in any of the 3 tables? Basically, I want to do a simple look-up but have it act on the union of the 3 tables - and I'd prefer to not use a view to achieve this. Note that this is an **Ingres Vectorwise** database.
2012/10/25
[ "https://Stackoverflow.com/questions/13075090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/857994/" ]
You do this by doing a union of the tables in the `from` clause: ``` select c2 from ((select c1, c2 from a) union all (select c1, c2 from b) union all (select c1, c2 from c) ) t where c1 = <your value> ``` I've used `union all` for performance reasons. If you are concerned about duplicate values, either use `union` or add a `distinct` in the `select`. This is standard SQL and should work in any database.
I don't know what you mean by " a specific C2 value using a C1 value ", but, whatever your query would be for the view, repeat that query and union the results, ``` SELECT * FROM A WHERE C2 = ? UNION ALL SELECT * FROM B WHERE C2 = ? UNION ALL SELECT * FROM C WHERE C2 = ? ``` (The view is a standard SQL feature, and will make any query you write easier.)
14,718,205
I am currently working on a small Java game in eclipse, and am knee deep in a few thousand lines of code. Right now, I am specifically attempting to use a String's contents to paint an image, and am wondering if it is possible. If it is it would save me at least a few hundred lines of individual variables for each image. Pasting the whole program would more than likely prove counter productive due to the length, so I will merely demonstrate what I am attemtping. What I am attempting to do: ``` ImageIcon ladder = new ImageIcon (getClass ().getResource ("ladder.png")); floorContents [currentX] [currentY] = "ladder"; public void paint (Graphics g) { if (floorContents [currentX] [currentY] != "none") // painting item where standing { floorContents[currentX][currentY].paintIcon (this, g, 0, 0); } } ``` Essentially I am attempting to get the program to see this line: ``` floorContents[currentX][currentY].paintIcon (this, g, 0, 0); ``` as this: ``` ladder.paintIcon (this, g, 0, 0); ``` If at all possible. This would save me from having to write in each image item seperately.
2013/02/05
[ "https://Stackoverflow.com/questions/14718205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2044333/" ]
Put each image in a [`Map`](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html) keyed by the string ``` imageMap.put("ladder", new ImageIcon (getClass ().getResource ("ladder.png"))); //... imageMap.get(floorContents [currentX] [currentY]).paintIcon (this, g, 0, 0); ``` Of course, you should key to see if the map contains the key first, or if the value returned is null... ``` if (imageMap.containsKey(floorContents [currentX] [currentY]) { //.... } ``` of ``` ImageIcon image = imageMap.get(floorContents [currentX] [currentY]); if (image != null) { //... } ``` But that's up to you
``` if (floorContents [currentX] [currentY] != "none") ``` Should be more like: ``` if (!floorContents [currentX] [currentY].equals("none")) ``` See [String comparison in Java](https://stackoverflow.com/questions/5286310/string-comparison-in-java) (and [about 500 more](https://stackoverflow.com/search?q=[string]+[java]+comparison)) for details.
14,718,205
I am currently working on a small Java game in eclipse, and am knee deep in a few thousand lines of code. Right now, I am specifically attempting to use a String's contents to paint an image, and am wondering if it is possible. If it is it would save me at least a few hundred lines of individual variables for each image. Pasting the whole program would more than likely prove counter productive due to the length, so I will merely demonstrate what I am attemtping. What I am attempting to do: ``` ImageIcon ladder = new ImageIcon (getClass ().getResource ("ladder.png")); floorContents [currentX] [currentY] = "ladder"; public void paint (Graphics g) { if (floorContents [currentX] [currentY] != "none") // painting item where standing { floorContents[currentX][currentY].paintIcon (this, g, 0, 0); } } ``` Essentially I am attempting to get the program to see this line: ``` floorContents[currentX][currentY].paintIcon (this, g, 0, 0); ``` as this: ``` ladder.paintIcon (this, g, 0, 0); ``` If at all possible. This would save me from having to write in each image item seperately.
2013/02/05
[ "https://Stackoverflow.com/questions/14718205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2044333/" ]
Put each image in a [`Map`](http://docs.oracle.com/javase/7/docs/api/java/util/Map.html) keyed by the string ``` imageMap.put("ladder", new ImageIcon (getClass ().getResource ("ladder.png"))); //... imageMap.get(floorContents [currentX] [currentY]).paintIcon (this, g, 0, 0); ``` Of course, you should key to see if the map contains the key first, or if the value returned is null... ``` if (imageMap.containsKey(floorContents [currentX] [currentY]) { //.... } ``` of ``` ImageIcon image = imageMap.get(floorContents [currentX] [currentY]); if (image != null) { //... } ``` But that's up to you
I would kill use of strings altogether. "none" is code-smell for `null` if I ever saw it. Why even match on a `String` at all. ``` ImageIcon[][] floorContents; ImageIcon ladder = new ImageIcon (getClass ().getResource ("ladder.png")); floorContents[currentX][currentY] = ladder; public void paint (Graphics g) { if (floorContents [currentX] [currentY] != null) { floorContents[currentX][currentY].paintIcon (this, g, 0, 0); } } ```
11,797,409
> > **Possible Duplicate:** > > [C++ - Check if pointer is pointing to valid memory (Can't use NULL checks here)](https://stackoverflow.com/questions/11787650/c-check-if-pointer-is-pointing-to-valid-memory-cant-use-null-checks-here) > > > How to check if pointer is valid without a wrapper or additional memory attached to him? By valid I mean that I didn't deleted it or I can reach it or It allocated. I am using VS\Windows.
2012/08/03
[ "https://Stackoverflow.com/questions/11797409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1565515/" ]
A pointer is valid if "you didn't deleted that or this memory is allocated or at al you can access that memory". So I suggest: 1. Keep track of memory you have allocated. If this pointer is not in any of those blocks, you didn't allocate it. 2. When you delete a pointer or free memory, remove it from the list. That way, you can also check that you didn't delete it. 3. Try to access it. If you can't access it, it's not valid. 4. If it passes these tests, it's valid. I am not joking. The right way to do this is to precisely define what you mean by "valid" and precisely test whether the pointer meets those conditions. But really, this is just not how C++ is done. Whatever your underlying issue is, there's probably a better way to do it.
This valid check checked in windows only (VS),here is the function: ``` #pragma once //ptrvalid.h __inline bool isValid(void* ptr) { if (((uint)ptr)&7==7) return false; char _prefix; __try { _prefix=*(((char*)ptr)-1); } __except (true) { return false; } switch (_prefix) { case 0: //Running release mode with debugger case -128: //Running release mode without debugger case -2: //Running debug mode with debugger case -35: //Running debug mode without debugger return false; break; } return true; } ``` Usage: ``` #include <stdio.h> #include "ptrvalid.h" void PrintValid(void* ptr) { if (isValid(ptr)) printf("%d is valid.\n",ptr); else printf("%d is not valid.\n",ptr); } int main() { int* my_array=(int*)malloc(4); PrintValid(my_array); PrintValid((void*)99); free(my_array); PrintValid(my_array); my_array=new int[4]; PrintValid(my_array); delete my_array; PrintValid(my_array); getchar(); } ``` Output: ``` 764776 is valid. 99 is not valid. 764776 is not valid. 774648 is valid. 774648 is not valid. ``` Function's explanation: (What it does) The functions check before the real checking ,if the address is valid\start point to memory. After that he checks if this process can reach this memory's prefix (If caught exception if can't) and the last checking is checking what the prefix of this memory if deleted at any mode. (Debugging\Without Debug Mode\Release Mode) If the function passed all of those checks ,it returns true.
22,516,410
I need to parse the string and I am having trouble identifying the order number. Here few examples with expected answer. I need Oracle SQL expression to ruturn the value ``` SOURCE_COLUMN PARAMETER RETURN_VALUE AAA_BBB_CCC_DDD AAA 1 AAA_BBB_CCCC_DDD BBB 2 AAA_BBB_CC_DDD CC 3 AAA_BBBB_CCC_DDD DDD 4 AAA_BBB_CCC_DDD EEE 0 ``` Here is SQL to generate first two columns ``` select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'AAA' PARAM FROM DUAL UNION ALL select 'AAA_BBB_CCCC_DDD' SOURCE_COLUMN, 'BBB' PARAM FROM DUAL UNION ALL select 'AAA_BBB_CC_DDD' SOURCE_COLUMN, 'CC' PARAM FROM DUAL UNION ALL select 'AAA_BBBB_CCC_DDD' SOURCE_COLUMN, 'DDD' PARAM FROM DUAL UNION ALL select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'EEE' PARAM FROM DUAL ```
2014/03/19
[ "https://Stackoverflow.com/questions/22516410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3319643/" ]
This query does what you want: ``` select (case when source_column like '%'||param||'%' then 1 + coalesce(length(substr(source_column, 1, instr(source_column, param) - 1)) - length(replace(substr(source_column, 1, instr(source_column, param) - 1), '_', '')), 0) else 0 end) as pos from t; ``` The idea is much simpler than the query looks. It finds the matching parameter and then takes the initial substring up to that point. You can count the number of `'_'` by using a trick: take the length of the string and then subtract the length of the string when you replace the `'_'` with `''`. The value you want is actually one more than this value. And, if the pattern is not found, then return `0`.
For your particular example (stable string patterns): ``` SQL> with t as ( 2 select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'AAA' PARAM FROM DUAL UNION ALL 3 select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'BBB' PARAM FROM DUAL UNION ALL 4 select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'CCC' PARAM FROM DUAL UNION ALL 5 select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'DDD' PARAM FROM DUAL UNION ALL 6 select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'EEE' PARAM FROM DUAL 7 ) 8 select SOURCE_COLUMN, PARAM, floor((instr(SOURCE_COLUMN,param)+3)/4) p from t; SOURCE_COLUMN PAR P --------------- --- ---------- AAA_BBB_CCC_DDD AAA 1 AAA_BBB_CCC_DDD BBB 2 AAA_BBB_CCC_DDD CCC 3 AAA_BBB_CCC_DDD DDD 4 AAA_BBB_CCC_DDD EEE 0 ```
22,516,410
I need to parse the string and I am having trouble identifying the order number. Here few examples with expected answer. I need Oracle SQL expression to ruturn the value ``` SOURCE_COLUMN PARAMETER RETURN_VALUE AAA_BBB_CCC_DDD AAA 1 AAA_BBB_CCCC_DDD BBB 2 AAA_BBB_CC_DDD CC 3 AAA_BBBB_CCC_DDD DDD 4 AAA_BBB_CCC_DDD EEE 0 ``` Here is SQL to generate first two columns ``` select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'AAA' PARAM FROM DUAL UNION ALL select 'AAA_BBB_CCCC_DDD' SOURCE_COLUMN, 'BBB' PARAM FROM DUAL UNION ALL select 'AAA_BBB_CC_DDD' SOURCE_COLUMN, 'CC' PARAM FROM DUAL UNION ALL select 'AAA_BBBB_CCC_DDD' SOURCE_COLUMN, 'DDD' PARAM FROM DUAL UNION ALL select 'AAA_BBB_CCC_DDD' SOURCE_COLUMN, 'EEE' PARAM FROM DUAL ```
2014/03/19
[ "https://Stackoverflow.com/questions/22516410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3319643/" ]
This query does what you want: ``` select (case when source_column like '%'||param||'%' then 1 + coalesce(length(substr(source_column, 1, instr(source_column, param) - 1)) - length(replace(substr(source_column, 1, instr(source_column, param) - 1), '_', '')), 0) else 0 end) as pos from t; ``` The idea is much simpler than the query looks. It finds the matching parameter and then takes the initial substring up to that point. You can count the number of `'_'` by using a trick: take the length of the string and then subtract the length of the string when you replace the `'_'` with `''`. The value you want is actually one more than this value. And, if the pattern is not found, then return `0`.
You can use `ROW_NUMBER()` in the following manner ``` SELECT source_column ,PARAM ,CASE WHEN ind IS NULL THEN 0 ELSE Row_number() over ( PARTITION BY source_column ORDER BY ind) END AS Return_Value FROM (SELECT source_column ,Param ,CASE WHEN Instr(source_column, param) = 0 THEN NULL ELSE Instr(source_column, param) END AS Ind FROM (select 'AAA_BBB_CC_DDD' SOURCE_COLUMN, 'AAA' Param FROM DUAL UNION ALL select 'AAA_BBB_CC_DDD' SOURCE_COLUMN, 'BBB' Param FROM DUAL UNION ALL select 'AAA_BBB_CC_DDD' SOURCE_COLUMN, 'CC' Param FROM DUAL UNION ALL select 'AAA_BBB_CC_DDD' SOURCE_COLUMN, 'DDD' Param FROM DUAL UNION ALL select 'AAA_BBB_CC_DDD' SOURCE_COLUMN, 'EEE' Param FROM DUAL ) ) ``` here SQL Fiddle to show results <http://sqlfiddle.com/#!4/d41d8/26754>
12,945
I've got an easy question concerning residual analysis. So when I compute a QQ-Plot with standardized residuals $\widehat{d}$ on the y-axis and I observe normal distributed standardized residuals, why can I assume that the error term $u$ is normal distributed? I'd think that if $\widehat{d}$ looks normal distributed I just could assume that the standardized error term $d$ should be normal distributed. So why can we assume that $u\sim N$ when we just observe that $\widehat{d}\approx N$. By the way can we assume it?
2011/07/12
[ "https://stats.stackexchange.com/questions/12945", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/4496/" ]
The $u$s are unobserved and the $\hat{d}$s are just estimates of them.
In a linear model $ y = X\beta + u $ with $u \sim N(0, \sigma^2I)$, the vector of raw residuals is $ \hat u = y - \hat y = (I - H)y $ where the hat matrix $H = X(X'X)^{-1}X' $. The response $y$ is normally distributed given the assumed normality of the error terms. Consequently, if the model assumes normality correctly, $\hat u$ is also normally distributed since each residual is a linear combination of $y$. Therefore, if a QQ-plot does not support the normality of $\hat u$, it warrants a question about the normality of $y$, which in turn raises a doubt about the normality assumption of $u$. On the other hand, if there is a lack of evidence to reject the normality of $\hat u$, the logic is to accept the normality of $u$. On the specific question about checking normality of $\hat d = \hat u/\hat \sigma $ and its relationship to the normality of $u$ ... As just mentioned, $\hat u$ is normally distributed under the model, so is $\hat u/c$ for any non-zero constant $c$, such as $\sigma$. If $\sigma$ were known, the scaled residual $\hat u/\sigma$ would be better than $\hat u$ for identifying potential outliers. As $\sigma$ is usually unknown, $\hat d$ = $\hat u/\hat \sigma$ is used instead. However, the approach of checking the normality of $\hat d$ to validate the normality of $u$ is approximate and less preferred given that its divisor $\hat \sigma$ is a statistic, not a constant. Is then using $\hat u$ to assess the normality of $u$ a perfect approach? Not necessarily... Note that $Var(\hat u)$ = $\sigma^2(I - H)$, indicating that raw residuals are correlated and variances are not constant. More specifically, such residuals are not sample points randomly (independently) drawn from a common underlined distribution. Is it then appropriate to subject the residuals to a univariate QQ-plot to assess normality? In brief, any conclusion about normality from a QQ-plot is visual based, thus subjective, regardless of which type of residuals (raw or otherwise) is evaluated. Besides, normality assessment is only one aspect of model adequacy assessment. While raw residuals may be more appropriate with QQ-plot, other types of residuals may be better suited with other diagnostic tools.
12,945
I've got an easy question concerning residual analysis. So when I compute a QQ-Plot with standardized residuals $\widehat{d}$ on the y-axis and I observe normal distributed standardized residuals, why can I assume that the error term $u$ is normal distributed? I'd think that if $\widehat{d}$ looks normal distributed I just could assume that the standardized error term $d$ should be normal distributed. So why can we assume that $u\sim N$ when we just observe that $\widehat{d}\approx N$. By the way can we assume it?
2011/07/12
[ "https://stats.stackexchange.com/questions/12945", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/4496/" ]
This inference is no different from any other inference we make. We assume a default (you could call it a 'null'). In this case, it's that the underlying distribution is Gaussian. We examine the data to see if they are inconsistent with our default hypothesis. If the qq-plot of our residuals looks sufficiently Gaussian for your satisfaction, then we stick with that assumption. In truth, no matter how non-normal our residuals appear, they *could* still have come from an underlying Gaussian distribution, but at some point, we just don't believe it anymore. Another way to phrase this is that we don't assume they're Gaussian *because* the qq-plot looks Gaussian, rather we don't *stop* assuming they're Gaussian because the qq-plot doen't look sufficiently *non-Gaussian*. Some people have trouble with this line of reasoning; which is perfectly fine. You might be interested in checking out the [Bayesian](http://en.wikipedia.org/wiki/Bayesian_statistics) approach to statistics.
In a linear model $ y = X\beta + u $ with $u \sim N(0, \sigma^2I)$, the vector of raw residuals is $ \hat u = y - \hat y = (I - H)y $ where the hat matrix $H = X(X'X)^{-1}X' $. The response $y$ is normally distributed given the assumed normality of the error terms. Consequently, if the model assumes normality correctly, $\hat u$ is also normally distributed since each residual is a linear combination of $y$. Therefore, if a QQ-plot does not support the normality of $\hat u$, it warrants a question about the normality of $y$, which in turn raises a doubt about the normality assumption of $u$. On the other hand, if there is a lack of evidence to reject the normality of $\hat u$, the logic is to accept the normality of $u$. On the specific question about checking normality of $\hat d = \hat u/\hat \sigma $ and its relationship to the normality of $u$ ... As just mentioned, $\hat u$ is normally distributed under the model, so is $\hat u/c$ for any non-zero constant $c$, such as $\sigma$. If $\sigma$ were known, the scaled residual $\hat u/\sigma$ would be better than $\hat u$ for identifying potential outliers. As $\sigma$ is usually unknown, $\hat d$ = $\hat u/\hat \sigma$ is used instead. However, the approach of checking the normality of $\hat d$ to validate the normality of $u$ is approximate and less preferred given that its divisor $\hat \sigma$ is a statistic, not a constant. Is then using $\hat u$ to assess the normality of $u$ a perfect approach? Not necessarily... Note that $Var(\hat u)$ = $\sigma^2(I - H)$, indicating that raw residuals are correlated and variances are not constant. More specifically, such residuals are not sample points randomly (independently) drawn from a common underlined distribution. Is it then appropriate to subject the residuals to a univariate QQ-plot to assess normality? In brief, any conclusion about normality from a QQ-plot is visual based, thus subjective, regardless of which type of residuals (raw or otherwise) is evaluated. Besides, normality assessment is only one aspect of model adequacy assessment. While raw residuals may be more appropriate with QQ-plot, other types of residuals may be better suited with other diagnostic tools.
39,559,204
Suppose I have a function x^2+y^2=1, how can I graph this function in R? I have tried: [enter image description here](http://i.stack.imgur.com/0SAID.png) but it doesn't work and says: [enter image description here](http://i.stack.imgur.com/ApA6P.png)
2016/09/18
[ "https://Stackoverflow.com/questions/39559204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6845690/" ]
To plot a circle: ----------------- ``` plot.new() plot.window(xlim = c(-1, 1), ylim = c(-1, 1)) theta <- seq(0, 2 * pi, length = 200) lines(x = cos(theta), y = sin(theta)) ``` [![enter image description here](https://i.stack.imgur.com/sBSqu.png)](https://i.stack.imgur.com/sBSqu.png) Plot the unit circle with the origin and aspect ratio = 1 --------------------------------------------------------- ``` plot(0, 0, asp = 1, xlim = c(-1, 1), ylim = c(-1, 1)) lines(x = cos(theta), y = sin(theta), col = "red") ``` [![enter image description here](https://i.stack.imgur.com/FQCGA.png)](https://i.stack.imgur.com/FQCGA.png) Plotting a surface ------------------ We'll use a different function for this. ![](https://latex.codecogs.com/gif.latex?f(x,&space;y)&space;=&space;cos(x)&space;+&space;sin(y) "f(x, y) = cos(x) + sin(y)") ``` f <- function(x, y) { cos(x) + sin(y) } xvec <- yvec <- seq(-pi, pi, length = 100) dat <- expand.grid(x = xvec, y = yvec) zmat <- matrix(f(dat$x, dat$y), ncol = 100) # use persp persp(xvec, yvec, zmat) ``` [![enter image description here](https://i.stack.imgur.com/fM7GO.png)](https://i.stack.imgur.com/fM7GO.png) ``` # view from a different angle persp(xvec, yvec, zmat, theta = 45) ``` [![enter image description here](https://i.stack.imgur.com/DLsUQ.png)](https://i.stack.imgur.com/DLsUQ.png) ### Using ggplot2 ``` library(ggplot2) dat$z <- f(dat$x, dat$y) ggplot(dat) + aes(x = x, y = y, fill = z) + geom_tile() + scale_fill_gradient2() ``` [![enter image description here](https://i.stack.imgur.com/OrJg2.png)](https://i.stack.imgur.com/OrJg2.png)
Try this: ``` x <- seq(-1,1,.01) plot(0,0, xlim=c(-1,1), ylim=c(-1,1)) curve(sqrt(1-x^2), add=TRUE) curve(-sqrt(1-x^2), add=TRUE) ```
12,969,622
I found a little javascript snippet for including javascripts only if they was not included before. That is working with my own scripts, but with two third-party libraries it's not working and I really don't know why. ``` var included_files = new Array(); function include_once(script_filename) { if (!in_array(script_filename, included_files)) { included_files[included_files.length] = script_filename; include_dom(script_filename); } } function in_array(needle, haystack) { for (var i = 0; i < haystack.length; i++) { if (haystack[i] == needle) { return true; } } return false; } function include_dom(script_filename) { var html_doc = document.getElementsByTagName('head').item(0); var js = document.createElement('script'); js.setAttribute('language', 'javascript'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', script_filename); html_doc.appendChild(js); return false; } function loaded() { include_once("shared/scripts/jquery.min.js"); include_once("shared/scripts/iscroll.js"); $(document).ready(function () { alert("hello"); }); } ``` error: $ is not defined. If I import jQuery the regular way its working and it says "iScroll" is not defined (because I'm using it later). Any ideas?
2012/10/19
[ "https://Stackoverflow.com/questions/12969622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1598840/" ]
`include_dom` is asynchronous. It loads the scripts in parallel, and you can't really determine when the scripts will be loaded. You try to use jQuery right after you started the download, which doesn't work. You need to use a script that allows you to specify a callback for loaded scripts. I would recommend require.js
You are adding the scripts to the DOM, but not letting them load before you try to use the functions they provide. You need to bind a callback to the load event of the script elements you are adding. (At least in most browsers, you might have to implement some hacks in others; you may wish to examine the source code for jQuery's getScript method).
12,969,622
I found a little javascript snippet for including javascripts only if they was not included before. That is working with my own scripts, but with two third-party libraries it's not working and I really don't know why. ``` var included_files = new Array(); function include_once(script_filename) { if (!in_array(script_filename, included_files)) { included_files[included_files.length] = script_filename; include_dom(script_filename); } } function in_array(needle, haystack) { for (var i = 0; i < haystack.length; i++) { if (haystack[i] == needle) { return true; } } return false; } function include_dom(script_filename) { var html_doc = document.getElementsByTagName('head').item(0); var js = document.createElement('script'); js.setAttribute('language', 'javascript'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', script_filename); html_doc.appendChild(js); return false; } function loaded() { include_once("shared/scripts/jquery.min.js"); include_once("shared/scripts/iscroll.js"); $(document).ready(function () { alert("hello"); }); } ``` error: $ is not defined. If I import jQuery the regular way its working and it says "iScroll" is not defined (because I'm using it later). Any ideas?
2012/10/19
[ "https://Stackoverflow.com/questions/12969622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1598840/" ]
Did someone say callback? ``` function include_once(script_filename, callback) { if (!in_array(script_filename, included_files)) { included_files[included_files.length] = script_filename; include_dom(script_filename, callback); } } function include_dom(script_filename, callback) { var html_doc = document.getElementsByTagName('head').item(0); var js = document.createElement('script'); js.setAttribute('language', 'javascript'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', script_filename); if(callback && callback != 'undefined'){ js.onload = callback; js.onreadystatechange = function() { if (this.readyState == 'complete') callback(); } } html_doc.appendChild(js); return false; } function loaded() { include_once("shared/scripts/jquery.min.js", function(){ $(document).ready(function () { alert("hello"); }); }); include_once("shared/scripts/iscroll.js"); } ```
You are adding the scripts to the DOM, but not letting them load before you try to use the functions they provide. You need to bind a callback to the load event of the script elements you are adding. (At least in most browsers, you might have to implement some hacks in others; you may wish to examine the source code for jQuery's getScript method).
12,969,622
I found a little javascript snippet for including javascripts only if they was not included before. That is working with my own scripts, but with two third-party libraries it's not working and I really don't know why. ``` var included_files = new Array(); function include_once(script_filename) { if (!in_array(script_filename, included_files)) { included_files[included_files.length] = script_filename; include_dom(script_filename); } } function in_array(needle, haystack) { for (var i = 0; i < haystack.length; i++) { if (haystack[i] == needle) { return true; } } return false; } function include_dom(script_filename) { var html_doc = document.getElementsByTagName('head').item(0); var js = document.createElement('script'); js.setAttribute('language', 'javascript'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', script_filename); html_doc.appendChild(js); return false; } function loaded() { include_once("shared/scripts/jquery.min.js"); include_once("shared/scripts/iscroll.js"); $(document).ready(function () { alert("hello"); }); } ``` error: $ is not defined. If I import jQuery the regular way its working and it says "iScroll" is not defined (because I'm using it later). Any ideas?
2012/10/19
[ "https://Stackoverflow.com/questions/12969622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1598840/" ]
`include_dom` is asynchronous. It loads the scripts in parallel, and you can't really determine when the scripts will be loaded. You try to use jQuery right after you started the download, which doesn't work. You need to use a script that allows you to specify a callback for loaded scripts. I would recommend require.js
Use a script loader. [yepnope](http://yepnopejs.com/) will do everything you are trying to do and more
12,969,622
I found a little javascript snippet for including javascripts only if they was not included before. That is working with my own scripts, but with two third-party libraries it's not working and I really don't know why. ``` var included_files = new Array(); function include_once(script_filename) { if (!in_array(script_filename, included_files)) { included_files[included_files.length] = script_filename; include_dom(script_filename); } } function in_array(needle, haystack) { for (var i = 0; i < haystack.length; i++) { if (haystack[i] == needle) { return true; } } return false; } function include_dom(script_filename) { var html_doc = document.getElementsByTagName('head').item(0); var js = document.createElement('script'); js.setAttribute('language', 'javascript'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', script_filename); html_doc.appendChild(js); return false; } function loaded() { include_once("shared/scripts/jquery.min.js"); include_once("shared/scripts/iscroll.js"); $(document).ready(function () { alert("hello"); }); } ``` error: $ is not defined. If I import jQuery the regular way its working and it says "iScroll" is not defined (because I'm using it later). Any ideas?
2012/10/19
[ "https://Stackoverflow.com/questions/12969622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1598840/" ]
Did someone say callback? ``` function include_once(script_filename, callback) { if (!in_array(script_filename, included_files)) { included_files[included_files.length] = script_filename; include_dom(script_filename, callback); } } function include_dom(script_filename, callback) { var html_doc = document.getElementsByTagName('head').item(0); var js = document.createElement('script'); js.setAttribute('language', 'javascript'); js.setAttribute('type', 'text/javascript'); js.setAttribute('src', script_filename); if(callback && callback != 'undefined'){ js.onload = callback; js.onreadystatechange = function() { if (this.readyState == 'complete') callback(); } } html_doc.appendChild(js); return false; } function loaded() { include_once("shared/scripts/jquery.min.js", function(){ $(document).ready(function () { alert("hello"); }); }); include_once("shared/scripts/iscroll.js"); } ```
Use a script loader. [yepnope](http://yepnopejs.com/) will do everything you are trying to do and more
71,609,582
I have a very basic html file (using electron); ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> File Uploader </title> <link rel="stylesheet" href="style.css"> <script defer src="render.js"></script> </head> <body> <h1>Drive File Uploader</h1> <input type="file" id="myFile" name="myFile"> <button onclick="FileUploadPing()">Upload your file</button> </body> </html> ``` and an event listener named render.js; ``` const ipcRenderer = require("electron").ipcRenderer; const FileUploadPing = () => { var input = document.getElementById("myFile").value if (input) { ipcRenderer.send("FileUploadPing",inputVal); }else{console.log("no path value")} }; ipcRenderer.on("FileRecievePing", (event, data) => { alert(data) }); ``` But when I click submit, `document.getElementById("myFile").value` returns `undefined` how can I pull that value?
2022/03/24
[ "https://Stackoverflow.com/questions/71609582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18569258/" ]
You can use a cte that returns the array of strings with a number that corresponds to the order of the string in the results and a `LEFT` join of the table: ``` WITH cte(id, word) AS (VALUES ROW(1, 'data'), ROW(2, 'riga'), ROW(3, 'ciao'), ROW(4, 'parola') ) SELECT COALESCE(p.en, 'not found') en, COALESCE(p.de, 'not found') de FROM cte c LEFT JOIN prova p ON p.it = c.word ORDER BY c.id; ``` Or, with `UNION ALL` for versions of MySql prior to 8.0 without the cte support: ``` SELECT COALESCE(p.en, 'not found') en, COALESCE(p.de, 'not found') de FROM ( SELECT 1 id, 'data' word UNION ALL SELECT 2, 'riga' UNION ALL SELECT 3, 'ciao' UNION ALL SELECT 4, 'parola' ) t LEFT JOIN prova p ON p.it = t.word ORDER BY t.id; ``` See the [demo](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e44db09fd4ca8b9167aa0e394f2f548c).
Use `coalesce` to fill in a null value with a default. ``` select coalesce(en, 'not found'), coalesce(de, 'not found') ... ``` For the second part, how to make all the `in` values show up as rows, see [this answer](https://stackoverflow.com/a/71579841/14660).
72,150,149
I have the following data set: which is daily sum. Based on this, how do i get last 7 days sum, 14 days sum and 21 days for each row in new columns. I have tried to get last 7 days sum by using below query. but Its is giving cumulative sum instead of giving lookback to last 7 days. ``` select date,sum(amount) as amount, sum(sum(amount)) over (order by date desc rows between 6 preceding and current row) as amount_7days_ago from table1 group by date order by date desc; ``` from there on, not able to move forward with the idea. how can i achieve this in query? [![enter image description here](https://i.stack.imgur.com/bql0q.png)](https://i.stack.imgur.com/bql0q.png) Desired Result : [![enter image description here](https://i.stack.imgur.com/imtg0.png)](https://i.stack.imgur.com/imtg0.png)
2022/05/07
[ "https://Stackoverflow.com/questions/72150149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929387/" ]
``` df[''] = df.groupby(['Customer ID', 'Product Code']).cumcount() df = df.pivot(index=['Customer ID', 'Product Code'], columns='') print(df) ``` Output: ``` Days since the last transaction 0 1 2 Customer ID Product Code A 1 10.0 23.0 7.0 2 8.0 9.0 NaN 3 6.0 NaN NaN B 1 18.0 NaN NaN 2 4.0 NaN NaN 3 4.0 12.0 NaN C 2 27.0 15.0 NaN ```
Below python code also worked for me. ``` #keep only the needed data grouped = df.groupby(['Customer_ID','Product Code'], as_index=False).agg({"Days since the last transaction": lambda x: x.tolist()[:3]+[x.iat[-1]]}).explode("Days since the last transaction") #get the count for the age columns grouped["idx"] = grouped.groupby(['Customer_ID','Product Code']).cumcount().add(1) #pivot to get the required structure output = grouped.pivot(["Customer_ID","Product Code"],"idx","Days since the last transaction").add_prefix("Days since the last transaction").reset_index().rename_axis(None, axis=1) output.head() ```
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
**It is possible to stroke *arbitrary paths* with a gradient, or any other fill effect, such as a pattern.** As you have found, stroked paths are not rendered with the current gradient. Only filled paths use the gradient (when you turn them in to a clip and then draw the gradient). **However**, Core Graphics has an amazingly cool procedure **`CGContextReplacePathWithStrokedPath`** that will transform the path you intend to **stroke** in to a path that is **equivalent when filled**. Behind the scenes, `CGContextReplacePathWithStrokedPath` builds up an edge polygon around your stroke path and switches that for the path you have defined. I'd speculate that the Core Graphics rendering engine probably does this *anyway* in calls to `CGContextStrokePath`. Here's Apple's documentation on this: > > Quartz creates a stroked path using the parameters of the current graphics context. The new path is created so that filling it draws the same pixels as stroking the original path. You can use this path in the same way you use the path of any context. For example, you can clip to the stroked version of a path by calling this function followed by a call to the function CGContextClip. > > > So, convert your path in to something you can fill, turn that in to a clip, and *then* draw your gradient. The effect will be as if you had stroked the path with the gradient. Code ==== It'll look something like this… ``` // Get the current graphics context. // const CGContextRef context = UIGraphicsGetCurrentContext(); // Define your stroked path. // // You can set up **anything** you like here. // CGContextAddRect(context, yourRectToStrokeWithAGradient); // Set up any stroking parameters like line. // // I'm setting width. You could also set up a dashed stroke // pattern, or whatever you like. // CGContextSetLineWidth(context, 1); // Use the magical call. // // It turns your _stroked_ path in to a **fillable** one. // CGContextReplacePathWithStrokedPath(context); // Use the current _fillable_ path in to define a clipping region. // CGContextClip(context); // Draw the gradient. // // The gradient will be clipped to your original path. // You could use other fill effects like patterns here. // CGContextDrawLinearGradient( context, yourGradient, gradientTop, gradientBottom, 0 ); ``` Further notes ============= It's worth emphasising part of the documentation above: > > Quartz creates a stroked path **using the parameters of the current graphics context**. > > > The obvious parameter is the line width. However, **all** line drawing state is used, such as stroke pattern, mitre limit, line joins, caps, dash patterns, etc. This makes the approach extremely powerful. For additional details see [this answer](https://stackoverflow.com/a/2770034/2547229) of [this S.O. question](https://stackoverflow.com/q/2737973/2547229).
I created a Swift version of Benjohn's answer. ``` class MyView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } context.addPath(createPath().cgPath) context.setLineWidth(15) context.replacePathWithStrokedPath() context.clip() let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.green.cgColor] as CFArray, locations: [0, 0.4, 1.0])! let radius:CGFloat = 200 let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) context.drawRadialGradient(gradient, startCenter: center, startRadius: 10, endCenter: center, endRadius: radius, options: .drawsBeforeStartLocation) } } ``` If the createPath() method creates a triangle, you get something like this: [![enter image description here](https://i.stack.imgur.com/RMppo.png)](https://i.stack.imgur.com/RMppo.png) Hope this helps anyone!
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
After several tries I'm now sure that gradients doesn't affect strokes, so I think it's impossible to draw gradient lines with `CGContextStrokePath()`. For horizontal and vertical lines the solution is to use `CGContextAddRect()` instead, which fortunately is what I need. I replaced ``` CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` with ``` CGContextSaveGState(context); CGContextAddRect(context, CGRectMake(x, y, width, height)); CGContextClip(context); CGContextDrawLinearGradient (context, gradient, startPoint, endPoint, 0); CGContextRestoreGState(context); ``` and everything works fine. Thanks to Brad Larson for the crucial hint.
You can use Core Animation layers. You can use a [CAShaperLayer](http://developer.apple.com/IPhone/library/documentation/GraphicsImaging/Reference/CAShapeLayer_class/Reference/Reference.html) for your line by settings its path property and then you can use a [CAGradientLayer](http://developer.apple.com/iphone/library/documentation/GraphicsImaging/Reference/CAGradientLayer_class/Reference/Reference.html) as a layer mask to your shape layer that will cause the line to fade. Replace your CGContext... calls with calls to CGPath... calls to create the line path. Set the path field on the layer using that path. Then in your gradient layer, specify the colors you want to use (probably black to white) and then set the mask to be the line layer like this: ``` [gradientLayer setMask:lineLayer]; ``` What's cool about the gradient layer is that is allows you to specify a list of locations where the gradient will stop, so you can fade in and fade out. It only supports linear gradients, but it sounds like that may fit your needs. Let me know if you need clarification. EDIT: Now that I think of it, just create a single CAGradientLayer that is the width/height of the line you desire. Specify the gradient colors (black to white or black to clear color) and the startPoint and endtPoints and it should give you what you need.
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
You can use Core Animation layers. You can use a [CAShaperLayer](http://developer.apple.com/IPhone/library/documentation/GraphicsImaging/Reference/CAShapeLayer_class/Reference/Reference.html) for your line by settings its path property and then you can use a [CAGradientLayer](http://developer.apple.com/iphone/library/documentation/GraphicsImaging/Reference/CAGradientLayer_class/Reference/Reference.html) as a layer mask to your shape layer that will cause the line to fade. Replace your CGContext... calls with calls to CGPath... calls to create the line path. Set the path field on the layer using that path. Then in your gradient layer, specify the colors you want to use (probably black to white) and then set the mask to be the line layer like this: ``` [gradientLayer setMask:lineLayer]; ``` What's cool about the gradient layer is that is allows you to specify a list of locations where the gradient will stop, so you can fade in and fade out. It only supports linear gradients, but it sounds like that may fit your needs. Let me know if you need clarification. EDIT: Now that I think of it, just create a single CAGradientLayer that is the width/height of the line you desire. Specify the gradient colors (black to white or black to clear color) and the startPoint and endtPoints and it should give you what you need.
``` CGContextMoveToPoint(context, frame.size.width-200, frame.origin.y+10); CGContextAddLineToPoint(context, frame.size.width-200, 100-10); CGFloat colors[16] = { 0,0, 0, 0, 0, 0, 0, .8, 0, 0, 0, .8, 0, 0,0 ,0 }; CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 4); CGContextSaveGState(context); CGContextAddRect(context, CGRectMake(frame.size.width-200,10, 1, 80)); CGContextClip(context); CGContextDrawLinearGradient (context, gradient, CGPointMake(frame.size.width-200, 10), CGPointMake(frame.size.width-200,80), 0); CGContextRestoreGState(context); ``` its work for me.
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
**It is possible to stroke *arbitrary paths* with a gradient, or any other fill effect, such as a pattern.** As you have found, stroked paths are not rendered with the current gradient. Only filled paths use the gradient (when you turn them in to a clip and then draw the gradient). **However**, Core Graphics has an amazingly cool procedure **`CGContextReplacePathWithStrokedPath`** that will transform the path you intend to **stroke** in to a path that is **equivalent when filled**. Behind the scenes, `CGContextReplacePathWithStrokedPath` builds up an edge polygon around your stroke path and switches that for the path you have defined. I'd speculate that the Core Graphics rendering engine probably does this *anyway* in calls to `CGContextStrokePath`. Here's Apple's documentation on this: > > Quartz creates a stroked path using the parameters of the current graphics context. The new path is created so that filling it draws the same pixels as stroking the original path. You can use this path in the same way you use the path of any context. For example, you can clip to the stroked version of a path by calling this function followed by a call to the function CGContextClip. > > > So, convert your path in to something you can fill, turn that in to a clip, and *then* draw your gradient. The effect will be as if you had stroked the path with the gradient. Code ==== It'll look something like this… ``` // Get the current graphics context. // const CGContextRef context = UIGraphicsGetCurrentContext(); // Define your stroked path. // // You can set up **anything** you like here. // CGContextAddRect(context, yourRectToStrokeWithAGradient); // Set up any stroking parameters like line. // // I'm setting width. You could also set up a dashed stroke // pattern, or whatever you like. // CGContextSetLineWidth(context, 1); // Use the magical call. // // It turns your _stroked_ path in to a **fillable** one. // CGContextReplacePathWithStrokedPath(context); // Use the current _fillable_ path in to define a clipping region. // CGContextClip(context); // Draw the gradient. // // The gradient will be clipped to your original path. // You could use other fill effects like patterns here. // CGContextDrawLinearGradient( context, yourGradient, gradientTop, gradientBottom, 0 ); ``` Further notes ============= It's worth emphasising part of the documentation above: > > Quartz creates a stroked path **using the parameters of the current graphics context**. > > > The obvious parameter is the line width. However, **all** line drawing state is used, such as stroke pattern, mitre limit, line joins, caps, dash patterns, etc. This makes the approach extremely powerful. For additional details see [this answer](https://stackoverflow.com/a/2770034/2547229) of [this S.O. question](https://stackoverflow.com/q/2737973/2547229).
**Swift 5** Version This code worked for me. ``` override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } drawGradientBorder(rect, context: context) } fileprivate func drawGradientBorder(_ rect: CGRect, context: CGContext) { context.saveGState() let path = ribbonPath() context.setLineWidth(5.0) context.addPath(path.cgPath) context.replacePathWithStrokedPath() context.clip() let baseSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorsSpace: baseSpace, colors: [UIColor.red.cgColor, UIColor.blue.cgColor] as CFArray, locations: [0.0 ,1.0])! context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: rect.height/2), end: CGPoint(x: rect.width, y: rect.height/2), options: []) context.restoreGState() } fileprivate func ribbonPath() -> UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint.zero) path.addLine(to: CGPoint(x: bounds.maxX - gradientWidth, y: 0)) path.addLine(to: CGPoint(x: bounds.maxX - gradientWidth - ribbonGap, y: bounds.maxY)) path.addLine(to: CGPoint(x: 0, y: bounds.maxY)) path.close() return path } ```
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
**It is possible to stroke *arbitrary paths* with a gradient, or any other fill effect, such as a pattern.** As you have found, stroked paths are not rendered with the current gradient. Only filled paths use the gradient (when you turn them in to a clip and then draw the gradient). **However**, Core Graphics has an amazingly cool procedure **`CGContextReplacePathWithStrokedPath`** that will transform the path you intend to **stroke** in to a path that is **equivalent when filled**. Behind the scenes, `CGContextReplacePathWithStrokedPath` builds up an edge polygon around your stroke path and switches that for the path you have defined. I'd speculate that the Core Graphics rendering engine probably does this *anyway* in calls to `CGContextStrokePath`. Here's Apple's documentation on this: > > Quartz creates a stroked path using the parameters of the current graphics context. The new path is created so that filling it draws the same pixels as stroking the original path. You can use this path in the same way you use the path of any context. For example, you can clip to the stroked version of a path by calling this function followed by a call to the function CGContextClip. > > > So, convert your path in to something you can fill, turn that in to a clip, and *then* draw your gradient. The effect will be as if you had stroked the path with the gradient. Code ==== It'll look something like this… ``` // Get the current graphics context. // const CGContextRef context = UIGraphicsGetCurrentContext(); // Define your stroked path. // // You can set up **anything** you like here. // CGContextAddRect(context, yourRectToStrokeWithAGradient); // Set up any stroking parameters like line. // // I'm setting width. You could also set up a dashed stroke // pattern, or whatever you like. // CGContextSetLineWidth(context, 1); // Use the magical call. // // It turns your _stroked_ path in to a **fillable** one. // CGContextReplacePathWithStrokedPath(context); // Use the current _fillable_ path in to define a clipping region. // CGContextClip(context); // Draw the gradient. // // The gradient will be clipped to your original path. // You could use other fill effects like patterns here. // CGContextDrawLinearGradient( context, yourGradient, gradientTop, gradientBottom, 0 ); ``` Further notes ============= It's worth emphasising part of the documentation above: > > Quartz creates a stroked path **using the parameters of the current graphics context**. > > > The obvious parameter is the line width. However, **all** line drawing state is used, such as stroke pattern, mitre limit, line joins, caps, dash patterns, etc. This makes the approach extremely powerful. For additional details see [this answer](https://stackoverflow.com/a/2770034/2547229) of [this S.O. question](https://stackoverflow.com/q/2737973/2547229).
After you draw the line, you can call ``` CGContextClip(context); ``` to clip further drawing to your line area. If you draw the gradient, it should now be contained within the line area. Note that you will need to use a clear color for your line if you just want the gradient to show, and not the line underneath it. There is the possibility that a line will be too thin for your gradient to show up, in which case you can use `CGContextAddRect()` to define a thicker area. I present a more elaborate example of using this context clipping in my answer [here](https://stackoverflow.com/questions/1266179/how-do-i-add-a-gradient-to-the-text-of-a-uilabel-but-not-the-background/1267638#1267638).
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
After several tries I'm now sure that gradients doesn't affect strokes, so I think it's impossible to draw gradient lines with `CGContextStrokePath()`. For horizontal and vertical lines the solution is to use `CGContextAddRect()` instead, which fortunately is what I need. I replaced ``` CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` with ``` CGContextSaveGState(context); CGContextAddRect(context, CGRectMake(x, y, width, height)); CGContextClip(context); CGContextDrawLinearGradient (context, gradient, startPoint, endPoint, 0); CGContextRestoreGState(context); ``` and everything works fine. Thanks to Brad Larson for the crucial hint.
I created a Swift version of Benjohn's answer. ``` class MyView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } context.addPath(createPath().cgPath) context.setLineWidth(15) context.replacePathWithStrokedPath() context.clip() let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.green.cgColor] as CFArray, locations: [0, 0.4, 1.0])! let radius:CGFloat = 200 let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) context.drawRadialGradient(gradient, startCenter: center, startRadius: 10, endCenter: center, endRadius: radius, options: .drawsBeforeStartLocation) } } ``` If the createPath() method creates a triangle, you get something like this: [![enter image description here](https://i.stack.imgur.com/RMppo.png)](https://i.stack.imgur.com/RMppo.png) Hope this helps anyone!
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
I created a Swift version of Benjohn's answer. ``` class MyView: UIView { override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } context.addPath(createPath().cgPath) context.setLineWidth(15) context.replacePathWithStrokedPath() context.clip() let gradient = CGGradient(colorsSpace: nil, colors: [UIColor.red.cgColor, UIColor.yellow.cgColor, UIColor.green.cgColor] as CFArray, locations: [0, 0.4, 1.0])! let radius:CGFloat = 200 let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) context.drawRadialGradient(gradient, startCenter: center, startRadius: 10, endCenter: center, endRadius: radius, options: .drawsBeforeStartLocation) } } ``` If the createPath() method creates a triangle, you get something like this: [![enter image description here](https://i.stack.imgur.com/RMppo.png)](https://i.stack.imgur.com/RMppo.png) Hope this helps anyone!
``` CGContextMoveToPoint(context, frame.size.width-200, frame.origin.y+10); CGContextAddLineToPoint(context, frame.size.width-200, 100-10); CGFloat colors[16] = { 0,0, 0, 0, 0, 0, 0, .8, 0, 0, 0, .8, 0, 0,0 ,0 }; CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 4); CGContextSaveGState(context); CGContextAddRect(context, CGRectMake(frame.size.width-200,10, 1, 80)); CGContextClip(context); CGContextDrawLinearGradient (context, gradient, CGPointMake(frame.size.width-200, 10), CGPointMake(frame.size.width-200,80), 0); CGContextRestoreGState(context); ``` its work for me.
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
After several tries I'm now sure that gradients doesn't affect strokes, so I think it's impossible to draw gradient lines with `CGContextStrokePath()`. For horizontal and vertical lines the solution is to use `CGContextAddRect()` instead, which fortunately is what I need. I replaced ``` CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` with ``` CGContextSaveGState(context); CGContextAddRect(context, CGRectMake(x, y, width, height)); CGContextClip(context); CGContextDrawLinearGradient (context, gradient, startPoint, endPoint, 0); CGContextRestoreGState(context); ``` and everything works fine. Thanks to Brad Larson for the crucial hint.
``` CGContextMoveToPoint(context, frame.size.width-200, frame.origin.y+10); CGContextAddLineToPoint(context, frame.size.width-200, 100-10); CGFloat colors[16] = { 0,0, 0, 0, 0, 0, 0, .8, 0, 0, 0, .8, 0, 0,0 ,0 }; CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB(); CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 4); CGContextSaveGState(context); CGContextAddRect(context, CGRectMake(frame.size.width-200,10, 1, 80)); CGContextClip(context); CGContextDrawLinearGradient (context, gradient, CGPointMake(frame.size.width-200, 10), CGPointMake(frame.size.width-200,80), 0); CGContextRestoreGState(context); ``` its work for me.
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
You can use Core Animation layers. You can use a [CAShaperLayer](http://developer.apple.com/IPhone/library/documentation/GraphicsImaging/Reference/CAShapeLayer_class/Reference/Reference.html) for your line by settings its path property and then you can use a [CAGradientLayer](http://developer.apple.com/iphone/library/documentation/GraphicsImaging/Reference/CAGradientLayer_class/Reference/Reference.html) as a layer mask to your shape layer that will cause the line to fade. Replace your CGContext... calls with calls to CGPath... calls to create the line path. Set the path field on the layer using that path. Then in your gradient layer, specify the colors you want to use (probably black to white) and then set the mask to be the line layer like this: ``` [gradientLayer setMask:lineLayer]; ``` What's cool about the gradient layer is that is allows you to specify a list of locations where the gradient will stop, so you can fade in and fade out. It only supports linear gradients, but it sounds like that may fit your needs. Let me know if you need clarification. EDIT: Now that I think of it, just create a single CAGradientLayer that is the width/height of the line you desire. Specify the gradient colors (black to white or black to clear color) and the startPoint and endtPoints and it should give you what you need.
**Swift 5** Version This code worked for me. ``` override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } drawGradientBorder(rect, context: context) } fileprivate func drawGradientBorder(_ rect: CGRect, context: CGContext) { context.saveGState() let path = ribbonPath() context.setLineWidth(5.0) context.addPath(path.cgPath) context.replacePathWithStrokedPath() context.clip() let baseSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorsSpace: baseSpace, colors: [UIColor.red.cgColor, UIColor.blue.cgColor] as CFArray, locations: [0.0 ,1.0])! context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: rect.height/2), end: CGPoint(x: rect.width, y: rect.height/2), options: []) context.restoreGState() } fileprivate func ribbonPath() -> UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint.zero) path.addLine(to: CGPoint(x: bounds.maxX - gradientWidth, y: 0)) path.addLine(to: CGPoint(x: bounds.maxX - gradientWidth - ribbonGap, y: bounds.maxY)) path.addLine(to: CGPoint(x: 0, y: bounds.maxY)) path.close() return path } ```
1,303,855
I know how to draw a simple line: ``` CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); CGContextMoveToPoint(context, x, y); CGContextAddLineToPoint(context, x2, y2); CGContextStrokePath(context); ``` And I know how to do a gradient rectangle, i.g.: ``` CGColorSpaceRef myColorspace=CGColorSpaceCreateDeviceRGB(); size_t num_locations = 2; CGFloat locations[2] = { 1.0, 0.0 }; CGFloat components[8] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0 }; CGGradientRef myGradient = CGGradientCreateWithColorComponents(myColorspace, components, locations, num_locations); CGPoint myStartPoint, myEndPoint; myStartPoint.x = 0.0; myStartPoint.y = 0.0; myEndPoint.x = 0.0; myEndPoint.y = 10.0; CGContextDrawLinearGradient (context, myGradient, myStartPoint, myEndPoint, 0); ``` But how could I draw a line with a gradient, i.g. fading in from black to white (and maybe fading out to black on the other side as well) ?
2009/08/20
[ "https://Stackoverflow.com/questions/1303855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112136/" ]
After you draw the line, you can call ``` CGContextClip(context); ``` to clip further drawing to your line area. If you draw the gradient, it should now be contained within the line area. Note that you will need to use a clear color for your line if you just want the gradient to show, and not the line underneath it. There is the possibility that a line will be too thin for your gradient to show up, in which case you can use `CGContextAddRect()` to define a thicker area. I present a more elaborate example of using this context clipping in my answer [here](https://stackoverflow.com/questions/1266179/how-do-i-add-a-gradient-to-the-text-of-a-uilabel-but-not-the-background/1267638#1267638).
**Swift 5** Version This code worked for me. ``` override func draw(_ rect: CGRect) { super.draw(rect) guard let context = UIGraphicsGetCurrentContext() else { return } drawGradientBorder(rect, context: context) } fileprivate func drawGradientBorder(_ rect: CGRect, context: CGContext) { context.saveGState() let path = ribbonPath() context.setLineWidth(5.0) context.addPath(path.cgPath) context.replacePathWithStrokedPath() context.clip() let baseSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorsSpace: baseSpace, colors: [UIColor.red.cgColor, UIColor.blue.cgColor] as CFArray, locations: [0.0 ,1.0])! context.drawLinearGradient(gradient, start: CGPoint(x: 0, y: rect.height/2), end: CGPoint(x: rect.width, y: rect.height/2), options: []) context.restoreGState() } fileprivate func ribbonPath() -> UIBezierPath { let path = UIBezierPath() path.move(to: CGPoint.zero) path.addLine(to: CGPoint(x: bounds.maxX - gradientWidth, y: 0)) path.addLine(to: CGPoint(x: bounds.maxX - gradientWidth - ribbonGap, y: bounds.maxY)) path.addLine(to: CGPoint(x: 0, y: bounds.maxY)) path.close() return path } ```
23,475,848
I have been searching and coding with the Google Maps iOS SDK 1.7.2 I need to build an app that displays custom InfoWindow after the marker is tapped. Google posted a [YouTube Video](https://www.youtube.com/watch?v=ILiBXYscsyY), that shows how to do it with just ONE marker. The practical use scenario uses more than ONE marker, but if we follow the example of YouTube Video adding more than one marker, all the markers would show the same info inside the custom InfoWindows. I did a iOS sample and uploaded to GitHub [Sample Here](https://github.com/lorencogonzaga/ioscode/) My Question is: Could anyone download the sample at GitHub and help me to implement that feature, display more than one marker with custom InfoWindow displaying different info for each marker ? In my sample inside the InfoWindow there is a WebView. For my use scenario I would need to load for each marker a different WebView(url) for each marker on the map but I couldn't load the WebView inside the custom InfoWindow. That WebView would be the size of the custom InfoWindow.I would load all the info for the markers as different webpages in the size of the info window. It also would help a lot of other people that right now can't find a complete and fully working sample of that custom InfoWindow for iOS. Thanks and Cheers!
2014/05/05
[ "https://Stackoverflow.com/questions/23475848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
using date('d.m.Y') will cut off the hours, minutes and seconds. Thus returning you the timestamp it was at midnight. If you use strtotime without filtering it through date, it returns the hours, minutes and seconds according to current time. Here in occurence, you ran the script arround 17 hours after midnight. ``` echo date('d.m.Y',strtotime("first day of previous month"));// 1.4.2014 echo date('d.m.Y H:i:s',strtotime("first day of previous month"));// 1.4.2014 17:26 echo date('d.m.Y H:i:s',strtotime("1.4.2014"));// 1.4.2014 00:00:00 ```
The format of `date()` matters as strtotime will interpret it different depending on that. Stick to standard formats like YYYY-MM-DD and you'll get expected results. In your case, you use `d.m.Y` which will give you `01.04.2014`. Is that April 1st or January 4th? PHP doesn't know so it guesses in this case. If you used `Y-m-d` you'd get the expected results as that format is not ambiguous to PHP. [Demo](http://codepad.viper-7.com/vtlwOU) ``` var_dump(strtotime("01.04.2014")); var_dump(strtotime("04.01.2014")); var_dump(strtotime("2014-04-01")); int(1396310400) int(1388793600) int(1396310400) ```
23,475,848
I have been searching and coding with the Google Maps iOS SDK 1.7.2 I need to build an app that displays custom InfoWindow after the marker is tapped. Google posted a [YouTube Video](https://www.youtube.com/watch?v=ILiBXYscsyY), that shows how to do it with just ONE marker. The practical use scenario uses more than ONE marker, but if we follow the example of YouTube Video adding more than one marker, all the markers would show the same info inside the custom InfoWindows. I did a iOS sample and uploaded to GitHub [Sample Here](https://github.com/lorencogonzaga/ioscode/) My Question is: Could anyone download the sample at GitHub and help me to implement that feature, display more than one marker with custom InfoWindow displaying different info for each marker ? In my sample inside the InfoWindow there is a WebView. For my use scenario I would need to load for each marker a different WebView(url) for each marker on the map but I couldn't load the WebView inside the custom InfoWindow. That WebView would be the size of the custom InfoWindow.I would load all the info for the markers as different webpages in the size of the info window. It also would help a lot of other people that right now can't find a complete and fully working sample of that custom InfoWindow for iOS. Thanks and Cheers!
2014/05/05
[ "https://Stackoverflow.com/questions/23475848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This has to do with how `strtotime()` interprets your date string. From the [documentation for `strtotime()`](http://php.net/strtotime): > > Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas **if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.** To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible. > > > Let's see what the timestamp values correspond to: ``` echo date('r', 1396303200) . "\n"; echo date('r', 1396364471); ``` Output: ``` Tue, 01 Apr 2014 03:30:00 +0530 Tue, 01 Apr 2014 20:31:11 +0530 ``` See the output of the following `var_dump()` statement: ``` var_dump(date('d.m.Y',strtotime("first day of previous month"))); ``` It outputs: ``` string(10) "01.04.2014" ``` Here the separator is a dot, so `strtotime()` will interpret the date as of `DD-MM-YYYY` format. To avoid such ambiguity, always use [`DateTime::createFromFormat()`](http://www.php.net/manual/en/datetime.createfromformat.php) instead.
The format of `date()` matters as strtotime will interpret it different depending on that. Stick to standard formats like YYYY-MM-DD and you'll get expected results. In your case, you use `d.m.Y` which will give you `01.04.2014`. Is that April 1st or January 4th? PHP doesn't know so it guesses in this case. If you used `Y-m-d` you'd get the expected results as that format is not ambiguous to PHP. [Demo](http://codepad.viper-7.com/vtlwOU) ``` var_dump(strtotime("01.04.2014")); var_dump(strtotime("04.01.2014")); var_dump(strtotime("2014-04-01")); int(1396310400) int(1388793600) int(1396310400) ```
2,521,059
When I make changes to a Flex project and rerun the project, it seems that FlashBuilder4 rewrites my html wrapper that embeds the SWF. But I have additional javascript code in the html wrapper and don't want to keep losing my code. I had to re-write the code once and it was a pain in the neck. How do I stop it from re-writing the html. And the related question: how do I stop it from deleting the html during a clean? I basically need to exclude the html from its processing once it's been created the first time. P.S. I'm using Flash Builder 4, but I suppose it's the same in Flex Builder 3.
2010/03/26
[ "https://Stackoverflow.com/questions/2521059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299300/" ]
Turn off "Generate HTML Wrapper file" in Project settings. [![Generate HTML Wrapper file](https://i.stack.imgur.com/kDyI2.png)](https://i.stack.imgur.com/kDyI2.png) This will delete the auto-generated HTML wrapper file in your bin directory. If you need to keep it, make a copy first and put it back after turning off this option.
If Flash Builder 4 is indeed based off Flex Builder 3 as you mentioned then the real solution you are looking for is to edit the HTML wrapper template in **<Flex-Project-Folder>/html-template/index.template.html** and put your own modifications there. You need to be mindful of the tokens used in the template while editing this file as they will be replaced when the HTML wrapper is generated when you perform a build. For instance - ``` <title>${title}</title> ``` will be replaced with the *pageTitle* you set in your Application mxml - ``` <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" pageTitle="Flex Project" width="100%" height="100%"> </mx:Application> ``` HTH
2,521,059
When I make changes to a Flex project and rerun the project, it seems that FlashBuilder4 rewrites my html wrapper that embeds the SWF. But I have additional javascript code in the html wrapper and don't want to keep losing my code. I had to re-write the code once and it was a pain in the neck. How do I stop it from re-writing the html. And the related question: how do I stop it from deleting the html during a clean? I basically need to exclude the html from its processing once it's been created the first time. P.S. I'm using Flash Builder 4, but I suppose it's the same in Flex Builder 3.
2010/03/26
[ "https://Stackoverflow.com/questions/2521059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299300/" ]
Turn off "Generate HTML Wrapper file" in Project settings. [![Generate HTML Wrapper file](https://i.stack.imgur.com/kDyI2.png)](https://i.stack.imgur.com/kDyI2.png) This will delete the auto-generated HTML wrapper file in your bin directory. If you need to keep it, make a copy first and put it back after turning off this option.
I had the same problem with FB4. My project is an ActionScript project. All you have to do is drop `[SWF(width="300", height="300", backgroundColor="#ffffff", frameRate="30")]` into your default package beneath the imports and it will use these setting to generate the HTML. Howie
2,521,059
When I make changes to a Flex project and rerun the project, it seems that FlashBuilder4 rewrites my html wrapper that embeds the SWF. But I have additional javascript code in the html wrapper and don't want to keep losing my code. I had to re-write the code once and it was a pain in the neck. How do I stop it from re-writing the html. And the related question: how do I stop it from deleting the html during a clean? I basically need to exclude the html from its processing once it's been created the first time. P.S. I'm using Flash Builder 4, but I suppose it's the same in Flex Builder 3.
2010/03/26
[ "https://Stackoverflow.com/questions/2521059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299300/" ]
Turn off "Generate HTML Wrapper file" in Project settings. [![Generate HTML Wrapper file](https://i.stack.imgur.com/kDyI2.png)](https://i.stack.imgur.com/kDyI2.png) This will delete the auto-generated HTML wrapper file in your bin directory. If you need to keep it, make a copy first and put it back after turning off this option.
Flash Builder 4.7 Right-click on the project of interest in the Package Explorer, select "properties", select "Actionscript Compiler", deselect the "Generate HTML wrapper file" checkbox. Check the adobe link for details: <http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-120529f3137a1e031d6-7fff.html>
2,521,059
When I make changes to a Flex project and rerun the project, it seems that FlashBuilder4 rewrites my html wrapper that embeds the SWF. But I have additional javascript code in the html wrapper and don't want to keep losing my code. I had to re-write the code once and it was a pain in the neck. How do I stop it from re-writing the html. And the related question: how do I stop it from deleting the html during a clean? I basically need to exclude the html from its processing once it's been created the first time. P.S. I'm using Flash Builder 4, but I suppose it's the same in Flex Builder 3.
2010/03/26
[ "https://Stackoverflow.com/questions/2521059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299300/" ]
If Flash Builder 4 is indeed based off Flex Builder 3 as you mentioned then the real solution you are looking for is to edit the HTML wrapper template in **<Flex-Project-Folder>/html-template/index.template.html** and put your own modifications there. You need to be mindful of the tokens used in the template while editing this file as they will be replaced when the HTML wrapper is generated when you perform a build. For instance - ``` <title>${title}</title> ``` will be replaced with the *pageTitle* you set in your Application mxml - ``` <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" pageTitle="Flex Project" width="100%" height="100%"> </mx:Application> ``` HTH
Flash Builder 4.7 Right-click on the project of interest in the Package Explorer, select "properties", select "Actionscript Compiler", deselect the "Generate HTML wrapper file" checkbox. Check the adobe link for details: <http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-120529f3137a1e031d6-7fff.html>
2,521,059
When I make changes to a Flex project and rerun the project, it seems that FlashBuilder4 rewrites my html wrapper that embeds the SWF. But I have additional javascript code in the html wrapper and don't want to keep losing my code. I had to re-write the code once and it was a pain in the neck. How do I stop it from re-writing the html. And the related question: how do I stop it from deleting the html during a clean? I basically need to exclude the html from its processing once it's been created the first time. P.S. I'm using Flash Builder 4, but I suppose it's the same in Flex Builder 3.
2010/03/26
[ "https://Stackoverflow.com/questions/2521059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299300/" ]
I had the same problem with FB4. My project is an ActionScript project. All you have to do is drop `[SWF(width="300", height="300", backgroundColor="#ffffff", frameRate="30")]` into your default package beneath the imports and it will use these setting to generate the HTML. Howie
Flash Builder 4.7 Right-click on the project of interest in the Package Explorer, select "properties", select "Actionscript Compiler", deselect the "Generate HTML wrapper file" checkbox. Check the adobe link for details: <http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-120529f3137a1e031d6-7fff.html>
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
``` sudo gem install -n /usr/local/bin cocoapods ``` Try this. It will definately work.
``` sudo chown -R $(whoami):admin /usr/local ``` That will give permissions back (Homebrew installs ruby there)
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
That is because of the new security function of OS X "El Capitan". Try adding `--user-install` instead of using sudo: ``` $ gem install *** --user-install ``` For example, if you want to install fake3 just use: ``` $ gem install fake3 --user-install ```
``` sudo chown -R $(whoami):admin /usr/local ``` That will give permissions back (Homebrew installs ruby there)
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
Looks like when upgrading to OS X El Capitain, the /usr/local directory is modified in multiple ways : 1. user permissions are reset (this is also a problem for people using Homebrew) 2. binaries and symlinks might have been deleted or altered [Edit] There's also a preliminary thing to do : upgrade Xcode... Solution for #1 : ================= ``` $ sudo chown -R $(whoami):admin /usr/local ``` This will fix permissions on the `/usr/local` directory which will then help both `gem install` and `brew install|link|...` commands working properly. Solution to #2 : ================ Ruby based issues ----------------- Make sure you have fixed the permissions of the `/usr/local` directory (see #1 above) First try to reinstall your gem using : ``` sudo gem install <gemname> ``` Note that it will install the latest version of the specified gem. If you don't want to face backward-compatibility issues, I suggest that you first determine which version of which gem you want to get and then reinstall it with the `-v version`. See an exemple below to make sure that the system won't get a new version of capistrano. ``` $ gem list | grep capistrano capistrano (3.4.0, 3.2.1, 2.14.2) $ sudo gem install capistrano -v 3.4.0 ``` Brew based issues ----------------- Update brew and upgrade your formulas ``` $ brew update $ brew upgrade ``` You might also need to re-link some of them manually ``` $ brew link <formula> ```
I ran across the same issue after installing El Capitan, I tried to install sass and compass into a symfony project, the following command returned the following error: $ sudo gem install compass ERROR: Error installing compass: ERROR: Failed to build gem native extension. ``` /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb ``` checking for ffi.h... /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/mkmf.rb:434:in `try\_do': The compiler failed to generate an executable file. (RuntimeError) So I then tried to install sass with: $ sudo gem install sass Got the same error message, after some googling I managed to install sass using the following command: $ sudo gem install -n /usr/local/bin sass The above worked for me with installing sass but did not work for installing compass. I read that someone somewhere had opened an instance of xcode then closed it again, then successfully ran the same command after which worked for them. I attempted to open xcode but was prompted with a message saying that the version of xcode installed was not compatible with El Capitan. So I then updated xcode from the app store, re-ran the following command which this time ran successfully: $ sudo gem install -n /usr/local/bin compass I was then able to run $ compass init I now have all my gems working and can proceed to build some lovely sass stuff :)
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
**Disclaimer:** @theTinMan and other Ruby developers often point out not to use `sudo` when installing gems and point to things like [RVM](http://rvm.io/rvm/install). That's absolutely true when doing Ruby development. Go ahead and use that. However, many of us just want some binary that happens to be distributed as a gem (e.g. `fakes3`, `cocoapods`, `xcpretty` …). I definitely don't want to bother with managing a separate ruby. Here are your quicker options: ### Option 1: Keep using sudo Using `sudo` is probably fine if you want these tools to be installed globally. The problem is that these binaries are installed into `/usr/bin`, which is [off-limits](https://en.wikipedia.org/wiki/System_Integrity_Protection) since El Capitan. However, you can install them into `/usr/local/bin` instead. That's where [Homebrew](http://brew.sh) install its stuff, so it [probably](https://apple.stackexchange.com/questions/157979/usr-local-doesnt-exist-in-fresh-install-yosemite) exists already. ``` sudo gem install fakes3 -n/usr/local/bin ``` Gems will be installed into `/usr/local/bin` and every user on your system can use them if it's in their [PATH](https://stackoverflow.com/a/10343891/168939). ### Option 2: Install in your home directory (without sudo) The following will install gems in `~/.gem` and put binaries in `~/bin` (which you should then add to your `PATH`). ``` gem install fakes3 --user-install -n~/bin ``` ### Make it the default Either way, you can add these parameters to your `~/.gemrc` so you don't have to remember them: ``` gem: -n/usr/local/bin ``` i.e. `echo "gem: -n/usr/local/bin" >> ~/.gemrc` **or** ``` gem: --user-install -n~/bin ``` i.e. `echo "gem: --user-install -n~/bin" >> ~/.gemrc` (*Tip:* You can also throw in `--no-document` to skip generating Ruby developer documentation.)
That is because of the new security function of OS X "El Capitan". Try adding `--user-install` instead of using sudo: ``` $ gem install *** --user-install ``` For example, if you want to install fake3 just use: ``` $ gem install fake3 --user-install ```
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
You have to update Xcode to the newest one (v7.0.1) and everything will work as normal. If after you install the newest Xcode and still doesn't work try to install gem in this way: ``` sudo gem install -n /usr/local/bin GEM_NAME_HERE ``` For example: ``` sudo gem install -n /usr/local/bin fakes3 sudo gem install -n /usr/local/bin compass sudo gem install -n /usr/local/bin susy ```
This is the solution that I have used: *Note: this fix is for compass as I wrote it on another SO question, but I have used the same process to restore functionality to all terminal processes, obviously the gems you are installing are different, but the process is the same.* I had the same issue. It is due to Apple implementing System Integrity Protection (SIP). You have to first disable that... **Reboot in recovery mode:** Reboot and hold **Command + R** until you see the apple logo. Once booted select **Utilities > Terminal** from top bar. type: `csrutil disable` then type: `reboot` **Once rebooted** Open terminal back up and enter the commands: `sudo gem uninstall bundler` `sudo gem install bundler` `sudo gem install compass` `sudo gem install sass` `sudo gem update --system` The the individual gems that failed need to be fixed, so for each do the following: *On my machine this was the first dependency not working so I listed it*: `sudo gem pristine ffi --version 1.9.3` Proceed through the list of gems that need to be repaired. In all you are looking at about 10 minutes to fix it, but you will have terminal commands for compass working. [Screenshot](http://i.stack.imgur.com/EwDc4.jpg)
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
**Disclaimer:** @theTinMan and other Ruby developers often point out not to use `sudo` when installing gems and point to things like [RVM](http://rvm.io/rvm/install). That's absolutely true when doing Ruby development. Go ahead and use that. However, many of us just want some binary that happens to be distributed as a gem (e.g. `fakes3`, `cocoapods`, `xcpretty` …). I definitely don't want to bother with managing a separate ruby. Here are your quicker options: ### Option 1: Keep using sudo Using `sudo` is probably fine if you want these tools to be installed globally. The problem is that these binaries are installed into `/usr/bin`, which is [off-limits](https://en.wikipedia.org/wiki/System_Integrity_Protection) since El Capitan. However, you can install them into `/usr/local/bin` instead. That's where [Homebrew](http://brew.sh) install its stuff, so it [probably](https://apple.stackexchange.com/questions/157979/usr-local-doesnt-exist-in-fresh-install-yosemite) exists already. ``` sudo gem install fakes3 -n/usr/local/bin ``` Gems will be installed into `/usr/local/bin` and every user on your system can use them if it's in their [PATH](https://stackoverflow.com/a/10343891/168939). ### Option 2: Install in your home directory (without sudo) The following will install gems in `~/.gem` and put binaries in `~/bin` (which you should then add to your `PATH`). ``` gem install fakes3 --user-install -n~/bin ``` ### Make it the default Either way, you can add these parameters to your `~/.gemrc` so you don't have to remember them: ``` gem: -n/usr/local/bin ``` i.e. `echo "gem: -n/usr/local/bin" >> ~/.gemrc` **or** ``` gem: --user-install -n~/bin ``` i.e. `echo "gem: --user-install -n~/bin" >> ~/.gemrc` (*Tip:* You can also throw in `--no-document` to skip generating Ruby developer documentation.)
I had to `rm -rf ./vendor` then run `bundle install` again.
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
That is because of the new security function of OS X "El Capitan". Try adding `--user-install` instead of using sudo: ``` $ gem install *** --user-install ``` For example, if you want to install fake3 just use: ``` $ gem install fake3 --user-install ```
As it have been said, the issue comes from a security function of Mac OSX since "El Capitan". Using the default system Ruby, the install process happens in the `/Library/Ruby/Gems/2.0.0` directory which is not available to the user and gives the error. You can have a look to your Ruby environments parameters with the command ``` $ gem env ``` There is an INSTALLATION DIRECTORY and a USER INSTALLATION DIRECTORY. To use the user installation directory instead of the default installation directory, you can use `--user-install` parameter instead as using `sudo` which is never a recommanded way of doing. ``` $ gem install myGemName --user-install ``` There should not be any rights issue anymore in the process. The gems are then installed in the user directory : `~/.gem/Ruby/2.0.0/bin` But to make the installed gems available, this directory should be available in your path. According to the [Ruby’s faq](http://guides.rubygems.org/faqs/#user-install), you can add the following line to your `~/.bash_profile` or `~/.bashrc` ``` if which ruby >/dev/null && which gem >/dev/null; then PATH="$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH" fi ``` Then close and reload your terminal or reload your `.bash_profile` or `.bashrc` (`. ~/.bash_profile`)
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
As it have been said, the issue comes from a security function of Mac OSX since "El Capitan". Using the default system Ruby, the install process happens in the `/Library/Ruby/Gems/2.0.0` directory which is not available to the user and gives the error. You can have a look to your Ruby environments parameters with the command ``` $ gem env ``` There is an INSTALLATION DIRECTORY and a USER INSTALLATION DIRECTORY. To use the user installation directory instead of the default installation directory, you can use `--user-install` parameter instead as using `sudo` which is never a recommanded way of doing. ``` $ gem install myGemName --user-install ``` There should not be any rights issue anymore in the process. The gems are then installed in the user directory : `~/.gem/Ruby/2.0.0/bin` But to make the installed gems available, this directory should be available in your path. According to the [Ruby’s faq](http://guides.rubygems.org/faqs/#user-install), you can add the following line to your `~/.bash_profile` or `~/.bashrc` ``` if which ruby >/dev/null && which gem >/dev/null; then PATH="$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH" fi ``` Then close and reload your terminal or reload your `.bash_profile` or `.bashrc` (`. ~/.bash_profile`)
You might have two options: 1. If you've installed ruby and rails, you can first try running the command: ``` rvm fix-permissions ``` 2. You can uninstall ruby completely, and reinstall in your `~` directory aka your home directory. If you're using homebrew the command is: ``` brew uninstall ruby ``` For rails uninstall without homebrew the command is: ``` rvm remove ``` This should reinstall the latest ruby by running command: ``` curl -L https://get.rvm.io | bash -s stable --rails<br> ``` Mac has 2.6.3 factory installed, and it's required... if not run this command: ``` rvm install "ruby-2.6.3" ``` and then: ``` gem install rails ``` You'll get a few error messages at the end saying you have to add some other bundles... **Just make sure you're in the home `~` directory when you're installing so the permissions won't be an issue, but just in case...** I again ran: ``` rvm fix-permissions ``` and: ``` rvm debug ``` which told me I had to download yarn, I didn't save the output for it. Basically I did whatever the prompt told me to do if it had to do with my OS. -D
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
``` sudo gem install -n /usr/local/bin cocoapods ``` Try this. It will definately work.
Looks like when upgrading to OS X El Capitain, the /usr/local directory is modified in multiple ways : 1. user permissions are reset (this is also a problem for people using Homebrew) 2. binaries and symlinks might have been deleted or altered [Edit] There's also a preliminary thing to do : upgrade Xcode... Solution for #1 : ================= ``` $ sudo chown -R $(whoami):admin /usr/local ``` This will fix permissions on the `/usr/local` directory which will then help both `gem install` and `brew install|link|...` commands working properly. Solution to #2 : ================ Ruby based issues ----------------- Make sure you have fixed the permissions of the `/usr/local` directory (see #1 above) First try to reinstall your gem using : ``` sudo gem install <gemname> ``` Note that it will install the latest version of the specified gem. If you don't want to face backward-compatibility issues, I suggest that you first determine which version of which gem you want to get and then reinstall it with the `-v version`. See an exemple below to make sure that the system won't get a new version of capistrano. ``` $ gem list | grep capistrano capistrano (3.4.0, 3.2.1, 2.14.2) $ sudo gem install capistrano -v 3.4.0 ``` Brew based issues ----------------- Update brew and upgrade your formulas ``` $ brew update $ brew upgrade ``` You might also need to re-link some of them manually ``` $ brew link <formula> ```
31,972,983
I've created a simple timer class which counts down from 20 to zero unless its timerStop variable is set to true, and updates a JTextFiled in an Array of GUIs after each second. Every time the timer is used a new GameTimer is created and passed to a new Thread. PROBLEM: The first run of the timer executes as expected but subsequent instances will start by updating the GUI text field with the last value of the previous timer (the number it was stopped on) before counting down from 20 as it should. I've tried resetting the variable back to 20 at the end of the code and printing out the value as a test, and the variable does indeed print "20", but still the GUI updates the previous stop time when the next instance is run. I'm using Netbeans IDE 8.0.2 Really appreciate any advice and tips about my code, Thanks! ``` public class GameTimer implements Runnable { private volatile int secondsLeft; private MultiTextGUI[] guis; private boolean timerStop; public GameTimer(MultiTextGUI[] MTguis) { secondsLeft = 20; guis = MTguis; timerStop = false; } public void setTimerStop(boolean stop) { timerStop = stop; } @Override public void run() { while (secondsLeft > 0 && !timerStop) { try { Thread.sleep(1000); } catch (Exception e) { System.out.println("Error: " + e.toString()); } secondsLeft--; System.out.println(secondsLeft); //TEST for (MultiTextGUI gui: guis) { if (secondsLeft > 0) { if (gui != null) { gui.updateTimer(secondsLeft); } } else { if (gui != null) { gui.setTimerOn(false); } } } } secondsLeft = 20; System.out.println(secondsLeft); //TEST } } ``` Main Thread: ``` GameTimer gt = new GameTimer(g); Thread timerThread = new Thread(gt); timerThread.start(); //code to show timer in gui //code for countdownlatch gt.setTimerStop(true); ```
2015/08/12
[ "https://Stackoverflow.com/questions/31972983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965561/" ]
**Disclaimer:** @theTinMan and other Ruby developers often point out not to use `sudo` when installing gems and point to things like [RVM](http://rvm.io/rvm/install). That's absolutely true when doing Ruby development. Go ahead and use that. However, many of us just want some binary that happens to be distributed as a gem (e.g. `fakes3`, `cocoapods`, `xcpretty` …). I definitely don't want to bother with managing a separate ruby. Here are your quicker options: ### Option 1: Keep using sudo Using `sudo` is probably fine if you want these tools to be installed globally. The problem is that these binaries are installed into `/usr/bin`, which is [off-limits](https://en.wikipedia.org/wiki/System_Integrity_Protection) since El Capitan. However, you can install them into `/usr/local/bin` instead. That's where [Homebrew](http://brew.sh) install its stuff, so it [probably](https://apple.stackexchange.com/questions/157979/usr-local-doesnt-exist-in-fresh-install-yosemite) exists already. ``` sudo gem install fakes3 -n/usr/local/bin ``` Gems will be installed into `/usr/local/bin` and every user on your system can use them if it's in their [PATH](https://stackoverflow.com/a/10343891/168939). ### Option 2: Install in your home directory (without sudo) The following will install gems in `~/.gem` and put binaries in `~/bin` (which you should then add to your `PATH`). ``` gem install fakes3 --user-install -n~/bin ``` ### Make it the default Either way, you can add these parameters to your `~/.gemrc` so you don't have to remember them: ``` gem: -n/usr/local/bin ``` i.e. `echo "gem: -n/usr/local/bin" >> ~/.gemrc` **or** ``` gem: --user-install -n~/bin ``` i.e. `echo "gem: --user-install -n~/bin" >> ~/.gemrc` (*Tip:* You can also throw in `--no-document` to skip generating Ruby developer documentation.)
Reinstalling RVM worked for me, but I had to reinstall all of my gems afterward: ``` rvm implode \curl -sSL https://get.rvm.io | bash -s stable --ruby rvm reload ```
401,939
I am wondering which API url scheme should I use. I am designing multi-site project so that the URL can looks like: ``` [GET] /website/1 [GET] /website/1/category [GET] /website/1/product ``` Which is life saving since we inject the root website id for the resources we want to list **but** there are cases when this is not important, mainly during update or delete: ``` [PUT] /website/1/category/1234 ``` This way I would only make the backend server code execution longer since I don't need the website `id` to update category `1234`. This could be as good as ``` [PUT] /category/1234 ``` Is there any decent argument for choosing one over another solution? I don't see the `/website/1/category/1234` as consistency example since it's a consistency that generates a boilerplate execution.
2019/12/02
[ "https://softwareengineering.stackexchange.com/questions/401939", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/320543/" ]
There are two (main) schools of thought on this. The first is that you create URIs that are human readable and that you can construct from an understanding of the structure. The other is that URIs should not be (or need not be) understandable or 'constructable'. In the latter school, all URIs are retrieved from the server by traversing from a root resource as you describe in the first part of the question. If you (or your team/client) are in the first school, the first option is probably more preferable because the second is inconsistent. If you are in the second school, it doesn't matter either way because no one should be attempting to construct the paths. You would just return the ids of the categories in your `GET` directory listings and on `POST` calls that create those resources. The one practical advantage of the first approach in both cases is that provides a minimal protect from errors or nefarious guessing. For example, if your id's are sequential, a user on one site can guess at URIs belonging to another site.
Another way to look at this is what can be a base URI and can `/website/1/` be a base URI? Please have a look at [Establishing a Base URI](https://www.rfc-editor.org/rfc/rfc3986#page-28). There are several ways to decide how a URI can be considered as Base URI. Specifically to your question, if somehow a client received e.g. `http://example.site/website/1` to retrieve a website and website is not part of some other entity, then that can be a Base URI.
139,006
I have a Asus EEE PC Netbook, 1015CX. I have created a bootable usb to try Ubuntu and to test how it looks. The main problem is that the screen resolution is locked at 800x600 where as my netbook usually runs at 1024 minimum. How can I change it? I see no option in the menu.
2012/05/18
[ "https://askubuntu.com/questions/139006", "https://askubuntu.com", "https://askubuntu.com/users/64466/" ]
Type "Displays" in the dash or click on the computer icon in the top right corner and select the second item in the menu.
Try launching the "Displays" control applet. If X thinks you can change your resolution, you can do it here.
139,006
I have a Asus EEE PC Netbook, 1015CX. I have created a bootable usb to try Ubuntu and to test how it looks. The main problem is that the screen resolution is locked at 800x600 where as my netbook usually runs at 1024 minimum. How can I change it? I see no option in the menu.
2012/05/18
[ "https://askubuntu.com/questions/139006", "https://askubuntu.com", "https://askubuntu.com/users/64466/" ]
Mik: tried xrandr -s 1024x600 (which this netbook runs at in Windows) and got: "size 1024x600 not found in available modes" Zigg: In Lubunut, 'monitor settings applet only offers 800x600 Right,just found this, which may be the solution: [Support for Intel GMA 3600](http://ubuntuforums.org/showpost.php?p=11976680&postcount=97) I'll try it, when I'm feeling calm and I've had a strong cup of tea. But if anyone wants to send me an easier way to get 1024x600, shoot,
Try launching the "Displays" control applet. If X thinks you can change your resolution, you can do it here.
139,006
I have a Asus EEE PC Netbook, 1015CX. I have created a bootable usb to try Ubuntu and to test how it looks. The main problem is that the screen resolution is locked at 800x600 where as my netbook usually runs at 1024 minimum. How can I change it? I see no option in the menu.
2012/05/18
[ "https://askubuntu.com/questions/139006", "https://askubuntu.com", "https://askubuntu.com/users/64466/" ]
You can even use custom resolution with this method. It really works for me. <http://dfourtheye.blogspot.in/2013/04/ubuntu-screen-custom-resolution.html>
Try launching the "Displays" control applet. If X thinks you can change your resolution, you can do it here.
139,006
I have a Asus EEE PC Netbook, 1015CX. I have created a bootable usb to try Ubuntu and to test how it looks. The main problem is that the screen resolution is locked at 800x600 where as my netbook usually runs at 1024 minimum. How can I change it? I see no option in the menu.
2012/05/18
[ "https://askubuntu.com/questions/139006", "https://askubuntu.com", "https://askubuntu.com/users/64466/" ]
Type "Displays" in the dash or click on the computer icon in the top right corner and select the second item in the menu.
Mik: tried xrandr -s 1024x600 (which this netbook runs at in Windows) and got: "size 1024x600 not found in available modes" Zigg: In Lubunut, 'monitor settings applet only offers 800x600 Right,just found this, which may be the solution: [Support for Intel GMA 3600](http://ubuntuforums.org/showpost.php?p=11976680&postcount=97) I'll try it, when I'm feeling calm and I've had a strong cup of tea. But if anyone wants to send me an easier way to get 1024x600, shoot,
139,006
I have a Asus EEE PC Netbook, 1015CX. I have created a bootable usb to try Ubuntu and to test how it looks. The main problem is that the screen resolution is locked at 800x600 where as my netbook usually runs at 1024 minimum. How can I change it? I see no option in the menu.
2012/05/18
[ "https://askubuntu.com/questions/139006", "https://askubuntu.com", "https://askubuntu.com/users/64466/" ]
Type "Displays" in the dash or click on the computer icon in the top right corner and select the second item in the menu.
You can even use custom resolution with this method. It really works for me. <http://dfourtheye.blogspot.in/2013/04/ubuntu-screen-custom-resolution.html>
14,611,727
I'm scraping content off of a public domain site (cancer.gov), and I want to reformat the markup because it's terribly formatted in a table. I have jQuery at my disposal, and I'm just trying to put it into the console so I can copy it and paste it into Vim. I've gotten as far as making an array of the `td` elements I want to make into `h3`'s, but when I try to loop over them and wrap them in `h3` tags, I get `Error: NOT_FOUND_ERR: DOM Exception 8`, which I believe is that a DOM element isn't found, which makes no sense. Check out my commented [fiddle](http://jsfiddle.net/nickcoxdotme/M4Pn5/). Bonus points: The `td`'s are all questions, and the only way I could think of to split them into array indices was to split them on the `?`, which cut out the question mark in the output. What's the best way to put them back in? ### Update If you want to check out the page and try things in the console, it's [here](http://www.cancer.gov/cancertopics/coping/chemotherapy-and-you/page2).
2013/01/30
[ "https://Stackoverflow.com/questions/14611727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/931934/" ]
Creating a jQuery object does not magically turn them into DOM elements. --- Just create on big string of HTML, and pass that to the jQuery constructor: ``` var questions = $('selector here...').text().split('?'); questions = $('<h3>' + questions.join('?</h3><h3>') + '?<h3>' ); ``` Here's your fiddle: <http://jsfiddle.net/M4Pn5/1/>
You could simply grab the content into an array and then do whatever you want with the array without the worry of the question mark. ``` var myarr = $('#Table1').find('tr:even');//even to exclude the hr rows ``` here I show some things you can do with that: ``` var myQuest = myarr.find('td:eq(0)').map(function () { return $(this).html(); });//questions var myAns = myarr.find('td:eq(1)').map(function () { return $(this).html(); });// answers //process the arrays: for (var i = 0; i < myQuest.length; i++) { alert(myQuest[i]+ myAns[i]); }; myarr.find('td:eq(0)').wrap('<h3>');//wrap the questions ```
208,956
How can I find the base current of this circuit. I was trying to find \$\beta \$ from \$(\beta+1)I\_B = I\_E \$. where \$V\_{BE}=0.7V, I\_E=0.5mA\$ ![schematic](https://i.stack.imgur.com/jJKlv.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fjJKlv.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
2016/01/01
[ "https://electronics.stackexchange.com/questions/208956", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/35407/" ]
That PNP is biased off. I suspect you really intended to put an NPN there, and exchange the E & C ?
Edit, now that you've exchanged the PNP for an NPN. Ve = (Ic \* R2)-5V. Vb = Vbe + Ve. Ib = (Vc - Vb)/ R3 **IF** your drawing is correct, then you're thinking about this too much. Vbe = 0.7V. There's a 100,000 ohm resister that the voltage appears across. I= V/R. That's the base current. BTW, the current should be flowing **out** of the base in this case.
208,956
How can I find the base current of this circuit. I was trying to find \$\beta \$ from \$(\beta+1)I\_B = I\_E \$. where \$V\_{BE}=0.7V, I\_E=0.5mA\$ ![schematic](https://i.stack.imgur.com/jJKlv.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fjJKlv.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
2016/01/01
[ "https://electronics.stackexchange.com/questions/208956", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/35407/" ]
That PNP is biased off. I suspect you really intended to put an NPN there, and exchange the E & C ?
You know the emitter current. That current through the emitter resistor gives the emitter voltage. Adding the base-emitter voltage to the known emitter voltage gives the base voltage. The difference between the collector voltage (known) and the base voltage (just calculated), divided by the base bias resistor, gives you the base current, and you can now calculate beta.
19,696,968
I’m writing a program that implements the Producer Consumer problem in Java using multithreading concepts. Below are few details how I’m supposed to do it: 1) The main thread should create a buffer with capacity specified as a command line argument. The number of producer and consumer threads are also specified as command line arguments. I’m supposed to assign a unique number to each producer and consumer thread. How do I assign a unique number to producer and consumer threads? 2) The producer thread operates in an infinite loop. It produces a data item (a string) with the following format: `<producer number>_<data item number>`. For example the 1st data item from thread number 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. How do create data items in such a format? 3) Then the Producer thread writes an entry into the producer log file (< producer number > “Generated” `<data item>`). Upon writing the log entry, it attempts to insert into the buffer. If insertion is successful, it creates an entry into the log file (`<producer number> <data item>` “Insertion successful”). How do I write such a code? Below is the Java code I wrote. ``` import java.util.*; import java.util.logging.*; public class PC2 { public static void main(String args[]) { ArrayList<Integer> queue = new ArrayList<Integer>(); int size = Integer.parseInt(args[2]); Thread[] prod = new Thread[Integer.parseInt(args[0])]; Thread[] cons = new Thread[Integer.parseInt(args[1])]; for(int i=0; i<prod.length; i++) { prod[i] = new Thread(new Producer(queue, size)); prod[i].start(); } for(int i=0; i<cons.length; i++) { cons[i] = new Thread(new Consumer(queue, size)); cons[i].start(); } } } class Producer extends Thread { private final ArrayList<Integer> queue; private final int size; public Producer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true){ for(int i=0; i<size; i++) { System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId()); try { produce(i); Thread.sleep(3000); } catch(Exception e) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e); } }} } public void produce(int i) throws InterruptedException { while(queue.size() == size) { synchronized(queue) { System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size()); queue.wait(); } } synchronized(queue) { queue.add(i); queue.notifyAll(); } } } class Consumer extends Thread { private final ArrayList<Integer> queue; private final int size; public Consumer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true) { try { System.out.println("Consumed: "+consume()); Thread.sleep(1000); } catch(Exception e) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e); } } } public int consume() throws InterruptedException { while(queue.isEmpty()) { synchronized(queue) { System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size()); queue.wait(); } } synchronized (queue) { queue.notifyAll(); System.out.println("Consumed by id "+Thread.currentThread().getId()); return (Integer) queue.remove(0); } } } ``` How can I carry out the above steps?
2013/10/31
[ "https://Stackoverflow.com/questions/19696968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201650/" ]
> > I’m supposed to assign a unique number to each producer and consumer > thread. How do I assign a unique number to producer and consumer > threads? > > > Add an instance (non-static) variable to the Producer/Consumer classes. When you initialize the new Producer/Consumer Objects, pass in the unique number. You can keep track of what number you're on with an `int counter` in your main class. > > 2) The producer thread operates in an infinite loop. It produces a > data item (a string) with the following format: < producer number >\_< > data item number > . For example the 1st data item from thread number > 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. > How do create data items in such a format? > > > Use synchronized methods and/or atomic variables. Look into Java [Concurrency](http://docs.oracle.com/javase/tutorial/essential/concurrency/). > > 3) Then the Producer thread writes an entry into the producer log file > (< producer number > “Generated” < data item >). Upon writing the log > entry, it attempts to insert into the buffer. If insertion is > successful, it creates an entry into the log file (< producer number > > < data item > “Insertion successful”). How do I write such a code? > > > My answer is the same as the previous question: read about Java concurrency. Spend an hour reading about synchronization, locks, and atomic variables and I guarantee you will easily write your program.
I tried the following which might work for you, except for the buffer condition on 3, which you can add the part of the code by yourself. Hope this helps. ``` public class Message { private String msg; public Message(String msg) { super(); this.msg = msg; } public String getMsg(){ return msg; } } import java.util.concurrent.BlockingQueue; public class Producer implements Runnable { private BlockingQueue<Message> queue; private boolean run = true; public Producer(BlockingQueue<Message> queue) { super(); this.queue = queue; } public void setRun(boolean val) { this.run = val; } @Override public void run() { int i = 0; while (run) { Message msg = new Message(Thread.currentThread().getName() + "_"+ i); try { Thread.sleep(i * 100); queue.put(msg); System.out.println("Producer: "+Thread.currentThread().getName()+" produced and added to the queue: "+msg.getMsg()); } catch (InterruptedException e) { e.printStackTrace(); } i++; if(i==10){ setRun(false); System.out.println(Thread.currentThread().getName()+" stopped"); } } } } import java.util.concurrent.BlockingQueue; public class Consumer implements Runnable{ private BlockingQueue<Message> queue; private boolean run = true; public Consumer(BlockingQueue<Message> queue) { super(); this.queue = queue; } public void setRun(boolean val){ this.run = val; } @Override public void run() { while(run){ try { Thread.sleep(100); Message msg = queue.take(); System.out.println("Consumer: "+Thread.currentThread().getName()+" generated/consumed "+msg.getMsg()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } import java.util.Scanner; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ProducerConsumerMain { public static void main(String[] args) { System.out .println("please enter the number of producer:consumer:size of the queue in order"); Scanner scan = new Scanner(System.in); Thread[] prodThreads = new Thread[scan.nextInt()]; Thread[] consThreads = new Thread[scan.nextInt()]; BlockingQueue<Message> queue = new ArrayBlockingQueue<Message>(scan.nextInt()); for (int i = 0; i < prodThreads.length; i++) { prodThreads[i] = new Thread(new Producer(queue), "" + i); prodThreads[i].start(); } for (int i = 0; i < consThreads.length; i++) { consThreads[i] = new Thread(new Consumer(queue), "" + i); consThreads[i].start(); } } } ```
19,696,968
I’m writing a program that implements the Producer Consumer problem in Java using multithreading concepts. Below are few details how I’m supposed to do it: 1) The main thread should create a buffer with capacity specified as a command line argument. The number of producer and consumer threads are also specified as command line arguments. I’m supposed to assign a unique number to each producer and consumer thread. How do I assign a unique number to producer and consumer threads? 2) The producer thread operates in an infinite loop. It produces a data item (a string) with the following format: `<producer number>_<data item number>`. For example the 1st data item from thread number 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. How do create data items in such a format? 3) Then the Producer thread writes an entry into the producer log file (< producer number > “Generated” `<data item>`). Upon writing the log entry, it attempts to insert into the buffer. If insertion is successful, it creates an entry into the log file (`<producer number> <data item>` “Insertion successful”). How do I write such a code? Below is the Java code I wrote. ``` import java.util.*; import java.util.logging.*; public class PC2 { public static void main(String args[]) { ArrayList<Integer> queue = new ArrayList<Integer>(); int size = Integer.parseInt(args[2]); Thread[] prod = new Thread[Integer.parseInt(args[0])]; Thread[] cons = new Thread[Integer.parseInt(args[1])]; for(int i=0; i<prod.length; i++) { prod[i] = new Thread(new Producer(queue, size)); prod[i].start(); } for(int i=0; i<cons.length; i++) { cons[i] = new Thread(new Consumer(queue, size)); cons[i].start(); } } } class Producer extends Thread { private final ArrayList<Integer> queue; private final int size; public Producer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true){ for(int i=0; i<size; i++) { System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId()); try { produce(i); Thread.sleep(3000); } catch(Exception e) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e); } }} } public void produce(int i) throws InterruptedException { while(queue.size() == size) { synchronized(queue) { System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size()); queue.wait(); } } synchronized(queue) { queue.add(i); queue.notifyAll(); } } } class Consumer extends Thread { private final ArrayList<Integer> queue; private final int size; public Consumer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true) { try { System.out.println("Consumed: "+consume()); Thread.sleep(1000); } catch(Exception e) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e); } } } public int consume() throws InterruptedException { while(queue.isEmpty()) { synchronized(queue) { System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size()); queue.wait(); } } synchronized (queue) { queue.notifyAll(); System.out.println("Consumed by id "+Thread.currentThread().getId()); return (Integer) queue.remove(0); } } } ``` How can I carry out the above steps?
2013/10/31
[ "https://Stackoverflow.com/questions/19696968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201650/" ]
> > I’m supposed to assign a unique number to each producer and consumer > thread. How do I assign a unique number to producer and consumer > threads? > > > Add an instance (non-static) variable to the Producer/Consumer classes. When you initialize the new Producer/Consumer Objects, pass in the unique number. You can keep track of what number you're on with an `int counter` in your main class. > > 2) The producer thread operates in an infinite loop. It produces a > data item (a string) with the following format: < producer number >\_< > data item number > . For example the 1st data item from thread number > 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. > How do create data items in such a format? > > > Use synchronized methods and/or atomic variables. Look into Java [Concurrency](http://docs.oracle.com/javase/tutorial/essential/concurrency/). > > 3) Then the Producer thread writes an entry into the producer log file > (< producer number > “Generated” < data item >). Upon writing the log > entry, it attempts to insert into the buffer. If insertion is > successful, it creates an entry into the log file (< producer number > > < data item > “Insertion successful”). How do I write such a code? > > > My answer is the same as the previous question: read about Java concurrency. Spend an hour reading about synchronization, locks, and atomic variables and I guarantee you will easily write your program.
Please refer the below code. You can change the constant values based on the command line arguments. I have tested the code, its working as per your requirement. ``` import java.util.LinkedList; import java.util.Queue; public class ProducerConsumerProblem { public static int CAPACITY = 10; // At a time maximum of 10 tasks can be // produced. public static int PRODUCERS = 2; public static int CONSUMERS = 4; public static void main(String args[]) { Queue<String> mTasks = new LinkedList<String>(); for (int i = 1; i <= PRODUCERS; i++) { Thread producer = new Thread(new Producer(mTasks)); producer.setName("Producer " + i); producer.start(); } for (int i = 1; i <= CONSUMERS; i++) { Thread consumer = new Thread(new Consumer(mTasks)); consumer.setName("Consumer " + i); consumer.start(); } } } class Producer implements Runnable { Queue<String> mSharedTasks; int taskCount = 1; public Producer(Queue<String> mSharedTasks) { super(); this.mSharedTasks = mSharedTasks; } @Override public void run() { while (true) { synchronized (mSharedTasks) { try { if (mSharedTasks.size() == ProducerConsumerProblem.CAPACITY) { System.out.println("Producer Waiting!!"); mSharedTasks.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } while (mSharedTasks.size() != ProducerConsumerProblem.CAPACITY) { try { Thread.sleep(50); } catch (InterruptedException e) { } String produceHere = Thread.currentThread().getName() + "_Item number_" + taskCount++; synchronized (mSharedTasks) { mSharedTasks.add(produceHere); System.out.println(produceHere); if (mSharedTasks.size() == 1) { mSharedTasks.notifyAll(); // Informs consumer that there // is something to consume. } } } } } } class Consumer implements Runnable { Queue<String> mSharedTasks; public Consumer(Queue<String> mSharedTasks) { super(); this.mSharedTasks = mSharedTasks; } @Override public void run() { while (true) { synchronized (mSharedTasks) { if (mSharedTasks.isEmpty()) { // Checks whether there is no task // to consume. try { mSharedTasks.wait(); // Waits for producer to produce! } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } while (!mSharedTasks.isEmpty()) { // Consumes till task list is // empty try { // Consumer consumes late hence producer has to wait...! Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (mSharedTasks) { System.out.println(Thread.currentThread().getName() + " consumed " + mSharedTasks.poll()); if (mSharedTasks.size() == ProducerConsumerProblem.CAPACITY - 1) mSharedTasks.notifyAll(); } } } } } ```
19,696,968
I’m writing a program that implements the Producer Consumer problem in Java using multithreading concepts. Below are few details how I’m supposed to do it: 1) The main thread should create a buffer with capacity specified as a command line argument. The number of producer and consumer threads are also specified as command line arguments. I’m supposed to assign a unique number to each producer and consumer thread. How do I assign a unique number to producer and consumer threads? 2) The producer thread operates in an infinite loop. It produces a data item (a string) with the following format: `<producer number>_<data item number>`. For example the 1st data item from thread number 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. How do create data items in such a format? 3) Then the Producer thread writes an entry into the producer log file (< producer number > “Generated” `<data item>`). Upon writing the log entry, it attempts to insert into the buffer. If insertion is successful, it creates an entry into the log file (`<producer number> <data item>` “Insertion successful”). How do I write such a code? Below is the Java code I wrote. ``` import java.util.*; import java.util.logging.*; public class PC2 { public static void main(String args[]) { ArrayList<Integer> queue = new ArrayList<Integer>(); int size = Integer.parseInt(args[2]); Thread[] prod = new Thread[Integer.parseInt(args[0])]; Thread[] cons = new Thread[Integer.parseInt(args[1])]; for(int i=0; i<prod.length; i++) { prod[i] = new Thread(new Producer(queue, size)); prod[i].start(); } for(int i=0; i<cons.length; i++) { cons[i] = new Thread(new Consumer(queue, size)); cons[i].start(); } } } class Producer extends Thread { private final ArrayList<Integer> queue; private final int size; public Producer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true){ for(int i=0; i<size; i++) { System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId()); try { produce(i); Thread.sleep(3000); } catch(Exception e) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e); } }} } public void produce(int i) throws InterruptedException { while(queue.size() == size) { synchronized(queue) { System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size()); queue.wait(); } } synchronized(queue) { queue.add(i); queue.notifyAll(); } } } class Consumer extends Thread { private final ArrayList<Integer> queue; private final int size; public Consumer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true) { try { System.out.println("Consumed: "+consume()); Thread.sleep(1000); } catch(Exception e) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e); } } } public int consume() throws InterruptedException { while(queue.isEmpty()) { synchronized(queue) { System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size()); queue.wait(); } } synchronized (queue) { queue.notifyAll(); System.out.println("Consumed by id "+Thread.currentThread().getId()); return (Integer) queue.remove(0); } } } ``` How can I carry out the above steps?
2013/10/31
[ "https://Stackoverflow.com/questions/19696968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201650/" ]
> > I’m supposed to assign a unique number to each producer and consumer > thread. How do I assign a unique number to producer and consumer > threads? > > > Add an instance (non-static) variable to the Producer/Consumer classes. When you initialize the new Producer/Consumer Objects, pass in the unique number. You can keep track of what number you're on with an `int counter` in your main class. > > 2) The producer thread operates in an infinite loop. It produces a > data item (a string) with the following format: < producer number >\_< > data item number > . For example the 1st data item from thread number > 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. > How do create data items in such a format? > > > Use synchronized methods and/or atomic variables. Look into Java [Concurrency](http://docs.oracle.com/javase/tutorial/essential/concurrency/). > > 3) Then the Producer thread writes an entry into the producer log file > (< producer number > “Generated” < data item >). Upon writing the log > entry, it attempts to insert into the buffer. If insertion is > successful, it creates an entry into the log file (< producer number > > < data item > “Insertion successful”). How do I write such a code? > > > My answer is the same as the previous question: read about Java concurrency. Spend an hour reading about synchronization, locks, and atomic variables and I guarantee you will easily write your program.
``` public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } } class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); } } class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); } } } class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { } } } } ```
19,696,968
I’m writing a program that implements the Producer Consumer problem in Java using multithreading concepts. Below are few details how I’m supposed to do it: 1) The main thread should create a buffer with capacity specified as a command line argument. The number of producer and consumer threads are also specified as command line arguments. I’m supposed to assign a unique number to each producer and consumer thread. How do I assign a unique number to producer and consumer threads? 2) The producer thread operates in an infinite loop. It produces a data item (a string) with the following format: `<producer number>_<data item number>`. For example the 1st data item from thread number 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. How do create data items in such a format? 3) Then the Producer thread writes an entry into the producer log file (< producer number > “Generated” `<data item>`). Upon writing the log entry, it attempts to insert into the buffer. If insertion is successful, it creates an entry into the log file (`<producer number> <data item>` “Insertion successful”). How do I write such a code? Below is the Java code I wrote. ``` import java.util.*; import java.util.logging.*; public class PC2 { public static void main(String args[]) { ArrayList<Integer> queue = new ArrayList<Integer>(); int size = Integer.parseInt(args[2]); Thread[] prod = new Thread[Integer.parseInt(args[0])]; Thread[] cons = new Thread[Integer.parseInt(args[1])]; for(int i=0; i<prod.length; i++) { prod[i] = new Thread(new Producer(queue, size)); prod[i].start(); } for(int i=0; i<cons.length; i++) { cons[i] = new Thread(new Consumer(queue, size)); cons[i].start(); } } } class Producer extends Thread { private final ArrayList<Integer> queue; private final int size; public Producer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true){ for(int i=0; i<size; i++) { System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId()); try { produce(i); Thread.sleep(3000); } catch(Exception e) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e); } }} } public void produce(int i) throws InterruptedException { while(queue.size() == size) { synchronized(queue) { System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size()); queue.wait(); } } synchronized(queue) { queue.add(i); queue.notifyAll(); } } } class Consumer extends Thread { private final ArrayList<Integer> queue; private final int size; public Consumer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true) { try { System.out.println("Consumed: "+consume()); Thread.sleep(1000); } catch(Exception e) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e); } } } public int consume() throws InterruptedException { while(queue.isEmpty()) { synchronized(queue) { System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size()); queue.wait(); } } synchronized (queue) { queue.notifyAll(); System.out.println("Consumed by id "+Thread.currentThread().getId()); return (Integer) queue.remove(0); } } } ``` How can I carry out the above steps?
2013/10/31
[ "https://Stackoverflow.com/questions/19696968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201650/" ]
For producer consumer problem best solution is BlockingQueue. I was testing a few things so designed same kind of program now modified it as per your need. See if it helps. ``` import java.util.concurrent.*; public class ThreadingExample { public static void main(String args[]){ BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<Message>(100); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new Producer(blockingQueue)); exec.execute(new Consumer(blockingQueue)); } } class Message{ private static int count=0; int messageId; Message(){ this.messageId=count++; System.out.print("message Id"+messageId+" Created "); } } class Producer implements Runnable{ private BlockingQueue<Message> blockingQueue; Producer(BlockingQueue<Message> blockingQueue){ this.blockingQueue=blockingQueue; } @Override public void run(){ while(!Thread.interrupted()){ System.out.print("Producer Started"); try { blockingQueue.put(new Message()); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Producer Done"); } } } class Consumer implements Runnable{ private BlockingQueue<Message> blockingQueue; Consumer(BlockingQueue<Message> blockingQueue){ this.blockingQueue=blockingQueue; } @Override public void run(){ while(!Thread.interrupted()){ System.out.print("Concumer Started"); try{ Message message = blockingQueue.take(); System.out.print("message Id"+message.messageId+" Consumed "); } catch(InterruptedException e){ e.printStackTrace(); } System.out.println("Concumer Done"); } } } ```
I tried the following which might work for you, except for the buffer condition on 3, which you can add the part of the code by yourself. Hope this helps. ``` public class Message { private String msg; public Message(String msg) { super(); this.msg = msg; } public String getMsg(){ return msg; } } import java.util.concurrent.BlockingQueue; public class Producer implements Runnable { private BlockingQueue<Message> queue; private boolean run = true; public Producer(BlockingQueue<Message> queue) { super(); this.queue = queue; } public void setRun(boolean val) { this.run = val; } @Override public void run() { int i = 0; while (run) { Message msg = new Message(Thread.currentThread().getName() + "_"+ i); try { Thread.sleep(i * 100); queue.put(msg); System.out.println("Producer: "+Thread.currentThread().getName()+" produced and added to the queue: "+msg.getMsg()); } catch (InterruptedException e) { e.printStackTrace(); } i++; if(i==10){ setRun(false); System.out.println(Thread.currentThread().getName()+" stopped"); } } } } import java.util.concurrent.BlockingQueue; public class Consumer implements Runnable{ private BlockingQueue<Message> queue; private boolean run = true; public Consumer(BlockingQueue<Message> queue) { super(); this.queue = queue; } public void setRun(boolean val){ this.run = val; } @Override public void run() { while(run){ try { Thread.sleep(100); Message msg = queue.take(); System.out.println("Consumer: "+Thread.currentThread().getName()+" generated/consumed "+msg.getMsg()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } import java.util.Scanner; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ProducerConsumerMain { public static void main(String[] args) { System.out .println("please enter the number of producer:consumer:size of the queue in order"); Scanner scan = new Scanner(System.in); Thread[] prodThreads = new Thread[scan.nextInt()]; Thread[] consThreads = new Thread[scan.nextInt()]; BlockingQueue<Message> queue = new ArrayBlockingQueue<Message>(scan.nextInt()); for (int i = 0; i < prodThreads.length; i++) { prodThreads[i] = new Thread(new Producer(queue), "" + i); prodThreads[i].start(); } for (int i = 0; i < consThreads.length; i++) { consThreads[i] = new Thread(new Consumer(queue), "" + i); consThreads[i].start(); } } } ```
19,696,968
I’m writing a program that implements the Producer Consumer problem in Java using multithreading concepts. Below are few details how I’m supposed to do it: 1) The main thread should create a buffer with capacity specified as a command line argument. The number of producer and consumer threads are also specified as command line arguments. I’m supposed to assign a unique number to each producer and consumer thread. How do I assign a unique number to producer and consumer threads? 2) The producer thread operates in an infinite loop. It produces a data item (a string) with the following format: `<producer number>_<data item number>`. For example the 1st data item from thread number 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. How do create data items in such a format? 3) Then the Producer thread writes an entry into the producer log file (< producer number > “Generated” `<data item>`). Upon writing the log entry, it attempts to insert into the buffer. If insertion is successful, it creates an entry into the log file (`<producer number> <data item>` “Insertion successful”). How do I write such a code? Below is the Java code I wrote. ``` import java.util.*; import java.util.logging.*; public class PC2 { public static void main(String args[]) { ArrayList<Integer> queue = new ArrayList<Integer>(); int size = Integer.parseInt(args[2]); Thread[] prod = new Thread[Integer.parseInt(args[0])]; Thread[] cons = new Thread[Integer.parseInt(args[1])]; for(int i=0; i<prod.length; i++) { prod[i] = new Thread(new Producer(queue, size)); prod[i].start(); } for(int i=0; i<cons.length; i++) { cons[i] = new Thread(new Consumer(queue, size)); cons[i].start(); } } } class Producer extends Thread { private final ArrayList<Integer> queue; private final int size; public Producer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true){ for(int i=0; i<size; i++) { System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId()); try { produce(i); Thread.sleep(3000); } catch(Exception e) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e); } }} } public void produce(int i) throws InterruptedException { while(queue.size() == size) { synchronized(queue) { System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size()); queue.wait(); } } synchronized(queue) { queue.add(i); queue.notifyAll(); } } } class Consumer extends Thread { private final ArrayList<Integer> queue; private final int size; public Consumer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true) { try { System.out.println("Consumed: "+consume()); Thread.sleep(1000); } catch(Exception e) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e); } } } public int consume() throws InterruptedException { while(queue.isEmpty()) { synchronized(queue) { System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size()); queue.wait(); } } synchronized (queue) { queue.notifyAll(); System.out.println("Consumed by id "+Thread.currentThread().getId()); return (Integer) queue.remove(0); } } } ``` How can I carry out the above steps?
2013/10/31
[ "https://Stackoverflow.com/questions/19696968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201650/" ]
For producer consumer problem best solution is BlockingQueue. I was testing a few things so designed same kind of program now modified it as per your need. See if it helps. ``` import java.util.concurrent.*; public class ThreadingExample { public static void main(String args[]){ BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<Message>(100); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new Producer(blockingQueue)); exec.execute(new Consumer(blockingQueue)); } } class Message{ private static int count=0; int messageId; Message(){ this.messageId=count++; System.out.print("message Id"+messageId+" Created "); } } class Producer implements Runnable{ private BlockingQueue<Message> blockingQueue; Producer(BlockingQueue<Message> blockingQueue){ this.blockingQueue=blockingQueue; } @Override public void run(){ while(!Thread.interrupted()){ System.out.print("Producer Started"); try { blockingQueue.put(new Message()); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Producer Done"); } } } class Consumer implements Runnable{ private BlockingQueue<Message> blockingQueue; Consumer(BlockingQueue<Message> blockingQueue){ this.blockingQueue=blockingQueue; } @Override public void run(){ while(!Thread.interrupted()){ System.out.print("Concumer Started"); try{ Message message = blockingQueue.take(); System.out.print("message Id"+message.messageId+" Consumed "); } catch(InterruptedException e){ e.printStackTrace(); } System.out.println("Concumer Done"); } } } ```
Please refer the below code. You can change the constant values based on the command line arguments. I have tested the code, its working as per your requirement. ``` import java.util.LinkedList; import java.util.Queue; public class ProducerConsumerProblem { public static int CAPACITY = 10; // At a time maximum of 10 tasks can be // produced. public static int PRODUCERS = 2; public static int CONSUMERS = 4; public static void main(String args[]) { Queue<String> mTasks = new LinkedList<String>(); for (int i = 1; i <= PRODUCERS; i++) { Thread producer = new Thread(new Producer(mTasks)); producer.setName("Producer " + i); producer.start(); } for (int i = 1; i <= CONSUMERS; i++) { Thread consumer = new Thread(new Consumer(mTasks)); consumer.setName("Consumer " + i); consumer.start(); } } } class Producer implements Runnable { Queue<String> mSharedTasks; int taskCount = 1; public Producer(Queue<String> mSharedTasks) { super(); this.mSharedTasks = mSharedTasks; } @Override public void run() { while (true) { synchronized (mSharedTasks) { try { if (mSharedTasks.size() == ProducerConsumerProblem.CAPACITY) { System.out.println("Producer Waiting!!"); mSharedTasks.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } while (mSharedTasks.size() != ProducerConsumerProblem.CAPACITY) { try { Thread.sleep(50); } catch (InterruptedException e) { } String produceHere = Thread.currentThread().getName() + "_Item number_" + taskCount++; synchronized (mSharedTasks) { mSharedTasks.add(produceHere); System.out.println(produceHere); if (mSharedTasks.size() == 1) { mSharedTasks.notifyAll(); // Informs consumer that there // is something to consume. } } } } } } class Consumer implements Runnable { Queue<String> mSharedTasks; public Consumer(Queue<String> mSharedTasks) { super(); this.mSharedTasks = mSharedTasks; } @Override public void run() { while (true) { synchronized (mSharedTasks) { if (mSharedTasks.isEmpty()) { // Checks whether there is no task // to consume. try { mSharedTasks.wait(); // Waits for producer to produce! } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } while (!mSharedTasks.isEmpty()) { // Consumes till task list is // empty try { // Consumer consumes late hence producer has to wait...! Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (mSharedTasks) { System.out.println(Thread.currentThread().getName() + " consumed " + mSharedTasks.poll()); if (mSharedTasks.size() == ProducerConsumerProblem.CAPACITY - 1) mSharedTasks.notifyAll(); } } } } } ```
19,696,968
I’m writing a program that implements the Producer Consumer problem in Java using multithreading concepts. Below are few details how I’m supposed to do it: 1) The main thread should create a buffer with capacity specified as a command line argument. The number of producer and consumer threads are also specified as command line arguments. I’m supposed to assign a unique number to each producer and consumer thread. How do I assign a unique number to producer and consumer threads? 2) The producer thread operates in an infinite loop. It produces a data item (a string) with the following format: `<producer number>_<data item number>`. For example the 1st data item from thread number 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. How do create data items in such a format? 3) Then the Producer thread writes an entry into the producer log file (< producer number > “Generated” `<data item>`). Upon writing the log entry, it attempts to insert into the buffer. If insertion is successful, it creates an entry into the log file (`<producer number> <data item>` “Insertion successful”). How do I write such a code? Below is the Java code I wrote. ``` import java.util.*; import java.util.logging.*; public class PC2 { public static void main(String args[]) { ArrayList<Integer> queue = new ArrayList<Integer>(); int size = Integer.parseInt(args[2]); Thread[] prod = new Thread[Integer.parseInt(args[0])]; Thread[] cons = new Thread[Integer.parseInt(args[1])]; for(int i=0; i<prod.length; i++) { prod[i] = new Thread(new Producer(queue, size)); prod[i].start(); } for(int i=0; i<cons.length; i++) { cons[i] = new Thread(new Consumer(queue, size)); cons[i].start(); } } } class Producer extends Thread { private final ArrayList<Integer> queue; private final int size; public Producer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true){ for(int i=0; i<size; i++) { System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId()); try { produce(i); Thread.sleep(3000); } catch(Exception e) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e); } }} } public void produce(int i) throws InterruptedException { while(queue.size() == size) { synchronized(queue) { System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size()); queue.wait(); } } synchronized(queue) { queue.add(i); queue.notifyAll(); } } } class Consumer extends Thread { private final ArrayList<Integer> queue; private final int size; public Consumer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true) { try { System.out.println("Consumed: "+consume()); Thread.sleep(1000); } catch(Exception e) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e); } } } public int consume() throws InterruptedException { while(queue.isEmpty()) { synchronized(queue) { System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size()); queue.wait(); } } synchronized (queue) { queue.notifyAll(); System.out.println("Consumed by id "+Thread.currentThread().getId()); return (Integer) queue.remove(0); } } } ``` How can I carry out the above steps?
2013/10/31
[ "https://Stackoverflow.com/questions/19696968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201650/" ]
For producer consumer problem best solution is BlockingQueue. I was testing a few things so designed same kind of program now modified it as per your need. See if it helps. ``` import java.util.concurrent.*; public class ThreadingExample { public static void main(String args[]){ BlockingQueue<Message> blockingQueue = new ArrayBlockingQueue<Message>(100); ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new Producer(blockingQueue)); exec.execute(new Consumer(blockingQueue)); } } class Message{ private static int count=0; int messageId; Message(){ this.messageId=count++; System.out.print("message Id"+messageId+" Created "); } } class Producer implements Runnable{ private BlockingQueue<Message> blockingQueue; Producer(BlockingQueue<Message> blockingQueue){ this.blockingQueue=blockingQueue; } @Override public void run(){ while(!Thread.interrupted()){ System.out.print("Producer Started"); try { blockingQueue.put(new Message()); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Producer Done"); } } } class Consumer implements Runnable{ private BlockingQueue<Message> blockingQueue; Consumer(BlockingQueue<Message> blockingQueue){ this.blockingQueue=blockingQueue; } @Override public void run(){ while(!Thread.interrupted()){ System.out.print("Concumer Started"); try{ Message message = blockingQueue.take(); System.out.print("message Id"+message.messageId+" Consumed "); } catch(InterruptedException e){ e.printStackTrace(); } System.out.println("Concumer Done"); } } } ```
``` public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } } class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); } } class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); } } } class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { } } } } ```
19,696,968
I’m writing a program that implements the Producer Consumer problem in Java using multithreading concepts. Below are few details how I’m supposed to do it: 1) The main thread should create a buffer with capacity specified as a command line argument. The number of producer and consumer threads are also specified as command line arguments. I’m supposed to assign a unique number to each producer and consumer thread. How do I assign a unique number to producer and consumer threads? 2) The producer thread operates in an infinite loop. It produces a data item (a string) with the following format: `<producer number>_<data item number>`. For example the 1st data item from thread number 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. How do create data items in such a format? 3) Then the Producer thread writes an entry into the producer log file (< producer number > “Generated” `<data item>`). Upon writing the log entry, it attempts to insert into the buffer. If insertion is successful, it creates an entry into the log file (`<producer number> <data item>` “Insertion successful”). How do I write such a code? Below is the Java code I wrote. ``` import java.util.*; import java.util.logging.*; public class PC2 { public static void main(String args[]) { ArrayList<Integer> queue = new ArrayList<Integer>(); int size = Integer.parseInt(args[2]); Thread[] prod = new Thread[Integer.parseInt(args[0])]; Thread[] cons = new Thread[Integer.parseInt(args[1])]; for(int i=0; i<prod.length; i++) { prod[i] = new Thread(new Producer(queue, size)); prod[i].start(); } for(int i=0; i<cons.length; i++) { cons[i] = new Thread(new Consumer(queue, size)); cons[i].start(); } } } class Producer extends Thread { private final ArrayList<Integer> queue; private final int size; public Producer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true){ for(int i=0; i<size; i++) { System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId()); try { produce(i); Thread.sleep(3000); } catch(Exception e) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e); } }} } public void produce(int i) throws InterruptedException { while(queue.size() == size) { synchronized(queue) { System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size()); queue.wait(); } } synchronized(queue) { queue.add(i); queue.notifyAll(); } } } class Consumer extends Thread { private final ArrayList<Integer> queue; private final int size; public Consumer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true) { try { System.out.println("Consumed: "+consume()); Thread.sleep(1000); } catch(Exception e) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e); } } } public int consume() throws InterruptedException { while(queue.isEmpty()) { synchronized(queue) { System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size()); queue.wait(); } } synchronized (queue) { queue.notifyAll(); System.out.println("Consumed by id "+Thread.currentThread().getId()); return (Integer) queue.remove(0); } } } ``` How can I carry out the above steps?
2013/10/31
[ "https://Stackoverflow.com/questions/19696968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201650/" ]
I tried the following which might work for you, except for the buffer condition on 3, which you can add the part of the code by yourself. Hope this helps. ``` public class Message { private String msg; public Message(String msg) { super(); this.msg = msg; } public String getMsg(){ return msg; } } import java.util.concurrent.BlockingQueue; public class Producer implements Runnable { private BlockingQueue<Message> queue; private boolean run = true; public Producer(BlockingQueue<Message> queue) { super(); this.queue = queue; } public void setRun(boolean val) { this.run = val; } @Override public void run() { int i = 0; while (run) { Message msg = new Message(Thread.currentThread().getName() + "_"+ i); try { Thread.sleep(i * 100); queue.put(msg); System.out.println("Producer: "+Thread.currentThread().getName()+" produced and added to the queue: "+msg.getMsg()); } catch (InterruptedException e) { e.printStackTrace(); } i++; if(i==10){ setRun(false); System.out.println(Thread.currentThread().getName()+" stopped"); } } } } import java.util.concurrent.BlockingQueue; public class Consumer implements Runnable{ private BlockingQueue<Message> queue; private boolean run = true; public Consumer(BlockingQueue<Message> queue) { super(); this.queue = queue; } public void setRun(boolean val){ this.run = val; } @Override public void run() { while(run){ try { Thread.sleep(100); Message msg = queue.take(); System.out.println("Consumer: "+Thread.currentThread().getName()+" generated/consumed "+msg.getMsg()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } import java.util.Scanner; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class ProducerConsumerMain { public static void main(String[] args) { System.out .println("please enter the number of producer:consumer:size of the queue in order"); Scanner scan = new Scanner(System.in); Thread[] prodThreads = new Thread[scan.nextInt()]; Thread[] consThreads = new Thread[scan.nextInt()]; BlockingQueue<Message> queue = new ArrayBlockingQueue<Message>(scan.nextInt()); for (int i = 0; i < prodThreads.length; i++) { prodThreads[i] = new Thread(new Producer(queue), "" + i); prodThreads[i].start(); } for (int i = 0; i < consThreads.length; i++) { consThreads[i] = new Thread(new Consumer(queue), "" + i); consThreads[i].start(); } } } ```
``` public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } } class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); } } class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); } } } class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { } } } } ```
19,696,968
I’m writing a program that implements the Producer Consumer problem in Java using multithreading concepts. Below are few details how I’m supposed to do it: 1) The main thread should create a buffer with capacity specified as a command line argument. The number of producer and consumer threads are also specified as command line arguments. I’m supposed to assign a unique number to each producer and consumer thread. How do I assign a unique number to producer and consumer threads? 2) The producer thread operates in an infinite loop. It produces a data item (a string) with the following format: `<producer number>_<data item number>`. For example the 1st data item from thread number 1 will be 1\_1 and second data item from thread number 3 will be 3\_2. How do create data items in such a format? 3) Then the Producer thread writes an entry into the producer log file (< producer number > “Generated” `<data item>`). Upon writing the log entry, it attempts to insert into the buffer. If insertion is successful, it creates an entry into the log file (`<producer number> <data item>` “Insertion successful”). How do I write such a code? Below is the Java code I wrote. ``` import java.util.*; import java.util.logging.*; public class PC2 { public static void main(String args[]) { ArrayList<Integer> queue = new ArrayList<Integer>(); int size = Integer.parseInt(args[2]); Thread[] prod = new Thread[Integer.parseInt(args[0])]; Thread[] cons = new Thread[Integer.parseInt(args[1])]; for(int i=0; i<prod.length; i++) { prod[i] = new Thread(new Producer(queue, size)); prod[i].start(); } for(int i=0; i<cons.length; i++) { cons[i] = new Thread(new Consumer(queue, size)); cons[i].start(); } } } class Producer extends Thread { private final ArrayList<Integer> queue; private final int size; public Producer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true){ for(int i=0; i<size; i++) { System.out.println("Produced: "+i+" by id " +Thread.currentThread().getId()); try { produce(i); Thread.sleep(3000); } catch(Exception e) { Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, e); } }} } public void produce(int i) throws InterruptedException { while(queue.size() == size) { synchronized(queue) { System.out.println("Queue is full "+Thread.currentThread().getName() +" is waiting, size: "+queue.size()); queue.wait(); } } synchronized(queue) { queue.add(i); queue.notifyAll(); } } } class Consumer extends Thread { private final ArrayList<Integer> queue; private final int size; public Consumer(ArrayList<Integer> queue, int size) { this.queue = queue; this.size = size; } public void run() { while(true) { try { System.out.println("Consumed: "+consume()); Thread.sleep(1000); } catch(Exception e) { Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, e); } } } public int consume() throws InterruptedException { while(queue.isEmpty()) { synchronized(queue) { System.out.println("Queue is empty "+Thread.currentThread().getName()+" is waiting, size: "+queue.size()); queue.wait(); } } synchronized (queue) { queue.notifyAll(); System.out.println("Consumed by id "+Thread.currentThread().getId()); return (Integer) queue.remove(0); } } } ``` How can I carry out the above steps?
2013/10/31
[ "https://Stackoverflow.com/questions/19696968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201650/" ]
Please refer the below code. You can change the constant values based on the command line arguments. I have tested the code, its working as per your requirement. ``` import java.util.LinkedList; import java.util.Queue; public class ProducerConsumerProblem { public static int CAPACITY = 10; // At a time maximum of 10 tasks can be // produced. public static int PRODUCERS = 2; public static int CONSUMERS = 4; public static void main(String args[]) { Queue<String> mTasks = new LinkedList<String>(); for (int i = 1; i <= PRODUCERS; i++) { Thread producer = new Thread(new Producer(mTasks)); producer.setName("Producer " + i); producer.start(); } for (int i = 1; i <= CONSUMERS; i++) { Thread consumer = new Thread(new Consumer(mTasks)); consumer.setName("Consumer " + i); consumer.start(); } } } class Producer implements Runnable { Queue<String> mSharedTasks; int taskCount = 1; public Producer(Queue<String> mSharedTasks) { super(); this.mSharedTasks = mSharedTasks; } @Override public void run() { while (true) { synchronized (mSharedTasks) { try { if (mSharedTasks.size() == ProducerConsumerProblem.CAPACITY) { System.out.println("Producer Waiting!!"); mSharedTasks.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } } while (mSharedTasks.size() != ProducerConsumerProblem.CAPACITY) { try { Thread.sleep(50); } catch (InterruptedException e) { } String produceHere = Thread.currentThread().getName() + "_Item number_" + taskCount++; synchronized (mSharedTasks) { mSharedTasks.add(produceHere); System.out.println(produceHere); if (mSharedTasks.size() == 1) { mSharedTasks.notifyAll(); // Informs consumer that there // is something to consume. } } } } } } class Consumer implements Runnable { Queue<String> mSharedTasks; public Consumer(Queue<String> mSharedTasks) { super(); this.mSharedTasks = mSharedTasks; } @Override public void run() { while (true) { synchronized (mSharedTasks) { if (mSharedTasks.isEmpty()) { // Checks whether there is no task // to consume. try { mSharedTasks.wait(); // Waits for producer to produce! } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } while (!mSharedTasks.isEmpty()) { // Consumes till task list is // empty try { // Consumer consumes late hence producer has to wait...! Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized (mSharedTasks) { System.out.println(Thread.currentThread().getName() + " consumed " + mSharedTasks.poll()); if (mSharedTasks.size() == ProducerConsumerProblem.CAPACITY - 1) mSharedTasks.notifyAll(); } } } } } ```
``` public class ProducerConsumerTest { public static void main(String[] args) { CubbyHole c = new CubbyHole(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } } class CubbyHole { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); } } class Consumer extends Thread { private CubbyHole cubbyhole; private int number; public Consumer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { int value = 0; for (int i = 0; i < 10; i++) { value = cubbyhole.get(); System.out.println("Consumer #" + this.number + " got: " + value); } } } class Producer extends Thread { private CubbyHole cubbyhole; private int number; public Producer(CubbyHole c, int number) { cubbyhole = c; this.number = number; } public void run() { for (int i = 0; i < 10; i++) { cubbyhole.put(i); System.out.println("Producer #" + this.number + " put: " + i); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { } } } } ```
65,939,751
Been struggling with the following: I have a JSON response of orders from our Ecommerce website (Shopify). I need to create a CSV from the response. Everything is fine for me until I get to the line item details. I only get the first item in the array. I have seen other solutions that showed the other array items as additional columns however I need to see these as rows. A lot of examples I have seen are also in C# which I am not great with. **Order Class** ``` Imports ChoETL Public Class Order <ChoJSONRecordField> Public Property Name As String <ChoJSONRecordField> Public Property Email As String <ChoJSONRecordField(JSONPath:="financial_status")> Public Property Financial_Status As String <ChoJSONRecordField(JSONPath:="line_items[*].title")> Public Property Title As String End Class ``` **Create CSV sub** ``` Private Shared Sub UsingPOCO() Using csv = New ChoCSVWriter("order3.csv").WithFirstLineHeader() Using json = New ChoJSONReader(Of Order)("order2.json") csv.Write(json) End Using End Using End Sub ``` **Sample JSON** ``` { "email": "[email protected]", "financial_status": "paid", "name": "#CCC94440", "line_items": [ { "title": "product1", "quantity": 3 }, { "title": "product2", "quantity": 2 }, { "title": "product3", "quantity": 1 } ] } ``` **CSV Output** [![enter image description here](https://i.stack.imgur.com/2J6jC.png)](https://i.stack.imgur.com/2J6jC.png) **What I need** [![enter image description here](https://i.stack.imgur.com/rfBFw.png)](https://i.stack.imgur.com/rfBFw.png) **OR** [![enter image description here](https://i.stack.imgur.com/31iyi.png)](https://i.stack.imgur.com/31iyi.png) **Update #1** I have found this answer on another question that seems to be on the track I want. However I can't figure out how to convert it to VB.net. The answer I believe will work is the selected answer update #2. <https://stackoverflow.com/a/57166153/2037475> **Update #2** I was able to convert the C# from the other answer to VB.net.... However I get the following error which I am still looking into: "'Select' is not a member of 'Dynamic()'" ``` Using fw = New StreamWriter("order3.csv", True) Using w = New ChoCSVWriter(fw).WithFirstLineHeader() Using r = New ChoJSONReader("order2.json").WithJSONPath("$.line_items[*]") w.Write(r.SelectMany(Function(r1) (CType(r1.line_items, Dynamic())).[Select](Function(r2) New With {r1.name, r2.title}))) End Using End Using End Using Console.WriteLine(File.ReadAllText("order3.csv")) ``` **Update 3** I dont need to stick with CHOETL its just the first thing I found that I had success with. Open to any suggestions. Thanks, Matt
2021/01/28
[ "https://Stackoverflow.com/questions/65939751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2037475/" ]
Here is working sample of it in VB.NET ``` Dim json As String json = " { ""email"": ""[email protected]"", ""financial_status"": ""paid"", ""name"": ""#CCC94440"", ""line_items"": [ { ""title"": ""product1"", ""quantity"": 3 }, { ""title"": ""product2"", ""quantity"": 2 }, { ""title"": ""product3"", ""quantity"": 1 } ] }" Dim csv As New StringBuilder Using w = New ChoCSVWriter(csv).WithFirstLineHeader() Using r = ChoJSONReader.LoadText(json) w.Write(r.SelectMany(Function(r1) (CType(r1.line_items, Object())).[Select](Function(r2) New With {r1.email, r1.financial_status, r1.name, r2.title, r2.quantity}))) End Using End Using Console.WriteLine(csv.ToString()) ``` **Output:** ``` email,financial_status,name,title,quantity [email protected],paid,#CCC94440,product1,3 [email protected],paid,#CCC94440,product2,2 [email protected],paid,#CCC94440,product3,1 ``` **UPDATE #1:** To retrieve price from shipping items ``` json = " { ""email"": ""[email protected]"", ""financial_status"": ""paid"", ""name"": ""#CCC94440"", ""line_items"": [ { ""title"": ""item0"", ""quantity"": 3 }, { ""title"": ""item1"", ""quantity"": 2 } ], ""shipping_lines"": [ { ""title"": ""Free Shipping"", ""price"": ""1.00"" } ] } " Dim csv As New StringBuilder Using w = New ChoCSVWriter(csv).WithFirstLineHeader() Using r = ChoJSONReader.LoadText(json) w.Write(r.SelectMany(Function(r1) CType(r1.line_items, Object()).[Select](Function(r2) Return New With { r1.email, r1.financial_status, r1.name, r2.title, r2.quantity, CType(r1.shipping_lines, Object())(0).price } End Function))) End Using End Using Console.WriteLine(csv.ToString()) ``` **Output:** ``` email,financial_status,name,title,quantity,price [email protected],paid,#CCC94440,item0,3,1.00 [email protected],paid,#CCC94440,item1,2,1.00 ```
To be honest, with all your emerging requirements, it's going to get messier and messier to keep trying to ram all this into a single line of LINQ... I'd head to jsonutils.com and paste the json there to turn it into VB, turn on PascalCase and JsonProperty attributes: ``` Public Class LineItem <JsonProperty("title")> Public Property Title As String <JsonProperty("quantity")> Public Property Quantity As Integer End Class Public Class ShippingLine <JsonProperty("title")> Public Property Title As String <JsonProperty("price")> Public Property Price As String End Class Public Class Example <JsonProperty("email")> Public Property Email As String <JsonProperty("financial_status")> Public Property FinancialStatus As String <JsonProperty("name")> Public Property Name As String <JsonProperty("line_items")> Public Property LineItems As LineItem() <JsonProperty("shipping_lines")> Public Property ShippingLines As ShippingLine() End Class ``` Then some loops are a tad more readable: ``` 'inside Using w.... Dim root = NewtonSoft.Json.JsonConvert.DeserializeObject(your_json_string) For Each li in root.LineItems Dim csvLineObject = New With { _ root.email, _ root.financial_status, _ root.name, _ li.title, _ li.quantity, _ root.ShippingLines.First().Price, _ root.OtherArrayMightBeEmpty.FirstOrDefault()?.OtherProperty } w.Write(csvLineObject) Next li ``` * Never used CHOETL, can probably get away with a similar construct on r (= root here)
23,477,344
I have the following code: ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta name="_csrf" th:content="${_csrf.token}"/> <!-- default header name is X-CSRF-TOKEN --> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> <title>Fileupload Test</title> </head> <body> <p th:text="${msg}"></p> <form action="#" th:action="@{/fileUpload}" method="post" enctype="multipart/form-data"> <input type="file" name="myFile"/> <input type="submit"/> </form> </body> </html> ``` I get the error HTTP 403: > > Invalid CSRF Token 'null' was found on the request parameter '\_csrf' or header 'X-CSRF-TOKEN' > > > CSRF is working if I use this line instead: ``` <form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data"> ``` But how can I achieve working CSRF if I use headers?
2014/05/05
[ "https://Stackoverflow.com/questions/23477344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2000811/" ]
``` <!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta name="_csrf" th:content="${_csrf.token}"/> <!-- default header name is X-CSRF-TOKEN --> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> ``` and ``` var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); }); $.ajax({ url: url, method: 'DELETE', success: function(result) { $('#table').bootstrapTable('remove', { field: 'id', values: [row.id] }); }, error:function(result) { console.log(result); } ``` }); Solved a problem with jquery ajax request delete .I use Spring Boot , Security and bootstrap -table .
Personally using same configuration as you (Thymleaf, Spring MVC, Spring Sec) i only was able to utilise meta csrf when uploading via ajax and direct inserts into action URL if submitting in standard fashion. So different types of forms used: e.g. ``` <form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data"> ``` for Standard submition ``` <form action="#" th:action="@{/fileUpload}" method="post" enctype="multipart/form-data"> ``` with following javascript: ``` var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); }); ``` to submit via Ajax/jQuery. Based on my recent research there doesn't seem to be a clean integration between the two and requires slight modifications to make code work.
23,477,344
I have the following code: ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta name="_csrf" th:content="${_csrf.token}"/> <!-- default header name is X-CSRF-TOKEN --> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> <title>Fileupload Test</title> </head> <body> <p th:text="${msg}"></p> <form action="#" th:action="@{/fileUpload}" method="post" enctype="multipart/form-data"> <input type="file" name="myFile"/> <input type="submit"/> </form> </body> </html> ``` I get the error HTTP 403: > > Invalid CSRF Token 'null' was found on the request parameter '\_csrf' or header 'X-CSRF-TOKEN' > > > CSRF is working if I use this line instead: ``` <form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data"> ``` But how can I achieve working CSRF if I use headers?
2014/05/05
[ "https://Stackoverflow.com/questions/23477344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2000811/" ]
After fighting with this issue for some time, I finally figured out why the code in the [official Spring documentation](https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-include-csrf-token-ajax) doesn't work... Notice the following: ``` <meta name="_csrf" content="${_csrf.token}" /> <meta name="_csrf_header" content="${_csrf.headerName}" /> ``` This is documentation with JSP in mind! Since we are using Thymeleaf, what you need to do is to use `th:content` instead of `content`: ``` <meta name="_csrf" th:content="${_csrf.token}"/> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> ``` Now it works!
Personally using same configuration as you (Thymleaf, Spring MVC, Spring Sec) i only was able to utilise meta csrf when uploading via ajax and direct inserts into action URL if submitting in standard fashion. So different types of forms used: e.g. ``` <form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data"> ``` for Standard submition ``` <form action="#" th:action="@{/fileUpload}" method="post" enctype="multipart/form-data"> ``` with following javascript: ``` var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); }); ``` to submit via Ajax/jQuery. Based on my recent research there doesn't seem to be a clean integration between the two and requires slight modifications to make code work.
23,477,344
I have the following code: ``` <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta name="_csrf" th:content="${_csrf.token}"/> <!-- default header name is X-CSRF-TOKEN --> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> <title>Fileupload Test</title> </head> <body> <p th:text="${msg}"></p> <form action="#" th:action="@{/fileUpload}" method="post" enctype="multipart/form-data"> <input type="file" name="myFile"/> <input type="submit"/> </form> </body> </html> ``` I get the error HTTP 403: > > Invalid CSRF Token 'null' was found on the request parameter '\_csrf' or header 'X-CSRF-TOKEN' > > > CSRF is working if I use this line instead: ``` <form action="#" th:action="@{/fileUpload} + '?' + ${_csrf.parameterName} + '=' + ${_csrf.token}" method="post" enctype="multipart/form-data"> ``` But how can I achieve working CSRF if I use headers?
2014/05/05
[ "https://Stackoverflow.com/questions/23477344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2000811/" ]
After fighting with this issue for some time, I finally figured out why the code in the [official Spring documentation](https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-include-csrf-token-ajax) doesn't work... Notice the following: ``` <meta name="_csrf" content="${_csrf.token}" /> <meta name="_csrf_header" content="${_csrf.headerName}" /> ``` This is documentation with JSP in mind! Since we are using Thymeleaf, what you need to do is to use `th:content` instead of `content`: ``` <meta name="_csrf" th:content="${_csrf.token}"/> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> ``` Now it works!
``` <!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta name="_csrf" th:content="${_csrf.token}"/> <!-- default header name is X-CSRF-TOKEN --> <meta name="_csrf_header" th:content="${_csrf.headerName}"/> ``` and ``` var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content"); $(document).ajaxSend(function(e, xhr, options) { xhr.setRequestHeader(header, token); }); $.ajax({ url: url, method: 'DELETE', success: function(result) { $('#table').bootstrapTable('remove', { field: 'id', values: [row.id] }); }, error:function(result) { console.log(result); } ``` }); Solved a problem with jquery ajax request delete .I use Spring Boot , Security and bootstrap -table .
10,091,918
Say I have an object ``` MyObj stuff; ``` To get the address of stuff, I would print ``` cout << &stuff << endl; 0x22ff68 ``` I want to save 0x22ff68 in a string. I know you can't do this: ``` string cheeseburger = (string) &stuff; ``` Is there a way to accomplish this?
2012/04/10
[ "https://Stackoverflow.com/questions/10091918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could use [std::ostringstream](http://www.cplusplus.com/reference/iostream/ostringstream/). See also [this question](https://stackoverflow.com/questions/8287188/stdostringstream-printing-the-address-of-the-c-string-instead-of-its-content). But don't expect the address you have to be really meaningful. It could vary from one run to the next of the same program with the same data (because of [address space layout randomization](http://en.wikipedia.org/wiki/Address_space_layout_randomization), etc.)
You can try using a string format char strAddress[] = "0x00000000"; // Note: You should allocate the correct size, here I assumed that you are using 32 bits address sprintf(strAddress, "0x%x", &stuff); Then you create your string from this char array using the normal string constructors
10,091,918
Say I have an object ``` MyObj stuff; ``` To get the address of stuff, I would print ``` cout << &stuff << endl; 0x22ff68 ``` I want to save 0x22ff68 in a string. I know you can't do this: ``` string cheeseburger = (string) &stuff; ``` Is there a way to accomplish this?
2012/04/10
[ "https://Stackoverflow.com/questions/10091918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could use [std::ostringstream](http://www.cplusplus.com/reference/iostream/ostringstream/). See also [this question](https://stackoverflow.com/questions/8287188/stdostringstream-printing-the-address-of-the-c-string-instead-of-its-content). But don't expect the address you have to be really meaningful. It could vary from one run to the next of the same program with the same data (because of [address space layout randomization](http://en.wikipedia.org/wiki/Address_space_layout_randomization), etc.)
Here's a way to save the address of a pointer to a string and then convert the address back to a pointer. I did this as a proof of concept that `const` didn't really offer any protection, but I think it answers this question well. ``` #include <iostream> #include <string> #include <sstream> using namespace std; int main() { // create pointer to int on heap const int *x = new int(5); // *x = 3; - this fails because it's constant // save address as a string // ======== this part directly answers your question ========= ostringstream get_the_address; get_the_address << x; string address = get_the_address.str(); // convert address to base 16 int hex_address = stoi(address, 0, 16); // make a new pointer int * new_pointer = (int *) hex_address; // can now change value of x *new_pointer = 3; return 0; } ```
875,578
I have code that looks like this: ``` template<class T> class list { public: class iterator; }; template<class T> class list::iterator { public: iterator(); protected: list* lstptr; }; list<T>::iterator::iterator() { //??? } ``` I want to make the constructor of `list::iterator` to make `iterator::lstptr` point to the list it's called from. I.e.: ``` list xlst; xlst::iterator xitr; //xitr.lstptr = xlst ``` How would I do that? And also, am I referencing my iterator-constructor right, or should I do something like this: ``` template<class T> class list<T>::iterator { public: list<T>::iterator(); protected: list* lstptr; }; ```
2009/05/17
[ "https://Stackoverflow.com/questions/875578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can pass the list to the constructor of iterator: ``` list xlst; list::iterator xitr(xlst); ``` Or, you could make an iterator factory function: ``` list xlst; list::iterator xitr = xlst.create_iter(); ``` In the factory function case, the `create_iter()` function can use `this` to refer to the enclosing list.
Since you don't need to change (reseat) the pointer and there's no need for the NULL value, I would instead use a reference. Also you can use an initializer list when assigning the member variable (and have to if you're using a reference). ``` template<class T> class list::iterator { public: iterator( list& parent ) : lstptr( parent ){} protected: list& lstptr; }; ``` And as mentioned before: use a factory method inside the list class to construct objects of type list::iterator.
36,496,998
I created a task link and a contextual one for base\_route: entity.node.canonical mymodule.routing.yml ``` mymodule.mycustomroute: path: '/node/{node}/custom-path' defaults: _form: '\Drupal\mymodule\Form\MyForm' requirements: _permission: 'my permission' node: '[0-9]+' ``` mymodule.links.tasks.yml ``` mymodule.mycustomroute: route_name: mymodule.mycustomroute base_route: entity.node.canonical title: 'my title' ``` mymodule.links.contextual.yml ``` mymodule.mycustomroute: route_name: mymodule.mycustomroute group: node ``` My link shows up next to View / Edit / Delete links on each node as I wanted. Now I am wondering how is it possible to make these links available only for specific node type(s)?
2016/04/08
[ "https://Stackoverflow.com/questions/36496998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3493566/" ]
**mymodule/mymodule.routing.yml** : ``` mymodule.mycustomroute: path: '/node/{node}/custom-path' defaults: _form: '\Drupal\mymodule\Form\MyForm' requirements: _permission: 'my permission' _custom_access: '\Drupal\mymodule\Access\NodeTypeAccessCheck::access' _node_types: 'node_type_1,node_type_2,node_type_n' node: '\d+' ``` **mymodule/src/Access/NodeTypeAccessCheck.php** : ``` namespace Drupal\mymodule\Access; use Drupal\Core\Access\AccessCheckInterface; use Drupal\Core\Access\AccessResult; use Drupal\node\NodeInterface; use Symfony\Component\Routing\Route; /** * Check the access to a node task based on the node type. */ class NodeTypeAccessCheck implements AccessCheckInterface { /** * {@inheritdoc} */ public function applies(Route $route) { return NULL; } /** * A custom access check. * * @param \Drupal\node\NodeInterface $node * Run access checks for this node. */ public function access(Route $route, NodeInterface $node) { if ($route->hasRequirement('_node_types')) { $allowed_node_types = explode(',', $route->getRequirement('_node_types')); if (in_array($node->getType(), $allowed_node_types)) { return AccessResult::allowed(); } } return AccessResult::forbidden(); } } ```
Or you can specify route parameters in the mymodule.links.menu.yml file: ``` mymodule.add_whatever: title: 'Add whatever' description: 'Add whatever' route_name: node.add route_parameters: { node_type: 'name_of_node_type' } menu_name: main weight: 7 ```
55,376,142
The issue i am facing is that when i click on active button all the article's active button change to inactive.. i want to change the status of that article id which i set to inactive from active. All articles will remain active or inactive as described status in database.how i can get this? If i Inactive Article button changes to Inactive of that article which is clicked not all articles and when i refresh page all articles status set to Active but in database their status changed to inactive. Html: ``` <button class="btn btn-sm btn-danger delete-article-btn" onclick="deleteArticle({{$article['aID']}})">Active </button> ``` Script: ``` <script> function deleteArticle(id) { $.ajax({ url: '{!! URL('/pay/dash/panel/delete_article') !!}', type: 'post', dataType: 'json', data: {'user_id': id}, success: function (response) { console.log(response); console.log('Article ID',id); if (response == 1) { $('.delete-article-btn').html('Inactive'); } else { $('.delete-article-btn').html('Active'); } }, error: function (error) { } }); } </script> ``` Controller: ``` public function deleteArticles(Request $request) { $userId = $request->input('user_id'); $result = 0; $checkArticle = Article::where('id', $userId)->where('is_deleted',0)->get(); if (count($checkArticle)>0) { Article::where('id', $userId)->update(['is_deleted' => 1]); $result = 1; } else { Article::where('id', $userId)->update(['is_deleted' => 0]); $result = 0; } return $result; } ```
2019/03/27
[ "https://Stackoverflow.com/questions/55376142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
```html <button class="btn btn-sm btn-danger delete-article-btn mybtn-{{$article['aID']}}" rel="{{ $article['aID'] }}" rel2="1">Active </button> ``` ```js <script> $(document).on('click','.delete-article-btn',function(){ var id = $(this).attr('rel'); var status = $(this).attr('rel2'); $.ajax({ url: '{!! URL('/pay/dash/panel/delete_article') !!}', type: 'post', dataType: 'json', data: {'user_id': id,'status':status}, success: function (response) { console.log(response); console.log('Article ID',id); if (response == 1) { $('.mybtn-'+id).html('Inactive'); $('.mybtn-'+id).attr('rel2',0); } else { $('.mybtn-'+id).html('Active'); $('.mybtn-'+id).attr('rel2',1); } }, error: function (error) { } }); }) </script> ``` ```php public function deleteArticles(Request $request) { $userId = $request->input('user_id'); $status = $request->input('status'); $result = 0; if ($status==0) { Article::where('id', $userId)->update(['is_deleted' => 1]); $result = 1; } else { Article::where('id', $userId)->update(['is_deleted' => 0]); $result = 0; } return $result; } ```
You are changing the the html content of all the buttons with the class ".delete-article-btn" ``` if (response == 1) { $('.delete-article-btn').html('Inactive'); } else { $('.delete-article-btn').html('Active'); } ``` You have to specify which button you have to update maybe with a data attribute, as you prefer.. ``` if (response == 1) { $('.delete-article-btn[data-id=X]').html('Inactive'); } else { $('.delete-article-btn[data-id=X]').html('Active'); } ``` Also, server side it seems you are targetting ALL articles from an user, i think you have to get only the Article you want to disable or not.
30,288,360
I wrote this code, but I can't handle with ".?!" and other combination of such characters? Could someone help me? I need to count the sentences in a line. ``` #include<stdlib.h> #include<string.h> #include<stdio.h> int main(){ int say=0,i; char line[250]; gets(line); int k = strlen(line); for(i=0; i<k; i++){ if(line[i]=='.' || line[i]=='?' || line[i]=='!'){ say++; } } printf("%d\n",say); return 0; } ```
2015/05/17
[ "https://Stackoverflow.com/questions/30288360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3017046/" ]
The Jinja template folder for app dirs defaults to `jinja2` not the standard `templates` folder. So try the following directory structure and Django will locate your Jinja templates: ``` mysite mysite myapp jinja2 myapp index.html manage.py ```
Another thing to consider is that render\_to\_response can not take a context\_instance for jinja2 templates <https://github.com/django-haystack/django-haystack/issues/1163> I believe, but I might be wrong, but I think jinja2 can't share the same directory as the django templates. try ``` TEMPLATES = { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(PROJECT_ROOT, 'jinja2'),], 'APP_DIRS': True, } ```
30,288,360
I wrote this code, but I can't handle with ".?!" and other combination of such characters? Could someone help me? I need to count the sentences in a line. ``` #include<stdlib.h> #include<string.h> #include<stdio.h> int main(){ int say=0,i; char line[250]; gets(line); int k = strlen(line); for(i=0; i<k; i++){ if(line[i]=='.' || line[i]=='?' || line[i]=='!'){ say++; } } printf("%d\n",say); return 0; } ```
2015/05/17
[ "https://Stackoverflow.com/questions/30288360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3017046/" ]
Another thing to consider is that render\_to\_response can not take a context\_instance for jinja2 templates <https://github.com/django-haystack/django-haystack/issues/1163> I believe, but I might be wrong, but I think jinja2 can't share the same directory as the django templates. try ``` TEMPLATES = { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [os.path.join(PROJECT_ROOT, 'jinja2'),], 'APP_DIRS': True, } ```
The Jinja template folder for app dirs defaults to jinja2 not the standard templates folder. So try the following directory structure and Django will locate your Jinja templates: mysite mysite myapp jinja2 myapp index.html manage.py And instead of: return render(request, 'myapp/index.html') you should write: return render(request, 'index.html')
30,288,360
I wrote this code, but I can't handle with ".?!" and other combination of such characters? Could someone help me? I need to count the sentences in a line. ``` #include<stdlib.h> #include<string.h> #include<stdio.h> int main(){ int say=0,i; char line[250]; gets(line); int k = strlen(line); for(i=0; i<k; i++){ if(line[i]=='.' || line[i]=='?' || line[i]=='!'){ say++; } } printf("%d\n",say); return 0; } ```
2015/05/17
[ "https://Stackoverflow.com/questions/30288360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3017046/" ]
The Jinja template folder for app dirs defaults to `jinja2` not the standard `templates` folder. So try the following directory structure and Django will locate your Jinja templates: ``` mysite mysite myapp jinja2 myapp index.html manage.py ```
The Jinja2 template backend searches the `jinja2` folder in the app directories, instead of `templates`. This has the advantange of preventing DTL and Jinja2 templates from being confused, especially if you enable multiple templating engines in your project. I would recommend sticking with the default behaviour, and renaming your `templates` directory to `jinja2`. However, if you must change it, you could create a custom backend, and set `app_dirname`. ``` from django.template.backends.jinja2 import Jinja2 class MyJinja2(jinja2): app_dirname = 'templates' ``` Then in your `TEMPLATES` setting, use `path.to.MyJinja2` instead of `django.template.backends.jinja2.Jinja2`.
30,288,360
I wrote this code, but I can't handle with ".?!" and other combination of such characters? Could someone help me? I need to count the sentences in a line. ``` #include<stdlib.h> #include<string.h> #include<stdio.h> int main(){ int say=0,i; char line[250]; gets(line); int k = strlen(line); for(i=0; i<k; i++){ if(line[i]=='.' || line[i]=='?' || line[i]=='!'){ say++; } } printf("%d\n",say); return 0; } ```
2015/05/17
[ "https://Stackoverflow.com/questions/30288360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3017046/" ]
The Jinja template folder for app dirs defaults to `jinja2` not the standard `templates` folder. So try the following directory structure and Django will locate your Jinja templates: ``` mysite mysite myapp jinja2 myapp index.html manage.py ```
The Jinja template folder for app dirs defaults to jinja2 not the standard templates folder. So try the following directory structure and Django will locate your Jinja templates: mysite mysite myapp jinja2 myapp index.html manage.py And instead of: return render(request, 'myapp/index.html') you should write: return render(request, 'index.html')
30,288,360
I wrote this code, but I can't handle with ".?!" and other combination of such characters? Could someone help me? I need to count the sentences in a line. ``` #include<stdlib.h> #include<string.h> #include<stdio.h> int main(){ int say=0,i; char line[250]; gets(line); int k = strlen(line); for(i=0; i<k; i++){ if(line[i]=='.' || line[i]=='?' || line[i]=='!'){ say++; } } printf("%d\n",say); return 0; } ```
2015/05/17
[ "https://Stackoverflow.com/questions/30288360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3017046/" ]
The Jinja2 template backend searches the `jinja2` folder in the app directories, instead of `templates`. This has the advantange of preventing DTL and Jinja2 templates from being confused, especially if you enable multiple templating engines in your project. I would recommend sticking with the default behaviour, and renaming your `templates` directory to `jinja2`. However, if you must change it, you could create a custom backend, and set `app_dirname`. ``` from django.template.backends.jinja2 import Jinja2 class MyJinja2(jinja2): app_dirname = 'templates' ``` Then in your `TEMPLATES` setting, use `path.to.MyJinja2` instead of `django.template.backends.jinja2.Jinja2`.
The Jinja template folder for app dirs defaults to jinja2 not the standard templates folder. So try the following directory structure and Django will locate your Jinja templates: mysite mysite myapp jinja2 myapp index.html manage.py And instead of: return render(request, 'myapp/index.html') you should write: return render(request, 'index.html')
3,022,656
How to understand why the set of nonsigular matrices is a differentiable submanifold of the the of matrices (of size $n$). I thought of introducing, given a nonsingular matrix $A$, the mapping $f:X\mapsto \det(X)-\det(A)$. But from this on I do not know how to proceed. Also, how to determine the tangent space at a point $A$?
2018/12/02
[ "https://math.stackexchange.com/questions/3022656", "https://math.stackexchange.com", "https://math.stackexchange.com/users/600438/" ]
The idea is that the singular matrices in $M\_{m \times q}(\Bbb R)$ form a closed subset, as they constitute precisely the subset $\text{det}^{-1}(\{0\})$, and $\text{det}$ is a continuous function on $M\_{m \times q}(\Bbb R)$. So the subset of nonsingular matrices is the open set $M\_{m \times q}(\Bbb R) \setminus \text{det}^{-1}(\{0\})$, and any open subset of a Euclidean space is a submanifold of the same dimension (in this case, $mq$). For any nonsingular matrix $\mathbf{A}$, the tangent space to $\mathbf{A}$ in this open set is the same as $T\_{\mathbf{A}} M\_{m \times q}(\Bbb R)$, which can be identified with $\Bbb R^{mq}$. --- More generally, let $\Sigma\_k \subset M\_{m \times q}(\Bbb R)$ be the space of matrices of rank $k$. For any matrix $\mathbf{A}$ in $\Sigma\_k$, there is a $(k \times k)$-minor, let's call it $A$, in $\mathbf{A}$ which is nonsingular, and let the rest of the elements be arranged in three matrices $B\_{k \times (q-k)}$, $C\_{(m-k) \times k}$ and $D\_{(m-k)\times(q-k)}$, where the arrangement is done by performing $k$ row operations $E\_1$ and $k$ column operations $E\_2$ so that in $E\_2E\_1 \mathbf{A}$, the minor $A$ is positioned at the upper left corner of the matrix, and $B, C, D$ are the other blocks. Since nonsingular matrices form an open subset, there is a neighborhood $U$ of $\mathbf{A}$ in $M\_{m \times q}(\Bbb R)$ where for any $\mathbf{A}\_0 \in U$, the $(k \times k)$-minor situated in the same position that $A$ is situated in $\mathbf{A}$ is also nonsingular. Therefore, the blocks $A, B, C, D$ of $\mathbf{A}$ are globally defined for every matrix in the open neighborhood $U$ of $\mathbf{A}$. Let $\mathbf{X} \in U$ be arbitrary and let $A, B, C, D$ be the blocks of $\mathbf{X}$ as defined above. Notice that $$\mathbf{X} \cdot \begin{pmatrix} I & -A^{-1}B \\ \mathsf{O} & I \end{pmatrix} = \begin{pmatrix} A & \mathsf{O} \\ C & D - CA^{-1}B \end{pmatrix}$$ Since the matrix we multiplied with is invertible, rank has remained unchanged. If $D - CA^{-1}B$ was nonzero we would have found a row in the bottom $(m-k)$-half of the matrix with a nonzero entry at one of the last $(q-k)$-th positions. This would then be linearly independent from the first $k$ rows of the matrix (as their last $(q-k)$ entries are all zero), which are themselves linearly independent by hypothesis on the minor $A$. That makes $\text{rank}(\mathbf{X}) \geq k+1$, absurd. Therefore $D - CA^{-1}B = \mathsf{O}$ is a necessary condition for $\text{rank}(\mathbf{X}) = k$. Once this condition holds the matrix above will have $k$ columns of vectors in $\Bbb R^m$ whose projection to the first $q$ coordinates are linearly independent, hence are themselves linearly independent. So consider the map $F : U \to M\_{(m-k)(q-k)}(\Bbb R)$ given by $F(\mathbf{X})= D - CA^{-1}B$. It's an easy check that $F$ is a smooth submersion, so $F^{-1}(\mathsf{O}) = U \cap \Sigma\_k$ is a submanifold of codimension $(m-k)(q-k)$ in $U$, which proves that $\Sigma\_k$ is a submanifold of $M\_{m \times q}(\Bbb R)$. This is not a closed, but a locally closed submanifold, of $M\_{m \times q}(\Bbb R)$, and the closure $\overline{\Sigma\_k}$ is precisely the subset of rank $\leq k$ matrices in $M\_{m \times q}(\Bbb R)$. This can be seen by taking any matrix $\mathbf{M}$ with $\text{rank}(\mathbf{M}) = l < k$, which implies the $q$ column vectors $v\_1, \cdots, v\_q$ span a subspace of dimension $l$ in $\Bbb R^q$. Without loss of generality suppose $v\_1, \cdots, v\_l$ is a basis of this subspace. Then $\text{Span}(v\_{l+1}), \cdots, \text{Span} (v\_{l+k})$ belong to this $l$-dimensional subspace; by a small perturbation in $\Bbb R^q$ we can make them transverse to this $l$-dimensional subspace as well as with themselves. Let $w\_{l+1}, \cdots, w\_{l+k}$ be the modified vectors; the matrix formed by the column vectors $v\_1, \cdots, v\_l, w\_{l+1}, \cdots, w\_{l+k}, v\_{l+k+1}, \cdots, v\_q$ is a perturbation of $\mathbf{M}$ which has rank $k$ (Note: if $k > q$, do the same argument with the $m$ rows). However, rank can never go down, as transverse subspaces remain transverse under small perturbations. Therefore, $\Sigma\_k \subset M\_{m \times q}(\Bbb R)$ are locally closed submanifolds such that $\overline{\Sigma\_k} = \Sigma\_0 \cup \cdots \cup \Sigma\_{k-1}$. This kind of iterative structure is called a *stratification*; indeed, $\Sigma\_k$'s constitute stratums for a Whitney stratification of $M\_{m \times q}(\Bbb R)$. But this was a long digression.
It is an open subspace of a vector space, $Gl(n,\mathbb{R})=det^{-1}(\mathbb{R}-\{0\}$. Here the vector space is the space of $n\times n$-matrices so it is a submaniflod with one chart which is the embedding map $Gl(n,\mathbb{R})\rightarrow M(n,\mathbb{R})$.
13,742,313
Given a table of tuples of currency and exchange rate, such as the following: ``` EUR CHF 1.20 USD EUR 0.80 CHF JPY 1.30 ``` How can I simply generate all the exchange rate between currency (A,B) and also (B,A)? I would like to have the following: ``` EUR CHF CHF EUR EUR USD USD EUR USD CHF CHF USD ``` with all the possible combinations, i.e. a rate can be derived from multiple rates by chaining them ``` A to B * B to C * C to D = A to D ```
2012/12/06
[ "https://Stackoverflow.com/questions/13742313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/701829/" ]
Though you are using `AsyncTask`, its `onPostExecute()` method is executed on UI thread (to let you update your views etc). Actually, the only method of `AsyncTask` executed in separate thread is `doInBackground()`, so you have to perform all operations involving I/O (disk, network), only in this method, otherwise you'll get an exception. Refer to [this](http://developer.android.com/reference/android/os/AsyncTask.html) for details.
From the Android Doc **android.os.NetworkOnMainThreadException** clearly stated that from `android 2.3.3` you can not call URL in main UI thread. Please cross check it and make sure you did not do this mistake **From Android Developer** The exception that is thrown when an application attempts to perform a networking operation on its main thread.This is only thrown for applications targeting the Honeycomb SDK or highe.
11,562,553
Please, share your experience in using software echo cancellers on Android: 1. Built-in (the one that appeared in v3.0, as I hear) 2. Speex 3. WebRTC 4. Etc.
2012/07/19
[ "https://Stackoverflow.com/questions/11562553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/915913/" ]
I'm just finishing the AEC work on android, I tried speex/android-built-in-ec/webrtc-aec and webrtc-aecm(echo control on mobile), and finally choose the AECM module, and there are some tips: 1. speex and webrtc-aec is not good for running on mobile(for low CPU perform reason). 2. android built-in EC is working, but the effect is not ideal, can still heard some echos or lots of self-excitation(maybe I'm not using it right). and not all the android device at this time support built-in EC, so this situation is discarded. 3. webrtc-aecm module is fine, it just took 1~2ms to process a 10ms frame. and the most important is the thing called `delay`, you should follow the description of it in [audio\_processing.h](https://chromium.googlesource.com/external/webrtc/stable/webrtc/+/b8a655ac3c71977abf0e8d657dbe9d0aec633ff9/modules/audio_processing/include/audio_processing.h) **`strictly`**, if you calculate a right value of delay, everything will be OK. **EDIT** 1. After a long long time working with WebRTC AECM(or APM), I still cannot make it work perfect on android. I think AECM need more optimazition, but Google seems no plan on it. Any way, I'll keep attention about Google WebRTC and its AECM(or AEC) performance on android. 2. (Updated on 6/23/2020) Please refer to my [GitHub project's README](https://github.com/BillHoo/webrtc-based-android-aecm), my solution above was deprecated by myself years ago. I don't want to misleading others.
There are two issues that relates to AEC on Android: 1. CPU. Most AEC algorithms does not perform well with low CPU. 2. Echo Path - many VoIP application on Android introduce echo delay that is higher than what the free algorithm can handle (efficiently). Bottom line, I suggest that you first measure the echo delay (i.e. echo tail) in your VoIP application. If it does not exceed 16ms-64ms you can try using one of the above mentioned free solutions. One more note, I believe Speex will not work good on mobile devices since as far as I know it does not have a fix-point version.
62,412,262
I am attempting to train the keras VGG-19 model on RGB images, when attempting to feed forward this error arises: ``` ValueError: Input 0 of layer block1_conv1 is incompatible with the layer: expected ndim=4, found ndim=3. Full shape received: [224, 224, 3] ``` When reshaping image to (224, 224, 3, 1) to include batch dim, and then feeding forward as shown in code, this error occurs: ``` ValueError: Dimensions must be equal, but are 1 and 3 for '{{node BiasAdd}} = BiasAdd[T=DT_FLOAT, data_format="NHWC"](strided_slice, Const)' with input shapes: [64,224,224,1], [3] ``` ``` for idx in tqdm(range(train_data.get_ds_size() // batch_size)): # train step batch = train_data.get_train_batch() for sample, label in zip(batch[0], batch[1]): sample = tf.reshape(sample, [*sample.shape, 1]) label = tf.reshape(label, [*label.shape, 1]) train_step(idx, sample, label) ``` `vgg` is intialized as: ``` vgg = tf.keras.applications.VGG19( include_top=True, weights=None, input_tensor=None, input_shape=[224, 224, 3], pooling=None, classes=1000, classifier_activation="softmax" ) ``` training function: ``` @tf.function def train_step(idx, sample, label): with tf.GradientTape() as tape: # preprocess for vgg-19 sample = tf.image.resize(sample, (224, 224)) sample = tf.keras.applications.vgg19.preprocess_input(sample * 255) predictions = vgg(sample, training=True) # mean squared error in prediction loss = tf.keras.losses.MSE(label, predictions) # apply gradients gradients = tape.gradient(loss, vgg.trainable_variables) optimizer.apply_gradients(zip(gradients, vgg.trainable_variables)) # update metrics train_loss(loss) train_accuracy(vgg, predictions) ``` I am wondering how the input should be formatted such that the keras VGG-19 implementation will accept it?
2020/06/16
[ "https://Stackoverflow.com/questions/62412262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13641853/" ]
You will have to unsqueeze one dimension to turn your shape into `[1, 224, 224, 3'`: ``` for idx in tqdm(range(train_data.get_ds_size() // batch_size)): # train step batch = train_data.get_train_batch() for sample, label in zip(batch[0], batch[1]): sample = tf.reshape(sample, [1, *sample.shape]) # added the 1 here label = tf.reshape(label, [*label.shape, 1]) train_step(idx, sample, label) ```
You use wrong dimension for the image batch, "When reshaping image to (224, 224, 3, 1) to include batch dim" -- this should be (x, 224, 224, 3), where `x` is the number of the images in the batch.
25,681,018
So I have these 3 tables: t\_student which looks like this: ``` STUDENT_ID| FIRST_NAME |LAST_NAME ----------------------------------- 1 | Ivan | Petrov 2 | Ivan | Ivanov 3 | Georgi | Georgiev ``` t\_course which looks like this: ``` course_id | NAME |LECTURER_NAME ----------------------------------- 1 | Basics | Vasilev 2 | Photography| Loyns ``` t\_enrolment which looks like this: ``` enrolment_id| student_fk |course_fk | Avarage_grade ------------------------------------------------------- 1 | 1 | 1 | 2 | 3 | 1 | 3 | 4 | 1 | 4 | 2 | 1 | 5 | 1 | 2 | 5.50 6 | 2 | 2 | 5.40 7 | 5 | 2 | 6.00 ``` I need to make 'select' statement and present the number of students per course. The result should be: ``` Count_students | Course_name ----------------------------- 4 | Basics 3 | Photography ```
2014/09/05
[ "https://Stackoverflow.com/questions/25681018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155020/" ]
Select all courses from your course Table, join the enrolment table and group by your course id. With count() you can select the number of Students ``` SELECT MAX(t_course.NAME) AS Course_name, COUNT(t_enrolment.student_fk) AS Count_students FROM t_course LEFT JOIN t_enrolment ON t_enrolment.course_fk = t_course.course_id GROUP BY t_course.course_id; ``` If you want to select the same student in one course only once (if more then one enrolment can happen) you can use COUNT(DISTINCT t\_enrolment.student\_fk) **UPDATE** To make it working not only in mySQL I added an aggregate function to the name column. Depending on the SQL database you are using you will have to add quotes or backticks.
Is this your homework? ``` select count(*) Count_students, c.name as course_name from t_enrolment e, t_course c group where e.course_fk = c.course_id by c.name ```
25,681,018
So I have these 3 tables: t\_student which looks like this: ``` STUDENT_ID| FIRST_NAME |LAST_NAME ----------------------------------- 1 | Ivan | Petrov 2 | Ivan | Ivanov 3 | Georgi | Georgiev ``` t\_course which looks like this: ``` course_id | NAME |LECTURER_NAME ----------------------------------- 1 | Basics | Vasilev 2 | Photography| Loyns ``` t\_enrolment which looks like this: ``` enrolment_id| student_fk |course_fk | Avarage_grade ------------------------------------------------------- 1 | 1 | 1 | 2 | 3 | 1 | 3 | 4 | 1 | 4 | 2 | 1 | 5 | 1 | 2 | 5.50 6 | 2 | 2 | 5.40 7 | 5 | 2 | 6.00 ``` I need to make 'select' statement and present the number of students per course. The result should be: ``` Count_students | Course_name ----------------------------- 4 | Basics 3 | Photography ```
2014/09/05
[ "https://Stackoverflow.com/questions/25681018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155020/" ]
Select all courses from your course Table, join the enrolment table and group by your course id. With count() you can select the number of Students ``` SELECT MAX(t_course.NAME) AS Course_name, COUNT(t_enrolment.student_fk) AS Count_students FROM t_course LEFT JOIN t_enrolment ON t_enrolment.course_fk = t_course.course_id GROUP BY t_course.course_id; ``` If you want to select the same student in one course only once (if more then one enrolment can happen) you can use COUNT(DISTINCT t\_enrolment.student\_fk) **UPDATE** To make it working not only in mySQL I added an aggregate function to the name column. Depending on the SQL database you are using you will have to add quotes or backticks.
You need a select statement with a join to the couse table (for the `Course_name`). Group by `'t_course'.name` to use the `COUNT(*)` function this will work: ``` SELECT COUNT(*) AS Count_students, c.NAME AS Course_name FROM t_enrolment e JOIN course c ON e.course_fk = c.course_id GROUP BY c.NAME ``` **More information** [Count function](http://dev.mysql.com/doc/refman/5.1/de/counting-rows.html) [Group by](http://dev.mysql.com/doc/refman/5.1/de/group-by-modifiers.html) [Join](http://dev.mysql.com/doc/refman/5.1/de/join.html)
71,244,250
### Input ``` import numpy as np import itertools a = np.array([ 1, 6, 7, 8, 10, 11, 13, 14, 15, 19, 20, 23, 24, 26, 28, 29, 33, 34, 41, 42, 43, 44, 45, 46, 47, 52, 54, 58, 60, 61, 65, 70, 75]).astype(np.uint8) b = np.array([ 2, 3, 4, 10, 12, 14, 16, 20, 22, 26, 28, 29, 30, 31, 34, 36, 37, 38, 39, 40, 41, 46, 48, 49, 50, 52, 53, 55, 56, 57, 59, 60, 63, 66, 67, 68, 69, 70, 71, 74]).astype(np.uint8) c = np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75]).astype(np.uint8) ``` I would like to get the Cartesian product of the 3 arrays but I do not want any duplicate elements in one row `[1, 2, 1]` would not be valid and only one of these two would be valid `[10, 14, 0]` or `[14, 10, 0]` since 10 and 14 are both in `a` and `b`. ### Python only ``` def no_numpy(): combos = {tuple(set(i)): i for i in itertools.product(a, b, c)} combos = [val for key, val in combos.items() if len(key) == 3] %timeit no_numpy() # 32.5 ms ± 508 µs per loop ``` ### Numpy ``` # Solution from (https://stackoverflow.com/a/11146645/18158000) def cartesian_product(*arrays): broadcastable = np.ix_(*arrays) broadcasted = np.broadcast_arrays(*broadcastable) rows, cols = np.prod(broadcasted[0].shape), len(broadcasted) dtype = np.result_type(*arrays) out = np.empty(rows * cols, dtype=dtype) start, end = 0, rows for a in broadcasted: out[start:end] = a.reshape(-1) start, end = end, end + rows return out.reshape(cols, rows).T def numpy(): combos = {tuple(set(i)): i for i in cartesian_product(*[a, b, c])} combos = [val for key, val in combos.items() if len(key) == 3] %timeit numpy() # 96.2 ms ± 136 µs per loop ``` My guess is in the numpy version converting the `np.array` to a set is why it is much slower but when comparing strictly getting the initial products `cartesian_product` is much faster than `itertools.product`. Can the numpy version be modified in anyway to outperform the pure python solution or is there another solution that outperforms both?
2022/02/23
[ "https://Stackoverflow.com/questions/71244250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18158000/" ]
You could do it like so: ``` # create full Cartessian product and keep items in sorted form arr = np.stack(np.meshgrid(a, b, c), axis=-1).reshape(-1, 3) arr_sort = np.sort(arr, axis=1) # apply condition 1: no duplicates between sorted items u, idx_c1 = np.unique(arr_sort, return_index=True, axis=0) arr_filter, arr_sort_filter = arr[idx_c1], arr_sort[idx_c1] # apply condition 2: no items with repeated values between sorted items idx_c2 = (arr_sort_filter[:,0] != arr_sort_filter[:,1]) & \ (arr_sort_filter[:,1] != arr_sort_filter[:,2]) arr_filter[idx_c2] >>> array([[ 1, 2, 0], [ 1, 3, 0], [ 1, 4, 0], ..., [75, 71, 74], [75, 74, 72], [75, 74, 73]], dtype=uint8) ``` It takes 57 ms on my computer vs 77 ms for `no_numpy(args?)` and returns 50014 items. You could later profile this algorithm in order to see what could be optimised. I do it manually but this would be a great idea to find some profiling tools :) * arr ~0.2 ms * arr\_sort ~1.4ms * u, idx\_c1 ~ 52ms * remaining part ~2.5ms So it's easy too see what consumes all the time here. It could be improved significantly using dimensionality reduction. One of the approaches is to replace ``` u, idx_c1 = np.unique(arr_sort, return_index=True, axis=0) ``` with ``` M = max(np.max(a), np.max(b), np.max(c)) idx = np.ravel_multi_index(arr_sort.T, (M+1, M+1, M+1)) u, idx_c1 = np.unique(idx, return_index=True) ``` It runs only 4.5 ms now and only 9 ms in total! I guess you are capable to speed up this algorithm ~3 times if you optimised these parts: * use `numba` for faster comparisons in `idx_c2` * use `numba` to speed up `np.ravel_multi_index` (manual implementation works faster even in `numpy`) * use `numba` or `numpy` version of `np.bincount` instead of `np.unique`
It is going to be quite hard to get numpy to go as fast as the filtered python iterator because numpy processes whole structures that will inevitably be larger than the result of filtering sets. Here is the best I could come up with to process the product of arrays in such a way that the result is filtered on unique combinations of distinct values: ``` def npProductSets(a,b,*others): if len(a.shape)<2 : a = a[:,None] if len(b.shape)<2 : b = b[:,None] left = np.repeat(a,b.shape[0],axis=0) right = np.tile(b,(a.shape[0],1)) distinct = ~np.any(right==left,axis=1) prod = np.concatenate((left[distinct],right[distinct]),axis=1) prod.sort(axis=1) prod = np.unique(prod,axis=0) if others: return npProductSets(prod,*others) return prod ``` This npProductSets function filters the expanded arrays as it goes and does it using numpy methods. It still runs slower than the Python generators though (0.078 sec vs 0.054 sec). Numpy is not the ideal tool to combinatorics and set manipulation. Note that npProductSets returns 50014 items instead of your 58363 because `tuple(set(i))` will not filter all permutations of the numbers. The conversion of a set to a tuple does not guarantee the order of elements (so duplicate combinations are included in your output because of permuted items).
71,244,250
### Input ``` import numpy as np import itertools a = np.array([ 1, 6, 7, 8, 10, 11, 13, 14, 15, 19, 20, 23, 24, 26, 28, 29, 33, 34, 41, 42, 43, 44, 45, 46, 47, 52, 54, 58, 60, 61, 65, 70, 75]).astype(np.uint8) b = np.array([ 2, 3, 4, 10, 12, 14, 16, 20, 22, 26, 28, 29, 30, 31, 34, 36, 37, 38, 39, 40, 41, 46, 48, 49, 50, 52, 53, 55, 56, 57, 59, 60, 63, 66, 67, 68, 69, 70, 71, 74]).astype(np.uint8) c = np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75]).astype(np.uint8) ``` I would like to get the Cartesian product of the 3 arrays but I do not want any duplicate elements in one row `[1, 2, 1]` would not be valid and only one of these two would be valid `[10, 14, 0]` or `[14, 10, 0]` since 10 and 14 are both in `a` and `b`. ### Python only ``` def no_numpy(): combos = {tuple(set(i)): i for i in itertools.product(a, b, c)} combos = [val for key, val in combos.items() if len(key) == 3] %timeit no_numpy() # 32.5 ms ± 508 µs per loop ``` ### Numpy ``` # Solution from (https://stackoverflow.com/a/11146645/18158000) def cartesian_product(*arrays): broadcastable = np.ix_(*arrays) broadcasted = np.broadcast_arrays(*broadcastable) rows, cols = np.prod(broadcasted[0].shape), len(broadcasted) dtype = np.result_type(*arrays) out = np.empty(rows * cols, dtype=dtype) start, end = 0, rows for a in broadcasted: out[start:end] = a.reshape(-1) start, end = end, end + rows return out.reshape(cols, rows).T def numpy(): combos = {tuple(set(i)): i for i in cartesian_product(*[a, b, c])} combos = [val for key, val in combos.items() if len(key) == 3] %timeit numpy() # 96.2 ms ± 136 µs per loop ``` My guess is in the numpy version converting the `np.array` to a set is why it is much slower but when comparing strictly getting the initial products `cartesian_product` is much faster than `itertools.product`. Can the numpy version be modified in anyway to outperform the pure python solution or is there another solution that outperforms both?
2022/02/23
[ "https://Stackoverflow.com/questions/71244250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18158000/" ]
Why current implementations are slow ------------------------------------ While the first solution is faster than the second one, it is quite inefficient since it creates a lot of temporary CPython objects (at least 6 per item of `itertools.product`). **Creating a lot of objects is expensive because they are dynamically allocated and reference-counted** by CPython. The Numpy function `cartesian_product` is pretty fast but the iteration over the resulting array is very slow because it creates a lot of Numpy views and operates on `numpy.uint8` instead of CPython `int`. **Numpy types and functions introduce a huge overhead for very small arrays**. Numpy can be used to speed up this operation as shown by @AlainT but this is not trivial to do and Numpy does not shine to solve such problems. --- How to improve performance -------------------------- One solution is to use **Numba** to do the job yourself more efficiently and let the Numba's *JIT compiler* optimizes loops. You can use 3 nested loops to efficiently generate the value of the Cartesian product and filter items. A dictionary can be used to track already seen values. The tuple of 3 items can be **packed** into one integer so to reduce the memory footprint and improve performance (so the dictionary can better fit in CPU caches and avoid the creation of slow tuple objects). Here is the resulting code: ```py import numba as nb # Signature of the function (parameter types) # Note: `::1` means the array is contiguous @nb.njit('(uint8[::1], uint8[::1], uint8[::1])') def with_numba(a, b, c): seen = dict() for va in a: for vb in b: for vc in c: # If the 3 values are different if va != vb and vc != vb and vc != va: # Sort the 3 values using a fast sorting network v1, v2, v3 = va, vb, vc if v1 > v2: v1, v2 = v2, v1 if v2 > v3: v2, v3 = v3, v2 if v1 > v2: v1, v2 = v2, v1 # Compact the 3 values into one 32-bit integer packedKey = (np.uint32(v1) << 16) | (np.uint32(v2) << 8) | np.uint32(v3) # Is the sorted tuple (v1,v2,v3) already seen? if packedKey not in seen: # Add the value and remember the ordered tuple (va,vb,vc) packedValue = (np.uint32(va) << 16) | (np.uint32(vb) << 8) | np.uint32(vc) seen[packedKey] = packedValue res = np.empty((len(seen), 3), dtype=np.uint8) for i, packed in enumerate(seen.values()): res[i, 0] = np.uint8(packed >> 16) res[i, 1] = np.uint8(packed >> 8) res[i, 2] = np.uint8(packed) return res with_numba(a, b, c) ``` --- Benchmark --------- Here are results on my i5-9600KF processor: ```none numpy: 122.1 ms (x 1.0) no_numpy: 49.6 ms (x 2.5) AlainT's solution: 49.0 ms (x 2.5) mathfux's solution 34.2 ms (x 3.5) mathfux's optimized solution 7.5 ms (x16.2) with_numba: 4.9 ms (x24.9) ``` The provided solution is about **25 times faster** than the slowest implementation and about **1.5 time faster** than the fastest provided implementation so far. The current Numba code is bounded by the speed of the Numba dictionary operations. The code can be optimized using more low-level tricks. On solution is to replace the dictionary by a *packed boolean array* (1 item = 1 bit) of size `256**3/8` to track the values already seen (by checking the `packedKey`th bit). The packed values can be directly added in `res` if the fetched bit is not set. This requires `res` to be preallocated to the maximum size or to implement an exponentially growing array (like `list` in Python or `std::vector` in C++). Another optimization is to sort the list and use a *tiling* strategy so to improve *cache locality*. Such optimization are far from being easy to implement but I expect them to drastically speed up the execution. If you plan to use more arrays, then the hash-map can become a bottleneck and a bit-array can be quite big. While using tiling certainly help to reduce the memory footprint, you can speed up the implementation by a large margin using [Bloom filters](https://en.wikipedia.org/wiki/Bloom_filter). This probabilist data structure can speed up the execution by skipping many duplicates without causing any *cache misses* and with a low memory footprint. You can remove most of the duplicates and then sort the array so to then remove the duplicates. Regarding your problem, a radix sort may be faster than usual sorting algorithms.
It is going to be quite hard to get numpy to go as fast as the filtered python iterator because numpy processes whole structures that will inevitably be larger than the result of filtering sets. Here is the best I could come up with to process the product of arrays in such a way that the result is filtered on unique combinations of distinct values: ``` def npProductSets(a,b,*others): if len(a.shape)<2 : a = a[:,None] if len(b.shape)<2 : b = b[:,None] left = np.repeat(a,b.shape[0],axis=0) right = np.tile(b,(a.shape[0],1)) distinct = ~np.any(right==left,axis=1) prod = np.concatenate((left[distinct],right[distinct]),axis=1) prod.sort(axis=1) prod = np.unique(prod,axis=0) if others: return npProductSets(prod,*others) return prod ``` This npProductSets function filters the expanded arrays as it goes and does it using numpy methods. It still runs slower than the Python generators though (0.078 sec vs 0.054 sec). Numpy is not the ideal tool to combinatorics and set manipulation. Note that npProductSets returns 50014 items instead of your 58363 because `tuple(set(i))` will not filter all permutations of the numbers. The conversion of a set to a tuple does not guarantee the order of elements (so duplicate combinations are included in your output because of permuted items).
71,244,250
### Input ``` import numpy as np import itertools a = np.array([ 1, 6, 7, 8, 10, 11, 13, 14, 15, 19, 20, 23, 24, 26, 28, 29, 33, 34, 41, 42, 43, 44, 45, 46, 47, 52, 54, 58, 60, 61, 65, 70, 75]).astype(np.uint8) b = np.array([ 2, 3, 4, 10, 12, 14, 16, 20, 22, 26, 28, 29, 30, 31, 34, 36, 37, 38, 39, 40, 41, 46, 48, 49, 50, 52, 53, 55, 56, 57, 59, 60, 63, 66, 67, 68, 69, 70, 71, 74]).astype(np.uint8) c = np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75]).astype(np.uint8) ``` I would like to get the Cartesian product of the 3 arrays but I do not want any duplicate elements in one row `[1, 2, 1]` would not be valid and only one of these two would be valid `[10, 14, 0]` or `[14, 10, 0]` since 10 and 14 are both in `a` and `b`. ### Python only ``` def no_numpy(): combos = {tuple(set(i)): i for i in itertools.product(a, b, c)} combos = [val for key, val in combos.items() if len(key) == 3] %timeit no_numpy() # 32.5 ms ± 508 µs per loop ``` ### Numpy ``` # Solution from (https://stackoverflow.com/a/11146645/18158000) def cartesian_product(*arrays): broadcastable = np.ix_(*arrays) broadcasted = np.broadcast_arrays(*broadcastable) rows, cols = np.prod(broadcasted[0].shape), len(broadcasted) dtype = np.result_type(*arrays) out = np.empty(rows * cols, dtype=dtype) start, end = 0, rows for a in broadcasted: out[start:end] = a.reshape(-1) start, end = end, end + rows return out.reshape(cols, rows).T def numpy(): combos = {tuple(set(i)): i for i in cartesian_product(*[a, b, c])} combos = [val for key, val in combos.items() if len(key) == 3] %timeit numpy() # 96.2 ms ± 136 µs per loop ``` My guess is in the numpy version converting the `np.array` to a set is why it is much slower but when comparing strictly getting the initial products `cartesian_product` is much faster than `itertools.product`. Can the numpy version be modified in anyway to outperform the pure python solution or is there another solution that outperforms both?
2022/02/23
[ "https://Stackoverflow.com/questions/71244250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18158000/" ]
Why current implementations are slow ------------------------------------ While the first solution is faster than the second one, it is quite inefficient since it creates a lot of temporary CPython objects (at least 6 per item of `itertools.product`). **Creating a lot of objects is expensive because they are dynamically allocated and reference-counted** by CPython. The Numpy function `cartesian_product` is pretty fast but the iteration over the resulting array is very slow because it creates a lot of Numpy views and operates on `numpy.uint8` instead of CPython `int`. **Numpy types and functions introduce a huge overhead for very small arrays**. Numpy can be used to speed up this operation as shown by @AlainT but this is not trivial to do and Numpy does not shine to solve such problems. --- How to improve performance -------------------------- One solution is to use **Numba** to do the job yourself more efficiently and let the Numba's *JIT compiler* optimizes loops. You can use 3 nested loops to efficiently generate the value of the Cartesian product and filter items. A dictionary can be used to track already seen values. The tuple of 3 items can be **packed** into one integer so to reduce the memory footprint and improve performance (so the dictionary can better fit in CPU caches and avoid the creation of slow tuple objects). Here is the resulting code: ```py import numba as nb # Signature of the function (parameter types) # Note: `::1` means the array is contiguous @nb.njit('(uint8[::1], uint8[::1], uint8[::1])') def with_numba(a, b, c): seen = dict() for va in a: for vb in b: for vc in c: # If the 3 values are different if va != vb and vc != vb and vc != va: # Sort the 3 values using a fast sorting network v1, v2, v3 = va, vb, vc if v1 > v2: v1, v2 = v2, v1 if v2 > v3: v2, v3 = v3, v2 if v1 > v2: v1, v2 = v2, v1 # Compact the 3 values into one 32-bit integer packedKey = (np.uint32(v1) << 16) | (np.uint32(v2) << 8) | np.uint32(v3) # Is the sorted tuple (v1,v2,v3) already seen? if packedKey not in seen: # Add the value and remember the ordered tuple (va,vb,vc) packedValue = (np.uint32(va) << 16) | (np.uint32(vb) << 8) | np.uint32(vc) seen[packedKey] = packedValue res = np.empty((len(seen), 3), dtype=np.uint8) for i, packed in enumerate(seen.values()): res[i, 0] = np.uint8(packed >> 16) res[i, 1] = np.uint8(packed >> 8) res[i, 2] = np.uint8(packed) return res with_numba(a, b, c) ``` --- Benchmark --------- Here are results on my i5-9600KF processor: ```none numpy: 122.1 ms (x 1.0) no_numpy: 49.6 ms (x 2.5) AlainT's solution: 49.0 ms (x 2.5) mathfux's solution 34.2 ms (x 3.5) mathfux's optimized solution 7.5 ms (x16.2) with_numba: 4.9 ms (x24.9) ``` The provided solution is about **25 times faster** than the slowest implementation and about **1.5 time faster** than the fastest provided implementation so far. The current Numba code is bounded by the speed of the Numba dictionary operations. The code can be optimized using more low-level tricks. On solution is to replace the dictionary by a *packed boolean array* (1 item = 1 bit) of size `256**3/8` to track the values already seen (by checking the `packedKey`th bit). The packed values can be directly added in `res` if the fetched bit is not set. This requires `res` to be preallocated to the maximum size or to implement an exponentially growing array (like `list` in Python or `std::vector` in C++). Another optimization is to sort the list and use a *tiling* strategy so to improve *cache locality*. Such optimization are far from being easy to implement but I expect them to drastically speed up the execution. If you plan to use more arrays, then the hash-map can become a bottleneck and a bit-array can be quite big. While using tiling certainly help to reduce the memory footprint, you can speed up the implementation by a large margin using [Bloom filters](https://en.wikipedia.org/wiki/Bloom_filter). This probabilist data structure can speed up the execution by skipping many duplicates without causing any *cache misses* and with a low memory footprint. You can remove most of the duplicates and then sort the array so to then remove the duplicates. Regarding your problem, a radix sort may be faster than usual sorting algorithms.
You could do it like so: ``` # create full Cartessian product and keep items in sorted form arr = np.stack(np.meshgrid(a, b, c), axis=-1).reshape(-1, 3) arr_sort = np.sort(arr, axis=1) # apply condition 1: no duplicates between sorted items u, idx_c1 = np.unique(arr_sort, return_index=True, axis=0) arr_filter, arr_sort_filter = arr[idx_c1], arr_sort[idx_c1] # apply condition 2: no items with repeated values between sorted items idx_c2 = (arr_sort_filter[:,0] != arr_sort_filter[:,1]) & \ (arr_sort_filter[:,1] != arr_sort_filter[:,2]) arr_filter[idx_c2] >>> array([[ 1, 2, 0], [ 1, 3, 0], [ 1, 4, 0], ..., [75, 71, 74], [75, 74, 72], [75, 74, 73]], dtype=uint8) ``` It takes 57 ms on my computer vs 77 ms for `no_numpy(args?)` and returns 50014 items. You could later profile this algorithm in order to see what could be optimised. I do it manually but this would be a great idea to find some profiling tools :) * arr ~0.2 ms * arr\_sort ~1.4ms * u, idx\_c1 ~ 52ms * remaining part ~2.5ms So it's easy too see what consumes all the time here. It could be improved significantly using dimensionality reduction. One of the approaches is to replace ``` u, idx_c1 = np.unique(arr_sort, return_index=True, axis=0) ``` with ``` M = max(np.max(a), np.max(b), np.max(c)) idx = np.ravel_multi_index(arr_sort.T, (M+1, M+1, M+1)) u, idx_c1 = np.unique(idx, return_index=True) ``` It runs only 4.5 ms now and only 9 ms in total! I guess you are capable to speed up this algorithm ~3 times if you optimised these parts: * use `numba` for faster comparisons in `idx_c2` * use `numba` to speed up `np.ravel_multi_index` (manual implementation works faster even in `numpy`) * use `numba` or `numpy` version of `np.bincount` instead of `np.unique`
23,912
According to [Wikipedia](https://en.wikipedia.org/wiki/Korean_War), there were many belligerents on the South Korean side involved in the war. This includes The UK, France, Australia, Canada, Greece and many, many others. Why, then, is there so much more hatred towards the US when other countries were a part of the war? Was the hatred for the US spawned from that war, or has it been the US actions (sanctions etc) towards the DPRK over the years which has created the situation we are in now? Are other countries involved seen in the same light by the DPRK, as the US is?
2017/08/22
[ "https://politics.stackexchange.com/questions/23912", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/16352/" ]
While Alexander's points are correct and certainly do not help the USA win North Korean sympathies, I think that more than an historical view the answer lies in the current situation: * USA is the only foreign power that still has troops stationed in South Korea. * USA was the most powerful nation of the UN coalition. The advantage it had in the Korean war has only increased. * The other major powers (UK, France) have lost or granted independence to most of the colonial possessions that helped them to project power in the area (Singapore, Malaysia, Hong Kong, former Indochina comprising of Vietnam, Cambodia and Laos), reducing their influence and making it less visible. * As a consequence of the above, USA remains the most significant and involved foreign member of the "Western coalition". The six-party talks, for example, included Russia, China, North Korea, South Korea, Japan and USA. Of the latter: + Pressuring South Korea into submission is not a viable tactic, specially while it has the support of the USA¹. + Japan has a limited military so it is not much of a threat. * Other members of the former UN coalition seem to be happy following the USA lead (there are no separate political initiatives coming from the UK, France or Australia). I have seen some different analysis behind NK politics, but the above points make the USA the prime target. For example: * They want to invade South Korea and the USA presence is an additional obstacle. NK leadership thinks that threatening the USA will get it to retire its support to South Korea and leave the South Korean army without allies. * They are honestly afraid of the USA and South Korea invading them, and want to have leverage to avoid that. * They need a foreign threat to justify its military control of the population, and the USA gives the most terrifying threat. --- ¹ And @SoylentGray has a point that North Korea has not been ignoring South Korea: there have been artillery attacks across the border and there are strong suspicions that a NK submarine sunk a SK destroyer.
Also according to Wikipedia (same article, in the box on the right, under "Strength"), albeit the Korea war was a U.N. mandate, the U.S. was the main force, providing 326k out of 370k of the allied personnel, or about 90%, plus they supplied most of the armament; and [they appointed the commander of the allied forces](https://en.wikipedia.org/wiki/United_Nations_Security_Council_Resolution_84). Without the U.S., North Korea would have won over South Korea, period. No other ally, even if their contribution may have been helpful, could have made any difference to the outcome of the war.
23,912
According to [Wikipedia](https://en.wikipedia.org/wiki/Korean_War), there were many belligerents on the South Korean side involved in the war. This includes The UK, France, Australia, Canada, Greece and many, many others. Why, then, is there so much more hatred towards the US when other countries were a part of the war? Was the hatred for the US spawned from that war, or has it been the US actions (sanctions etc) towards the DPRK over the years which has created the situation we are in now? Are other countries involved seen in the same light by the DPRK, as the US is?
2017/08/22
[ "https://politics.stackexchange.com/questions/23912", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/16352/" ]
Also according to Wikipedia (same article, in the box on the right, under "Strength"), albeit the Korea war was a U.N. mandate, the U.S. was the main force, providing 326k out of 370k of the allied personnel, or about 90%, plus they supplied most of the armament; and [they appointed the commander of the allied forces](https://en.wikipedia.org/wiki/United_Nations_Security_Council_Resolution_84). Without the U.S., North Korea would have won over South Korea, period. No other ally, even if their contribution may have been helpful, could have made any difference to the outcome of the war.
The US has a variety of justifications for having hundreds of thousands of troops and thousands of bases overseas. The US presence in Japan and South Korea, in particular, is contingent on the North Korean threat. If North Korea ceases to be a threat, the US troops stationed in South Korea and Japan will have even less support from local populations then they have now. This is why the US politicians and the mainstream media cheerleaders continue to cast DPRK as an extreme threat. Or, alternatively, the US would need to cast China into the villain role that DPRK currently fills. Unfortunately, there is so much Won, Yen, and USD invested in China that making China into the next pariah would be deeply unpopular with the powerful investment classes in these countries. Most of the other countries you mention in the question - UK Commonwealth, France, etc - no longer have a large overseas presence due to the end of colonialism. Therefore, they have no interest in having a large troop presence in East Asia. Said another way, these countries now trust the US to "police the world" and enforce post-colonial international security. Sooo... the US, the most powerful nation in the world, uses DPRK as a justification to station troops and nuclear weapon in its vicinity. The most powerful nation minces no words in stating that the DPRK is the reason for having those troops there. The US has bombed the entire DPRK economy to dust, and has aggressively invaded Iraq, Afghanistan, Libya, Panama, Vietnam, Laos, Cambodia, and others since the 1950s. The US has sponsored coups and attempted to overthrow governments in Venezuela, Guatemala, Chile, Ukraine, Syria, Cuba, Nicaragua, South Korea, and throughout Africa. The threat of overthrow by the US has also worked to keep the DPRK regime in power; in a word, the presence of a threat has worked to unify the regime. In many ways, the US presence keeps the DPRK government in power. Thus DPRK must keep the US boogey man in place.
23,912
According to [Wikipedia](https://en.wikipedia.org/wiki/Korean_War), there were many belligerents on the South Korean side involved in the war. This includes The UK, France, Australia, Canada, Greece and many, many others. Why, then, is there so much more hatred towards the US when other countries were a part of the war? Was the hatred for the US spawned from that war, or has it been the US actions (sanctions etc) towards the DPRK over the years which has created the situation we are in now? Are other countries involved seen in the same light by the DPRK, as the US is?
2017/08/22
[ "https://politics.stackexchange.com/questions/23912", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/16352/" ]
While Alexander's points are correct and certainly do not help the USA win North Korean sympathies, I think that more than an historical view the answer lies in the current situation: * USA is the only foreign power that still has troops stationed in South Korea. * USA was the most powerful nation of the UN coalition. The advantage it had in the Korean war has only increased. * The other major powers (UK, France) have lost or granted independence to most of the colonial possessions that helped them to project power in the area (Singapore, Malaysia, Hong Kong, former Indochina comprising of Vietnam, Cambodia and Laos), reducing their influence and making it less visible. * As a consequence of the above, USA remains the most significant and involved foreign member of the "Western coalition". The six-party talks, for example, included Russia, China, North Korea, South Korea, Japan and USA. Of the latter: + Pressuring South Korea into submission is not a viable tactic, specially while it has the support of the USA¹. + Japan has a limited military so it is not much of a threat. * Other members of the former UN coalition seem to be happy following the USA lead (there are no separate political initiatives coming from the UK, France or Australia). I have seen some different analysis behind NK politics, but the above points make the USA the prime target. For example: * They want to invade South Korea and the USA presence is an additional obstacle. NK leadership thinks that threatening the USA will get it to retire its support to South Korea and leave the South Korean army without allies. * They are honestly afraid of the USA and South Korea invading them, and want to have leverage to avoid that. * They need a foreign threat to justify its military control of the population, and the USA gives the most terrifying threat. --- ¹ And @SoylentGray has a point that North Korea has not been ignoring South Korea: there have been artillery attacks across the border and there are strong suspicions that a NK submarine sunk a SK destroyer.
The US maintained a particularly destructive and deadly [bombing campaign](http://www.newsweek.com/us-forget-korean-war-led-crisis-north-592630) on North Korea during the Korean war: > > During the course of the three-year war, which both sides accuse one > another of provoking, t**he U.S. dropped 635,000 tons of explosives on > North Korea**, including 32,557 tons of napalm, an incendiary liquid > that can clear forested areas and cause devastating burns to human > skin. (In constrast [sic], the U.S. used 503,000 tons of bombs during the > entire Pacific Theater of World War Two, according to a 2009 study by > the Asia-Pacific Journal.) In a 1984 interview, **Air Force Gen. Curtis > LeMay**, head of the Strategic Air Command during the Korean War, > **claimed U.S. bombs "killed off 20 percent of the population" and > "targeted everything that moved in North Korea."** These acts, largely > ignored by the U.S.' collective memory, have deeply contributed to > Pyongyang's contempt for the U.S. and especially its ongoing military > presence on the Korean Peninsula. > > > "Most Americans are completely unaware that we destroyed more cities > in the North then we did in Japan or Germany during World War II... > Every North Korean knows about this, it's drilled into their minds. We > never hear about it," historian and author Bruce Cumings told Newsweek > by email Monday. > > > This is recent enough to still be a living memory in North Korea, and plays heavily in North Korean propaganda. <http://www.newsweek.com/us-forget-korean-war-led-crisis-north-592630>
23,912
According to [Wikipedia](https://en.wikipedia.org/wiki/Korean_War), there were many belligerents on the South Korean side involved in the war. This includes The UK, France, Australia, Canada, Greece and many, many others. Why, then, is there so much more hatred towards the US when other countries were a part of the war? Was the hatred for the US spawned from that war, or has it been the US actions (sanctions etc) towards the DPRK over the years which has created the situation we are in now? Are other countries involved seen in the same light by the DPRK, as the US is?
2017/08/22
[ "https://politics.stackexchange.com/questions/23912", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/16352/" ]
While Alexander's points are correct and certainly do not help the USA win North Korean sympathies, I think that more than an historical view the answer lies in the current situation: * USA is the only foreign power that still has troops stationed in South Korea. * USA was the most powerful nation of the UN coalition. The advantage it had in the Korean war has only increased. * The other major powers (UK, France) have lost or granted independence to most of the colonial possessions that helped them to project power in the area (Singapore, Malaysia, Hong Kong, former Indochina comprising of Vietnam, Cambodia and Laos), reducing their influence and making it less visible. * As a consequence of the above, USA remains the most significant and involved foreign member of the "Western coalition". The six-party talks, for example, included Russia, China, North Korea, South Korea, Japan and USA. Of the latter: + Pressuring South Korea into submission is not a viable tactic, specially while it has the support of the USA¹. + Japan has a limited military so it is not much of a threat. * Other members of the former UN coalition seem to be happy following the USA lead (there are no separate political initiatives coming from the UK, France or Australia). I have seen some different analysis behind NK politics, but the above points make the USA the prime target. For example: * They want to invade South Korea and the USA presence is an additional obstacle. NK leadership thinks that threatening the USA will get it to retire its support to South Korea and leave the South Korean army without allies. * They are honestly afraid of the USA and South Korea invading them, and want to have leverage to avoid that. * They need a foreign threat to justify its military control of the population, and the USA gives the most terrifying threat. --- ¹ And @SoylentGray has a point that North Korea has not been ignoring South Korea: there have been artillery attacks across the border and there are strong suspicions that a NK submarine sunk a SK destroyer.
The US has a variety of justifications for having hundreds of thousands of troops and thousands of bases overseas. The US presence in Japan and South Korea, in particular, is contingent on the North Korean threat. If North Korea ceases to be a threat, the US troops stationed in South Korea and Japan will have even less support from local populations then they have now. This is why the US politicians and the mainstream media cheerleaders continue to cast DPRK as an extreme threat. Or, alternatively, the US would need to cast China into the villain role that DPRK currently fills. Unfortunately, there is so much Won, Yen, and USD invested in China that making China into the next pariah would be deeply unpopular with the powerful investment classes in these countries. Most of the other countries you mention in the question - UK Commonwealth, France, etc - no longer have a large overseas presence due to the end of colonialism. Therefore, they have no interest in having a large troop presence in East Asia. Said another way, these countries now trust the US to "police the world" and enforce post-colonial international security. Sooo... the US, the most powerful nation in the world, uses DPRK as a justification to station troops and nuclear weapon in its vicinity. The most powerful nation minces no words in stating that the DPRK is the reason for having those troops there. The US has bombed the entire DPRK economy to dust, and has aggressively invaded Iraq, Afghanistan, Libya, Panama, Vietnam, Laos, Cambodia, and others since the 1950s. The US has sponsored coups and attempted to overthrow governments in Venezuela, Guatemala, Chile, Ukraine, Syria, Cuba, Nicaragua, South Korea, and throughout Africa. The threat of overthrow by the US has also worked to keep the DPRK regime in power; in a word, the presence of a threat has worked to unify the regime. In many ways, the US presence keeps the DPRK government in power. Thus DPRK must keep the US boogey man in place.
23,912
According to [Wikipedia](https://en.wikipedia.org/wiki/Korean_War), there were many belligerents on the South Korean side involved in the war. This includes The UK, France, Australia, Canada, Greece and many, many others. Why, then, is there so much more hatred towards the US when other countries were a part of the war? Was the hatred for the US spawned from that war, or has it been the US actions (sanctions etc) towards the DPRK over the years which has created the situation we are in now? Are other countries involved seen in the same light by the DPRK, as the US is?
2017/08/22
[ "https://politics.stackexchange.com/questions/23912", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/16352/" ]
The US maintained a particularly destructive and deadly [bombing campaign](http://www.newsweek.com/us-forget-korean-war-led-crisis-north-592630) on North Korea during the Korean war: > > During the course of the three-year war, which both sides accuse one > another of provoking, t**he U.S. dropped 635,000 tons of explosives on > North Korea**, including 32,557 tons of napalm, an incendiary liquid > that can clear forested areas and cause devastating burns to human > skin. (In constrast [sic], the U.S. used 503,000 tons of bombs during the > entire Pacific Theater of World War Two, according to a 2009 study by > the Asia-Pacific Journal.) In a 1984 interview, **Air Force Gen. Curtis > LeMay**, head of the Strategic Air Command during the Korean War, > **claimed U.S. bombs "killed off 20 percent of the population" and > "targeted everything that moved in North Korea."** These acts, largely > ignored by the U.S.' collective memory, have deeply contributed to > Pyongyang's contempt for the U.S. and especially its ongoing military > presence on the Korean Peninsula. > > > "Most Americans are completely unaware that we destroyed more cities > in the North then we did in Japan or Germany during World War II... > Every North Korean knows about this, it's drilled into their minds. We > never hear about it," historian and author Bruce Cumings told Newsweek > by email Monday. > > > This is recent enough to still be a living memory in North Korea, and plays heavily in North Korean propaganda. <http://www.newsweek.com/us-forget-korean-war-led-crisis-north-592630>
The US has a variety of justifications for having hundreds of thousands of troops and thousands of bases overseas. The US presence in Japan and South Korea, in particular, is contingent on the North Korean threat. If North Korea ceases to be a threat, the US troops stationed in South Korea and Japan will have even less support from local populations then they have now. This is why the US politicians and the mainstream media cheerleaders continue to cast DPRK as an extreme threat. Or, alternatively, the US would need to cast China into the villain role that DPRK currently fills. Unfortunately, there is so much Won, Yen, and USD invested in China that making China into the next pariah would be deeply unpopular with the powerful investment classes in these countries. Most of the other countries you mention in the question - UK Commonwealth, France, etc - no longer have a large overseas presence due to the end of colonialism. Therefore, they have no interest in having a large troop presence in East Asia. Said another way, these countries now trust the US to "police the world" and enforce post-colonial international security. Sooo... the US, the most powerful nation in the world, uses DPRK as a justification to station troops and nuclear weapon in its vicinity. The most powerful nation minces no words in stating that the DPRK is the reason for having those troops there. The US has bombed the entire DPRK economy to dust, and has aggressively invaded Iraq, Afghanistan, Libya, Panama, Vietnam, Laos, Cambodia, and others since the 1950s. The US has sponsored coups and attempted to overthrow governments in Venezuela, Guatemala, Chile, Ukraine, Syria, Cuba, Nicaragua, South Korea, and throughout Africa. The threat of overthrow by the US has also worked to keep the DPRK regime in power; in a word, the presence of a threat has worked to unify the regime. In many ways, the US presence keeps the DPRK government in power. Thus DPRK must keep the US boogey man in place.