qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
25,932,257 | I would like to show a different **div** depending on what class my 3 **span** elems contain.
If all **span** hasClass *up* or *up1* the code would show a **div** with class *allUp* . If it hasClass *up* *up1* and *down* then it would show a **div** with class *twoUp*.
I wrote the following, but of course it doesn't work.
```
var $line1 = $(".line1")
var $line2 = $(".line2")
var $line3 = $(".line3")
if($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("up") || $line3.hasClass("up1")) {
$(".allUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".twoUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("down") || $line2.hasClass("down1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".oneUp").show();
}
else {
$(".down").show();
}
```
***think I've fixed the syntax errors*** | 2014/09/19 | [
"https://Stackoverflow.com/questions/25932257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3246460/"
] | Through my substantial searches on Mockito I found there are two types of mocking:
1. Proxy Mocking (Usual stubbing)
2. Class remapping(Only Jmockit supports)
You can read about "How Mock Objects Work" [here](http://java.dzone.com/articles/the-concept-mocking).
For my question, Class Remapping was the solution
Another solution is through the use of `InjectMocks` and `ReflectionTestUtils`
```
/* We can place this code in the JUnit test Class */
@Mock
PersonDAO personDAO;
@InjectMocks
PersonService personService;
@Before
public void setUP() {
MockitoAnnotations.init(this);
}
@Test
public void shouldUpdatePersonName(){
ReflectionTestutils.setField(personService,"personDao",personDAO);
............Remaining Code..........
}
```
What `ReflectionTestUtils` does is it will replace the `personDao`(created using "new" operator) present in the `personService` object with the locally created(using `@Mock`) mock `personDAO`.
```
ReflectionTestutils.setField(target,"name",actual);
```
There is a wealth of information beyond what I can give here about `ReflectionTestUtils` on the net. | I think your tests are telling you that database records are hard to implement as unmodifiable objects.
How about adding
```
Person updateName(String name);
```
to Person class? |
25,932,257 | I would like to show a different **div** depending on what class my 3 **span** elems contain.
If all **span** hasClass *up* or *up1* the code would show a **div** with class *allUp* . If it hasClass *up* *up1* and *down* then it would show a **div** with class *twoUp*.
I wrote the following, but of course it doesn't work.
```
var $line1 = $(".line1")
var $line2 = $(".line2")
var $line3 = $(".line3")
if($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("up") || $line3.hasClass("up1")) {
$(".allUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".twoUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("down") || $line2.hasClass("down1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".oneUp").show();
}
else {
$(".down").show();
}
```
***think I've fixed the syntax errors*** | 2014/09/19 | [
"https://Stackoverflow.com/questions/25932257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3246460/"
] | Just for the record, here is what the test class looks like with JMockit 1.12:
```
public class PersonServiceTest
{
@Tested PersonService personService;
@Mocked PersonDao personDAO;
@Test
public void shouldUpdatePersonName()
{
final Person person = new Person(1, "Phillip");
new NonStrictExpectations() {{
personDAO.fetchPerson(1); result = person; times = 1;
}};
boolean updated = personService.update(1, "David");
assertTrue(updated);
new FullVerifications() {{
Person updatedPerson;
personDAO.update(updatedPerson = withCapture());
assertEquals("David", updatedPerson.getPersonName());
}};
}
@Test
public void shouldNotUpdateIfPersonNotFound()
{
new Expectations() {{ personDAO.fetchPerson(1); result = null; }};
boolean updated = personService.update(1, "David");
assertFalse(updated);
}
}
``` | I think your tests are telling you that database records are hard to implement as unmodifiable objects.
How about adding
```
Person updateName(String name);
```
to Person class? |
25,932,257 | I would like to show a different **div** depending on what class my 3 **span** elems contain.
If all **span** hasClass *up* or *up1* the code would show a **div** with class *allUp* . If it hasClass *up* *up1* and *down* then it would show a **div** with class *twoUp*.
I wrote the following, but of course it doesn't work.
```
var $line1 = $(".line1")
var $line2 = $(".line2")
var $line3 = $(".line3")
if($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("up") || $line3.hasClass("up1")) {
$(".allUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("up") || $line2.hasClass("up1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".twoUp").show();
}
else if ($line1.hasClass("up") || $line1.hasClass("up1")
&& $line2.hasClass("down") || $line2.hasClass("down1")
&& $line3.hasClass("down") || $line3.hasClass("down1")) {
$(".oneUp").show();
}
else {
$(".down").show();
}
```
***think I've fixed the syntax errors*** | 2014/09/19 | [
"https://Stackoverflow.com/questions/25932257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3246460/"
] | Through my substantial searches on Mockito I found there are two types of mocking:
1. Proxy Mocking (Usual stubbing)
2. Class remapping(Only Jmockit supports)
You can read about "How Mock Objects Work" [here](http://java.dzone.com/articles/the-concept-mocking).
For my question, Class Remapping was the solution
Another solution is through the use of `InjectMocks` and `ReflectionTestUtils`
```
/* We can place this code in the JUnit test Class */
@Mock
PersonDAO personDAO;
@InjectMocks
PersonService personService;
@Before
public void setUP() {
MockitoAnnotations.init(this);
}
@Test
public void shouldUpdatePersonName(){
ReflectionTestutils.setField(personService,"personDao",personDAO);
............Remaining Code..........
}
```
What `ReflectionTestUtils` does is it will replace the `personDao`(created using "new" operator) present in the `personService` object with the locally created(using `@Mock`) mock `personDAO`.
```
ReflectionTestutils.setField(target,"name",actual);
```
There is a wealth of information beyond what I can give here about `ReflectionTestUtils` on the net. | Just for the record, here is what the test class looks like with JMockit 1.12:
```
public class PersonServiceTest
{
@Tested PersonService personService;
@Mocked PersonDao personDAO;
@Test
public void shouldUpdatePersonName()
{
final Person person = new Person(1, "Phillip");
new NonStrictExpectations() {{
personDAO.fetchPerson(1); result = person; times = 1;
}};
boolean updated = personService.update(1, "David");
assertTrue(updated);
new FullVerifications() {{
Person updatedPerson;
personDAO.update(updatedPerson = withCapture());
assertEquals("David", updatedPerson.getPersonName());
}};
}
@Test
public void shouldNotUpdateIfPersonNotFound()
{
new Expectations() {{ personDAO.fetchPerson(1); result = null; }};
boolean updated = personService.update(1, "David");
assertFalse(updated);
}
}
``` |
62,271 | During the Punk Hazard arc, Trafalgar Law swaps Sanji into Nami's body and Smoker into Tashigi's. In spite of them being in bodies not addicted to nicotine, it seems they both still need to smoke. Nami (in Franky's body) even offers Sanji a pack of cigarettes saying something to the effect, "You need them, right?"
When Trafalgar Law swaps everyone, the image shown is some weird heart thing, not swapping their brains. I assume this is some kind of representation of a soul, but if they still need nicotine, maybe I'm wrong. So, what exactly does Law swap? And why do Sanji and Smoker still need to smoke? | 2021/03/23 | [
"https://anime.stackexchange.com/questions/62271",
"https://anime.stackexchange.com",
"https://anime.stackexchange.com/users/19307/"
] | If you ask any smoker, he will tell you that most of the addiction comes from the brain as it gives the neuro-signals for pleasure when smoking. Most smokers can't quit not because the body demands nicotine, but because of the apparent relaxating effect that is produced by smoking and the habbit that results from it.
Smoking is a recreational drug in public view and tends to work as such.
Edit: And now on how Law's power work. The swap technique that Law uses looks like he is swaping the "hearts" of people, but because they retain their original thoughts, memories and even habbits (like smoking) makes me believe that it's actually their consciousness that is being transfered since all these reside in the brain and not the heart.
Hope this answers your question. | Simple Answer: Law's DF is wired (even kadio annoyed by that), and even a mystery to that point.
It was stated, one of the most usable, power devil fruit in the world.
So, How law can change someone's mind(brain) to another person by swiping their hearts! It ven does seems, it's only the conscious state. And sub part reamins in the brain of that body. (ref: Franky in Chopper's body)
A Heart never can have a mind!
This is a unanswered mystery yet. We've to wait until the real information. Until, you can check some fan theories, analysis on that. Maybe will help to understand better. |
62,271 | During the Punk Hazard arc, Trafalgar Law swaps Sanji into Nami's body and Smoker into Tashigi's. In spite of them being in bodies not addicted to nicotine, it seems they both still need to smoke. Nami (in Franky's body) even offers Sanji a pack of cigarettes saying something to the effect, "You need them, right?"
When Trafalgar Law swaps everyone, the image shown is some weird heart thing, not swapping their brains. I assume this is some kind of representation of a soul, but if they still need nicotine, maybe I'm wrong. So, what exactly does Law swap? And why do Sanji and Smoker still need to smoke? | 2021/03/23 | [
"https://anime.stackexchange.com/questions/62271",
"https://anime.stackexchange.com",
"https://anime.stackexchange.com/users/19307/"
] | If you ask any smoker, he will tell you that most of the addiction comes from the brain as it gives the neuro-signals for pleasure when smoking. Most smokers can't quit not because the body demands nicotine, but because of the apparent relaxating effect that is produced by smoking and the habbit that results from it.
Smoking is a recreational drug in public view and tends to work as such.
Edit: And now on how Law's power work. The swap technique that Law uses looks like he is swaping the "hearts" of people, but because they retain their original thoughts, memories and even habbits (like smoking) makes me believe that it's actually their consciousness that is being transfered since all these reside in the brain and not the heart.
Hope this answers your question. | I don't think this question can be fully answered, so I'll just list out some possibilities, as well as some evidence for and against.
**First Possibility**: Law actually swapped not only their brains, but a lot of their internals as well. Sanji in Nami's body claims to be the best swimmer on the crew and thus he has to be the one to rescue the samurai's torso from the sea. But why does Sanji still have his abilities while in Nami's body? It might make sense if Law swapped the internals of the bodies, including muscles.
Where this theory seems to fail: Franky and Chopper's bodies seem to work as normal. Also, when Sanji and Nami swap back, Sanji feels the pain his body went through under Nami after she punches him, saying "My body hurts from a whole lot more than one punch." If the injuries were only skin deep, he likely wouldn't collapse from the pain here.
**Second Possibility**: Law actually did swap their souls. And somehow, in the world of *One Piece*, skills and memory are stored in the soul, thus why Sanji still has fighting potential while in Nami's body. And maybe the soul really is stored in the physical heart (Who's to say in a fictional world? Whether it was the actual heart is not important, however, and as previously stated, the physical representation of the swap did not look like a real heart.). And what else is stored in the soul? The urge to smoke, apparently.
Where this theory is weak: If the characters still have access to the actual brain of the body they're in, and thus the memories and knowledge, this would be odd, as they don't appear to have much idea of how to use their abilities. Nami in Franky's body seems particularly inept.
**Third Possibility**: Law swapped their brains. It is very plausible that the urge to smoke would carry over, then, along with all their memories. Though as to why Sanji retains some physical prowess, there would seem to be no good answer.
The second and third possibilities likely are more credible, as Sanji does struggle a bit in Nami's body, saying at times he can't keep up,etc. But at the same time, he's clearly got too much physical prowess while in Nami's body, so something is definitely off. It could possibly be a combination of the second and third as well. |
29,794,536 | Hi i m using datepicker to get the date. I had done the jquery datepicker but **its returns undefined value**. please help me.
HTML CODE
```
<input type="text" class="form-control fromdate" id="datepicker" name="from_date" placeholder="From date" value="<?php echo set_value('from_date'); ?>" >
```
script
```
var fromdate = $('.fromdate').datepicker('getDate');
alert(fromdate);
``` | 2015/04/22 | [
"https://Stackoverflow.com/questions/29794536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4809070/"
] | When you are using a jQuery UI widget, you first have to instantiate the widget before calling any functions on it:
```
$(function() {
//Instanciate the widget
$( ".fromdate" ).datepicker();
//Access to widget's functions
alert($( ".fromdate" ).datepicker('getDate'))
});
```
[jsFiddle](http://jsfiddle.net/mq8hmxdj/)
Note: `$(function(){ YOUR CODE HERE });` is just a shortcut for `$(document).ready(function(){ YOUR CODE HERE });` | Without your full page/code this is guesswork, but using `datepicker` is pretty simple. You need to "turn it on first", then use it:
```
$('.fromdate').datepicker({
onSelect: function (dateText) {
var fromdate = $('.fromdate').datepicker('getDate');
alert(fromdate);
}
});
```
**JSFiddle:** <http://jsfiddle.net/TrueBlueAussie/zr9ewogp/1/>
You example seemed odd as the `onSelect` event passes the date value, so fetching it is not actually needed:
e.g.
```
$('.fromdate').datepicker({
onSelect: function (dateText) {
alert(dateText);
}
});
``` |
29,794,536 | Hi i m using datepicker to get the date. I had done the jquery datepicker but **its returns undefined value**. please help me.
HTML CODE
```
<input type="text" class="form-control fromdate" id="datepicker" name="from_date" placeholder="From date" value="<?php echo set_value('from_date'); ?>" >
```
script
```
var fromdate = $('.fromdate').datepicker('getDate');
alert(fromdate);
``` | 2015/04/22 | [
"https://Stackoverflow.com/questions/29794536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4809070/"
] | When you are using datepicker we need to initalize it first
```
<input type="text" class="form-control fromdate" id="datepicker" name="from_date" value="2015-4-10" />
<script>
$(document).ready(function(){
$('.fromdate').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
alert(day + '-' + month + '-' + year);
}
});
var fromdate = $('.fromdate').datepicker('getDate');
alert(fromdate);
});
</script>
``` | When you are using a jQuery UI widget, you first have to instantiate the widget before calling any functions on it:
```
$(function() {
//Instanciate the widget
$( ".fromdate" ).datepicker();
//Access to widget's functions
alert($( ".fromdate" ).datepicker('getDate'))
});
```
[jsFiddle](http://jsfiddle.net/mq8hmxdj/)
Note: `$(function(){ YOUR CODE HERE });` is just a shortcut for `$(document).ready(function(){ YOUR CODE HERE });` |
29,794,536 | Hi i m using datepicker to get the date. I had done the jquery datepicker but **its returns undefined value**. please help me.
HTML CODE
```
<input type="text" class="form-control fromdate" id="datepicker" name="from_date" placeholder="From date" value="<?php echo set_value('from_date'); ?>" >
```
script
```
var fromdate = $('.fromdate').datepicker('getDate');
alert(fromdate);
``` | 2015/04/22 | [
"https://Stackoverflow.com/questions/29794536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4809070/"
] | When you are using datepicker we need to initalize it first
```
<input type="text" class="form-control fromdate" id="datepicker" name="from_date" value="2015-4-10" />
<script>
$(document).ready(function(){
$('.fromdate').datepicker({
dateFormat: 'yy-m-d',
inline: true,
onSelect: function(dateText, inst) {
var date = $(this).datepicker('getDate'),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear();
alert(day + '-' + month + '-' + year);
}
});
var fromdate = $('.fromdate').datepicker('getDate');
alert(fromdate);
});
</script>
``` | Without your full page/code this is guesswork, but using `datepicker` is pretty simple. You need to "turn it on first", then use it:
```
$('.fromdate').datepicker({
onSelect: function (dateText) {
var fromdate = $('.fromdate').datepicker('getDate');
alert(fromdate);
}
});
```
**JSFiddle:** <http://jsfiddle.net/TrueBlueAussie/zr9ewogp/1/>
You example seemed odd as the `onSelect` event passes the date value, so fetching it is not actually needed:
e.g.
```
$('.fromdate').datepicker({
onSelect: function (dateText) {
alert(dateText);
}
});
``` |
1,069,433 | Below is the sample code.
```
- (void) keyDown: (NSEvent *) event
{
NSString *chars = [event characters];
unichar character = [chars characterAtIndex: 0];
if (character == 27) {
NSLog (@"ESCAPE!");
}
}
```
Should I need to set any delegate in InterfaceBuilder or any kinda binding??
Help Appreciated... | 2009/07/01 | [
"https://Stackoverflow.com/questions/1069433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | `keyDown` needs to be overridden in an `NSView` subclass whose object is set as first responder. The responder chain *should* pass down the event, but to be sure you get it, make sure that your object is first responder. | In cocoa only views participate in responder chain for this event. So you should override a some view method. The easy way is to find out what view is first responder for particular event you want to handle and use it.
window sends `keyDown(with: )` stright to first responder which could handle it or pass up to responder chain. Not all views pass the events up. NSCollectionView doesn't pass the key event. It plays a bump sound instead.
It is also possible that a key you want to handle is a **Key equivalent** [read more here](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW10). If so you should override performKeyEquivalent(with: ) method to receive this type of events instead. This events unlike keyDown events passed down from the window to the all subviews until someone handle them.
As mentioned NSCollectionView keyDown(with: ) method do not pass the key events up the responder chain. To handle such events in one of it's super views you should override it in collection view first and send event manually by calling self.nextResponder?.keyDown(with: event) for such events that you want to handle by yourself. |
18,710,548 | I run node with
```
node --debug app
OR
node --debug-brk app
```
it responds
```
debugger listening on port 5858
Express server listening on port 1338
```
I now start node-inspector
```
node-inspector --web-port=5859
```
It responds with
```
Node Inspector v0.3.2
info - socket.io started
Visit http://127.0.0.1:5859/debug?port=5858 to start debugging.
```
Open chrome and go to
```
http://127.0.0.1:5859/debug?port=5858
```
Console logs the following

Using TCPview, it shows node is listening to port 5858 but it has no established connection.
When the connection is attempted this message appears on the node console
```
}Content-Length: 108
```
Nothing else.
I then tried to get the debugger to run on a different port:
```
node --debug=5000 app
node-inspector --debug-port=5000 --web-port=5859
```
but node-inspector would not connect
EDIT:
Well the error is not with node. I installed the Eclipse node environment and was able to debug. Decided to give node-inspector the benefit of the doubt and reinstall.
```
npm uninstall node-inspector
npm WARN uninstall not installed in C:\Program Files\nodejs\node_modules: "node-inspector"
```
re-installed node
re-installed chrome
No luck same problem.
So Eclipse it is. | 2013/09/10 | [
"https://Stackoverflow.com/questions/18710548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/529273/"
] | With your first attempt, you're telling node-inspector to try to connect to the debugger on 5859 (not default), then telling node debugger to listen on the default 5858.
Start node: `node --debug-brk app.js` and it will run the debugger on 5858.
Start node-inspector: `node-inspector` and it will try to connect to 5858.
Open your browser to the provided url to access the web interface and the browser should load up the sources panel and execution should be halted on the very first line of your app.
In your second attempt, your approach looks okay, and having used node-inspector for a year (presently struggling with 0.12.3), I'd say it was likely node-inspector causing the issue there. | This are some steps may help you.
* Try to visit `chrome`.
* Open New Tab
* Type `chrome://inspect`
* This will open a Window, where you find the `Remote Target #LOCALHOST`
* You will find your node file name below `target` header.
* Click the link, This will open a debugger window for you.
That's It. Happy debugging. :) |
4,087,996 | Assume that I have a project that contains two buttons on it. Each buttons generate a custom form. I wrote both forms manually. But I wonder, is there a way that I can make these forms by using toolbox in different projects and combine them in one solution. I mean, when I press a button I want to call another project.
And finally if such a solution exists, is it proper way to make programs like this , or is it better to create forms manually ? | 2010/11/03 | [
"https://Stackoverflow.com/questions/4087996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/235174/"
] | You can call a form from another project (if we are talking about VS project) if it is public. You need to add reference to the project where this form is "placed" to the project where the call is made.
Of course, you can create forms manually, but you can as well create new windows form and add controls to it via designer.
And about the proper way. If you need the same form to be called from different projects, then, yes, keeping in in some third project is alright. | Yes you can invoke the forms even if they are in different projects. But you need to have references to that projects and to have defined a proper using statements. |
4,383,958 | I am having trouble with a part of my assignment. I need to show that
$||x - P\_Ex||^2$ = $||x||^2 - \sum\_{j=1}^n |\langle e\_j,x \rangle|^2$
where $e\_j$ is in a hilbert space and an orthonormal set, and $P\_Ex$ is the orthogonal projection of x onto E and is defined as
$P\_Ex = \sum\_{i=1}^n \langle e\_i,x \rangle e\_i$,
and
$ \langle e\_j,e\_i \rangle = 1$ if $i=j$ and $0$ if $i\neq j$
So far I have started by expanding the lefthand side and got this.
$||x - P\_Ex||^2$ = $ \langle x, x\rangle - \langle x,P\_Ex \rangle - \langle P\_Ex,x \rangle + \langle P\_Ex,P\_Ex \rangle$
Since $P\_Ex$ is orthogonal to x (I believe), the above line reduces to
$||x - P\_Ex||^2$ = $ \langle x, x\rangle + \langle P\_Ex,P\_Ex \rangle$
From here I would like to expand the last part
$\langle P\_Ex,P\_Ex \rangle = \left\langle \sum\_{i=1}^n \langle e\_i,x \rangle e\_i, \quad \sum\_{j=1}^n \langle e\_j,x \rangle e\_j \right\rangle$
I feel like this would result in a vector of vectors but I don't really understand how it would work exactly. | 2022/02/16 | [
"https://math.stackexchange.com/questions/4383958",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1026361/"
] | Use uniqueness. Let $z(x) := -y(-x)$. Then
$$ z'(x) = y'(-x) = x^2 + y(-x)^2 + 1 = x^2 + z^2(x) + 1 $$
as $z(0) = 0$, by uniqueness, $z = y$ and $y$ is odd. | (C) is also correct. By implicit differentiation, $\frac12(y^2)' = yy' = y(x^2+y^2+1)$. So $\frac12(y^2)'' = y'(x^2+y^2+1) + y(2x+2yy')$. From this we deduce that $(y^2)' = 0$ at $x=0$ and $(y^2)'' = 1$ at $x=0$, and so $y^2$ has a local minimum at $0$. |
25,422,407 | I had a problem when parse my json data with php in select html element
This my [JSON DATA](http://en.textsave.org/WjQ)
This my [PHP CODE](http://txs.io/Yfqb)
Error message :
```
Notice: Trying to get property of non-object in C:\xampp\htdocs\test\index.php on line 6
```
This line 6 :
```
$provider = $jfo->product->provider;
```
I try to parse "provider" to select html element after someone choose "Jenis Produk". | 2014/08/21 | [
"https://Stackoverflow.com/questions/25422407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2746365/"
] | product is not an object, it is an array:
```
$jfo->product['provider'];
``` | It appears that `product` is not an object.
Have you tried dumping $jfo->product?
My guess is that it is an array. |
25,422,407 | I had a problem when parse my json data with php in select html element
This my [JSON DATA](http://en.textsave.org/WjQ)
This my [PHP CODE](http://txs.io/Yfqb)
Error message :
```
Notice: Trying to get property of non-object in C:\xampp\htdocs\test\index.php on line 6
```
This line 6 :
```
$provider = $jfo->product->provider;
```
I try to parse "provider" to select html element after someone choose "Jenis Produk". | 2014/08/21 | [
"https://Stackoverflow.com/questions/25422407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2746365/"
] | product is an array, containing multiple products.
```
$jfo->product[0]->provider;
```
You'll need to loop through the products.
```
for ($i = 0; $i < sizeof($jfo->product); $i++) {
$provider = $jfo->product[$i]->provider;
}
``` | It appears that `product` is not an object.
Have you tried dumping $jfo->product?
My guess is that it is an array. |
1,544,160 | I have written an authentication class controller containing a method to check login status of user, and redirect him to login page if he/she is not logged in.
I need to call this function from other controller methods to authenticate the user. What is a good way to do that? | 2009/10/09 | [
"https://Stackoverflow.com/questions/1544160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6561/"
] | Take that method out of that controller.
Assuming you have a User model, that is a great place to put it if it is authenticating a user and logging them in.
Other places that you may put repeatable code is in helpers (static functions) and libraries (classes). | Take the function to a Model or code it in a library.
Helpers I won't recommend as you are not advised to access the database from Helpers.
Easy way out is put it in a model say user\_model and call it by any controller anywhere. |
1,544,160 | I have written an authentication class controller containing a method to check login status of user, and redirect him to login page if he/she is not logged in.
I need to call this function from other controller methods to authenticate the user. What is a good way to do that? | 2009/10/09 | [
"https://Stackoverflow.com/questions/1544160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6561/"
] | Take that method out of that controller.
Assuming you have a User model, that is a great place to put it if it is authenticating a user and logging them in.
Other places that you may put repeatable code is in helpers (static functions) and libraries (classes). | I put a check login method in base controller, which is extended by all controllers. Now if a controller's action requires users to be logged in, I call it there like `parent::_check_login()`, if the whole controller requires it I call it from the constructor of that controller, that's all. |
1,544,160 | I have written an authentication class controller containing a method to check login status of user, and redirect him to login page if he/she is not logged in.
I need to call this function from other controller methods to authenticate the user. What is a good way to do that? | 2009/10/09 | [
"https://Stackoverflow.com/questions/1544160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6561/"
] | Take that method out of that controller.
Assuming you have a User model, that is a great place to put it if it is authenticating a user and logging them in.
Other places that you may put repeatable code is in helpers (static functions) and libraries (classes). | sumanchalki is correct but he might not be giving quite enough information on how to do it.
[CodeIgniter Base Classes: Keeping it DRY](http://philsturgeon.co.uk/news/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY)
This will show you how to make named base controllers such as a Admin Controller which could contain your user authentication logic and much more. |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | Consider using comprehension
```py
usernames: dict = {idx: "" for idx in range(1001)}
``` | Try this.
```
usernames = {}
for i in range(0, 100):
usernames[i] = ""
``` |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | Consider using comprehension
```py
usernames: dict = {idx: "" for idx in range(1001)}
``` | Assuming your use-case:
>
> want to use this dict as a "database" to store hardcoded data
>
>
>
### The database approach
Most databases don't reserve space upfront and create something like dummy-records. Nor do they create and reserve keys in advance.
What a typical database and the setup for a collection or table of users would do:
1. create the schema or table `user` with columns or fields `id` for the key or sequential number, `name` more for the attributes.
2. create the sequence or auto-numbering to generate a new `id` value for each newly added or inserted record
### The data structure approach in Python
Analogously you would create either a dict with some functions to manage:
```py
user_store = {} # empty dict, no schema, no elements yet
current_id = None # the sequence to increment for each new record added
def nextId():
if not current_id:
current_id = 0 # the initial first value of the sequence
else:
current_id += 1 # increment each time
return current_id
def add_user(name):
id = nextId() # generate unique id from sequence
user_store[id] = name # add new key with value
return id # return the generated id to reference the user record later
def remove_user_by_id(id):
del user_store[id] # frees space
def update_user(id, new_name):
user_store[id] = new_name # update the name
def count():
# there may be records and ids deleted, so the count is not related to current_id
return len(user_store)
```
See also:
* RealPython: [Dictionaries in Python](https://realpython.com/python-dicts)
If the (primary) *key* or id is a sequential number starting with 0 you can also use a list instead a dict. |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | This looks like the kind of thing you should do programmatically rather than manually editing a file. For sequential numeric keys, consider using a list instead of a dict.
If you really need a dict, then use a dict comprehension as Demitri shows or `defaultdict` which allows you to provide a default value for any key that isn't explicitly set in the dict.
If you have some data other than just empty strings, then consider reading the data from an external file rather than putting it in code. Generally, data should be stored separately from code anyway. | Try this.
```
usernames = {}
for i in range(0, 100):
usernames[i] = ""
``` |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | Start by creating a dictionary:
```
dictionary = {}
```
Now you can use a for loop to create the keys:
```
for num in range(1001):
dictionary[num] = ""
``` | Try this.
```
usernames = {}
for i in range(0, 100):
usernames[i] = ""
``` |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | Use the classmethod factory [`fromkeys`](https://docs.python.org/3/library/stdtypes.html#dict.fromkeys):
```
dict.fromkeys(range(1001), "")
```
And perhaps consider using a list. This is more memory efficient than using a dict with consecutive integer keys.
```
[""] * 1001
``` | Try this.
```
usernames = {}
for i in range(0, 100):
usernames[i] = ""
``` |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | Assuming your use-case:
>
> want to use this dict as a "database" to store hardcoded data
>
>
>
### The database approach
Most databases don't reserve space upfront and create something like dummy-records. Nor do they create and reserve keys in advance.
What a typical database and the setup for a collection or table of users would do:
1. create the schema or table `user` with columns or fields `id` for the key or sequential number, `name` more for the attributes.
2. create the sequence or auto-numbering to generate a new `id` value for each newly added or inserted record
### The data structure approach in Python
Analogously you would create either a dict with some functions to manage:
```py
user_store = {} # empty dict, no schema, no elements yet
current_id = None # the sequence to increment for each new record added
def nextId():
if not current_id:
current_id = 0 # the initial first value of the sequence
else:
current_id += 1 # increment each time
return current_id
def add_user(name):
id = nextId() # generate unique id from sequence
user_store[id] = name # add new key with value
return id # return the generated id to reference the user record later
def remove_user_by_id(id):
del user_store[id] # frees space
def update_user(id, new_name):
user_store[id] = new_name # update the name
def count():
# there may be records and ids deleted, so the count is not related to current_id
return len(user_store)
```
See also:
* RealPython: [Dictionaries in Python](https://realpython.com/python-dicts)
If the (primary) *key* or id is a sequential number starting with 0 you can also use a list instead a dict. | Try this.
```
usernames = {}
for i in range(0, 100):
usernames[i] = ""
``` |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | This looks like the kind of thing you should do programmatically rather than manually editing a file. For sequential numeric keys, consider using a list instead of a dict.
If you really need a dict, then use a dict comprehension as Demitri shows or `defaultdict` which allows you to provide a default value for any key that isn't explicitly set in the dict.
If you have some data other than just empty strings, then consider reading the data from an external file rather than putting it in code. Generally, data should be stored separately from code anyway. | Assuming your use-case:
>
> want to use this dict as a "database" to store hardcoded data
>
>
>
### The database approach
Most databases don't reserve space upfront and create something like dummy-records. Nor do they create and reserve keys in advance.
What a typical database and the setup for a collection or table of users would do:
1. create the schema or table `user` with columns or fields `id` for the key or sequential number, `name` more for the attributes.
2. create the sequence or auto-numbering to generate a new `id` value for each newly added or inserted record
### The data structure approach in Python
Analogously you would create either a dict with some functions to manage:
```py
user_store = {} # empty dict, no schema, no elements yet
current_id = None # the sequence to increment for each new record added
def nextId():
if not current_id:
current_id = 0 # the initial first value of the sequence
else:
current_id += 1 # increment each time
return current_id
def add_user(name):
id = nextId() # generate unique id from sequence
user_store[id] = name # add new key with value
return id # return the generated id to reference the user record later
def remove_user_by_id(id):
del user_store[id] # frees space
def update_user(id, new_name):
user_store[id] = new_name # update the name
def count():
# there may be records and ids deleted, so the count is not related to current_id
return len(user_store)
```
See also:
* RealPython: [Dictionaries in Python](https://realpython.com/python-dicts)
If the (primary) *key* or id is a sequential number starting with 0 you can also use a list instead a dict. |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | Start by creating a dictionary:
```
dictionary = {}
```
Now you can use a for loop to create the keys:
```
for num in range(1001):
dictionary[num] = ""
``` | Assuming your use-case:
>
> want to use this dict as a "database" to store hardcoded data
>
>
>
### The database approach
Most databases don't reserve space upfront and create something like dummy-records. Nor do they create and reserve keys in advance.
What a typical database and the setup for a collection or table of users would do:
1. create the schema or table `user` with columns or fields `id` for the key or sequential number, `name` more for the attributes.
2. create the sequence or auto-numbering to generate a new `id` value for each newly added or inserted record
### The data structure approach in Python
Analogously you would create either a dict with some functions to manage:
```py
user_store = {} # empty dict, no schema, no elements yet
current_id = None # the sequence to increment for each new record added
def nextId():
if not current_id:
current_id = 0 # the initial first value of the sequence
else:
current_id += 1 # increment each time
return current_id
def add_user(name):
id = nextId() # generate unique id from sequence
user_store[id] = name # add new key with value
return id # return the generated id to reference the user record later
def remove_user_by_id(id):
del user_store[id] # frees space
def update_user(id, new_name):
user_store[id] = new_name # update the name
def count():
# there may be records and ids deleted, so the count is not related to current_id
return len(user_store)
```
See also:
* RealPython: [Dictionaries in Python](https://realpython.com/python-dicts)
If the (primary) *key* or id is a sequential number starting with 0 you can also use a list instead a dict. |
73,378,056 | I am working on a simple simulator for a radio frequency application and have to deal with very low complex numbers. During the process I have a Matrix like `np.array([[A,B],[C,D]], dtype=np.clongdouble)` which ensures the necessary "resolution(?)". However, I have to do stuff like
```
den = A+B/z0+C*z0+D
s11 = A+B/z0-C*z0-D)/den
s12 = 2*(A*D-B*C)/den
s21 = 2/den
s22 = (-A+B/z0-C*z0+D)/den
```
I think `Z0` is of type `double` since it's calculated without numpy.
Now I wonder: Do I have to do the calculations of `den` etc with numpy to achieve/keep resolution or are the 'normal' calculations sufficient enough? | 2022/08/16 | [
"https://Stackoverflow.com/questions/73378056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5962420/"
] | Use the classmethod factory [`fromkeys`](https://docs.python.org/3/library/stdtypes.html#dict.fromkeys):
```
dict.fromkeys(range(1001), "")
```
And perhaps consider using a list. This is more memory efficient than using a dict with consecutive integer keys.
```
[""] * 1001
``` | Assuming your use-case:
>
> want to use this dict as a "database" to store hardcoded data
>
>
>
### The database approach
Most databases don't reserve space upfront and create something like dummy-records. Nor do they create and reserve keys in advance.
What a typical database and the setup for a collection or table of users would do:
1. create the schema or table `user` with columns or fields `id` for the key or sequential number, `name` more for the attributes.
2. create the sequence or auto-numbering to generate a new `id` value for each newly added or inserted record
### The data structure approach in Python
Analogously you would create either a dict with some functions to manage:
```py
user_store = {} # empty dict, no schema, no elements yet
current_id = None # the sequence to increment for each new record added
def nextId():
if not current_id:
current_id = 0 # the initial first value of the sequence
else:
current_id += 1 # increment each time
return current_id
def add_user(name):
id = nextId() # generate unique id from sequence
user_store[id] = name # add new key with value
return id # return the generated id to reference the user record later
def remove_user_by_id(id):
del user_store[id] # frees space
def update_user(id, new_name):
user_store[id] = new_name # update the name
def count():
# there may be records and ids deleted, so the count is not related to current_id
return len(user_store)
```
See also:
* RealPython: [Dictionaries in Python](https://realpython.com/python-dicts)
If the (primary) *key* or id is a sequential number starting with 0 you can also use a list instead a dict. |
30,217,446 | I have the following Activity that throws an exception if something is configured wrong.
```
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
throw new IllegalStateException("something went wrong");
}
}
```
I tried to write a test for this `ActivityInstrumentationTestCase2`
```
public void testException() throws Exception {
try {
getActivity().onCreate(null);
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
which throws the correct `Exception` but doesn't run in my `catch` block due to some internal `Sandboxing` of the `ActivityInstrumentationTestCase2`.
So I tried it with plain Java
```
public void testException() throws Exception {
final MockNavigationDrawerActivity activity = Mockito.mock(MockNavigationDrawerActivity.class);
Mockito.doCallRealMethod().when(activity).onCreate(null);
try {
activity.onCreate(null);
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
which does not work
```
java.lang.AbstractMethodError: abstract method "boolean org.mockito.internal.invocation.AbstractAwareMethod.isAbstract()"
at org.mockito.internal.invocation.InvocationImpl.callRealMethod(InvocationImpl.java:109)
at org.mockito.internal.stubbing.answers.CallsRealMethods.answer(CallsRealMethods.java:41)
at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:34)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:91)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)
at com.google.dexmaker.mockito.InvocationHandlerAdapter.invoke(InvocationHandlerAdapter.java:49)
at MockNavigationDrawerActivity_Proxy.onCreate(MockNavigationDrawerActivity_Proxy.generated)
```
Any idea how to test this **simple** case?
Update #1
---------
I tried absolutely everything. I reduced it to the absolute minimum which doesn't work.
```
public void testUpdate1() throws Exception {
try {
getActivity();
fail();
} catch (Exception e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
stacktrace:
```
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.MyActivity}: java.lang.IllegalStateException: something went wrong
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalStateException: something went wrong
at com.example.MyActivity.onCreate(MyActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.support.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:346)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
```
Update #2
---------
I started from the beginning. Generated a new project, threw the Exception
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
throw new IllegalStateException("something");
}
```
an tried to catch it with a `Throwable`.
```
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
public MainActivityTest() {
super(MainActivity.class);
}
public void testOnCreate() throws Exception {
try {
getActivity();
fail();
} catch (Throwable throwable) {
assertTrue(throwable.getCause().getMessage().contains("something"));
}
}
}
```
I got this (complete) stacktrace which does not lead to my test. The system seems to call `onCreate`, perhaps from a different process, not my test.
```
Process: com.pascalwelsch.onccreatetest, PID: 3915 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pascalwelsch.onccreatetest/com.pascalwelsch.onccreatetest.MainActivity}: java.lang.IllegalStateException: something
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalStateException: something
at com.pascalwelsch.onccreatetest.MainActivity.onCreate(MainActivity.java:15)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
``` | 2015/05/13 | [
"https://Stackoverflow.com/questions/30217446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669294/"
] | You are throwing `IllegalArgumentException` and catching `IllegalStateException`. You can add another catch block with catching `Exception` - it will work. | Why do you mock the class you are trying to test? You should mock dependencies of `MyActivity` to test that its methods are correctly using the mocks.
For example if you want to test class `A` which depends on `B` and `C`, then you want to create 2 mocks for `B` and `C` and a concrete object of `A`. Then you inject those 2 mocks in your object and you can start calling methods on it.
This is probably also the reason you get a `java.lang.AbstractMethodError` (there is not enough code posted to confirm it though). If you call a real method on a mock, whereas this method is abstract (for example you are mocking an interface or abstract class), then this error is thrown.
Below I posted some code and a test as example of how you can insert mocks into a concrete object.
In code:
```
class A {
B b;
C c;
void doSomething() {
b.aMethod();
c.anotherMethod();
throw new IllegalArgumentException("something went wrong");
}
}
interface B {
void aMethod();
}
abstract class C {
void anotherMethod();
}
```
with a test:
```
@RunWith(MockitoJUnitRunner.class)
class ATest {
@Mock B b;
@Mock C c;
// The inject mocks will insert both b and c into a by using reflection
@InjectMocks A a;
@Test(expected=IllegalArgumentException.class)
public void testSomething() {
a.doSomething();
}
}
``` |
30,217,446 | I have the following Activity that throws an exception if something is configured wrong.
```
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
throw new IllegalStateException("something went wrong");
}
}
```
I tried to write a test for this `ActivityInstrumentationTestCase2`
```
public void testException() throws Exception {
try {
getActivity().onCreate(null);
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
which throws the correct `Exception` but doesn't run in my `catch` block due to some internal `Sandboxing` of the `ActivityInstrumentationTestCase2`.
So I tried it with plain Java
```
public void testException() throws Exception {
final MockNavigationDrawerActivity activity = Mockito.mock(MockNavigationDrawerActivity.class);
Mockito.doCallRealMethod().when(activity).onCreate(null);
try {
activity.onCreate(null);
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
which does not work
```
java.lang.AbstractMethodError: abstract method "boolean org.mockito.internal.invocation.AbstractAwareMethod.isAbstract()"
at org.mockito.internal.invocation.InvocationImpl.callRealMethod(InvocationImpl.java:109)
at org.mockito.internal.stubbing.answers.CallsRealMethods.answer(CallsRealMethods.java:41)
at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:34)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:91)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)
at com.google.dexmaker.mockito.InvocationHandlerAdapter.invoke(InvocationHandlerAdapter.java:49)
at MockNavigationDrawerActivity_Proxy.onCreate(MockNavigationDrawerActivity_Proxy.generated)
```
Any idea how to test this **simple** case?
Update #1
---------
I tried absolutely everything. I reduced it to the absolute minimum which doesn't work.
```
public void testUpdate1() throws Exception {
try {
getActivity();
fail();
} catch (Exception e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
stacktrace:
```
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.MyActivity}: java.lang.IllegalStateException: something went wrong
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalStateException: something went wrong
at com.example.MyActivity.onCreate(MyActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.support.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:346)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
```
Update #2
---------
I started from the beginning. Generated a new project, threw the Exception
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
throw new IllegalStateException("something");
}
```
an tried to catch it with a `Throwable`.
```
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
public MainActivityTest() {
super(MainActivity.class);
}
public void testOnCreate() throws Exception {
try {
getActivity();
fail();
} catch (Throwable throwable) {
assertTrue(throwable.getCause().getMessage().contains("something"));
}
}
}
```
I got this (complete) stacktrace which does not lead to my test. The system seems to call `onCreate`, perhaps from a different process, not my test.
```
Process: com.pascalwelsch.onccreatetest, PID: 3915 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pascalwelsch.onccreatetest/com.pascalwelsch.onccreatetest.MainActivity}: java.lang.IllegalStateException: something
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalStateException: something
at com.pascalwelsch.onccreatetest.MainActivity.onCreate(MainActivity.java:15)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
``` | 2015/05/13 | [
"https://Stackoverflow.com/questions/30217446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669294/"
] | You are throwing `IllegalArgumentException` and catching `IllegalStateException`. You can add another catch block with catching `Exception` - it will work. | `getActivity` is indeed calling `onCreate` method, so it is failing with your programmed exception and it throws another one (`RuntimeException`) with your generated one as the root cause. |
30,217,446 | I have the following Activity that throws an exception if something is configured wrong.
```
public class MyActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
throw new IllegalStateException("something went wrong");
}
}
```
I tried to write a test for this `ActivityInstrumentationTestCase2`
```
public void testException() throws Exception {
try {
getActivity().onCreate(null);
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
which throws the correct `Exception` but doesn't run in my `catch` block due to some internal `Sandboxing` of the `ActivityInstrumentationTestCase2`.
So I tried it with plain Java
```
public void testException() throws Exception {
final MockNavigationDrawerActivity activity = Mockito.mock(MockNavigationDrawerActivity.class);
Mockito.doCallRealMethod().when(activity).onCreate(null);
try {
activity.onCreate(null);
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
which does not work
```
java.lang.AbstractMethodError: abstract method "boolean org.mockito.internal.invocation.AbstractAwareMethod.isAbstract()"
at org.mockito.internal.invocation.InvocationImpl.callRealMethod(InvocationImpl.java:109)
at org.mockito.internal.stubbing.answers.CallsRealMethods.answer(CallsRealMethods.java:41)
at org.mockito.internal.stubbing.StubbedInvocationMatcher.answer(StubbedInvocationMatcher.java:34)
at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:91)
at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)
at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:38)
at com.google.dexmaker.mockito.InvocationHandlerAdapter.invoke(InvocationHandlerAdapter.java:49)
at MockNavigationDrawerActivity_Proxy.onCreate(MockNavigationDrawerActivity_Proxy.generated)
```
Any idea how to test this **simple** case?
Update #1
---------
I tried absolutely everything. I reduced it to the absolute minimum which doesn't work.
```
public void testUpdate1() throws Exception {
try {
getActivity();
fail();
} catch (Exception e) {
assertThat(e.getMessage()).contains("something went wrong");
}
}
```
stacktrace:
```
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example/com.example.MyActivity}: java.lang.IllegalStateException: something went wrong
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalStateException: something went wrong
at com.example.MyActivity.onCreate(MyActivity.java:28)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.support.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:346)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
```
Update #2
---------
I started from the beginning. Generated a new project, threw the Exception
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
throw new IllegalStateException("something");
}
```
an tried to catch it with a `Throwable`.
```
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
public MainActivityTest() {
super(MainActivity.class);
}
public void testOnCreate() throws Exception {
try {
getActivity();
fail();
} catch (Throwable throwable) {
assertTrue(throwable.getCause().getMessage().contains("something"));
}
}
}
```
I got this (complete) stacktrace which does not lead to my test. The system seems to call `onCreate`, perhaps from a different process, not my test.
```
Process: com.pascalwelsch.onccreatetest, PID: 3915 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pascalwelsch.onccreatetest/com.pascalwelsch.onccreatetest.MainActivity}: java.lang.IllegalStateException: something
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalStateException: something
at com.pascalwelsch.onccreatetest.MainActivity.onCreate(MainActivity.java:15)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
``` | 2015/05/13 | [
"https://Stackoverflow.com/questions/30217446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/669294/"
] | Why do you mock the class you are trying to test? You should mock dependencies of `MyActivity` to test that its methods are correctly using the mocks.
For example if you want to test class `A` which depends on `B` and `C`, then you want to create 2 mocks for `B` and `C` and a concrete object of `A`. Then you inject those 2 mocks in your object and you can start calling methods on it.
This is probably also the reason you get a `java.lang.AbstractMethodError` (there is not enough code posted to confirm it though). If you call a real method on a mock, whereas this method is abstract (for example you are mocking an interface or abstract class), then this error is thrown.
Below I posted some code and a test as example of how you can insert mocks into a concrete object.
In code:
```
class A {
B b;
C c;
void doSomething() {
b.aMethod();
c.anotherMethod();
throw new IllegalArgumentException("something went wrong");
}
}
interface B {
void aMethod();
}
abstract class C {
void anotherMethod();
}
```
with a test:
```
@RunWith(MockitoJUnitRunner.class)
class ATest {
@Mock B b;
@Mock C c;
// The inject mocks will insert both b and c into a by using reflection
@InjectMocks A a;
@Test(expected=IllegalArgumentException.class)
public void testSomething() {
a.doSomething();
}
}
``` | `getActivity` is indeed calling `onCreate` method, so it is failing with your programmed exception and it throws another one (`RuntimeException`) with your generated one as the root cause. |
27,711,766 | I am using **Page** classes to its **NavigationService.Navigate** API to create navigation between few pages. In the page I have provided buttons for navigation but I am getting following control for free.

Is there someway to hide this control so that its not shown? | 2014/12/30 | [
"https://Stackoverflow.com/questions/27711766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4059893/"
] | Is your page rendered inside of a frame? A frame by default supports Navigation. If this is the case you have to set the navigation visibility property of the frame control to hidden.
```
<Frame Name="Frame1" NavigationUIVisibility="Hidden" >
``` | Yes, `Page` object has `ShowsNavigationUI` property that you can use.
```
<Page ...
ShowsNavigationUI="False">
<Grid Background="LightBlue" />
</Page>
``` |
46,707,234 | Here is my code:
```
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using System;
using System.IO;
public class CarMove : MonoBehaviour
{
public unsafe struct TrafficRoadSystem { };
public unsafe struct CarsSimulation { };
public unsafe struct CarPostion
{
double position_x;
double position_y;
double position_z;
};
// Use this for initialization
[DllImport("Assets/traffic.dll", CharSet = CharSet.Ansi)]
public unsafe static extern int traffic_import_osm([MarshalAs(UnmanagedType.LPStr)] string osm_pbf_path, TrafficRoadSystem** out_road_system);
[DllImport("Assets/traffic.dll")]
public unsafe static extern int create_simulation(TrafficRoadSystem* road_system, CarsSimulation** out_simulation, double speed, int cars_count);
[DllImport("Assets/traffic.dll")]
public static extern void update_simulation(ref CarsSimulation simulation, double time);
[DllImport("Assets/traffic.dll")]
public static extern CarPostion get_car_postion(ref CarsSimulation simulation, int car_number);
unsafe CarsSimulation* carSimulation;
unsafe TrafficRoadSystem* trafficRoadSystem;
void Start()
{
unsafe
{
string osmPath = "Assets/Resources/map.osm.pbf";
int results;
results = traffic_import_osm(osmPath, &trafficRoadSystem);
}
}
// Update is called once per frame
void Update()
{
}
}
```
This is from dll C library. Function `int traffic_import_osm()` works on `TrafficRoadSystem* trafficRoadSystem;` object as reference and I want to have in access to object in `void Update()`. This works well in one function but I cannot get address of a class variable and I get error
`Error CS0212 You can only take the address of an unfixed expression inside of a fixed statement initializer`
in line `results = traffic_import_osm(osmPath, &trafficRoadSystem);`
I try to use this solution
<https://msdn.microsoft.com/en-us/library/29ak9b70(v=vs.90).aspx>
I wrote this:
```
TrafficRoadSystem trafficRoadSystem;
void Start()
{
unsafe
{
string osmPath = "Assets/Resources/map.osm.pbf";
CarMove carMove = new CarMove();
int results;
fixed( TrafficRoadSystem* ptr = &carMove.trafficRoadSystem)
{
results = traffic_import_osm(osmPath, &ptr);
}
}
}
```
and I get error `CS0459 Cannot take the address of a read-only local variable` in line
`results = traffic_import_osm(osmPath, &ptr);` | 2017/10/12 | [
"https://Stackoverflow.com/questions/46707234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8764416/"
] | Making a C or C++ plugin in Unity requires extensive knowledge of these languages. This means you should spend time learning pointers before attempting to use raw pointer in Unity. Because even if you get it to compile, you may also run into hard to fix crashes.
You have:
```
unsafe TrafficRoadSystem* trafficRoadSystem;
```
and want to pass it to the function below:
```
public unsafe static extern int traffic_import_osm(..., TrafficRoadSystem** out_road_system);
```
---
**1**.The `trafficRoadSystem` variable is a pointer and you will need to make another pointer that points to `trafficRoadSystem`. This is called "pointers to pointer"
```
TrafficRoadSystem** addressOfTrafficRoadSystem = &trafficRoadSystem;
```
Notice the double "`**`".
**2**.You must use `fixed` keyword to do what I mentione in #1.
```
fixed (TrafficRoadSystem** addressOfTrafficRoadSystem = &trafficRoadSystem)
{
}
```
**3**.You can pass that pointer to pointer address to the `traffic_import_osm` function.
The whole new Start function:
```
void Start()
{
unsafe
{
fixed (TrafficRoadSystem** addressOfTrafficRoadSystem = &trafficRoadSystem)
{
string osmPath = "Assets/Resources/map.osm.pbf";
int results;
results = traffic_import_osm(osmPath, addressOfTrafficRoadSystem);
}
}
}
```
---
Unrelated possible future issues:
**1**.I noticed that you did `CarMove carMove = new CarMove();` in your updated question. Don't use the `new` keyword here because `CarMove` inherits from `MonoBehaviour`. See [this](https://stackoverflow.com/questions/37398538/unity-null-while-making-new-class-instance/37399263#37399263) answer for what to do.
**2**.I also noticed you used `"Assets/Resources/map.osm.pbf";`. This path will be invalid when you build your project. Consider using the *StreamingAssets* folder instead of the Resources folder which only works with the [`Resources`](https://stackoverflow.com/questions/41326248/using-resources-folder-in-unity/41326276#41326276) API. You use `Application.streamingAssetsPath` with the *StreamingAssets* folder. | An alternative to using raw Pointers is to use Marshalling. Marshalling allows you to take C# data structures and transform them to C-understandable data without the need of any unsafe-keywords.
Mono has a [document](http://www.mono-project.com/docs/advanced/pinvoke/) describing how to properly interact with native libraries using **PInvoke** (which is the search term you're looking for).
[Here](http://www.c-sharpcorner.com/uploadfile/GemingLeader/marshaling-with-C-Sharp-chapter-1-introducing-marshaling/), [here](http://www.c-sharpcorner.com/uploadfile/GemingLeader/marshaling-with-C-Sharp-chapter-2-marshaling-simple-types/) and [here](http://www.c-sharpcorner.com/uploadfile/GemingLeader/marshaling-with-C-Sharp-chapter-3-marshaling-compound-types/) you can also find an introduction into PInvoke and Marshalling.
Basically you replace the pointer signatures with the `IntPtr`-type, which is a managed version of a pointer. To transform your managed struct variable you'll first need to allocate a memory region and use it for your struct
```
IntPtr ptr;
TrafficRoadSystem _struct;
try {
ptr = Marshal.AllocHGlobal(Marshal.SizeOf(_struct));
Marshal.StructureToPtr(_struct, ptr, false);
} finally {
Marshal.FreeHGlobal(ptr);
}
```
I don't know how to properly deal with double pointers though.. |
35,274 | There's a dead, gnarly old tree in the courtyard outside of Denethor's 'throne room' on the top level of Minas Tirith. Gandalf told Pippin that it's called the White Tree of Gondor. We see it several times in 'Return of the King' and it's obviously dried-up dead. Yet after they defeat Sauron and Aragorn is crowned King just weeks later, it's suddenly flowered and in full bloom, blowing its petals across the coronation. How can that be? | 2013/05/07 | [
"https://scifi.stackexchange.com/questions/35274",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/13090/"
] | One word: Jackson. A second word: nonsense.
The story is different in the books - Aragorn finds a sapling of the dead tree and plants it, which becomes the new White Tree:
>
> Then Aragorn turned, and there was a stony slope behind him running down from the skirts of the snow; and as he looked he was aware that alone there in the waste a growing thing stood. And he climbed to it, and saw that out of the very edge of the snow there sprang a sapling tree no more than three foot high. Already it had put forth young leaves long and shapely, dark above and silver beneath, and upon its slender crown it bore one small cluster of flowers whose white petals shone like the sunlit snow.
>
>
>
This ain't no normal tree either:
>
> Verily this is a sapling of the line of Nimloth the fair; and that was a seedling of Galathilion, and that a fruit of Telperion of many names, Eldest of Trees.
>
>
>
And Telperion, as one of the Two Trees of Valinor, the light of which was captured in the Silmarils, is therefore quite central to all of Tolkien's work.
(Quotes from RotK Book VI Chapter 5) | Indeed, Peter Jackson did somewhat over-dramatise this part, though I find the original fairly dramatic/moving in of itself.
Further to Jimmy S's point, Tolkien describes the history of Minas Tirith, where the White Tree would regularly start to die but the King/Stewards would plant a new sapling:
>
> When King Telemar died the White Tree of Minas Anor also withered and died. But Tarandor, his nephew. who succeeded him, replanted a seedling in the citadel.
> *[LotR appendix A., I(iv)]*
>
>
>
The first sapling was planted by Isildur (before he lost the ring), when the city was still Minas Anor. [LotR Book II, ch. 2, *The Council of Elrond*]
Also, the finding of the sapling in the snow was a prophecy linked to the return of the king, and the fact the the White Tree died without a sapling was indicative (allegorically) of the petering out of the line of Kings/Stewards:
>
> When Belecthor II, the twenty-first Steward died, the White Tree died also in Minas Tirith, but it was left standing 'until the King returns', for no seedling could be found.
> *[LotR Appendix A., I(iv) The Stewards]*
>
>
>
As an aside, yes Sauron wasn't as powerful as Morgoth, but that's because he was only his "lieutenant" - he was a Maia like Gandalf. He still fooled the Elves into making his rings and engineered the destruction of Númenor though! |
35,274 | There's a dead, gnarly old tree in the courtyard outside of Denethor's 'throne room' on the top level of Minas Tirith. Gandalf told Pippin that it's called the White Tree of Gondor. We see it several times in 'Return of the King' and it's obviously dried-up dead. Yet after they defeat Sauron and Aragorn is crowned King just weeks later, it's suddenly flowered and in full bloom, blowing its petals across the coronation. How can that be? | 2013/05/07 | [
"https://scifi.stackexchange.com/questions/35274",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/13090/"
] | One word: Jackson. A second word: nonsense.
The story is different in the books - Aragorn finds a sapling of the dead tree and plants it, which becomes the new White Tree:
>
> Then Aragorn turned, and there was a stony slope behind him running down from the skirts of the snow; and as he looked he was aware that alone there in the waste a growing thing stood. And he climbed to it, and saw that out of the very edge of the snow there sprang a sapling tree no more than three foot high. Already it had put forth young leaves long and shapely, dark above and silver beneath, and upon its slender crown it bore one small cluster of flowers whose white petals shone like the sunlit snow.
>
>
>
This ain't no normal tree either:
>
> Verily this is a sapling of the line of Nimloth the fair; and that was a seedling of Galathilion, and that a fruit of Telperion of many names, Eldest of Trees.
>
>
>
And Telperion, as one of the Two Trees of Valinor, the light of which was captured in the Silmarils, is therefore quite central to all of Tolkien's work.
(Quotes from RotK Book VI Chapter 5) | Others have answered in terms of the books, but another answer is possible if we ignore the books (I can't believe I just said those words!), and look only for movie-logic
Basically the answer is, "it's magic". But it's not completely abrupt. There's a moment in the movie (when Denethor is *en route* to immolating himself) when we see the tree in the foreground, and just for a moment the camera lingers on a single flower that has appeared on the "dead" tree!
It's also not *quite* as lame as "it's magic" might suggest. I see it as a kind of "fisher-king" thing: the life of the tree is tied to the kingship; as Aragorn's day approaches, the dead (or at the very least, extremely dormant) tree begins to awaken. |
71,416,848 | Is there anyway to use the reference funtion in an ARM parameter file? I understand the following can be used to retrieve the intrumentation key of an app insights instance but this doesnt seem to work in a parameter file.
```
"[reference('microsoft.insights/components/web-app-name-01', '2015-05-01').InstrumentationKey]"
```
I currently set a long list of environment variables using an array from a parameter file and need to include the dynamic app insights instrumentation key to that list of variables. | 2022/03/09 | [
"https://Stackoverflow.com/questions/71416848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13283222/"
] | Not in a param file... it's possible to simulate what you want by nested a deployment if that's an option. So your param file can contain the resourceId of the insights resource and then a nested deployment can make the reference call - but TBH, probably easier to fetch the key as a pipeline step (or similar).
```json
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"insightsResourceId": {
"type": "string",
"defaultValue": "'microsoft.insights/components/web-app-name-01'"
}
},
"resources": [
{
"apiVersion": "2018-02-01",
"type": "Microsoft.Resources/deployments",
"name": "nestedDeployment",
"properties": {
"mode": "Incremental",
"parameters": {
"instrumentationKey": {
"value": "[reference(parameters('insightsResourceId'), '2015-05-01').InstrumentationKey]"
}
},
"template": {
// original template goes here
}
}
}
]
}
``` | ### Way 1
Use the **reference** function in your parameter file for resources that are already deployed in another template. For that you have to pass the **ApiVersion** parameter. Refer [MsDoc](https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource#reference). which follows:
```json
"value": "[reference(resourceId(variables('<AppInsightsResourceGroup>'),'Microsoft.Insights/components', variables('<ApplicationInsightsName>')), '2015-05-01', 'Full').properties.InstrumentationKey]"
```
>
> You need to change the property that you are referencing from '**.InstrumentationKey**' to '**.properties.InstrumentationKey**'.
>
>
>
Refer to [Kwill answer](https://stackoverflow.com/a/60511699/15997690) for more information.
### Way 2
Get the Content of parameter file in PowerShell **variable/Object** using
```json
$ParameterObject = Get-Content ./ParameterFileName.json
Update the Parameter file values using
```
```json
#Assign the parameter values using
$ParameterObject.parameters.<KeyName>.value = "your dynamic value"
```
Pass `$parameterObject` to `-TemplateParameterObject` parameter
Refer [here](https://stackoverflow.com/a/57194774/15997690)
### Way 3
You have to **Add/Modify** the parameter file values using (PowerShell/ Dev lang (like Python, c#,...) ). After changing the parameter file try to deploy it. |
71,416,848 | Is there anyway to use the reference funtion in an ARM parameter file? I understand the following can be used to retrieve the intrumentation key of an app insights instance but this doesnt seem to work in a parameter file.
```
"[reference('microsoft.insights/components/web-app-name-01', '2015-05-01').InstrumentationKey]"
```
I currently set a long list of environment variables using an array from a parameter file and need to include the dynamic app insights instrumentation key to that list of variables. | 2022/03/09 | [
"https://Stackoverflow.com/questions/71416848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13283222/"
] | Unfortunately, no.
Reference function only works at runtime. It can't be used in the parameters or variables sections because both are resolved during the initial parsing phase of the template.
Here is an excerpt from [the docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/best-practices) and also how to use reference correctly:
>
> You can't use the reference function in the variables section of the template. The reference function derives its value from the resource's runtime state. However, variables are resolved during the initial parsing of the template. Construct values that need the reference function directly in the resources or outputs section of the template.
>
>
> | ### Way 1
Use the **reference** function in your parameter file for resources that are already deployed in another template. For that you have to pass the **ApiVersion** parameter. Refer [MsDoc](https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions-resource#reference). which follows:
```json
"value": "[reference(resourceId(variables('<AppInsightsResourceGroup>'),'Microsoft.Insights/components', variables('<ApplicationInsightsName>')), '2015-05-01', 'Full').properties.InstrumentationKey]"
```
>
> You need to change the property that you are referencing from '**.InstrumentationKey**' to '**.properties.InstrumentationKey**'.
>
>
>
Refer to [Kwill answer](https://stackoverflow.com/a/60511699/15997690) for more information.
### Way 2
Get the Content of parameter file in PowerShell **variable/Object** using
```json
$ParameterObject = Get-Content ./ParameterFileName.json
Update the Parameter file values using
```
```json
#Assign the parameter values using
$ParameterObject.parameters.<KeyName>.value = "your dynamic value"
```
Pass `$parameterObject` to `-TemplateParameterObject` parameter
Refer [here](https://stackoverflow.com/a/57194774/15997690)
### Way 3
You have to **Add/Modify** the parameter file values using (PowerShell/ Dev lang (like Python, c#,...) ). After changing the parameter file try to deploy it. |
9,844,499 | I am looking for a script that shows my logo while loading the game and shows the loading percentage or a bar representing how much of the game is loaded, and then makes my logo disappear once the game is loaded.
e-g like this site has used <http://www.gamegape.com/en-2095-elemental-battles.html>
If something like this is not available, can someone at least tell me how this site has done it, so I could copy it from them? | 2012/03/23 | [
"https://Stackoverflow.com/questions/9844499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1303767/"
] | This might help. Its a JavaScript Preloader for HTML5 Apps
<http://thinkpixellab.com/pxloader/>
have alook at the smples page. | The site you have mentioned is using flash, well this can easily be achieved by js or css3 itself.
Check this eaxample out for a progress bar <http://ivanvanderbyl.com/>.
You can either add animations using jquery or by css3. |
65,651,835 | ```java
public class Second_Largest_Number_In_Array_with_Dupes {
public static void main(String[] args) {
int[] a = {6,8,2,4,3,1,5,7};
int temp ;
for (int i = 0; i < a.length; i++){
for (int j = i + 1; j < a.length; j++){
if (a[i] < a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Second Largest element is " + a[1]);
}
}
```
This only works for array with no duplicate values.
For example it does not work for this array: `int[] a = {6,8,2,4,3,1,5,7,8};` | 2021/01/10 | [
"https://Stackoverflow.com/questions/65651835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3813730/"
] | Solution
--------
* Initialize max and second\_max with the lowest possible value `Integer.MIN_Value`
* Then go through your array and check for each element if it is greater then the `max_value` -> When yes reassign your max\_value with a[i] and reassign your second\_max\_value with max\_malue
---
```
if (a[i] > max) {
temp = max;
max = a[i];
second_max = temp;
```
* Then check if your a[i] is greater then your second\_max\_value and not equal to your max\_value . If yes reassign your second\_max\_value with a[i]
`a[i] > second_max && a[i] != max`
* Last but not least check if second\_max is equal to the initial value
If yes then there is no second highest Value in your Array. Example Arrays for this case
{5, 5, 5}, {1}
@Thanks to Henry
Here the Code
```
public static void main(String[] args) {
int[] a = { 6, 8, 2, 4, 3, 1, 5, 7 };
int max = Integer.MIN_VALUE;
int second_max = Integer.MIN_VALUE;
int temp;
for (int i = 0; i < a.length; i++) {
if (a[i] > max) {
temp = max;
max = a[i];
second_max = temp;
} else if (a[i] > second_max && a[i] != max) {
second_max = a[i];
}
}
if (second_max == Integer.MIN_VALUE) {
System.out.println("No Second Highest value");
} else {
System.out.println(second_max);
}
}
```
### Output
7 | You could take advantage of java inbuild collection.
For that you need a structure that retain values with no duplicates and also store values in order
(eg: natural-order, ascending this case).
```
import java.util.SortedSet;
import java.util.TreeSet;
public class MinArr {
public static void main(String[] args) {
int[] a = { 6, 8, 2, 4, 3, 1, 5, 7, 7, 8, 8 };
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i = 0; i < a.length; i++) {
set.add(a[i]);
}
set.forEach(System.out::println);
if (set.size() >= 2) {
set.remove(set.last());
System.out.println("second max is =" + set.last());
} else {
System.out.println("there is no second max");
}
}
}
```
Output:
```
//list values
1
2
3
4
5
6
7
8
second max is =7
``` |
65,651,835 | ```java
public class Second_Largest_Number_In_Array_with_Dupes {
public static void main(String[] args) {
int[] a = {6,8,2,4,3,1,5,7};
int temp ;
for (int i = 0; i < a.length; i++){
for (int j = i + 1; j < a.length; j++){
if (a[i] < a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Second Largest element is " + a[1]);
}
}
```
This only works for array with no duplicate values.
For example it does not work for this array: `int[] a = {6,8,2,4,3,1,5,7,8};` | 2021/01/10 | [
"https://Stackoverflow.com/questions/65651835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3813730/"
] | Solution
--------
* Initialize max and second\_max with the lowest possible value `Integer.MIN_Value`
* Then go through your array and check for each element if it is greater then the `max_value` -> When yes reassign your max\_value with a[i] and reassign your second\_max\_value with max\_malue
---
```
if (a[i] > max) {
temp = max;
max = a[i];
second_max = temp;
```
* Then check if your a[i] is greater then your second\_max\_value and not equal to your max\_value . If yes reassign your second\_max\_value with a[i]
`a[i] > second_max && a[i] != max`
* Last but not least check if second\_max is equal to the initial value
If yes then there is no second highest Value in your Array. Example Arrays for this case
{5, 5, 5}, {1}
@Thanks to Henry
Here the Code
```
public static void main(String[] args) {
int[] a = { 6, 8, 2, 4, 3, 1, 5, 7 };
int max = Integer.MIN_VALUE;
int second_max = Integer.MIN_VALUE;
int temp;
for (int i = 0; i < a.length; i++) {
if (a[i] > max) {
temp = max;
max = a[i];
second_max = temp;
} else if (a[i] > second_max && a[i] != max) {
second_max = a[i];
}
}
if (second_max == Integer.MIN_VALUE) {
System.out.println("No Second Highest value");
} else {
System.out.println(second_max);
}
}
```
### Output
7 | The best way to get k highest number in the array if space is not a constraint then we can use priority queue.
```
int[] a = {6,8,2,4,3,1,5,7};
PriorityQueue<Integer> pr = new PriorityQueue<Integer>(Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
pr.add(a[i]);
}
pr.poll();
System.out.println(pr.poll());``
``` |
65,651,835 | ```java
public class Second_Largest_Number_In_Array_with_Dupes {
public static void main(String[] args) {
int[] a = {6,8,2,4,3,1,5,7};
int temp ;
for (int i = 0; i < a.length; i++){
for (int j = i + 1; j < a.length; j++){
if (a[i] < a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Second Largest element is " + a[1]);
}
}
```
This only works for array with no duplicate values.
For example it does not work for this array: `int[] a = {6,8,2,4,3,1,5,7,8};` | 2021/01/10 | [
"https://Stackoverflow.com/questions/65651835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3813730/"
] | Alternatively to the correct answer, one can also use the following algorithm:
```
public static void main(String[] args) {
int [] a= {6,8,2,4,3,1,5,7,8} ;
SortedSet<Integer> sortedSet = new TreeSet<Integer>();
Arrays.stream(a).forEach(sortedSet::add);
sortedSet.remove(sortedSet.last());
System.out.println(sortedSet.last());
}
```
Add to a sorted set, so that the highest values will be at the end of that set. Moreover, by using a set we are removing any duplicated values. To get the highest element one would do `sorted_set.last()`, for the second highest one has to first remove the last element.
One can generalize the function to any `nth` max element, like so:
```
public static int getNthMaxElement(int [] array, int nth){
SortedSet<Integer> sortedSet = new TreeSet<Integer>();
Arrays.stream(array).forEach(sortedSet::add);
if(array.length < nth) return Integer.MIN_VALUE;
for(int i = 1; i < nth; i++)
sortedSet.remove(sortedSet.last());
return sortedSet.last();
}
```
Test:
```
public static void main(String[] args) {
int [] a= {6,8,2,4,3,1,5,7,8} ;
for(int i = 1; i < a.length; i++)
System.out.println(i+"th max : "+getNthMaxElement(a, i));
}
```
**output:**
```
1th max : 8
2th max : 7
3th max : 6
4th max : 5
5th max : 4
6th max : 3
7th max : 2
8th max : 1
``` | You could take advantage of java inbuild collection.
For that you need a structure that retain values with no duplicates and also store values in order
(eg: natural-order, ascending this case).
```
import java.util.SortedSet;
import java.util.TreeSet;
public class MinArr {
public static void main(String[] args) {
int[] a = { 6, 8, 2, 4, 3, 1, 5, 7, 7, 8, 8 };
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i = 0; i < a.length; i++) {
set.add(a[i]);
}
set.forEach(System.out::println);
if (set.size() >= 2) {
set.remove(set.last());
System.out.println("second max is =" + set.last());
} else {
System.out.println("there is no second max");
}
}
}
```
Output:
```
//list values
1
2
3
4
5
6
7
8
second max is =7
``` |
65,651,835 | ```java
public class Second_Largest_Number_In_Array_with_Dupes {
public static void main(String[] args) {
int[] a = {6,8,2,4,3,1,5,7};
int temp ;
for (int i = 0; i < a.length; i++){
for (int j = i + 1; j < a.length; j++){
if (a[i] < a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("Second Largest element is " + a[1]);
}
}
```
This only works for array with no duplicate values.
For example it does not work for this array: `int[] a = {6,8,2,4,3,1,5,7,8};` | 2021/01/10 | [
"https://Stackoverflow.com/questions/65651835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3813730/"
] | Alternatively to the correct answer, one can also use the following algorithm:
```
public static void main(String[] args) {
int [] a= {6,8,2,4,3,1,5,7,8} ;
SortedSet<Integer> sortedSet = new TreeSet<Integer>();
Arrays.stream(a).forEach(sortedSet::add);
sortedSet.remove(sortedSet.last());
System.out.println(sortedSet.last());
}
```
Add to a sorted set, so that the highest values will be at the end of that set. Moreover, by using a set we are removing any duplicated values. To get the highest element one would do `sorted_set.last()`, for the second highest one has to first remove the last element.
One can generalize the function to any `nth` max element, like so:
```
public static int getNthMaxElement(int [] array, int nth){
SortedSet<Integer> sortedSet = new TreeSet<Integer>();
Arrays.stream(array).forEach(sortedSet::add);
if(array.length < nth) return Integer.MIN_VALUE;
for(int i = 1; i < nth; i++)
sortedSet.remove(sortedSet.last());
return sortedSet.last();
}
```
Test:
```
public static void main(String[] args) {
int [] a= {6,8,2,4,3,1,5,7,8} ;
for(int i = 1; i < a.length; i++)
System.out.println(i+"th max : "+getNthMaxElement(a, i));
}
```
**output:**
```
1th max : 8
2th max : 7
3th max : 6
4th max : 5
5th max : 4
6th max : 3
7th max : 2
8th max : 1
``` | The best way to get k highest number in the array if space is not a constraint then we can use priority queue.
```
int[] a = {6,8,2,4,3,1,5,7};
PriorityQueue<Integer> pr = new PriorityQueue<Integer>(Collections.reverseOrder());
for (int i = 0; i < a.length; i++) {
pr.add(a[i]);
}
pr.poll();
System.out.println(pr.poll());``
``` |
54,983,334 | I'm trying to create a UI test for my android application using Espresso. My activities are extending `AppCompatActivity` and I'm using `ActivityTestRule` to launch the activity but it gives this exception:
```
Type parameter bound for T in constructor ActivityTestRule<T : Activity (activityClass: Class<T!>!)is not satisfied: inferred type HomeActivity! is not a subtype of Activity!
```
Here's my test class:
```
@RunWith(AndroidJUnit4::class)
class ProductListRestrictionsUITest {
@Rule @JvmField
var activityRule = ActivityTestRule(HomeActivity::class.java)
@Test
fun buttonClick_goToSecondActivity() {
onView(withId(R.id.floatingSearchView)).perform(click())
onView(withId(R.id.floatingSearchView)).perform(typeText("olut"))
onView(withId(R.id.floatingSearchView)).perform(pressKey(KeyEvent.KEYCODE_SEARCH))
// onView(withId(R.id.layout)).check(matches(isDisplayed()))
}
}
```
I have the required dependencies in the gralde file as well:
```
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test:rules:1.0.2'
// espresso support
androidTestImplementation('com.android.support.test.espresso:espresso-core:3.0.1', {
exclude group: 'com.android.support', module: 'support-annotations'
})
```
I couldn't find any resource that says what other rule to use for `AppCompatActivity`. What am i doing wrong here? | 2019/03/04 | [
"https://Stackoverflow.com/questions/54983334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1754112/"
] | This was happening to me on a separate module I created for my tests. I have a `base-android` module that hold my `BaseActivity` and did not import it on my tests module. As it cannot see the imported base activity, the test cannot see its super type. Importing the `base-android` module on my `tests` module fixed the issue. | This can happen in a `com.android.test` module, when the versions of appcompat were different between the main app, and the test module.
Fix is to explicitly declare the appcompat dependency with version number in both `app/build.gradle` and `testmodule/build.gradle`, so you get the same version in both. |
280,901 | I made a bone-headed mistake in one of my init.d scripts which gets stuck in an infinite loop during the boot process and blocks the completion. I therefore can not get to a shell and fix it. How can I boot and not perform all the boot scripts? I have root if necessary. | 2011/06/16 | [
"https://serverfault.com/questions/280901",
"https://serverfault.com",
"https://serverfault.com/users/20943/"
] | You can't.
Quote from [SQL Azure Overview (http://msdn.microsoft.com/en-us/library/ee336241.aspx)](http://msdn.microsoft.com/en-us/library/ee336241.aspx)
>
> For example, you cannot specify the
> physical hard drive or file group
> where a database or index will reside.
> Because the computer file system is
> not accessible and all data is
> automatically replicated, SQL Server
> backup and restore commands **are not
> applicable** to SQL Azure Database.
>
>
> | Not 100% sure, but I know that Azure is a subset of SQL so they might not allow restoration of a backup in case you're using functionality and features that are not included in Azure.
You're discovering the biggest issue (in my mind) of working with SQL Azure, there aren't "simple" ways to sync between a local database and azure. |
280,901 | I made a bone-headed mistake in one of my init.d scripts which gets stuck in an infinite loop during the boot process and blocks the completion. I therefore can not get to a shell and fix it. How can I boot and not perform all the boot scripts? I have root if necessary. | 2011/06/16 | [
"https://serverfault.com/questions/280901",
"https://serverfault.com",
"https://serverfault.com/users/20943/"
] | Backup and Restore aren't current supports by SQL Azure. There are various ways to backup data including using BCP, Data Sync Services.
I wrote a small (currently free) tool that creates a backup of a SQL Azure database on a local SQL Server, cunningly called SQL Azure Backup. Really interested in getting feedback on it to make it better.
<http://redg.at/gAM985> | Not 100% sure, but I know that Azure is a subset of SQL so they might not allow restoration of a backup in case you're using functionality and features that are not included in Azure.
You're discovering the biggest issue (in my mind) of working with SQL Azure, there aren't "simple" ways to sync between a local database and azure. |
280,901 | I made a bone-headed mistake in one of my init.d scripts which gets stuck in an infinite loop during the boot process and blocks the completion. I therefore can not get to a shell and fix it. How can I boot and not perform all the boot scripts? I have root if necessary. | 2011/06/16 | [
"https://serverfault.com/questions/280901",
"https://serverfault.com",
"https://serverfault.com/users/20943/"
] | You can't.
Quote from [SQL Azure Overview (http://msdn.microsoft.com/en-us/library/ee336241.aspx)](http://msdn.microsoft.com/en-us/library/ee336241.aspx)
>
> For example, you cannot specify the
> physical hard drive or file group
> where a database or index will reside.
> Because the computer file system is
> not accessible and all data is
> automatically replicated, SQL Server
> backup and restore commands **are not
> applicable** to SQL Azure Database.
>
>
> | Backup and Restore aren't current supports by SQL Azure. There are various ways to backup data including using BCP, Data Sync Services.
I wrote a small (currently free) tool that creates a backup of a SQL Azure database on a local SQL Server, cunningly called SQL Azure Backup. Really interested in getting feedback on it to make it better.
<http://redg.at/gAM985> |
52,417,327 | I am using a regular expression to capture a URL string, but it's not working out.
Here's my code, which is coming from an external JavaScript document, linked to the HTML file:
```
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch);
```
The output that I get is this: "www.google.com,www.,,www."
What am I doing wrong?
Thanks! :) | 2018/09/20 | [
"https://Stackoverflow.com/questions/52417327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10109002/"
] | Your regex works fine, what happens is that according to the match function you are getting one extra result for each group (defined by these parenthesis) that you have in your regex. to access the whole match you can access to the first item of the match return like the following:
```
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/;
var urlRegMatch = url.match(urlRegEx)[0]; //this line changed, im using [0] to access the whole match only
document.write(urlRegMatch);
```
working example: <https://jsfiddle.net/2sptg5rz/3/>
reference about the match function: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#Return_value> | I'd like to thank @Dknacht and @Tressa for directing me to the correct answer, since the first value of the array, 0, is the matched text.
This code works for what I want to do:
```
var url = 'The URL was www.google.com';
var urlRegEx = /((\bhttps?:\/\/)|(\bwww\.))\S*/
var urlRegMatch = url.match(urlRegEx);
document.write(urlRegMatch[0]);
``` |
16,844,356 | In my project I have 5-6 Activities.
Now I want to set a `Spinner` at the top of an activity, i.e. in the top corner, in front of the title.
Suppose we are in Activity 1: then by using Spinner, in front of the title name, we can go to any of the other activities.
Same thing should happen in all activities.
Please help me how to implement in android. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16844356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2126417/"
] | In all likelihood, the intermediate assigment will be optimized away by the JVM, and they will have exactly the same performance.
In either case, the possible performance hits for these things are hardly ever noticeable. You shouldn't worry about performance unless in extreme circumstances. Always opt for readability.
It should also be added that the type of micro-benchmarking you have in your code above is incredibly hard to get reliable measurements from. Too many factors out of your control (internal JVM optimizations, JVM warmup etc etc) are involved to get an accurate measurement of the exact thing you want to test. | you could profile both implementations with a tool like JVisualVM to see the exact difference. In case you want to test with high volume you could use a tool like Contiperf <http://databene.org/contiperf> And then share the results for all of us :) |
16,844,356 | In my project I have 5-6 Activities.
Now I want to set a `Spinner` at the top of an activity, i.e. in the top corner, in front of the title.
Suppose we are in Activity 1: then by using Spinner, in front of the title name, we can go to any of the other activities.
Same thing should happen in all activities.
Please help me how to implement in android. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16844356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2126417/"
] | In all likelihood, the intermediate assigment will be optimized away by the JVM, and they will have exactly the same performance.
In either case, the possible performance hits for these things are hardly ever noticeable. You shouldn't worry about performance unless in extreme circumstances. Always opt for readability.
It should also be added that the type of micro-benchmarking you have in your code above is incredibly hard to get reliable measurements from. Too many factors out of your control (internal JVM optimizations, JVM warmup etc etc) are involved to get an accurate measurement of the exact thing you want to test. | I agree with Keppil that the performance is probably exactly the same. If there is a slight difference, and if you care about such a small improvement in performance, then you probably shouldn't be using Java in the first place. |
16,844,356 | In my project I have 5-6 Activities.
Now I want to set a `Spinner` at the top of an activity, i.e. in the top corner, in front of the title.
Suppose we are in Activity 1: then by using Spinner, in front of the title name, we can go to any of the other activities.
Same thing should happen in all activities.
Please help me how to implement in android. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16844356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2126417/"
] | you could profile both implementations with a tool like JVisualVM to see the exact difference. In case you want to test with high volume you could use a tool like Contiperf <http://databene.org/contiperf> And then share the results for all of us :) | I agree with Keppil that the performance is probably exactly the same. If there is a slight difference, and if you care about such a small improvement in performance, then you probably shouldn't be using Java in the first place. |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | ```
Object o = new Student(); //upcasting - Implicit cast
Student x = (Student) o; //downcasting -Explicit cast
```
**Upcasting**: We're narrowing the reference conversion (moving up the inheritance hierarchy). Since a Student `IS-A` Object, it does not require an explicit cast
**Downcasting**: We're are widening the reference conversion (moving down the inheritance hierarchy). Since Object could be anything, we must use an explicit cast to cast it to a Student. | ```
Object o;
if (Math.random < 0.5) {
o = new Student();
} else {
o = new Dog();
}
```
You can't have `Student x = o;` obviously
Unless the dog is also a student, but that's a different story. |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | There is no casting going on here.
As you say, `Object` is a base class of `Student`.
This means that every instance of `Student` is also an `Object`, and we can always treat it as one.
```
Object o = new Student(); // A Student is an Object
```
The opposite relation does not hold, however - not all instances of `Object` are `Student`s.
After you have assigned the `Student` to `o`, the information that it's *actually* a `Student` is unavailable to the compiler.
That information is available at runtime - you can say `o instanceof Student` and it will
be true - but the compiler does not know that. | You basically have to see if it passes the `IS-A` test, you can say `Student IS-A Object` (as every class in Java is a subclass of class Object) which is why the first implicit cast works.
However you cannot say an `Object IS-A Student` because it might not be. Unless you know for a fact that it will be a `Student` then you can do a *downcast* with:
```
Student x = (Student) o;
```
Just in case you make a mistake with that *downcast* though, you might want to wrap it in an if statement like so:
```
if(o instanceof Student) {
Student x = (Student) o;
}
``` |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | There is no casting going on here.
As you say, `Object` is a base class of `Student`.
This means that every instance of `Student` is also an `Object`, and we can always treat it as one.
```
Object o = new Student(); // A Student is an Object
```
The opposite relation does not hold, however - not all instances of `Object` are `Student`s.
After you have assigned the `Student` to `o`, the information that it's *actually* a `Student` is unavailable to the compiler.
That information is available at runtime - you can say `o instanceof Student` and it will
be true - but the compiler does not know that. | You need to explicitly cast this to Student
```
Student x = (Student) o;
```
The reason for this is because the compiler doesn't know if this is correct, so you need to cast this as if to say **"I am confident that this will work. Please trust me"**. |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | There is no casting going on here.
As you say, `Object` is a base class of `Student`.
This means that every instance of `Student` is also an `Object`, and we can always treat it as one.
```
Object o = new Student(); // A Student is an Object
```
The opposite relation does not hold, however - not all instances of `Object` are `Student`s.
After you have assigned the `Student` to `o`, the information that it's *actually* a `Student` is unavailable to the compiler.
That information is available at runtime - you can say `o instanceof Student` and it will
be true - but the compiler does not know that. | Java only allows implicit upcasting, not implicit downcasting.
Upcasting in Java is also called widening conversion, and downcasting is called narrowing conversion.
Objects can be implicitly or explicitly cast to a supertype. In this example, `Object` is a supertype of `Student`.
```
Object o = new Student();
Object x = o; // implicit works
Object x = (Object) o; // explicit works
```
Objects cannot be implicitly cast to a subtype, and must be explicitly cast. In this example, `Student` is a subtype of `Object`.
```
Object o = new Student();
// Student x = o; // implicit doesn't work
Student x = (Student) o; // explicit works
```
[Explicit and Implicit Type Casting - Herong Yang](http://www.herongyang.com/Java/Reference-Type-Explicit-and-Implicit-Type-Casting.html)
[5.1.5. Widening Reference Conversion - Java docs](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.5)
[5.1.6. Narrowing Reference Conversion - Java docs](http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.6) |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | ```
Object o;
if (Math.random < 0.5) {
o = new Student();
} else {
o = new Dog();
}
```
You can't have `Student x = o;` obviously
Unless the dog is also a student, but that's a different story. | You can assign the instance of Student to a variable declared to be of type Object, because every Student is a kind of (or specialization of) Object. Since not every object IS A Student, the compiler balks at the assignment of something it knows only to be an instance of Object to any specialization of Object, such as Student. So, you can assign to an instance variable of a more general type implicitly without difficulty, but in the opposite direction the compiler wants some assurance that you mean to do this, so you explicitly downcast.
```
Student x = (Student)o;
```
This is simply the nature of a statically typed language. |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | ```
Object o = new Student(); //upcasting - Implicit cast
Student x = (Student) o; //downcasting -Explicit cast
```
**Upcasting**: We're narrowing the reference conversion (moving up the inheritance hierarchy). Since a Student `IS-A` Object, it does not require an explicit cast
**Downcasting**: We're are widening the reference conversion (moving down the inheritance hierarchy). Since Object could be anything, we must use an explicit cast to cast it to a Student. | You basically have to see if it passes the `IS-A` test, you can say `Student IS-A Object` (as every class in Java is a subclass of class Object) which is why the first implicit cast works.
However you cannot say an `Object IS-A Student` because it might not be. Unless you know for a fact that it will be a `Student` then you can do a *downcast* with:
```
Student x = (Student) o;
```
Just in case you make a mistake with that *downcast* though, you might want to wrap it in an if statement like so:
```
if(o instanceof Student) {
Student x = (Student) o;
}
``` |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | ```
Object o = new Student(); //upcasting - Implicit cast
Student x = (Student) o; //downcasting -Explicit cast
```
**Upcasting**: We're narrowing the reference conversion (moving up the inheritance hierarchy). Since a Student `IS-A` Object, it does not require an explicit cast
**Downcasting**: We're are widening the reference conversion (moving down the inheritance hierarchy). Since Object could be anything, we must use an explicit cast to cast it to a Student. | You need to explicitly cast this to Student
```
Student x = (Student) o;
```
The reason for this is because the compiler doesn't know if this is correct, so you need to cast this as if to say **"I am confident that this will work. Please trust me"**. |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | ```
Object o;
if (Math.random < 0.5) {
o = new Student();
} else {
o = new Dog();
}
```
You can't have `Student x = o;` obviously
Unless the dog is also a student, but that's a different story. | You need to explicitly cast this to Student
```
Student x = (Student) o;
```
The reason for this is because the compiler doesn't know if this is correct, so you need to cast this as if to say **"I am confident that this will work. Please trust me"**. |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | ```
Object o = new Student(); //upcasting - Implicit cast
Student x = (Student) o; //downcasting -Explicit cast
```
**Upcasting**: We're narrowing the reference conversion (moving up the inheritance hierarchy). Since a Student `IS-A` Object, it does not require an explicit cast
**Downcasting**: We're are widening the reference conversion (moving down the inheritance hierarchy). Since Object could be anything, we must use an explicit cast to cast it to a Student. | You can assign the instance of Student to a variable declared to be of type Object, because every Student is a kind of (or specialization of) Object. Since not every object IS A Student, the compiler balks at the assignment of something it knows only to be an instance of Object to any specialization of Object, such as Student. So, you can assign to an instance variable of a more general type implicitly without difficulty, but in the opposite direction the compiler wants some assurance that you mean to do this, so you explicitly downcast.
```
Student x = (Student)o;
```
This is simply the nature of a statically typed language. |
27,568,979 | I have a EF code first database, to populate the initial tables, I am using sql scripts (are far easier to handle and update that the seed methods).
The problem is, that the scripts are inserting wihtout special characters....
The database collation is: **SQL\_Latin1\_General\_CP1\_CI\_AS**
The seed is reading the script like this:
```
context.Database.ExecuteSqlCommand(File.ReadAllText(baseDir + @"..\..\Scripts\Oficina.sql"));
```
And the script looks like this:
```
INSERT [dbo].[Oficina] ([IdOficina], [Nombre], [SISTEMA], [ORDEN]) VALUES (20, N'Comisión Admisión', 1, 5)
```
The problem is, that its being saved in the database as:
```
Comisi�n Admisi�n
```
I have no clue what the problem could be.....any ideas? | 2014/12/19 | [
"https://Stackoverflow.com/questions/27568979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3351423/"
] | There is no casting going on here.
As you say, `Object` is a base class of `Student`.
This means that every instance of `Student` is also an `Object`, and we can always treat it as one.
```
Object o = new Student(); // A Student is an Object
```
The opposite relation does not hold, however - not all instances of `Object` are `Student`s.
After you have assigned the `Student` to `o`, the information that it's *actually* a `Student` is unavailable to the compiler.
That information is available at runtime - you can say `o instanceof Student` and it will
be true - but the compiler does not know that. | ```
Object o;
if (Math.random < 0.5) {
o = new Student();
} else {
o = new Dog();
}
```
You can't have `Student x = o;` obviously
Unless the dog is also a student, but that's a different story. |
29,253,624 | I have the following list of pointers:
(here is a simple example, but in reality, my list could be componed by hundreds of entries)
```
{0xae5c4e8, 0xa09d4e8, 0xa753458, 0xae554e8}
```
I successfully print pointers content, one by one, by using :
```
p *(const Point *) 0xae5c4e8
```
How can I print contents of the preceding list in one command ? | 2015/03/25 | [
"https://Stackoverflow.com/questions/29253624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463398/"
] | I don't think there is a simple way to show all the list elements at once. You could try to iterate through the items using:
```
set $it=mylist.begin()._M_node
print *(*(std::_List_node<const Point *>*)$it)._M_data
set $it=(*$it)._M_next
...
```
In the batch way. The problem is that the list items do not need to be located near to each other in the memory. To have better preview option in debug you could switch to the `std::vector`.
Hope this will help. | >
> I have the following list of pointers:
>
>
>
You don't appear to have a *list*, you appear to have an array. Let's assume that it looks something like:
```
void *array[10] = {0xae5c4e8, 0xa09d4e8, 0xa753458, 0xae554e8};
```
You can print the first 4 dereferenced elements of that array like so:
```
(gdb) print ((Point**)array)[0]@4
``` |
29,253,624 | I have the following list of pointers:
(here is a simple example, but in reality, my list could be componed by hundreds of entries)
```
{0xae5c4e8, 0xa09d4e8, 0xa753458, 0xae554e8}
```
I successfully print pointers content, one by one, by using :
```
p *(const Point *) 0xae5c4e8
```
How can I print contents of the preceding list in one command ? | 2015/03/25 | [
"https://Stackoverflow.com/questions/29253624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463398/"
] | There is no canned way to do this. It would be cool if you could type `print *(*p @ 23)` -- using the `@` extension inside another expression, resulting in an implicit loop -- but you can't.
However, there are two decent ways to do this.
One way to do it is to use Python. Something like:
```
(gdb) python x = gdb.parse_and_eval('my_array')
(gdb) python
> for i in range(nnn):
> print x[i].dereference()
> end
```
You can wrap this in a new gdb command, written in Python, pretty easily.
Another way is to use `define` to make your own command using the gdb command language. This is a bit uglier, and has some (minor) limitations compared to the Python approach, but it is still doable.
Finally, once upon a time there was a gdb extension called "duel" that provided this feature. Unfortunately it was never merged in. | I don't think there is a simple way to show all the list elements at once. You could try to iterate through the items using:
```
set $it=mylist.begin()._M_node
print *(*(std::_List_node<const Point *>*)$it)._M_data
set $it=(*$it)._M_next
...
```
In the batch way. The problem is that the list items do not need to be located near to each other in the memory. To have better preview option in debug you could switch to the `std::vector`.
Hope this will help. |
29,253,624 | I have the following list of pointers:
(here is a simple example, but in reality, my list could be componed by hundreds of entries)
```
{0xae5c4e8, 0xa09d4e8, 0xa753458, 0xae554e8}
```
I successfully print pointers content, one by one, by using :
```
p *(const Point *) 0xae5c4e8
```
How can I print contents of the preceding list in one command ? | 2015/03/25 | [
"https://Stackoverflow.com/questions/29253624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463398/"
] | There is no canned way to do this. It would be cool if you could type `print *(*p @ 23)` -- using the `@` extension inside another expression, resulting in an implicit loop -- but you can't.
However, there are two decent ways to do this.
One way to do it is to use Python. Something like:
```
(gdb) python x = gdb.parse_and_eval('my_array')
(gdb) python
> for i in range(nnn):
> print x[i].dereference()
> end
```
You can wrap this in a new gdb command, written in Python, pretty easily.
Another way is to use `define` to make your own command using the gdb command language. This is a bit uglier, and has some (minor) limitations compared to the Python approach, but it is still doable.
Finally, once upon a time there was a gdb extension called "duel" that provided this feature. Unfortunately it was never merged in. | >
> I have the following list of pointers:
>
>
>
You don't appear to have a *list*, you appear to have an array. Let's assume that it looks something like:
```
void *array[10] = {0xae5c4e8, 0xa09d4e8, 0xa753458, 0xae554e8};
```
You can print the first 4 dereferenced elements of that array like so:
```
(gdb) print ((Point**)array)[0]@4
``` |
8,840,219 | I'm modifying a C source file (`libape-spidermonkey.c`). I include a lib header file that uses some C++ features (such as, `class definitions`, `STL string vector`), so I have to compile `libape-spidermonkey.c` using `g++` instead of `gcc`.
However, because of the type-checking in C++, I got a lot of errors (NOT warnings):
```
libape-spidermonkey.c: In function ‘JSBool ape_sm_raw_constructor(JSContext*, JSObject*, uintN, jsval*, jsval*)’:
libape-spidermonkey.c:2217:1: error: invalid conversion from ‘void*’ to ‘ape_sm_compiled*’
libape-spidermonkey.c: In function ‘JSBool ape_sm_sockclient_constructor(JSContext*, JSObject*, uintN,
libape-spidermonkey.c:2231:1: error: invalid conversion from ‘void*’ to ‘ape_sm_compiled*’
libape-spidermonkey.c:2244:38: error: invalid conversion from ‘void*’ to ‘_ape_sock_js_obj*’
libape-spidermonkey.c:2248:53: error: invalid conversion from ‘void*’ to ‘_ape_sock_callbacks*’
libape-spidermonkey.c:2257:36: error: invalid conversion from ‘void*’ to ‘ape_socket*’
libape-spidermonkey.c: In function ‘JSBool ape_sm_pipe_constructor(JSContext*, JSObject*, uintN, jsval*
libape-spidermonkey.c:2281:1: error: invalid conversion from ‘void*’ to ‘ape_sm_compiled*’
libape-spidermonkey.c: In function ‘JSBool ape_sm_sockserver_constructor(JSContext*, JSObject*, uintN,
libape-spidermonkey.c:2585:1: error: invalid conversion from ‘void*’ to ‘ape_sm_compiled*’
libape-spidermonkey.c: In function ‘JSBool ape_sm_xorize(JSContext*, JSObject*, uintN, jsval*, jsval*)’
libape-spidermonkey.c:2632:1: error: invalid conversion from ‘void*’ to ‘ape_sm_compiled*’
libape-spidermonkey.c:2646:31: warning: comparison between signed and unsigned integer expressions
libape-spidermonkey.c:2650:36: error: invalid conversion from ‘void*’ to ‘char*’
```
Is there any easy way to solve this issue? Like some macro magic?
Thanks.
Peter | 2012/01/12 | [
"https://Stackoverflow.com/questions/8840219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/301336/"
] | Compile that file as a C file, rather than a C++ file. C and C++ objects can be linked together without problems. | It is a good practice (even for C developers) to try to compile their C codes using a C++ compiler. The errors found by the C++ compiler will help you to improve your code quality.
So I'd recommend you to fix the errors in your libape-spidermonkey.c using C style casting (and not the C++ static\_casts). That will garantee that your code will still compile in C compilers if you need that in the future. |
38,230,342 | I've been working on an endless runner game using unity 5 engine studying some examples. I applied jump action to my character. It did work fine but I wanted it to be bit perfect so I implanted the jump using curves with this [example](https://i.stack.imgur.com/asx0r.png), came across this issue. That is after applying curves for the character controller with some adjustments, now when I jump, the curves starting to adjust the controller after I touched a platform (the ground) which make the jump unrealistic. I did tried to achieve the jump using fixed Update method, since the game is an endless runner which basically updates everything frame by frame it did not work.
How do I achieve a realistic jump? below is what I tried so far.
```
if (controller.isGrounded)
{
verticalVelocity = -0.5f; //upward thrust / jump height
if (currentBaseState.fullPathHash == locoState) // is character in moving state
{
if (Input.GetButtonDown("Jump"))
{
verticalVelocity = 18f;
anim.SetBool("Jump", true);
}
}
else if (currentBaseState.fullPathHash == jumpState) //Is character in jump state
{
if (!anim.IsInTransition(0))
{
if (useCurves)
{
controller.height = anim.GetFloat("ColliderHeight"); //get the controller height using curves
controller.center = new Vector3(0f, anim.GetFloat("ColliderY"), 0f); //Get the controller Y axis using the curves (center of chr ctrlr)
}
anim.SetBool("Jump", false);
}
// Applying curves
Ray ray = new Ray(transform.position + Vector3.up, -Vector3.up);
RaycastHit hitInfo = new RaycastHit();
if (Physics.Raycast(ray, out hitInfo))
{
print(ray.ToString());
if (hitInfo.distance > 1.75f)
{
anim.MatchTarget(hitInfo.point, Quaternion.identity, AvatarTarget.Root, new MatchTargetWeightMask(new Vector3(0, 1f, 0), 0), 0.03f, 0.6f);
}
}
}
}
```
[](https://i.stack.imgur.com/asx0r.png)
Character jumping at start
[](https://i.stack.imgur.com/mxWGV.png)
Char controller touching the ground
[](https://i.stack.imgur.com/ckoZb.png)
Result after touching the ground
Help would be deeply appreciated | 2016/07/06 | [
"https://Stackoverflow.com/questions/38230342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4225618/"
] | Your bit of code that adjusts the controller based on the curves is inside the if statement asking if the character is grounded.
```
if (controller.isGrounded)
{
...
}
```
that way it will adjust only when the character is touching the ground. | Does your gameobject has rigidbody ? if not then try to add and make rigidbody to iskinematic because when you move an object with a collider and without a rigidbody, the complete static collision data needs to be recalculated, which is slow.
Or, may be ,try playing with animation jump frame rate don't make it too small |
64,205,692 | I am using UiPath to create a robot to get files from email. Some files are password protected and some files are not protected.
The password-protected files are sent in with a password in email body.
```
Example email
From: ABC <abc@outlook.com>
Sent: Monday, 5 October 2020 10:54 AM
To: BCD <bcd@outlook.com>
Subject: Files
```

The password is: ......
There can be 10 emails and 2 have password-protected files do I let the robot know which files are password protected and to open the password-protected Excel file and move the data to a mega Excel sheet containing all the files from the 10 emails.
I am unsure of the activities to put in the workflow to perform these functions.
I am also unsure if the below method I did is the right way to approach this.



[](https://i.stack.imgur.com/JSzlm.png) | 2020/10/05 | [
"https://Stackoverflow.com/questions/64205692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14393022/"
] | You have to save the object first then split the tag values by comma and then add the tags into the field of your object this way. I have added the comments for your understanding.
**Views.py
Uploading Posts( views.py )**
```py
@login_required(login_url="/login/")
def post_upload(request):
index1 = Blog.objects.all().order_by('-time')[0]
content = request.POST.get('content')
title = request.POST.get('title')
image = request.FILES.get('image')
if request.method == 'POST':
post_form = PostUpload(request.POST, request.FILES, instance=request.user)
if post_form.is_valid():
tags = post_form.cleaned_data['tags']
context = post_form.cleaned_data['context']
excerpt_type = post_form.cleaned_data['excerpt_type']
# Removed tags=tags from the below line
# Also, if you want to use `save` then you don't want to use
# `create` as it will persist into your db right away.
# Simply create an instance of Blog
ins = Blog(user=request.user, content=content, title=title,
image=image, context=context,
excerpt_type=excerpt_type)
# Adding tags against the object field after the object creation
for tag in tags:
ins.tags.add(tag)
ins.save()
messages.success(request, 'Your Post has been successfully posted')
print(request.POST)
print(tags)
return HttpResponseRedirect(reverse('post_upload'))
else:
print(f'error in {request.POST}')
else:
post_form = PostUpload(instance=request.user)
context = {'post_form': post_form, 'index1': index1}
return render(request, 'post_upload.html', context)
``` | You have to call **form.save\_m2m()** to save tags when using django-taggit library like this:
```
post_form = PostUpload(request.POST, request.FILES, instance=request.user)
if post_form.is_valid():
obj = post_form.save(commit=False)
obj.save()
# Without this next line the tags won't be saved.
post_form.save_m2m()
messages.success(request, 'Your Post has been successfully posted')
print(request.POST)
print(tags)
return HttpResponseRedirect(reverse('post_upload'))
```
You can read more [here](https://django-taggit.readthedocs.io/en/latest/forms.html#commit-false). |
64,205,692 | I am using UiPath to create a robot to get files from email. Some files are password protected and some files are not protected.
The password-protected files are sent in with a password in email body.
```
Example email
From: ABC <abc@outlook.com>
Sent: Monday, 5 October 2020 10:54 AM
To: BCD <bcd@outlook.com>
Subject: Files
```

The password is: ......
There can be 10 emails and 2 have password-protected files do I let the robot know which files are password protected and to open the password-protected Excel file and move the data to a mega Excel sheet containing all the files from the 10 emails.
I am unsure of the activities to put in the workflow to perform these functions.
I am also unsure if the below method I did is the right way to approach this.



[](https://i.stack.imgur.com/JSzlm.png) | 2020/10/05 | [
"https://Stackoverflow.com/questions/64205692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14393022/"
] | You have to save the object first then split the tag values by comma and then add the tags into the field of your object this way. I have added the comments for your understanding.
**Views.py
Uploading Posts( views.py )**
```py
@login_required(login_url="/login/")
def post_upload(request):
index1 = Blog.objects.all().order_by('-time')[0]
content = request.POST.get('content')
title = request.POST.get('title')
image = request.FILES.get('image')
if request.method == 'POST':
post_form = PostUpload(request.POST, request.FILES, instance=request.user)
if post_form.is_valid():
tags = post_form.cleaned_data['tags']
context = post_form.cleaned_data['context']
excerpt_type = post_form.cleaned_data['excerpt_type']
# Removed tags=tags from the below line
# Also, if you want to use `save` then you don't want to use
# `create` as it will persist into your db right away.
# Simply create an instance of Blog
ins = Blog(user=request.user, content=content, title=title,
image=image, context=context,
excerpt_type=excerpt_type)
# Adding tags against the object field after the object creation
for tag in tags:
ins.tags.add(tag)
ins.save()
messages.success(request, 'Your Post has been successfully posted')
print(request.POST)
print(tags)
return HttpResponseRedirect(reverse('post_upload'))
else:
print(f'error in {request.POST}')
else:
post_form = PostUpload(instance=request.user)
context = {'post_form': post_form, 'index1': index1}
return render(request, 'post_upload.html', context)
``` | Inside `post_upload` method, are you sure you need `instance=request.user` to create a `post_form` object? |
37,460,746 | I am currently trying to handle exceptions and errors in a NodeJS app which will be used for critical information. I need a clean error management !
I've been wondering if there is something similar to Java Exceptions encapsulation.
I'm explaning.
In Java you can do something like that :
```
try {
// something that throws Exception
} catch (Throwable t) {
throw new Exception("My message", t);
}
```
That allows you to decide when to log your exception and you get the whole stack trace and call path !
I would like to know if there is a way to do the same in NodeJS because logging at every step seems not to be the right way of doing things.
Thank you. | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2520098/"
] | You should look at this module :
<https://www.npmjs.com/package/verror>
Joyent quote it on his error management best pratices : <https://www.joyent.com/developers/node/design/errors>
>
> At Joyent, we use the verror module to wrap errors since it's
> syntactically concise. As of this writing, it doesn't quite do all of
> this yet, but it will be extended to do so.
>
>
>
It allow you to get details on error message. And tracking the step of the error.
And also hide details to the client with wrapped error : WError() who returns only the last error message. | You should be able to do something like:
```
funtion exception(message, error) {
this.message = message;
this.stacktrace = error.stack;
}
try {
if(someData == false)
throw new exception("something went wrong!", new Error());
}
catch(ex) {
console.log(ex.message);
console.log(ex.stacktrace);
}
```
You can then throw your own custom exception instance containing whatever debugging info you need.
EDIT: added stack trace to exception object |
37,460,746 | I am currently trying to handle exceptions and errors in a NodeJS app which will be used for critical information. I need a clean error management !
I've been wondering if there is something similar to Java Exceptions encapsulation.
I'm explaning.
In Java you can do something like that :
```
try {
// something that throws Exception
} catch (Throwable t) {
throw new Exception("My message", t);
}
```
That allows you to decide when to log your exception and you get the whole stack trace and call path !
I would like to know if there is a way to do the same in NodeJS because logging at every step seems not to be the right way of doing things.
Thank you. | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2520098/"
] | I answer my own question to explain what i finaly did to have the wanted encapsulation.
I used <https://www.npmjs.com/package/verror> as Sachacr suggested.
Then I extended it that way :
my\_error.js :
```
var VError = require('verror');
var _ = require('lodash');
function MyError() {
var args = [];
var httpErrorCode;
var cause;
if (arguments.length > 0) {
var lastArgumentIndex = [arguments.length];
cause = manageCause(lastArgumentIndex, arguments);
httpErrorCode = manageHttpCode(lastArgumentIndex, arguments);
for (var i = 0; i < lastArgumentIndex; i++) {
args[i] = arguments[i];
}
}
this.__proto__.__proto__.constructor.apply(this, args);
if (cause) {
if (this.stack) {
this.stack += '\n' + cause.stack;
} else {
this.stack = cause.stack;
}
}
this.httpErrorCode = httpErrorCode;
}
MyError.prototype.__proto__ = VError.prototype;
function manageCause(lastArgumentIndex, arguments) {
if (lastArgumentIndex[0] > 0
&& arguments[lastArgumentIndex[0] - 1] instanceof Error) {
lastArgumentIndex[0]--;
return arguments[lastArgumentIndex[0]];
}
}
function manageHttpCode(lastArgumentIndex, arguments) {
if (lastArgumentIndex[0] > 0
&& _.isNumber(arguments[lastArgumentIndex[0] - 1])) {
lastArgumentIndex[0]--;
return arguments[lastArgumentIndex[0]];
}
}
module.exports = MyError;
```
It allows me to use it easily in my code :
```
var MyError = require('./my_error.js');
function withErrors() {
try {
// something with errors
} catch (err) {
// This is the same pattern as VError
return new MyError("My message", err, 401);
}
}
function somethingToDo(req, res) {
var result = withErrors();
if (result instanceof MyError) {
logger.warn(result);
res.status(result.httpErrorCode).send(result.message).end();
return
}
}
```
That way, i hace a nice stack trace with call path and every line involved in error/exception.
Hope it will help people, cause i searched a looooong time :)
EDIT : I modified my MyError class to add HTTP Error codes and clean arguments management. | You should be able to do something like:
```
funtion exception(message, error) {
this.message = message;
this.stacktrace = error.stack;
}
try {
if(someData == false)
throw new exception("something went wrong!", new Error());
}
catch(ex) {
console.log(ex.message);
console.log(ex.stacktrace);
}
```
You can then throw your own custom exception instance containing whatever debugging info you need.
EDIT: added stack trace to exception object |
37,460,746 | I am currently trying to handle exceptions and errors in a NodeJS app which will be used for critical information. I need a clean error management !
I've been wondering if there is something similar to Java Exceptions encapsulation.
I'm explaning.
In Java you can do something like that :
```
try {
// something that throws Exception
} catch (Throwable t) {
throw new Exception("My message", t);
}
```
That allows you to decide when to log your exception and you get the whole stack trace and call path !
I would like to know if there is a way to do the same in NodeJS because logging at every step seems not to be the right way of doing things.
Thank you. | 2016/05/26 | [
"https://Stackoverflow.com/questions/37460746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2520098/"
] | I answer my own question to explain what i finaly did to have the wanted encapsulation.
I used <https://www.npmjs.com/package/verror> as Sachacr suggested.
Then I extended it that way :
my\_error.js :
```
var VError = require('verror');
var _ = require('lodash');
function MyError() {
var args = [];
var httpErrorCode;
var cause;
if (arguments.length > 0) {
var lastArgumentIndex = [arguments.length];
cause = manageCause(lastArgumentIndex, arguments);
httpErrorCode = manageHttpCode(lastArgumentIndex, arguments);
for (var i = 0; i < lastArgumentIndex; i++) {
args[i] = arguments[i];
}
}
this.__proto__.__proto__.constructor.apply(this, args);
if (cause) {
if (this.stack) {
this.stack += '\n' + cause.stack;
} else {
this.stack = cause.stack;
}
}
this.httpErrorCode = httpErrorCode;
}
MyError.prototype.__proto__ = VError.prototype;
function manageCause(lastArgumentIndex, arguments) {
if (lastArgumentIndex[0] > 0
&& arguments[lastArgumentIndex[0] - 1] instanceof Error) {
lastArgumentIndex[0]--;
return arguments[lastArgumentIndex[0]];
}
}
function manageHttpCode(lastArgumentIndex, arguments) {
if (lastArgumentIndex[0] > 0
&& _.isNumber(arguments[lastArgumentIndex[0] - 1])) {
lastArgumentIndex[0]--;
return arguments[lastArgumentIndex[0]];
}
}
module.exports = MyError;
```
It allows me to use it easily in my code :
```
var MyError = require('./my_error.js');
function withErrors() {
try {
// something with errors
} catch (err) {
// This is the same pattern as VError
return new MyError("My message", err, 401);
}
}
function somethingToDo(req, res) {
var result = withErrors();
if (result instanceof MyError) {
logger.warn(result);
res.status(result.httpErrorCode).send(result.message).end();
return
}
}
```
That way, i hace a nice stack trace with call path and every line involved in error/exception.
Hope it will help people, cause i searched a looooong time :)
EDIT : I modified my MyError class to add HTTP Error codes and clean arguments management. | You should look at this module :
<https://www.npmjs.com/package/verror>
Joyent quote it on his error management best pratices : <https://www.joyent.com/developers/node/design/errors>
>
> At Joyent, we use the verror module to wrap errors since it's
> syntactically concise. As of this writing, it doesn't quite do all of
> this yet, but it will be extended to do so.
>
>
>
It allow you to get details on error message. And tracking the step of the error.
And also hide details to the client with wrapped error : WError() who returns only the last error message. |
6,538 | I'm studying for my Technician license, and listening in to HF, VHF and UHF bands just to get a feel for how to work with frequencies, squelch, antennas, etc. Had something happen today that I couldn't explain. I was doing a scan through the 70cm band, running from 400MHz to 480MHz, and at 450.040 I picked up a local AM radio station. I checked the radio station website and they only broadcast on 1520 KHz. How did I receive that signal on such a different frequency? I wasn't even working with a very powerful antenna, just a Baofeng UV5R. My first thought was that perhaps the local signal was just so powerful it overcame my radio reception. But if that's the case, why did it happen just on that one frequency? I was scanning other frequencies through the day and didn't have it happen on any other frequency. I also checked to see if we had any nearby repeaters at that frequency but we don't; nearest frequency for a regional repeater is 444.9750. Thanks. | 2016/08/14 | [
"https://ham.stackexchange.com/questions/6538",
"https://ham.stackexchange.com",
"https://ham.stackexchange.com/users/8164/"
] | >
> at 450.040 I picked up a local AM radio station
>
>
>
I am sure you picked up a transmission
>
> just a Baofeng UV5R
>
>
>
But not with that radio, or at least not AM
You either:
* Picked up a signal which is indeed AM, but then it would not be very distorted as the radio you are using only has FM (de)modulation.
or:
* Picked up something else.
If the audio received was not distorted (so then it must be FM), and clearly the same 'program' as the said AM station on 1520 KHz. Then it is very likely this is a "studio to transmitter link/feed" that you picked up. (as detailed in the comments already)
**But to give you the official answer:**
You are **not** picking up an **AM** transmission originally on **1520 KHz**, on **450.040 MHz** with an **Baofeng UV5R** radio. *That would be quite impossible*
:-) | The 450-451 MHz band is often used by news media, broadcast TV and AM radio. They use it for communications between the station and the news vans, or between the station and the traffic helicopters. In addition, they use it for something called [Interruptible foldback](https://en.wikipedia.org/wiki/Interruptible_foldback) which is a stream containing the programming and occasionally commands from the studio to the "reporter on the scene". I hear these often, and it's just minutes and minutes of broadcast programming that suddenly stops.
I Googled and found some exact listings for the Boston media market - your area will have different frequencies but used for a similar purpose. <http://scan-ne.net/wiki/index.php?title=Media_and_Fire_Buff>
This can be handy to listen to, if you get traffic reports direct from the helicopter during rush hour! |
6,538 | I'm studying for my Technician license, and listening in to HF, VHF and UHF bands just to get a feel for how to work with frequencies, squelch, antennas, etc. Had something happen today that I couldn't explain. I was doing a scan through the 70cm band, running from 400MHz to 480MHz, and at 450.040 I picked up a local AM radio station. I checked the radio station website and they only broadcast on 1520 KHz. How did I receive that signal on such a different frequency? I wasn't even working with a very powerful antenna, just a Baofeng UV5R. My first thought was that perhaps the local signal was just so powerful it overcame my radio reception. But if that's the case, why did it happen just on that one frequency? I was scanning other frequencies through the day and didn't have it happen on any other frequency. I also checked to see if we had any nearby repeaters at that frequency but we don't; nearest frequency for a regional repeater is 444.9750. Thanks. | 2016/08/14 | [
"https://ham.stackexchange.com/questions/6538",
"https://ham.stackexchange.com",
"https://ham.stackexchange.com/users/8164/"
] | I was trying to research some info and I came across your thread.
My guess is they took the audio output from the 1520 kHz tuner and fed it in the input of a 450.040 MHz transmitter. That's why it can be heard in the UHF region. In this way, FM or AM or frequency doesn't matter, because its only an audio feed from an 1520 kHz tuner. You could have listen to a 1520 kHz tuner and a 450.040 MHz tuner at the same time. There should be a delay between the two tuners, I would guess. | The 450-451 MHz band is often used by news media, broadcast TV and AM radio. They use it for communications between the station and the news vans, or between the station and the traffic helicopters. In addition, they use it for something called [Interruptible foldback](https://en.wikipedia.org/wiki/Interruptible_foldback) which is a stream containing the programming and occasionally commands from the studio to the "reporter on the scene". I hear these often, and it's just minutes and minutes of broadcast programming that suddenly stops.
I Googled and found some exact listings for the Boston media market - your area will have different frequencies but used for a similar purpose. <http://scan-ne.net/wiki/index.php?title=Media_and_Fire_Buff>
This can be handy to listen to, if you get traffic reports direct from the helicopter during rush hour! |
12,149,070 | I am writing a script to launch remote desktop sessions using rdesktop. The relevant portion of the code looks like this:
```
subprocess.call(["rdesktop", "-a 16", "-u user", "-g 1280x1024",, server])
```
When this happens, the terminal is locked up until I exit the rdesktop session. Would it be possible to launch multiple desktop sessions with this script? | 2012/08/27 | [
"https://Stackoverflow.com/questions/12149070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1290192/"
] | `subprocess.Popen` ([py2 docs](https://docs.python.org/2/library/subprocess.html#subprocess.Popen), [py3 docs](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)) is the correct answer here.
`subprocess.call` waits for the command to complete, while `subprocess.Popen` calls it in the background, and immediately executes the next line. | You can fork the python process or use threads, or run the process in the background. |
42,256,412 | I'd like to use Entity Framework to return data from 2 tables, and a selection of columns of the 2 tables, at first I was not having much luck with something simple, like returning int's and strings (ie. `select new { id = t1.ID, other = t2.OtherData }`, as casting that anonymous type was cumbersome at the destination (destination being my winform), so I struck on the idea to just return both table rows...
So something like this :
```
public static IQueryable<{Table1,Table2}> byRecID(Guid recID, MyContext DBContext)
{
return (from i1 in DBContext.Table1
join j1 in DBContext.Table2 on i1.GroupID equals j1.GroupID
where i1.RecID.Equals(RecID)
select new { i1, j1 }).SingleOrDefault();
}
```
This is all fine EXCEPT the return type of the method is incorrect. I've tried a few combinations. Unfortunately, when I call "byRecID" from the winform, "SingleOrDefault" is not available, but IS available inside 'byRecID' method, so I can't just return `IQueryable`, needs to be the typed `IQueryable<SOMETHING IN HERE>` (because `SingleOrDefault` not an extension of `IQueryable`, only `IQueryable<T>`).
My Question... is there a syntax for 'SOMETHING IN HERE' that lets me specify its a join of two table rows?
and I'm wondering... Why is SingleOrDefault an option INSIDE the method but not an option of the result of the method when called from my winform?
Basically I was hoping for something that allows clean data calls from my winforms, without casting to hideous anonymous types then using reflection (like when I returned anonymous type of primitives), but also don't want to spawn a Type just for use by my `byRecID` method. | 2017/02/15 | [
"https://Stackoverflow.com/questions/42256412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/858282/"
] | In C# anonymous types are best used in the scope of the same method where you project them. As you have seen for your self **they can't be used outside of the defining method**. So you can't return anonymous types from methods (and keep their structure, you can always return them as objects, but this is not good idea) this makes your **syntax of the method invalid**.
Best option is to project the result to class specified for your needs.
```
public class TableJoinResult
{
public Table1 Table1 { get; set; }
public Table2 Table2 { get; set; }
}
```
**Your query:**
```
public static IQueryable<TableJoinResult> byRecID(Guid recID, MyContext DBContext)
{
return (from i1 in DBContext.Table1
join j1 in DBContext.Table2 on i1.GroupID equals j1.GroupID
where i1.RecID.Equals(RecID)
select new TableJoinResult { Table1= i1, Table2 = j1 }).SingleOrDefault();
}
```
**More info on anonymous types**: <https://msdn.microsoft.com/en-us/library/bb397696.aspx> | 1)Create a specific class that describes you result.
2)See 1 |
42,256,412 | I'd like to use Entity Framework to return data from 2 tables, and a selection of columns of the 2 tables, at first I was not having much luck with something simple, like returning int's and strings (ie. `select new { id = t1.ID, other = t2.OtherData }`, as casting that anonymous type was cumbersome at the destination (destination being my winform), so I struck on the idea to just return both table rows...
So something like this :
```
public static IQueryable<{Table1,Table2}> byRecID(Guid recID, MyContext DBContext)
{
return (from i1 in DBContext.Table1
join j1 in DBContext.Table2 on i1.GroupID equals j1.GroupID
where i1.RecID.Equals(RecID)
select new { i1, j1 }).SingleOrDefault();
}
```
This is all fine EXCEPT the return type of the method is incorrect. I've tried a few combinations. Unfortunately, when I call "byRecID" from the winform, "SingleOrDefault" is not available, but IS available inside 'byRecID' method, so I can't just return `IQueryable`, needs to be the typed `IQueryable<SOMETHING IN HERE>` (because `SingleOrDefault` not an extension of `IQueryable`, only `IQueryable<T>`).
My Question... is there a syntax for 'SOMETHING IN HERE' that lets me specify its a join of two table rows?
and I'm wondering... Why is SingleOrDefault an option INSIDE the method but not an option of the result of the method when called from my winform?
Basically I was hoping for something that allows clean data calls from my winforms, without casting to hideous anonymous types then using reflection (like when I returned anonymous type of primitives), but also don't want to spawn a Type just for use by my `byRecID` method. | 2017/02/15 | [
"https://Stackoverflow.com/questions/42256412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/858282/"
] | 1)Create a specific class that describes you result.
2)See 1 | I wanted to avoid creating a specific class or a struct.
The below is a lengthy way that avoids creating a struct/class.
So I did this in my service class:-
```
List<KeyValuePair<string,int>> IWorkflowService.GetServiceRetention()
{
var serviceRetention = from y in _context.SERVICES
join z in _context.SERVICE_SETTINGS on y.ID equals z.SERVICEID
select new { Service= y.SERVICE, Retention=z.RETENTION };//new KeyValuePair<string,int?>( y.SERVICE, z.RETENTION ));
var list = new List<KeyValuePair<string, int>>();
foreach (var obj in serviceRetention)
{
list.Add(new KeyValuePair<string, int>(obj.Service,Convert.ToInt32(obj.Retention)));
}
return list;
}
```
I had to do this in my controller class:
```
List<KeyValuePair<string, int>> c = _service.GetServiceRetention();
foreach (var obj in c)
{
//The key contains service and value contains Rtention.
RecurringJob.AddOrUpdate(DELETE_SERVICE + obj.Key, () =>
Delete(obj.Key), //this is my function that does the actual process
Cron.DayInterval(Convert.ToInt32(obj.Value)));
}
```
I am not sure if this is the best way to do it, but works for me. |
42,256,412 | I'd like to use Entity Framework to return data from 2 tables, and a selection of columns of the 2 tables, at first I was not having much luck with something simple, like returning int's and strings (ie. `select new { id = t1.ID, other = t2.OtherData }`, as casting that anonymous type was cumbersome at the destination (destination being my winform), so I struck on the idea to just return both table rows...
So something like this :
```
public static IQueryable<{Table1,Table2}> byRecID(Guid recID, MyContext DBContext)
{
return (from i1 in DBContext.Table1
join j1 in DBContext.Table2 on i1.GroupID equals j1.GroupID
where i1.RecID.Equals(RecID)
select new { i1, j1 }).SingleOrDefault();
}
```
This is all fine EXCEPT the return type of the method is incorrect. I've tried a few combinations. Unfortunately, when I call "byRecID" from the winform, "SingleOrDefault" is not available, but IS available inside 'byRecID' method, so I can't just return `IQueryable`, needs to be the typed `IQueryable<SOMETHING IN HERE>` (because `SingleOrDefault` not an extension of `IQueryable`, only `IQueryable<T>`).
My Question... is there a syntax for 'SOMETHING IN HERE' that lets me specify its a join of two table rows?
and I'm wondering... Why is SingleOrDefault an option INSIDE the method but not an option of the result of the method when called from my winform?
Basically I was hoping for something that allows clean data calls from my winforms, without casting to hideous anonymous types then using reflection (like when I returned anonymous type of primitives), but also don't want to spawn a Type just for use by my `byRecID` method. | 2017/02/15 | [
"https://Stackoverflow.com/questions/42256412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/858282/"
] | In C# anonymous types are best used in the scope of the same method where you project them. As you have seen for your self **they can't be used outside of the defining method**. So you can't return anonymous types from methods (and keep their structure, you can always return them as objects, but this is not good idea) this makes your **syntax of the method invalid**.
Best option is to project the result to class specified for your needs.
```
public class TableJoinResult
{
public Table1 Table1 { get; set; }
public Table2 Table2 { get; set; }
}
```
**Your query:**
```
public static IQueryable<TableJoinResult> byRecID(Guid recID, MyContext DBContext)
{
return (from i1 in DBContext.Table1
join j1 in DBContext.Table2 on i1.GroupID equals j1.GroupID
where i1.RecID.Equals(RecID)
select new TableJoinResult { Table1= i1, Table2 = j1 }).SingleOrDefault();
}
```
**More info on anonymous types**: <https://msdn.microsoft.com/en-us/library/bb397696.aspx> | I wanted to avoid creating a specific class or a struct.
The below is a lengthy way that avoids creating a struct/class.
So I did this in my service class:-
```
List<KeyValuePair<string,int>> IWorkflowService.GetServiceRetention()
{
var serviceRetention = from y in _context.SERVICES
join z in _context.SERVICE_SETTINGS on y.ID equals z.SERVICEID
select new { Service= y.SERVICE, Retention=z.RETENTION };//new KeyValuePair<string,int?>( y.SERVICE, z.RETENTION ));
var list = new List<KeyValuePair<string, int>>();
foreach (var obj in serviceRetention)
{
list.Add(new KeyValuePair<string, int>(obj.Service,Convert.ToInt32(obj.Retention)));
}
return list;
}
```
I had to do this in my controller class:
```
List<KeyValuePair<string, int>> c = _service.GetServiceRetention();
foreach (var obj in c)
{
//The key contains service and value contains Rtention.
RecurringJob.AddOrUpdate(DELETE_SERVICE + obj.Key, () =>
Delete(obj.Key), //this is my function that does the actual process
Cron.DayInterval(Convert.ToInt32(obj.Value)));
}
```
I am not sure if this is the best way to do it, but works for me. |
21,466,277 | I have this code:
```
var json = Newtonsoft.Json.Linq.JObject.Parse("{items:"+response.Content+"}");
Console.WriteLine(json.Count);
var items = (JArray)json["items"];
for (int i = 0; i < items.Count; i++) {
Console.WriteLine("ae");
Console.WriteLine((JObject)items[i]);
}
```
Here is the response.Content i have:
```
[{"IdUva":36,"Uva":"TESTES","IdPais":249,"Pais":"Australia","IdProduto":5114,"Descricao":"ABEL PINCHARD COTES DU RHONE","Estoque":-467700.801,"idVinhoDetalhes":84,"Produtor":"TEST","Regiao":"TESTE","Tipo":"BRANCO","Safra":"2011","Teor":99.00,"FichaTecnica":"FHGFGHFFJHFJFJHGFJFJHF","Servico":"FRANGO","Mapa":"Koala.jpg","Foto":"Chrysanthemum.jpg","Preco":1.00,"CodigoPais":36,"Bandeira":"Australia.png"}]
```
I need a way to like add each of the fields that i have in each object in a database.
For example i need to say like var wineId = (JObject)items[i].WineID;
I need to get the values of the fields that i want... how can i do that? | 2014/01/30 | [
"https://Stackoverflow.com/questions/21466277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120770/"
] | How about this way (XSLT 1.0):
```
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:variable name="file2" select="document('b.xml')" />
<xsl:variable name="IDs1" select="/cases/no/@sort" />
<xsl:variable name="IDs2" select="$file2/cases/no/@sort" />
<xsl:template match="/cases">
<cases>
<xsl:apply-templates select="no[not(@sort=$IDs2)]"/>
<xsl:apply-templates select="$file2/cases/no[not(@sort=$IDs1)]"/>
</cases>
</xsl:template>
<xsl:template match="no">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
```
You need to apply the stylesheet to your "a.xml " file and make sure "b.xml " is in the same directory. | If you websearch "xml diff", you'll find past versions of tools that compare XML documents and output their differences as an XML document See also <https://stackoverflow.com/questions/1871076/are-there-any-free-xml-diff-merge-tools-available> |
21,466,277 | I have this code:
```
var json = Newtonsoft.Json.Linq.JObject.Parse("{items:"+response.Content+"}");
Console.WriteLine(json.Count);
var items = (JArray)json["items"];
for (int i = 0; i < items.Count; i++) {
Console.WriteLine("ae");
Console.WriteLine((JObject)items[i]);
}
```
Here is the response.Content i have:
```
[{"IdUva":36,"Uva":"TESTES","IdPais":249,"Pais":"Australia","IdProduto":5114,"Descricao":"ABEL PINCHARD COTES DU RHONE","Estoque":-467700.801,"idVinhoDetalhes":84,"Produtor":"TEST","Regiao":"TESTE","Tipo":"BRANCO","Safra":"2011","Teor":99.00,"FichaTecnica":"FHGFGHFFJHFJFJHGFJFJHF","Servico":"FRANGO","Mapa":"Koala.jpg","Foto":"Chrysanthemum.jpg","Preco":1.00,"CodigoPais":36,"Bandeira":"Australia.png"}]
```
I need a way to like add each of the fields that i have in each object in a database.
For example i need to say like var wineId = (JObject)items[i].WineID;
I need to get the values of the fields that i want... how can i do that? | 2014/01/30 | [
"https://Stackoverflow.com/questions/21466277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120770/"
] | If you websearch "xml diff", you'll find past versions of tools that compare XML documents and output their differences as an XML document See also <https://stackoverflow.com/questions/1871076/are-there-any-free-xml-diff-merge-tools-available> | If I need to compare 2 XML files and see quickly the differences between them I sort the files using XSLT and then compare the two xml files manually by using WinMerge for example (a simple unix diff can also do the job). If you want to output the differences you can follow the method given by @keshlam
Here is the XSLT that sort my XML files :
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*">
<xsl:sort select="name()" />
<xsl:sort select="@*" />
<xsl:sort select="*" />
<xsl:sort select="text()" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
``` |
21,466,277 | I have this code:
```
var json = Newtonsoft.Json.Linq.JObject.Parse("{items:"+response.Content+"}");
Console.WriteLine(json.Count);
var items = (JArray)json["items"];
for (int i = 0; i < items.Count; i++) {
Console.WriteLine("ae");
Console.WriteLine((JObject)items[i]);
}
```
Here is the response.Content i have:
```
[{"IdUva":36,"Uva":"TESTES","IdPais":249,"Pais":"Australia","IdProduto":5114,"Descricao":"ABEL PINCHARD COTES DU RHONE","Estoque":-467700.801,"idVinhoDetalhes":84,"Produtor":"TEST","Regiao":"TESTE","Tipo":"BRANCO","Safra":"2011","Teor":99.00,"FichaTecnica":"FHGFGHFFJHFJFJHGFJFJHF","Servico":"FRANGO","Mapa":"Koala.jpg","Foto":"Chrysanthemum.jpg","Preco":1.00,"CodigoPais":36,"Bandeira":"Australia.png"}]
```
I need a way to like add each of the fields that i have in each object in a database.
For example i need to say like var wineId = (JObject)items[i].WineID;
I need to get the values of the fields that i want... how can i do that? | 2014/01/30 | [
"https://Stackoverflow.com/questions/21466277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3120770/"
] | How about this way (XSLT 1.0):
```
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
<xsl:variable name="file2" select="document('b.xml')" />
<xsl:variable name="IDs1" select="/cases/no/@sort" />
<xsl:variable name="IDs2" select="$file2/cases/no/@sort" />
<xsl:template match="/cases">
<cases>
<xsl:apply-templates select="no[not(@sort=$IDs2)]"/>
<xsl:apply-templates select="$file2/cases/no[not(@sort=$IDs1)]"/>
</cases>
</xsl:template>
<xsl:template match="no">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
```
You need to apply the stylesheet to your "a.xml " file and make sure "b.xml " is in the same directory. | If I need to compare 2 XML files and see quickly the differences between them I sort the files using XSLT and then compare the two xml files manually by using WinMerge for example (a simple unix diff can also do the job). If you want to output the differences you can follow the method given by @keshlam
Here is the XSLT that sort my XML files :
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="UTF-8"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*">
<xsl:sort select="name()" />
<xsl:sort select="@*" />
<xsl:sort select="*" />
<xsl:sort select="text()" />
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
``` |
18,530,706 | Let's say I have this function:
```
void changeMap(Player* player, int map) {
player->setMap(map);
}
```
And I want a timer class that enables me to run that function after a certain amount of time, Something like this.
```
Player* chr;
int mapid = 300;
int milliseconds = 6000;
Timer.Schedule(changeMap(chr, 300), milliseconds);
```
Thanks in advance. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18530706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2561241/"
] | If this is a game loop then one way is to keep of list of events that you want to happen some time in the future where you store a time and a pointer to the function you want to call. (Or a std::function, or whatever). Keep the list sorted by time so the soonest event is a the top of the list.
Then in your main game loop, every loop, check the top of the list to see if the time of that event has been reached yet and if it has pop the event and call the function. | You can achieve the desired effect by the liberal use of Functor delegate objects and templates:
CAlarm.h
```
#ifndef CALARM_H
#define CALARM_H
#include "ADTtime.h"
#include "CStopwatch.h"
template<class FunctionObject>
class Alarm : public StopWatch {
public:
Alarm(const FunctionObject& fn);
Alarm(double tickTime, const FunctionObject& fn);
virtual ~Alarm();
FunctionObject Tick();
protected:
FunctionObject _delegate;
double _tickTime;
private:
};
template<class FunctionObject>
Alarm<FunctionObject>::Alarm(const FunctionObject& fn)
: StopWatch(), _delegate(fn), _tickTime(1.0) { }
template<class FunctionObject>
Alarm<FunctionObject>::Alarm(double tickTime, const FunctionObject& fn)
: StopWatch(), _delegate(fn), _tickTime(tickTime) { }
template<class FunctionObject>
Alarm<FunctionObject>::~Alarm() {
if(_isRunning) Stop();
}
template<class FunctionObject>
FunctionObject Alarm<FunctionObject>::Tick() {
if(IsRunning() == false) return _delegate;
if(GetElapsedTimeInSeconds() >= _tickTime) {
Reset();
_delegate();
}
return _delegate;
}
#endif
```
CStopwatch.h
```
#ifndef CSTOPWATCH_H
#define CSTOPWATCH_H
#include "ADTtime.h"
class StopWatch : public ADTTime {
public:
StopWatch();
virtual ~StopWatch();
void Start();
void Restart();
void Stop();
void Reset();
virtual void CalculateElapsedTime();
virtual double GetElapsedTimeInSeconds();
virtual double GetElapsedTimeInMilliseconds();
protected:
private:
};
#endif
```
CStopwatch.cpp
```
#include "CStopwatch.h"
StopWatch::StopWatch() : ADTTime() {
/* DO NOTHING. ALL INITIALIZATION HAPPENS IN BASE CLASS */
}
StopWatch::~StopWatch() {
_startTime = -1;
_endTime = -1;
_deltaTime = -1.0;
_isRunning = false;
}
void StopWatch::Start() {
if(_isRunning == true) return;
_startTime = clock();
_isRunning = true;
}
void StopWatch::Stop() {
if(_isRunning == false) return;
_isRunning = false;
CalculateElapsedTime();
}
void StopWatch::Restart() {
Reset();
Start();
}
void StopWatch::Reset() {
Stop();
_startTime = 0;
_endTime = 0;
_deltaTime = 0.0;
}
void StopWatch::CalculateElapsedTime() {
_endTime = clock();
_deltaTime = difftime(_startTime, _endTime);
}
double StopWatch::GetElapsedTimeInSeconds() {
CalculateElapsedTime();
return -ADTTime::GetElapsedTimeInSeconds();
}
double StopWatch::GetElapsedTimeInMilliseconds() {
CalculateElapsedTime();
return -ADTTime::GetElapsedTimeInMilliseconds();
}
```
ADTTime.h
```
#ifndef ADTTIME_H
#define ADTTIME_H
#include <ctime>
class ADTTime {
public:
clock_t GetStartTime() const;
clock_t GetStartTime();
double GetStartTimeInSeconds() const;
double GetStartTimeInSeconds();
clock_t GetEndTime() const;
clock_t GetEndTime();
double GetEndTimeInSeconds() const;
double GetEndTimeInSeconds();
virtual double GetElapsedTimeInSeconds();
virtual double GetElapsedTimeInMilliseconds();
virtual void CalculateElapsedTime()=0;
bool IsRunning() const;
bool IsRunning();
virtual void Start()=0;
virtual void Restart()=0;
virtual void Stop()=0;
virtual void Reset()=0;
ADTTime();
virtual ~ADTTime();
protected:
bool _isRunning;
clock_t _startTime;
clock_t _endTime;
double _deltaTime;
private:
};
#endif
```
CADTTime.cpp
```
#include "ADTtime.h"
clock_t ADTTime::GetStartTime() const {
return _startTime;
}
clock_t ADTTime::GetStartTime() {
return static_cast<const ADTTime&>(*this).GetStartTime();
}
double ADTTime::GetStartTimeInSeconds() const {
return static_cast<double>((_startTime / CLOCKS_PER_SEC));
}
double ADTTime::GetStartTimeInSeconds() {
return static_cast<const ADTTime&>(*this).GetStartTimeInSeconds();
}
clock_t ADTTime::GetEndTime() const {
return _endTime;
}
clock_t ADTTime::GetEndTime() {
return static_cast<const ADTTime&>(*this).GetEndTime();
}
double ADTTime::GetEndTimeInSeconds() const {
return static_cast<double>((_endTime / CLOCKS_PER_SEC));
}
double ADTTime::GetEndTimeInSeconds() {
return static_cast<const ADTTime&>(*this).GetEndTimeInSeconds();
}
double ADTTime::GetElapsedTimeInSeconds() {
return _deltaTime / CLOCKS_PER_SEC;
}
double ADTTime::GetElapsedTimeInMilliseconds() {
return _deltaTime;
}
bool ADTTime::IsRunning() const {
return _isRunning;
}
bool ADTTime::IsRunning() {
return static_cast<const ADTTime&>(*this).IsRunning();
}
ADTTime::ADTTime() : _isRunning(false), _startTime(-1), _endTime(-1), _deltaTime(-1.0) { }
ADTTime::~ADTTime() {
_isRunning = false;
_startTime = -1;
_endTime = -1;
_deltaTime = -1.0;
}
``` |
18,530,706 | Let's say I have this function:
```
void changeMap(Player* player, int map) {
player->setMap(map);
}
```
And I want a timer class that enables me to run that function after a certain amount of time, Something like this.
```
Player* chr;
int mapid = 300;
int milliseconds = 6000;
Timer.Schedule(changeMap(chr, 300), milliseconds);
```
Thanks in advance. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18530706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2561241/"
] | If this is a game loop then one way is to keep of list of events that you want to happen some time in the future where you store a time and a pointer to the function you want to call. (Or a std::function, or whatever). Keep the list sorted by time so the soonest event is a the top of the list.
Then in your main game loop, every loop, check the top of the list to see if the time of that event has been reached yet and if it has pop the event and call the function. | Since you are running on Windows OS, I don't understand why are you reinventing the wheel?
```
CComPtr<IReferenceClock> pReferenceClock;
HRESULT hr = CoCreateInstance( CLSID_SystemClock, NULL, CLSCTX_INPROC_SERVER, IID_IReferenceClock, (void**)&pReferenceClock );
hr = pReferenceClock->AdviseTime( ... );
// or, hr = pReferenceClock->AdvisePeriodic( ... );
```
and once you are done,
```
hr = pReferenceClock->Unadvise( adviseCookie );
``` |
18,530,706 | Let's say I have this function:
```
void changeMap(Player* player, int map) {
player->setMap(map);
}
```
And I want a timer class that enables me to run that function after a certain amount of time, Something like this.
```
Player* chr;
int mapid = 300;
int milliseconds = 6000;
Timer.Schedule(changeMap(chr, 300), milliseconds);
```
Thanks in advance. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18530706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2561241/"
] | If this is a game loop then one way is to keep of list of events that you want to happen some time in the future where you store a time and a pointer to the function you want to call. (Or a std::function, or whatever). Keep the list sorted by time so the soonest event is a the top of the list.
Then in your main game loop, every loop, check the top of the list to see if the time of that event has been reached yet and if it has pop the event and call the function. | You can implement a simple (perhaps a bit rough around the edges) function that fire off a one-off event, like a timer, after a specified amount of milliseconds, using `std::thread` and `std::chrono` facilities
Something like that:
```
void doAfter( const std::function<void(void)>& f,
size_t intervalMs )
{
std::thread t{[f, intervalMs] () -> void
{
auto chronoInterval = std::chrono::milliseconds( intervalMs );
std::this_thread::sleep_for( chronoInterval );
f();
}
};
// You can either `t.detach()` the thread, or wait to `join` it in main
}
``` |
46,686,328 | I have a dialog containing two combo boxes, one owner draw and one non owner draw.
This is how they are defined in the .rc file:
```
COMBOBOX IDC_COMBO2,149,49,77,73,
CBS_DROPDOWNLIST | CBS_OWNERDRAWFIXED | CBS_SORT | VS_VSCROLL
COMBOBOX IDC_COMBO3,237,49,48,30,
CBS_DROPDOWNLIST CBS_SORT | WS_VSCROLL
```
They have exactly the same height in the .rc file, but the owner draw one (the one on the left side) is slightly higher that the non owner drawn one:
[](https://i.stack.imgur.com/xtVFj.png). | 2017/10/11 | [
"https://Stackoverflow.com/questions/46686328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/898348/"
] | First the given height in the resource is the height of the combo box in the dropped down state.
This behavior is by
design. The size of the combobox item height is I believe determined by
the font height of the font assigned to the control.
With an owner-draw combobox the system has no idea so it sends you a
WM\_MEASUREITEM initialized with the default size of the combobox (probably
depending on the system font rather than the gui font).
So you need to handle WM\_MEASUREITEM in the parent dialog...
Something like this might help (code not validated against a compiler):
```
void CMyDlg::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
CClientDC dc(this);
CFont* pFont = GetFont();
CFont* pFontPrev = NULL;
if (pFont != NULL)
pFontPrev = dc.SelectObject(pFont);
int iborder = ::GetSystemMetrics(SM_CYBORDER);
CSize sz = dc.GetTextExtent(_T("0"));
lpMeasureItemStruct->itemHeight = sz.cy + 2*iborder;
if (pFont != NULL)
dc.SelectObject(pFontPrev);
__super::OnMeasureItem(nIDCtl, lpMeasureItemStruct);
}
``` | The combobox is the most horrible control to work with in Windows when dealing with size and layout. Because it also supports the "simple" style with separate edit and listbox controls always visible it does not use the standard window border/edge styles and instead draws its borders when required.
The height specified when you create the control is actually the size used in the dropped-down state. It forces its own size of the edit control at run-time based on its font. Because so many people got this wrong the themed ComCtl32 v6 implementation makes sure the dropdown size is sane even if you gave it a small size initially.
To match the system you need to try to calculate the required size in `WM_MEASUREITEM` but the exact layout of the default control is of course not documented. It is probably the height of the font + the system metric size of SM\_C\*EDGE and probably some padding.
If you only need a icon next to the text you can use the [ComboBoxEx](https://msdn.microsoft.com/en-us/library/windows/desktop/bb775740(v=vs.85).aspx) control instead. |
27,558,579 | I have a requirement as below:
```
SELECT code from Products
```
* Select code to table Products
* Check length of code; if < 8 auto insert "0" before it to enough 8 character.
Sample:
```
If code is : 1234 => 00001234
12345 => 00012345
..... => xxxxxxxx
```
I want to use a stored procedures in SQL Server 2012 to do it. | 2014/12/19 | [
"https://Stackoverflow.com/questions/27558579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024503/"
] | If the `CODE` field is string, this will work
```
SELECT RIGHT('00000000'+ISNULL(CODE,''),8) from Products
```
If `CODE` is integer then
```
SELECT RIGHT('00000000'+CAST(CODE AS VARCHAR(8)),8) from Products
``` | ```
SELECT
CASE
WHEN LEN(code) < 8 THEN REPLICATE('0', 8 - LEN(code)) + code
ELSE code
END
FROM Products
``` |
27,558,579 | I have a requirement as below:
```
SELECT code from Products
```
* Select code to table Products
* Check length of code; if < 8 auto insert "0" before it to enough 8 character.
Sample:
```
If code is : 1234 => 00001234
12345 => 00012345
..... => xxxxxxxx
```
I want to use a stored procedures in SQL Server 2012 to do it. | 2014/12/19 | [
"https://Stackoverflow.com/questions/27558579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024503/"
] | If the `CODE` field is string, this will work
```
SELECT RIGHT('00000000'+ISNULL(CODE,''),8) from Products
```
If `CODE` is integer then
```
SELECT RIGHT('00000000'+CAST(CODE AS VARCHAR(8)),8) from Products
``` | Do something like this.
1. Use function "CONCAT" your numbers with 000000000 .
2. Use function "RIGHT" to show 8 digits from right to left .
`select right(CONCAT('000000000', 1234),8) as xxx`
Hope its help. |
13,020,328 | I've got a 400+ node munin-1.4.x installation, that I'd like to upgrade to munin-2.x, to take advantage of the CGI based content generation (html & graphs) on the munin master server. I've gone through the official dox ( <http://munin-monitoring.org/wiki/CgiHowto2> ), and its simply not working. It only covers a VirtualHost ( <http://munin.example.com> ), which is not my setup, but I tried to use it as a starting point.
Specifically, I want & need <http://example.com/munin> to be the base URL that dynamically generates the html content listing all the nodes, with links to the individual node pages (which are then dynamically generated/updated when clicked upon). The added catch is that I'm doing this on Fedora(16), and the vast majority of howto's that I've found assume Debian/Ubuntu (or assume non-cgi static content generation via cron).
The official Fedora munin package installs the following:
* munin base directory is /var/www/html/munin
* munin static content direcotry is /var/www/html/munin/static
* munin cgi scripts (munin-cg-graph & munin-cg-html) are in /var/www/html/munin/cgi
What I've done so far:
\* set "html\_strategy cgi" and "cgiurl\_graph /munin/cgi/munin-cgi-html" in /etc/munin/munin.conf
\* Added the following to /etc/httpd/conf/httpd.conf:
```
# Rewrites
RewriteEngine On
Alias /static /var/www/html/munin/static
Alias /munin /var/www/html/munin
# HTML
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} .html$ [or]
RewriteCond %{REQUEST_URI} =/
RewriteRule ^/(.*) /var/www/html/munin/cgi/munin-cgi-html/$1 [L]
# Images
# - remove path to munin-cgi-graph, if present
RewriteRule ^/munin/cgi/munin-cgi-graph/(.*) /$1
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} .png$
RewriteRule ^/(.*) /var/www/html/munin/cgi/munin-cgi-graph/$1 [L]
ScriptAlias /munin/cgi/munin-cgi-graph /var/www/html/munin/cgi/munin-cgi-graph
<Location /munin/cgi/munin-cgi-graph>
Options +ExecCGI FollowSymLinks
<IfModule mod_fcgid.c>
SetHandler fcgi-script
</IfModule>
<IfModule !mod_fcgid.c>
SetHandler cgi-script
</IfModule>
</Location>
ScriptAlias /munin/cgi/munin-cgi-html /var/www/html/munin/cgi/munin-cgi-html
<Location /munin/cgi/munin-cgi-html>
Options +ExecCGI FollowSymLinks
<IfModule mod_fcgid.c>
SetHandler fcgi-script
</IfModule>
<IfModule !mod_fcgid.c>
SetHandler cgi-script
</IfModule>
</Location>
```
However, after doing all that (and restarting apache), when I go to <http://example.com/munin> , I get a 404 error, and in the apache error log I see:
```
File does not exist: /var/www/html/munin/cgi/munin-cgi-html/munin/index.html
```
I'm hoping that i'm just missing something obvious, but right now I'm at a complete loss on what else might need to be adjusted to make this work. thanks. | 2012/10/22 | [
"https://Stackoverflow.com/questions/13020328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179922/"
] | The problem is that, if you use the configuration in a "location" based setup (rather than in a VirtualHost"), the flag for the RewriteRule is wrong.
As per [mod\_rewrite](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) docu:
```
L Stop the rewriting process immediately and don't apply any more rules.
```
However, in your case you want /munin/cgi/munin-cgi-html to be passed on so that the ScriptAlias actually triggers. Thus:
```
PT Forces the resulting URI to be passed back to the URL mapping engine for
processing of other URI-to-filename translators, such as Alias or Redirect
```
If you change your rules to read
```
RewriteRule ^/(.*) /munin/cgi/munin-cgi-html/$1 [PT]
....
RewriteRule ^/(.*) /munin/cgi/munin-cgi-graph/$1 [PT]
```
Note the relative path, as otherwise the ScriptAlias doesn't work. | I had exactly the same problem and I struggled for a while, but I eventually came up with the following config which should do exactly what you want.
My system is Ubuntu Server 12.10. For some reasons my static files are located at /var/cache/munin/www, I'm not sure whether this is standard on Ubuntu or it was caused by my recent upgrade from Ubuntu 12.04.
```
RewriteEngine On
# HTML
RewriteRule ^/munin/(.*\.html)?$ /munin/munin-cgi/munin-cgi-html/$1 [PT]
# Images
RewriteRule ^/munin/munin-cgi/munin-cgi-graph/(.*) /munin/$1
RewriteCond %{REQUEST_URI} !^/static
RewriteRule ^/munin/(.*.png)$ /munin/munin-cgi/munin-cgi-graph/$1 [L,PT]
<Directory /var/cache/munin/www/>
Order deny,allow
Allow from all
</Directory>
# Ensure we can run (fast)cgi scripts
ScriptAlias /munin/munin-cgi/munin-cgi-graph /usr/lib/cgi-bin/munin-cgi-graph
<Location /munin/munin-cgi/munin-cgi-graph>
Options +ExecCGI
SetHandler fcgid-script
Allow from all
</Location>
ScriptAlias /munin/munin-cgi/munin-cgi-html /usr/lib/cgi-bin/munin-cgi-html
<Location /munin/munin-cgi/munin-cgi-html>
Options +ExecCGI
SetHandler fcgid-script
Allow from all
</Location>
``` |
13,020,328 | I've got a 400+ node munin-1.4.x installation, that I'd like to upgrade to munin-2.x, to take advantage of the CGI based content generation (html & graphs) on the munin master server. I've gone through the official dox ( <http://munin-monitoring.org/wiki/CgiHowto2> ), and its simply not working. It only covers a VirtualHost ( <http://munin.example.com> ), which is not my setup, but I tried to use it as a starting point.
Specifically, I want & need <http://example.com/munin> to be the base URL that dynamically generates the html content listing all the nodes, with links to the individual node pages (which are then dynamically generated/updated when clicked upon). The added catch is that I'm doing this on Fedora(16), and the vast majority of howto's that I've found assume Debian/Ubuntu (or assume non-cgi static content generation via cron).
The official Fedora munin package installs the following:
* munin base directory is /var/www/html/munin
* munin static content direcotry is /var/www/html/munin/static
* munin cgi scripts (munin-cg-graph & munin-cg-html) are in /var/www/html/munin/cgi
What I've done so far:
\* set "html\_strategy cgi" and "cgiurl\_graph /munin/cgi/munin-cgi-html" in /etc/munin/munin.conf
\* Added the following to /etc/httpd/conf/httpd.conf:
```
# Rewrites
RewriteEngine On
Alias /static /var/www/html/munin/static
Alias /munin /var/www/html/munin
# HTML
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} .html$ [or]
RewriteCond %{REQUEST_URI} =/
RewriteRule ^/(.*) /var/www/html/munin/cgi/munin-cgi-html/$1 [L]
# Images
# - remove path to munin-cgi-graph, if present
RewriteRule ^/munin/cgi/munin-cgi-graph/(.*) /$1
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} .png$
RewriteRule ^/(.*) /var/www/html/munin/cgi/munin-cgi-graph/$1 [L]
ScriptAlias /munin/cgi/munin-cgi-graph /var/www/html/munin/cgi/munin-cgi-graph
<Location /munin/cgi/munin-cgi-graph>
Options +ExecCGI FollowSymLinks
<IfModule mod_fcgid.c>
SetHandler fcgi-script
</IfModule>
<IfModule !mod_fcgid.c>
SetHandler cgi-script
</IfModule>
</Location>
ScriptAlias /munin/cgi/munin-cgi-html /var/www/html/munin/cgi/munin-cgi-html
<Location /munin/cgi/munin-cgi-html>
Options +ExecCGI FollowSymLinks
<IfModule mod_fcgid.c>
SetHandler fcgi-script
</IfModule>
<IfModule !mod_fcgid.c>
SetHandler cgi-script
</IfModule>
</Location>
```
However, after doing all that (and restarting apache), when I go to <http://example.com/munin> , I get a 404 error, and in the apache error log I see:
```
File does not exist: /var/www/html/munin/cgi/munin-cgi-html/munin/index.html
```
I'm hoping that i'm just missing something obvious, but right now I'm at a complete loss on what else might need to be adjusted to make this work. thanks. | 2012/10/22 | [
"https://Stackoverflow.com/questions/13020328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179922/"
] | The problem is that, if you use the configuration in a "location" based setup (rather than in a VirtualHost"), the flag for the RewriteRule is wrong.
As per [mod\_rewrite](http://httpd.apache.org/docs/current/mod/mod_rewrite.html) docu:
```
L Stop the rewriting process immediately and don't apply any more rules.
```
However, in your case you want /munin/cgi/munin-cgi-html to be passed on so that the ScriptAlias actually triggers. Thus:
```
PT Forces the resulting URI to be passed back to the URL mapping engine for
processing of other URI-to-filename translators, such as Alias or Redirect
```
If you change your rules to read
```
RewriteRule ^/(.*) /munin/cgi/munin-cgi-html/$1 [PT]
....
RewriteRule ^/(.*) /munin/cgi/munin-cgi-graph/$1 [PT]
```
Note the relative path, as otherwise the ScriptAlias doesn't work. | Ensure munin-cgi is installed and the dependencies: mod\_fcgid.
CentOS 7, no special parameters added to the file configuration located at /etc/httpd/conf.d/munin.conf.
Regards. |
13,020,328 | I've got a 400+ node munin-1.4.x installation, that I'd like to upgrade to munin-2.x, to take advantage of the CGI based content generation (html & graphs) on the munin master server. I've gone through the official dox ( <http://munin-monitoring.org/wiki/CgiHowto2> ), and its simply not working. It only covers a VirtualHost ( <http://munin.example.com> ), which is not my setup, but I tried to use it as a starting point.
Specifically, I want & need <http://example.com/munin> to be the base URL that dynamically generates the html content listing all the nodes, with links to the individual node pages (which are then dynamically generated/updated when clicked upon). The added catch is that I'm doing this on Fedora(16), and the vast majority of howto's that I've found assume Debian/Ubuntu (or assume non-cgi static content generation via cron).
The official Fedora munin package installs the following:
* munin base directory is /var/www/html/munin
* munin static content direcotry is /var/www/html/munin/static
* munin cgi scripts (munin-cg-graph & munin-cg-html) are in /var/www/html/munin/cgi
What I've done so far:
\* set "html\_strategy cgi" and "cgiurl\_graph /munin/cgi/munin-cgi-html" in /etc/munin/munin.conf
\* Added the following to /etc/httpd/conf/httpd.conf:
```
# Rewrites
RewriteEngine On
Alias /static /var/www/html/munin/static
Alias /munin /var/www/html/munin
# HTML
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} .html$ [or]
RewriteCond %{REQUEST_URI} =/
RewriteRule ^/(.*) /var/www/html/munin/cgi/munin-cgi-html/$1 [L]
# Images
# - remove path to munin-cgi-graph, if present
RewriteRule ^/munin/cgi/munin-cgi-graph/(.*) /$1
RewriteCond %{REQUEST_URI} !^/static
RewriteCond %{REQUEST_URI} .png$
RewriteRule ^/(.*) /var/www/html/munin/cgi/munin-cgi-graph/$1 [L]
ScriptAlias /munin/cgi/munin-cgi-graph /var/www/html/munin/cgi/munin-cgi-graph
<Location /munin/cgi/munin-cgi-graph>
Options +ExecCGI FollowSymLinks
<IfModule mod_fcgid.c>
SetHandler fcgi-script
</IfModule>
<IfModule !mod_fcgid.c>
SetHandler cgi-script
</IfModule>
</Location>
ScriptAlias /munin/cgi/munin-cgi-html /var/www/html/munin/cgi/munin-cgi-html
<Location /munin/cgi/munin-cgi-html>
Options +ExecCGI FollowSymLinks
<IfModule mod_fcgid.c>
SetHandler fcgi-script
</IfModule>
<IfModule !mod_fcgid.c>
SetHandler cgi-script
</IfModule>
</Location>
```
However, after doing all that (and restarting apache), when I go to <http://example.com/munin> , I get a 404 error, and in the apache error log I see:
```
File does not exist: /var/www/html/munin/cgi/munin-cgi-html/munin/index.html
```
I'm hoping that i'm just missing something obvious, but right now I'm at a complete loss on what else might need to be adjusted to make this work. thanks. | 2012/10/22 | [
"https://Stackoverflow.com/questions/13020328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179922/"
] | I had exactly the same problem and I struggled for a while, but I eventually came up with the following config which should do exactly what you want.
My system is Ubuntu Server 12.10. For some reasons my static files are located at /var/cache/munin/www, I'm not sure whether this is standard on Ubuntu or it was caused by my recent upgrade from Ubuntu 12.04.
```
RewriteEngine On
# HTML
RewriteRule ^/munin/(.*\.html)?$ /munin/munin-cgi/munin-cgi-html/$1 [PT]
# Images
RewriteRule ^/munin/munin-cgi/munin-cgi-graph/(.*) /munin/$1
RewriteCond %{REQUEST_URI} !^/static
RewriteRule ^/munin/(.*.png)$ /munin/munin-cgi/munin-cgi-graph/$1 [L,PT]
<Directory /var/cache/munin/www/>
Order deny,allow
Allow from all
</Directory>
# Ensure we can run (fast)cgi scripts
ScriptAlias /munin/munin-cgi/munin-cgi-graph /usr/lib/cgi-bin/munin-cgi-graph
<Location /munin/munin-cgi/munin-cgi-graph>
Options +ExecCGI
SetHandler fcgid-script
Allow from all
</Location>
ScriptAlias /munin/munin-cgi/munin-cgi-html /usr/lib/cgi-bin/munin-cgi-html
<Location /munin/munin-cgi/munin-cgi-html>
Options +ExecCGI
SetHandler fcgid-script
Allow from all
</Location>
``` | Ensure munin-cgi is installed and the dependencies: mod\_fcgid.
CentOS 7, no special parameters added to the file configuration located at /etc/httpd/conf.d/munin.conf.
Regards. |
19,784,453 | Is there a way to get the index of class name (I.e. the third element with the class "className" would be 3 without using jQ?
I don't know jQ, and I don't have time to learn it right now, and I don't want to include code into my code that I don't understand at least some.
Thanks.
BTW, I've used jQ instead of spelling it out so those results can be filtered out in Google should somebody have the same question. If I spelled it out, and somebody used the NOT operator in Google, this one would also disappear. | 2013/11/05 | [
"https://Stackoverflow.com/questions/19784453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1940394/"
] | you can use [document.getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName)
```
var el = document.getElementsByClassName('className');
for (var i = 0; i < el.length; i++) {
// your index is inside here
}
```
`el[i]` is the element in the current iteration, `i` is the index
>
> (I.e. the third element with the class "className" would be 3)
>
>
>
```
if (i == 3)
return el[i]
```
---
JsFiddle: [here](http://jsfiddle.net/MYspu/1/). | Just use [`getElementsByClassName`](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName), it returns a list of elements with the specified classes.
```
elements = document.getElementsByClassName("test")
element = elements[2] //get the 3rd element
```
Hope this helps! |
19,784,453 | Is there a way to get the index of class name (I.e. the third element with the class "className" would be 3 without using jQ?
I don't know jQ, and I don't have time to learn it right now, and I don't want to include code into my code that I don't understand at least some.
Thanks.
BTW, I've used jQ instead of spelling it out so those results can be filtered out in Google should somebody have the same question. If I spelled it out, and somebody used the NOT operator in Google, this one would also disappear. | 2013/11/05 | [
"https://Stackoverflow.com/questions/19784453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1940394/"
] | you can use [document.getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName)
```
var el = document.getElementsByClassName('className');
for (var i = 0; i < el.length; i++) {
// your index is inside here
}
```
`el[i]` is the element in the current iteration, `i` is the index
>
> (I.e. the third element with the class "className" would be 3)
>
>
>
```
if (i == 3)
return el[i]
```
---
JsFiddle: [here](http://jsfiddle.net/MYspu/1/). | these work as of es6:
```
Array.from(document.querySelectorAll('.elements')).indexOf(anElement)
```
or
```
[...document.querySelectorAll('.elements')].indexOf(anElement)
``` |
19,784,453 | Is there a way to get the index of class name (I.e. the third element with the class "className" would be 3 without using jQ?
I don't know jQ, and I don't have time to learn it right now, and I don't want to include code into my code that I don't understand at least some.
Thanks.
BTW, I've used jQ instead of spelling it out so those results can be filtered out in Google should somebody have the same question. If I spelled it out, and somebody used the NOT operator in Google, this one would also disappear. | 2013/11/05 | [
"https://Stackoverflow.com/questions/19784453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1940394/"
] | You could do something like:
```
// the element you're looking for
var target = document.getElementById("an-element");
// the collection you're looking in
var nodes = document.querySelectorAll(".yourclass");
var index = [].indexOf.call(nodes, target);
```
See: [Array's indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf).
If you have already a proper array as `nodes` instead of a NodeList, you can just do `nodes.indexOf(target)`. | Just use [`getElementsByClassName`](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName), it returns a list of elements with the specified classes.
```
elements = document.getElementsByClassName("test")
element = elements[2] //get the 3rd element
```
Hope this helps! |
19,784,453 | Is there a way to get the index of class name (I.e. the third element with the class "className" would be 3 without using jQ?
I don't know jQ, and I don't have time to learn it right now, and I don't want to include code into my code that I don't understand at least some.
Thanks.
BTW, I've used jQ instead of spelling it out so those results can be filtered out in Google should somebody have the same question. If I spelled it out, and somebody used the NOT operator in Google, this one would also disappear. | 2013/11/05 | [
"https://Stackoverflow.com/questions/19784453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1940394/"
] | You could do something like:
```
// the element you're looking for
var target = document.getElementById("an-element");
// the collection you're looking in
var nodes = document.querySelectorAll(".yourclass");
var index = [].indexOf.call(nodes, target);
```
See: [Array's indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf).
If you have already a proper array as `nodes` instead of a NodeList, you can just do `nodes.indexOf(target)`. | these work as of es6:
```
Array.from(document.querySelectorAll('.elements')).indexOf(anElement)
```
or
```
[...document.querySelectorAll('.elements')].indexOf(anElement)
``` |
52,419,862 | I am currently learning python and tried to implement chess.
(I've already done this in multiple different languages)
```
class Board:
def __init__(self):
self._reset()
def _reset(self, func=Board.default_layout):
self.values = [[0 for x in range(8)] for i in range(8)]
self.currentPlayer = 1
func(self.values)
@staticmethod
def default_layout(values):
pass
if __name__ == "__main__":
b = Board()
```
The idea of the reset method is to reset the board. The pieces on it will be removed and a function will be called that places the pieces on the board in the initial layout.
There are chess versions, where there are different starting layouts. Therefor I wanted to make it an optional parameter with the default method: `default_layout(self)`
However this code does not compile and I would like to know where my problem is.
I get the error message:
```
NameError: name 'default_layout' is not defined
``` | 2018/09/20 | [
"https://Stackoverflow.com/questions/52419862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4944986/"
] | Your `def _reset(self, func=Board.default_layout):` is being evaluated as part of the definition of `Board`, so `Board.default_layout` is not defined yet.
You could make `default_layout` an ordinary function instead of a static method. It needs to be defined before you use it.
```
def default_layout(values):
... whatever
class Board:
...
def _reset(self, func=default_layout):
...
```
Or, if it *must* be a static method, don't try and reference it inside the function declaration. You can reference it inside the function *body*, because the body isn't executed until the function is actually called.
```
def _reset(self, func=None):
if func is None:
func = Board.default_layout
``` | As an alternative to @khelwood's answer, you can also use a `lambda` function instead if you prefer to keep `default_layout` a static method of the `Board` class.
Change:
```
def _reset(self, func=Board.default_layout):
```
to
```
def _reset(self, func=lambda values: Board.default_layout(values)):
``` |
36,109 | The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.
```
#! /bin/sh
if [ "${1+set}" != "set" ]
then
echo "Usage; winewrap EXEC [ARGS...]"
exit 1
fi
EXEC="$1"
shift
ARGS=""
for p in "$@";
do
if [ -e "$p" ]
then
p=$(winepath -w $p)
fi
ARGS="$ARGS '$p'"
done
CMD="wine '$EXEC' $ARGS"
echo $CMD
$CMD
```
However, there's something wrong with the quotation of command-line arguments.
```
$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt
Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt'
wine: cannot find ''/home/chris/.wine/drive_c/Program'
```
Note that:
1. The path to the executable is being chopped off at the first space, even though it is single-quoted.
2. The literal "\t" in the last path is being transformed into a tab character.
Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?
EDIT: The "\t" is being expanded through two levels of indirection: first, `"$p"` (and/or `"$ARGS"`) is being expanded into `Z:\tmp\smtlib3cee8b.smt`; then, `\t` is being expanded into the tab character. This is (seemingly) equivalent to
```
Y='y\ty'
Z="z${Y}z"
echo $Z
```
which yields
```
zy\tyz
```
and *not*
```
zy yz
```
UPDATE: `eval "$CMD"` does the trick. The "`\t`" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." ([POSIX specification of `echo`](http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html)) | 2008/08/30 | [
"https://Stackoverflow.com/questions/36109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | I you do want to have the assignment to CMD you should use
`eval $CMD`
instead of just `$CMD` in the last line of your script. This should solve your problem with spaces in the paths, I don't know what to do about the "\t" problem. | You can try preceeding the spaces with \ like so:
```
/home/chris/.wine/drive_c/Program Files/Microsoft\ Research/Z3-1.3.6/bin/z3.exe
```
You can also do the same with your \t problem - replace it with \\t. |
36,109 | The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.
```
#! /bin/sh
if [ "${1+set}" != "set" ]
then
echo "Usage; winewrap EXEC [ARGS...]"
exit 1
fi
EXEC="$1"
shift
ARGS=""
for p in "$@";
do
if [ -e "$p" ]
then
p=$(winepath -w $p)
fi
ARGS="$ARGS '$p'"
done
CMD="wine '$EXEC' $ARGS"
echo $CMD
$CMD
```
However, there's something wrong with the quotation of command-line arguments.
```
$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt
Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt'
wine: cannot find ''/home/chris/.wine/drive_c/Program'
```
Note that:
1. The path to the executable is being chopped off at the first space, even though it is single-quoted.
2. The literal "\t" in the last path is being transformed into a tab character.
Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?
EDIT: The "\t" is being expanded through two levels of indirection: first, `"$p"` (and/or `"$ARGS"`) is being expanded into `Z:\tmp\smtlib3cee8b.smt`; then, `\t` is being expanded into the tab character. This is (seemingly) equivalent to
```
Y='y\ty'
Z="z${Y}z"
echo $Z
```
which yields
```
zy\tyz
```
and *not*
```
zy yz
```
UPDATE: `eval "$CMD"` does the trick. The "`\t`" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." ([POSIX specification of `echo`](http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html)) | 2008/08/30 | [
"https://Stackoverflow.com/questions/36109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | * bash’s arrays are unportable but the only sane way to handle argument lists in shell
* The number of arguments is in ${#}
* Bad stuff will happen with your script if there are filenames starting with a dash in the current directory
* If the last line of your script just runs a program, and there are no traps on exit, you should exec it
With that in mind
```
#! /bin/bash
# push ARRAY arg1 arg2 ...
# adds arg1, arg2, ... to the end of ARRAY
function push() {
local ARRAY_NAME="${1}"
shift
for ARG in "${@}"; do
eval "${ARRAY_NAME}[\${#${ARRAY_NAME}[@]}]=\${ARG}"
done
}
PROG="$(basename -- "${0}")"
if (( ${#} < 1 )); then
# Error messages should state the program name and go to stderr
echo "${PROG}: Usage: winewrap EXEC [ARGS...]" 1>&2
exit 1
fi
EXEC=("${1}")
shift
for p in "${@}"; do
if [ -e "${p}" ]; then
p="$(winepath -w -- "${p}")"
fi
push EXEC "${p}"
done
exec "${EXEC[@]}"
``` | You can try preceeding the spaces with \ like so:
```
/home/chris/.wine/drive_c/Program Files/Microsoft\ Research/Z3-1.3.6/bin/z3.exe
```
You can also do the same with your \t problem - replace it with \\t. |
36,109 | The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.
```
#! /bin/sh
if [ "${1+set}" != "set" ]
then
echo "Usage; winewrap EXEC [ARGS...]"
exit 1
fi
EXEC="$1"
shift
ARGS=""
for p in "$@";
do
if [ -e "$p" ]
then
p=$(winepath -w $p)
fi
ARGS="$ARGS '$p'"
done
CMD="wine '$EXEC' $ARGS"
echo $CMD
$CMD
```
However, there's something wrong with the quotation of command-line arguments.
```
$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt
Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt'
wine: cannot find ''/home/chris/.wine/drive_c/Program'
```
Note that:
1. The path to the executable is being chopped off at the first space, even though it is single-quoted.
2. The literal "\t" in the last path is being transformed into a tab character.
Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?
EDIT: The "\t" is being expanded through two levels of indirection: first, `"$p"` (and/or `"$ARGS"`) is being expanded into `Z:\tmp\smtlib3cee8b.smt`; then, `\t` is being expanded into the tab character. This is (seemingly) equivalent to
```
Y='y\ty'
Z="z${Y}z"
echo $Z
```
which yields
```
zy\tyz
```
and *not*
```
zy yz
```
UPDATE: `eval "$CMD"` does the trick. The "`\t`" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." ([POSIX specification of `echo`](http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html)) | 2008/08/30 | [
"https://Stackoverflow.com/questions/36109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | I you do want to have the assignment to CMD you should use
`eval $CMD`
instead of just `$CMD` in the last line of your script. This should solve your problem with spaces in the paths, I don't know what to do about the "\t" problem. | replace the last line from $CMD to just
wine '$EXEC' $ARGS
You'll note that the error is ''/home/chris/.wine/drive\_c/Program' and not '/home/chris/.wine/drive\_c/Program'
The single quotes are not being interpolated properly, and the string is being split by spaces. |
36,109 | The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.
```
#! /bin/sh
if [ "${1+set}" != "set" ]
then
echo "Usage; winewrap EXEC [ARGS...]"
exit 1
fi
EXEC="$1"
shift
ARGS=""
for p in "$@";
do
if [ -e "$p" ]
then
p=$(winepath -w $p)
fi
ARGS="$ARGS '$p'"
done
CMD="wine '$EXEC' $ARGS"
echo $CMD
$CMD
```
However, there's something wrong with the quotation of command-line arguments.
```
$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt
Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt'
wine: cannot find ''/home/chris/.wine/drive_c/Program'
```
Note that:
1. The path to the executable is being chopped off at the first space, even though it is single-quoted.
2. The literal "\t" in the last path is being transformed into a tab character.
Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?
EDIT: The "\t" is being expanded through two levels of indirection: first, `"$p"` (and/or `"$ARGS"`) is being expanded into `Z:\tmp\smtlib3cee8b.smt`; then, `\t` is being expanded into the tab character. This is (seemingly) equivalent to
```
Y='y\ty'
Z="z${Y}z"
echo $Z
```
which yields
```
zy\tyz
```
and *not*
```
zy yz
```
UPDATE: `eval "$CMD"` does the trick. The "`\t`" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." ([POSIX specification of `echo`](http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html)) | 2008/08/30 | [
"https://Stackoverflow.com/questions/36109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | * bash’s arrays are unportable but the only sane way to handle argument lists in shell
* The number of arguments is in ${#}
* Bad stuff will happen with your script if there are filenames starting with a dash in the current directory
* If the last line of your script just runs a program, and there are no traps on exit, you should exec it
With that in mind
```
#! /bin/bash
# push ARRAY arg1 arg2 ...
# adds arg1, arg2, ... to the end of ARRAY
function push() {
local ARRAY_NAME="${1}"
shift
for ARG in "${@}"; do
eval "${ARRAY_NAME}[\${#${ARRAY_NAME}[@]}]=\${ARG}"
done
}
PROG="$(basename -- "${0}")"
if (( ${#} < 1 )); then
# Error messages should state the program name and go to stderr
echo "${PROG}: Usage: winewrap EXEC [ARGS...]" 1>&2
exit 1
fi
EXEC=("${1}")
shift
for p in "${@}"; do
if [ -e "${p}" ]; then
p="$(winepath -w -- "${p}")"
fi
push EXEC "${p}"
done
exec "${EXEC[@]}"
``` | replace the last line from $CMD to just
wine '$EXEC' $ARGS
You'll note that the error is ''/home/chris/.wine/drive\_c/Program' and not '/home/chris/.wine/drive\_c/Program'
The single quotes are not being interpolated properly, and the string is being split by spaces. |
79,070 | As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on? | 2017/04/26 | [
"https://money.stackexchange.com/questions/79070",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/41914/"
] | The time value decay is theoretically constant. In reality, it is driven by supply and demand, just like everything else in the market.
For instance, if a big earnings announcement is coming out after the close for the day, you may see little or no time decay in the price of the options during the day before.
Also, while in theory options have a set value as related to the trading price of the underlying security, that does not mean there will always be a buyer willing to pay a premium as they come close to expiration (in the last few minutes). You can't forget to account for the transaction fees associated with buying the options, or the risk factor involved.
It is rare, but there are times I've actually had to sell in the money calls at a penny or two LESS than they're actually worth at the time just to unload them in the last few minutes before the market closed on expiration day. | If you're talking about just Theta, the amount of decay due to the passage of time (all else being equal), then theoretically, the time value is a continuous function, so it would decay throughout the day (although by the day of expiry the time value is very, very small). Which makes sense, since even with 15 minutes to go, there's still a 50/50 shot of an ATM option expiring in-the-money, so there should be some time value associated with that one-sided probability. The further away from ATM the option is, the smaller the time value will be, and will be virtually zero for options that are deep in- or out-of-the-money.
If you're talking about *total* time value, then yes it will definitely change during the day, since the underlying components (volatility, underlying price, etc.) change more or less continually. |
79,070 | As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on? | 2017/04/26 | [
"https://money.stackexchange.com/questions/79070",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/41914/"
] | If you're talking about just Theta, the amount of decay due to the passage of time (all else being equal), then theoretically, the time value is a continuous function, so it would decay throughout the day (although by the day of expiry the time value is very, very small). Which makes sense, since even with 15 minutes to go, there's still a 50/50 shot of an ATM option expiring in-the-money, so there should be some time value associated with that one-sided probability. The further away from ATM the option is, the smaller the time value will be, and will be virtually zero for options that are deep in- or out-of-the-money.
If you're talking about *total* time value, then yes it will definitely change during the day, since the underlying components (volatility, underlying price, etc.) change more or less continually. | It has been my experience as an amateur trader, theory aside, that I generally see the time value come off at market open and not much during the trading day. |
79,070 | As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on? | 2017/04/26 | [
"https://money.stackexchange.com/questions/79070",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/41914/"
] | If you're talking about just Theta, the amount of decay due to the passage of time (all else being equal), then theoretically, the time value is a continuous function, so it would decay throughout the day (although by the day of expiry the time value is very, very small). Which makes sense, since even with 15 minutes to go, there's still a 50/50 shot of an ATM option expiring in-the-money, so there should be some time value associated with that one-sided probability. The further away from ATM the option is, the smaller the time value will be, and will be virtually zero for options that are deep in- or out-of-the-money.
If you're talking about *total* time value, then yes it will definitely change during the day, since the underlying components (volatility, underlying price, etc.) change more or less continually. | The time value of the option (theta) decays constantly (by the millisecond)
As it is one of the inputs to the option pricing model, it usually has a lower impact on the overall option price than other changes in the market.
As the (US) markets price options in penny ($0.01) or nickel ($0.05) increments, you will only observe these changes when the impact of theta is big enough for the market maker to increase or decrease his bid or offer by another $0.01 or $0.05.
This will happen slowly throughout the day but should be more significant from one day’s close to the next day’s open particularly if there is a weekend or long weekend in between. |
79,070 | As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on? | 2017/04/26 | [
"https://money.stackexchange.com/questions/79070",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/41914/"
] | If you're talking about just Theta, the amount of decay due to the passage of time (all else being equal), then theoretically, the time value is a continuous function, so it would decay throughout the day (although by the day of expiry the time value is very, very small). Which makes sense, since even with 15 minutes to go, there's still a 50/50 shot of an ATM option expiring in-the-money, so there should be some time value associated with that one-sided probability. The further away from ATM the option is, the smaller the time value will be, and will be virtually zero for options that are deep in- or out-of-the-money.
If you're talking about *total* time value, then yes it will definitely change during the day, since the underlying components (volatility, underlying price, etc.) change more or less continually. | This has been my observation in the markets pertaining to option decay. Bulk of the decay happens in the first 15 minutes of trade at market open. Rest of the decay usually happens in pulses whenever market breaks out of ranges intraday. So if its call option and market breaks a range to the downside, call option will experience decay in proportion to time elapsed since open. |
79,070 | As days tick off of call options, time value decays. My question is does that happen automatically at 9:30AM at market open or does it get continuously deducted as the day ticks on? | 2017/04/26 | [
"https://money.stackexchange.com/questions/79070",
"https://money.stackexchange.com",
"https://money.stackexchange.com/users/41914/"
] | The time value decay is theoretically constant. In reality, it is driven by supply and demand, just like everything else in the market.
For instance, if a big earnings announcement is coming out after the close for the day, you may see little or no time decay in the price of the options during the day before.
Also, while in theory options have a set value as related to the trading price of the underlying security, that does not mean there will always be a buyer willing to pay a premium as they come close to expiration (in the last few minutes). You can't forget to account for the transaction fees associated with buying the options, or the risk factor involved.
It is rare, but there are times I've actually had to sell in the money calls at a penny or two LESS than they're actually worth at the time just to unload them in the last few minutes before the market closed on expiration day. | It has been my experience as an amateur trader, theory aside, that I generally see the time value come off at market open and not much during the trading day. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.