qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
17,696,760
![enter image description here](https://i.stack.imgur.com/Dl6v9.png) As show in Picture above UIView A & UIView C are Added on UIView B. for B ClipToBounds is YES so the Red area is not visible. Is it possible to get Visible rectangle of A & C ( shown with Lines ) I need show Rectangle in visible area when I touches e.g View A. thats it. ![enter image description here](https://i.stack.imgur.com/wllxD.png)
2013/07/17
[ "https://Stackoverflow.com/questions/17696760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355082/" ]
Yes you can with this function: ``` CGRect CGRectIntersection ( CGRect r1, CGRect r2 ); ``` If you tell exactly what you want to do maybe are better ways, for example i needed something similar and instead cropping manually i just captured the UIView B content as an image.
Use for this ``` [UIView convertRect:<#(CGRect)#> fromView:<#(UIView *)#>] [UIView convertRect:<#(CGRect)#> toView:<#(UIView *)#>] ``` And CGRectIntersection function
17,696,760
![enter image description here](https://i.stack.imgur.com/Dl6v9.png) As show in Picture above UIView A & UIView C are Added on UIView B. for B ClipToBounds is YES so the Red area is not visible. Is it possible to get Visible rectangle of A & C ( shown with Lines ) I need show Rectangle in visible area when I touches e.g View A. thats it. ![enter image description here](https://i.stack.imgur.com/wllxD.png)
2013/07/17
[ "https://Stackoverflow.com/questions/17696760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/355082/" ]
Yes you can with this function: ``` CGRect CGRectIntersection ( CGRect r1, CGRect r2 ); ``` If you tell exactly what you want to do maybe are better ways, for example i needed something similar and instead cropping manually i just captured the UIView B content as an image.
on `touchesEnded:` method you can find it like bellow.. ``` -(void) touchesEnded:(NSSet *) touches { if(CGRectIntersectsRect([ViewA frame], [ViewB frame]) { //Do something here } } ``` Read More Information about RectInterSect From [This Link](https://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CGGeometry/Reference/reference.html#//apple_ref/c/func/CGRectContainsPoint) i hope its helpful to you...
5,524,712
I currently have a design like follows View1(mainview) creates a view2, sets a reference back to view1 in view2, presents view2 view2 creates a view3, sets view3 to have the same view1 reference, presents view3 view3 then needs to , depending on user selection, call a function on view1, which currently works perfectly and it should then present view1. The issue is I need a way of showing view1 when view3 is done, so this reference gets passed along and clearly works because the method called on it executes. The issue I have is when trying to present it the app freezes. I also tried creating a new view1, setting it to the reference and presenting that, this causes a freeze too. What could be the issue? I present it like everything else.
2011/04/02
[ "https://Stackoverflow.com/questions/5524712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356387/" ]
I suddenly realised what caused my problem. I had previously changed the default setting for mass\_assignment in a config file to enforce that all attributes were protected unless declared otherwise. An obvious mistake in retrospect but hopefully this might save someone else some time too
Attr\_accessible is a safety feature. It tells your model to only save the mentioned values, upon a mass assignment (like save). Im' pretty sure that you will notice a Warning on mass assignment if you look at your logs. If you have try to save a model even with a single accessible attribute, ONLY this will be saved in a mass assignment. Thus, if you have :password accessible but :password\_confirmation not accessible, only :password will be inserted, and you will get a warning. I think that this is probably the reason why you get this behaviour.
5,524,712
I currently have a design like follows View1(mainview) creates a view2, sets a reference back to view1 in view2, presents view2 view2 creates a view3, sets view3 to have the same view1 reference, presents view3 view3 then needs to , depending on user selection, call a function on view1, which currently works perfectly and it should then present view1. The issue is I need a way of showing view1 when view3 is done, so this reference gets passed along and clearly works because the method called on it executes. The issue I have is when trying to present it the app freezes. I also tried creating a new view1, setting it to the reference and presenting that, this causes a freeze too. What could be the issue? I present it like everything else.
2011/04/02
[ "https://Stackoverflow.com/questions/5524712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356387/" ]
Attr\_accessible is a safety feature. It tells your model to only save the mentioned values, upon a mass assignment (like save). Im' pretty sure that you will notice a Warning on mass assignment if you look at your logs. If you have try to save a model even with a single accessible attribute, ONLY this will be saved in a mass assignment. Thus, if you have :password accessible but :password\_confirmation not accessible, only :password will be inserted, and you will get a warning. I think that this is probably the reason why you get this behaviour.
To add to Peter Nixey's answer, to resolve this problem in rails 3 I changed the following: ``` # application.rb config.active_record.whitelist_attributes = false #it was true ``` When set to true, a whitelist is enforced for all attributes that can be mass assigned. This needs to be disabled or you can add them to the white list with ``` attr_accessible <your attributes> ``` **Edit** As Peter quite rightly points out in the comments; by setting the configuration to false you leave yourself open to mass\_assignment attacks, so using the white list is the securest option,
5,524,712
I currently have a design like follows View1(mainview) creates a view2, sets a reference back to view1 in view2, presents view2 view2 creates a view3, sets view3 to have the same view1 reference, presents view3 view3 then needs to , depending on user selection, call a function on view1, which currently works perfectly and it should then present view1. The issue is I need a way of showing view1 when view3 is done, so this reference gets passed along and clearly works because the method called on it executes. The issue I have is when trying to present it the app freezes. I also tried creating a new view1, setting it to the reference and presenting that, this causes a freeze too. What could be the issue? I present it like everything else.
2011/04/02
[ "https://Stackoverflow.com/questions/5524712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356387/" ]
I suddenly realised what caused my problem. I had previously changed the default setting for mass\_assignment in a config file to enforce that all attributes were protected unless declared otherwise. An obvious mistake in retrospect but hopefully this might save someone else some time too
To add to Peter Nixey's answer, to resolve this problem in rails 3 I changed the following: ``` # application.rb config.active_record.whitelist_attributes = false #it was true ``` When set to true, a whitelist is enforced for all attributes that can be mass assigned. This needs to be disabled or you can add them to the white list with ``` attr_accessible <your attributes> ``` **Edit** As Peter quite rightly points out in the comments; by setting the configuration to false you leave yourself open to mass\_assignment attacks, so using the white list is the securest option,
2,415,297
Find the least positive integer $m$ such that $m^2 - m + 11$ is a product of at least four not necessarily distinct primes. I tried but not able to solve it. **Edit** : Please note that I am looking for mathematical solution not the programming one.
2017/09/03
[ "https://math.stackexchange.com/questions/2415297", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let the equality $$m(m-1)+11=N$$ It is clear that $N$ must be odd and that can be divisible by the prime $11$. However the following congruences have no solution as it is easy to prove directly checking the few possibilities with $m(m-1)$ not divisible by $3,5$ and $7$ respectively $$\begin{cases}m(m-1)+2\equiv 0\pmod3\\m(m-1)+1\equiv 0\pmod5\\m(m-1)+4\equiv 0\pmod7\end{cases}$$ Thus $N=\prod p\_i^{a\_i}$ with $p\_i\ge11$. A necessary condition is that (solving the quadratic in $m$) $$\sqrt{4N-43}=x^2$$ and from this we need that $$N\equiv 1,3,7\pmod{10}$$ By chance we find the minimum $N=11^3\cdot13$ which corresponds to $\color{red}{m=132}$ and that could have been calculated by direct trials but the next solution seems to be far from $132$.
$$132^2 - 132 + 11 = 11 \times 11 \times 11 \times 13$$ [Pyth program](http://pyth.herokuapp.com/?code=f%3C3lP%2B%2aTtT11&debug=0): ``` f<3lP+*TtT11 ```
2,415,297
Find the least positive integer $m$ such that $m^2 - m + 11$ is a product of at least four not necessarily distinct primes. I tried but not able to solve it. **Edit** : Please note that I am looking for mathematical solution not the programming one.
2017/09/03
[ "https://math.stackexchange.com/questions/2415297", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let the equality $$m(m-1)+11=N$$ It is clear that $N$ must be odd and that can be divisible by the prime $11$. However the following congruences have no solution as it is easy to prove directly checking the few possibilities with $m(m-1)$ not divisible by $3,5$ and $7$ respectively $$\begin{cases}m(m-1)+2\equiv 0\pmod3\\m(m-1)+1\equiv 0\pmod5\\m(m-1)+4\equiv 0\pmod7\end{cases}$$ Thus $N=\prod p\_i^{a\_i}$ with $p\_i\ge11$. A necessary condition is that (solving the quadratic in $m$) $$\sqrt{4N-43}=x^2$$ and from this we need that $$N\equiv 1,3,7\pmod{10}$$ By chance we find the minimum $N=11^3\cdot13$ which corresponds to $\color{red}{m=132}$ and that could have been calculated by direct trials but the next solution seems to be far from $132$.
By checking the choices $m=0,1,\ldots,p-1$, you can show that $m^2-m+11$ is never divisible by $p$ when $p=2,3,5$ or $7$. So the smallest possible product of four primes is $11^4$. The next smallest is $11^3\cdot 13$. (Taking a peek at Kenny Lau's answer). All you need to do is to check that $$m^2-m+11=11^4$$ has no integer solutions, but $$m^2-m+11=11^3\cdot13$$ does.
69,152,784
I'm trying to create an HTML page with a footer sticking to the bottom, independently from the size of the browser window. I created the following HTML file: ```html <!doctype html> <html> <head> <meta charset="utf-8"> <title> Home </title> <link rel="stylesheet" href="./assets/css/styles.css"> </head> <body> <h1> Home </h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <footer id="footer"> Foo Bar Baz </footer> </body> </html> ``` And my stylesheet is: ```css #footer { position: absolute; bottom: 0px; width: 100%; padding: 10px; border: 1px solid; } ``` I used the properties `position` and `bottom` following several guides. I get the footer at the expected vertical position, but it is shifted horizontally to the right, whatever the window width is. For example: [full screen](https://i.stack.imgur.com/sFPqK.png), [medium](https://i.stack.imgur.com/OpKkf.png), [small](https://i.stack.imgur.com/oBWvk.png). Where is the error? And how can I fix it?
2021/09/12
[ "https://Stackoverflow.com/questions/69152784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12293618/" ]
According to your requirement, if you don't want to show `right` and `left` border of the footer then you can only use `left:0px;` with your footer `CSS`. i.e. ``` #footer { position: fixed; bottom: 0px; width: 100%; padding: 10px; border: 1px solid; left: 0px; } ``` And also if you want to show `right` and `left` borders of footer then decrease the `width` of `footer` and increase value of `left` accordingly. Hopefully it will help you.
to answer your question, please look at this question. [How to get rid of white space on left and right of div?](https://stackoverflow.com/questions/34302798/how-to-get-rid-of-white-space-on-left-and-right-of-div) You have to reset your CSS. You can do this by adding the following to your Code. ``` html, body { margin: 0; padding: 0; width: 100%; height: 100%; } ```
69,152,784
I'm trying to create an HTML page with a footer sticking to the bottom, independently from the size of the browser window. I created the following HTML file: ```html <!doctype html> <html> <head> <meta charset="utf-8"> <title> Home </title> <link rel="stylesheet" href="./assets/css/styles.css"> </head> <body> <h1> Home </h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <footer id="footer"> Foo Bar Baz </footer> </body> </html> ``` And my stylesheet is: ```css #footer { position: absolute; bottom: 0px; width: 100%; padding: 10px; border: 1px solid; } ``` I used the properties `position` and `bottom` following several guides. I get the footer at the expected vertical position, but it is shifted horizontally to the right, whatever the window width is. For example: [full screen](https://i.stack.imgur.com/sFPqK.png), [medium](https://i.stack.imgur.com/OpKkf.png), [small](https://i.stack.imgur.com/oBWvk.png). Where is the error? And how can I fix it?
2021/09/12
[ "https://Stackoverflow.com/questions/69152784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12293618/" ]
If you use the position property outside of normal (such as absolute or fixed), you must give the property you gave on the vertical axis also on the horizontal. The Width value may not work because you are no longer in a normal flow. Therefore, using it like this will give the correct result. ``` #footer { position: fixed; bottom: 0px; width: 100%; padding: 10px; border: 1px solid; left: 0px; } ```
to answer your question, please look at this question. [How to get rid of white space on left and right of div?](https://stackoverflow.com/questions/34302798/how-to-get-rid-of-white-space-on-left-and-right-of-div) You have to reset your CSS. You can do this by adding the following to your Code. ``` html, body { margin: 0; padding: 0; width: 100%; height: 100%; } ```
42,734,801
everyone! I'm using matplotlib and I have a field with randomly generated circles. Also I have button which has to generate new random circles in the field but every time I press it, circles are generated inside the BUTTON, but not in the field. Please show me what I'm doing wrong, I'm new to python(actually started learning it yesterday). Here is my code: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Button plt.subplots_adjust(bottom=0.2) N = 10 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * 0.2 l = plt.scatter(x, y, s=area, c=colors, alpha=0.8) def gen(event): N = 10 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * 0.2 plt.scatter(x, y, s=area, c=colors, alpha=0.8) plt.draw() axgen = plt.axes([0.81, 0.05, 0.1, 0.075]) bgen = Button(axgen, 'Generate') bgen.on_clicked(gen) plt.show() ``` ![enter image description here](https://i.stack.imgur.com/LUXKT.png)
2017/03/11
[ "https://Stackoverflow.com/questions/42734801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What you have is efficient enough, really. In this context almost anything you could dream up is efficient enough, but for neatness? Well, I would've at least refactored the conversion into a function, and do you really need a long int to store the age levels? I doubt it as humans generally don't become *that* old. I would just go for a regular int. Something like this: ``` int ConvertFromMaturityConfig(string maturityConfig) { string ageString = maturityConfig.Split('=')[0]; return int.Parse(ageString); } ``` Usage: ``` string maturity = "0=Child|13=Teen|18=Adult"; string[] configuration = maturity.Split('|'); int childAgeMin = ConvertFromMaturityConfig(configuration[0]); int teenAgeMin = ConvertFromMaturityConfig(configuration[1]); int adultAgeMin = ConvertFromMaturityConfig(configuration[2]); ``` I would also consider trying to determine which configuration belongs to which value. As it is, you're expecting you get the child age, the teen age and the adult age, in that order. Personally, with the constraints you have, I would've put it into a dictionary so that you could look it up there. Then you could have something like this: ``` string maturity = "0=Child|13=Teen|18=Adult"; var config = maturity.Split('|') .Select(s => s.Split('=')) .ToDictionary( c => c[1], // key selector c => int.Parse(c[0])); ``` Then you can use it like this: ``` if (age >= config["Child"] && age < config["Teen"]) maturity = "Child"; else if (age >= config["Teen"] && age < config["Adult"]) maturity = "Teen"; else if (age >= config["Adult"]) maturity = "Adult"; ``` You would be wise to consider what happens if the age is below the minimum child age, by the way.
Create a class like below: ``` public class PersonRecord { public int MinAge { get; set; } public string Maturity { get; set; } } ``` Create a method which will parse the string like below: ``` public static List<PersonRecord> Parse(string records) { var splits = records.Split('|'); var persons = splits.Select(p => { int age; var split = p.Split('='); if(int.TryParse(split[0], out age)) { return new PersonRecord { MinAge = age, Maturity = split[1] }; } // Age was not a number so so whatever you want here // Or you can return a dummy person record throw new InvalidOperationException("Records is not valid."); }).ToList(); return persons; } ``` Use it like this: ``` string records = "0=Child|13=Teen|18=Adult"; var persons = Parse(records); var p1Maturity = persons[0].Maturity; ``` --- **Performance** Choose usability and code clarity firstly. Do not worry about performance if it is not an issue yet. Do performance testing and if the above code is the bottleneck then you can optimize it. --- **Possible Enhancements** You can add another property to the `PersonRecord` class `MaxAge` if you need/want and more methods and properties depending on your needs.
42,734,801
everyone! I'm using matplotlib and I have a field with randomly generated circles. Also I have button which has to generate new random circles in the field but every time I press it, circles are generated inside the BUTTON, but not in the field. Please show me what I'm doing wrong, I'm new to python(actually started learning it yesterday). Here is my code: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Button plt.subplots_adjust(bottom=0.2) N = 10 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * 0.2 l = plt.scatter(x, y, s=area, c=colors, alpha=0.8) def gen(event): N = 10 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * 0.2 plt.scatter(x, y, s=area, c=colors, alpha=0.8) plt.draw() axgen = plt.axes([0.81, 0.05, 0.1, 0.075]) bgen = Button(axgen, 'Generate') bgen.on_clicked(gen) plt.show() ``` ![enter image description here](https://i.stack.imgur.com/LUXKT.png)
2017/03/11
[ "https://Stackoverflow.com/questions/42734801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Create a class like below: ``` public class PersonRecord { public int MinAge { get; set; } public string Maturity { get; set; } } ``` Create a method which will parse the string like below: ``` public static List<PersonRecord> Parse(string records) { var splits = records.Split('|'); var persons = splits.Select(p => { int age; var split = p.Split('='); if(int.TryParse(split[0], out age)) { return new PersonRecord { MinAge = age, Maturity = split[1] }; } // Age was not a number so so whatever you want here // Or you can return a dummy person record throw new InvalidOperationException("Records is not valid."); }).ToList(); return persons; } ``` Use it like this: ``` string records = "0=Child|13=Teen|18=Adult"; var persons = Parse(records); var p1Maturity = persons[0].Maturity; ``` --- **Performance** Choose usability and code clarity firstly. Do not worry about performance if it is not an issue yet. Do performance testing and if the above code is the bottleneck then you can optimize it. --- **Possible Enhancements** You can add another property to the `PersonRecord` class `MaxAge` if you need/want and more methods and properties depending on your needs.
try this ``` string str = "0=Child|13=Teen|18=Adult"; List<string> seplist = str.Split('|').ToList(); int Age = 14; string Maturity = string.Empty; foreach (var item in seplist) { var part = item.Split('='); if (int.Parse(part.First()) <= Age) Maturity = part.Last(); else { if (int.Parse(part.First()) > Age) break; } } Console.WriteLine(Maturity); Console.ReadLine(); ```
42,734,801
everyone! I'm using matplotlib and I have a field with randomly generated circles. Also I have button which has to generate new random circles in the field but every time I press it, circles are generated inside the BUTTON, but not in the field. Please show me what I'm doing wrong, I'm new to python(actually started learning it yesterday). Here is my code: ``` import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Button plt.subplots_adjust(bottom=0.2) N = 10 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * 0.2 l = plt.scatter(x, y, s=area, c=colors, alpha=0.8) def gen(event): N = 10 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = np.pi * 0.2 plt.scatter(x, y, s=area, c=colors, alpha=0.8) plt.draw() axgen = plt.axes([0.81, 0.05, 0.1, 0.075]) bgen = Button(axgen, 'Generate') bgen.on_clicked(gen) plt.show() ``` ![enter image description here](https://i.stack.imgur.com/LUXKT.png)
2017/03/11
[ "https://Stackoverflow.com/questions/42734801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What you have is efficient enough, really. In this context almost anything you could dream up is efficient enough, but for neatness? Well, I would've at least refactored the conversion into a function, and do you really need a long int to store the age levels? I doubt it as humans generally don't become *that* old. I would just go for a regular int. Something like this: ``` int ConvertFromMaturityConfig(string maturityConfig) { string ageString = maturityConfig.Split('=')[0]; return int.Parse(ageString); } ``` Usage: ``` string maturity = "0=Child|13=Teen|18=Adult"; string[] configuration = maturity.Split('|'); int childAgeMin = ConvertFromMaturityConfig(configuration[0]); int teenAgeMin = ConvertFromMaturityConfig(configuration[1]); int adultAgeMin = ConvertFromMaturityConfig(configuration[2]); ``` I would also consider trying to determine which configuration belongs to which value. As it is, you're expecting you get the child age, the teen age and the adult age, in that order. Personally, with the constraints you have, I would've put it into a dictionary so that you could look it up there. Then you could have something like this: ``` string maturity = "0=Child|13=Teen|18=Adult"; var config = maturity.Split('|') .Select(s => s.Split('=')) .ToDictionary( c => c[1], // key selector c => int.Parse(c[0])); ``` Then you can use it like this: ``` if (age >= config["Child"] && age < config["Teen"]) maturity = "Child"; else if (age >= config["Teen"] && age < config["Adult"]) maturity = "Teen"; else if (age >= config["Adult"]) maturity = "Adult"; ``` You would be wise to consider what happens if the age is below the minimum child age, by the way.
try this ``` string str = "0=Child|13=Teen|18=Adult"; List<string> seplist = str.Split('|').ToList(); int Age = 14; string Maturity = string.Empty; foreach (var item in seplist) { var part = item.Split('='); if (int.Parse(part.First()) <= Age) Maturity = part.Last(); else { if (int.Parse(part.First()) > Age) break; } } Console.WriteLine(Maturity); Console.ReadLine(); ```
47,814,410
I have an array of numbers, for example (calendar days): 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 I want to highlight every three numbers after two. So it should looks like: **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** Or it can be two after two, or four after two or any other pair. I need some algorithm to make this work, help please.
2017/12/14
[ "https://Stackoverflow.com/questions/47814410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1379147/" ]
You can use modulo `%`. If modulo is less than or equal to 2 (0,1,2) highlight it. ``` $arr = array(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); foreach( $arr as $key => $value ) { if ( ( $key % 5 ) <= 2 ) echo "<b>" . $value . "</b>"; else echo $value; echo "<br />"; } ```
You can achieve this with a simple `mod` on `$i` in a for loop: ``` for ($i = 0; $i < 31; $i++) { if ($i%5 == 1 || $i%5 == 2 || $i%5 == 3 ) { echo "<strong>" . $i . "</strong>"; } else { echo $i; } } ``` It will need slight adjustments to output how you need it output, but the general logic should work. Check here for a working example <https://ideone.com/bpgdgm>
47,814,410
I have an array of numbers, for example (calendar days): 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 I want to highlight every three numbers after two. So it should looks like: **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** Or it can be two after two, or four after two or any other pair. I need some algorithm to make this work, help please.
2017/12/14
[ "https://Stackoverflow.com/questions/47814410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1379147/" ]
Here is one method using [array\_slice](http://php.net/manual/en/function.array-slice.php) and [implode](http://php.net/manual/en/function.implode.php) to build the string. This does fewer loops. How many loops depends on the "settings". In this case you mention it makes seven loops compared to 31 when you loop every value of the array. ``` $days = range(1,31); $i = 3; // consecutive bolded days $j = 2; // consecutive not bolded days between the bolded $str =""; for($k=0;$k<end($days);){ $str .= "<b>" . implode("</b> <b>", array_slice($days, $k,$i)) ."</b> " . implode(" ", array_slice($days, $k+$i, $j)). " "; $k=$k+$i+$j; } echo $str; ``` <https://3v4l.org/CpoVb> Array\_slice captures first the values that should be bolded, then captures the ones that should not be bolded until the next "bold" value and stores it in $str.
You can achieve this with a simple `mod` on `$i` in a for loop: ``` for ($i = 0; $i < 31; $i++) { if ($i%5 == 1 || $i%5 == 2 || $i%5 == 3 ) { echo "<strong>" . $i . "</strong>"; } else { echo $i; } } ``` It will need slight adjustments to output how you need it output, but the general logic should work. Check here for a working example <https://ideone.com/bpgdgm>
47,814,410
I have an array of numbers, for example (calendar days): 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 I want to highlight every three numbers after two. So it should looks like: **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** Or it can be two after two, or four after two or any other pair. I need some algorithm to make this work, help please.
2017/12/14
[ "https://Stackoverflow.com/questions/47814410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1379147/" ]
You can use modulo `%`. If modulo is less than or equal to 2 (0,1,2) highlight it. ``` $arr = array(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); foreach( $arr as $key => $value ) { if ( ( $key % 5 ) <= 2 ) echo "<b>" . $value . "</b>"; else echo $value; echo "<br />"; } ```
Here is one method using [array\_slice](http://php.net/manual/en/function.array-slice.php) and [implode](http://php.net/manual/en/function.implode.php) to build the string. This does fewer loops. How many loops depends on the "settings". In this case you mention it makes seven loops compared to 31 when you loop every value of the array. ``` $days = range(1,31); $i = 3; // consecutive bolded days $j = 2; // consecutive not bolded days between the bolded $str =""; for($k=0;$k<end($days);){ $str .= "<b>" . implode("</b> <b>", array_slice($days, $k,$i)) ."</b> " . implode(" ", array_slice($days, $k+$i, $j)). " "; $k=$k+$i+$j; } echo $str; ``` <https://3v4l.org/CpoVb> Array\_slice captures first the values that should be bolded, then captures the ones that should not be bolded until the next "bold" value and stores it in $str.
1,337
When asking an "ID My Bike" question what information about the bike should I include? Would a good "ID My Bike" question need all of the following or are there a few key things that would offer the best chance of an ID? Maybe something like - if these three things are included the chance of ID is 50/50. If these two things are added to that the chance goes up to 80% **Pictures** (maybe some coaching on how to take good pictures) * every major frame joint * all decals/logos/stamped names * every component * Other **Words** * Serial number * Information about my current knowledge of the bike * Links to information I have found so far * Other
2019/05/28
[ "https://bicycles.meta.stackexchange.com/questions/1337", "https://bicycles.meta.stackexchange.com", "https://bicycles.meta.stackexchange.com/users/41662/" ]
In order to ID a bike a question **must have**: At least one clear picture. If there is no picture there is zero chance of providing an ID. The question will be closed. The picture should be high resolution (any modern smart-phone will work) In the picture the bike should be: - well lit - right side up (sitting on it's wheels) - of the whole bike - from the chain side of the bike flat on. Pictures of the following are helpful: - head badge ( on the front of the frame) - logos - decals - distinctive frame features (lug work, square tubing, etc.) Other helpful information: - Country in which the bike is located. - What has already learned or is known about the bike. Here is an example of a good picture. [![Required and Optional Pictures](https://i.stack.imgur.com/pXhFv.png)](https://i.stack.imgur.com/pXhFv.png) This answer is a summary of the excellent answers provided by Argenti Apparatus and Criggie
First, accept that the chances of your bike manufacturer, brand or model being identified are low, effectively zero in many cases (repainted BMX frames, generic 80's drop bar ten-speeds, 90's inexpensive hybrids ...) Having seen a great many id-my-bike questions on this site I think the goal is not so much getting the bike identified but avoiding looking like an idiot, collecting sarcastic comments and getting your question closed as a duplicate of [Why shouldn't I care what model/make/year my bicycle is?](https://bicycles.stackexchange.com/questions/52060/why-shouldnt-i-care-what-model-make-year-my-bicycle-is) within 20 minutes. That said ... An absolute necessity is well lit, high resolution, straight-on photo of the whole bike, right way up, from the drive side, with an uncluttered background. Include the year of sale when new if you know it (or a guess). Description or photos of major groupset components helps. Knowing the series/level of derailleurs, crank, shifters, wheels etc. can help narrow down the year range and model level. Any other info or photos you can provide won't hurt, but don't raise the probability of an identification much it seems. A piece of info that is generally left out that I think might help in some cases is the country or location where the bike is. Including the serial number generally won't help. Collectors have made databases of numbers of a few collectable brands, and sometimes someone will be able to decode a numbering scheme, but in general they are meaningless as manufacturers don't provide a serial number lookup that will provide model or component configuration to the public.
1,337
When asking an "ID My Bike" question what information about the bike should I include? Would a good "ID My Bike" question need all of the following or are there a few key things that would offer the best chance of an ID? Maybe something like - if these three things are included the chance of ID is 50/50. If these two things are added to that the chance goes up to 80% **Pictures** (maybe some coaching on how to take good pictures) * every major frame joint * all decals/logos/stamped names * every component * Other **Words** * Serial number * Information about my current knowledge of the bike * Links to information I have found so far * Other
2019/05/28
[ "https://bicycles.meta.stackexchange.com/questions/1337", "https://bicycles.meta.stackexchange.com", "https://bicycles.meta.stackexchange.com/users/41662/" ]
First, accept that the chances of your bike manufacturer, brand or model being identified are low, effectively zero in many cases (repainted BMX frames, generic 80's drop bar ten-speeds, 90's inexpensive hybrids ...) Having seen a great many id-my-bike questions on this site I think the goal is not so much getting the bike identified but avoiding looking like an idiot, collecting sarcastic comments and getting your question closed as a duplicate of [Why shouldn't I care what model/make/year my bicycle is?](https://bicycles.stackexchange.com/questions/52060/why-shouldnt-i-care-what-model-make-year-my-bicycle-is) within 20 minutes. That said ... An absolute necessity is well lit, high resolution, straight-on photo of the whole bike, right way up, from the drive side, with an uncluttered background. Include the year of sale when new if you know it (or a guess). Description or photos of major groupset components helps. Knowing the series/level of derailleurs, crank, shifters, wheels etc. can help narrow down the year range and model level. Any other info or photos you can provide won't hurt, but don't raise the probability of an identification much it seems. A piece of info that is generally left out that I think might help in some cases is the country or location where the bike is. Including the serial number generally won't help. Collectors have made databases of numbers of a few collectable brands, and sometimes someone will be able to decode a numbering scheme, but in general they are meaningless as manufacturers don't provide a serial number lookup that will provide model or component configuration to the public.
This answer emphasizes a few things in other answers for clarity. In general, we ask for clear photographs of the entire bike, and preferably some close ups of select parts as well. Be aware that these are usually necessary *but not sufficient* to ID a manufacturer, model, and year. Identifying a manufacturer is easier, identifying model and year is harder. Bicycle companies typically rely on decals, usually on the down tube at minimum, and head tube badges for branding. If you have those in the photo, you usually know who the bicycle *manufacturer* is. Of course, if those items are present, then the OP usually has the information to identify the manufacturer already. Nevertheless, not all head badges state the manufacturer clearly, but they can be recognized by enthusiasts. One example is Giant Bicycles' head tube badge. Naturally, some bicycles have had their decals and/or head badges removed. Failing that, with steel bikes, the design of the frame lugs and fork crown lugs can sometimes be informative, although not all frames use lugged construction. Some other design elements on bikes in general can be distinctive, which is why Criggie mentioned things like unusual-looking dropouts, sometimes the seat cluster. As another example, some Colnago steel bicycles (e.g. Master and Master X-Lite) used star-shaped down tubes on the argument that they had higher torsional rigidity, and I don't believe anyone else used these. I think that these unusual design elements are more rare, however. Identifying the *model* and manufacturing *year* of the bicycle can be harder. Sometimes, enthusiasts can match a paint scheme to a catalog, thus providing model and year - if someone posted a scanned catalog online, or if they collect catalogs, or if there's an example of the bike online, e.g. on Bicycle Blue Book (but that tends to cover more modern bikes). We can make guesses if we recognize the components or other frame features. For example, in the first photo Criggie posted, the components look like 9-speed Shimano 105, which was current in the early 2000s. The bike has a quill stem, rather than a threadless headset and stem, and these were less common on early 2000s bikes. So, it's possible the bike is from around the early 2000s, but it's also possible the components were refitted and the bike was from the 1990s. It's been stated elsewhere, but the serial number is usually not helpful at all. Presenting the serial number alone is worthless, and it is quite possible that the question will get downvoted and maybe closed.
1,337
When asking an "ID My Bike" question what information about the bike should I include? Would a good "ID My Bike" question need all of the following or are there a few key things that would offer the best chance of an ID? Maybe something like - if these three things are included the chance of ID is 50/50. If these two things are added to that the chance goes up to 80% **Pictures** (maybe some coaching on how to take good pictures) * every major frame joint * all decals/logos/stamped names * every component * Other **Words** * Serial number * Information about my current knowledge of the bike * Links to information I have found so far * Other
2019/05/28
[ "https://bicycles.meta.stackexchange.com/questions/1337", "https://bicycles.meta.stackexchange.com", "https://bicycles.meta.stackexchange.com/users/41662/" ]
In order to ID a bike a question **must have**: At least one clear picture. If there is no picture there is zero chance of providing an ID. The question will be closed. The picture should be high resolution (any modern smart-phone will work) In the picture the bike should be: - well lit - right side up (sitting on it's wheels) - of the whole bike - from the chain side of the bike flat on. Pictures of the following are helpful: - head badge ( on the front of the frame) - logos - decals - distinctive frame features (lug work, square tubing, etc.) Other helpful information: - Country in which the bike is located. - What has already learned or is known about the bike. Here is an example of a good picture. [![Required and Optional Pictures](https://i.stack.imgur.com/pXhFv.png)](https://i.stack.imgur.com/pXhFv.png) This answer is a summary of the excellent answers provided by Argenti Apparatus and Criggie
**Photos** a. the first photo should be a clear and well lit shot of the right-hand side of the bike. Ideally it should be sunlit or good incandescent or LED lighting. Avoid fluorescent tube lighting at all costs. b. the bike should be clean-ish. Doesn't have to be concours level but we need to see the details and small features. c. Show the whole bike, not just the frame. d. high resolution - let us zoom in. The SE limit is 2 Mbytes on an uploaded photo. If that's not enough, upload your photo directly to <http://Imgur.com/> and share the link. e. Right-way up! Don't send in photos of the bike lying in a heap - try and get a view point that equates to about 2~3 metres from the bike, equidistant between wheel axles, and at a height somewhere even with the saddle or top tube. f. Don't care about valve angles and crank angles, though trying to leave text visible is helpful. Here's a workable photo - a plain background would have helped. [![Own work](https://i.stack.imgur.com/tZKDj.jpg)](https://i.stack.imgur.com/tZKDj.jpg) You can read off that its a shimano 105 groupset with dual pivot rim brakes and brifters, so the mechanicals are decades newer than the frame. Another good photo from a successful ID question at [Identify old bicycle w/locking steering column?](https://bicycles.stackexchange.com/questions/58308/identify-old-bicycle-w-locking-steering-column) Yes its inside, but the image is clear and well lit. [![enter image description here](https://i.stack.imgur.com/rr3ru.jpg)](https://i.stack.imgur.com/rr3ru.jpg) Not terrible but not great photos for ID purposes: [![enter image description here](https://i.stack.imgur.com/MfMzU.jpg)](https://i.stack.imgur.com/MfMzU.jpg) from [Looking for help identifying my newest addition](https://bicycles.stackexchange.com/questions/52085/looking-for-help-identifying-my-newest-addition) Pretty awful photo for ID purposes (though to be fair this question was somewhat focused on the logo visible) [![enter image description here](https://i.stack.imgur.com/RJc41.jpg)](https://i.stack.imgur.com/RJc41.jpg) from [What kind of bike is this? Can anyone tell by the logo?](https://bicycles.stackexchange.com/questions/43791/what-kind-of-bike-is-this-can-anyone-tell-by-the-logo) --- Subsequent photos should zoom in on points of interest - what about this bike might be unique enough to promote recognition? Standard things would include * Head badge or logo * Any decals anywhere on the bike * Strange things like writing or emblems in the frame * Odd dropouts, front or rear * Odd seat stay attachment to the seat tube * Sometimes the fork crown can be distinctive This question has some great examples of closeups on useful areas, but even so still remains without a confirmed identification. [Name that frame! (Likely Japanese, likely made in 1986, with known serial number, likely a Bianchi)](https://bicycles.stackexchange.com/questions/20847/name-that-frame-likely-japanese-likely-made-in-1986-with-known-serial-number) Component close ups might help with dating, but often the components are used on many different bikes from different assemblers, and they can be changed after purchase. So a bike with "Shimano" on it is not a lot of help.
1,337
When asking an "ID My Bike" question what information about the bike should I include? Would a good "ID My Bike" question need all of the following or are there a few key things that would offer the best chance of an ID? Maybe something like - if these three things are included the chance of ID is 50/50. If these two things are added to that the chance goes up to 80% **Pictures** (maybe some coaching on how to take good pictures) * every major frame joint * all decals/logos/stamped names * every component * Other **Words** * Serial number * Information about my current knowledge of the bike * Links to information I have found so far * Other
2019/05/28
[ "https://bicycles.meta.stackexchange.com/questions/1337", "https://bicycles.meta.stackexchange.com", "https://bicycles.meta.stackexchange.com/users/41662/" ]
**Photos** a. the first photo should be a clear and well lit shot of the right-hand side of the bike. Ideally it should be sunlit or good incandescent or LED lighting. Avoid fluorescent tube lighting at all costs. b. the bike should be clean-ish. Doesn't have to be concours level but we need to see the details and small features. c. Show the whole bike, not just the frame. d. high resolution - let us zoom in. The SE limit is 2 Mbytes on an uploaded photo. If that's not enough, upload your photo directly to <http://Imgur.com/> and share the link. e. Right-way up! Don't send in photos of the bike lying in a heap - try and get a view point that equates to about 2~3 metres from the bike, equidistant between wheel axles, and at a height somewhere even with the saddle or top tube. f. Don't care about valve angles and crank angles, though trying to leave text visible is helpful. Here's a workable photo - a plain background would have helped. [![Own work](https://i.stack.imgur.com/tZKDj.jpg)](https://i.stack.imgur.com/tZKDj.jpg) You can read off that its a shimano 105 groupset with dual pivot rim brakes and brifters, so the mechanicals are decades newer than the frame. Another good photo from a successful ID question at [Identify old bicycle w/locking steering column?](https://bicycles.stackexchange.com/questions/58308/identify-old-bicycle-w-locking-steering-column) Yes its inside, but the image is clear and well lit. [![enter image description here](https://i.stack.imgur.com/rr3ru.jpg)](https://i.stack.imgur.com/rr3ru.jpg) Not terrible but not great photos for ID purposes: [![enter image description here](https://i.stack.imgur.com/MfMzU.jpg)](https://i.stack.imgur.com/MfMzU.jpg) from [Looking for help identifying my newest addition](https://bicycles.stackexchange.com/questions/52085/looking-for-help-identifying-my-newest-addition) Pretty awful photo for ID purposes (though to be fair this question was somewhat focused on the logo visible) [![enter image description here](https://i.stack.imgur.com/RJc41.jpg)](https://i.stack.imgur.com/RJc41.jpg) from [What kind of bike is this? Can anyone tell by the logo?](https://bicycles.stackexchange.com/questions/43791/what-kind-of-bike-is-this-can-anyone-tell-by-the-logo) --- Subsequent photos should zoom in on points of interest - what about this bike might be unique enough to promote recognition? Standard things would include * Head badge or logo * Any decals anywhere on the bike * Strange things like writing or emblems in the frame * Odd dropouts, front or rear * Odd seat stay attachment to the seat tube * Sometimes the fork crown can be distinctive This question has some great examples of closeups on useful areas, but even so still remains without a confirmed identification. [Name that frame! (Likely Japanese, likely made in 1986, with known serial number, likely a Bianchi)](https://bicycles.stackexchange.com/questions/20847/name-that-frame-likely-japanese-likely-made-in-1986-with-known-serial-number) Component close ups might help with dating, but often the components are used on many different bikes from different assemblers, and they can be changed after purchase. So a bike with "Shimano" on it is not a lot of help.
This answer emphasizes a few things in other answers for clarity. In general, we ask for clear photographs of the entire bike, and preferably some close ups of select parts as well. Be aware that these are usually necessary *but not sufficient* to ID a manufacturer, model, and year. Identifying a manufacturer is easier, identifying model and year is harder. Bicycle companies typically rely on decals, usually on the down tube at minimum, and head tube badges for branding. If you have those in the photo, you usually know who the bicycle *manufacturer* is. Of course, if those items are present, then the OP usually has the information to identify the manufacturer already. Nevertheless, not all head badges state the manufacturer clearly, but they can be recognized by enthusiasts. One example is Giant Bicycles' head tube badge. Naturally, some bicycles have had their decals and/or head badges removed. Failing that, with steel bikes, the design of the frame lugs and fork crown lugs can sometimes be informative, although not all frames use lugged construction. Some other design elements on bikes in general can be distinctive, which is why Criggie mentioned things like unusual-looking dropouts, sometimes the seat cluster. As another example, some Colnago steel bicycles (e.g. Master and Master X-Lite) used star-shaped down tubes on the argument that they had higher torsional rigidity, and I don't believe anyone else used these. I think that these unusual design elements are more rare, however. Identifying the *model* and manufacturing *year* of the bicycle can be harder. Sometimes, enthusiasts can match a paint scheme to a catalog, thus providing model and year - if someone posted a scanned catalog online, or if they collect catalogs, or if there's an example of the bike online, e.g. on Bicycle Blue Book (but that tends to cover more modern bikes). We can make guesses if we recognize the components or other frame features. For example, in the first photo Criggie posted, the components look like 9-speed Shimano 105, which was current in the early 2000s. The bike has a quill stem, rather than a threadless headset and stem, and these were less common on early 2000s bikes. So, it's possible the bike is from around the early 2000s, but it's also possible the components were refitted and the bike was from the 1990s. It's been stated elsewhere, but the serial number is usually not helpful at all. Presenting the serial number alone is worthless, and it is quite possible that the question will get downvoted and maybe closed.
1,337
When asking an "ID My Bike" question what information about the bike should I include? Would a good "ID My Bike" question need all of the following or are there a few key things that would offer the best chance of an ID? Maybe something like - if these three things are included the chance of ID is 50/50. If these two things are added to that the chance goes up to 80% **Pictures** (maybe some coaching on how to take good pictures) * every major frame joint * all decals/logos/stamped names * every component * Other **Words** * Serial number * Information about my current knowledge of the bike * Links to information I have found so far * Other
2019/05/28
[ "https://bicycles.meta.stackexchange.com/questions/1337", "https://bicycles.meta.stackexchange.com", "https://bicycles.meta.stackexchange.com/users/41662/" ]
In order to ID a bike a question **must have**: At least one clear picture. If there is no picture there is zero chance of providing an ID. The question will be closed. The picture should be high resolution (any modern smart-phone will work) In the picture the bike should be: - well lit - right side up (sitting on it's wheels) - of the whole bike - from the chain side of the bike flat on. Pictures of the following are helpful: - head badge ( on the front of the frame) - logos - decals - distinctive frame features (lug work, square tubing, etc.) Other helpful information: - Country in which the bike is located. - What has already learned or is known about the bike. Here is an example of a good picture. [![Required and Optional Pictures](https://i.stack.imgur.com/pXhFv.png)](https://i.stack.imgur.com/pXhFv.png) This answer is a summary of the excellent answers provided by Argenti Apparatus and Criggie
This answer emphasizes a few things in other answers for clarity. In general, we ask for clear photographs of the entire bike, and preferably some close ups of select parts as well. Be aware that these are usually necessary *but not sufficient* to ID a manufacturer, model, and year. Identifying a manufacturer is easier, identifying model and year is harder. Bicycle companies typically rely on decals, usually on the down tube at minimum, and head tube badges for branding. If you have those in the photo, you usually know who the bicycle *manufacturer* is. Of course, if those items are present, then the OP usually has the information to identify the manufacturer already. Nevertheless, not all head badges state the manufacturer clearly, but they can be recognized by enthusiasts. One example is Giant Bicycles' head tube badge. Naturally, some bicycles have had their decals and/or head badges removed. Failing that, with steel bikes, the design of the frame lugs and fork crown lugs can sometimes be informative, although not all frames use lugged construction. Some other design elements on bikes in general can be distinctive, which is why Criggie mentioned things like unusual-looking dropouts, sometimes the seat cluster. As another example, some Colnago steel bicycles (e.g. Master and Master X-Lite) used star-shaped down tubes on the argument that they had higher torsional rigidity, and I don't believe anyone else used these. I think that these unusual design elements are more rare, however. Identifying the *model* and manufacturing *year* of the bicycle can be harder. Sometimes, enthusiasts can match a paint scheme to a catalog, thus providing model and year - if someone posted a scanned catalog online, or if they collect catalogs, or if there's an example of the bike online, e.g. on Bicycle Blue Book (but that tends to cover more modern bikes). We can make guesses if we recognize the components or other frame features. For example, in the first photo Criggie posted, the components look like 9-speed Shimano 105, which was current in the early 2000s. The bike has a quill stem, rather than a threadless headset and stem, and these were less common on early 2000s bikes. So, it's possible the bike is from around the early 2000s, but it's also possible the components were refitted and the bike was from the 1990s. It's been stated elsewhere, but the serial number is usually not helpful at all. Presenting the serial number alone is worthless, and it is quite possible that the question will get downvoted and maybe closed.
50,187,829
I want from `path="/users/:login/:repo"` to view login's repo detail page but it doesn't work and views UserProfile component. Here is the click: ``` <Link to={this.props.location.pathname+'/'+item.name}> <div> <h4>{item.name}</h4> <p>{item.description} </p> </div> </Link> <Switch> <Route exact path="/" component={Contributors}/> <Route path="/users/:login" component={UserProfile}/> <Route path="/users/:login/:repo" component={RepoPage}/> </Switch> ```
2018/05/05
[ "https://Stackoverflow.com/questions/50187829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4868320/" ]
You need to reverse the ordering of your routes, since `Switch` matches the first route ``` <Switch> <Route exact path="/" component={Contributors}/> <Route path="/users/:login/:repo" component={RepoPage}/> <Route path="/users/:login" component={UserProfile}/> </Switch> ``` With React-router the paths that are prefixes to the exactly matching path are also matched and hence `"/users/:login/:repo"` also matches `"/users/:login"`, and since you are using switch, RepoPage is getting rendered and not other Routes defined after this are getting checked.
Any url matched by `"/users/:login/:repo"` will be matched by `"/users/:login"` as well, unless you use `exact` qualifier. In the context of `Switch` it means that `UserProfile` will be rendered every time because it comes first. Solution would be to change: ``` <Route path="/users/:login" component={UserProfile}/> ``` to ``` <Route exact path="/users/:login" component={UserProfile}/> ```
57,588
I observed that dictators often appoint highly educated and qualified technocrats as advisors or spokespersons. For example, * Dr. Gowher Rizvi, advisor to Sheikh Hasina, Ph.D. from Oxford University. * Ibrahim Kalin, spokesperson of Erdogan, Ph.D. from George Washington University. * Bouthaina Shaaban, advisor to Bashar Al Assad, Ph.D. from the University of Warwick. * etc. My question is, Do dictators find such people, Or, those people find dictators?
2020/09/28
[ "https://politics.stackexchange.com/questions/57588", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/32479/" ]
> > Do dictators find such people, Or, those people find dictators? > > > It's mutual. Dictators need someone to "make the trains run on time" and operating a modern state is a complex enterprise beyond the capacity of the ambitious soldiers and politicians who usually end up as dictators to do without expert advice for very long. So, like any other executive leading a large organization, they hire people to fill these posts and look for people who can provide them with quality advice. In many cases, their view of what quality advice looks like is quite mainstream. Many dictators are not particularly ideologically pure and they often don't have well worked out policy doctrines themselves, instead seizing upon a historical moment to take power when it arises. Hitler and Mao's manifestos were the exception and not the rule among dictators. Ideologically driven and thought out agendas are more common among small "d" democratic politicians and revolutionaries (who often fail entirely or have short lived regimes) in order to persuade large numbers of mid-level elites to join their movement. In contrast, run of the mill dictators tend to be less ideological than political genius manifesto writers. They frequently step into a power vacuum marked by chaos, corruption and incompetence on the part of the democratically elected regimes that they replace, or the incompetence of their authoritarian predecessors whom they replace. Since dictators often rise to power based upon the gross incompetence of a predecessor, being able to show some level of competence is often a significant goal for the new dictator if the dictator wishes to hold onto power for long. Skilled professionals need jobs and also believe in their ideas and long to test out those ideas. Dictatorships allow intellectuals to implement their ideas rapidly and uncompromisingly in a way that democratic political processes which tend towards incrementalism and traditional solutions to social and economic problems rarely do. A famous historical example of this is the advice provided by famed democratic free market supporter and premier economist [Milton Friedman](https://en.wikipedia.org/wiki/Milton_Friedman#Chile) who provided economic guidance to military dictator President Augusto Pinochet in Chile the 1970s. Friedman was heavily criticized for this and later attempted to publicly justify his involvement as a voice for positive change from within the regime in the long run (from the same link). > > During the 2000 PBS documentary The Commanding Heights (based on the > book), Friedman continued to argue that "free markets would undermine > [Pinochet's] political centralization and political control.", and > that criticism over his role in Chile missed his main contention that > freer markets resulted in freer people, and that Chile's unfree > economy had caused the military government. Friedman advocated for > free markets which undermined "political centralization and political > control". > > >
A simple factual analysis leads to the following conclusion: the autocratic power that dictators hold may not have been granted through a process reflecting the will of some concept of majority of the citizens in the country but, see, their decisions are not based on their whims or personal interests, but on solid technocratic advise - hence the PhDs. So there is a certain drive from the dictator's side to seek out technocrats. In other words, it can be seen as a marketing tactic to make the political product "dictatorship" more palatable to end-users (or end-sufferers, as the case may be). In principle, this does not eliminate the possibility that these technocrats are seriously listened to, and they may be listened to in matters "not politically sensitive". But historical experience says that in a dictatorship *everything* is considered "politically sensitive", so this possibility has rather low probability. Note that we are talking here about "technocrats as *personal advisors* to dictators", not "technocrats as part of the wider government system". Of course, elected officials in countries with representative systems, also tend to use technocrats as advisors. Casual observation indicates that the reason here is slightly different: Not so much to provide credibility to decisions taken, but to take away responsibility for them, if the need arises: if the decision is unpopular or is deemed a failure, well, it wasn't us, the technocrats told us to do it.
43,998,352
I am using netCDF4 to store multidimensional data. The data has, for example, three dimensions, `time = [0, 1, 2]`, `height = [10, 20]`, `direction = [0, 120, 180, 240, 300]`, but not for all combinations (grid points) there is data. In our example, let this be limited to `height`/`direction`-combinations. Namely, suppose that at `height == 10` we have data only for `direction in {0, 120, 240}` and at `height == 20` only for `direction in {120, 180, 300}`. The approaches for dealing with this I see are: 1. Use a separate unidimensional `Variable` for each `height`/`direction`-combination. 2. Use a single three-dimensional `Variable` over the Cartesian product, i.e., all possible combinations, and live with the fact that for some combinations all values are masked. 3. Use different location dimension definitions for each height and a two-dimensional `Variable` for each height. Are there other approaches and what are reasons, both principled as well as practical, for preferring one approach over another?
2017/05/16
[ "https://Stackoverflow.com/questions/43998352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/671672/" ]
Basically your answer number 2 is the correct one. NETCDF files are gridded files, and so the natural structure for the data describe is to define three dimensions, time, height and direction. For the array entries for which data does not exist you need to set the data to equal the value defined by the metadata: ``` _FillValue ``` This means that any software such as R, python, ncview etc that is reading the data will assign these points as "missing". For more details on defining missing values see: <http://www.unidata.ucar.edu/software/netcdf/docs/fill_values.html>
When reading up on metadata conventions, I encountered another option: ‘[compression by gathering](http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#compression-by-gathering)’ of the `height` and `direction` variables into a single `location variable`. How would this work in the toy example? First gather all locations into a one-dimensional list: ``` 0: 10,0 * 1: 10,120 * 2: 10,180 3: 10,240 * 4: 10,300 5: 20,0 6: 20,120 * 7: 20,180 * 8: 20,240 9: 20,300 * ``` Then `location = [0, 1, 3, 6, 7, 9]` and data is defined using only two dimensions, `location`, which has a `compress: "height direction"` attribute, and `time`. Probably it is best to add a two-dimensional auxiliary coordinate variable to make the relationship between the location indices and the `height/direction` value explicit: `height_direction = [(10,0), (10,120), (10,240), (20,120), (20,180), (0,300)]`. Given that there seems to be no library support for this, it is not necessarily the most convenient option in all respects. However, it does seem a legitimate option to consider given that it is encoded in a metadata standard, “[NetCDF Climate and Forecast (CF) Metadata Conventions](http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html)”.
2,559,314
I recently looked at the proof given for the fundamental theorem of calculus in this link: [Why is the area under a curve the integral?](https://math.stackexchange.com/questions/15294/why-is-the-area-under-a-curve-the-integral/15301#15301) It made perfect sense, except for one thing. The proof relies on creating a function $F(b)$ that gives the area under the curve $f(x)$ from $0$ to some real number $b$ so that in essence $F(b) = \int\_{0}^{b}f(x)dx $ and then proved that $F(b)$ is the anti derivative of $f(x)$. However, if we define the integral in this way, then it seems strange that when integrating a function from 0 to a value b we have to evaluate $F(b)-F(0)$ rather than just evaluate $F(b)$. Since the former would generally imply that if we want to find the area under the curve from a to b, then given the definition of an integral, we simply have to subtract the area from 0 to a from the area from 0 to b. Which in this case makes no sense, since we would be subtracting the area from 0 to 0, ie. 0 from the area from 0 to b. Which means we could just discard the first part of the evaluation, yet this would cause us problems if we wanted to evaluate something like $ \int\_{0}^{\pi/2}sin(x)dx $ which would be zero if we just evaluate the antiderivative of sin(x) at $\pi/2$.
2017/12/10
[ "https://math.stackexchange.com/questions/2559314", "https://math.stackexchange.com", "https://math.stackexchange.com/users/446153/" ]
In the notation of the post you linked to, you are confusing $\mathcal{M}$ and $F$. What you are calling $F(b)$, a function which measures the area under the curve from $0$ to $b$, is what the post calls $\mathcal{M}(b)$. The function $F$ is instead *any* antiderivative of $f$. That is, we know *nothing* about $F$ at all other than that it is *some* function whose derivative is $f$. This doesn't mean that $F$ is the same as $\mathcal{M}$, since a function can have more than one antiderivative! Indeed, for any constant $C$, $F(x)=\mathcal{M}(x)+C$ is another antiderivative of $f$, since adding a constant does not change the derivative. However, this is the only way to get another antiderivative: if $F$ is an antiderivative of $f$, then $F'(x)-\mathcal{M}'(x)=f(x)-f(x)=0$, so the function $F(x)-\mathcal{M}(x)$ has derivative $0$ and hence is a constant. So, we're starting with some function $F$ which is an antiderivative, but what we actually want is $\mathcal{M}$. To fix this, we have to subtract a constant from $F$, and that constant is exactly $F(0)$, since $\mathcal{M}(0)=0$.
Adding to what Dylan said, I think you are misunderstanding how to calculate a definite integral, as in your example: There are three steps to calculating one, which are: $1)$ Find the *indefinite integral* - the integral without the bounds: $\int \sin x = -\cos x$ (the classical way is to prove this by Taylor series, not sure about any others) $2)$ Find the bounds: The upper bound is $-\cos{\pi/2}$ which is $0$, the lower bound is $-\cos{0}$, which is $-1.$ $3)$ Subtract the lower bound from the upper bound: $0 - (-1)$ equals $1$, which is the *signed area* - the area above the $x$-axis minus the area below.
2,559,314
I recently looked at the proof given for the fundamental theorem of calculus in this link: [Why is the area under a curve the integral?](https://math.stackexchange.com/questions/15294/why-is-the-area-under-a-curve-the-integral/15301#15301) It made perfect sense, except for one thing. The proof relies on creating a function $F(b)$ that gives the area under the curve $f(x)$ from $0$ to some real number $b$ so that in essence $F(b) = \int\_{0}^{b}f(x)dx $ and then proved that $F(b)$ is the anti derivative of $f(x)$. However, if we define the integral in this way, then it seems strange that when integrating a function from 0 to a value b we have to evaluate $F(b)-F(0)$ rather than just evaluate $F(b)$. Since the former would generally imply that if we want to find the area under the curve from a to b, then given the definition of an integral, we simply have to subtract the area from 0 to a from the area from 0 to b. Which in this case makes no sense, since we would be subtracting the area from 0 to 0, ie. 0 from the area from 0 to b. Which means we could just discard the first part of the evaluation, yet this would cause us problems if we wanted to evaluate something like $ \int\_{0}^{\pi/2}sin(x)dx $ which would be zero if we just evaluate the antiderivative of sin(x) at $\pi/2$.
2017/12/10
[ "https://math.stackexchange.com/questions/2559314", "https://math.stackexchange.com", "https://math.stackexchange.com/users/446153/" ]
In the notation of the post you linked to, you are confusing $\mathcal{M}$ and $F$. What you are calling $F(b)$, a function which measures the area under the curve from $0$ to $b$, is what the post calls $\mathcal{M}(b)$. The function $F$ is instead *any* antiderivative of $f$. That is, we know *nothing* about $F$ at all other than that it is *some* function whose derivative is $f$. This doesn't mean that $F$ is the same as $\mathcal{M}$, since a function can have more than one antiderivative! Indeed, for any constant $C$, $F(x)=\mathcal{M}(x)+C$ is another antiderivative of $f$, since adding a constant does not change the derivative. However, this is the only way to get another antiderivative: if $F$ is an antiderivative of $f$, then $F'(x)-\mathcal{M}'(x)=f(x)-f(x)=0$, so the function $F(x)-\mathcal{M}(x)$ has derivative $0$ and hence is a constant. So, we're starting with some function $F$ which is an antiderivative, but what we actually want is $\mathcal{M}$. To fix this, we have to subtract a constant from $F$, and that constant is exactly $F(0)$, since $\mathcal{M}(0)=0$.
From my point.of view a simple way to see this fact is to consider the integral function: $$F(x) = \int\_{0}^{x}f(t)dt $$ that rapresent the area “under” the graph from 0 to x. Now if we think to calculate its derivative is pretty clear that for a small change $\Delta x$ the area varies of the quantity: $$\Delta F(x)=f(x)\cdot \Delta x$$ Thus the rate of change is $$\frac{\Delta F(x)}{\Delta x}=f(x) $$ and in the limit $$F’(x)=f(x)$$ That’s the link between the two concept. > > Now, since the derivative of a constant is zero, any constant may be added to an antiderivative and will still correspond to the same integral (i.e. the antiderivative is a nonunique inverse of the derivative). > For this reason, indefinite integrals are written in the form > $$\int f(x)dx = F(x) + c$$ > where $c$ is an arbitrary constant of integration. > > > For this reason when we evaluate a definite integral we need to calculate it as a difference, just to eliminate the constant of integration. > > >
2,559,314
I recently looked at the proof given for the fundamental theorem of calculus in this link: [Why is the area under a curve the integral?](https://math.stackexchange.com/questions/15294/why-is-the-area-under-a-curve-the-integral/15301#15301) It made perfect sense, except for one thing. The proof relies on creating a function $F(b)$ that gives the area under the curve $f(x)$ from $0$ to some real number $b$ so that in essence $F(b) = \int\_{0}^{b}f(x)dx $ and then proved that $F(b)$ is the anti derivative of $f(x)$. However, if we define the integral in this way, then it seems strange that when integrating a function from 0 to a value b we have to evaluate $F(b)-F(0)$ rather than just evaluate $F(b)$. Since the former would generally imply that if we want to find the area under the curve from a to b, then given the definition of an integral, we simply have to subtract the area from 0 to a from the area from 0 to b. Which in this case makes no sense, since we would be subtracting the area from 0 to 0, ie. 0 from the area from 0 to b. Which means we could just discard the first part of the evaluation, yet this would cause us problems if we wanted to evaluate something like $ \int\_{0}^{\pi/2}sin(x)dx $ which would be zero if we just evaluate the antiderivative of sin(x) at $\pi/2$.
2017/12/10
[ "https://math.stackexchange.com/questions/2559314", "https://math.stackexchange.com", "https://math.stackexchange.com/users/446153/" ]
In the notation of the post you linked to, you are confusing $\mathcal{M}$ and $F$. What you are calling $F(b)$, a function which measures the area under the curve from $0$ to $b$, is what the post calls $\mathcal{M}(b)$. The function $F$ is instead *any* antiderivative of $f$. That is, we know *nothing* about $F$ at all other than that it is *some* function whose derivative is $f$. This doesn't mean that $F$ is the same as $\mathcal{M}$, since a function can have more than one antiderivative! Indeed, for any constant $C$, $F(x)=\mathcal{M}(x)+C$ is another antiderivative of $f$, since adding a constant does not change the derivative. However, this is the only way to get another antiderivative: if $F$ is an antiderivative of $f$, then $F'(x)-\mathcal{M}'(x)=f(x)-f(x)=0$, so the function $F(x)-\mathcal{M}(x)$ has derivative $0$ and hence is a constant. So, we're starting with some function $F$ which is an antiderivative, but what we actually want is $\mathcal{M}$. To fix this, we have to subtract a constant from $F$, and that constant is exactly $F(0)$, since $\mathcal{M}(0)=0$.
An antiderivative of $f$ is a function that collects area under the graph of $f$, starting somewhere. In order to find the area from $a$ to $b$, we need to plug $x=b$ into the particular antiderivative that collects area starting at $a$. One name for this function is $$\int\_a^x f(t) \,dt$$ When we write down some random antiderivative $F$, though, we don't know if it starts in the right place. However, if we subtract $F(a)$, then we have $F(x)-F(a)$: an antiderivative that has a value of $0$ at $x=a$, which is perfect. The integral from $a$ to $b$ is what we get when we plug $b$ into the specific antiderivative given by $F(x)-F(a)$. Does this help?
36,386,358
I am trying to create UML Class Diagram for this problem: So, user is prompted to enter a password. It's a 9 digit number. System receives passwords and checks if it's correct or not by looking into database which has correct password stored inside. If the password is correct, System needs to show message "Correct". Otherwise, message "Error" is shown. If the user enters wrong password more than 5 times in a row, then System stops showing messages. I have 4 classes here, right? User, System, Database, Counter ``` ┌─────────────────────────┬ │ User │ ├─────────────────────────┬ │- pass: int | ├─────────────────────────┼ |+ EnterPass() | ├─────────────────────────┼ | * | | | | | 1 ┌─────────────────────────┬ │ System │ ├─────────────────────────┬ │ | ├─────────────────────────┼ |+ CheckPass() | |+ ShowSuccess() | |+ ShowError() | |+ ShowNothing() | |+ ChangeCategory() | ├─────────────────────────┼ | 1 | | | | | 1 ┌─────────────────────────┬ │ Database │ ├─────────────────────────┬ │- CorrectPass: int | ├─────────────────────────┼ |+ ValidatePass(): bool | |+ Increment1() | ├─────────────────────────┼ | 1 | | | | | 1 ┌─────────────────────────┬ │ Counter │ ├─────────────────────────┬ │- CounterState: int | ├─────────────────────────┼ |+ increment() | |+ GetState(): int | ├─────────────────────────┼ ``` Can someone tell me if this is correct? I am not quite sure if I should connect Counter and System somehow? Is there anything I should add?
2016/04/03
[ "https://Stackoverflow.com/questions/36386358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6108379/" ]
You generally do not want to model this much detail because you'll wind up with a stale, inert model. Users and counters are more of a concern for OOP, and are akin to modeling the sand and clay that make up the bricks to make a house. Who cares about that level of detail? Instead, you're better off modeling the problem domain, which is utterly absent here. You could model the system architecture, which would identify the components, responsibilities, and interactions. You might evolve your System and Database into an architecture. Is your model correct UML? Sure, but it's not particularly useful. BTW, when you see one to one multiplicity, that is almost always a red flag.
This is not really a good design. Database and Counter should not be classes. The first for its complexity and the second because of its simplicity. Instead of using System for the password check, make this one Authentication. What you call System will be a conglomerate of many other classes besides Authentication. The counter will just be a private attribute inside Authentication. Now to your Database. Here it probably represents the users which the system allows. So call this class User and assign it whatever properties a user has (name, encrypted password, last login, etc.). Mapping this to a real database is subject of a later design phase where you make those classes persistent by implementing some persistence interface.
10,835,355
I have a ListView with 3 columns and would like to edit the third column, aka Subitem[1]. If I set ListView.ReadOnly to True, it allows me to edit the caption of the selected item. Is there an easy way to do the same thing for the subitem? I would like to stay away from adding a borderless control on top that does the editing.
2012/05/31
[ "https://Stackoverflow.com/questions/10835355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981120/" ]
You can Edit a subitem of the listview (in report mode) using a TEdit, a custom message and handling the `OnClick` event of the ListView. Try this sample ``` Const USER_EDITLISTVIEW = WM_USER + 666; type TForm1 = class(TForm) ListView1: TListView; procedure FormCreate(Sender: TObject); procedure ListView1Click(Sender: TObject); private ListViewEditor: TEdit; LItem: TListitem; procedure UserEditListView( Var Message: TMessage ); message USER_EDITLISTVIEW; procedure ListViewEditorExit(Sender: TObject); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses CommCtrl; const EDIT_COLUMN = 2; //Index of the column to Edit procedure TForm1.FormCreate(Sender: TObject); Var I : Integer; Item : TListItem; begin for I := 0 to 9 do begin Item:=ListView1.Items.Add; Item.Caption:=Format('%d.%d',[i,1]); Item.SubItems.Add(Format('%d.%d',[i,2])); Item.SubItems.Add(Format('%d.%d',[i,3])); end; //create the TEdit and assign the OnExit event ListViewEditor:=TEdit.Create(Self); ListViewEditor.Parent:=ListView1; ListViewEditor.OnExit:=ListViewEditorExit; ListViewEditor.Visible:=False; end; procedure TForm1.ListView1Click(Sender: TObject); var LPoint: TPoint; LVHitTestInfo: TLVHitTestInfo; begin LPoint:= listview1.ScreenToClient(Mouse.CursorPos); ZeroMemory( @LVHitTestInfo, SizeOf(LVHitTestInfo)); LVHitTestInfo.pt := LPoint; //Check if the click was made in the column to edit If (ListView1.perform( LVM_SUBITEMHITTEST, 0, LPARAM(@LVHitTestInfo))<>-1) and ( LVHitTestInfo.iSubItem = EDIT_COLUMN ) Then PostMessage( self.Handle, USER_EDITLISTVIEW, LVHitTestInfo.iItem, 0 ) else ListViewEditor.Visible:=False; //hide the TEdit end; procedure TForm1.ListViewEditorExit(Sender: TObject); begin If Assigned(LItem) Then Begin //assign the vslue of the TEdit to the Subitem LItem.SubItems[ EDIT_COLUMN-1 ] := ListViewEditor.Text; LItem := nil; End; end; procedure TForm1.UserEditListView(var Message: TMessage); var LRect: TRect; begin LRect.Top := EDIT_COLUMN; LRect.Left:= LVIR_BOUNDS; listview1.Perform( LVM_GETSUBITEMRECT, Message.wparam, LPARAM(@LRect) ); MapWindowPoints( listview1.Handle, ListViewEditor.Parent.Handle, LRect, 2 ); //get the current Item to edit LItem := listview1.Items[ Message.wparam ]; //set the text of the Edit ListViewEditor.Text := LItem.Subitems[ EDIT_COLUMN-1]; //set the bounds of the TEdit ListViewEditor.BoundsRect := LRect; //Show the TEdit ListViewEditor.Visible:=True; end; ```
I wrote sample code on CodeCentral that shows how to do this. [How to use the Build-in Editor of TListView to Edit SubItems](http://codecentral.embarcadero.com/Item/23873) **Update:** Here is an updated version that should compile now: ```pascal unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls; type TForm1 = class(TForm) ListView1: TListView; procedure ListView1Editing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); procedure ListView1Edited(Sender: TObject; Item: TListItem; var S: string); procedure ListView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ListView1DrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState); private { Private declarations } ColumnToEdit: Integer; OldListViewEditProc: Pointer; hListViewEditWnd: HWND; ListViewEditWndProcPtr: Pointer; procedure ListViewEditWndProc(var Message: TMessage); public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation uses Commctrl; {$R *.dfm} type TListViewCoord = record Item: Integer; Column: Integer; end; TLVGetColumnAt = function(Item: TListItem; const Pt: TPoint): Integer; TLVGetColumnRect = function(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; TLVGetIndexesAt = function(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; // TCustomListViewAccess provides access to the protected members of TCustomListView TCustomListViewAccess = class(TCustomListView); var // these will be assigned according to the version of COMCTL32.DLL being used GetColumnAt: TLVGetColumnAt = nil; GetColumnRect: TLVGetColumnRect = nil; GetIndexesAt: TLVGetIndexesAt = nil; //--------------------------------------------------------------------------- // GetComCtl32Version // // Purpose: Helper function to determine the version of CommCtrl32.dll that is loaded. //--------------------------------------------------------------------------- var ComCtl32Version: DWORD = 0; function GetComCtl32Version: DWORD; type DLLVERSIONINFO = packed record cbSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformID: DWORD; end; DLLGETVERSIONPROC = function(var dvi: DLLVERSIONINFO): Integer; stdcall; var hComCtrl32: HMODULE; lpDllGetVersion: DLLGETVERSIONPROC; dvi: DLLVERSIONINFO; FileName: array[0..MAX_PATH] of Char; dwHandle: DWORD; dwSize: DWORD; pData: Pointer; pVersion: Pointer; uiLen: UINT; begin if ComCtl32Version = 0 then begin hComCtrl32 := GetModuleHandle('comctl32.dll'); if hComCtrl32 <> 0 then begin @lpDllGetVersion := GetProcAddress(hComCtrl32, 'DllGetVersion'); if @lpDllGetVersion <> nil then begin ZeroMemory(@dvi, SizeOf(dvi)); dvi.cbSize := SizeOf(dvi); if lpDllGetVersion(dvi) >= 0 then ComCtl32Version := MAKELONG(Word(dvi.dwMinorVersion), Word(dvi.dwMajorVersion)); end; if ComCtl32Version = 0 then begin ZeroMemory(@FileName[0], SizeOf(FileName)); if GetModuleFileName(hComCtrl32, FileName, MAX_PATH) <> 0 then begin dwHandle := 0; dwSize := GetFileVersionInfoSize(FileName, dwHandle); if dwSize <> 0 then begin GetMem(pData, dwSize); try if GetFileVersionInfo(FileName, dwHandle, dwSize, pData) then begin pVersion := nil; uiLen := 0; if VerQueryValue(pData, '\', pVersion, uiLen) then begin with PVSFixedFileInfo(pVersion)^ do ComCtl32Version := MAKELONG(LOWORD(dwFileVersionMS), HIWORD(dwFileVersionMS)); end; end; finally FreeMem(pData); end; end; end; end; end; end; Result := ComCtl32Version; end; //--------------------------------------------------------------------------- // Manual_GetColumnAt // // Purpose: Returns the column index at the specified coordinates, // relative to the specified item //--------------------------------------------------------------------------- function Manual_GetColumnAt(Item: TListItem; const Pt: TPoint): Integer; var LV: TCustomListViewAccess; R: TRect; I: Integer; begin LV := TCustomListViewAccess(Item.ListView); // determine the dimensions of the current column value, and // see if the coordinates are inside of the column value // get the dimensions of the entire item R := Item.DisplayRect(drBounds); // loop through all of the columns looking for the value that was clicked on for I := 0 to LV.Columns.Count-1 do begin R.Right := (R.Left + LV.Column[I].Width); if PtInRect(R, Pt) then begin Result := I; Exit; end; R.Left := R.Right; end; Result := -1; end; //--------------------------------------------------------------------------- // Manual_GetColumnRect // // Purpose: Calculate the dimensions of the specified column, // relative to the specified item //--------------------------------------------------------------------------- function Manual_GetColumnRect(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; var LV: TCustomListViewAccess; I: Integer; begin Result := False; LV := TCustomListViewAccess(Item.ListView); // make sure the index is in the valid range if (ColumnIndex >= 0) and (ColumnIndex < LV.Columns.Count) then begin // get the dimensions of the entire item Rect := Item.DisplayRect(drBounds); // loop through the columns calculating the desired offsets for I := 0 to ColumnIndex-1 do Rect.Left := (Rect.Left + LV.Column[i].Width); Rect.Right := (Rect.Left + LV.Column[ColumnIndex].Width); Result := True; end; end; //--------------------------------------------------------------------------- // Manual_GetIndexesAt // // Purpose: Returns the Item and Column indexes at the specified coordinates //--------------------------------------------------------------------------- function Manual_GetIndexesAt(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; var Item: TListItem; begin Result := False; Item := ListView.GetItemAt(Pt.x, Pt.y); if Item <> nil then begin Coord.Item := Item.Index; Coord.Column := Manual_GetColumnAt(Item, Pt); Result := True; end; end; //--------------------------------------------------------------------------- // ComCtl_GetColumnAt // // Purpose: Returns the column index at the specified coordinates, relative to the specified item //--------------------------------------------------------------------------- function ComCtl_GetColumnAt(Item: TListItem; const Pt: TPoint): Integer; var HitTest: LV_HITTESTINFO; begin Result := -1; ZeroMemory(@HitTest, SizeOf(HitTest)); HitTest.pt := Pt; if ListView_SubItemHitTest(Item.ListView.Handle, @HitTest) > -1 then begin if HitTest.iItem = Item.Index then Result := HitTest.iSubItem; end; end; //--------------------------------------------------------------------------- // ComCtl_GetColumnRect // // Purpose: Calculate the dimensions of the specified column, relative to the specified item //--------------------------------------------------------------------------- function ComCtl_GetColumnRect(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; begin Result := ListView_GetSubItemRect(Item.ListView.Handle, Item.Index, ColumnIndex, LVIR_BOUNDS, @Rect); end; //--------------------------------------------------------------------------- // ComCtl_GetIndexesAt // // Purpose: Returns the Item and Column indexes at the specified coordinates //--------------------------------------------------------------------------- function ComCtl_GetIndexesAt(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; var HitTest: LV_HITTESTINFO; begin Result := False; ZeroMemory(@HitTest, SizeOf(HitTest)); HitTest.pt := Pt; if ListView_SubItemHitTest(ListView.Handle, @HitTest) > -1 then begin Coord.Item := HitTest.iItem; Coord.Column := HitTest.iSubItem; Result := True; end; end; //--------------------------------------------------------------------------- // TForm1 Constructor // // Purpose: Form constructor //--------------------------------------------------------------------------- constructor TForm1.Create(Owner: TComponent); begin inherited Create(Owner); // no editing yet ColumnToEdit := -1; OldListViewEditProc := nil; hListViewEditWnd := 0; ListViewEditWndProcPtr := MakeObjectInstance(ListViewEditWndProc); if ListViewEditWndProcPtr = nil then raise Exception.Create('Could not allocate memory for ListViewEditWndProc proxy'); if GetComCtl32Version >= DWORD(MAKELONG(70, 4)) then begin @GetColumnAt := @ComCtl_GetColumnAt; @GetColumnRect := @ComCtl_GetColumnRect; @GetIndexesAt := @ComCtl_GetIndexesAt; end else begin @GetColumnAt := @Manual_GetColumnAt; @GetColumnRect := @Manual_GetColumnRect; @GetIndexesAt := @Manual_GetIndexesAt; end; end; //--------------------------------------------------------------------------- // TForm1 Destructor // // Purpose: Form destructor //--------------------------------------------------------------------------- destructor TForm1.Destroy; begin if ListViewEditWndProcPtr <> nil then FreeObjectInstance(ListViewEditWndProcPtr); inherited Destroy; end; //--------------------------------------------------------------------------- // ListViewEditWndProc // // Purpose: Custom Window Procedure for TListView's editor window //--------------------------------------------------------------------------- procedure TForm1.ListViewEditWndProc(var Message: TMessage); begin if Message.Msg = WM_WINDOWPOSCHANGING then begin // this inline editor has a bad habit of re-positioning itself // back on top of the Caption after every key typed in, // so let's stop it from moving with TWMWindowPosMsg(Message).WindowPos^ do flags := flags or SWP_NOMOVE; Message.Result := 0; end else begin // everything else Message.Result := CallWindowProc(OldListViewEditProc, hListViewEditWnd, Message.Msg, Message.WParam, Message.LParam); end; end; //--------------------------------------------------------------------------- // ListView1DrawItem // // Purpose: Handler for the TListView::OnDrawItem event //--------------------------------------------------------------------------- procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState); var LV: TCustomListViewAccess; R: TRect; P: TPoint; I: Integer; S: String; begin LV := TCustomListViewAccess(Sender); // erase the entire item to start fresh R := Item.DisplayRect(drBounds); LV.Canvas.Brush.Color := LV.Color; LV.Canvas.FillRect(R); // see if the mouse is currently held down, and if so update the marker as needed if (GetKeyState(VK_LBUTTON) and $8000) <> 0 then begin // find the mouse cursor onscreen, convert the coordinates to client // coordinates on the list view GetCursorPos(P); ColumnToEdit := GetColumnAt(Item, LV.ScreenToClient(P)); end; // loop through all of the columns drawing each column for I := 0 to LV.Columns.Count-1 do begin // determine the dimensions of the current column value if not GetColumnRect(Item, I, R) then Continue; // mimic the default behavior by only drawing a value as highlighted if // the entire item is selected, the particular column matches the marker, // and the ListView is not already editing if Item.Selected and (I = ColumnToEdit) and (not LV.IsEditing) then begin LV.Canvas.Brush.Color := clHighlight; LV.Canvas.Font.Color := clHighlightText; end else begin LV.Canvas.Brush.Color := LV.Color; LV.Canvas.Font.Color := LV.Font.Color; end; LV.Canvas.FillRect(R); // draw the column's text if I = 0 then S := Item.Caption else S := Item.SubItems[I-1]; LV.Canvas.TextRect(R, R.Left + 2, R.Top, S); end; end; //--------------------------------------------------------------------------- // ListView1Edited // // Purpose: Handler for the TListView::OnEdited event //--------------------------------------------------------------------------- procedure TForm1.ListView1Edited(Sender: TObject; Item: TListItem; var S: string); begin // ignore the Caption, let it do its default handling if ColumnToEdit <= 0 then Exit; // restore the previous window procedure for the inline editor if hListViewEditWnd <> 0 then begin SetWindowLongPtr(hListViewEditWnd, GWL_WNDPROC, LONG_PTR(OldListViewEditProc)); hListViewEditWnd := 0; end; // assign the new text to the subitem being edited Item.SubItems[ColumnToEdit-1] := S; // prevent the default behavior from updating the Caption as well S := Item.Caption; end; //--------------------------------------------------------------------------- // ListView1Editing // // Purpose: Handler for the TListView::OnEditing event //--------------------------------------------------------------------------- procedure TForm1.ListView1Editing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); var Wnd: HWND; R: TRect; begin // ignore the Caption, let it do its default handling if ColumnToEdit <= 0 then Exit; // get the inline editor's handle Wnd := ListView_GetEditControl(ListView1.Handle); if Wnd = 0 then Exit; // determine the dimensions of the subitem being edited if not GetColumnRect(Item, ColumnToEdit, R) then Exit; // move the inline editor over the subitem MoveWindow(Wnd, R.Left, R.Top - 2, R.Right-R.Left, (R.Bottom-R.Top) + 4, TRUE); // update the inline editor's text with the subitem's text rather than the Caption SetWindowText(Wnd, PChar(Item.SubItems[ColumnToEdit-1])); // subclass the inline editor so we can catch its movements hListViewEditWnd := Wnd; OldListViewEditProc := Pointer(GetWindowLongPtr(Wnd, GWL_WNDPROC)); SetWindowLongPtr(Wnd, GWL_WNDPROC, LONG_PTR(ListViewEditWndProcPtr)); end; //--------------------------------------------------------------------------- // ListView1MouseDown // // Purpose: Handler for the TListView::OnMouseDown event //--------------------------------------------------------------------------- procedure TForm1.ListView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Coord: TListViewCoord; begin if GetIndexesAt(ListView1, Point(X, Y), Coord) then begin if Coord.Column <> ColumnToEdit then begin // update the marker ColumnToEdit := Coord.Column; // cancel the editing so that the listview won't go into // its edit mode immediately upon clicking the new item ListView1.Items[Coord.Item].CancelEdit; // update the display with a new highlight selection ListView1.Invalidate; end; end else ColumnToEdit := -1; end; end. ```
10,835,355
I have a ListView with 3 columns and would like to edit the third column, aka Subitem[1]. If I set ListView.ReadOnly to True, it allows me to edit the caption of the selected item. Is there an easy way to do the same thing for the subitem? I would like to stay away from adding a borderless control on top that does the editing.
2012/05/31
[ "https://Stackoverflow.com/questions/10835355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981120/" ]
I wrote sample code on CodeCentral that shows how to do this. [How to use the Build-in Editor of TListView to Edit SubItems](http://codecentral.embarcadero.com/Item/23873) **Update:** Here is an updated version that should compile now: ```pascal unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls; type TForm1 = class(TForm) ListView1: TListView; procedure ListView1Editing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); procedure ListView1Edited(Sender: TObject; Item: TListItem; var S: string); procedure ListView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ListView1DrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState); private { Private declarations } ColumnToEdit: Integer; OldListViewEditProc: Pointer; hListViewEditWnd: HWND; ListViewEditWndProcPtr: Pointer; procedure ListViewEditWndProc(var Message: TMessage); public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation uses Commctrl; {$R *.dfm} type TListViewCoord = record Item: Integer; Column: Integer; end; TLVGetColumnAt = function(Item: TListItem; const Pt: TPoint): Integer; TLVGetColumnRect = function(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; TLVGetIndexesAt = function(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; // TCustomListViewAccess provides access to the protected members of TCustomListView TCustomListViewAccess = class(TCustomListView); var // these will be assigned according to the version of COMCTL32.DLL being used GetColumnAt: TLVGetColumnAt = nil; GetColumnRect: TLVGetColumnRect = nil; GetIndexesAt: TLVGetIndexesAt = nil; //--------------------------------------------------------------------------- // GetComCtl32Version // // Purpose: Helper function to determine the version of CommCtrl32.dll that is loaded. //--------------------------------------------------------------------------- var ComCtl32Version: DWORD = 0; function GetComCtl32Version: DWORD; type DLLVERSIONINFO = packed record cbSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformID: DWORD; end; DLLGETVERSIONPROC = function(var dvi: DLLVERSIONINFO): Integer; stdcall; var hComCtrl32: HMODULE; lpDllGetVersion: DLLGETVERSIONPROC; dvi: DLLVERSIONINFO; FileName: array[0..MAX_PATH] of Char; dwHandle: DWORD; dwSize: DWORD; pData: Pointer; pVersion: Pointer; uiLen: UINT; begin if ComCtl32Version = 0 then begin hComCtrl32 := GetModuleHandle('comctl32.dll'); if hComCtrl32 <> 0 then begin @lpDllGetVersion := GetProcAddress(hComCtrl32, 'DllGetVersion'); if @lpDllGetVersion <> nil then begin ZeroMemory(@dvi, SizeOf(dvi)); dvi.cbSize := SizeOf(dvi); if lpDllGetVersion(dvi) >= 0 then ComCtl32Version := MAKELONG(Word(dvi.dwMinorVersion), Word(dvi.dwMajorVersion)); end; if ComCtl32Version = 0 then begin ZeroMemory(@FileName[0], SizeOf(FileName)); if GetModuleFileName(hComCtrl32, FileName, MAX_PATH) <> 0 then begin dwHandle := 0; dwSize := GetFileVersionInfoSize(FileName, dwHandle); if dwSize <> 0 then begin GetMem(pData, dwSize); try if GetFileVersionInfo(FileName, dwHandle, dwSize, pData) then begin pVersion := nil; uiLen := 0; if VerQueryValue(pData, '\', pVersion, uiLen) then begin with PVSFixedFileInfo(pVersion)^ do ComCtl32Version := MAKELONG(LOWORD(dwFileVersionMS), HIWORD(dwFileVersionMS)); end; end; finally FreeMem(pData); end; end; end; end; end; end; Result := ComCtl32Version; end; //--------------------------------------------------------------------------- // Manual_GetColumnAt // // Purpose: Returns the column index at the specified coordinates, // relative to the specified item //--------------------------------------------------------------------------- function Manual_GetColumnAt(Item: TListItem; const Pt: TPoint): Integer; var LV: TCustomListViewAccess; R: TRect; I: Integer; begin LV := TCustomListViewAccess(Item.ListView); // determine the dimensions of the current column value, and // see if the coordinates are inside of the column value // get the dimensions of the entire item R := Item.DisplayRect(drBounds); // loop through all of the columns looking for the value that was clicked on for I := 0 to LV.Columns.Count-1 do begin R.Right := (R.Left + LV.Column[I].Width); if PtInRect(R, Pt) then begin Result := I; Exit; end; R.Left := R.Right; end; Result := -1; end; //--------------------------------------------------------------------------- // Manual_GetColumnRect // // Purpose: Calculate the dimensions of the specified column, // relative to the specified item //--------------------------------------------------------------------------- function Manual_GetColumnRect(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; var LV: TCustomListViewAccess; I: Integer; begin Result := False; LV := TCustomListViewAccess(Item.ListView); // make sure the index is in the valid range if (ColumnIndex >= 0) and (ColumnIndex < LV.Columns.Count) then begin // get the dimensions of the entire item Rect := Item.DisplayRect(drBounds); // loop through the columns calculating the desired offsets for I := 0 to ColumnIndex-1 do Rect.Left := (Rect.Left + LV.Column[i].Width); Rect.Right := (Rect.Left + LV.Column[ColumnIndex].Width); Result := True; end; end; //--------------------------------------------------------------------------- // Manual_GetIndexesAt // // Purpose: Returns the Item and Column indexes at the specified coordinates //--------------------------------------------------------------------------- function Manual_GetIndexesAt(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; var Item: TListItem; begin Result := False; Item := ListView.GetItemAt(Pt.x, Pt.y); if Item <> nil then begin Coord.Item := Item.Index; Coord.Column := Manual_GetColumnAt(Item, Pt); Result := True; end; end; //--------------------------------------------------------------------------- // ComCtl_GetColumnAt // // Purpose: Returns the column index at the specified coordinates, relative to the specified item //--------------------------------------------------------------------------- function ComCtl_GetColumnAt(Item: TListItem; const Pt: TPoint): Integer; var HitTest: LV_HITTESTINFO; begin Result := -1; ZeroMemory(@HitTest, SizeOf(HitTest)); HitTest.pt := Pt; if ListView_SubItemHitTest(Item.ListView.Handle, @HitTest) > -1 then begin if HitTest.iItem = Item.Index then Result := HitTest.iSubItem; end; end; //--------------------------------------------------------------------------- // ComCtl_GetColumnRect // // Purpose: Calculate the dimensions of the specified column, relative to the specified item //--------------------------------------------------------------------------- function ComCtl_GetColumnRect(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; begin Result := ListView_GetSubItemRect(Item.ListView.Handle, Item.Index, ColumnIndex, LVIR_BOUNDS, @Rect); end; //--------------------------------------------------------------------------- // ComCtl_GetIndexesAt // // Purpose: Returns the Item and Column indexes at the specified coordinates //--------------------------------------------------------------------------- function ComCtl_GetIndexesAt(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; var HitTest: LV_HITTESTINFO; begin Result := False; ZeroMemory(@HitTest, SizeOf(HitTest)); HitTest.pt := Pt; if ListView_SubItemHitTest(ListView.Handle, @HitTest) > -1 then begin Coord.Item := HitTest.iItem; Coord.Column := HitTest.iSubItem; Result := True; end; end; //--------------------------------------------------------------------------- // TForm1 Constructor // // Purpose: Form constructor //--------------------------------------------------------------------------- constructor TForm1.Create(Owner: TComponent); begin inherited Create(Owner); // no editing yet ColumnToEdit := -1; OldListViewEditProc := nil; hListViewEditWnd := 0; ListViewEditWndProcPtr := MakeObjectInstance(ListViewEditWndProc); if ListViewEditWndProcPtr = nil then raise Exception.Create('Could not allocate memory for ListViewEditWndProc proxy'); if GetComCtl32Version >= DWORD(MAKELONG(70, 4)) then begin @GetColumnAt := @ComCtl_GetColumnAt; @GetColumnRect := @ComCtl_GetColumnRect; @GetIndexesAt := @ComCtl_GetIndexesAt; end else begin @GetColumnAt := @Manual_GetColumnAt; @GetColumnRect := @Manual_GetColumnRect; @GetIndexesAt := @Manual_GetIndexesAt; end; end; //--------------------------------------------------------------------------- // TForm1 Destructor // // Purpose: Form destructor //--------------------------------------------------------------------------- destructor TForm1.Destroy; begin if ListViewEditWndProcPtr <> nil then FreeObjectInstance(ListViewEditWndProcPtr); inherited Destroy; end; //--------------------------------------------------------------------------- // ListViewEditWndProc // // Purpose: Custom Window Procedure for TListView's editor window //--------------------------------------------------------------------------- procedure TForm1.ListViewEditWndProc(var Message: TMessage); begin if Message.Msg = WM_WINDOWPOSCHANGING then begin // this inline editor has a bad habit of re-positioning itself // back on top of the Caption after every key typed in, // so let's stop it from moving with TWMWindowPosMsg(Message).WindowPos^ do flags := flags or SWP_NOMOVE; Message.Result := 0; end else begin // everything else Message.Result := CallWindowProc(OldListViewEditProc, hListViewEditWnd, Message.Msg, Message.WParam, Message.LParam); end; end; //--------------------------------------------------------------------------- // ListView1DrawItem // // Purpose: Handler for the TListView::OnDrawItem event //--------------------------------------------------------------------------- procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState); var LV: TCustomListViewAccess; R: TRect; P: TPoint; I: Integer; S: String; begin LV := TCustomListViewAccess(Sender); // erase the entire item to start fresh R := Item.DisplayRect(drBounds); LV.Canvas.Brush.Color := LV.Color; LV.Canvas.FillRect(R); // see if the mouse is currently held down, and if so update the marker as needed if (GetKeyState(VK_LBUTTON) and $8000) <> 0 then begin // find the mouse cursor onscreen, convert the coordinates to client // coordinates on the list view GetCursorPos(P); ColumnToEdit := GetColumnAt(Item, LV.ScreenToClient(P)); end; // loop through all of the columns drawing each column for I := 0 to LV.Columns.Count-1 do begin // determine the dimensions of the current column value if not GetColumnRect(Item, I, R) then Continue; // mimic the default behavior by only drawing a value as highlighted if // the entire item is selected, the particular column matches the marker, // and the ListView is not already editing if Item.Selected and (I = ColumnToEdit) and (not LV.IsEditing) then begin LV.Canvas.Brush.Color := clHighlight; LV.Canvas.Font.Color := clHighlightText; end else begin LV.Canvas.Brush.Color := LV.Color; LV.Canvas.Font.Color := LV.Font.Color; end; LV.Canvas.FillRect(R); // draw the column's text if I = 0 then S := Item.Caption else S := Item.SubItems[I-1]; LV.Canvas.TextRect(R, R.Left + 2, R.Top, S); end; end; //--------------------------------------------------------------------------- // ListView1Edited // // Purpose: Handler for the TListView::OnEdited event //--------------------------------------------------------------------------- procedure TForm1.ListView1Edited(Sender: TObject; Item: TListItem; var S: string); begin // ignore the Caption, let it do its default handling if ColumnToEdit <= 0 then Exit; // restore the previous window procedure for the inline editor if hListViewEditWnd <> 0 then begin SetWindowLongPtr(hListViewEditWnd, GWL_WNDPROC, LONG_PTR(OldListViewEditProc)); hListViewEditWnd := 0; end; // assign the new text to the subitem being edited Item.SubItems[ColumnToEdit-1] := S; // prevent the default behavior from updating the Caption as well S := Item.Caption; end; //--------------------------------------------------------------------------- // ListView1Editing // // Purpose: Handler for the TListView::OnEditing event //--------------------------------------------------------------------------- procedure TForm1.ListView1Editing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); var Wnd: HWND; R: TRect; begin // ignore the Caption, let it do its default handling if ColumnToEdit <= 0 then Exit; // get the inline editor's handle Wnd := ListView_GetEditControl(ListView1.Handle); if Wnd = 0 then Exit; // determine the dimensions of the subitem being edited if not GetColumnRect(Item, ColumnToEdit, R) then Exit; // move the inline editor over the subitem MoveWindow(Wnd, R.Left, R.Top - 2, R.Right-R.Left, (R.Bottom-R.Top) + 4, TRUE); // update the inline editor's text with the subitem's text rather than the Caption SetWindowText(Wnd, PChar(Item.SubItems[ColumnToEdit-1])); // subclass the inline editor so we can catch its movements hListViewEditWnd := Wnd; OldListViewEditProc := Pointer(GetWindowLongPtr(Wnd, GWL_WNDPROC)); SetWindowLongPtr(Wnd, GWL_WNDPROC, LONG_PTR(ListViewEditWndProcPtr)); end; //--------------------------------------------------------------------------- // ListView1MouseDown // // Purpose: Handler for the TListView::OnMouseDown event //--------------------------------------------------------------------------- procedure TForm1.ListView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Coord: TListViewCoord; begin if GetIndexesAt(ListView1, Point(X, Y), Coord) then begin if Coord.Column <> ColumnToEdit then begin // update the marker ColumnToEdit := Coord.Column; // cancel the editing so that the listview won't go into // its edit mode immediately upon clicking the new item ListView1.Items[Coord.Item].CancelEdit; // update the display with a new highlight selection ListView1.Invalidate; end; end else ColumnToEdit := -1; end; end. ```
I took RRUZ's code and decided to make a self-contained unit of it, with a derived TListView object that supports multiple editable columns. It also allows you to move between editable items using the arrows, enter and tab. ``` unit EditableListView; interface uses Messages, Classes, StdCtrls, ComCtrls, System.Types, Generics.Collections; Const ELV_EDIT = WM_USER + 16; type TEditableListView = class(TListView) private FEditable: TList<integer>; FEditor: TEdit; FItem: TListItem; FEditColumn: integer; procedure EditListView(var AMessage: TMessage); message ELV_EDIT; procedure EditExit(Sender: TObject); procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DoEdit; procedure CleanupEditable; function GetEditable(const I: integer): boolean; procedure SetEditable(const I: integer; const Value: boolean); protected procedure Click; override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Editable[const I: integer]: boolean read GetEditable write SetEditable; end; implementation uses Windows, SysUtils, CommCtrl, Controls; { TEditableListView } constructor TEditableListView.Create(AOwner: TComponent); begin inherited Create(AOwner); FEditable := TList<integer>.Create; FEditor := TEdit.Create(self); FEditor.Parent := self; FEditor.OnExit := EditExit; FEditor.OnKeyDown := EditKeyDown; FEditor.Visible := false; ViewStyle := vsReport; // Default to vsReport instead of vsIcon end; destructor TEditableListView.Destroy; begin FEditable.Free; inherited Destroy; end; procedure TEditableListView.DoEdit; begin if Assigned(FItem) Then begin // assign the value of the TEdit to the Subitem if FEditColumn = 0 then FItem.Caption := FEditor.Text else if FEditColumn > 0 then FItem.SubItems[FEditColumn - 1] := FEditor.Text; end; end; function TEditableListView.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin DoEdit; FEditor.Visible := false; SetFocus; Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos); end; procedure TEditableListView.CleanupEditable; var I: integer; begin for I := FEditable.Count - 1 downto 0 do begin if not Assigned(Columns.FindItemID(FEditable[I])) then FEditable.Delete(I); end; end; procedure TEditableListView.Click; var LPoint: TPoint; LVHitTestInfo: TLVHitTestInfo; begin LPoint := ScreenToClient(Mouse.CursorPos); FillChar(LVHitTestInfo, SizeOf(LVHitTestInfo), 0); LVHitTestInfo.pt := LPoint; // Check if the click was made in the column to edit if (perform(LVM_SUBITEMHITTEST, 0, LPARAM(@LVHitTestInfo)) <> -1) Then PostMessage(self.Handle, ELV_EDIT, LVHitTestInfo.iItem, LVHitTestInfo.iSubItem) else FEditor.Visible := false; //hide the TEdit inherited Click; end; procedure TEditableListView.EditExit(Sender: TObject); begin DoEdit; end; procedure TEditableListView.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var lNextRow, lNextCol: integer; begin if Key in [VK_RETURN, VK_TAB, VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN] then begin DoEdit; lNextRow := FItem.Index; lNextCol := FEditColumn; case Key of VK_RETURN, VK_DOWN: lNextRow := lNextRow + 1; VK_UP: lNextRow := lNextRow - 1; VK_TAB, VK_RIGHT: lNextCol := lNextCol + 1; VK_LEFT: lNextCol := lNextCol - 1; end; if not ( (Key = VK_RIGHT) and (FEditor.SelStart+FEditor.SelLength < Length(FEditor.Text)) ) and not ( (Key = VK_LEFT) and (FEditor.SelStart+FEditor.SelLength > 0) ) then begin Key := 0; if (lNextRow >= 0) and (lNextRow < Items.Count) and (lNextCol >= 0) and (lNextCol < Columns.Count) then PostMessage(self.Handle, ELV_EDIT, lNextRow, lNextCol); end; end; end; procedure TEditableListView.EditListView(var AMessage: TMessage); var LRect: TRect; begin if Editable[AMessage.LParam] then begin LRect.Top := AMessage.LParam; LRect.Left:= LVIR_BOUNDS; Perform(LVM_GETSUBITEMRECT, AMessage.wparam, LPARAM(@LRect)); //get the current Item to edit FItem := Items[AMessage.wparam]; FEditColumn := AMessage.LParam; //set the text of the Edit if FEditColumn = 0 then FEditor.Text := FItem.Caption else if FEditColumn > 0 then FEditor.Text := FItem.Subitems[FEditColumn-1] else FEditor.Text := ''; //set the bounds of the TEdit FEditor.BoundsRect := LRect; //Show the TEdit FEditor.Visible := true; FEditor.SetFocus; FEditor.SelectAll; end else FEditor.Visible := false; end; function TEditableListView.GetEditable(const I: integer): boolean; begin if (I > 0) and (I < Columns.Count) then Result := FEditable.IndexOf(Columns[I].ID) >= 0 else Result := false; CleanupEditable; end; procedure TEditableListView.SetEditable(const I: integer; const Value: boolean); var Lix: integer; begin if (I > 0) and (I < Columns.Count) then begin Lix := FEditable.IndexOf(Columns[I].ID); if Value and (Lix < 0)then FEditable.Add(Columns[I].ID) else if not Value and (Lix >= 0) then FEditable.Delete(Lix); end; CleanupEditable; end; end. ``` EDIT1: Added detection for mousewheel scroll to exit editing. EDIT2: Allow for moving the cursor within the edit box with the arrow keys
10,835,355
I have a ListView with 3 columns and would like to edit the third column, aka Subitem[1]. If I set ListView.ReadOnly to True, it allows me to edit the caption of the selected item. Is there an easy way to do the same thing for the subitem? I would like to stay away from adding a borderless control on top that does the editing.
2012/05/31
[ "https://Stackoverflow.com/questions/10835355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981120/" ]
I wrote sample code on CodeCentral that shows how to do this. [How to use the Build-in Editor of TListView to Edit SubItems](http://codecentral.embarcadero.com/Item/23873) **Update:** Here is an updated version that should compile now: ```pascal unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls; type TForm1 = class(TForm) ListView1: TListView; procedure ListView1Editing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); procedure ListView1Edited(Sender: TObject; Item: TListItem; var S: string); procedure ListView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure ListView1DrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState); private { Private declarations } ColumnToEdit: Integer; OldListViewEditProc: Pointer; hListViewEditWnd: HWND; ListViewEditWndProcPtr: Pointer; procedure ListViewEditWndProc(var Message: TMessage); public { Public declarations } constructor Create(Owner: TComponent); override; destructor Destroy; override; end; var Form1: TForm1; implementation uses Commctrl; {$R *.dfm} type TListViewCoord = record Item: Integer; Column: Integer; end; TLVGetColumnAt = function(Item: TListItem; const Pt: TPoint): Integer; TLVGetColumnRect = function(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; TLVGetIndexesAt = function(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; // TCustomListViewAccess provides access to the protected members of TCustomListView TCustomListViewAccess = class(TCustomListView); var // these will be assigned according to the version of COMCTL32.DLL being used GetColumnAt: TLVGetColumnAt = nil; GetColumnRect: TLVGetColumnRect = nil; GetIndexesAt: TLVGetIndexesAt = nil; //--------------------------------------------------------------------------- // GetComCtl32Version // // Purpose: Helper function to determine the version of CommCtrl32.dll that is loaded. //--------------------------------------------------------------------------- var ComCtl32Version: DWORD = 0; function GetComCtl32Version: DWORD; type DLLVERSIONINFO = packed record cbSize: DWORD; dwMajorVersion: DWORD; dwMinorVersion: DWORD; dwBuildNumber: DWORD; dwPlatformID: DWORD; end; DLLGETVERSIONPROC = function(var dvi: DLLVERSIONINFO): Integer; stdcall; var hComCtrl32: HMODULE; lpDllGetVersion: DLLGETVERSIONPROC; dvi: DLLVERSIONINFO; FileName: array[0..MAX_PATH] of Char; dwHandle: DWORD; dwSize: DWORD; pData: Pointer; pVersion: Pointer; uiLen: UINT; begin if ComCtl32Version = 0 then begin hComCtrl32 := GetModuleHandle('comctl32.dll'); if hComCtrl32 <> 0 then begin @lpDllGetVersion := GetProcAddress(hComCtrl32, 'DllGetVersion'); if @lpDllGetVersion <> nil then begin ZeroMemory(@dvi, SizeOf(dvi)); dvi.cbSize := SizeOf(dvi); if lpDllGetVersion(dvi) >= 0 then ComCtl32Version := MAKELONG(Word(dvi.dwMinorVersion), Word(dvi.dwMajorVersion)); end; if ComCtl32Version = 0 then begin ZeroMemory(@FileName[0], SizeOf(FileName)); if GetModuleFileName(hComCtrl32, FileName, MAX_PATH) <> 0 then begin dwHandle := 0; dwSize := GetFileVersionInfoSize(FileName, dwHandle); if dwSize <> 0 then begin GetMem(pData, dwSize); try if GetFileVersionInfo(FileName, dwHandle, dwSize, pData) then begin pVersion := nil; uiLen := 0; if VerQueryValue(pData, '\', pVersion, uiLen) then begin with PVSFixedFileInfo(pVersion)^ do ComCtl32Version := MAKELONG(LOWORD(dwFileVersionMS), HIWORD(dwFileVersionMS)); end; end; finally FreeMem(pData); end; end; end; end; end; end; Result := ComCtl32Version; end; //--------------------------------------------------------------------------- // Manual_GetColumnAt // // Purpose: Returns the column index at the specified coordinates, // relative to the specified item //--------------------------------------------------------------------------- function Manual_GetColumnAt(Item: TListItem; const Pt: TPoint): Integer; var LV: TCustomListViewAccess; R: TRect; I: Integer; begin LV := TCustomListViewAccess(Item.ListView); // determine the dimensions of the current column value, and // see if the coordinates are inside of the column value // get the dimensions of the entire item R := Item.DisplayRect(drBounds); // loop through all of the columns looking for the value that was clicked on for I := 0 to LV.Columns.Count-1 do begin R.Right := (R.Left + LV.Column[I].Width); if PtInRect(R, Pt) then begin Result := I; Exit; end; R.Left := R.Right; end; Result := -1; end; //--------------------------------------------------------------------------- // Manual_GetColumnRect // // Purpose: Calculate the dimensions of the specified column, // relative to the specified item //--------------------------------------------------------------------------- function Manual_GetColumnRect(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; var LV: TCustomListViewAccess; I: Integer; begin Result := False; LV := TCustomListViewAccess(Item.ListView); // make sure the index is in the valid range if (ColumnIndex >= 0) and (ColumnIndex < LV.Columns.Count) then begin // get the dimensions of the entire item Rect := Item.DisplayRect(drBounds); // loop through the columns calculating the desired offsets for I := 0 to ColumnIndex-1 do Rect.Left := (Rect.Left + LV.Column[i].Width); Rect.Right := (Rect.Left + LV.Column[ColumnIndex].Width); Result := True; end; end; //--------------------------------------------------------------------------- // Manual_GetIndexesAt // // Purpose: Returns the Item and Column indexes at the specified coordinates //--------------------------------------------------------------------------- function Manual_GetIndexesAt(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; var Item: TListItem; begin Result := False; Item := ListView.GetItemAt(Pt.x, Pt.y); if Item <> nil then begin Coord.Item := Item.Index; Coord.Column := Manual_GetColumnAt(Item, Pt); Result := True; end; end; //--------------------------------------------------------------------------- // ComCtl_GetColumnAt // // Purpose: Returns the column index at the specified coordinates, relative to the specified item //--------------------------------------------------------------------------- function ComCtl_GetColumnAt(Item: TListItem; const Pt: TPoint): Integer; var HitTest: LV_HITTESTINFO; begin Result := -1; ZeroMemory(@HitTest, SizeOf(HitTest)); HitTest.pt := Pt; if ListView_SubItemHitTest(Item.ListView.Handle, @HitTest) > -1 then begin if HitTest.iItem = Item.Index then Result := HitTest.iSubItem; end; end; //--------------------------------------------------------------------------- // ComCtl_GetColumnRect // // Purpose: Calculate the dimensions of the specified column, relative to the specified item //--------------------------------------------------------------------------- function ComCtl_GetColumnRect(Item: TListItem; ColumnIndex: Integer; var Rect: TRect): Boolean; begin Result := ListView_GetSubItemRect(Item.ListView.Handle, Item.Index, ColumnIndex, LVIR_BOUNDS, @Rect); end; //--------------------------------------------------------------------------- // ComCtl_GetIndexesAt // // Purpose: Returns the Item and Column indexes at the specified coordinates //--------------------------------------------------------------------------- function ComCtl_GetIndexesAt(ListView: TCustomListView; const Pt: TPoint; var Coord: TListViewCoord): Boolean; var HitTest: LV_HITTESTINFO; begin Result := False; ZeroMemory(@HitTest, SizeOf(HitTest)); HitTest.pt := Pt; if ListView_SubItemHitTest(ListView.Handle, @HitTest) > -1 then begin Coord.Item := HitTest.iItem; Coord.Column := HitTest.iSubItem; Result := True; end; end; //--------------------------------------------------------------------------- // TForm1 Constructor // // Purpose: Form constructor //--------------------------------------------------------------------------- constructor TForm1.Create(Owner: TComponent); begin inherited Create(Owner); // no editing yet ColumnToEdit := -1; OldListViewEditProc := nil; hListViewEditWnd := 0; ListViewEditWndProcPtr := MakeObjectInstance(ListViewEditWndProc); if ListViewEditWndProcPtr = nil then raise Exception.Create('Could not allocate memory for ListViewEditWndProc proxy'); if GetComCtl32Version >= DWORD(MAKELONG(70, 4)) then begin @GetColumnAt := @ComCtl_GetColumnAt; @GetColumnRect := @ComCtl_GetColumnRect; @GetIndexesAt := @ComCtl_GetIndexesAt; end else begin @GetColumnAt := @Manual_GetColumnAt; @GetColumnRect := @Manual_GetColumnRect; @GetIndexesAt := @Manual_GetIndexesAt; end; end; //--------------------------------------------------------------------------- // TForm1 Destructor // // Purpose: Form destructor //--------------------------------------------------------------------------- destructor TForm1.Destroy; begin if ListViewEditWndProcPtr <> nil then FreeObjectInstance(ListViewEditWndProcPtr); inherited Destroy; end; //--------------------------------------------------------------------------- // ListViewEditWndProc // // Purpose: Custom Window Procedure for TListView's editor window //--------------------------------------------------------------------------- procedure TForm1.ListViewEditWndProc(var Message: TMessage); begin if Message.Msg = WM_WINDOWPOSCHANGING then begin // this inline editor has a bad habit of re-positioning itself // back on top of the Caption after every key typed in, // so let's stop it from moving with TWMWindowPosMsg(Message).WindowPos^ do flags := flags or SWP_NOMOVE; Message.Result := 0; end else begin // everything else Message.Result := CallWindowProc(OldListViewEditProc, hListViewEditWnd, Message.Msg, Message.WParam, Message.LParam); end; end; //--------------------------------------------------------------------------- // ListView1DrawItem // // Purpose: Handler for the TListView::OnDrawItem event //--------------------------------------------------------------------------- procedure TForm1.ListView1DrawItem(Sender: TCustomListView; Item: TListItem; Rect: TRect; State: TOwnerDrawState); var LV: TCustomListViewAccess; R: TRect; P: TPoint; I: Integer; S: String; begin LV := TCustomListViewAccess(Sender); // erase the entire item to start fresh R := Item.DisplayRect(drBounds); LV.Canvas.Brush.Color := LV.Color; LV.Canvas.FillRect(R); // see if the mouse is currently held down, and if so update the marker as needed if (GetKeyState(VK_LBUTTON) and $8000) <> 0 then begin // find the mouse cursor onscreen, convert the coordinates to client // coordinates on the list view GetCursorPos(P); ColumnToEdit := GetColumnAt(Item, LV.ScreenToClient(P)); end; // loop through all of the columns drawing each column for I := 0 to LV.Columns.Count-1 do begin // determine the dimensions of the current column value if not GetColumnRect(Item, I, R) then Continue; // mimic the default behavior by only drawing a value as highlighted if // the entire item is selected, the particular column matches the marker, // and the ListView is not already editing if Item.Selected and (I = ColumnToEdit) and (not LV.IsEditing) then begin LV.Canvas.Brush.Color := clHighlight; LV.Canvas.Font.Color := clHighlightText; end else begin LV.Canvas.Brush.Color := LV.Color; LV.Canvas.Font.Color := LV.Font.Color; end; LV.Canvas.FillRect(R); // draw the column's text if I = 0 then S := Item.Caption else S := Item.SubItems[I-1]; LV.Canvas.TextRect(R, R.Left + 2, R.Top, S); end; end; //--------------------------------------------------------------------------- // ListView1Edited // // Purpose: Handler for the TListView::OnEdited event //--------------------------------------------------------------------------- procedure TForm1.ListView1Edited(Sender: TObject; Item: TListItem; var S: string); begin // ignore the Caption, let it do its default handling if ColumnToEdit <= 0 then Exit; // restore the previous window procedure for the inline editor if hListViewEditWnd <> 0 then begin SetWindowLongPtr(hListViewEditWnd, GWL_WNDPROC, LONG_PTR(OldListViewEditProc)); hListViewEditWnd := 0; end; // assign the new text to the subitem being edited Item.SubItems[ColumnToEdit-1] := S; // prevent the default behavior from updating the Caption as well S := Item.Caption; end; //--------------------------------------------------------------------------- // ListView1Editing // // Purpose: Handler for the TListView::OnEditing event //--------------------------------------------------------------------------- procedure TForm1.ListView1Editing(Sender: TObject; Item: TListItem; var AllowEdit: Boolean); var Wnd: HWND; R: TRect; begin // ignore the Caption, let it do its default handling if ColumnToEdit <= 0 then Exit; // get the inline editor's handle Wnd := ListView_GetEditControl(ListView1.Handle); if Wnd = 0 then Exit; // determine the dimensions of the subitem being edited if not GetColumnRect(Item, ColumnToEdit, R) then Exit; // move the inline editor over the subitem MoveWindow(Wnd, R.Left, R.Top - 2, R.Right-R.Left, (R.Bottom-R.Top) + 4, TRUE); // update the inline editor's text with the subitem's text rather than the Caption SetWindowText(Wnd, PChar(Item.SubItems[ColumnToEdit-1])); // subclass the inline editor so we can catch its movements hListViewEditWnd := Wnd; OldListViewEditProc := Pointer(GetWindowLongPtr(Wnd, GWL_WNDPROC)); SetWindowLongPtr(Wnd, GWL_WNDPROC, LONG_PTR(ListViewEditWndProcPtr)); end; //--------------------------------------------------------------------------- // ListView1MouseDown // // Purpose: Handler for the TListView::OnMouseDown event //--------------------------------------------------------------------------- procedure TForm1.ListView1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var Coord: TListViewCoord; begin if GetIndexesAt(ListView1, Point(X, Y), Coord) then begin if Coord.Column <> ColumnToEdit then begin // update the marker ColumnToEdit := Coord.Column; // cancel the editing so that the listview won't go into // its edit mode immediately upon clicking the new item ListView1.Items[Coord.Item].CancelEdit; // update the display with a new highlight selection ListView1.Invalidate; end; end else ColumnToEdit := -1; end; end. ```
From the [review queue](https://stackoverflow.com/review/first-posts/16571510): > > For those interested, I've created a TListView extension based in > RRUZ's answer > > > <https://github.com/BakasuraRCE/TEditableListView> > > > The code is as follows: ``` unit UnitEditableListView; interface uses Winapi.Windows, Winapi.Messages, Winapi.CommCtrl, System.Classes, Vcl.ComCtrls, Vcl.StdCtrls; type /// /// Based on: https://stackoverflow.com/a/10836109 /// TListView = class(Vcl.ComCtrls.TListView) strict private FListViewEditor: TEdit; FEditorItemIndex, FEditorSubItemIndex: Integer; FCursorPos: TPoint; // Create native item function CreateItem(Index: Integer; ListItem: TListItem): TLVItem; // Free TEdit procedure FreeEditorItemInstance; // Invalidate cursor position procedure ResetCursorPos; { TEdit Events } procedure ListViewEditorExit(Sender: TObject); procedure ListViewEditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ListViewEditorKeyPress(Sender: TObject; var Key: Char); { Override Events } procedure Click; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; { Windows Events } { TODO -cenhancement : Scroll edit control with listview } procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; /// /// Start edition on local position /// procedure EditCaptionAt(Point: TPoint); end; implementation uses Vcl.Controls; { TListView } procedure TListView.Click; begin inherited; // Get current point FCursorPos := ScreenToClient(Mouse.CursorPos); FreeEditorItemInstance; end; constructor TListView.Create(AOwner: TComponent); begin inherited Create(AOwner); // Create the TEdit and assign the OnExit event FListViewEditor := TEdit.Create(AOwner); with FListViewEditor do begin Parent := Self; OnKeyDown := ListViewEditorKeyDown; OnKeyPress := ListViewEditorKeyPress; OnExit := ListViewEditorExit; Visible := False; end; end; destructor TListView.Destroy; begin // Free TEdit FListViewEditor.Free; inherited; end; procedure TListView.EditCaptionAt(Point: TPoint); var Rect: TRect; CursorPos: TPoint; HitTestInfo: TLVHitTestInfo; CurrentItem: TListItem; begin // Set position to handle HitTestInfo.pt := Point; // Get item select if ListView_SubItemHitTest(Handle, @HitTestInfo) = -1 then Exit; with HitTestInfo do begin FEditorItemIndex := iItem; FEditorSubItemIndex := iSubItem; end; // Nothing? if (FEditorItemIndex < 0) or (FEditorItemIndex >= Items.Count) then Exit; if FEditorSubItemIndex < 0 then Exit; CurrentItem := Items[ItemIndex]; if not CanEdit(CurrentItem) then Exit; // Get bounds ListView_GetSubItemRect(Handle, FEditorItemIndex, FEditorSubItemIndex, LVIR_LABEL, @Rect); // set the text of the Edit if FEditorSubItemIndex = 0 then FListViewEditor.Text := CurrentItem.Caption else begin FListViewEditor.Text := CurrentItem.SubItems[FEditorSubItemIndex - 1]; end; // Set the bounds of the TEdit FListViewEditor.BoundsRect := Rect; // Show the TEdit FListViewEditor.Visible := True; // Set focus FListViewEditor.SetFocus; end; procedure TListView.ResetCursorPos; begin // Free cursos pos FCursorPos := Point(-1, -1); end; procedure TListView.FreeEditorItemInstance; begin FEditorItemIndex := -1; FEditorSubItemIndex := -1; FListViewEditor.Visible := False; // Hide the TEdit end; procedure TListView.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); // F2 key start edit if (Key = VK_F2) then EditCaptionAt(FCursorPos); end; /// /// Create a LVItem /// function TListView.CreateItem(Index: Integer; ListItem: TListItem): TLVItem; begin with Result do begin mask := LVIF_PARAM or LVIF_IMAGE or LVIF_GROUPID; iItem := index; iSubItem := 0; iImage := I_IMAGECALLBACK; iGroupId := -1; pszText := PChar(ListItem.Caption); {$IFDEF CLR} lParam := ListItem.GetHashCode; {$ELSE} lParam := Winapi.Windows.lParam(ListItem); {$ENDIF} end; end; procedure TListView.ListViewEditorExit(Sender: TObject); begin // I have an instance? if FEditorItemIndex = -1 then Exit; // Assign the value of the TEdit to the Subitem if FEditorSubItemIndex = 0 then Items[FEditorItemIndex].Caption := FListViewEditor.Text else Items[FEditorItemIndex].SubItems[FEditorSubItemIndex - 1] := FListViewEditor.Text; // Raise OnEdited event Edit(CreateItem(FEditorItemIndex, Items[FEditorItemIndex])); // Free instanse FreeEditorItemInstance; end; procedure TListView.ListViewEditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // ESCAPE key exit of editor if Key = VK_ESCAPE then FreeEditorItemInstance; end; procedure TListView.ListViewEditorKeyPress(Sender: TObject; var Key: Char); begin // Update item on press ENTER if (Key = #$0A) or (Key = #$0D) then FListViewEditor.OnExit(Sender); end; procedure TListView.WMHScroll(var Message: TWMHScroll); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; procedure TListView.WMMouseWheel(var Message: TWMMouseWheel); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; procedure TListView.WMVScroll(var Message: TWMVScroll); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; end. ``` The original poster's, [Bakasura](https://stackoverflow.com/users/8235752/bakasura), answer had been deleted: [![Screenshot of original answer](https://i.stack.imgur.com/z5l80.png)](https://i.stack.imgur.com/z5l80.png)
10,835,355
I have a ListView with 3 columns and would like to edit the third column, aka Subitem[1]. If I set ListView.ReadOnly to True, it allows me to edit the caption of the selected item. Is there an easy way to do the same thing for the subitem? I would like to stay away from adding a borderless control on top that does the editing.
2012/05/31
[ "https://Stackoverflow.com/questions/10835355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981120/" ]
You can Edit a subitem of the listview (in report mode) using a TEdit, a custom message and handling the `OnClick` event of the ListView. Try this sample ``` Const USER_EDITLISTVIEW = WM_USER + 666; type TForm1 = class(TForm) ListView1: TListView; procedure FormCreate(Sender: TObject); procedure ListView1Click(Sender: TObject); private ListViewEditor: TEdit; LItem: TListitem; procedure UserEditListView( Var Message: TMessage ); message USER_EDITLISTVIEW; procedure ListViewEditorExit(Sender: TObject); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses CommCtrl; const EDIT_COLUMN = 2; //Index of the column to Edit procedure TForm1.FormCreate(Sender: TObject); Var I : Integer; Item : TListItem; begin for I := 0 to 9 do begin Item:=ListView1.Items.Add; Item.Caption:=Format('%d.%d',[i,1]); Item.SubItems.Add(Format('%d.%d',[i,2])); Item.SubItems.Add(Format('%d.%d',[i,3])); end; //create the TEdit and assign the OnExit event ListViewEditor:=TEdit.Create(Self); ListViewEditor.Parent:=ListView1; ListViewEditor.OnExit:=ListViewEditorExit; ListViewEditor.Visible:=False; end; procedure TForm1.ListView1Click(Sender: TObject); var LPoint: TPoint; LVHitTestInfo: TLVHitTestInfo; begin LPoint:= listview1.ScreenToClient(Mouse.CursorPos); ZeroMemory( @LVHitTestInfo, SizeOf(LVHitTestInfo)); LVHitTestInfo.pt := LPoint; //Check if the click was made in the column to edit If (ListView1.perform( LVM_SUBITEMHITTEST, 0, LPARAM(@LVHitTestInfo))<>-1) and ( LVHitTestInfo.iSubItem = EDIT_COLUMN ) Then PostMessage( self.Handle, USER_EDITLISTVIEW, LVHitTestInfo.iItem, 0 ) else ListViewEditor.Visible:=False; //hide the TEdit end; procedure TForm1.ListViewEditorExit(Sender: TObject); begin If Assigned(LItem) Then Begin //assign the vslue of the TEdit to the Subitem LItem.SubItems[ EDIT_COLUMN-1 ] := ListViewEditor.Text; LItem := nil; End; end; procedure TForm1.UserEditListView(var Message: TMessage); var LRect: TRect; begin LRect.Top := EDIT_COLUMN; LRect.Left:= LVIR_BOUNDS; listview1.Perform( LVM_GETSUBITEMRECT, Message.wparam, LPARAM(@LRect) ); MapWindowPoints( listview1.Handle, ListViewEditor.Parent.Handle, LRect, 2 ); //get the current Item to edit LItem := listview1.Items[ Message.wparam ]; //set the text of the Edit ListViewEditor.Text := LItem.Subitems[ EDIT_COLUMN-1]; //set the bounds of the TEdit ListViewEditor.BoundsRect := LRect; //Show the TEdit ListViewEditor.Visible:=True; end; ```
I took RRUZ's code and decided to make a self-contained unit of it, with a derived TListView object that supports multiple editable columns. It also allows you to move between editable items using the arrows, enter and tab. ``` unit EditableListView; interface uses Messages, Classes, StdCtrls, ComCtrls, System.Types, Generics.Collections; Const ELV_EDIT = WM_USER + 16; type TEditableListView = class(TListView) private FEditable: TList<integer>; FEditor: TEdit; FItem: TListItem; FEditColumn: integer; procedure EditListView(var AMessage: TMessage); message ELV_EDIT; procedure EditExit(Sender: TObject); procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DoEdit; procedure CleanupEditable; function GetEditable(const I: integer): boolean; procedure SetEditable(const I: integer; const Value: boolean); protected procedure Click; override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Editable[const I: integer]: boolean read GetEditable write SetEditable; end; implementation uses Windows, SysUtils, CommCtrl, Controls; { TEditableListView } constructor TEditableListView.Create(AOwner: TComponent); begin inherited Create(AOwner); FEditable := TList<integer>.Create; FEditor := TEdit.Create(self); FEditor.Parent := self; FEditor.OnExit := EditExit; FEditor.OnKeyDown := EditKeyDown; FEditor.Visible := false; ViewStyle := vsReport; // Default to vsReport instead of vsIcon end; destructor TEditableListView.Destroy; begin FEditable.Free; inherited Destroy; end; procedure TEditableListView.DoEdit; begin if Assigned(FItem) Then begin // assign the value of the TEdit to the Subitem if FEditColumn = 0 then FItem.Caption := FEditor.Text else if FEditColumn > 0 then FItem.SubItems[FEditColumn - 1] := FEditor.Text; end; end; function TEditableListView.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin DoEdit; FEditor.Visible := false; SetFocus; Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos); end; procedure TEditableListView.CleanupEditable; var I: integer; begin for I := FEditable.Count - 1 downto 0 do begin if not Assigned(Columns.FindItemID(FEditable[I])) then FEditable.Delete(I); end; end; procedure TEditableListView.Click; var LPoint: TPoint; LVHitTestInfo: TLVHitTestInfo; begin LPoint := ScreenToClient(Mouse.CursorPos); FillChar(LVHitTestInfo, SizeOf(LVHitTestInfo), 0); LVHitTestInfo.pt := LPoint; // Check if the click was made in the column to edit if (perform(LVM_SUBITEMHITTEST, 0, LPARAM(@LVHitTestInfo)) <> -1) Then PostMessage(self.Handle, ELV_EDIT, LVHitTestInfo.iItem, LVHitTestInfo.iSubItem) else FEditor.Visible := false; //hide the TEdit inherited Click; end; procedure TEditableListView.EditExit(Sender: TObject); begin DoEdit; end; procedure TEditableListView.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var lNextRow, lNextCol: integer; begin if Key in [VK_RETURN, VK_TAB, VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN] then begin DoEdit; lNextRow := FItem.Index; lNextCol := FEditColumn; case Key of VK_RETURN, VK_DOWN: lNextRow := lNextRow + 1; VK_UP: lNextRow := lNextRow - 1; VK_TAB, VK_RIGHT: lNextCol := lNextCol + 1; VK_LEFT: lNextCol := lNextCol - 1; end; if not ( (Key = VK_RIGHT) and (FEditor.SelStart+FEditor.SelLength < Length(FEditor.Text)) ) and not ( (Key = VK_LEFT) and (FEditor.SelStart+FEditor.SelLength > 0) ) then begin Key := 0; if (lNextRow >= 0) and (lNextRow < Items.Count) and (lNextCol >= 0) and (lNextCol < Columns.Count) then PostMessage(self.Handle, ELV_EDIT, lNextRow, lNextCol); end; end; end; procedure TEditableListView.EditListView(var AMessage: TMessage); var LRect: TRect; begin if Editable[AMessage.LParam] then begin LRect.Top := AMessage.LParam; LRect.Left:= LVIR_BOUNDS; Perform(LVM_GETSUBITEMRECT, AMessage.wparam, LPARAM(@LRect)); //get the current Item to edit FItem := Items[AMessage.wparam]; FEditColumn := AMessage.LParam; //set the text of the Edit if FEditColumn = 0 then FEditor.Text := FItem.Caption else if FEditColumn > 0 then FEditor.Text := FItem.Subitems[FEditColumn-1] else FEditor.Text := ''; //set the bounds of the TEdit FEditor.BoundsRect := LRect; //Show the TEdit FEditor.Visible := true; FEditor.SetFocus; FEditor.SelectAll; end else FEditor.Visible := false; end; function TEditableListView.GetEditable(const I: integer): boolean; begin if (I > 0) and (I < Columns.Count) then Result := FEditable.IndexOf(Columns[I].ID) >= 0 else Result := false; CleanupEditable; end; procedure TEditableListView.SetEditable(const I: integer; const Value: boolean); var Lix: integer; begin if (I > 0) and (I < Columns.Count) then begin Lix := FEditable.IndexOf(Columns[I].ID); if Value and (Lix < 0)then FEditable.Add(Columns[I].ID) else if not Value and (Lix >= 0) then FEditable.Delete(Lix); end; CleanupEditable; end; end. ``` EDIT1: Added detection for mousewheel scroll to exit editing. EDIT2: Allow for moving the cursor within the edit box with the arrow keys
10,835,355
I have a ListView with 3 columns and would like to edit the third column, aka Subitem[1]. If I set ListView.ReadOnly to True, it allows me to edit the caption of the selected item. Is there an easy way to do the same thing for the subitem? I would like to stay away from adding a borderless control on top that does the editing.
2012/05/31
[ "https://Stackoverflow.com/questions/10835355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981120/" ]
You can Edit a subitem of the listview (in report mode) using a TEdit, a custom message and handling the `OnClick` event of the ListView. Try this sample ``` Const USER_EDITLISTVIEW = WM_USER + 666; type TForm1 = class(TForm) ListView1: TListView; procedure FormCreate(Sender: TObject); procedure ListView1Click(Sender: TObject); private ListViewEditor: TEdit; LItem: TListitem; procedure UserEditListView( Var Message: TMessage ); message USER_EDITLISTVIEW; procedure ListViewEditorExit(Sender: TObject); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses CommCtrl; const EDIT_COLUMN = 2; //Index of the column to Edit procedure TForm1.FormCreate(Sender: TObject); Var I : Integer; Item : TListItem; begin for I := 0 to 9 do begin Item:=ListView1.Items.Add; Item.Caption:=Format('%d.%d',[i,1]); Item.SubItems.Add(Format('%d.%d',[i,2])); Item.SubItems.Add(Format('%d.%d',[i,3])); end; //create the TEdit and assign the OnExit event ListViewEditor:=TEdit.Create(Self); ListViewEditor.Parent:=ListView1; ListViewEditor.OnExit:=ListViewEditorExit; ListViewEditor.Visible:=False; end; procedure TForm1.ListView1Click(Sender: TObject); var LPoint: TPoint; LVHitTestInfo: TLVHitTestInfo; begin LPoint:= listview1.ScreenToClient(Mouse.CursorPos); ZeroMemory( @LVHitTestInfo, SizeOf(LVHitTestInfo)); LVHitTestInfo.pt := LPoint; //Check if the click was made in the column to edit If (ListView1.perform( LVM_SUBITEMHITTEST, 0, LPARAM(@LVHitTestInfo))<>-1) and ( LVHitTestInfo.iSubItem = EDIT_COLUMN ) Then PostMessage( self.Handle, USER_EDITLISTVIEW, LVHitTestInfo.iItem, 0 ) else ListViewEditor.Visible:=False; //hide the TEdit end; procedure TForm1.ListViewEditorExit(Sender: TObject); begin If Assigned(LItem) Then Begin //assign the vslue of the TEdit to the Subitem LItem.SubItems[ EDIT_COLUMN-1 ] := ListViewEditor.Text; LItem := nil; End; end; procedure TForm1.UserEditListView(var Message: TMessage); var LRect: TRect; begin LRect.Top := EDIT_COLUMN; LRect.Left:= LVIR_BOUNDS; listview1.Perform( LVM_GETSUBITEMRECT, Message.wparam, LPARAM(@LRect) ); MapWindowPoints( listview1.Handle, ListViewEditor.Parent.Handle, LRect, 2 ); //get the current Item to edit LItem := listview1.Items[ Message.wparam ]; //set the text of the Edit ListViewEditor.Text := LItem.Subitems[ EDIT_COLUMN-1]; //set the bounds of the TEdit ListViewEditor.BoundsRect := LRect; //Show the TEdit ListViewEditor.Visible:=True; end; ```
From the [review queue](https://stackoverflow.com/review/first-posts/16571510): > > For those interested, I've created a TListView extension based in > RRUZ's answer > > > <https://github.com/BakasuraRCE/TEditableListView> > > > The code is as follows: ``` unit UnitEditableListView; interface uses Winapi.Windows, Winapi.Messages, Winapi.CommCtrl, System.Classes, Vcl.ComCtrls, Vcl.StdCtrls; type /// /// Based on: https://stackoverflow.com/a/10836109 /// TListView = class(Vcl.ComCtrls.TListView) strict private FListViewEditor: TEdit; FEditorItemIndex, FEditorSubItemIndex: Integer; FCursorPos: TPoint; // Create native item function CreateItem(Index: Integer; ListItem: TListItem): TLVItem; // Free TEdit procedure FreeEditorItemInstance; // Invalidate cursor position procedure ResetCursorPos; { TEdit Events } procedure ListViewEditorExit(Sender: TObject); procedure ListViewEditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ListViewEditorKeyPress(Sender: TObject; var Key: Char); { Override Events } procedure Click; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; { Windows Events } { TODO -cenhancement : Scroll edit control with listview } procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; /// /// Start edition on local position /// procedure EditCaptionAt(Point: TPoint); end; implementation uses Vcl.Controls; { TListView } procedure TListView.Click; begin inherited; // Get current point FCursorPos := ScreenToClient(Mouse.CursorPos); FreeEditorItemInstance; end; constructor TListView.Create(AOwner: TComponent); begin inherited Create(AOwner); // Create the TEdit and assign the OnExit event FListViewEditor := TEdit.Create(AOwner); with FListViewEditor do begin Parent := Self; OnKeyDown := ListViewEditorKeyDown; OnKeyPress := ListViewEditorKeyPress; OnExit := ListViewEditorExit; Visible := False; end; end; destructor TListView.Destroy; begin // Free TEdit FListViewEditor.Free; inherited; end; procedure TListView.EditCaptionAt(Point: TPoint); var Rect: TRect; CursorPos: TPoint; HitTestInfo: TLVHitTestInfo; CurrentItem: TListItem; begin // Set position to handle HitTestInfo.pt := Point; // Get item select if ListView_SubItemHitTest(Handle, @HitTestInfo) = -1 then Exit; with HitTestInfo do begin FEditorItemIndex := iItem; FEditorSubItemIndex := iSubItem; end; // Nothing? if (FEditorItemIndex < 0) or (FEditorItemIndex >= Items.Count) then Exit; if FEditorSubItemIndex < 0 then Exit; CurrentItem := Items[ItemIndex]; if not CanEdit(CurrentItem) then Exit; // Get bounds ListView_GetSubItemRect(Handle, FEditorItemIndex, FEditorSubItemIndex, LVIR_LABEL, @Rect); // set the text of the Edit if FEditorSubItemIndex = 0 then FListViewEditor.Text := CurrentItem.Caption else begin FListViewEditor.Text := CurrentItem.SubItems[FEditorSubItemIndex - 1]; end; // Set the bounds of the TEdit FListViewEditor.BoundsRect := Rect; // Show the TEdit FListViewEditor.Visible := True; // Set focus FListViewEditor.SetFocus; end; procedure TListView.ResetCursorPos; begin // Free cursos pos FCursorPos := Point(-1, -1); end; procedure TListView.FreeEditorItemInstance; begin FEditorItemIndex := -1; FEditorSubItemIndex := -1; FListViewEditor.Visible := False; // Hide the TEdit end; procedure TListView.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); // F2 key start edit if (Key = VK_F2) then EditCaptionAt(FCursorPos); end; /// /// Create a LVItem /// function TListView.CreateItem(Index: Integer; ListItem: TListItem): TLVItem; begin with Result do begin mask := LVIF_PARAM or LVIF_IMAGE or LVIF_GROUPID; iItem := index; iSubItem := 0; iImage := I_IMAGECALLBACK; iGroupId := -1; pszText := PChar(ListItem.Caption); {$IFDEF CLR} lParam := ListItem.GetHashCode; {$ELSE} lParam := Winapi.Windows.lParam(ListItem); {$ENDIF} end; end; procedure TListView.ListViewEditorExit(Sender: TObject); begin // I have an instance? if FEditorItemIndex = -1 then Exit; // Assign the value of the TEdit to the Subitem if FEditorSubItemIndex = 0 then Items[FEditorItemIndex].Caption := FListViewEditor.Text else Items[FEditorItemIndex].SubItems[FEditorSubItemIndex - 1] := FListViewEditor.Text; // Raise OnEdited event Edit(CreateItem(FEditorItemIndex, Items[FEditorItemIndex])); // Free instanse FreeEditorItemInstance; end; procedure TListView.ListViewEditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // ESCAPE key exit of editor if Key = VK_ESCAPE then FreeEditorItemInstance; end; procedure TListView.ListViewEditorKeyPress(Sender: TObject; var Key: Char); begin // Update item on press ENTER if (Key = #$0A) or (Key = #$0D) then FListViewEditor.OnExit(Sender); end; procedure TListView.WMHScroll(var Message: TWMHScroll); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; procedure TListView.WMMouseWheel(var Message: TWMMouseWheel); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; procedure TListView.WMVScroll(var Message: TWMVScroll); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; end. ``` The original poster's, [Bakasura](https://stackoverflow.com/users/8235752/bakasura), answer had been deleted: [![Screenshot of original answer](https://i.stack.imgur.com/z5l80.png)](https://i.stack.imgur.com/z5l80.png)
10,835,355
I have a ListView with 3 columns and would like to edit the third column, aka Subitem[1]. If I set ListView.ReadOnly to True, it allows me to edit the caption of the selected item. Is there an easy way to do the same thing for the subitem? I would like to stay away from adding a borderless control on top that does the editing.
2012/05/31
[ "https://Stackoverflow.com/questions/10835355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/981120/" ]
I took RRUZ's code and decided to make a self-contained unit of it, with a derived TListView object that supports multiple editable columns. It also allows you to move between editable items using the arrows, enter and tab. ``` unit EditableListView; interface uses Messages, Classes, StdCtrls, ComCtrls, System.Types, Generics.Collections; Const ELV_EDIT = WM_USER + 16; type TEditableListView = class(TListView) private FEditable: TList<integer>; FEditor: TEdit; FItem: TListItem; FEditColumn: integer; procedure EditListView(var AMessage: TMessage); message ELV_EDIT; procedure EditExit(Sender: TObject); procedure EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure DoEdit; procedure CleanupEditable; function GetEditable(const I: integer): boolean; procedure SetEditable(const I: integer; const Value: boolean); protected procedure Click; override; function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Editable[const I: integer]: boolean read GetEditable write SetEditable; end; implementation uses Windows, SysUtils, CommCtrl, Controls; { TEditableListView } constructor TEditableListView.Create(AOwner: TComponent); begin inherited Create(AOwner); FEditable := TList<integer>.Create; FEditor := TEdit.Create(self); FEditor.Parent := self; FEditor.OnExit := EditExit; FEditor.OnKeyDown := EditKeyDown; FEditor.Visible := false; ViewStyle := vsReport; // Default to vsReport instead of vsIcon end; destructor TEditableListView.Destroy; begin FEditable.Free; inherited Destroy; end; procedure TEditableListView.DoEdit; begin if Assigned(FItem) Then begin // assign the value of the TEdit to the Subitem if FEditColumn = 0 then FItem.Caption := FEditor.Text else if FEditColumn > 0 then FItem.SubItems[FEditColumn - 1] := FEditor.Text; end; end; function TEditableListView.DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; begin DoEdit; FEditor.Visible := false; SetFocus; Result := inherited DoMouseWheel(Shift, WheelDelta, MousePos); end; procedure TEditableListView.CleanupEditable; var I: integer; begin for I := FEditable.Count - 1 downto 0 do begin if not Assigned(Columns.FindItemID(FEditable[I])) then FEditable.Delete(I); end; end; procedure TEditableListView.Click; var LPoint: TPoint; LVHitTestInfo: TLVHitTestInfo; begin LPoint := ScreenToClient(Mouse.CursorPos); FillChar(LVHitTestInfo, SizeOf(LVHitTestInfo), 0); LVHitTestInfo.pt := LPoint; // Check if the click was made in the column to edit if (perform(LVM_SUBITEMHITTEST, 0, LPARAM(@LVHitTestInfo)) <> -1) Then PostMessage(self.Handle, ELV_EDIT, LVHitTestInfo.iItem, LVHitTestInfo.iSubItem) else FEditor.Visible := false; //hide the TEdit inherited Click; end; procedure TEditableListView.EditExit(Sender: TObject); begin DoEdit; end; procedure TEditableListView.EditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var lNextRow, lNextCol: integer; begin if Key in [VK_RETURN, VK_TAB, VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN] then begin DoEdit; lNextRow := FItem.Index; lNextCol := FEditColumn; case Key of VK_RETURN, VK_DOWN: lNextRow := lNextRow + 1; VK_UP: lNextRow := lNextRow - 1; VK_TAB, VK_RIGHT: lNextCol := lNextCol + 1; VK_LEFT: lNextCol := lNextCol - 1; end; if not ( (Key = VK_RIGHT) and (FEditor.SelStart+FEditor.SelLength < Length(FEditor.Text)) ) and not ( (Key = VK_LEFT) and (FEditor.SelStart+FEditor.SelLength > 0) ) then begin Key := 0; if (lNextRow >= 0) and (lNextRow < Items.Count) and (lNextCol >= 0) and (lNextCol < Columns.Count) then PostMessage(self.Handle, ELV_EDIT, lNextRow, lNextCol); end; end; end; procedure TEditableListView.EditListView(var AMessage: TMessage); var LRect: TRect; begin if Editable[AMessage.LParam] then begin LRect.Top := AMessage.LParam; LRect.Left:= LVIR_BOUNDS; Perform(LVM_GETSUBITEMRECT, AMessage.wparam, LPARAM(@LRect)); //get the current Item to edit FItem := Items[AMessage.wparam]; FEditColumn := AMessage.LParam; //set the text of the Edit if FEditColumn = 0 then FEditor.Text := FItem.Caption else if FEditColumn > 0 then FEditor.Text := FItem.Subitems[FEditColumn-1] else FEditor.Text := ''; //set the bounds of the TEdit FEditor.BoundsRect := LRect; //Show the TEdit FEditor.Visible := true; FEditor.SetFocus; FEditor.SelectAll; end else FEditor.Visible := false; end; function TEditableListView.GetEditable(const I: integer): boolean; begin if (I > 0) and (I < Columns.Count) then Result := FEditable.IndexOf(Columns[I].ID) >= 0 else Result := false; CleanupEditable; end; procedure TEditableListView.SetEditable(const I: integer; const Value: boolean); var Lix: integer; begin if (I > 0) and (I < Columns.Count) then begin Lix := FEditable.IndexOf(Columns[I].ID); if Value and (Lix < 0)then FEditable.Add(Columns[I].ID) else if not Value and (Lix >= 0) then FEditable.Delete(Lix); end; CleanupEditable; end; end. ``` EDIT1: Added detection for mousewheel scroll to exit editing. EDIT2: Allow for moving the cursor within the edit box with the arrow keys
From the [review queue](https://stackoverflow.com/review/first-posts/16571510): > > For those interested, I've created a TListView extension based in > RRUZ's answer > > > <https://github.com/BakasuraRCE/TEditableListView> > > > The code is as follows: ``` unit UnitEditableListView; interface uses Winapi.Windows, Winapi.Messages, Winapi.CommCtrl, System.Classes, Vcl.ComCtrls, Vcl.StdCtrls; type /// /// Based on: https://stackoverflow.com/a/10836109 /// TListView = class(Vcl.ComCtrls.TListView) strict private FListViewEditor: TEdit; FEditorItemIndex, FEditorSubItemIndex: Integer; FCursorPos: TPoint; // Create native item function CreateItem(Index: Integer; ListItem: TListItem): TLVItem; // Free TEdit procedure FreeEditorItemInstance; // Invalidate cursor position procedure ResetCursorPos; { TEdit Events } procedure ListViewEditorExit(Sender: TObject); procedure ListViewEditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure ListViewEditorKeyPress(Sender: TObject; var Key: Char); { Override Events } procedure Click; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; { Windows Events } { TODO -cenhancement : Scroll edit control with listview } procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL; procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL; procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; /// /// Start edition on local position /// procedure EditCaptionAt(Point: TPoint); end; implementation uses Vcl.Controls; { TListView } procedure TListView.Click; begin inherited; // Get current point FCursorPos := ScreenToClient(Mouse.CursorPos); FreeEditorItemInstance; end; constructor TListView.Create(AOwner: TComponent); begin inherited Create(AOwner); // Create the TEdit and assign the OnExit event FListViewEditor := TEdit.Create(AOwner); with FListViewEditor do begin Parent := Self; OnKeyDown := ListViewEditorKeyDown; OnKeyPress := ListViewEditorKeyPress; OnExit := ListViewEditorExit; Visible := False; end; end; destructor TListView.Destroy; begin // Free TEdit FListViewEditor.Free; inherited; end; procedure TListView.EditCaptionAt(Point: TPoint); var Rect: TRect; CursorPos: TPoint; HitTestInfo: TLVHitTestInfo; CurrentItem: TListItem; begin // Set position to handle HitTestInfo.pt := Point; // Get item select if ListView_SubItemHitTest(Handle, @HitTestInfo) = -1 then Exit; with HitTestInfo do begin FEditorItemIndex := iItem; FEditorSubItemIndex := iSubItem; end; // Nothing? if (FEditorItemIndex < 0) or (FEditorItemIndex >= Items.Count) then Exit; if FEditorSubItemIndex < 0 then Exit; CurrentItem := Items[ItemIndex]; if not CanEdit(CurrentItem) then Exit; // Get bounds ListView_GetSubItemRect(Handle, FEditorItemIndex, FEditorSubItemIndex, LVIR_LABEL, @Rect); // set the text of the Edit if FEditorSubItemIndex = 0 then FListViewEditor.Text := CurrentItem.Caption else begin FListViewEditor.Text := CurrentItem.SubItems[FEditorSubItemIndex - 1]; end; // Set the bounds of the TEdit FListViewEditor.BoundsRect := Rect; // Show the TEdit FListViewEditor.Visible := True; // Set focus FListViewEditor.SetFocus; end; procedure TListView.ResetCursorPos; begin // Free cursos pos FCursorPos := Point(-1, -1); end; procedure TListView.FreeEditorItemInstance; begin FEditorItemIndex := -1; FEditorSubItemIndex := -1; FListViewEditor.Visible := False; // Hide the TEdit end; procedure TListView.KeyDown(var Key: Word; Shift: TShiftState); begin inherited KeyDown(Key, Shift); // F2 key start edit if (Key = VK_F2) then EditCaptionAt(FCursorPos); end; /// /// Create a LVItem /// function TListView.CreateItem(Index: Integer; ListItem: TListItem): TLVItem; begin with Result do begin mask := LVIF_PARAM or LVIF_IMAGE or LVIF_GROUPID; iItem := index; iSubItem := 0; iImage := I_IMAGECALLBACK; iGroupId := -1; pszText := PChar(ListItem.Caption); {$IFDEF CLR} lParam := ListItem.GetHashCode; {$ELSE} lParam := Winapi.Windows.lParam(ListItem); {$ENDIF} end; end; procedure TListView.ListViewEditorExit(Sender: TObject); begin // I have an instance? if FEditorItemIndex = -1 then Exit; // Assign the value of the TEdit to the Subitem if FEditorSubItemIndex = 0 then Items[FEditorItemIndex].Caption := FListViewEditor.Text else Items[FEditorItemIndex].SubItems[FEditorSubItemIndex - 1] := FListViewEditor.Text; // Raise OnEdited event Edit(CreateItem(FEditorItemIndex, Items[FEditorItemIndex])); // Free instanse FreeEditorItemInstance; end; procedure TListView.ListViewEditorKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin // ESCAPE key exit of editor if Key = VK_ESCAPE then FreeEditorItemInstance; end; procedure TListView.ListViewEditorKeyPress(Sender: TObject; var Key: Char); begin // Update item on press ENTER if (Key = #$0A) or (Key = #$0D) then FListViewEditor.OnExit(Sender); end; procedure TListView.WMHScroll(var Message: TWMHScroll); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; procedure TListView.WMMouseWheel(var Message: TWMMouseWheel); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; procedure TListView.WMVScroll(var Message: TWMVScroll); begin inherited; // Reset cursos pos ResetCursorPos; // Free instanse FreeEditorItemInstance; end; end. ``` The original poster's, [Bakasura](https://stackoverflow.com/users/8235752/bakasura), answer had been deleted: [![Screenshot of original answer](https://i.stack.imgur.com/z5l80.png)](https://i.stack.imgur.com/z5l80.png)
58,320,581
Is there a way in xpath to select an element and than select children of the element? i.e. given a parent result, how can I find a child that is relative to `this` paraent suppose the following code: ```html <div class="product-general" prod-id="4407"> <img src="..."/> <div class="prod-name">Black Dog</div> </div> ``` in `jQuery` one can do: ```js parent = $('.product-general') id = parent.attr('prod-id') name = $('.prod-name', parent).text() ``` I have the following code (php): ``` $results = $xpath->query("//*[@class='product-general']"); for ($i = 0; $i < $results->length; $i++) { $parent = $results->item($i)->nodeValue; // todo: get prod-id and prod-name } ``` Is it possible to get the prod-id and prod-name that are relative to the parent? NOTE: I know I can do it as follow: ``` $results = $xpath->query("//*[@class='product-general']/@data-pid"); for ($i = 0; $i < $results->length; $i++) { $pid = $results->item($i)->nodeValue; $results2 = $xpath->query("//*[@class='product-general' and @data-pid='".$pid."']//*[contains(@class,'prod-name')]");// $name= $results2->item(0)->nodeValue; $this->products[] = ['pid' => $pid, 'name' => $name]; } ``` But I want to know if there is something more elegant, like the JQ example Also, this solution is painfully slow for a document with 1000 products 10x
2019/10/10
[ "https://Stackoverflow.com/questions/58320581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1406269/" ]
The second param to the `query` is a `$contextnode` that way you can use **relative XPath** like this: ``` foreach ($articles as $article) { $href = $xpath->query('./a/@href', $article)->item(0)->nodeValue; # $href = $xpath->evaluate('string(./a/@href)', $article); # using evaluate } ```
I came up with this: ``` $results = $xpath->query("//*[@id='searchPage']//article"); for ($i = 0; $i < $results->length; $i++) { $counter = $i+1; $href = $xpath->query("//*[@id='searchPage']//article[".$counter."]/a/@href")->item(0)->nodeValue; } ``` This code will loop on all `article` in `searchPage` and extract their `<a href="...">` The key idea is that by adding the `[".$counter."]` to the query u can use the current loop index as a context for searching sub-elements NOTE that `$counter = $i+1;`
46,984,896
I'm trying to determine if a list `A` contains a value different from two other values, which make up list `B` (`0` and `1`): ``` [0, 1, 0, 1, 0] # False [0, 0, 0, 0, 0] # False [1, 1, 1, 1, 1] # False [0, 1, 0, 2, 0] # True ``` Here's what I have so far but I feel like there's a nice one-liner or a generally much more efficient way: ``` indicator = False A = [0, 1, 0, 2, 0] B = [0, 1] for i in A: if i not in B: indicator = True ```
2017/10/27
[ "https://Stackoverflow.com/questions/46984896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6611672/" ]
You can use `set.issubset()` for this purpose. ``` if not set(A).issubset(B): print("True") else: print("False") ``` Input: ``` A = [0, 1, 0, 2, 0] B = [0, 1] ``` Output: `True` Input: ``` A = [0, 1, 0, 1, 0] B = [0, 1] ``` Output: `False`
The complexity of a solution is at best linear, meaning that in the worst case you will have to check all the items in the list. That's, however, the **worst** case. So, if performance is the issue, you can just stop when you find the first different value: ``` for i in A: if i not in B: indicator = True break ``` If in a very long list of 20 billion values the first item is already not in B, the outer loop will execute only one time and exit, instead of 20 billion! It will not guarantee you to run faster -the algorithm is still linear, if you can stop earlier depends on the values in the list- but with a bit of luck you may end up saving a significant amount of time. Also note that the `i not in B`, as it is, is linear in complexity. Every time you execute that line, it will implicitly iterate on the B list values. If A contains N elements and B contains M elements, the total number of operations will be N\*M in the worst case scenario. For very small M is ok, but for large lists of values you could consider a `set`. If B is a set, the check `i not in B` would be executed in constant time, so that the total number of operations will scale only with N. If your problem is having a one-liner, as previous answer pointed out, a `set` is a collection of unique items, so using them you can obtain elegant one-liners with linear complexity. My version: ``` indicator = not(set(array) == set(allowed_values)) ``` Generating the set, however, requires to read all the input array, which again could be slower than the first solution when you have very large arrays and you're in a lucky situation: for example when the first number of the array is not in your accepted values.
650,215
I came across the term "Particle Phenomenology", which is "the application of theoretical physics to experimental data by making quantitative predictions based upon known theories" (quote from Wikipedia). It appears to be a field between particle experiment and particle theory. My question is: who contributes to the field of "Particle Phenomenology", experimentalists or theorists?
2021/07/08
[ "https://physics.stackexchange.com/questions/650215", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/210948/" ]
I copy here from a [prominent US university.](https://phy.princeton.edu/research/research-areas/particle-phenomenology) > > Particle physics phenomenolog*y is the field of theoretical physics* that focuses on the observable consequences of the fundamental particles of Nature and their interactions. The recent discovery of the Higgs boson provides an exquisite confirmation of the Standard Model, but important mysteries remain, including the nature of dark matter, the origin of the matter-antimatter asymmetry in the Universe, the properties of the neutrino sector, and the lightness of the Higgs mass. The Princeton phenomenology group works at the interface between theory and experiment to tackle these many challenges. > > > Italics mine.
> > It appears to be a field between particle experiment and particle theory. > > > Exactly. There is one big gray wash from engineering to experimental (particle) physics to phenomenology to theoretical physics to mathematics that defining clear boundaries between those is a moot exercise. Typically when particle theorists deal with real data, that is called phenomenology. Often, experimentalists contribute to that too. Since phenomenology doesn't require expensive equipment, the job market for phenomenologists is similar to that for theorists. That fortifies the notion to count phenomenology towards theory.
1,174,609
I'm trying to use this formula, but Excel keeps telling me there's an error. ``` =SI(NB.SI(A2;"*D*");"Data";"SI(NB.SI(A2;"*V*");"Voice";"Autres")") ``` (In English: ``` =IF(COUNTIF(A2;"*D*");"Data";"IF(COUNTIF(A2;"*V*");"Voice";"Autres")") ``` ) I don't understand where it is. SI Means IF, I am using a french version on Excel 2010 on Win7. As my English is not perfect, some things I'll say might sound weird. Here is a demo of what I am doing: ![Screeenshot](https://i.stack.imgur.com/A1PMi.png) * IF D*x* Type Data * IF V*x* Type Voice * IF anything else, Type Autres. *x* is a number. There are no other types, only “Data”, “Voice” and “Autres”. It may be my own formula that is incorrect, if you have another way to type this, feel free to do so.
2017/02/02
[ "https://superuser.com/questions/1174609", "https://superuser.com", "https://superuser.com/users/674711/" ]
I don't have the french version, so I can't rule out that SI and NB.SI are good or bad. Assuming they're good, here is the formula broken down: ``` =SI ( NB.SI ( A2; "D" ); * "Data"; "SI < ( NB.SI ( A2; "V" ); * "Voice"; "Autres" )" < ) ``` This tells me there are two " that are incorrect. These are highlighted above using the <. In addition the NB.SI formula is incomplete. NB.SI will return the amount of matches, but IF only checks for a true of false, so we need to change the amount of matches in a true or false by evaluating if they're more than 0. These are highlighted above using an \*. The correct formula would be ``` =SI ( NB.SI ( A2; "D" )>0; "Data"; SI ( NB.SI ( A2; "V" )>0; "Voice"; "Autres" ) ) ``` or: ``` =SI(NB.SI(A2;"D")>0;"Data";SI(NB.SI(A2;"V")>0;"Voice";"Autres")) ```
=IF(COUNTIF(A2,"D\*"),"Data",IF(COUNTIF(A2,"V\*"),"Voice","Autres")) In French the following after your update: `=SI(NB.SI(A2;"D*");"Data",SI(NB.SI(A2;"V*");"Voice";"Autres"))` Maybe you should use SI instead of NB.SI if your Data in A2 is only D or V since no count is needed the formula become `=SI(A2="D";"Data",SI(A2="V";"Voice";"Autres"))` Or after your update: `=SI(GAUCHE(A2,1)="D";"Data",SI(GAUCHE(A2,1)="V";"Voice";"Autres"))`
1,174,609
I'm trying to use this formula, but Excel keeps telling me there's an error. ``` =SI(NB.SI(A2;"*D*");"Data";"SI(NB.SI(A2;"*V*");"Voice";"Autres")") ``` (In English: ``` =IF(COUNTIF(A2;"*D*");"Data";"IF(COUNTIF(A2;"*V*");"Voice";"Autres")") ``` ) I don't understand where it is. SI Means IF, I am using a french version on Excel 2010 on Win7. As my English is not perfect, some things I'll say might sound weird. Here is a demo of what I am doing: ![Screeenshot](https://i.stack.imgur.com/A1PMi.png) * IF D*x* Type Data * IF V*x* Type Voice * IF anything else, Type Autres. *x* is a number. There are no other types, only “Data”, “Voice” and “Autres”. It may be my own formula that is incorrect, if you have another way to type this, feel free to do so.
2017/02/02
[ "https://superuser.com/questions/1174609", "https://superuser.com", "https://superuser.com/users/674711/" ]
I don't have the french version, so I can't rule out that SI and NB.SI are good or bad. Assuming they're good, here is the formula broken down: ``` =SI ( NB.SI ( A2; "D" ); * "Data"; "SI < ( NB.SI ( A2; "V" ); * "Voice"; "Autres" )" < ) ``` This tells me there are two " that are incorrect. These are highlighted above using the <. In addition the NB.SI formula is incomplete. NB.SI will return the amount of matches, but IF only checks for a true of false, so we need to change the amount of matches in a true or false by evaluating if they're more than 0. These are highlighted above using an \*. The correct formula would be ``` =SI ( NB.SI ( A2; "D" )>0; "Data"; SI ( NB.SI ( A2; "V" )>0; "Voice"; "Autres" ) ) ``` or: ``` =SI(NB.SI(A2;"D")>0;"Data";SI(NB.SI(A2;"V")>0;"Voice";"Autres")) ```
Yorik helped me find the answer. I used the formula: ``` =SI(GAUCHE(A2)="D";"Data";SI(GAUCHE(A2)="V";"Voice";"Autres")) ``` (English: ``` =IF(LEFT(A2)="D";"Data";IF(LEFT(A2)="V";"Voice";"Autres")) ``` And it worked perfectly. This also thought me a lesson about how to use Brackets and Quotes correctly ! Thanks SuperUsers :)
41,668,251
Given a list of non negative integers, I would like to arrange them such that they form the largest number. Given [1, 20, 23, 4, 8], the largest formed number is 8423201. But I want to figure how the order of the variables in compareTo method influences the result of Arrays.sort. e.g, what's the difference between (s2 + s1).compareTo(s1 + s2) and (s1 + s2).compareTo(s2 + s1). ``` enter code here private static class NumbersComparator implements Comparator<String> { @Override public int compare(String s1, String s2){ return (s2 + s1).compareTo(s1 + s2); } } String strs = {"1", "20", "23", "4", "8"}; Arrays.sort(strs, new NumbersComparator()); ```
2017/01/16
[ "https://Stackoverflow.com/questions/41668251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6939031/" ]
Sort the numbers with reverse (*descending*) [lexicographical order](https://en.wikipedia.org/wiki/Lexicographical_order), that is the numbers are sorted with `String`(s) in the default *reverse order*. Like, ``` String[] strs = { "1", "20", "23", "4", "8" }; Stream.of(strs).sorted(Comparator.reverseOrder()) // <-- sort in reverse order .forEachOrdered(System.out::print); System.out.println(); ``` Which outputs ``` 8423201 ``` Because `8` is greater than the first digit of all the other numbers, `4` is the next, and so on.
Yes. The order in compareTo method will makes a difference. When you use compareTo method for string it compares the Unicode values of each character in a string and return the difference of two character value from the strings. For example, ``` System.out.println("abdc".compareTo("abcd")); ``` will return the difference of 'd'-'c' ``` Output : 1 ``` and, ``` System.out.println("abcd".compareTo("abdc")); ``` will give difference of 'c'-'d' ``` Output : -1 ``` Overall, the order matters as it returns the difference in certain way, that is: ``` thisString.charAt(index) - argumentString.charAt(index); ```
14,385,003
I have a database (on DB2 9.7) A in which suppose I have tables X,Y,Z...n Now I have created same tables X,Y,Z...n in database B. I want to provide same GRANTs to users in database B as it was in database A. So based on SYSCAT.TABAUTH I am trying to generate GRANT SQLs. I have written the following query for it: ``` db2 "select 'GRANT '|| case INSERTAUTH WHEN 'Y' THEN 'INSERT,' WHEN 'N' THEN ' ' END|| case ALTERAUTH WHEN 'Y' THEN 'ALTER,' WHEN 'N' THEN ' ' END|| case DELETEAUTH WHEN 'Y' THEN 'DELETE,' WHEN 'N' THEN ' ' END|| case SELECTAUTH WHEN 'Y' THEN 'SELECT,' WHEN 'N' THEN ' ' END|| case UPDATEAUTH WHEN 'Y' THEN 'UPDATE,' WHEN 'N' THEN ' ' END|| ' ON '||TABSCHEMA||'.'||TABNAME||' TO '||GRANTEE from SYSCAT.TABAUTH where INSERTAUTH='Y' OR ALTERAUTH='Y' OR DELETEAUTH='Y' OR SELECTAUTH='Y' OR UPDATEAUTH='Y'" ``` However, the problem I am facing is of the additional ',' at end. Suppose a user has only Insert auth, the above query will generate GRANT sql as: ``` GRANT INSERT, ON SCHEMA.TABLE TO GRANTEENAME or if user has insert and select grants then: GRANT INSERT,SELECT, ON SCHEMA.TABLE TO GRANTEENAME ``` How can I solve this? Please help..
2013/01/17
[ "https://Stackoverflow.com/questions/14385003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969753/" ]
Add a function parameter and call it on success: ``` function myfunction(callback) { var value = "myvalue"; var post_url = "ajax.php"; $.post( post_url, { value: value, }, function(responseText){ var json = JSON.parse(responseText); if(json.success) { console.log('success'); //call callback callback(); } } ); } } ```
Have `myfunction` accept a callback: ``` function myfunction(callback) { var value = "myvalue"; var post_url = "ajax.php"; $.post(post_url, { value: value }, callback); } ``` And then you can pass in any function to be executed when the `POST` comes back: ``` myfunction(function(responseText){ var json = JSON.parse(responseText); if (json.success) { console.log('success'); } }); ```
14,385,003
I have a database (on DB2 9.7) A in which suppose I have tables X,Y,Z...n Now I have created same tables X,Y,Z...n in database B. I want to provide same GRANTs to users in database B as it was in database A. So based on SYSCAT.TABAUTH I am trying to generate GRANT SQLs. I have written the following query for it: ``` db2 "select 'GRANT '|| case INSERTAUTH WHEN 'Y' THEN 'INSERT,' WHEN 'N' THEN ' ' END|| case ALTERAUTH WHEN 'Y' THEN 'ALTER,' WHEN 'N' THEN ' ' END|| case DELETEAUTH WHEN 'Y' THEN 'DELETE,' WHEN 'N' THEN ' ' END|| case SELECTAUTH WHEN 'Y' THEN 'SELECT,' WHEN 'N' THEN ' ' END|| case UPDATEAUTH WHEN 'Y' THEN 'UPDATE,' WHEN 'N' THEN ' ' END|| ' ON '||TABSCHEMA||'.'||TABNAME||' TO '||GRANTEE from SYSCAT.TABAUTH where INSERTAUTH='Y' OR ALTERAUTH='Y' OR DELETEAUTH='Y' OR SELECTAUTH='Y' OR UPDATEAUTH='Y'" ``` However, the problem I am facing is of the additional ',' at end. Suppose a user has only Insert auth, the above query will generate GRANT sql as: ``` GRANT INSERT, ON SCHEMA.TABLE TO GRANTEENAME or if user has insert and select grants then: GRANT INSERT,SELECT, ON SCHEMA.TABLE TO GRANTEENAME ``` How can I solve this? Please help..
2013/01/17
[ "https://Stackoverflow.com/questions/14385003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969753/" ]
Have `myfunction` accept a callback: ``` function myfunction(callback) { var value = "myvalue"; var post_url = "ajax.php"; $.post(post_url, { value: value }, callback); } ``` And then you can pass in any function to be executed when the `POST` comes back: ``` myfunction(function(responseText){ var json = JSON.parse(responseText); if (json.success) { console.log('success'); } }); ```
Yes, you will either need to have a parameter to identify the caller, like ``` function myfunction(caller) { if (caller == "Foo") { // some code } } myFunction("Foo"); ``` Or use a global variable ``` function myFunction() { if (caller == "Foo") { // some code } } caller = "Foo"; myFunction(); ```
14,385,003
I have a database (on DB2 9.7) A in which suppose I have tables X,Y,Z...n Now I have created same tables X,Y,Z...n in database B. I want to provide same GRANTs to users in database B as it was in database A. So based on SYSCAT.TABAUTH I am trying to generate GRANT SQLs. I have written the following query for it: ``` db2 "select 'GRANT '|| case INSERTAUTH WHEN 'Y' THEN 'INSERT,' WHEN 'N' THEN ' ' END|| case ALTERAUTH WHEN 'Y' THEN 'ALTER,' WHEN 'N' THEN ' ' END|| case DELETEAUTH WHEN 'Y' THEN 'DELETE,' WHEN 'N' THEN ' ' END|| case SELECTAUTH WHEN 'Y' THEN 'SELECT,' WHEN 'N' THEN ' ' END|| case UPDATEAUTH WHEN 'Y' THEN 'UPDATE,' WHEN 'N' THEN ' ' END|| ' ON '||TABSCHEMA||'.'||TABNAME||' TO '||GRANTEE from SYSCAT.TABAUTH where INSERTAUTH='Y' OR ALTERAUTH='Y' OR DELETEAUTH='Y' OR SELECTAUTH='Y' OR UPDATEAUTH='Y'" ``` However, the problem I am facing is of the additional ',' at end. Suppose a user has only Insert auth, the above query will generate GRANT sql as: ``` GRANT INSERT, ON SCHEMA.TABLE TO GRANTEENAME or if user has insert and select grants then: GRANT INSERT,SELECT, ON SCHEMA.TABLE TO GRANTEENAME ``` How can I solve this? Please help..
2013/01/17
[ "https://Stackoverflow.com/questions/14385003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969753/" ]
Add a function parameter and call it on success: ``` function myfunction(callback) { var value = "myvalue"; var post_url = "ajax.php"; $.post( post_url, { value: value, }, function(responseText){ var json = JSON.parse(responseText); if(json.success) { console.log('success'); //call callback callback(); } } ); } } ```
Yes, you will either need to have a parameter to identify the caller, like ``` function myfunction(caller) { if (caller == "Foo") { // some code } } myFunction("Foo"); ``` Or use a global variable ``` function myFunction() { if (caller == "Foo") { // some code } } caller = "Foo"; myFunction(); ```
122,836
I am trying to search all input elements that starts with a partcular set of characters such as 'idAcc' where my VF page has two inputfields with id = idAccFN and id= idAccLN respectively. ``` <apex:inputField id="idAccFN" value="{!cr.FirstName__c}" /> <apex:inputField id="idAccLN" value="{!cr.LastName__c}" /> ``` I'm using the below JQuery syntax but thats working partially ... Explained in comments below .. Kindly help. ``` var j$ = jQuery.noConflict(); j$(document).ready(function(){ jQuery( 'input[id$=Name]' ).val('Foo'); // ID ending with Name working jQuery( 'input[id^=idAcc]' ).val('Apu') //Id starting with idAcc not working }); ```
2016/05/21
[ "https://salesforce.stackexchange.com/questions/122836", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/16234/" ]
the Id you set gets prepended by VF, so you need to do a "contains" selector. And if you want each element on the page, you need to use a ".each", like this: ``` j$(document).ready(function(){ jQuery( 'input[id*=Name]' ).each(function(el){ el.val('Foo'); // do something with the input here. }); ```
If you inspect the elements on the page you will notice that the id's are actually prepended by VF with j\_id0 etc (`j_id0:j_id1:page:messageDetail`)if you do not place IDs on all parent elements in your vf page. Thus the ID's do not start with the `idAcc` that you expect. If you need the 'Starts With' then you could look at `$Component` in javascript: > > Use the $Component global variable to simplify referencing the DOM ID > that is generated for a Visualforce component, and reduce some of the > dependency on the overall page structure. > > > <https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_access.htm>
67,547,166
This is the **Home Page** Code ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>HZ Everything Business</title> <link rel="stylesheet" href="home.css" /> <style> .menu { height: 70px; width: 70px; right: 70px; top: 20px; text-align: center; position: absolute; background: #fff; overflow: hidden; transition: all 0.2s ease; z-index: 999; } .menu.active { width: calc(100% - 140px); } .menu.active .menuContent * { opacity: 1; } .menu.active span i:nth-child(1) { transform: rotate(-45deg) translate(-50%, -50%); top: 50%; } .menu.active span i:nth-child(2) { transform: translateX(-100px); opacity: 0; } .menu.active span i:nth-child(3) { transform: rotate(45deg) translate(-50%, -50%); top: 50%; } .menu span { width: 70px; height: 70px; position: absolute; right: 0; cursor: pointer; background: #fff; z-index: 1; } .menu span i { position: absolute; transform-origin: 50% 50%; width: 45%; height: 2px; left: 0; right: 0; margin: auto; background-color: #ccc; transition: transform 0.3s ease, opacity 0.1s ease 0.1s; } .menu span i:nth-child(1) { top: 40%; } .menu span i:nth-child(2) { top: 50%; } .menu span i:nth-child(3) { top: 60%; } .menu .menuContent { position: absolute; width: 100%; height: 100%; line-height: 40px; right: 0px; text-align: center; } .menu .menuContent * { opacity: 0; } .menu .menuContent ul li { display: inline-block; margin-left: 50px; margin-right: 50px; color: #2d3235; transition: opacity 0.3s ease 0.3s; cursor: pointer; position: relative; } .menu .menuContent ul li:hover:before { opacity: 0.8; top: 13px; left: 20px; } .menu .menuContent ul li:hover:after { opacity: 0.8; bottom: 13px; left: -20px; } .menu .menuContent ul li:before, .menu .menuContent ul li:after { content: ""; position: absolute; width: 20px; height: 2px; background: #ccc; transition: all 0.3s ease; } .menu .menuContent ul li:before { transform: rotate(-55deg); left: 60px; top: -30px; opacity: 0; right: 0; margin: auto; } .menu .menuContent ul li:after { transform: rotate(-55deg); left: -60px; bottom: -30px; opacity: 0; right: 0; margin: auto; } </style> </head> <body> <div class='menu'> <span class='toggle'> <i></i> <i></i> <i></i> </span> <div class='menuContent'> <ul> <li>HZ Social Media Agency</li> <li>HZ WEBSITE & APP DEV</li> <li>HZ PHOTO & VIDEO EDITING</li> <li>OUR WORK</li> </ul> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.js" ></script> <script> $('.toggle').on('click', function() { $('.menu').toggleClass('active'); }); </script> <div class="bg"></div> </body> </html> ``` **CSS** ``` bg { height: 100%; width: 100%; background-color: blue; clip-path: polygon(100% 0, 100% 25%, 0 90%, 0 61%, 0 0); position: absolute; z-index: -1; } ``` I have tried everything I can do but it does not work , I tried changing the name of the CSS file even but it is still not working, any idea how I can fix that ? I have also tried putting it in the "styling tag as bg {} but still did not work , could it have something to do with where I typed the link ? under the title tags ?
2021/05/15
[ "https://Stackoverflow.com/questions/67547166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13097698/" ]
try this ``` foreach( $terms_arg as $display_term ){ if( $display_term->term_id != $queried_object->term_id ) { printf( '<div class="cat-list"><h3><a href="%s">%s</a></h3></div>', esc_url(get_term_link($display_term->term_id)), $display_term->name, ); } } ```
According to me get\_terms() is having the options of exclude under the argument parameter Try with below code ``` $terms_arg = get_terms( 'product_cat', array( 'orderby' => 'name', 'hide_empty' => false, 'parent' => $main_term->term_id, 'exclude' => $display_term->term_id, //assuming that $display_term->term_id is getting current category id ) ); ```
10,521
I just want to know whether both the usages are right or not. Also, do these usages depend on geography?
2011/01/29
[ "https://english.stackexchange.com/questions/10521", "https://english.stackexchange.com", "https://english.stackexchange.com/users/1749/" ]
It's a noun so it's necessary to specify the quantity. "One hundred" is the same as saying "a hundred," just like if you had six hundred it would be necessary to say "six hundred." The same rule applies to other nouns; you don't say "I have dollar" you say "I have one dollar" and you don't say "I have car" you say "I have a car." (or, of course, "I have six cars").
'Hundred' is a noun, not a quantity. Thus it needs a determiner like 'a' or 'one' to function as a quantity. 'Dozen' is functionally similar.
10,521
I just want to know whether both the usages are right or not. Also, do these usages depend on geography?
2011/01/29
[ "https://english.stackexchange.com/questions/10521", "https://english.stackexchange.com", "https://english.stackexchange.com/users/1749/" ]
'Hundred' is a noun, not a quantity. Thus it needs a determiner like 'a' or 'one' to function as a quantity. 'Dozen' is functionally similar.
Hundred in English signifies a unit of 10x10, 100. If you want to think about it mathematically, one hundred is 1x100. Two hundred is 2x100, or 200. In English you must specify how many units of 10x10 you have if you wish to make sense. Oyu can't just tell me that you have the unit 10x10, you need to say how many. Exception: this rule works, obviously, only with numbers between 100 and 9900. The rule is less consistent with numbers above five digits.
10,521
I just want to know whether both the usages are right or not. Also, do these usages depend on geography?
2011/01/29
[ "https://english.stackexchange.com/questions/10521", "https://english.stackexchange.com", "https://english.stackexchange.com/users/1749/" ]
It's a noun so it's necessary to specify the quantity. "One hundred" is the same as saying "a hundred," just like if you had six hundred it would be necessary to say "six hundred." The same rule applies to other nouns; you don't say "I have dollar" you say "I have one dollar" and you don't say "I have car" you say "I have a car." (or, of course, "I have six cars").
Hundred in English signifies a unit of 10x10, 100. If you want to think about it mathematically, one hundred is 1x100. Two hundred is 2x100, or 200. In English you must specify how many units of 10x10 you have if you wish to make sense. Oyu can't just tell me that you have the unit 10x10, you need to say how many. Exception: this rule works, obviously, only with numbers between 100 and 9900. The rule is less consistent with numbers above five digits.
223,731
I have one store (base) and I need to create another root category to test a new strucutre out so my plan was to create a new `Root Category` and then tell magmi to import into that... No such luck. I've created a new root category called Testing. Here is a sample of the Data. ``` sku,categories 12345, [Testing]/Level1;;[Testing]/Level1/Level2;;[Testing]/Level1/Level2/Level3 ``` Every time I try and import this, I get this error: `On the fly category creator/importer v0.2.5 - Cannot find site root with names : Testing,Testing,Testing` Can anyone help me out with this one?
2018/04/25
[ "https://magento.stackexchange.com/questions/223731", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/50626/" ]
Can you please add the following to the index.php of your website ``` ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); ```
Can you try to disable any custom module one by one to see that causes the issue? That may be cause by a faulty module or conflicting modules.
1,302,927
### Background By default, Microsoft [BitLocker](https://en.wikipedia.org/wiki/BitLocker) does not allow the user to enable full disk encryption (FDE) of the system disk, unless the PC has a compatible [TPM](https://en.wikipedia.org/wiki/Trusted_Platform_Module). However, if the "Allow BitLocker without a compatible TPM" option is turned on (under *Computer Configuration -> Administrative Templates -> Windows Components -> BitLocker Drive Encryption -> Operating System Drives -> Require additional authentication at startup*), then the BitLocker [wizard](https://en.wikipedia.org/wiki/Wizard_(software)) will permit FDE of the system disk. If this is done, then one of the wizard's dialogue boxes, headed "Choose how to unlock your drive at startup", will require the user to choose between two alternative authentication mechanisms: * Insert a USB flash drive; * Enter a password. If the user picks "Insert a USB flash drive", then typically the wizard will generate a "**startup key**" and will ask for a USB flash drive on which to write it. (The idea is that when wanting to boot the PC in the future, the user will *first* insert that USB flash drive into the PC and *then* switch on the PC. The Windows bootloader will then read the **startup key** from the flash drive in order to decrypt the system disk before booting Windows. I know people who do this in practice, and it works well. For more background, see e.g. [this](https://blogs.msdn.microsoft.com/mvpawardprogram/2016/01/12/securing-windows-10-with-bitlocker-drive-encryption/) and [this](https://superuser.com/questions/1075220/what-is-the-difference-between-a-bitlocker-startup-and-recovery-key).) ### My question When encrypting a drive with BitLocker, so as to require a **startup key**, can the user specify *her own custom* **startup key** (e.g. if she has previously generated one with the wizard and wants to use it on additional PCs), or must she accept the key generated by the BitLocker wizard? Alternatively, if she must accept the key created by the BitLocker wizard (at least while the wizard is running) then as a workaround, can she *later* replace this with her preferred **startup key**? Via the BitLocker Manage Keys interface, perhaps?
2018/03/13
[ "https://superuser.com/questions/1302927", "https://superuser.com", "https://superuser.com/users/-1/" ]
You cannot make your own startup key or import startup keys, BUT: > > When encrypting a drive with BitLocker, so as to require a startup > key, can the user specify her own custom startup key (e.g. if she has > previously generated one with the wizard and wants to use it on > additional PCs), or must she accept the key generated by the BitLocker > wizard? > > > In this example, if she is wishing to use the *same* startup key on multiple computers, it cannot be done. But, she CAN have the startup keys from different computers on the same USB. I do want to add that you may think that manage-bde -add could be used to "add" your own startup key as a protector, but it just creates a new startup key and adds it as a protector.
To answer your question: > > When encrypting a drive with BitLocker, so as to require a startup key, can the user specify her own custom startup key (e.g. if she has previously generated one with the wizard and wants to use it on additional PCs), or must she accept the key generated by the BitLocker wizard? > > > **The answer** is that we have to accepted the key generated by Bitlocer. > > Alternatively, if she must accept the key created by the BitLocker wizard (at least while the wizard is running) then as a workaround, can she later replace this with her preferred startup key? Via the BitLocker Manage Keys interface, perhaps? > > > **The answer** is that we cannot do this.
22,726,562
I cannot understand the difference between `interleaving` and `concatenation` Interleaving ``` proc sort data=ds1 out=ds1; by var1; run; proc sort data=ds2 out=ds2; by var1; run; data testInterleaving ; set ds1 ds2 ; run ; ``` Concatenation ``` data testConcatenation; set ds1 ds2; run; ``` I tested these and the resulting datasets were exactly the same except for the order of observations which I think does not really matter. The two resulting datasets contain exactly the same observations. So, what is the difference, except for order?
2014/03/29
[ "https://Stackoverflow.com/questions/22726562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2178635/" ]
SAS defines [INTERLEAVING](https://support.sas.com/documentation/cdl/en/basess/58133/HTML/default/viewer.htm#a001318366.htm) as using a BY statement with a SET statement. The included link shows two data sets, sorted by the same variable(s), generating one data set using a BY statement with a SET statement.
The data steps at the end are the exact same. You are performing the same code, it doesn't matter if you sort before hand. What I think you mean in the interleaving is ``` data testInterleaving ; MERGE ds1 ds2; by var1; run; ``` The `set` statement reads sequentially through the data sets in the order you list them. The `merge` statement compares records between the sets and puts them into the output in the order of the variable(s) in the `by` statement. I recommend looking at the SAS documentation on the `merge` statement as this is a very simplistic explanation for a very powerful tool.
22,726,562
I cannot understand the difference between `interleaving` and `concatenation` Interleaving ``` proc sort data=ds1 out=ds1; by var1; run; proc sort data=ds2 out=ds2; by var1; run; data testInterleaving ; set ds1 ds2 ; run ; ``` Concatenation ``` data testConcatenation; set ds1 ds2; run; ``` I tested these and the resulting datasets were exactly the same except for the order of observations which I think does not really matter. The two resulting datasets contain exactly the same observations. So, what is the difference, except for order?
2014/03/29
[ "https://Stackoverflow.com/questions/22726562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2178635/" ]
Interleaving, as CarolinaJay notes, is combining `SET` with `BY`. It is not merging, and it is not just sorting prior to setting. For example, let's create a pair of datasets, the female and the male members of `sashelp.class`. ``` data male female; set sashelp.class; if sex='F' then output female; else output male; run; proc sort data=male; by name; run; proc sort data=female; by name; run; data concatenated; set male female; run; data interleaved; set male female; by name; run; ``` Now, look at the datasets. `Concatenated` is all of the males, then all of the females - it processes the `set` statements in order, exhausting the first before moving onto the second. `Interleaved` is in name order, not in order by sex. That's because it traverses the two (in this case) `set` datasets by name, keeping track of where it is in the `name` ordering. You can add debugging statements (Either use the data step debugger, or add a `put _all_;` to the datastep) to see how it works.
The data steps at the end are the exact same. You are performing the same code, it doesn't matter if you sort before hand. What I think you mean in the interleaving is ``` data testInterleaving ; MERGE ds1 ds2; by var1; run; ``` The `set` statement reads sequentially through the data sets in the order you list them. The `merge` statement compares records between the sets and puts them into the output in the order of the variable(s) in the `by` statement. I recommend looking at the SAS documentation on the `merge` statement as this is a very simplistic explanation for a very powerful tool.
22,726,562
I cannot understand the difference between `interleaving` and `concatenation` Interleaving ``` proc sort data=ds1 out=ds1; by var1; run; proc sort data=ds2 out=ds2; by var1; run; data testInterleaving ; set ds1 ds2 ; run ; ``` Concatenation ``` data testConcatenation; set ds1 ds2; run; ``` I tested these and the resulting datasets were exactly the same except for the order of observations which I think does not really matter. The two resulting datasets contain exactly the same observations. So, what is the difference, except for order?
2014/03/29
[ "https://Stackoverflow.com/questions/22726562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2178635/" ]
Interleaving, as CarolinaJay notes, is combining `SET` with `BY`. It is not merging, and it is not just sorting prior to setting. For example, let's create a pair of datasets, the female and the male members of `sashelp.class`. ``` data male female; set sashelp.class; if sex='F' then output female; else output male; run; proc sort data=male; by name; run; proc sort data=female; by name; run; data concatenated; set male female; run; data interleaved; set male female; by name; run; ``` Now, look at the datasets. `Concatenated` is all of the males, then all of the females - it processes the `set` statements in order, exhausting the first before moving onto the second. `Interleaved` is in name order, not in order by sex. That's because it traverses the two (in this case) `set` datasets by name, keeping track of where it is in the `name` ordering. You can add debugging statements (Either use the data step debugger, or add a `put _all_;` to the datastep) to see how it works.
SAS defines [INTERLEAVING](https://support.sas.com/documentation/cdl/en/basess/58133/HTML/default/viewer.htm#a001318366.htm) as using a BY statement with a SET statement. The included link shows two data sets, sorted by the same variable(s), generating one data set using a BY statement with a SET statement.
6,045,317
I have a small database with several hundred resources of varying types (medical, education and research, for example). Each resource will need to be identified by its region. Some of the resources serve multiple regions. I need to be able to define each resource by its type, and it's region. Since one region will have many resources, and one resource can serve many counties I figure I should have a junction table between them, right? My question is, should I have a junction / linking table for each resource type? Should I have a table of education\_resources, regions and link them with a junction table education\_regions? And do the same thing for the rest of the categories?
2011/05/18
[ "https://Stackoverflow.com/questions/6045317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619741/" ]
I don't know if need to use CSV only, but a good plugin/function that I use is this one: <http://codeigniter.com/wiki/Excel_Plugin/> It's works with CodeIgniter Query system for exporting stuff to Excel. I use it a lot and never have problems with it.
Use `ob_clean();` before writing CSV to remove White spaces.
6,045,317
I have a small database with several hundred resources of varying types (medical, education and research, for example). Each resource will need to be identified by its region. Some of the resources serve multiple regions. I need to be able to define each resource by its type, and it's region. Since one region will have many resources, and one resource can serve many counties I figure I should have a junction table between them, right? My question is, should I have a junction / linking table for each resource type? Should I have a table of education\_resources, regions and link them with a junction table education\_regions? And do the same thing for the rest of the categories?
2011/05/18
[ "https://Stackoverflow.com/questions/6045317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619741/" ]
try to print on the browser, if you see some extra space then remove. if the extra is still on the csv file when you download, then this extra space is coming from any of your include file. when you start writing your code try not to leave some space on the top/bottom of the code.
Use `ob_clean();` before writing CSV to remove White spaces.
43,923
The following problem is homework of a sort -- but homework I can't do! The following problem is in Problem 1.F in *Van Lint and Wilson*: > > Let $G$ be a graph where every vertex > has degree $d$. Suppose that $G$ has > no loops, multiple edges, $3$-cycles > or $4$-cycles. Then $G$ has at least > $d^2+1$ vertices. When can equality > occur? > > > I assigned the lower bound early on in my graph theory course. Solutions for $d=2$ and $d=3$ are easy to find. Then, last week, when I covered eigenvalue methods, I had people use them to show that there were no solutions for $d=4$, $5$, $6$, $8$, $9$ or $10$. (Problem 2 [here](http://www.math.lsa.umich.edu/~speyer/PSet6.pdf).) I can go beyond this and show that the only possible values are $d \in \{ 2,3,7,57 \}$, and I wrote this up in a [handout](http://www.math.lsa.umich.edu/~speyer/Solution6.pdf) for my students. Does anyone know if the last two exist? I'd like to tell my class the complete story.
2010/10/28
[ "https://mathoverflow.net/questions/43923", "https://mathoverflow.net", "https://mathoverflow.net/users/297/" ]
This is the [Moore graph](http://en.wikipedia.org/wiki/Moore_graph), which is a regular graph of degree $d$ with diameter $k$, with maximum possible nodes. A calculation shows that the number of nodes $n$ is at most $$ 1+d \sum\_{i=0}^{k-1} (d-1)^i $$ and as you mentioned it can be shown by spectral techniques that the only possible values for $d$ are $$ d = 2,3,7,57. $$ Example for $d=7$ is the [Hoffman–Singleton graph](http://en.wikipedia.org/wiki/Hoffman-Singleton_graph), but for the case $d=57$ it is still open. See Theorem 8.1.5 in the book "[Spectra of graphs](http://homepages.cwi.nl/~aeb/math/ipm.pdf)" by Brouwer and Haemers for reference.
Additional random facts. The Peterson Graph can be obtained by identifying the antipodal points of a dodecahedron and it has $S\_5$ as its automorphism group (order 120 of course). There are a number of geometric constructions of the Hoffman-Singleton Graph (the 25 points and 25 non-vertical lines of an affine plane over $Z\_5$ are used in one , the 15 points and 35 lines of projective 3-space over $Z\_2$ in another). The automorphism group has order 252000. A Moore graph of degree 57, if it exists, ~~would have a trivial automorphism group:~~ would have to have a small automorphism group. **edit** See the comment below from Chris Godsil Aschbacher, M. "The Non-Existence of Rank Three Permutation Group of Degree 3250 and Subdegree 57." J. Algebra 19, 538-540, 1971. Here is a good reference from 2010: [Search for properties of the missing Moore graph](http://dx.doi.org/doi%3A10.1016/j.laa.2009.07.018) which shows among other things that if such a graph exists then it has automorphism group of order at most 375. **later** Since we have new interest I'll add some beautiful well known facts. * The triangle graph $T\_5$ is the line graph of $K\_5$ and is regular of degree 6 with 10 vertices. So $S\_5$ acts on it and that is the full automorphism group. As mentioned by N. Elkies, the Peterson graph is the complement of $T\_5$. $T\_5$ has five maximal cliques $K\_4$ corresponding to the 5 vertices. These become the five totally disconnected 4-vertex induced sub-graphs (independent sets) mentioned by R. Bell. If we fix one such independent 4-set, connect one new vertex with each of the six pairs and then connect each of these to the one pair disjoint from it, we get the Peterson Graph. So this is the points and edges of a tetrahedron. * In a Moore graph of order 7 the largest independent sets have 15 vertices. The incidence between these and the other 35 is the same as that between the points and blocks of a certain resolvable Steiner triple system and (equivalently) that between the 15 points and 35 lines of PG(3,2). These descriptions leave some edges unspecified, but: * Consider the 35 triples from $\{a,b,c,d,e,f,g\}$ as labels for 35 vertices and connect each to the four with labels disjoint from its own. There are 30 *heptads* being choices of seven triples no two disjoint (so forming a Fano plane). $S\_7$ is transitive on these but $A\_7$ has two orbits of size 15. If we use one such orbit to label 15 more vertices and make the obvious connections, we get the Moore graph of order 7. * The Peterson graph has a nice description in terms of the 4 points and 6 edges of a tetrahedron or PG(3,1) if we abuse notation. The Moore graph of order 7 has a nice description in terms of the 15 points and 35 lines of PG(3,2). Now, PG(3,7) has 400 points and 2850 lines and if there is a Moore graph of order 57 (warning! warning! Many would conjecture that there is none!) then it has 400+2850 vertices of which at most 400 could be independent... The fact that a large automorphism group has been ruled out makes this an unpromising approach, but who knows?
31,533,155
I am using Zotero as a plugin in Firefox on a Ubuntu12.4 machine. Since last week, the BibTex format for export seems to have disappeared from the options in the preferences. I have absolutely no idea why and I don't really care why. I simply want to get it back since it worked before. So I am looking for explanation on how to reinstall this option and eventually on where to get the format. I tried to desactivate and reactivate the zotero plug-in but it did not work. Thanks for any help
2015/07/21
[ "https://Stackoverflow.com/questions/31533155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4799951/" ]
Use a parameterized query and set the parameter type to [`Datetime`](https://msdn.microsoft.com/en-us/library/system.data.sqldbtype(v=vs.110).aspx): ``` SqlCommand cmd = new SqlCommand( "INSERT INTO ... (..., datetimecolumn, ...) VALUES (..,@datetimeparameter,...", connection); SqlParameter datetimeParameter = new SqlParameter( "@datetimeparameter", SqlDbType.Datetime); datetimeParameter.Value = <your C# variable of type Date>; ... cmd.ExecuteNonQuery(); ``` Using a framework like Entity Framework would take care of a lot of the boilerplate coding. Using [`SqlBulkCopy`](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx) is another viable approach. What does **not** work is passing in values as hard coded strings in T-SQL. Aside from SQL injection prone, slow and unperformant, there are countless issues around the combination of client (app) locale, server locale and SQL Server locale settings ([`SET DATEFORMAT`](https://msdn.microsoft.com/en-us/library/ms189491.aspx)). For the record: there is a locale independent datetime format in SQL Server, namely the `YYYYMMDD hh:mm:ss` format. Whenever you *must* use a T-SQL string to represent a date, use this format as is locale agnostic. Also you might want to learn a bit about [SSIS](https://msdn.microsoft.com/en-us/library/ms141026.aspx) as it does what you're trying to achieve out-of-the-box (there is an [SSIS Excel source](https://msdn.microsoft.com/en-us/library/ms141683.aspx)).
Excel stores internally the datetime as a number. So you will probably have to read it as number as well and convert it "manually" before storing it in SQL
31,533,155
I am using Zotero as a plugin in Firefox on a Ubuntu12.4 machine. Since last week, the BibTex format for export seems to have disappeared from the options in the preferences. I have absolutely no idea why and I don't really care why. I simply want to get it back since it worked before. So I am looking for explanation on how to reinstall this option and eventually on where to get the format. I tried to desactivate and reactivate the zotero plug-in but it did not work. Thanks for any help
2015/07/21
[ "https://Stackoverflow.com/questions/31533155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4799951/" ]
I did't test so i'm not 100% sure. Can you change your column to be datetime2(7) on database? and then send the datetime in following format YYYY-MM-DD hh:mm:ss. I suggest that because the datetime2 as a Default string literal in above format while the datetime don't has it so it's based on the system culture. I suggest that because the Datetime2 has the default literal string while the DateTime don't have it you can Click [MSDN web site](https://msdn.microsoft.com/en-us/library/bb677335.aspx) to find out more about it.
Excel stores internally the datetime as a number. So you will probably have to read it as number as well and convert it "manually" before storing it in SQL
31,533,155
I am using Zotero as a plugin in Firefox on a Ubuntu12.4 machine. Since last week, the BibTex format for export seems to have disappeared from the options in the preferences. I have absolutely no idea why and I don't really care why. I simply want to get it back since it worked before. So I am looking for explanation on how to reinstall this option and eventually on where to get the format. I tried to desactivate and reactivate the zotero plug-in but it did not work. Thanks for any help
2015/07/21
[ "https://Stackoverflow.com/questions/31533155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4799951/" ]
Use a parameterized query and set the parameter type to [`Datetime`](https://msdn.microsoft.com/en-us/library/system.data.sqldbtype(v=vs.110).aspx): ``` SqlCommand cmd = new SqlCommand( "INSERT INTO ... (..., datetimecolumn, ...) VALUES (..,@datetimeparameter,...", connection); SqlParameter datetimeParameter = new SqlParameter( "@datetimeparameter", SqlDbType.Datetime); datetimeParameter.Value = <your C# variable of type Date>; ... cmd.ExecuteNonQuery(); ``` Using a framework like Entity Framework would take care of a lot of the boilerplate coding. Using [`SqlBulkCopy`](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx) is another viable approach. What does **not** work is passing in values as hard coded strings in T-SQL. Aside from SQL injection prone, slow and unperformant, there are countless issues around the combination of client (app) locale, server locale and SQL Server locale settings ([`SET DATEFORMAT`](https://msdn.microsoft.com/en-us/library/ms189491.aspx)). For the record: there is a locale independent datetime format in SQL Server, namely the `YYYYMMDD hh:mm:ss` format. Whenever you *must* use a T-SQL string to represent a date, use this format as is locale agnostic. Also you might want to learn a bit about [SSIS](https://msdn.microsoft.com/en-us/library/ms141026.aspx) as it does what you're trying to achieve out-of-the-box (there is an [SSIS Excel source](https://msdn.microsoft.com/en-us/library/ms141683.aspx)).
I did't test so i'm not 100% sure. Can you change your column to be datetime2(7) on database? and then send the datetime in following format YYYY-MM-DD hh:mm:ss. I suggest that because the datetime2 as a Default string literal in above format while the datetime don't has it so it's based on the system culture. I suggest that because the Datetime2 has the default literal string while the DateTime don't have it you can Click [MSDN web site](https://msdn.microsoft.com/en-us/library/bb677335.aspx) to find out more about it.
5,853,804
I am working on a camera application. For first time if I capture image its working fine but if I take a picture again its throwing a error > > ERROR/dalvikvm-heap(2398): 10077696-byte external allocation too large for this process." VM won't let us allocate 10077696 bytes" and finally"05-02 05:35:38.390: ERROR/AndroidRuntime(2398): FATAL EXCEPTION: main > 05-02 05:35:38.390: ERROR/AndroidRuntime(2398): java.lang.OutOfMemoryError: bitmap size exceeds VM budget > > > and application force closes..how to handle this how to clear heap and vm? please help.. Thanks in advance..
2011/05/02
[ "https://Stackoverflow.com/questions/5853804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/707942/" ]
I found the answer. I used the following code: ``` BitmapFactory.Options bfOptions=new BitmapFactory.Options(); bfOptions.inDither=false; //Disable Dithering mode bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future bfOptions.inTempStorage=new byte[32 * 1024]; CameraTricks.SdCardImage= BitmapFactory.decodeFile(CameraTricks.yu,bfOptions); CameraTricks.yu is my path to bitmap ```
You don't. You can soft reset the device, but I doubt that will do any good. Android's garbage collector should take care of it. Most probably, your app is using too much memory for some operation. You can use DDMS to check memory consumption ([read about it here](http://developer.android.com/guide/developing/debugging/ddms.html)). You can read about similar issues in all these links: * <http://markmail.org/message/smg7pog5tz25p7w5> * [External allocation too large for this process in Android](https://stackoverflow.com/questions/4193917/external-allocation-too-large-for-this-process-in-android) * [Strange out of memory issue while loading an image to a Bitmap object](https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue) * <http://code.google.com/p/android/issues/detail?id=2822> * [Bitmap, Bitmap.recycle(), WeakReferences, and Garbage Collection](https://stackoverflow.com/questions/4959485/android-bitmap-bitmap-recycle-weakreference-and-garbage-collector) * [How to deal with "java.lang.OutOfMemoryError: Java heap space" error (64MB heap size)](https://stackoverflow.com/questions/37335/how-to-deal-with-java-lang-outofmemoryerror-java-heap-space-error-64mb-heap-s) It looks like a common theme is the loading of several large images. Make sure you don't keep references to images (or any other large object) you don't use any more, so the garbage collector can recover that memory. Use `Bitamp.recycle()`, for example. Lastly, make sure you read the article [Avoiding Memory Leaks](http://developer.android.com/resources/articles/avoiding-memory-leaks.html).
91,635
I work in an office with 8 people. We have no allocated seating. Which I am quite cool with. However, recently the tidiness has gotten quite out of hand. Papers, coffee stains, and some brochures scatter over the tables. It's quite a rude shock when I almost put my laptop down on someone's old coffee stain in the morning. Now my daily ritual is to wipe away all leftover hairs and dirt and choose an area that has less clutter. We have introduced individual shelf compartment for us to store our personal goods. However, most of them still do not have the habit to clear up after themselves when they leave at the end of the work day. I am quite concerned about how to keep the cleanliness, and would like to know if anyone has any experience in maintaining cleanliness in a free seating plan office?
2017/05/26
[ "https://workplace.stackexchange.com/questions/91635", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/70574/" ]
The answer would be either: 1. To hire a cleaner 2. Have allocated desks
You didn't mention any communication with the other 7 members of your work space, so I would suggest that as a first step. This is very similar to sharing an apartment with roommates, or having a common area. Sometimes you just need to set out rules for everyone to follow to maintain cleanliness. You could even provide some cleaning supplies as another person suggested, but cleaning up should be everyone's responsibility.
91,635
I work in an office with 8 people. We have no allocated seating. Which I am quite cool with. However, recently the tidiness has gotten quite out of hand. Papers, coffee stains, and some brochures scatter over the tables. It's quite a rude shock when I almost put my laptop down on someone's old coffee stain in the morning. Now my daily ritual is to wipe away all leftover hairs and dirt and choose an area that has less clutter. We have introduced individual shelf compartment for us to store our personal goods. However, most of them still do not have the habit to clear up after themselves when they leave at the end of the work day. I am quite concerned about how to keep the cleanliness, and would like to know if anyone has any experience in maintaining cleanliness in a free seating plan office?
2017/05/26
[ "https://workplace.stackexchange.com/questions/91635", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/70574/" ]
The answer would be either: 1. To hire a cleaner 2. Have allocated desks
Those who refuse to return the space they are using for the day back to a neutral clean environment are likely doing so as a way to make the free seating arrangement painful. If all the work environments were equal in resources, space, and comfort; and the work required in the morning and the evening to convert those spaces to your use was trivial; then depending on the number of people vs work space involved, free seating might make sense. If there are 8 work spaces but 15 employees but many are at customer sites or on travel or working from home, then free seating is a way to better use the resources. The behavior of those who continue to leave papers, stains and brochures at the end of each day may be a way of marking their territory. Or it a way resisting the lack of assigned seats. They may be leaving a level of clutter and filth that they can tolerate in the hopes that you won't take their seat. They may even settle for the situation where you spend time cleaning their spot from yesterday, while they take your clean spot. The next phase of their plan is for somebody who likes a clean work space to complain to management and to try and put a cleaning policy in place....
91,635
I work in an office with 8 people. We have no allocated seating. Which I am quite cool with. However, recently the tidiness has gotten quite out of hand. Papers, coffee stains, and some brochures scatter over the tables. It's quite a rude shock when I almost put my laptop down on someone's old coffee stain in the morning. Now my daily ritual is to wipe away all leftover hairs and dirt and choose an area that has less clutter. We have introduced individual shelf compartment for us to store our personal goods. However, most of them still do not have the habit to clear up after themselves when they leave at the end of the work day. I am quite concerned about how to keep the cleanliness, and would like to know if anyone has any experience in maintaining cleanliness in a free seating plan office?
2017/05/26
[ "https://workplace.stackexchange.com/questions/91635", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/70574/" ]
The answer would be either: 1. To hire a cleaner 2. Have allocated desks
It's the <https://en.wikipedia.org/wiki/Tragedy_of_the_commons> . Make it the Owner's problem, everyone's problem, or keep it to yourself (see who cracks first). Don't be Felix and live with Oscar.
91,635
I work in an office with 8 people. We have no allocated seating. Which I am quite cool with. However, recently the tidiness has gotten quite out of hand. Papers, coffee stains, and some brochures scatter over the tables. It's quite a rude shock when I almost put my laptop down on someone's old coffee stain in the morning. Now my daily ritual is to wipe away all leftover hairs and dirt and choose an area that has less clutter. We have introduced individual shelf compartment for us to store our personal goods. However, most of them still do not have the habit to clear up after themselves when they leave at the end of the work day. I am quite concerned about how to keep the cleanliness, and would like to know if anyone has any experience in maintaining cleanliness in a free seating plan office?
2017/05/26
[ "https://workplace.stackexchange.com/questions/91635", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/70574/" ]
You didn't mention any communication with the other 7 members of your work space, so I would suggest that as a first step. This is very similar to sharing an apartment with roommates, or having a common area. Sometimes you just need to set out rules for everyone to follow to maintain cleanliness. You could even provide some cleaning supplies as another person suggested, but cleaning up should be everyone's responsibility.
Those who refuse to return the space they are using for the day back to a neutral clean environment are likely doing so as a way to make the free seating arrangement painful. If all the work environments were equal in resources, space, and comfort; and the work required in the morning and the evening to convert those spaces to your use was trivial; then depending on the number of people vs work space involved, free seating might make sense. If there are 8 work spaces but 15 employees but many are at customer sites or on travel or working from home, then free seating is a way to better use the resources. The behavior of those who continue to leave papers, stains and brochures at the end of each day may be a way of marking their territory. Or it a way resisting the lack of assigned seats. They may be leaving a level of clutter and filth that they can tolerate in the hopes that you won't take their seat. They may even settle for the situation where you spend time cleaning their spot from yesterday, while they take your clean spot. The next phase of their plan is for somebody who likes a clean work space to complain to management and to try and put a cleaning policy in place....
91,635
I work in an office with 8 people. We have no allocated seating. Which I am quite cool with. However, recently the tidiness has gotten quite out of hand. Papers, coffee stains, and some brochures scatter over the tables. It's quite a rude shock when I almost put my laptop down on someone's old coffee stain in the morning. Now my daily ritual is to wipe away all leftover hairs and dirt and choose an area that has less clutter. We have introduced individual shelf compartment for us to store our personal goods. However, most of them still do not have the habit to clear up after themselves when they leave at the end of the work day. I am quite concerned about how to keep the cleanliness, and would like to know if anyone has any experience in maintaining cleanliness in a free seating plan office?
2017/05/26
[ "https://workplace.stackexchange.com/questions/91635", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/70574/" ]
You didn't mention any communication with the other 7 members of your work space, so I would suggest that as a first step. This is very similar to sharing an apartment with roommates, or having a common area. Sometimes you just need to set out rules for everyone to follow to maintain cleanliness. You could even provide some cleaning supplies as another person suggested, but cleaning up should be everyone's responsibility.
It's the <https://en.wikipedia.org/wiki/Tragedy_of_the_commons> . Make it the Owner's problem, everyone's problem, or keep it to yourself (see who cracks first). Don't be Felix and live with Oscar.
46,986,793
I'm trying to create a default value in Sequel: ``` create_table(:my_table) do primary_key :id # .......... Timestamp :created_at, default: "now()" ``` After running a migration, it generates a table with this column definition: ``` --........ created_at timestamp without time zone DEFAULT '2017-10-28 12:26:00.129157'::timestamp without time zone, ``` But what I want is the value "now()" to be set when I'm inserting a new value.
2017/10/28
[ "https://Stackoverflow.com/questions/46986793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8841042/" ]
I know this was asked a while ago but I had a similar problem that I solved by using `Sequal.lit` `Timestamp :created_at, default: Sequel.lit("now()")`
Are you trying to set a String in a Time field? I don't think this is going to work. You'll have to use `String :created_at, default: "now()"`
46,986,793
I'm trying to create a default value in Sequel: ``` create_table(:my_table) do primary_key :id # .......... Timestamp :created_at, default: "now()" ``` After running a migration, it generates a table with this column definition: ``` --........ created_at timestamp without time zone DEFAULT '2017-10-28 12:26:00.129157'::timestamp without time zone, ``` But what I want is the value "now()" to be set when I'm inserting a new value.
2017/10/28
[ "https://Stackoverflow.com/questions/46986793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8841042/" ]
I know this was asked a while ago but I had a similar problem that I solved by using `Sequal.lit` `Timestamp :created_at, default: Sequel.lit("now()")`
The way to do it is as follows, using either `Sequel.function(:now)` or `Sequel::CURRENT_TIMESTAMP` ```rb Time :created_at, default: Sequel.function(:now) # or... Time :created_at, default: Sequel::CURRENT_TIMESTAMP ```
60,295,386
I am trying to delete a row in my table. Here is my sample code ``` String DBDate = new String(); Long date = new Date().getTime(); String dateToday = date.toString(); dbobj.clear(); dbobj.put(LAST_TIME_ANSWERED, ""); int hasDB = dbobj.getFromDB(tableName,column key, primary key); if(hasDB != 0) { DBDate = dbobj.get(LAST_TIME_ANSWERED); if(DBDate != dateToday) { dbobj.deleteClientDB(tableName, column key, primary key); } } ``` How could I change the date of a timer? Any help would be nice. Thanks in advance!
2020/02/19
[ "https://Stackoverflow.com/questions/60295386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12923933/" ]
This is awkward to achieve in java, because you need to run a job on a schedule to achieve this. You should strongly consider using the mysql event scheduler. See [this answer](https://stackoverflow.com/a/14806127/2051454) for an example of this. When you insert the row in the db you should set up an event that is triggered exactly once, 24-hours later, with the necessary sql to delete the row. You would end up with one event per row. Alternatively, with java and a properly configured server, after each row insert you could add a cron or quartz job that would trigger once, 24-hours later, that would invoke a java function to remove the row. This is harder than using the db's built-in event scheduler. Depending on your JEE version (>6) you could use an EJB 3.1 timer, as detailed in [this blog post](http://www.adam-bien.com/roller/abien/entry/simplest_possible_ejb_3_16). Of these options, the db event scheduler is probably the best, because the others can go wrong if the JEE sever is down.
there are two options for this. 1.) use java scheduler or 2.) use a scheduled job at DB level to clear data at the end of each day
60,295,386
I am trying to delete a row in my table. Here is my sample code ``` String DBDate = new String(); Long date = new Date().getTime(); String dateToday = date.toString(); dbobj.clear(); dbobj.put(LAST_TIME_ANSWERED, ""); int hasDB = dbobj.getFromDB(tableName,column key, primary key); if(hasDB != 0) { DBDate = dbobj.get(LAST_TIME_ANSWERED); if(DBDate != dateToday) { dbobj.deleteClientDB(tableName, column key, primary key); } } ``` How could I change the date of a timer? Any help would be nice. Thanks in advance!
2020/02/19
[ "https://Stackoverflow.com/questions/60295386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12923933/" ]
One common practice is to delete database records which are older than some threshold value. For this purpose, the database table should have a column with a timestamp representing insert or update time. When executing the scheduled task there a command is performed (pseudocode, assuming an 'update' timestamp): DELETE FROM TABLE\_NAME WHERE LAST\_UPDATED < (CURRENT\_TIME - THRESHOLD) Or there is a select query performed to retrieve all these records and handle their deletion one by one including logging and maybe some conditional logic. To achieve this functionality java SE provides [ScheduledExecutorService](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html) which can be used to execute delayed tasks: ``` // initialize scheduler ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // schedule repeating task ScheduledFuture future = scheduler.scheduleAtFixedRate( () -> { System.out.println("Excuting task..."); }, 60, 60, TimeUnit.SECONDS ); ``` The future object can be used to cancel task: ``` future.cancel(true); scheduler.shutdown(); ``` But when using enterprise solutions, there are normally libraries and frameworks, providing functionality for executing scheduled tasks: [quartz scheduler](https://github.com/quartz-scheduler/quartz), [spring framework task scheduling](https://spring.io/guides/gs/scheduling-tasks/) or [EJB timer services](https://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html).
there are two options for this. 1.) use java scheduler or 2.) use a scheduled job at DB level to clear data at the end of each day
33,081,669
I'm taking a Udacity course on making a site responsive and I tried applying `<meta name="viewport" content="width=device-width, initial-scale=1.0">` on a non-responsive site. The result was that page did not try to fit the device's width. Am I misunderstanding something? [![enter image description here](https://i.stack.imgur.com/MBqE8.png)](https://i.stack.imgur.com/MBqE8.png)
2015/10/12
[ "https://Stackoverflow.com/questions/33081669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1242842/" ]
Your html page probably has a wrapping container that has a fixed width in pixel. `<meta name="viewport" content="width=device-width, initial-scale=1.0">` will not make your webpage responsive, but rather has an effect on the ratio sizes that i.e. fonts will be rendered with. Try giving the container a width of `100%` and go from there.
It appears part of your page consists of a table. Most likely that table simply won't fit inside the available width, forcing the page to overflow the device, so to speak. It could also be any other element either having a fixed width that's too high or that for other reasons can't scale to fit the available width, like text with `white-space: nowrap`. Without seeing more of your code it's impossible to tell.
33,081,669
I'm taking a Udacity course on making a site responsive and I tried applying `<meta name="viewport" content="width=device-width, initial-scale=1.0">` on a non-responsive site. The result was that page did not try to fit the device's width. Am I misunderstanding something? [![enter image description here](https://i.stack.imgur.com/MBqE8.png)](https://i.stack.imgur.com/MBqE8.png)
2015/10/12
[ "https://Stackoverflow.com/questions/33081669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1242842/" ]
It appears part of your page consists of a table. Most likely that table simply won't fit inside the available width, forcing the page to overflow the device, so to speak. It could also be any other element either having a fixed width that's too high or that for other reasons can't scale to fit the available width, like text with `white-space: nowrap`. Without seeing more of your code it's impossible to tell.
Change the ratio in your Dev tools. Now, it is 2. Change it to 1.
33,081,669
I'm taking a Udacity course on making a site responsive and I tried applying `<meta name="viewport" content="width=device-width, initial-scale=1.0">` on a non-responsive site. The result was that page did not try to fit the device's width. Am I misunderstanding something? [![enter image description here](https://i.stack.imgur.com/MBqE8.png)](https://i.stack.imgur.com/MBqE8.png)
2015/10/12
[ "https://Stackoverflow.com/questions/33081669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1242842/" ]
Your html page probably has a wrapping container that has a fixed width in pixel. `<meta name="viewport" content="width=device-width, initial-scale=1.0">` will not make your webpage responsive, but rather has an effect on the ratio sizes that i.e. fonts will be rendered with. Try giving the container a width of `100%` and go from there.
``` <meta name="viewport" content="width=device-width, initial-scale=1"> ``` you should try this.
33,081,669
I'm taking a Udacity course on making a site responsive and I tried applying `<meta name="viewport" content="width=device-width, initial-scale=1.0">` on a non-responsive site. The result was that page did not try to fit the device's width. Am I misunderstanding something? [![enter image description here](https://i.stack.imgur.com/MBqE8.png)](https://i.stack.imgur.com/MBqE8.png)
2015/10/12
[ "https://Stackoverflow.com/questions/33081669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1242842/" ]
Your html page probably has a wrapping container that has a fixed width in pixel. `<meta name="viewport" content="width=device-width, initial-scale=1.0">` will not make your webpage responsive, but rather has an effect on the ratio sizes that i.e. fonts will be rendered with. Try giving the container a width of `100%` and go from there.
Change the ratio in your Dev tools. Now, it is 2. Change it to 1.
33,081,669
I'm taking a Udacity course on making a site responsive and I tried applying `<meta name="viewport" content="width=device-width, initial-scale=1.0">` on a non-responsive site. The result was that page did not try to fit the device's width. Am I misunderstanding something? [![enter image description here](https://i.stack.imgur.com/MBqE8.png)](https://i.stack.imgur.com/MBqE8.png)
2015/10/12
[ "https://Stackoverflow.com/questions/33081669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1242842/" ]
``` <meta name="viewport" content="width=device-width, initial-scale=1"> ``` you should try this.
Change the ratio in your Dev tools. Now, it is 2. Change it to 1.
10,330,598
I'm using Netbeans, SWING to get data from mysql table to jTable. I done it, but headers of table. Headers are the same like in mysql table. How to change headers of jTable after getting data from DB? P.S. Default headers don't works in this issue. This is auto-generated code: @SuppressWarnings("unchecked") // private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); ``` progressjournalPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("progressjournalPU").createEntityManager(); pupilsQuery = java.beans.Beans.isDesignTime() ? null : progressjournalPUEntityManager.createQuery("SELECT p FROM Pupils p"); pupilsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : pupilsQuery.getResultList(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Журнал успеваемости"); setResizable(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "ФИО", "Курс", "Предмет", "Оценка" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, pupilsList, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilMark}")); columnBinding.setColumnName("Pupil Mark"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilSubject}")); columnBinding.setColumnName("Pupil Subject"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilCourse}")); columnBinding.setColumnName("Pupil Course"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilName}")); columnBinding.setColumnName("Pupil Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilId}")); columnBinding.setColumnName("Pupil Id"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); bindingGroup.bind(); pack(); ``` }// And this code is locked for editing.
2012/04/26
[ "https://Stackoverflow.com/questions/10330598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568975/" ]
I have made it run for these dependencies: ``` def poiVersion='3.9' compile 'org.apache.poi:poi:'+poiVersion compile 'org.apache.poi:poi-ooxml:'+poiVersion compile 'org.apache.poi:poi-ooxml-schemas:'+poiVersion ``` When I try for others it does not work: 3.10 : is not known to maven central 3.11 : fails, with exact the error in this case !!! Conclusion POI 3.9 works !!!!
I use 3.7 but have you try adding ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.8</version> </dependency> ```
10,330,598
I'm using Netbeans, SWING to get data from mysql table to jTable. I done it, but headers of table. Headers are the same like in mysql table. How to change headers of jTable after getting data from DB? P.S. Default headers don't works in this issue. This is auto-generated code: @SuppressWarnings("unchecked") // private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); ``` progressjournalPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("progressjournalPU").createEntityManager(); pupilsQuery = java.beans.Beans.isDesignTime() ? null : progressjournalPUEntityManager.createQuery("SELECT p FROM Pupils p"); pupilsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : pupilsQuery.getResultList(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Журнал успеваемости"); setResizable(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "ФИО", "Курс", "Предмет", "Оценка" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, pupilsList, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilMark}")); columnBinding.setColumnName("Pupil Mark"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilSubject}")); columnBinding.setColumnName("Pupil Subject"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilCourse}")); columnBinding.setColumnName("Pupil Course"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilName}")); columnBinding.setColumnName("Pupil Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilId}")); columnBinding.setColumnName("Pupil Id"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); bindingGroup.bind(); pack(); ``` }// And this code is locked for editing.
2012/04/26
[ "https://Stackoverflow.com/questions/10330598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568975/" ]
I tried using `poi 3.10`, `3.11` and `3.12 beta` with Grails and get this error as well. After downloading and including <http://mirrors.ibiblio.org/pub/mirrors/maven2/org/apache/poi/ooxml-schemas/1.0/ooxml-schemas-1.0.jar> the error is gone.
I use 3.7 but have you try adding ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.8</version> </dependency> ```
10,330,598
I'm using Netbeans, SWING to get data from mysql table to jTable. I done it, but headers of table. Headers are the same like in mysql table. How to change headers of jTable after getting data from DB? P.S. Default headers don't works in this issue. This is auto-generated code: @SuppressWarnings("unchecked") // private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); ``` progressjournalPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("progressjournalPU").createEntityManager(); pupilsQuery = java.beans.Beans.isDesignTime() ? null : progressjournalPUEntityManager.createQuery("SELECT p FROM Pupils p"); pupilsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : pupilsQuery.getResultList(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Журнал успеваемости"); setResizable(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "ФИО", "Курс", "Предмет", "Оценка" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, pupilsList, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilMark}")); columnBinding.setColumnName("Pupil Mark"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilSubject}")); columnBinding.setColumnName("Pupil Subject"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilCourse}")); columnBinding.setColumnName("Pupil Course"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilName}")); columnBinding.setColumnName("Pupil Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilId}")); columnBinding.setColumnName("Pupil Id"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); bindingGroup.bind(); pack(); ``` }// And this code is locked for editing.
2012/04/26
[ "https://Stackoverflow.com/questions/10330598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568975/" ]
I used poi with version 3.12. The following dependency is also required: `compile 'org.apache.poi:ooxml-schemas:1.1'` see also <http://poi.apache.org/faq.html#faq-N10025>
I use 3.7 but have you try adding ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.8</version> </dependency> ```
10,330,598
I'm using Netbeans, SWING to get data from mysql table to jTable. I done it, but headers of table. Headers are the same like in mysql table. How to change headers of jTable after getting data from DB? P.S. Default headers don't works in this issue. This is auto-generated code: @SuppressWarnings("unchecked") // private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); ``` progressjournalPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("progressjournalPU").createEntityManager(); pupilsQuery = java.beans.Beans.isDesignTime() ? null : progressjournalPUEntityManager.createQuery("SELECT p FROM Pupils p"); pupilsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : pupilsQuery.getResultList(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Журнал успеваемости"); setResizable(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "ФИО", "Курс", "Предмет", "Оценка" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, pupilsList, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilMark}")); columnBinding.setColumnName("Pupil Mark"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilSubject}")); columnBinding.setColumnName("Pupil Subject"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilCourse}")); columnBinding.setColumnName("Pupil Course"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilName}")); columnBinding.setColumnName("Pupil Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilId}")); columnBinding.setColumnName("Pupil Id"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); bindingGroup.bind(); pack(); ``` }// And this code is locked for editing.
2012/04/26
[ "https://Stackoverflow.com/questions/10330598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568975/" ]
I used poi with version 3.12. The following dependency is also required: `compile 'org.apache.poi:ooxml-schemas:1.1'` see also <http://poi.apache.org/faq.html#faq-N10025>
I have made it run for these dependencies: ``` def poiVersion='3.9' compile 'org.apache.poi:poi:'+poiVersion compile 'org.apache.poi:poi-ooxml:'+poiVersion compile 'org.apache.poi:poi-ooxml-schemas:'+poiVersion ``` When I try for others it does not work: 3.10 : is not known to maven central 3.11 : fails, with exact the error in this case !!! Conclusion POI 3.9 works !!!!
10,330,598
I'm using Netbeans, SWING to get data from mysql table to jTable. I done it, but headers of table. Headers are the same like in mysql table. How to change headers of jTable after getting data from DB? P.S. Default headers don't works in this issue. This is auto-generated code: @SuppressWarnings("unchecked") // private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); ``` progressjournalPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("progressjournalPU").createEntityManager(); pupilsQuery = java.beans.Beans.isDesignTime() ? null : progressjournalPUEntityManager.createQuery("SELECT p FROM Pupils p"); pupilsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : pupilsQuery.getResultList(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Журнал успеваемости"); setResizable(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "ФИО", "Курс", "Предмет", "Оценка" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, pupilsList, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilMark}")); columnBinding.setColumnName("Pupil Mark"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilSubject}")); columnBinding.setColumnName("Pupil Subject"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilCourse}")); columnBinding.setColumnName("Pupil Course"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilName}")); columnBinding.setColumnName("Pupil Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilId}")); columnBinding.setColumnName("Pupil Id"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); bindingGroup.bind(); pack(); ``` }// And this code is locked for editing.
2012/04/26
[ "https://Stackoverflow.com/questions/10330598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568975/" ]
I have made it run for these dependencies: ``` def poiVersion='3.9' compile 'org.apache.poi:poi:'+poiVersion compile 'org.apache.poi:poi-ooxml:'+poiVersion compile 'org.apache.poi:poi-ooxml-schemas:'+poiVersion ``` When I try for others it does not work: 3.10 : is not known to maven central 3.11 : fails, with exact the error in this case !!! Conclusion POI 3.9 works !!!!
This is happening due to inconsistency is the poi jars. You can download latest jars and it will start working. you can add latest jar files for all below: Commons-compress , ooxml-schemas , poi-scratchpad , poi-ooxml , poi , poi-ooxml-schemas , dom4j , poi-excelant
10,330,598
I'm using Netbeans, SWING to get data from mysql table to jTable. I done it, but headers of table. Headers are the same like in mysql table. How to change headers of jTable after getting data from DB? P.S. Default headers don't works in this issue. This is auto-generated code: @SuppressWarnings("unchecked") // private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); ``` progressjournalPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("progressjournalPU").createEntityManager(); pupilsQuery = java.beans.Beans.isDesignTime() ? null : progressjournalPUEntityManager.createQuery("SELECT p FROM Pupils p"); pupilsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : pupilsQuery.getResultList(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Журнал успеваемости"); setResizable(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "ФИО", "Курс", "Предмет", "Оценка" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, pupilsList, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilMark}")); columnBinding.setColumnName("Pupil Mark"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilSubject}")); columnBinding.setColumnName("Pupil Subject"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilCourse}")); columnBinding.setColumnName("Pupil Course"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilName}")); columnBinding.setColumnName("Pupil Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilId}")); columnBinding.setColumnName("Pupil Id"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); bindingGroup.bind(); pack(); ``` }// And this code is locked for editing.
2012/04/26
[ "https://Stackoverflow.com/questions/10330598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568975/" ]
I used poi with version 3.12. The following dependency is also required: `compile 'org.apache.poi:ooxml-schemas:1.1'` see also <http://poi.apache.org/faq.html#faq-N10025>
I tried using `poi 3.10`, `3.11` and `3.12 beta` with Grails and get this error as well. After downloading and including <http://mirrors.ibiblio.org/pub/mirrors/maven2/org/apache/poi/ooxml-schemas/1.0/ooxml-schemas-1.0.jar> the error is gone.
10,330,598
I'm using Netbeans, SWING to get data from mysql table to jTable. I done it, but headers of table. Headers are the same like in mysql table. How to change headers of jTable after getting data from DB? P.S. Default headers don't works in this issue. This is auto-generated code: @SuppressWarnings("unchecked") // private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); ``` progressjournalPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("progressjournalPU").createEntityManager(); pupilsQuery = java.beans.Beans.isDesignTime() ? null : progressjournalPUEntityManager.createQuery("SELECT p FROM Pupils p"); pupilsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : pupilsQuery.getResultList(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Журнал успеваемости"); setResizable(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "ФИО", "Курс", "Предмет", "Оценка" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, pupilsList, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilMark}")); columnBinding.setColumnName("Pupil Mark"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilSubject}")); columnBinding.setColumnName("Pupil Subject"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilCourse}")); columnBinding.setColumnName("Pupil Course"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilName}")); columnBinding.setColumnName("Pupil Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilId}")); columnBinding.setColumnName("Pupil Id"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); bindingGroup.bind(); pack(); ``` }// And this code is locked for editing.
2012/04/26
[ "https://Stackoverflow.com/questions/10330598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568975/" ]
I tried using `poi 3.10`, `3.11` and `3.12 beta` with Grails and get this error as well. After downloading and including <http://mirrors.ibiblio.org/pub/mirrors/maven2/org/apache/poi/ooxml-schemas/1.0/ooxml-schemas-1.0.jar> the error is gone.
This is happening due to inconsistency is the poi jars. You can download latest jars and it will start working. you can add latest jar files for all below: Commons-compress , ooxml-schemas , poi-scratchpad , poi-ooxml , poi , poi-ooxml-schemas , dom4j , poi-excelant
10,330,598
I'm using Netbeans, SWING to get data from mysql table to jTable. I done it, but headers of table. Headers are the same like in mysql table. How to change headers of jTable after getting data from DB? P.S. Default headers don't works in this issue. This is auto-generated code: @SuppressWarnings("unchecked") // private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); ``` progressjournalPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("progressjournalPU").createEntityManager(); pupilsQuery = java.beans.Beans.isDesignTime() ? null : progressjournalPUEntityManager.createQuery("SELECT p FROM Pupils p"); pupilsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : pupilsQuery.getResultList(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Журнал успеваемости"); setResizable(false); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "#", "ФИО", "Курс", "Предмет", "Оценка" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, pupilsList, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilMark}")); columnBinding.setColumnName("Pupil Mark"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilSubject}")); columnBinding.setColumnName("Pupil Subject"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilCourse}")); columnBinding.setColumnName("Pupil Course"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilName}")); columnBinding.setColumnName("Pupil Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pupilId}")); columnBinding.setColumnName("Pupil Id"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind(); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(14, Short.MAX_VALUE)) ); bindingGroup.bind(); pack(); ``` }// And this code is locked for editing.
2012/04/26
[ "https://Stackoverflow.com/questions/10330598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568975/" ]
I used poi with version 3.12. The following dependency is also required: `compile 'org.apache.poi:ooxml-schemas:1.1'` see also <http://poi.apache.org/faq.html#faq-N10025>
This is happening due to inconsistency is the poi jars. You can download latest jars and it will start working. you can add latest jar files for all below: Commons-compress , ooxml-schemas , poi-scratchpad , poi-ooxml , poi , poi-ooxml-schemas , dom4j , poi-excelant
21,536,218
Alright, so I'm trying to compare two columns, in two tables, in separate databases. I am going to warn you, I quite new to SQL. I am trying to write a query to do something like this: ``` If a field in tableA column2 contains a field from tableB column1 at least once, increment a counter ``` I want to know the value of the counter. Also, when I same "contains" I mean in a `substr()` kind of way (fe. "marketplace" contains the word "market"). Can anyone help me out with this, or at least point me in the right direction?
2014/02/03
[ "https://Stackoverflow.com/questions/21536218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/989859/" ]
I think this is what you are after. it will obviously not loop, but it accomplishes what you are trying to do. ``` select a.c2, count(case when a.c2 = b.c1 then 1 else 0 end) as c1count from table1 as a left join table2 as b on a.key = b.key group by a.c2 ``` or something like that. that join will probably need some work, but it is hard to say without more information. good luck.
This will get you the number of times that the contents of tableB.col1 is found as part of the contents of tableA.col2: ``` SELECT COUNT(*) FROM tableA JOIN tableB ON tableA.col2 RLIKE tableB.col1 ``` In general, SQL engines are optimized to work better with set-based logic as opposed to procedural algorithms, such as looping.
50,644,513
I have a scenario where I need to identify a result. Below is a sample excel cells with three columns `Prod Name, Qty and Result`. ``` Prod Name Qty Result abc 10 zyz 9 test1 5 ``` If the product name is `abc or zyz` and its qty is 10, then I need to add text `Refill` in Column Result. For any other product. in this case `test1` and its qty is 5, then I need to add the same text `Refill` in Column Result. Else it will always be `Don't Refill`
2018/06/01
[ "https://Stackoverflow.com/questions/50644513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7468305/" ]
Try this formula: ``` =IF(OR(AND(OR(A1="abc", A1="xyz"), B1=10), AND(AND(A1<>"abc", A1<>"xyz"), B1=5)), "Refill", "Don't Refill") ```
The formula provided by Tim above should work nicely, but if you're looking for VBA approach: > > *(Presuming the data is in a table called Table1 in a sheet called > Sheet1)* > > > ``` Private Sub comb_products() Dim tbl As ListObject: Set tbl = Sheets("Sheet1").ListObjects("Table1") For Each Rng In tbl.ListColumns(1).DataBodyRange If ((Rng.Value2 = "abc" Or Rng.Value2 = "zyz") And Rng.Offset(0, 1).Value2 = 10) Then Rng.Offset(0, 2).Value2 = "Refill" ElseIf ((Rng.Value2 <> "abc" Or Rng.Value2 <> "zyz") And Rng.Offset(0, 1).Value2 = 5) Then Rng.Offset(0, 2).Value2 = "Refill" Else Rng.Offset(0, 2).Value2 = "Don't refill" End If Next Rng End Sub ``` Result as expected: [![enter image description here](https://i.stack.imgur.com/sfFtt.png)](https://i.stack.imgur.com/sfFtt.png)
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
Which serializer is that? If you only know the `Type` at runtime (not compile time), and it doesn't have a non-generic API, then you might have to use `MakeGenericMethod`: ``` void Foo(Type ty) { object result = typeof(ContainingClass).GetMethod("Bar"). .MakeGenericMethod(ty).Invoke(null, new object[] {inputContent}); } public static T Bar<T>(SomeType inputContent) { return serializer.Deserialize<T>(inputContent); } ```
Use ``` void Foo<T>(){ var result = serializer.Deserialize<T>(inputContent); } ``` With the following call ``` Foo<Person>(); ```
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
Use ``` void Foo<T>(){ var result = serializer.Deserialize<T>(inputContent); } ``` With the following call ``` Foo<Person>(); ```
In this case, just do this: ``` void Foo<ty>() { var result = serializer.Deserialize<ty>(inputContent); } Foo<Person>(); ``` Otherwise, you need to call the generic method late-bound, since you have to get the correct generic method for it first (it is not known at compile time). Have a look at the [MethodInfo.MakeGenericMethod](http://msdn.microsoft.com/de-de/library/system.reflection.methodinfo.makegenericmethod(VS.95).aspx) method.
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
If `ty` is known at compile-time, why don't just ``` void Foo<T>() { var result = serializer.Deserialize<T>(inputContext); } ``` Otherwise, ``` MethodInfo genericDeserializeMethod = serializer.GetType().GetMethod("Deserialize"); MethodInfo closedDeserializeMethod = genericDeserializeMethod.MakeGenericMethod(ty); closedDeserializeMethod.Invoke(serializer, new object[] { inputContext }); ```
Use ``` void Foo<T>(){ var result = serializer.Deserialize<T>(inputContent); } ``` With the following call ``` Foo<Person>(); ```
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
Use ``` void Foo<T>(){ var result = serializer.Deserialize<T>(inputContent); } ``` With the following call ``` Foo<Person>(); ```
Like Lucero said, ``` void Foo<ty>() { var result = serializer.Deserialize<ty>(inputContent); } Foo<Person>(); ``` typeof(Person) is not the same thing as Person. Person is a compile-time type, whereas typeof(Person) is an expression that *returns a Type instance representing the runtime type information of Person*.
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
Which serializer is that? If you only know the `Type` at runtime (not compile time), and it doesn't have a non-generic API, then you might have to use `MakeGenericMethod`: ``` void Foo(Type ty) { object result = typeof(ContainingClass).GetMethod("Bar"). .MakeGenericMethod(ty).Invoke(null, new object[] {inputContent}); } public static T Bar<T>(SomeType inputContent) { return serializer.Deserialize<T>(inputContent); } ```
In this case, just do this: ``` void Foo<ty>() { var result = serializer.Deserialize<ty>(inputContent); } Foo<Person>(); ``` Otherwise, you need to call the generic method late-bound, since you have to get the correct generic method for it first (it is not known at compile time). Have a look at the [MethodInfo.MakeGenericMethod](http://msdn.microsoft.com/de-de/library/system.reflection.methodinfo.makegenericmethod(VS.95).aspx) method.
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
If `ty` is known at compile-time, why don't just ``` void Foo<T>() { var result = serializer.Deserialize<T>(inputContext); } ``` Otherwise, ``` MethodInfo genericDeserializeMethod = serializer.GetType().GetMethod("Deserialize"); MethodInfo closedDeserializeMethod = genericDeserializeMethod.MakeGenericMethod(ty); closedDeserializeMethod.Invoke(serializer, new object[] { inputContext }); ```
Which serializer is that? If you only know the `Type` at runtime (not compile time), and it doesn't have a non-generic API, then you might have to use `MakeGenericMethod`: ``` void Foo(Type ty) { object result = typeof(ContainingClass).GetMethod("Bar"). .MakeGenericMethod(ty).Invoke(null, new object[] {inputContent}); } public static T Bar<T>(SomeType inputContent) { return serializer.Deserialize<T>(inputContent); } ```
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
Which serializer is that? If you only know the `Type` at runtime (not compile time), and it doesn't have a non-generic API, then you might have to use `MakeGenericMethod`: ``` void Foo(Type ty) { object result = typeof(ContainingClass).GetMethod("Bar"). .MakeGenericMethod(ty).Invoke(null, new object[] {inputContent}); } public static T Bar<T>(SomeType inputContent) { return serializer.Deserialize<T>(inputContent); } ```
Like Lucero said, ``` void Foo<ty>() { var result = serializer.Deserialize<ty>(inputContent); } Foo<Person>(); ``` typeof(Person) is not the same thing as Person. Person is a compile-time type, whereas typeof(Person) is an expression that *returns a Type instance representing the runtime type information of Person*.
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
If `ty` is known at compile-time, why don't just ``` void Foo<T>() { var result = serializer.Deserialize<T>(inputContext); } ``` Otherwise, ``` MethodInfo genericDeserializeMethod = serializer.GetType().GetMethod("Deserialize"); MethodInfo closedDeserializeMethod = genericDeserializeMethod.MakeGenericMethod(ty); closedDeserializeMethod.Invoke(serializer, new object[] { inputContext }); ```
In this case, just do this: ``` void Foo<ty>() { var result = serializer.Deserialize<ty>(inputContent); } Foo<Person>(); ``` Otherwise, you need to call the generic method late-bound, since you have to get the correct generic method for it first (it is not known at compile time). Have a look at the [MethodInfo.MakeGenericMethod](http://msdn.microsoft.com/de-de/library/system.reflection.methodinfo.makegenericmethod(VS.95).aspx) method.
856,665
I basically have something like this: ``` void Foo(Type ty) { var result = serializer.Deserialize<ty>(inputContent); } Foo(typeof(Person)); ``` The `Deserialize<ty>` doesn't work because it expects `Deserialize<Person>` instead. How do I work around this? I'd also like to understand how generics work and why it won't accept `ty` which is `typeof(Person)`. EDIT: I ought to have mentioned that this is a contrived example. I cannot actually change the signature of the function because it implements an interface. EDIT: serializer is a JavascriptSerializer and implemented as an action filter here. It is called thusly: ``` [JsonFilter(Param="test", JsonDataType=typeof(Person))] ``` Solution -------- Based on Marc and Anton's answers: ``` var result = typeof(JavaScriptSerializer).GetMethod("Deserialize") .MakeGenericMethod(JsonDataType) .Invoke(serializer, new object[] { inputContent }); ```
2009/05/13
[ "https://Stackoverflow.com/questions/856665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50475/" ]
If `ty` is known at compile-time, why don't just ``` void Foo<T>() { var result = serializer.Deserialize<T>(inputContext); } ``` Otherwise, ``` MethodInfo genericDeserializeMethod = serializer.GetType().GetMethod("Deserialize"); MethodInfo closedDeserializeMethod = genericDeserializeMethod.MakeGenericMethod(ty); closedDeserializeMethod.Invoke(serializer, new object[] { inputContext }); ```
Like Lucero said, ``` void Foo<ty>() { var result = serializer.Deserialize<ty>(inputContent); } Foo<Person>(); ``` typeof(Person) is not the same thing as Person. Person is a compile-time type, whereas typeof(Person) is an expression that *returns a Type instance representing the runtime type information of Person*.
53,452,226
In C++, if I try to do this: ``` std::function<void(bool,void)> ``` then the compiler will throw errors. Why is this? It's useful in many cases. One example: ``` //g++ -std=c++17 prblm.cpp #include <cstdio> #include <functional> template<class type_t> class some_callback { public: using callback_t = std::function<void(bool,type_t)>; some_callback(callback_t _myfunc) { this->myfunc = _myfunc; } callback_t myfunc; }; using callback_with_just_bool = some_callback<void>; using callback_with_an_int_too = some_callback<int>; int main() { auto my_callback_with_int = callback_with_an_int_too([](bool x, int y) { }); //OK auto my_callback_just_bool = callback_with_just_bool([](bool x) { }); //Error auto my_callback_just_bool = callback_with_just_bool([](bool x,void z) { }); //Error return 0; } ``` This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool` Why is it like this, and is there a clean way around it? Thanks. Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure.
2018/11/23
[ "https://Stackoverflow.com/questions/53452226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438811/" ]
*"Why is this?"* Because the only permitted usage of `void` in a parameter list is to show that the function doesn't accept any parameters. From [[function]](https://en.cppreference.com/w/cpp/language/function): > > `void` > > > Indicates that the function takes no parameters, it is the exact synonym for an empty parameter list: `int f(void);` and `int f();` declare the same function. Note that the type void (possibly cv-qualified) cannot be used in a parameter list otherwise: `int f(void, int);` and `int f(const void);` are errors (although derived types, such as `void*` can be used) > > > *"Is there a clean way around it?"* I would suggest to specialize for `void`: ``` template<class type_t> class some_callback { std::function<void(bool,type_t)> myfunc; }; template<> class some_callback<void> { std::function<void(bool)> myfunc; }; ```
The problem is not the code you showed, it is because in C/C++, you cannot define a function, f, as ``` void f(bool b, void v) {} ``` The reason is that, as @Peter Ruderman said, `void` is not a valid parameter type.
53,452,226
In C++, if I try to do this: ``` std::function<void(bool,void)> ``` then the compiler will throw errors. Why is this? It's useful in many cases. One example: ``` //g++ -std=c++17 prblm.cpp #include <cstdio> #include <functional> template<class type_t> class some_callback { public: using callback_t = std::function<void(bool,type_t)>; some_callback(callback_t _myfunc) { this->myfunc = _myfunc; } callback_t myfunc; }; using callback_with_just_bool = some_callback<void>; using callback_with_an_int_too = some_callback<int>; int main() { auto my_callback_with_int = callback_with_an_int_too([](bool x, int y) { }); //OK auto my_callback_just_bool = callback_with_just_bool([](bool x) { }); //Error auto my_callback_just_bool = callback_with_just_bool([](bool x,void z) { }); //Error return 0; } ``` This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool` Why is it like this, and is there a clean way around it? Thanks. Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure.
2018/11/23
[ "https://Stackoverflow.com/questions/53452226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438811/" ]
*"Why is this?"* Because the only permitted usage of `void` in a parameter list is to show that the function doesn't accept any parameters. From [[function]](https://en.cppreference.com/w/cpp/language/function): > > `void` > > > Indicates that the function takes no parameters, it is the exact synonym for an empty parameter list: `int f(void);` and `int f();` declare the same function. Note that the type void (possibly cv-qualified) cannot be used in a parameter list otherwise: `int f(void, int);` and `int f(const void);` are errors (although derived types, such as `void*` can be used) > > > *"Is there a clean way around it?"* I would suggest to specialize for `void`: ``` template<class type_t> class some_callback { std::function<void(bool,type_t)> myfunc; }; template<> class some_callback<void> { std::function<void(bool)> myfunc; }; ```
Variadic templates are one way to do this: ``` template <class... T> struct some_callback { std::function<void(bool, T...)> myfunc; }; using callback_with_just_bool = some_callback<>; using callback_with_an_int_too = some_callback<int>; ``` This is even cleaner with an alias template: ``` template <class... T> using callback_type = std::function<void(bool, T...)>; int main() { callback_type<int> my_callback_with_int = [](bool x, int y) { }; //OK callback_type<> my_callback_just_bool = [](bool x) { }; //OK now too... } ```
53,452,226
In C++, if I try to do this: ``` std::function<void(bool,void)> ``` then the compiler will throw errors. Why is this? It's useful in many cases. One example: ``` //g++ -std=c++17 prblm.cpp #include <cstdio> #include <functional> template<class type_t> class some_callback { public: using callback_t = std::function<void(bool,type_t)>; some_callback(callback_t _myfunc) { this->myfunc = _myfunc; } callback_t myfunc; }; using callback_with_just_bool = some_callback<void>; using callback_with_an_int_too = some_callback<int>; int main() { auto my_callback_with_int = callback_with_an_int_too([](bool x, int y) { }); //OK auto my_callback_just_bool = callback_with_just_bool([](bool x) { }); //Error auto my_callback_just_bool = callback_with_just_bool([](bool x,void z) { }); //Error return 0; } ``` This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool` Why is it like this, and is there a clean way around it? Thanks. Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure.
2018/11/23
[ "https://Stackoverflow.com/questions/53452226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438811/" ]
*"Why is this?"* Because the only permitted usage of `void` in a parameter list is to show that the function doesn't accept any parameters. From [[function]](https://en.cppreference.com/w/cpp/language/function): > > `void` > > > Indicates that the function takes no parameters, it is the exact synonym for an empty parameter list: `int f(void);` and `int f();` declare the same function. Note that the type void (possibly cv-qualified) cannot be used in a parameter list otherwise: `int f(void, int);` and `int f(const void);` are errors (although derived types, such as `void*` can be used) > > > *"Is there a clean way around it?"* I would suggest to specialize for `void`: ``` template<class type_t> class some_callback { std::function<void(bool,type_t)> myfunc; }; template<> class some_callback<void> { std::function<void(bool)> myfunc; }; ```
You might create specialization: ``` template<class type_t> class some_callback { std::function<void(bool,type_t)> myfunc; }; template<> class some_callback<void> { std::function<void(bool)> myfunc; }; ```
53,452,226
In C++, if I try to do this: ``` std::function<void(bool,void)> ``` then the compiler will throw errors. Why is this? It's useful in many cases. One example: ``` //g++ -std=c++17 prblm.cpp #include <cstdio> #include <functional> template<class type_t> class some_callback { public: using callback_t = std::function<void(bool,type_t)>; some_callback(callback_t _myfunc) { this->myfunc = _myfunc; } callback_t myfunc; }; using callback_with_just_bool = some_callback<void>; using callback_with_an_int_too = some_callback<int>; int main() { auto my_callback_with_int = callback_with_an_int_too([](bool x, int y) { }); //OK auto my_callback_just_bool = callback_with_just_bool([](bool x) { }); //Error auto my_callback_just_bool = callback_with_just_bool([](bool x,void z) { }); //Error return 0; } ``` This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool` Why is it like this, and is there a clean way around it? Thanks. Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure.
2018/11/23
[ "https://Stackoverflow.com/questions/53452226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438811/" ]
The problem is not the code you showed, it is because in C/C++, you cannot define a function, f, as ``` void f(bool b, void v) {} ``` The reason is that, as @Peter Ruderman said, `void` is not a valid parameter type.
Other answers have explained the why. This answers "is there a clean way around it?" What I usually do for callbacks is use lambdas. ``` std::function<void(void)> myfunc; bool b = false; int i = 42; myfunc = [&]() { if (b) ++i; }; ```
53,452,226
In C++, if I try to do this: ``` std::function<void(bool,void)> ``` then the compiler will throw errors. Why is this? It's useful in many cases. One example: ``` //g++ -std=c++17 prblm.cpp #include <cstdio> #include <functional> template<class type_t> class some_callback { public: using callback_t = std::function<void(bool,type_t)>; some_callback(callback_t _myfunc) { this->myfunc = _myfunc; } callback_t myfunc; }; using callback_with_just_bool = some_callback<void>; using callback_with_an_int_too = some_callback<int>; int main() { auto my_callback_with_int = callback_with_an_int_too([](bool x, int y) { }); //OK auto my_callback_just_bool = callback_with_just_bool([](bool x) { }); //Error auto my_callback_just_bool = callback_with_just_bool([](bool x,void z) { }); //Error return 0; } ``` This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool` Why is it like this, and is there a clean way around it? Thanks. Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure.
2018/11/23
[ "https://Stackoverflow.com/questions/53452226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438811/" ]
There is a proposal to add "regular void" to the language. In it, void becomes a monostate type that all other types implicitly convert to. You can emulate this with ``` struct monostate_t { template<class T> monostate_t(T&&) {} }; ``` then ``` using callback_with_just_bool = some_callback<monostate_t>; auto my_callback_just_bool = callback_with_just_bool([](bool x, auto&&...) { }); ``` works roughly as you like.
Other answers have explained the why. This answers "is there a clean way around it?" What I usually do for callbacks is use lambdas. ``` std::function<void(void)> myfunc; bool b = false; int i = 42; myfunc = [&]() { if (b) ++i; }; ```
53,452,226
In C++, if I try to do this: ``` std::function<void(bool,void)> ``` then the compiler will throw errors. Why is this? It's useful in many cases. One example: ``` //g++ -std=c++17 prblm.cpp #include <cstdio> #include <functional> template<class type_t> class some_callback { public: using callback_t = std::function<void(bool,type_t)>; some_callback(callback_t _myfunc) { this->myfunc = _myfunc; } callback_t myfunc; }; using callback_with_just_bool = some_callback<void>; using callback_with_an_int_too = some_callback<int>; int main() { auto my_callback_with_int = callback_with_an_int_too([](bool x, int y) { }); //OK auto my_callback_just_bool = callback_with_just_bool([](bool x) { }); //Error auto my_callback_just_bool = callback_with_just_bool([](bool x,void z) { }); //Error return 0; } ``` This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool` Why is it like this, and is there a clean way around it? Thanks. Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure.
2018/11/23
[ "https://Stackoverflow.com/questions/53452226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438811/" ]
You might create specialization: ``` template<class type_t> class some_callback { std::function<void(bool,type_t)> myfunc; }; template<> class some_callback<void> { std::function<void(bool)> myfunc; }; ```
The problem is not the code you showed, it is because in C/C++, you cannot define a function, f, as ``` void f(bool b, void v) {} ``` The reason is that, as @Peter Ruderman said, `void` is not a valid parameter type.
53,452,226
In C++, if I try to do this: ``` std::function<void(bool,void)> ``` then the compiler will throw errors. Why is this? It's useful in many cases. One example: ``` //g++ -std=c++17 prblm.cpp #include <cstdio> #include <functional> template<class type_t> class some_callback { public: using callback_t = std::function<void(bool,type_t)>; some_callback(callback_t _myfunc) { this->myfunc = _myfunc; } callback_t myfunc; }; using callback_with_just_bool = some_callback<void>; using callback_with_an_int_too = some_callback<int>; int main() { auto my_callback_with_int = callback_with_an_int_too([](bool x, int y) { }); //OK auto my_callback_just_bool = callback_with_just_bool([](bool x) { }); //Error auto my_callback_just_bool = callback_with_just_bool([](bool x,void z) { }); //Error return 0; } ``` This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool` Why is it like this, and is there a clean way around it? Thanks. Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure.
2018/11/23
[ "https://Stackoverflow.com/questions/53452226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438811/" ]
There is a proposal to add "regular void" to the language. In it, void becomes a monostate type that all other types implicitly convert to. You can emulate this with ``` struct monostate_t { template<class T> monostate_t(T&&) {} }; ``` then ``` using callback_with_just_bool = some_callback<monostate_t>; auto my_callback_just_bool = callback_with_just_bool([](bool x, auto&&...) { }); ``` works roughly as you like.
Variadic templates are one way to do this: ``` template <class... T> struct some_callback { std::function<void(bool, T...)> myfunc; }; using callback_with_just_bool = some_callback<>; using callback_with_an_int_too = some_callback<int>; ``` This is even cleaner with an alias template: ``` template <class... T> using callback_type = std::function<void(bool, T...)>; int main() { callback_type<int> my_callback_with_int = [](bool x, int y) { }; //OK callback_type<> my_callback_just_bool = [](bool x) { }; //OK now too... } ```
53,452,226
In C++, if I try to do this: ``` std::function<void(bool,void)> ``` then the compiler will throw errors. Why is this? It's useful in many cases. One example: ``` //g++ -std=c++17 prblm.cpp #include <cstdio> #include <functional> template<class type_t> class some_callback { public: using callback_t = std::function<void(bool,type_t)>; some_callback(callback_t _myfunc) { this->myfunc = _myfunc; } callback_t myfunc; }; using callback_with_just_bool = some_callback<void>; using callback_with_an_int_too = some_callback<int>; int main() { auto my_callback_with_int = callback_with_an_int_too([](bool x, int y) { }); //OK auto my_callback_just_bool = callback_with_just_bool([](bool x) { }); //Error auto my_callback_just_bool = callback_with_just_bool([](bool x,void z) { }); //Error return 0; } ``` This allows for a very clean syntax if the user would like to optionally have additional data in their callback, but not have to. However, the compiler will reject code that tries to initialize an object of `callback_with_just_bool` Why is it like this, and is there a clean way around it? Thanks. Edit: The specific reason I'm trying to do this, in real world code, is in an event system. There is data provided to the event system about an individual object that wishes to *conditionally* receive events (e.x. "if you're close enough to the source, you'll receive a sound event") as well as data provided to a callback *about* the event (e.x. "a 10khz noise at X200 Y200"). Most of the time, the data needed to check the requirements will exist inside the data provided to the callback *about* the event, but I wanted to provided an optional additional data structure if that was not the case. Hence, the user would specify "void" if they didn't need this additional data structure.
2018/11/23
[ "https://Stackoverflow.com/questions/53452226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10438811/" ]
There is a proposal to add "regular void" to the language. In it, void becomes a monostate type that all other types implicitly convert to. You can emulate this with ``` struct monostate_t { template<class T> monostate_t(T&&) {} }; ``` then ``` using callback_with_just_bool = some_callback<monostate_t>; auto my_callback_just_bool = callback_with_just_bool([](bool x, auto&&...) { }); ``` works roughly as you like.
The problem is not the code you showed, it is because in C/C++, you cannot define a function, f, as ``` void f(bool b, void v) {} ``` The reason is that, as @Peter Ruderman said, `void` is not a valid parameter type.