qid
int64
1
74.7M
question
stringlengths
17
39.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
41.1k
response_k
stringlengths
2
47.9k
70,940,210
Lets say I have a base class `A` and `A1, A2, A3` all extends A. I create a factory class say, `FactoryForA` that implements a method say `getObject` as ``` getObject(typeToSwitch) { case A1: // return an object of A1 case A2: // return an object of A2 case A3: // return an object of A3 } ``` I am looking for a way to make the argument `typeToSwitch` type safe.
2022/02/01
[ "https://Stackoverflow.com/questions/70940210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9391556/" ]
My approach would be using *infer* typescript keyword to return the requested type. Something like the below: ``` class A { public getA = () => {} } class A1 extends A { constructor() { super(); } public getA = () => { return 'A1'; } } class A2 extends A { constructor() { super(); } public getA = () => { return 'A1'; } } // get the key map types ( a1 and a2 ) type Keys = keyof typeof FactoryA.AMap; // get the classes types type aTypes = typeof FactoryA.AMap[Keys]; // build the return type with generics type ClassInstanceType<T> = T extends new () => infer R ? R : never; class FactoryA { public static AMap = { a1: A1, a2: A2 }; public static getObject = (typeToSwitch: Keys ): ClassInstanceType<aTypes> => { return new FactoryA.AMap[typeToSwitch](); } } const a1instance: A1 = FactoryA.getObject('a1'); console.log(a1instance.getA()); ```
What I came up with is `getObject<T extends new(...args: any[]) => A>(typeToSwitch: T)`. It says `T` is something that extends A and is constructible, so it allows us to use a type as value(I am yet to figure this why). Also `getObject(T extends A)` does not work(why only a constructible type is supported.) If anyone has suggestions or explanations please update the answer or comment. [Here](https://www.typescriptlang.org/play?#code/MYGwhgzhAECC0G8C%20AoFpI1gRmgUwA8AXPAOwBMtEVppgB7UiIgJwFdgj6WAKASmq1aENgAc8vPgG4aQhk3og8AOhD0A5jwBEOLdNmpUGKHABM%20YmUpxBdRs3adu-W8LET%20MoXYVLVG7VhTPS9oQ3RwE1gAZgsSCioEWXkHDi5JV2gRcUlQ2hTFFTVNHWiQgxRUCMxoADEwJxYATwB5ADN4JNp1PCIASSYiMFJgPAAeABU4qxhSPAB3aB5lFbAWdQgALmhhpoBtAF0BAF4APjhTngh5gEsiYAALFtIJpvFtiYEuoWu7x6Xfvcni83ngvrJvMBIHg4NhNhDvNAWL02CxSNA5oscJ4EfloWZ4YihMiiKj0ZizDiiVCIDCYoSiUiUWiMQs4NEqYjyHg2mA2CAiAyiUQHix6IsAKIsMW8LSvcQY%20hEOwAW1EYCINwARkpoLcRdBeY0muVvKhaOF0PZlW1oMdWYt6sb2rB%20Moev1BsNRjwgvogA) is a link to an example of what I said above.
46,238
I normally try to place myself in my character's shoes and I think to myself, "how would I react if I were in this situation?" Well one of my beta-readers commented on my work, and he said the chapter sounds like it was written in haste to go along with the panic and dire of the situation at hand. He said that's not a good thing. How can I write a panicked/dire scene without it feeling like it was written in haste? Any feedback is appreciated. Thanks in advance!
2019/06/25
[ "https://writers.stackexchange.com/questions/46238", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/33805/" ]
I've noticed something about many books and movies. Just as two characters are getting into a deep conversation, either sharing something important or showing emotion or leaning forward slowly to kiss, a random passerby will walk right between them. It totally throws them off and - you would think - breaks things up. But instead, it actually heightens the audience's anticipation. We can't wait until the interruption leaves so we can get back to what was about to happen. This is part of pacing, and it's hard to get right, mostly because it's not always intuitive. Interrupting a tense scene can increase tension? Slowing down the sword fight can make it even more gripping? Yes. What readers need is *variation*. A section of panic and then a strangely quiet moment - the eye of the storm, as it were - before returning to the panic and ratcheting it up even higher. Don't spam these moments. They need to happen naturally, just once or twice in the scene. My recommendation is to pay special attention to tense, panicked, or dire situations in other books. You might be surprised to see that despite the heavy action, the author doesn't completely cut out all introspection. There has to be feeling even if there isn't conscious thought. I recommend re-watching *Inception*. Literally the most gripping movie I've seen in theaters. Notice that Fischer, the rich son whose dream they enter, spends much of the dreamstate talking with his father. It's slow and emotional, and perfectly contrasts with the alpine chase scene and the shootouts. Don't forget the emotional stakes during these scenes. That is often what makes a good action scene work, anyway. UPDATE: Let me be clear: showing *too much* emotion and introspection during a scene will slow it to a crawl. That's not what you want. The trick is to use a balance of interruptions to the action: some will be thoughts and emotions, and some will be literal breaks in the action, like the characters barricading a door to buy themselves time. They can still hear the enemies pounding on the outside, and they can see the metal bending around the handle, but for a few brief moments they are safe enough to realize how much danger they're really in.
**Panic and dire situations do not necessarily make time seem to flow faster.** People frequently talk about adrenaline making time seem to slow down, and it's not a bad idea to let your writing reflect that. I once got hit by a car in the crosswalk (Spoiler alert, it was going slowly, stopped almost as soon as it hit me, and I was not permanently injured). When I turned my head and noticed that the car was going to hit me, I had basically no time to react. As I am not a parkour master or a stunt man, I didn't have time to make a conscious decision to jump or roll or dodge or anything that might have softened the blow. Instead, I looked at the car, stood there like a deer in the headlights, and the split-second seemed to stretch out to infinity, my brain echoing with the thoughts, "I'm about to be hit by a car. There's nothing I can do to stop it," as it rolled towards me. Continuing forward about ten minutes, I took a test for a college course (because my panic somehow rolled into 'I'm going to be late for my test' and I did not make good decisions) -- I distinctly remember reading through the first question on the exam about a dozen times, and every time I got to the multiple choice options, I got distracted by overwhelming thoughts like "OMIGOD, I JUST GOT HIT BY A CAR", "My leg hurts" or "A CAR, A FREAKING CAR!" (No, I did not get this particular question correct) The point I'm trying to make is that, just because your character has very streamlined actions or intentions, does not mean that their brain is shut down and only thinking about what they're doing. It might be imperative that they go chop down a tree. If that's just a simple chore, go ahead and say they went out back, chopped down the tree, gathered some firewood, and brought it inside. If, on the other hand, chopping down this tree is going to save the world, they're going to be thinking about the weight of the axe in their hand, how heavy their footsteps are as they cross the yard, what this is going to mean for the rest of humanity. They'll pick the best angle to swing at the tree, so they don't have to work up the nerve to do it a second time, and they'll pull back their shoulders and swing with all their faith and resolution. The axe will slice through the air, and the sound it makes as it cuts into the bark will resound through their head in chorus with the reverberations of Newton's Third Law in their arms. **tl;dr During moments of extreme importance, be sure to express the character's thoughts and emotions, even if decisions/actions are made quickly.**
46,238
I normally try to place myself in my character's shoes and I think to myself, "how would I react if I were in this situation?" Well one of my beta-readers commented on my work, and he said the chapter sounds like it was written in haste to go along with the panic and dire of the situation at hand. He said that's not a good thing. How can I write a panicked/dire scene without it feeling like it was written in haste? Any feedback is appreciated. Thanks in advance!
2019/06/25
[ "https://writers.stackexchange.com/questions/46238", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/33805/" ]
I've noticed something about many books and movies. Just as two characters are getting into a deep conversation, either sharing something important or showing emotion or leaning forward slowly to kiss, a random passerby will walk right between them. It totally throws them off and - you would think - breaks things up. But instead, it actually heightens the audience's anticipation. We can't wait until the interruption leaves so we can get back to what was about to happen. This is part of pacing, and it's hard to get right, mostly because it's not always intuitive. Interrupting a tense scene can increase tension? Slowing down the sword fight can make it even more gripping? Yes. What readers need is *variation*. A section of panic and then a strangely quiet moment - the eye of the storm, as it were - before returning to the panic and ratcheting it up even higher. Don't spam these moments. They need to happen naturally, just once or twice in the scene. My recommendation is to pay special attention to tense, panicked, or dire situations in other books. You might be surprised to see that despite the heavy action, the author doesn't completely cut out all introspection. There has to be feeling even if there isn't conscious thought. I recommend re-watching *Inception*. Literally the most gripping movie I've seen in theaters. Notice that Fischer, the rich son whose dream they enter, spends much of the dreamstate talking with his father. It's slow and emotional, and perfectly contrasts with the alpine chase scene and the shootouts. Don't forget the emotional stakes during these scenes. That is often what makes a good action scene work, anyway. UPDATE: Let me be clear: showing *too much* emotion and introspection during a scene will slow it to a crawl. That's not what you want. The trick is to use a balance of interruptions to the action: some will be thoughts and emotions, and some will be literal breaks in the action, like the characters barricading a door to buy themselves time. They can still hear the enemies pounding on the outside, and they can see the metal bending around the handle, but for a few brief moments they are safe enough to realize how much danger they're really in.
You *write* slow. It is fine to put yourself into the character and see how you would react, but take your time describing that. Get into the details. This isn't a "real time" exercise, the length of the writing does not have to reflect the length of the action. The only time that is true is during *dialogue*, people know that sentences take a certain amount of time to say. They know it is seldom true that anybody talks in long paragraphs or soliloquys or speeches or sermons. But that does not hold for *action* or *exposition* that has no dialogue. Thoughts are on the borderline, but it is fair to describe several wordless thoughts or impressions that go through somebody's mind, and even though that took six paragraphs, the reader will still get this all happened in a single second. Consider when you describe a scene the character sees. You can spend a page on something they "saw" in three seconds of scanning a room. We still get it, they didn't stand in the doorway for a full minute as they walked in, the exposition about the setting is not a "real time" description. The same goes for your panic attack. Don't rush the prose to match the rushed mood. Describe what is going on, thoroughly but as always without getting repetitive or irrelevant. Don't worry about "real time" or getting through it quick. The author's job is to aid the reader's imagination, so they "see" an image of what is going on and what happened and the consequences of that.
46,238
I normally try to place myself in my character's shoes and I think to myself, "how would I react if I were in this situation?" Well one of my beta-readers commented on my work, and he said the chapter sounds like it was written in haste to go along with the panic and dire of the situation at hand. He said that's not a good thing. How can I write a panicked/dire scene without it feeling like it was written in haste? Any feedback is appreciated. Thanks in advance!
2019/06/25
[ "https://writers.stackexchange.com/questions/46238", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/33805/" ]
I've noticed something about many books and movies. Just as two characters are getting into a deep conversation, either sharing something important or showing emotion or leaning forward slowly to kiss, a random passerby will walk right between them. It totally throws them off and - you would think - breaks things up. But instead, it actually heightens the audience's anticipation. We can't wait until the interruption leaves so we can get back to what was about to happen. This is part of pacing, and it's hard to get right, mostly because it's not always intuitive. Interrupting a tense scene can increase tension? Slowing down the sword fight can make it even more gripping? Yes. What readers need is *variation*. A section of panic and then a strangely quiet moment - the eye of the storm, as it were - before returning to the panic and ratcheting it up even higher. Don't spam these moments. They need to happen naturally, just once or twice in the scene. My recommendation is to pay special attention to tense, panicked, or dire situations in other books. You might be surprised to see that despite the heavy action, the author doesn't completely cut out all introspection. There has to be feeling even if there isn't conscious thought. I recommend re-watching *Inception*. Literally the most gripping movie I've seen in theaters. Notice that Fischer, the rich son whose dream they enter, spends much of the dreamstate talking with his father. It's slow and emotional, and perfectly contrasts with the alpine chase scene and the shootouts. Don't forget the emotional stakes during these scenes. That is often what makes a good action scene work, anyway. UPDATE: Let me be clear: showing *too much* emotion and introspection during a scene will slow it to a crawl. That's not what you want. The trick is to use a balance of interruptions to the action: some will be thoughts and emotions, and some will be literal breaks in the action, like the characters barricading a door to buy themselves time. They can still hear the enemies pounding on the outside, and they can see the metal bending around the handle, but for a few brief moments they are safe enough to realize how much danger they're really in.
Beta-readers are great for identifying areas in our writing like this. What you have been told is this section does not feel finished or polished. However, there is an implied prescription of what you need to do to fix it. That bit I would suggest disregarding. My first step would be to review the passage and see where I need to edit and work on it. Maybe I did not give it the attention I needed. Maybe I did but I gave that one reader the wrong impression. Maybe I need to add more panic feelings to the scene? Panic is a feeling deep within the gut. For me, the best way to make my reader share this is to lead in with a fast-paced scene and then slow right down. A fast-paced scene, as I am sure others will tell you. Is easiest to compose with short sentences. I strive for a varied but generally short length. This makes readers read faster. Much faster. Sometimes they are as tense as your characters. Not always, but sometimes. Then, at a critical moment, I slow down and allow the reader time to feel that panic too. The best way to describe it is to ask you to imagine playing a game. For some reason, there are higher sakes than usual. Perhaps you bet on winning. Maybe your pride is at stake. Whatever the reason, this game matters. After a flurry of rapid-fire moves, we suddenly enter the end-game. You notice that the other player has a material advantage. You, on the other hand, have a slight situational advantage. You see two possible outcomes. Counting the moves ahead you see that you can only lose slowly unless the other player makes a mistake. The alternative is a daring gambit. You make the gambit move. If your opponent plays to form, you will crush them within a few moves. If they surprise you with a counter, then you have definitely lost. Only then do you see that you had another option. A sure-fire unblockable win. It is too late to take that option. You look at your opponent. "Your move," you tell them. Then you wait. The only sound is the ticking of the clock. Time passes. They consider their next move very carefully. You stare at the board. All you can see is the best move that you missed. You hope they will bite but you can do nothing but watch. You try to appear relaxed lest you give away your feelings to your opponent. You force your hands to your lap - out of site under the table. You force your face to smile a little. No, not too much - they must not think you believe you have one. Now you cannot even work out what expression to make your face adopt. You try to look bored. You focus on your breathing, willing them to make the move you want them to make. Finally, they move and it is your turn but your opponent has made a neutral move. Have they seen the trap? Are they testing you before they commit? Have they just failed to see the situation? Do you now follow through, or give up some material and try to regain the win another way? That feeling you have from the end of your move to the start of your next. That is panic. If you can allow your reader to empathise with that feeling within your character, you can draw it out and make it one of the tensest and compelling parts of the story. Like in the gameplay example, time seems to crawl along. You go through so many emotions and thoughts - doing nothing but waiting. My aim is to put my reader through that feeling by putting my character through it. The same is true of action-packed scenes. Scenes where the character is acting from fear rather than reason. I follow a four-point cycle for those. It is triggered by something happening. Something happens -> reaction (say, shock) -> reasoning (this is bad) -> anticipation (he is going to shoot me) -> reaction (panic)... The reaction is, of course, something happening, so we can go right back into that cycle again. For panic, I try to keep reasoning tiny or simply implied because panic requires anticipation of negative outcome without calm reasoning. Better yet, this pattern allows me to bring on an out of character moment that feels entirely justified. The pacifist hitting someone, the good guy doing something slightly evil, etc.. Even though this is an action scene I am still trying to give my reader that same feeling as the tense endgame. Bursts of action followed by enough time where anticipation can do its best work. Only you know what the scene is supposed to do. So only you can tune it to make it do that. My general advice is usually that any scene worth including is worth fully committing to. Sometimes we writers rush through a scene to get to the next bit. It is okay to do that as long as we go back and give that scene as much love as the others later on.
46,238
I normally try to place myself in my character's shoes and I think to myself, "how would I react if I were in this situation?" Well one of my beta-readers commented on my work, and he said the chapter sounds like it was written in haste to go along with the panic and dire of the situation at hand. He said that's not a good thing. How can I write a panicked/dire scene without it feeling like it was written in haste? Any feedback is appreciated. Thanks in advance!
2019/06/25
[ "https://writers.stackexchange.com/questions/46238", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/33805/" ]
**Panic and dire situations do not necessarily make time seem to flow faster.** People frequently talk about adrenaline making time seem to slow down, and it's not a bad idea to let your writing reflect that. I once got hit by a car in the crosswalk (Spoiler alert, it was going slowly, stopped almost as soon as it hit me, and I was not permanently injured). When I turned my head and noticed that the car was going to hit me, I had basically no time to react. As I am not a parkour master or a stunt man, I didn't have time to make a conscious decision to jump or roll or dodge or anything that might have softened the blow. Instead, I looked at the car, stood there like a deer in the headlights, and the split-second seemed to stretch out to infinity, my brain echoing with the thoughts, "I'm about to be hit by a car. There's nothing I can do to stop it," as it rolled towards me. Continuing forward about ten minutes, I took a test for a college course (because my panic somehow rolled into 'I'm going to be late for my test' and I did not make good decisions) -- I distinctly remember reading through the first question on the exam about a dozen times, and every time I got to the multiple choice options, I got distracted by overwhelming thoughts like "OMIGOD, I JUST GOT HIT BY A CAR", "My leg hurts" or "A CAR, A FREAKING CAR!" (No, I did not get this particular question correct) The point I'm trying to make is that, just because your character has very streamlined actions or intentions, does not mean that their brain is shut down and only thinking about what they're doing. It might be imperative that they go chop down a tree. If that's just a simple chore, go ahead and say they went out back, chopped down the tree, gathered some firewood, and brought it inside. If, on the other hand, chopping down this tree is going to save the world, they're going to be thinking about the weight of the axe in their hand, how heavy their footsteps are as they cross the yard, what this is going to mean for the rest of humanity. They'll pick the best angle to swing at the tree, so they don't have to work up the nerve to do it a second time, and they'll pull back their shoulders and swing with all their faith and resolution. The axe will slice through the air, and the sound it makes as it cuts into the bark will resound through their head in chorus with the reverberations of Newton's Third Law in their arms. **tl;dr During moments of extreme importance, be sure to express the character's thoughts and emotions, even if decisions/actions are made quickly.**
Beta-readers are great for identifying areas in our writing like this. What you have been told is this section does not feel finished or polished. However, there is an implied prescription of what you need to do to fix it. That bit I would suggest disregarding. My first step would be to review the passage and see where I need to edit and work on it. Maybe I did not give it the attention I needed. Maybe I did but I gave that one reader the wrong impression. Maybe I need to add more panic feelings to the scene? Panic is a feeling deep within the gut. For me, the best way to make my reader share this is to lead in with a fast-paced scene and then slow right down. A fast-paced scene, as I am sure others will tell you. Is easiest to compose with short sentences. I strive for a varied but generally short length. This makes readers read faster. Much faster. Sometimes they are as tense as your characters. Not always, but sometimes. Then, at a critical moment, I slow down and allow the reader time to feel that panic too. The best way to describe it is to ask you to imagine playing a game. For some reason, there are higher sakes than usual. Perhaps you bet on winning. Maybe your pride is at stake. Whatever the reason, this game matters. After a flurry of rapid-fire moves, we suddenly enter the end-game. You notice that the other player has a material advantage. You, on the other hand, have a slight situational advantage. You see two possible outcomes. Counting the moves ahead you see that you can only lose slowly unless the other player makes a mistake. The alternative is a daring gambit. You make the gambit move. If your opponent plays to form, you will crush them within a few moves. If they surprise you with a counter, then you have definitely lost. Only then do you see that you had another option. A sure-fire unblockable win. It is too late to take that option. You look at your opponent. "Your move," you tell them. Then you wait. The only sound is the ticking of the clock. Time passes. They consider their next move very carefully. You stare at the board. All you can see is the best move that you missed. You hope they will bite but you can do nothing but watch. You try to appear relaxed lest you give away your feelings to your opponent. You force your hands to your lap - out of site under the table. You force your face to smile a little. No, not too much - they must not think you believe you have one. Now you cannot even work out what expression to make your face adopt. You try to look bored. You focus on your breathing, willing them to make the move you want them to make. Finally, they move and it is your turn but your opponent has made a neutral move. Have they seen the trap? Are they testing you before they commit? Have they just failed to see the situation? Do you now follow through, or give up some material and try to regain the win another way? That feeling you have from the end of your move to the start of your next. That is panic. If you can allow your reader to empathise with that feeling within your character, you can draw it out and make it one of the tensest and compelling parts of the story. Like in the gameplay example, time seems to crawl along. You go through so many emotions and thoughts - doing nothing but waiting. My aim is to put my reader through that feeling by putting my character through it. The same is true of action-packed scenes. Scenes where the character is acting from fear rather than reason. I follow a four-point cycle for those. It is triggered by something happening. Something happens -> reaction (say, shock) -> reasoning (this is bad) -> anticipation (he is going to shoot me) -> reaction (panic)... The reaction is, of course, something happening, so we can go right back into that cycle again. For panic, I try to keep reasoning tiny or simply implied because panic requires anticipation of negative outcome without calm reasoning. Better yet, this pattern allows me to bring on an out of character moment that feels entirely justified. The pacifist hitting someone, the good guy doing something slightly evil, etc.. Even though this is an action scene I am still trying to give my reader that same feeling as the tense endgame. Bursts of action followed by enough time where anticipation can do its best work. Only you know what the scene is supposed to do. So only you can tune it to make it do that. My general advice is usually that any scene worth including is worth fully committing to. Sometimes we writers rush through a scene to get to the next bit. It is okay to do that as long as we go back and give that scene as much love as the others later on.
46,238
I normally try to place myself in my character's shoes and I think to myself, "how would I react if I were in this situation?" Well one of my beta-readers commented on my work, and he said the chapter sounds like it was written in haste to go along with the panic and dire of the situation at hand. He said that's not a good thing. How can I write a panicked/dire scene without it feeling like it was written in haste? Any feedback is appreciated. Thanks in advance!
2019/06/25
[ "https://writers.stackexchange.com/questions/46238", "https://writers.stackexchange.com", "https://writers.stackexchange.com/users/33805/" ]
You *write* slow. It is fine to put yourself into the character and see how you would react, but take your time describing that. Get into the details. This isn't a "real time" exercise, the length of the writing does not have to reflect the length of the action. The only time that is true is during *dialogue*, people know that sentences take a certain amount of time to say. They know it is seldom true that anybody talks in long paragraphs or soliloquys or speeches or sermons. But that does not hold for *action* or *exposition* that has no dialogue. Thoughts are on the borderline, but it is fair to describe several wordless thoughts or impressions that go through somebody's mind, and even though that took six paragraphs, the reader will still get this all happened in a single second. Consider when you describe a scene the character sees. You can spend a page on something they "saw" in three seconds of scanning a room. We still get it, they didn't stand in the doorway for a full minute as they walked in, the exposition about the setting is not a "real time" description. The same goes for your panic attack. Don't rush the prose to match the rushed mood. Describe what is going on, thoroughly but as always without getting repetitive or irrelevant. Don't worry about "real time" or getting through it quick. The author's job is to aid the reader's imagination, so they "see" an image of what is going on and what happened and the consequences of that.
Beta-readers are great for identifying areas in our writing like this. What you have been told is this section does not feel finished or polished. However, there is an implied prescription of what you need to do to fix it. That bit I would suggest disregarding. My first step would be to review the passage and see where I need to edit and work on it. Maybe I did not give it the attention I needed. Maybe I did but I gave that one reader the wrong impression. Maybe I need to add more panic feelings to the scene? Panic is a feeling deep within the gut. For me, the best way to make my reader share this is to lead in with a fast-paced scene and then slow right down. A fast-paced scene, as I am sure others will tell you. Is easiest to compose with short sentences. I strive for a varied but generally short length. This makes readers read faster. Much faster. Sometimes they are as tense as your characters. Not always, but sometimes. Then, at a critical moment, I slow down and allow the reader time to feel that panic too. The best way to describe it is to ask you to imagine playing a game. For some reason, there are higher sakes than usual. Perhaps you bet on winning. Maybe your pride is at stake. Whatever the reason, this game matters. After a flurry of rapid-fire moves, we suddenly enter the end-game. You notice that the other player has a material advantage. You, on the other hand, have a slight situational advantage. You see two possible outcomes. Counting the moves ahead you see that you can only lose slowly unless the other player makes a mistake. The alternative is a daring gambit. You make the gambit move. If your opponent plays to form, you will crush them within a few moves. If they surprise you with a counter, then you have definitely lost. Only then do you see that you had another option. A sure-fire unblockable win. It is too late to take that option. You look at your opponent. "Your move," you tell them. Then you wait. The only sound is the ticking of the clock. Time passes. They consider their next move very carefully. You stare at the board. All you can see is the best move that you missed. You hope they will bite but you can do nothing but watch. You try to appear relaxed lest you give away your feelings to your opponent. You force your hands to your lap - out of site under the table. You force your face to smile a little. No, not too much - they must not think you believe you have one. Now you cannot even work out what expression to make your face adopt. You try to look bored. You focus on your breathing, willing them to make the move you want them to make. Finally, they move and it is your turn but your opponent has made a neutral move. Have they seen the trap? Are they testing you before they commit? Have they just failed to see the situation? Do you now follow through, or give up some material and try to regain the win another way? That feeling you have from the end of your move to the start of your next. That is panic. If you can allow your reader to empathise with that feeling within your character, you can draw it out and make it one of the tensest and compelling parts of the story. Like in the gameplay example, time seems to crawl along. You go through so many emotions and thoughts - doing nothing but waiting. My aim is to put my reader through that feeling by putting my character through it. The same is true of action-packed scenes. Scenes where the character is acting from fear rather than reason. I follow a four-point cycle for those. It is triggered by something happening. Something happens -> reaction (say, shock) -> reasoning (this is bad) -> anticipation (he is going to shoot me) -> reaction (panic)... The reaction is, of course, something happening, so we can go right back into that cycle again. For panic, I try to keep reasoning tiny or simply implied because panic requires anticipation of negative outcome without calm reasoning. Better yet, this pattern allows me to bring on an out of character moment that feels entirely justified. The pacifist hitting someone, the good guy doing something slightly evil, etc.. Even though this is an action scene I am still trying to give my reader that same feeling as the tense endgame. Bursts of action followed by enough time where anticipation can do its best work. Only you know what the scene is supposed to do. So only you can tune it to make it do that. My general advice is usually that any scene worth including is worth fully committing to. Sometimes we writers rush through a scene to get to the next bit. It is okay to do that as long as we go back and give that scene as much love as the others later on.
31,836,434
If a library project defines some variables and utility functions in its stdafx.h/cpp, will these be visible throughout application projects built on top of the library?
2015/08/05
[ "https://Stackoverflow.com/questions/31836434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197229/" ]
Yes and no, they need to be exported just as anything else. Precompiled headers are there to speed up compilation, they do not affect the produced executable/library.
No, it is an implementation detail for the library project only. And in general it does not contain declarations that are exposed by the library, they are exposed by a .h file that was meant to be #included in your own project's source files. The library's stdafx.h *may* include that .h file as well, it isn't very common. You use your own precompiled header, if you want to #include the library's .h file(s) then that's up to you. Useful only if you use the library declarations in multiple source files of your own project and the library is stable.
5,866,441
I am developing an integration test involving a couple of webapps, but when compiling using maven, a linkageError is given due to version inconsistency between spring and spring context, even though I use the same version for both of them. The pom.xml used is the following one: .... ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> </dependencies> ``` ... ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Copies the war from repository and deploys on a jetty server --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.1.0-SNAPSHOT</version> <configuration> <!-- Container configuration --> <container> <containerId>jetty6x</containerId> <type>embedded</type> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> </container> <!-- Configuration with the required deployable wars --> <configuration> <deployables> <deployable> <groupId>group</groupId> <artifactId>artifact</artifactId> <type>war</type> <properties> <context>war context</context> </properties> </deployable> </deployables> </configuration> <!-- Don't wait, execute the tests after the container is started --> <wait>false</wait> </configuration> <executions> <execution> <id>start-container</id> <phase>generate-sources</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-container</id> <phase>post-verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ``` ... The error produced when prompting mvn verify: ``` 2011-05-03 09:19:54.919:WARN::failed ContextHandlerCollection@10cafa1: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::failed HandlerCollection@1de7497: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::Error starting handlers java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:61) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:249) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.cargo.container.jetty.internal.JettyExecutorThread.run(JettyExecutorThread.java:69) ``` Thanks for your replies.
2011/05/03
[ "https://Stackoverflow.com/questions/5866441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735663/" ]
do (not) use singleton anti-pattern, with a static class method. <http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/>
Have you ever heard about constructors? <http://www.javabeginner.com/learn-java/java-constructors>
5,866,441
I am developing an integration test involving a couple of webapps, but when compiling using maven, a linkageError is given due to version inconsistency between spring and spring context, even though I use the same version for both of them. The pom.xml used is the following one: .... ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> </dependencies> ``` ... ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Copies the war from repository and deploys on a jetty server --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.1.0-SNAPSHOT</version> <configuration> <!-- Container configuration --> <container> <containerId>jetty6x</containerId> <type>embedded</type> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> </container> <!-- Configuration with the required deployable wars --> <configuration> <deployables> <deployable> <groupId>group</groupId> <artifactId>artifact</artifactId> <type>war</type> <properties> <context>war context</context> </properties> </deployable> </deployables> </configuration> <!-- Don't wait, execute the tests after the container is started --> <wait>false</wait> </configuration> <executions> <execution> <id>start-container</id> <phase>generate-sources</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-container</id> <phase>post-verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ``` ... The error produced when prompting mvn verify: ``` 2011-05-03 09:19:54.919:WARN::failed ContextHandlerCollection@10cafa1: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::failed HandlerCollection@1de7497: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::Error starting handlers java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:61) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:249) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.cargo.container.jetty.internal.JettyExecutorThread.run(JettyExecutorThread.java:69) ``` Thanks for your replies.
2011/05/03
[ "https://Stackoverflow.com/questions/5866441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735663/" ]
Have you ever heard about constructors? <http://www.javabeginner.com/learn-java/java-constructors>
> > **So I wanted the execution of that code to be run only once for any number execution of that class.** > > > There's no built in language-feature for this I'm afraid. You'll have to encapsulate it using something like ``` if (!initialized) { // init ... initialized = true; } ``` (But make sure to declare such `init` methods as `synchronized` so two threads don't both initialize an object due to caching or race conditions etc.) Btw... it's a bit unclear what you mean by *"execution of that class"*. Do you mean "any number of *instantiations* of that class"?
5,866,441
I am developing an integration test involving a couple of webapps, but when compiling using maven, a linkageError is given due to version inconsistency between spring and spring context, even though I use the same version for both of them. The pom.xml used is the following one: .... ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> </dependencies> ``` ... ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Copies the war from repository and deploys on a jetty server --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.1.0-SNAPSHOT</version> <configuration> <!-- Container configuration --> <container> <containerId>jetty6x</containerId> <type>embedded</type> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> </container> <!-- Configuration with the required deployable wars --> <configuration> <deployables> <deployable> <groupId>group</groupId> <artifactId>artifact</artifactId> <type>war</type> <properties> <context>war context</context> </properties> </deployable> </deployables> </configuration> <!-- Don't wait, execute the tests after the container is started --> <wait>false</wait> </configuration> <executions> <execution> <id>start-container</id> <phase>generate-sources</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-container</id> <phase>post-verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ``` ... The error produced when prompting mvn verify: ``` 2011-05-03 09:19:54.919:WARN::failed ContextHandlerCollection@10cafa1: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::failed HandlerCollection@1de7497: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::Error starting handlers java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:61) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:249) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.cargo.container.jetty.internal.JettyExecutorThread.run(JettyExecutorThread.java:69) ``` Thanks for your replies.
2011/05/03
[ "https://Stackoverflow.com/questions/5866441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735663/" ]
Have you ever heard about constructors? <http://www.javabeginner.com/learn-java/java-constructors>
1) use the static block code: ``` public class MyClass { static { // do your thing here, it gets executed just once at class loading } } ``` 2) use a constructor, as others have previously pointed
5,866,441
I am developing an integration test involving a couple of webapps, but when compiling using maven, a linkageError is given due to version inconsistency between spring and spring context, even though I use the same version for both of them. The pom.xml used is the following one: .... ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> </dependencies> ``` ... ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Copies the war from repository and deploys on a jetty server --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.1.0-SNAPSHOT</version> <configuration> <!-- Container configuration --> <container> <containerId>jetty6x</containerId> <type>embedded</type> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> </container> <!-- Configuration with the required deployable wars --> <configuration> <deployables> <deployable> <groupId>group</groupId> <artifactId>artifact</artifactId> <type>war</type> <properties> <context>war context</context> </properties> </deployable> </deployables> </configuration> <!-- Don't wait, execute the tests after the container is started --> <wait>false</wait> </configuration> <executions> <execution> <id>start-container</id> <phase>generate-sources</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-container</id> <phase>post-verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ``` ... The error produced when prompting mvn verify: ``` 2011-05-03 09:19:54.919:WARN::failed ContextHandlerCollection@10cafa1: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::failed HandlerCollection@1de7497: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::Error starting handlers java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:61) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:249) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.cargo.container.jetty.internal.JettyExecutorThread.run(JettyExecutorThread.java:69) ``` Thanks for your replies.
2011/05/03
[ "https://Stackoverflow.com/questions/5866441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735663/" ]
do (not) use singleton anti-pattern, with a static class method. <http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/>
Couldn't you just make this init method a class method ? (In java, using the "static" keyword)
5,866,441
I am developing an integration test involving a couple of webapps, but when compiling using maven, a linkageError is given due to version inconsistency between spring and spring context, even though I use the same version for both of them. The pom.xml used is the following one: .... ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> </dependencies> ``` ... ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Copies the war from repository and deploys on a jetty server --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.1.0-SNAPSHOT</version> <configuration> <!-- Container configuration --> <container> <containerId>jetty6x</containerId> <type>embedded</type> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> </container> <!-- Configuration with the required deployable wars --> <configuration> <deployables> <deployable> <groupId>group</groupId> <artifactId>artifact</artifactId> <type>war</type> <properties> <context>war context</context> </properties> </deployable> </deployables> </configuration> <!-- Don't wait, execute the tests after the container is started --> <wait>false</wait> </configuration> <executions> <execution> <id>start-container</id> <phase>generate-sources</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-container</id> <phase>post-verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ``` ... The error produced when prompting mvn verify: ``` 2011-05-03 09:19:54.919:WARN::failed ContextHandlerCollection@10cafa1: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::failed HandlerCollection@1de7497: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::Error starting handlers java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:61) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:249) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.cargo.container.jetty.internal.JettyExecutorThread.run(JettyExecutorThread.java:69) ``` Thanks for your replies.
2011/05/03
[ "https://Stackoverflow.com/questions/5866441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735663/" ]
Couldn't you just make this init method a class method ? (In java, using the "static" keyword)
> > **So I wanted the execution of that code to be run only once for any number execution of that class.** > > > There's no built in language-feature for this I'm afraid. You'll have to encapsulate it using something like ``` if (!initialized) { // init ... initialized = true; } ``` (But make sure to declare such `init` methods as `synchronized` so two threads don't both initialize an object due to caching or race conditions etc.) Btw... it's a bit unclear what you mean by *"execution of that class"*. Do you mean "any number of *instantiations* of that class"?
5,866,441
I am developing an integration test involving a couple of webapps, but when compiling using maven, a linkageError is given due to version inconsistency between spring and spring context, even though I use the same version for both of them. The pom.xml used is the following one: .... ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> </dependencies> ``` ... ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Copies the war from repository and deploys on a jetty server --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.1.0-SNAPSHOT</version> <configuration> <!-- Container configuration --> <container> <containerId>jetty6x</containerId> <type>embedded</type> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> </container> <!-- Configuration with the required deployable wars --> <configuration> <deployables> <deployable> <groupId>group</groupId> <artifactId>artifact</artifactId> <type>war</type> <properties> <context>war context</context> </properties> </deployable> </deployables> </configuration> <!-- Don't wait, execute the tests after the container is started --> <wait>false</wait> </configuration> <executions> <execution> <id>start-container</id> <phase>generate-sources</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-container</id> <phase>post-verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ``` ... The error produced when prompting mvn verify: ``` 2011-05-03 09:19:54.919:WARN::failed ContextHandlerCollection@10cafa1: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::failed HandlerCollection@1de7497: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::Error starting handlers java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:61) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:249) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.cargo.container.jetty.internal.JettyExecutorThread.run(JettyExecutorThread.java:69) ``` Thanks for your replies.
2011/05/03
[ "https://Stackoverflow.com/questions/5866441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735663/" ]
Couldn't you just make this init method a class method ? (In java, using the "static" keyword)
1) use the static block code: ``` public class MyClass { static { // do your thing here, it gets executed just once at class loading } } ``` 2) use a constructor, as others have previously pointed
5,866,441
I am developing an integration test involving a couple of webapps, but when compiling using maven, a linkageError is given due to version inconsistency between spring and spring context, even though I use the same version for both of them. The pom.xml used is the following one: .... ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> </dependencies> ``` ... ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Copies the war from repository and deploys on a jetty server --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.1.0-SNAPSHOT</version> <configuration> <!-- Container configuration --> <container> <containerId>jetty6x</containerId> <type>embedded</type> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> </container> <!-- Configuration with the required deployable wars --> <configuration> <deployables> <deployable> <groupId>group</groupId> <artifactId>artifact</artifactId> <type>war</type> <properties> <context>war context</context> </properties> </deployable> </deployables> </configuration> <!-- Don't wait, execute the tests after the container is started --> <wait>false</wait> </configuration> <executions> <execution> <id>start-container</id> <phase>generate-sources</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-container</id> <phase>post-verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ``` ... The error produced when prompting mvn verify: ``` 2011-05-03 09:19:54.919:WARN::failed ContextHandlerCollection@10cafa1: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::failed HandlerCollection@1de7497: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::Error starting handlers java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:61) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:249) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.cargo.container.jetty.internal.JettyExecutorThread.run(JettyExecutorThread.java:69) ``` Thanks for your replies.
2011/05/03
[ "https://Stackoverflow.com/questions/5866441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735663/" ]
do (not) use singleton anti-pattern, with a static class method. <http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/>
> > **So I wanted the execution of that code to be run only once for any number execution of that class.** > > > There's no built in language-feature for this I'm afraid. You'll have to encapsulate it using something like ``` if (!initialized) { // init ... initialized = true; } ``` (But make sure to declare such `init` methods as `synchronized` so two threads don't both initialize an object due to caching or race conditions etc.) Btw... it's a bit unclear what you mean by *"execution of that class"*. Do you mean "any number of *instantiations* of that class"?
5,866,441
I am developing an integration test involving a couple of webapps, but when compiling using maven, a linkageError is given due to version inconsistency between spring and spring context, even though I use the same version for both of them. The pom.xml used is the following one: .... ``` <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.2</version> </dependency> </dependencies> ``` ... ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <!-- Copies the war from repository and deploys on a jetty server --> <plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.1.0-SNAPSHOT</version> <configuration> <!-- Container configuration --> <container> <containerId>jetty6x</containerId> <type>embedded</type> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> </dependencies> </container> <!-- Configuration with the required deployable wars --> <configuration> <deployables> <deployable> <groupId>group</groupId> <artifactId>artifact</artifactId> <type>war</type> <properties> <context>war context</context> </properties> </deployable> </deployables> </configuration> <!-- Don't wait, execute the tests after the container is started --> <wait>false</wait> </configuration> <executions> <execution> <id>start-container</id> <phase>generate-sources</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-container</id> <phase>post-verify</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> ``` ... The error produced when prompting mvn verify: ``` 2011-05-03 09:19:54.919:WARN::failed ContextHandlerCollection@10cafa1: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::failed HandlerCollection@1de7497: java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature 2011-05-03 09:19:54.919:WARN::Error starting handlers java.lang.LinkageError: loader constraint violation: when resolving overridden method "org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.getResourceByPath(Ljava/lang/String;)Lorg/springframework/core/io/Resource;" the class loader (instance of org/mortbay/jetty/webapp/WebAppClassLoader) of the current class, org/springframework/web/context/support/AbstractRefreshableWebApplicationContext, and its superclass loader (instance of java/net/URLClassLoader), have different Class objects for the type org/springframework/core/io/Resource used in the signature at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389) at java.lang.Class.getConstructor0(Class.java:2699) at java.lang.Class.getDeclaredConstructor(Class.java:1985) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:61) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:249) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:549) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1282) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:518) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:499) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.jetty.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:156) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerCollection.doStart(HandlerCollection.java:152) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130) at org.mortbay.jetty.Server.doStart(Server.java:224) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.codehaus.cargo.container.jetty.internal.JettyExecutorThread.run(JettyExecutorThread.java:69) ``` Thanks for your replies.
2011/05/03
[ "https://Stackoverflow.com/questions/5866441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735663/" ]
do (not) use singleton anti-pattern, with a static class method. <http://thetechcandy.wordpress.com/2009/12/02/singletons-is-anti-pattern/>
1) use the static block code: ``` public class MyClass { static { // do your thing here, it gets executed just once at class loading } } ``` 2) use a constructor, as others have previously pointed
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
One option I haven't seen yet is [*Boasting.*](http://www.dictionary.com/browse/boast) Unlike the other terms I've seen mentioned, Boasting is speaking very highly of yourself and implying that you're superior to your opponents, instead of simply saying your opponents are inferior. As such, it's considered slightly more positive & polite than trying to belittle your opposition. Since your first example was about Heroes, I believe Boasting is a better fit.
US presidential debates are excellent examples. They belittle each other but there are rules. It's almost like a show. Obviously they won't physically fight, but the concept is the same. The word you are looking for is very environment based. I would recommend 'taunt', 'berate', 'degrade' or 'belittle' versus slang terms. You could say Hector was 'dissing' Patroclus, but it doesnt have the same effect. Maybe in something like Romeo + Juliet it would
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
Somewhat more formal: > > **hector** (hĕkˈtər)► v. To intimidate or dominate in a blustering way. -[wordnik](http://www.wordnik.com/words/hector) > > >
Try "posturing" It's a little more generic, includes ideas like boasting, posing, etc.
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
One you probably don't want to use because I don't think it's widespread outside cricket, but I mention it out of interest, is Sledging. > > Sledging is a term used in cricket to describe the practice whereby > some players seek to gain an advantage by insulting or verbally > intimidating the opposing player. > > > <https://en.wikipedia.org/wiki/Sledging_(cricket)>
In the context of heroes, the phrase **verbal jousting** might be appropriate. It means to have a battle of words, a verbal back and forth between individuals to see who can come out on top, and generally suggests an egotistic and sporting motive. *Verbal jousting* is evocative of medieval combat and its inherent sense of pride and honor. > > "As soon as the banners fell and their eyes met, the heroes began their traditional bout of verbal jousting." > > > "The smack talk went on all night, a verbal joust of epic proportions." > > > "In general, English comedians are fond of quick wit and verbal jousting." > > > Hope this helps! It's a fun phrase!
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
See synonyms for "taunt": *mock, belittle, deride, insult, derogate, disparage, deprecate, ridicule, jeer, put down, make fun of*, as well as slang terms like *disrespect, trash, or hate on*. "Taunt" is the verb closest to your meaning, but not necessarily the one you want to use since it doesn't automatically mean "insult". "Trash" is a good slang term in a contemporary context, but not necessarily when talking about mythical or historical figures since it would be a modern anachronism.
I find that "chest-beating" (or "chest-thumping") works well here. Depending on the context, it might also be "ritual chest-beating". Of course the phrase is lent from the behavior of great apes. Now that's generally only a behavior you see with male apes (and they have the better-suited anatomy for it) but, uhm, the behavior you describe is really observable a whole lot more often with male humans as well.
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
In the context of heroes, the phrase **verbal jousting** might be appropriate. It means to have a battle of words, a verbal back and forth between individuals to see who can come out on top, and generally suggests an egotistic and sporting motive. *Verbal jousting* is evocative of medieval combat and its inherent sense of pride and honor. > > "As soon as the banners fell and their eyes met, the heroes began their traditional bout of verbal jousting." > > > "The smack talk went on all night, a verbal joust of epic proportions." > > > "In general, English comedians are fond of quick wit and verbal jousting." > > > Hope this helps! It's a fun phrase!
My first thought was taunt, but I think a better word is **[harangue](http://www.collinsdictionary.com/dictionary/english/harangue)** since it can include both boasting and taunting. I do have to admit though that the word has lost popularity over time. But it is still sufficiently current to be known, and does not seem out of place when talking of historical events. > > verb: to address (a person or crowd) in an angry, vehement, or > forcefully persuasive way > > > The word can also be used as a noun. Examples: > > The heroes began their **haranguing**. > > > (from [story about Kit Carson](http://www.elpalacio.org/placeseries/winter07KitCarson.pdf)) > > ...the exhausted mail party was pursued by 150 hostile Indians. Carson > guided his companions into a copse of stunted trees, where they tied > their mules, then he arranged them in a skirmishers’ line. He next > stepped forward, fully exposed, and began to **harangue** the enemy in > their own language. Brewerton wrote, “Carson’s whole demeanor was now > so entirely changed that he looked like a different man. His eyes > fairly flashed, and his rifle was grasped with all the energy of an > iron will.” And the lieutenant added that Carson knew “boldness alone > could save us.” > > >
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
See synonyms for "taunt": *mock, belittle, deride, insult, derogate, disparage, deprecate, ridicule, jeer, put down, make fun of*, as well as slang terms like *disrespect, trash, or hate on*. "Taunt" is the verb closest to your meaning, but not necessarily the one you want to use since it doesn't automatically mean "insult". "Trash" is a good slang term in a contemporary context, but not necessarily when talking about mythical or historical figures since it would be a modern anachronism.
Somewhat more formal: > > **hector** (hĕkˈtər)► v. To intimidate or dominate in a blustering way. -[wordnik](http://www.wordnik.com/words/hector) > > >
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
See synonyms for "taunt": *mock, belittle, deride, insult, derogate, disparage, deprecate, ridicule, jeer, put down, make fun of*, as well as slang terms like *disrespect, trash, or hate on*. "Taunt" is the verb closest to your meaning, but not necessarily the one you want to use since it doesn't automatically mean "insult". "Trash" is a good slang term in a contemporary context, but not necessarily when talking about mythical or historical figures since it would be a modern anachronism.
In the context of heroes, the phrase **verbal jousting** might be appropriate. It means to have a battle of words, a verbal back and forth between individuals to see who can come out on top, and generally suggests an egotistic and sporting motive. *Verbal jousting* is evocative of medieval combat and its inherent sense of pride and honor. > > "As soon as the banners fell and their eyes met, the heroes began their traditional bout of verbal jousting." > > > "The smack talk went on all night, a verbal joust of epic proportions." > > > "In general, English comedians are fond of quick wit and verbal jousting." > > > Hope this helps! It's a fun phrase!
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
One option I haven't seen yet is [*Boasting.*](http://www.dictionary.com/browse/boast) Unlike the other terms I've seen mentioned, Boasting is speaking very highly of yourself and implying that you're superior to your opponents, instead of simply saying your opponents are inferior. As such, it's considered slightly more positive & polite than trying to belittle your opposition. Since your first example was about Heroes, I believe Boasting is a better fit.
In the context of opponents, you could try the phrase "Provocation" which stems from the verb "Provocate" meaning to provoke something. This would be a bad-natured way of trying to get your enemy to fight. It has an angry connotation to it. An example of a good phrase would be "exaggerated". The opponents want to show off to each other who has the better skills to fight. Sources: www.thesaurus.com for ideas of other synonym relations. Hope this helped with some ideas.
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
US presidential debates are excellent examples. They belittle each other but there are rules. It's almost like a show. Obviously they won't physically fight, but the concept is the same. The word you are looking for is very environment based. I would recommend 'taunt', 'berate', 'degrade' or 'belittle' versus slang terms. You could say Hector was 'dissing' Patroclus, but it doesnt have the same effect. Maybe in something like Romeo + Juliet it would
One word you may try is "bantering." The dictionary definition denotes exchanging belittling remarks in a teasing or good-natured way, as between friends. However, common usage today doesn't necessarily include the connotation of playfulness or good nature.
104,906
What's the difference between 'lead', 'cable' and 'wire'? And which of these words is more commonly used for, say, household appliances or office equipment?
2016/09/27
[ "https://ell.stackexchange.com/questions/104906", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/41115/" ]
I find that "chest-beating" (or "chest-thumping") works well here. Depending on the context, it might also be "ritual chest-beating". Of course the phrase is lent from the behavior of great apes. Now that's generally only a behavior you see with male apes (and they have the better-suited anatomy for it) but, uhm, the behavior you describe is really observable a whole lot more often with male humans as well.
Try "posturing" It's a little more generic, includes ideas like boasting, posing, etc.
147,656
Is there any publicly available printer at Taiwan Taoyuan International Airport (TPE) that airline passengers can use?
2019/09/27
[ "https://travel.stackexchange.com/questions/147656", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/1810/" ]
There are a couple businesses within Taiwan Taoyuan International Airport that provide printing / photocopying service. 7-eleven / ibon Kiosk in Terminal 1 =================================== The [7-eleven](https://www.taoyuan-airport.com/english/store2_detail/7-11) in Terminal 1 (B1) has [two ibon Kiosks](http://www.ibon.com.tw/event/FLA/index.html), a self-service machine that supports printing and scanning of documents (instructions [here](http://www.ibon.com.tw/pdf/web/Picture_print.html)): > > You can print out any documents or pictures saved in the memory card, USB, or email the attachment to [email protected] at ibon Kiosk in any 7-ELEVEN stores anytime. All the printing requirements will be easily met. > (Options of paper types: A4, A4-160lb, A3 and 4x6) > > > ibon has independently confirmed the location of their kiosks via [their own directory](http://www.ibon.com.tw/retail_inquiry.aspx#gsc.tab=0) (Chinese only, but I can confirm the address is that of TPE Terminal 1): [![Search result on ibon kiosk in Taiwan Taoyuan International Airport, result in Chinese.](https://i.stack.imgur.com/b32cT.png)](https://i.stack.imgur.com/b32cT.png) hi-life - may or may not be closed ================================== While [hi-life](http://www.hilife.com.tw/serviceInfo_photocopyFax.aspx) provides printing, photocopying and faxing services in their stores. It looks like they do not have a store in TPE anymore (a search within TPE's own website yielded a cached link that [leads to nothing](http://www.hilife.com.tw/serviceInfo_photocopyFax.aspx) upon clicking through). Post office in Terminal 2 ========================= The [post office](https://www.taoyuan-airport.com/english/store3_1/1102) in Terminal 2 (1F) also provides photocopying services, as [confirmed on their directory](https://www.post.gov.tw/post/internet/I_location/index_post.jsp?prsb_no=012135-8) (Chinese only, keyword: 提供影印服務 - providing photocopying services). As of today, the charge is as follow (translation mine): > > 影印服務 > > > 影印文件用紙僅提供A4(21×29.7公分)、A3(29.7×42公分)兩種規格紙張,A4每頁新台幣2元、A3每頁新台幣4元,紙張正反兩面均影印者,按上述收費標準加倍收取。 > > > B5紙張(18.2×25.7公分)比照A4收費、B4紙張(25.7×36.4公分)比照A3收費。 > > > Photocoping services > > > We only provide photocopies in A4 and A3 format. A4 photocopying cost NTD 2 per page, A3 photocopying cost NTD 4 per page. Double side printing cost double. > > > B5 paper photocopying is charged at A4 paper rate, B4 paper photocopying is charged at A3 rate. > > >
[According to TripAdvisor](https://www.tripadvisor.com/ShowTopic-g293910-i9303-k12083657-Taoyuan_Airport_Printing_Area-Taiwan.html), the 7-11 convenience store has printers where you can print, scan and fax. I can't really confirm based [on their website](https://www.7-11.com.tw/in/en.html) (in English, there is a Taiwan website too) because it's not explicit on there but there is [a phone number](https://www.taoyuan-airport.com/english/store2_detail/7-11) to the terminal where the store is located that you probably can call to be sure.
2,533,725
I want to find the eigenvalues of the matrix, $$ \begin{bmatrix} 0 & cos(k)+sin(k) \\ cos(k)+sin(k) & 0\\ \end{bmatrix}.$$ With diagonalize {{0, cos(k)+sin(k)}, {cos(k)+sin(k), 0}} I get the two eigenvalues: $$\pm\sqrt{sin(2k)+1}$$ With eigenvalues {{0, cos(k)+sin(k)}, {cos(k)+sin(k), 0}} I get: $$\pm(cos(k)+sin(k))$$ Why do I get different results?
2017/11/23
[ "https://math.stackexchange.com/questions/2533725", "https://math.stackexchange.com", "https://math.stackexchange.com/users/415122/" ]
$$\pm \sqrt{\sin(2k) + 1} = \pm \sqrt{(\sin(k) + \cos(k))^2} = \pm (\sin(k) + \cos(k))$$
Both answers are correct. For each real number *k*, the number $\sin(2k)+1$ is non-negative; therefore, it has $2$ square roots. Note that$$\bigl(\cos(k)+\sin(k)\bigr)^2=1+2\sin(k)\cos(k)=1+\sin(2k).$$Therefore, the square roots of $\sin(2k)+1$ are $\pm\bigl(\cos(k)+\sin(k)\bigr)$.
368,241
Let $X\_1, X\_2,\dots$ be a sequence of random variables with $\lim\_{n\to +\infty} E[|X\_n|] = 0$. Is it correct or wrong that the sequence $X\_n$ must converge to $0$ in probability?
2013/04/21
[ "https://math.stackexchange.com/questions/368241", "https://math.stackexchange.com", "https://math.stackexchange.com/users/60571/" ]
Yes, it follows from Chebyshev's inequality. For every $\varepsilon > 0$, we have $$\mathrm{Pr}(|X\_n| > \varepsilon) \leq {\mathbb E}[|X\_n|]/\varepsilon \to 0 \text{ as } n\to\infty.$$
Yes, as a consequence of the inequality $\mu\{|X\_n|\geqslant \varepsilon\}\leqslant\frac 1{\varepsilon}E[|X\_n|]$ for each positive $\varepsilon$.
2,911,315
I came across the following question while studying logic and cannot find a solution for it anywhere. I am studying by myself and think I just don't know exactly the right terms to search for it online (I'm not sure it is called a logical equation so excuse the title of this question in case it isn't): --- Given the proposition $P$, it's logical value is defined as $[P] = 0$, in case $P$ is false, and $[P] = 1$, in case $P$ is true. Consider the following open sentences defined in the set of integers: $ P\_i(x): x \le 5$ $ P\_{ii}(x): x \ge 3$ $ P\_{iii}(x): $ **x is odd** $ P\_{iv}(x): x \ge 6$ How many solutions does the following equation have? $ x = [P\_i(x)] + 2 \cdot[P\_{ii}(x)]+3\cdot[P\_{iii}(x)]+4\cdot[P\_{iv}(x)]$ --- I've made this [jsfiddle](https://jsfiddle.net/6z1g3472/4) and from there, I can count the number of solutions through a loop. In this case I've looped from 0 to 1000 and it yields 2 solutions. Though I can clearly reason it wouldn't be possible for a very large number to work here, since these are all sums of multiplications of 0s or 1s, I am having a hard time articulating exactly why. How would you go about finding the largest number possible, in this very specific case? So you wouldn't have to loop through values of X too far off from it?
2018/09/10
[ "https://math.stackexchange.com/questions/2911315", "https://math.stackexchange.com", "https://math.stackexchange.com/users/110324/" ]
First, let's observe that $[P\_i(x)]+4\cdot[P\_{iv}(x)]=1+3\cdot[P\_{iv}(x)]$. We can check three cases: 1. $x<3$: Our equation becomes $x=1+3\cdot(x\%2)$ where $\%$ is the mod operator. Clearly, no even number can satisfy this equation, and neither can an odd number. So, $x\geq3$. 2. $3\leq x<6$ We can convert the equation to $x=3+3\cdot(x\%2)$. Again, no even or odd numbers can satisfy this equation, so we move on to case three. 3. $x\geq6$ Since we know any solution must satisfy this, we can convert the equation to $6+3\cdot(x\%2)$. So, $x=6$ and $x=9$ are solutions. Hence, there are $\color{red}{2}$ solutions to this equation.
Here's how this problem would be coded in the SMT-LIB format, understood by most SMT solvers. ``` (define-fun Pi ((x Int)) Int (ite (<= x 5) 1 0)) (define-fun Pii ((x Int)) Int (ite (>= x 3) 1 0)) (define-fun Piii ((x Int)) Int (mod x 2)) (define-fun Piv ((x Int)) Int (ite (>= x 6) 1 0)) (declare-const x Int) (assert (= x (+ (Pi x) (* 2 (Pii x)) (* 3 (Piii x)) (* 4 (Piv x))))) (check-sat) (get-model) (assert (not (= x 6))) (check-sat) (get-model) (assert (not (= x 9))) (check-sat) (exit) ``` After getting the first solution, we add a constraint that forbids that solution and solve again. When we do it again, the SMT solver reports that the constraints are now unsatisfiable; hence we know that we have enumerated all solutions.
2,911,315
I came across the following question while studying logic and cannot find a solution for it anywhere. I am studying by myself and think I just don't know exactly the right terms to search for it online (I'm not sure it is called a logical equation so excuse the title of this question in case it isn't): --- Given the proposition $P$, it's logical value is defined as $[P] = 0$, in case $P$ is false, and $[P] = 1$, in case $P$ is true. Consider the following open sentences defined in the set of integers: $ P\_i(x): x \le 5$ $ P\_{ii}(x): x \ge 3$ $ P\_{iii}(x): $ **x is odd** $ P\_{iv}(x): x \ge 6$ How many solutions does the following equation have? $ x = [P\_i(x)] + 2 \cdot[P\_{ii}(x)]+3\cdot[P\_{iii}(x)]+4\cdot[P\_{iv}(x)]$ --- I've made this [jsfiddle](https://jsfiddle.net/6z1g3472/4) and from there, I can count the number of solutions through a loop. In this case I've looped from 0 to 1000 and it yields 2 solutions. Though I can clearly reason it wouldn't be possible for a very large number to work here, since these are all sums of multiplications of 0s or 1s, I am having a hard time articulating exactly why. How would you go about finding the largest number possible, in this very specific case? So you wouldn't have to loop through values of X too far off from it?
2018/09/10
[ "https://math.stackexchange.com/questions/2911315", "https://math.stackexchange.com", "https://math.stackexchange.com/users/110324/" ]
First, let's observe that $[P\_i(x)]+4\cdot[P\_{iv}(x)]=1+3\cdot[P\_{iv}(x)]$. We can check three cases: 1. $x<3$: Our equation becomes $x=1+3\cdot(x\%2)$ where $\%$ is the mod operator. Clearly, no even number can satisfy this equation, and neither can an odd number. So, $x\geq3$. 2. $3\leq x<6$ We can convert the equation to $x=3+3\cdot(x\%2)$. Again, no even or odd numbers can satisfy this equation, so we move on to case three. 3. $x\geq6$ Since we know any solution must satisfy this, we can convert the equation to $6+3\cdot(x\%2)$. So, $x=6$ and $x=9$ are solutions. Hence, there are $\color{red}{2}$ solutions to this equation.
In addition to @Rushabh Mehta's answer: note that $[P\_i]$ can be seen as a "classic" (aka Pre-Calculus) function. For example, $f\_1=[P\_1]$ is simply the function $$f\_1(x)=[P\_1(x)]=\left\{ \begin{array}{rl} 1, & x \leqslant 5 \\ 0, &x>5 \end{array} \right.$$ Therefore, you can study the given equation $x=f\_1(x)+2f\_2(x)+3f\_3(x)+4f\_4(x)$ using all techniques you already knows for this kind of problems: considering cases (as in Rushabh Mehta's answer), drawing the graph carefully,...
2,911,315
I came across the following question while studying logic and cannot find a solution for it anywhere. I am studying by myself and think I just don't know exactly the right terms to search for it online (I'm not sure it is called a logical equation so excuse the title of this question in case it isn't): --- Given the proposition $P$, it's logical value is defined as $[P] = 0$, in case $P$ is false, and $[P] = 1$, in case $P$ is true. Consider the following open sentences defined in the set of integers: $ P\_i(x): x \le 5$ $ P\_{ii}(x): x \ge 3$ $ P\_{iii}(x): $ **x is odd** $ P\_{iv}(x): x \ge 6$ How many solutions does the following equation have? $ x = [P\_i(x)] + 2 \cdot[P\_{ii}(x)]+3\cdot[P\_{iii}(x)]+4\cdot[P\_{iv}(x)]$ --- I've made this [jsfiddle](https://jsfiddle.net/6z1g3472/4) and from there, I can count the number of solutions through a loop. In this case I've looped from 0 to 1000 and it yields 2 solutions. Though I can clearly reason it wouldn't be possible for a very large number to work here, since these are all sums of multiplications of 0s or 1s, I am having a hard time articulating exactly why. How would you go about finding the largest number possible, in this very specific case? So you wouldn't have to loop through values of X too far off from it?
2018/09/10
[ "https://math.stackexchange.com/questions/2911315", "https://math.stackexchange.com", "https://math.stackexchange.com/users/110324/" ]
First, let's observe that $[P\_i(x)]+4\cdot[P\_{iv}(x)]=1+3\cdot[P\_{iv}(x)]$. We can check three cases: 1. $x<3$: Our equation becomes $x=1+3\cdot(x\%2)$ where $\%$ is the mod operator. Clearly, no even number can satisfy this equation, and neither can an odd number. So, $x\geq3$. 2. $3\leq x<6$ We can convert the equation to $x=3+3\cdot(x\%2)$. Again, no even or odd numbers can satisfy this equation, so we move on to case three. 3. $x\geq6$ Since we know any solution must satisfy this, we can convert the equation to $6+3\cdot(x\%2)$. So, $x=6$ and $x=9$ are solutions. Hence, there are $\color{red}{2}$ solutions to this equation.
Other answers show how to get a full solution, with a bit of thought/work. But a very quick observation that narrows down the possibilities is that **since logical functions can only take values $0$ and $1$, the right-hand side can’t be more than $1 + 2\cdot1 + 3\cdot1 + 4\cdot1 = 10$, and can’t be less than $0$.** So the only values you need to try for $x$ are $\{0, 1, …, 10\}$. This is something always worth thinking of: when some complex function (like the right-hand side here) is built out of other functions, if you know restrictions/bounds on the pieces it’s build out of, then those will often give restrictions/bounds on the complex function. (Justifying the bounds in detail: if $a \geq 0$ and $0 \leq b \leq 1$, then $0 \leq ab \leq a$. So $0 \leq 2\cdot [P\_2(x)] \leq 2$, and so on; so for any $x$, $$0 = 0 + 0 + 0 + 0 \leq [P\_1(x)] + 2\cdot [P\_2(x)] + 3\cdot [P\_3(x)] + 4\cdot [P\_4(x)] \leq 1 + 2 + 3 + 4 = 10$$ and so in particular, if $x = [P\_1(x)] + 2\cdot [P\_2(x)] + 3\cdot [P\_3(x)] + 4\cdot [P\_4(x)]$, then $0 \leq x \leq 10$.)
2,911,315
I came across the following question while studying logic and cannot find a solution for it anywhere. I am studying by myself and think I just don't know exactly the right terms to search for it online (I'm not sure it is called a logical equation so excuse the title of this question in case it isn't): --- Given the proposition $P$, it's logical value is defined as $[P] = 0$, in case $P$ is false, and $[P] = 1$, in case $P$ is true. Consider the following open sentences defined in the set of integers: $ P\_i(x): x \le 5$ $ P\_{ii}(x): x \ge 3$ $ P\_{iii}(x): $ **x is odd** $ P\_{iv}(x): x \ge 6$ How many solutions does the following equation have? $ x = [P\_i(x)] + 2 \cdot[P\_{ii}(x)]+3\cdot[P\_{iii}(x)]+4\cdot[P\_{iv}(x)]$ --- I've made this [jsfiddle](https://jsfiddle.net/6z1g3472/4) and from there, I can count the number of solutions through a loop. In this case I've looped from 0 to 1000 and it yields 2 solutions. Though I can clearly reason it wouldn't be possible for a very large number to work here, since these are all sums of multiplications of 0s or 1s, I am having a hard time articulating exactly why. How would you go about finding the largest number possible, in this very specific case? So you wouldn't have to loop through values of X too far off from it?
2018/09/10
[ "https://math.stackexchange.com/questions/2911315", "https://math.stackexchange.com", "https://math.stackexchange.com/users/110324/" ]
Here's how this problem would be coded in the SMT-LIB format, understood by most SMT solvers. ``` (define-fun Pi ((x Int)) Int (ite (<= x 5) 1 0)) (define-fun Pii ((x Int)) Int (ite (>= x 3) 1 0)) (define-fun Piii ((x Int)) Int (mod x 2)) (define-fun Piv ((x Int)) Int (ite (>= x 6) 1 0)) (declare-const x Int) (assert (= x (+ (Pi x) (* 2 (Pii x)) (* 3 (Piii x)) (* 4 (Piv x))))) (check-sat) (get-model) (assert (not (= x 6))) (check-sat) (get-model) (assert (not (= x 9))) (check-sat) (exit) ``` After getting the first solution, we add a constraint that forbids that solution and solve again. When we do it again, the SMT solver reports that the constraints are now unsatisfiable; hence we know that we have enumerated all solutions.
In addition to @Rushabh Mehta's answer: note that $[P\_i]$ can be seen as a "classic" (aka Pre-Calculus) function. For example, $f\_1=[P\_1]$ is simply the function $$f\_1(x)=[P\_1(x)]=\left\{ \begin{array}{rl} 1, & x \leqslant 5 \\ 0, &x>5 \end{array} \right.$$ Therefore, you can study the given equation $x=f\_1(x)+2f\_2(x)+3f\_3(x)+4f\_4(x)$ using all techniques you already knows for this kind of problems: considering cases (as in Rushabh Mehta's answer), drawing the graph carefully,...
2,911,315
I came across the following question while studying logic and cannot find a solution for it anywhere. I am studying by myself and think I just don't know exactly the right terms to search for it online (I'm not sure it is called a logical equation so excuse the title of this question in case it isn't): --- Given the proposition $P$, it's logical value is defined as $[P] = 0$, in case $P$ is false, and $[P] = 1$, in case $P$ is true. Consider the following open sentences defined in the set of integers: $ P\_i(x): x \le 5$ $ P\_{ii}(x): x \ge 3$ $ P\_{iii}(x): $ **x is odd** $ P\_{iv}(x): x \ge 6$ How many solutions does the following equation have? $ x = [P\_i(x)] + 2 \cdot[P\_{ii}(x)]+3\cdot[P\_{iii}(x)]+4\cdot[P\_{iv}(x)]$ --- I've made this [jsfiddle](https://jsfiddle.net/6z1g3472/4) and from there, I can count the number of solutions through a loop. In this case I've looped from 0 to 1000 and it yields 2 solutions. Though I can clearly reason it wouldn't be possible for a very large number to work here, since these are all sums of multiplications of 0s or 1s, I am having a hard time articulating exactly why. How would you go about finding the largest number possible, in this very specific case? So you wouldn't have to loop through values of X too far off from it?
2018/09/10
[ "https://math.stackexchange.com/questions/2911315", "https://math.stackexchange.com", "https://math.stackexchange.com/users/110324/" ]
Other answers show how to get a full solution, with a bit of thought/work. But a very quick observation that narrows down the possibilities is that **since logical functions can only take values $0$ and $1$, the right-hand side can’t be more than $1 + 2\cdot1 + 3\cdot1 + 4\cdot1 = 10$, and can’t be less than $0$.** So the only values you need to try for $x$ are $\{0, 1, …, 10\}$. This is something always worth thinking of: when some complex function (like the right-hand side here) is built out of other functions, if you know restrictions/bounds on the pieces it’s build out of, then those will often give restrictions/bounds on the complex function. (Justifying the bounds in detail: if $a \geq 0$ and $0 \leq b \leq 1$, then $0 \leq ab \leq a$. So $0 \leq 2\cdot [P\_2(x)] \leq 2$, and so on; so for any $x$, $$0 = 0 + 0 + 0 + 0 \leq [P\_1(x)] + 2\cdot [P\_2(x)] + 3\cdot [P\_3(x)] + 4\cdot [P\_4(x)] \leq 1 + 2 + 3 + 4 = 10$$ and so in particular, if $x = [P\_1(x)] + 2\cdot [P\_2(x)] + 3\cdot [P\_3(x)] + 4\cdot [P\_4(x)]$, then $0 \leq x \leq 10$.)
In addition to @Rushabh Mehta's answer: note that $[P\_i]$ can be seen as a "classic" (aka Pre-Calculus) function. For example, $f\_1=[P\_1]$ is simply the function $$f\_1(x)=[P\_1(x)]=\left\{ \begin{array}{rl} 1, & x \leqslant 5 \\ 0, &x>5 \end{array} \right.$$ Therefore, you can study the given equation $x=f\_1(x)+2f\_2(x)+3f\_3(x)+4f\_4(x)$ using all techniques you already knows for this kind of problems: considering cases (as in Rushabh Mehta's answer), drawing the graph carefully,...
21,731,207
I'm ashamed to admit that I don't know how to clear a `UITextView`. By clearing, I mean leaving its text blank and removing all of its attributes. I thought setting it to `nil` would be enough, but the attributes of the first character remain there, silently waiting until I type again to be added. For example, the following code has a vanilla `UITextView` that can be cleared on double tap (`doubleTapAction:`). When loaded, I add a custom attribute that should also be removed when the `UITextView` is cleared. ``` @implementation HPViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test"]; [attributedString addAttributes:@{@"attribute" : @"value"} range:NSMakeRange(0, 1)]; self.textView.attributedText = attributedString; } - (IBAction)doubleTapAction:(id)sender { self.textView.text = nil; // Also tried: // self.textView.text = @""; // self.textView.attributedText = nil; // self.textView.attributedText = [[NSAttributedString alloc] initWithString:@""]; } - (void)textViewDidChange:(UITextView *)textView { NSLog(@"%@", textView.attributedText); } @end ``` Clearing the `UITextView` and then typing the letter "d" logs the following: ``` d{ NSFont = "<UICTFont: 0x8a7e4e0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; attribute = value; } ``` My custom attribute is still there! Is this a bug or expected behaviour?
2014/02/12
[ "https://Stackoverflow.com/questions/21731207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143378/" ]
This awful hack does the trick: ``` self.textView.text = @"Something, doesn't matter what as long as it's not empty"; self.textView.text = @""; ``` Still, it would be nice to confirm if this is a bug or expected behaviour. I couldn't find anything in the documentation about it.
You have to manually reset font, text color etc. to your default values. Setting attributedText always sets the UITextView's "global" attributes to those of the first letter in the attributed string.
21,731,207
I'm ashamed to admit that I don't know how to clear a `UITextView`. By clearing, I mean leaving its text blank and removing all of its attributes. I thought setting it to `nil` would be enough, but the attributes of the first character remain there, silently waiting until I type again to be added. For example, the following code has a vanilla `UITextView` that can be cleared on double tap (`doubleTapAction:`). When loaded, I add a custom attribute that should also be removed when the `UITextView` is cleared. ``` @implementation HPViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test"]; [attributedString addAttributes:@{@"attribute" : @"value"} range:NSMakeRange(0, 1)]; self.textView.attributedText = attributedString; } - (IBAction)doubleTapAction:(id)sender { self.textView.text = nil; // Also tried: // self.textView.text = @""; // self.textView.attributedText = nil; // self.textView.attributedText = [[NSAttributedString alloc] initWithString:@""]; } - (void)textViewDidChange:(UITextView *)textView { NSLog(@"%@", textView.attributedText); } @end ``` Clearing the `UITextView` and then typing the letter "d" logs the following: ``` d{ NSFont = "<UICTFont: 0x8a7e4e0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; attribute = value; } ``` My custom attribute is still there! Is this a bug or expected behaviour?
2014/02/12
[ "https://Stackoverflow.com/questions/21731207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143378/" ]
``` textView.text=@""; [textView insertText:@""]; ``` try this!
You have to manually reset font, text color etc. to your default values. Setting attributedText always sets the UITextView's "global" attributes to those of the first letter in the attributed string.
21,731,207
I'm ashamed to admit that I don't know how to clear a `UITextView`. By clearing, I mean leaving its text blank and removing all of its attributes. I thought setting it to `nil` would be enough, but the attributes of the first character remain there, silently waiting until I type again to be added. For example, the following code has a vanilla `UITextView` that can be cleared on double tap (`doubleTapAction:`). When loaded, I add a custom attribute that should also be removed when the `UITextView` is cleared. ``` @implementation HPViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test"]; [attributedString addAttributes:@{@"attribute" : @"value"} range:NSMakeRange(0, 1)]; self.textView.attributedText = attributedString; } - (IBAction)doubleTapAction:(id)sender { self.textView.text = nil; // Also tried: // self.textView.text = @""; // self.textView.attributedText = nil; // self.textView.attributedText = [[NSAttributedString alloc] initWithString:@""]; } - (void)textViewDidChange:(UITextView *)textView { NSLog(@"%@", textView.attributedText); } @end ``` Clearing the `UITextView` and then typing the letter "d" logs the following: ``` d{ NSFont = "<UICTFont: 0x8a7e4e0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; attribute = value; } ``` My custom attribute is still there! Is this a bug or expected behaviour?
2014/02/12
[ "https://Stackoverflow.com/questions/21731207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143378/" ]
This awful hack does the trick: ``` self.textView.text = @"Something, doesn't matter what as long as it's not empty"; self.textView.text = @""; ``` Still, it would be nice to confirm if this is a bug or expected behaviour. I couldn't find anything in the documentation about it.
``` textView.text=@""; [textView insertText:@""]; ``` try this!
21,731,207
I'm ashamed to admit that I don't know how to clear a `UITextView`. By clearing, I mean leaving its text blank and removing all of its attributes. I thought setting it to `nil` would be enough, but the attributes of the first character remain there, silently waiting until I type again to be added. For example, the following code has a vanilla `UITextView` that can be cleared on double tap (`doubleTapAction:`). When loaded, I add a custom attribute that should also be removed when the `UITextView` is cleared. ``` @implementation HPViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test"]; [attributedString addAttributes:@{@"attribute" : @"value"} range:NSMakeRange(0, 1)]; self.textView.attributedText = attributedString; } - (IBAction)doubleTapAction:(id)sender { self.textView.text = nil; // Also tried: // self.textView.text = @""; // self.textView.attributedText = nil; // self.textView.attributedText = [[NSAttributedString alloc] initWithString:@""]; } - (void)textViewDidChange:(UITextView *)textView { NSLog(@"%@", textView.attributedText); } @end ``` Clearing the `UITextView` and then typing the letter "d" logs the following: ``` d{ NSFont = "<UICTFont: 0x8a7e4e0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; attribute = value; } ``` My custom attribute is still there! Is this a bug or expected behaviour?
2014/02/12
[ "https://Stackoverflow.com/questions/21731207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143378/" ]
This awful hack does the trick: ``` self.textView.text = @"Something, doesn't matter what as long as it's not empty"; self.textView.text = @""; ``` Still, it would be nice to confirm if this is a bug or expected behaviour. I couldn't find anything in the documentation about it.
In my app I was seeing poor performance from the hack suggested by hpique: ``` self.textView.text = @"Something, doesn't matter what as long as it's not empty"; self.textView.text = @""; ``` The first line forces the UITextView to layout everything again. This is costly if the UITextView is used in a reused cell (in a UITableView for example). In iOS 8 and later I found it much more performant with the following reset method on my UITextView subclass: ``` - (void)reset { self.text = nil; self.font = nil; self.textColor = nil; self.textAlignment = NSTextAlignmentLeft; } ```
21,731,207
I'm ashamed to admit that I don't know how to clear a `UITextView`. By clearing, I mean leaving its text blank and removing all of its attributes. I thought setting it to `nil` would be enough, but the attributes of the first character remain there, silently waiting until I type again to be added. For example, the following code has a vanilla `UITextView` that can be cleared on double tap (`doubleTapAction:`). When loaded, I add a custom attribute that should also be removed when the `UITextView` is cleared. ``` @implementation HPViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test"]; [attributedString addAttributes:@{@"attribute" : @"value"} range:NSMakeRange(0, 1)]; self.textView.attributedText = attributedString; } - (IBAction)doubleTapAction:(id)sender { self.textView.text = nil; // Also tried: // self.textView.text = @""; // self.textView.attributedText = nil; // self.textView.attributedText = [[NSAttributedString alloc] initWithString:@""]; } - (void)textViewDidChange:(UITextView *)textView { NSLog(@"%@", textView.attributedText); } @end ``` Clearing the `UITextView` and then typing the letter "d" logs the following: ``` d{ NSFont = "<UICTFont: 0x8a7e4e0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; attribute = value; } ``` My custom attribute is still there! Is this a bug or expected behaviour?
2014/02/12
[ "https://Stackoverflow.com/questions/21731207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143378/" ]
This awful hack does the trick: ``` self.textView.text = @"Something, doesn't matter what as long as it's not empty"; self.textView.text = @""; ``` Still, it would be nice to confirm if this is a bug or expected behaviour. I couldn't find anything in the documentation about it.
There is one property which can be useful in this situation. It's `typingAttributes`. ```swift let textView = UITextView() let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 16, weight: .regular), .foregroundColor: UIColor.black, ] textView.typingAttributes = attributes ```
21,731,207
I'm ashamed to admit that I don't know how to clear a `UITextView`. By clearing, I mean leaving its text blank and removing all of its attributes. I thought setting it to `nil` would be enough, but the attributes of the first character remain there, silently waiting until I type again to be added. For example, the following code has a vanilla `UITextView` that can be cleared on double tap (`doubleTapAction:`). When loaded, I add a custom attribute that should also be removed when the `UITextView` is cleared. ``` @implementation HPViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test"]; [attributedString addAttributes:@{@"attribute" : @"value"} range:NSMakeRange(0, 1)]; self.textView.attributedText = attributedString; } - (IBAction)doubleTapAction:(id)sender { self.textView.text = nil; // Also tried: // self.textView.text = @""; // self.textView.attributedText = nil; // self.textView.attributedText = [[NSAttributedString alloc] initWithString:@""]; } - (void)textViewDidChange:(UITextView *)textView { NSLog(@"%@", textView.attributedText); } @end ``` Clearing the `UITextView` and then typing the letter "d" logs the following: ``` d{ NSFont = "<UICTFont: 0x8a7e4e0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; attribute = value; } ``` My custom attribute is still there! Is this a bug or expected behaviour?
2014/02/12
[ "https://Stackoverflow.com/questions/21731207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143378/" ]
``` textView.text=@""; [textView insertText:@""]; ``` try this!
In my app I was seeing poor performance from the hack suggested by hpique: ``` self.textView.text = @"Something, doesn't matter what as long as it's not empty"; self.textView.text = @""; ``` The first line forces the UITextView to layout everything again. This is costly if the UITextView is used in a reused cell (in a UITableView for example). In iOS 8 and later I found it much more performant with the following reset method on my UITextView subclass: ``` - (void)reset { self.text = nil; self.font = nil; self.textColor = nil; self.textAlignment = NSTextAlignmentLeft; } ```
21,731,207
I'm ashamed to admit that I don't know how to clear a `UITextView`. By clearing, I mean leaving its text blank and removing all of its attributes. I thought setting it to `nil` would be enough, but the attributes of the first character remain there, silently waiting until I type again to be added. For example, the following code has a vanilla `UITextView` that can be cleared on double tap (`doubleTapAction:`). When loaded, I add a custom attribute that should also be removed when the `UITextView` is cleared. ``` @implementation HPViewController - (void)viewDidLoad { [super viewDidLoad]; NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test"]; [attributedString addAttributes:@{@"attribute" : @"value"} range:NSMakeRange(0, 1)]; self.textView.attributedText = attributedString; } - (IBAction)doubleTapAction:(id)sender { self.textView.text = nil; // Also tried: // self.textView.text = @""; // self.textView.attributedText = nil; // self.textView.attributedText = [[NSAttributedString alloc] initWithString:@""]; } - (void)textViewDidChange:(UITextView *)textView { NSLog(@"%@", textView.attributedText); } @end ``` Clearing the `UITextView` and then typing the letter "d" logs the following: ``` d{ NSFont = "<UICTFont: 0x8a7e4e0> font-family: \"Helvetica\"; font-weight: normal; font-style: normal; font-size: 12.00pt"; NSParagraphStyle = "Alignment 4, LineSpacing 0, ParagraphSpacing 0, ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0, LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 0, Tabs (\n 28L,\n 56L,\n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n), DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection 0, HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; attribute = value; } ``` My custom attribute is still there! Is this a bug or expected behaviour?
2014/02/12
[ "https://Stackoverflow.com/questions/21731207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143378/" ]
``` textView.text=@""; [textView insertText:@""]; ``` try this!
There is one property which can be useful in this situation. It's `typingAttributes`. ```swift let textView = UITextView() let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 16, weight: .regular), .foregroundColor: UIColor.black, ] textView.typingAttributes = attributes ```
26,995,572
I make a plot like this: ``` plot( layer(x=sort(randn(1000),1), y=sort(randn(1000),1), Geom.point), layer(x=[-4,4], y=[-4,4], Geom.line(), Theme(default_color=color("black")))) ``` ![ScatterPlot](https://i.stack.imgur.com/k0YKE.png) As you can see, the white circle around the points makes the high density parts of the plot almost white. I would like to change the outer circle color of the points to black (or blue) to better show that the points are really there. From [the Gadfly documentation](http://gadflyjl.org/themes.html) it seems like the `highlight_color` argument of `Theme()` might do that, but it takes a function as argument. I don't understand how that is supposed to work. Any ideas?
2014/11/18
[ "https://Stackoverflow.com/questions/26995572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1783952/" ]
The argument name turns out to be `discrete_highlight_color`... It should be a function that modifies the colour used for the plot, typically by making it lighter (a "tint") or darker (a "shade"). In our case, we can just ignore the current colour and return black. ``` using Color using Gadfly plot( layer( x = sort(randn(1000),1), y = sort(randn(1000),1), Geom.point, # Theme(highlight_width=0.0mm) # To remove the border Theme( discrete_highlight_color = u -> LCHab(0,0,0) ) ), layer( x = [-4,4], y = [-4,4], Geom.line(), Theme(default_color=color("black")) ) ) ``` ![Scatterplot](https://i.stack.imgur.com/B6QH9.png) To find the correct argument, I first typed ``` code_lowered( Theme, () ) ``` which gives the list of arguments, and then ``` less( Gadfly.default_discrete_highlight_color ) ``` which shows how the default value is defined.
For those like me trying to solve this problem more recently, I discovered that the best way to get rid of that pesky white ring is through the theme setting `highlight_width=0pt` for example ``` plot(x=rand(10),y=rand(10),Theme(highlight_width=0pt)) ``` I had some additional themes in the below image[![an example I did](https://i.stack.imgur.com/Ie1lt.png)](https://i.stack.imgur.com/Ie1lt.png)
22,726,243
I am trying to understand pattern matching in Java. However, I am stumped by the output of the code below. It prints a count of 2 while matching "aa" against "aaaa" however I expect it to print 3 because 'a' followed by 'a' happens thrice in the given string. Can anybody explain what's the issue here? ``` Pattern p = Pattern.compile("aa"); Matcher m = p.matcher("aaaa"); int count = 0; while(m.find()) count++; System.out.println(count); ```
2014/03/29
[ "https://Stackoverflow.com/questions/22726243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/114260/" ]
The matcher will not find overlapping matches. So since the first match is found at index 0 with a length of two, it won't start looking for the next match until index 2, and the potential match starting at index 1 isn't found. If you wanted to find overlapping matches you could use `m.find(start)` where `start` is an index one higher than your previous match. For example: ``` Pattern p = Pattern.compile("aa"); Matcher m = p.matcher("aaaa"); int count = 0; int start = 0; while(m.find(start)) { count++; start = m.start() + 1; } System.out.println(count); ```
When searching for literal strings, you can also use `indexOf`: ``` public class Test { public static final void main(String[] ignored) { String toFind = "aa"; String toSearch = "aaaa"; int idxLastFound = 0; int foundCount = 0; while(idxLastFound <= (toSearch.length() - toFind.length())) { idxLastFound = toSearch.indexOf(toFind, idxLastFound); if(idxLastFound == -1) { break; } System.out.println("Found at " + idxLastFound); idxLastFound++; foundCount++; } System.out.println("Found " + foundCount + " times"); } } ``` Output: ``` [C:\java_code\]java Test Found at 0 Found at 1 Found at 2 Found 3 times ```
40,754,254
I'm working on an application that receives messages from a server. When a message is received, a notification appears. When a second message is received, it should stack instead of creating a whole new notification. I created an interface that has a method that will be run when the message is received. The `Server` object is where the message is received, and the constructor accepts the interface I mentioned above. When I initialize the server object, I pass a new instance of the listener interface, in which the method overridden creates the notification. The thought process is that every time a new notification is created, I increase the `NEW_POST_NOTI` integer by one and add it to a group. My code looks like this: ``` final int PUSHES_GROUP = 67; int NEW_POST_NOTI = 56; ``` ... ``` Server server = new Server((msg) -> { nm = NotificationManagerCompat.from(ctx); Notification noti = new NotificationCompat.Builder(ctx) .setSmallIcon(R.drawable.ic_noti) .setContentTitle("New Message") .setContentText(msg) .setGroup(PUSHES_GROUP) .build(); nm.notify(NEW_PUSH_NOTI++, noti); }); ``` That same code is run every time a message is received, but creates separate notifications for each message instead of grouping them. I also tried using `setStyle` to make it `InboxStyle`, but I'm not sure how to dynamically add notifications to that. Is there an issue with my logic or am I simply using the Notification APIs incorrectly?
2016/11/23
[ "https://Stackoverflow.com/questions/40754254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1739765/" ]
The answer was to create an `InboxStyle` instance variable, and call `addLine` on it every time a new message is received. Then, once the app calls `onResume`, reset the `InboxStyle`. So for example: ``` public class ServerService extends Service { ... NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); private static NotificationManagerCompat nm; private final Context ctx = Server.this; Server server; private static int pendingPushes = 0; private final int NEW_PUSH_NOT = 2; ... @Override public int onStartCommand(Intent i, int f, final int s) { nm = NotificationManagerCompat.from(ctx); try { server = new Server((msg) -> { pendingPushes++; style.setBigContentTitle(pendingPushes +" new pushes"); style.addLine(msg); Notification noti = new NotificationCompat.Builder(ctx) .setSmallIcon(R.drawable.ic_noti) .setStyle(style) .setGroupSummary("Click here to view") .setNumber(pendingPushes) //Should make the number in bottom right the amount of pending messages but not tested yet .build(); nm.notify(NEW_PUSH_NOT, noti); }); server.start(); } catch(IOException e) { e.printStackTrace(); } return START_STICKY; } ``` Then I created a method to restart the pending count, and close the notification. I run that in my `MainActivity` inside of the `onResume()` ``` public static void resetPendingPushes() { pendingPushes = 0; style = new NotificationCompat.InboxStyle(); if (nm != null) { nm.cancel(NEW_PUSH_NOT); } } ``` MainActivity ``` @Override protected void onResume() { super.onResume(); ServerService.resetPendingPushes(); } ``` Thanks to everyone who answered, you helped a bunch!! To anyone with a similar question, sorry if there's typos in my answer, I typed it up from my cell rather quickly.
I advise you to make use of `Notification ID` which is used in `NotificationManager`. This NotificationID basically represents a unique ID per application so if you use the same notification id then you will be able to club all your notifications. Try the following and let me know. ``` static final int MY_NOTIFICATION_ID = 1; ``` Declare a static Notification ID like that. And notify with the same! So instead of ``` nm.notify(NEW_PUSH_NOTI++, noti); ``` You write ``` nm.notify(MY_NOTIFICATION_ID, noti); ```
24,829,123
I have an n1-by-n2 bi-adjacency matrix A of a bipartite graph. The matrix A is a scipy.sparse csc matrix. I would like to plot the bipartite graph using A in networkx. Assume that the nodes are colored according to their class labels called node\_class. I could do the following: ``` import networkx as nx G = nx.from_numpy_matrix(A) graph_pos = nx.fruchterman_reingold_layout(G) degree = nx.degree(G) nx.draw(G, node_color = node_class, with_labels = False, node_size = [v * 35 for v in degree.values()]) ``` The above code works fine for a square dense adjacency matrix. However not for a non-square bi-adjacency matrix A. The error is: ``` 'Adjacency matrix is not square.' ``` Moreover the matrix A I have is a scipy.sparse matrix` because it is very large and have lots of zeros. So I would want to avoid making an (n1+n2)-by-(n1+n2) adjacency matrix by stacking A and adding zeros. I checked the documentation of NetworkX for bipartite graphs, it does not mention how to plot bi-partite graph using bi-adjacency matrix, or create a graph using bi-adjacency sparse matrix. If someone could tell me how to plot the bipartite graph, that would be great!
2014/07/18
[ "https://Stackoverflow.com/questions/24829123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2498497/" ]
I don't believe there is a NetworkX function that creates a graph from a biadjacency matrix, so you'll have to write your own. (However, they do have a [bipartite module](https://networkx.github.io/documentation/latest/reference/algorithms.bipartite.html) you should check out.) Here's one way to define a function that takes a sparse biadjacency matrix and converts it to a NetworkX graph (see the comments for explanation). ``` # Input: M scipy.sparse.csc_matrix # Output: NetworkX Graph def nx_graph_from_biadjacency_matrix(M): # Give names to the nodes in the two node sets U = [ "u{}".format(i) for i in range(M.shape[0]) ] V = [ "v{}".format(i) for i in range(M.shape[1]) ] # Create the graph and add each set of nodes G = nx.Graph() G.add_nodes_from(U, bipartite=0) G.add_nodes_from(V, bipartite=1) # Find the non-zero indices in the biadjacency matrix to connect # those nodes G.add_edges_from([ (U[i], V[j]) for i, j in zip(*M.nonzero()) ]) return G ``` See an example use case below, where I use [`nx.complete_bipartite_graph`](http://networkx.lanl.gov/reference/generated/networkx.generators.classic.complete_bipartite_graph.html#networkx.generators.classic.complete_bipartite_graph) to generate a complete graph: ``` import networkx as nx, numpy as np from networkx.algorithms import bipartite from scipy.sparse import csc_matrix import matplotlib.pyplot as plt RB = nx.complete_bipartite_graph(3, 2) A = csc_matrix(bipartite.biadjacency_matrix(RB, row_order=bipartite.sets(RB)[0])) G = nx_graph_from_biadjacency_matrix(A) nx.draw_circular(G, node_color = "red", with_labels = True) plt.show() ``` And here's the output graph: ![example-bipartite-graph](https://i.stack.imgur.com/K3yno.png)
Here is a simple example: ``` import networkx as nx import matplotlib.pyplot as plt from networkx.algorithms import matching %matplotlib inline ls=[ [0,0,0,1,1], [1,0,0,0,0], [1,0,1,0,0], [0,1,1,0,0], [1,0,0,0,0] ] g = nx.Graph() a=['a'+str(i) for i in range(len(ls))] b=['b'+str(j) for j in range(len(ls[0]))] g.add_nodes_from(a,bipartite=0) g.add_nodes_from(b,bipartite=1) for i in range(len(ls)): for j in range(len(ls[i])): if ls[i][j] != 0: g.add_edge(a[i], b[j]) pos_a={} x=0.100 const=0.100 y=1.0 for i in range(len(a)): pos_a[a[i]]=[x,y-i*const] xb=0.500 pos_b={} for i in range(len(b)): pos_b[b[i]]=[xb,y-i*const] nx.draw_networkx_nodes(g,pos_a,nodelist=a,node_color='r',node_size=300,alpha=0.8) nx.draw_networkx_nodes(g,pos_b,nodelist=b,node_color='b',node_size=300,alpha=0.8) # edges pos={} pos.update(pos_a) pos.update(pos_b) #nx.draw_networkx_edges(g,pos,edgelist=nx.edges(g),width=1,alpha=0.8,edge_color='g') nx.draw_networkx_labels(g,pos,font_size=10,font_family='sans-serif') m=matching.maximal_matching(g) nx.draw_networkx_edges(g,pos,edgelist=m,width=1,alpha=0.8,edge_color='k') plt.show() ```
29,716,167
I was working on this where I have 2 variables * $pmid * $pmid2 And a table with few variables and 2 principal columns that I am going to use for this script * pmid * pmid2 Now What I want it to do is to check if $pmid or $pmid is matching pmid in table or pmid2 any of the variables to match any of these two table columns mentioned Here's My script: ``` $selectpm = mysql_query("SELECT * FROM pm WHERE pmid=($chat_id OR $chat_id2) AND pmid2=($ chat_id OR $chat_id2)"); ``` Of Course my code is wrong its just how I tough It could work , But I don't know how exactly is supposed to work thanks !
2015/04/18
[ "https://Stackoverflow.com/questions/29716167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4316850/" ]
Please use: ``` $selectpm = mysql_query("SELECT * FROM pm WHERE pmid IN($chat_id,$chat_id2) OR pmid2 IN($chat_id,$chat_id2)"); ```
This is how you can do it ``` SELECT * FROM pm WHERE ( pmid=$chat_id OR pmid= $chat_id2 ) AND ( pmid2 = $chat_id OR pmid2 = $chat_id2 ) $selectpm = mysql_query( "SELECT * FROM pm WHERE ( pmid=$chat_id OR pmid= $chat_id2 ) AND (pmid2 = $chat_id OR pmid2 = $chat_id2)"); ``` A better way is to write the query in a variable as ``` $qry = "SELECT * FROM pm WHERE ( pmid=$chat_id OR pmid= $chat_id2 ) AND (pmid2 = $chat_id OR pmid2 = $chat_id2)" ; $selectpm = mysql_query($qry); ```
29,716,167
I was working on this where I have 2 variables * $pmid * $pmid2 And a table with few variables and 2 principal columns that I am going to use for this script * pmid * pmid2 Now What I want it to do is to check if $pmid or $pmid is matching pmid in table or pmid2 any of the variables to match any of these two table columns mentioned Here's My script: ``` $selectpm = mysql_query("SELECT * FROM pm WHERE pmid=($chat_id OR $chat_id2) AND pmid2=($ chat_id OR $chat_id2)"); ``` Of Course my code is wrong its just how I tough It could work , But I don't know how exactly is supposed to work thanks !
2015/04/18
[ "https://Stackoverflow.com/questions/29716167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4316850/" ]
Please use: ``` $selectpm = mysql_query("SELECT * FROM pm WHERE pmid IN($chat_id,$chat_id2) OR pmid2 IN($chat_id,$chat_id2)"); ```
You can use the `in` clause ``` SELECT * FROM pm WHERE pmid in ($chat_id , $chat_id2) AND pmid2 in ($chat_id , $chat_id2) ```
42,291,565
I have a windows form application. I need to store date value it should be available after the application restart. One option is saving in a file which can be accessible and modified.I have tried embedded resource but it is read only.Is there any option for windows form application to persist such variables.
2017/02/17
[ "https://Stackoverflow.com/questions/42291565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6219759/" ]
You can use a local file (xml, ini, app.config, etc...) or you can use the Windows Registry if you don't want to write it in a file.
You can use Service based database(local db) just for saving that data. At first store some default values and then update and retrieve when ever necessary. It works for me.Not sure it's efficient!
1,221,370
How can I disable Parameter Prompt in sub report at run time in Crystal Report XI? I used Ms VS 2005 and report also included. Other report features is the same Crystal Report features. Other report not show prompt at run time which are not included Sub report. Prompt appeared one is included sub report. so you may hv any suggestion. let me know pls. thanks.
2009/08/03
[ "https://Stackoverflow.com/questions/1221370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I solved it from this web site: <http://www.it-sideways.com/2011/10/how-to-disable-parameter-prompt-for.html>
Take a look at this link. [Pass parameters to a stored procedure in a Crystal Report sub report?](https://stackoverflow.com/questions/849455/pass-parameters-to-a-stored-procedure-in-a-crystal-report-sub-report) Here are two other links that could prove helpful as well. [passing parameters in crystal report](https://stackoverflow.com/questions/1006873/passing-parameters-in-crystal-report) <http://www.tek-tips.com/faqs.cfm?fid=1329>
1,221,370
How can I disable Parameter Prompt in sub report at run time in Crystal Report XI? I used Ms VS 2005 and report also included. Other report features is the same Crystal Report features. Other report not show prompt at run time which are not included Sub report. Prompt appeared one is included sub report. so you may hv any suggestion. let me know pls. thanks.
2009/08/03
[ "https://Stackoverflow.com/questions/1221370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I solved it from this web site: <http://www.it-sideways.com/2011/10/how-to-disable-parameter-prompt-for.html>
We had the same issue and resolved this by modifying our code that prints the report. Instead of setting the `ReportSource` of the `CrystalReportViewer` before setting the report parameters, set it after you have added all the report and subreport parameters.
1,221,370
How can I disable Parameter Prompt in sub report at run time in Crystal Report XI? I used Ms VS 2005 and report also included. Other report features is the same Crystal Report features. Other report not show prompt at run time which are not included Sub report. Prompt appeared one is included sub report. so you may hv any suggestion. let me know pls. thanks.
2009/08/03
[ "https://Stackoverflow.com/questions/1221370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I solved it from this web site: <http://www.it-sideways.com/2011/10/how-to-disable-parameter-prompt-for.html>
I just solved it with something very simple, I don`t know if it works in every case but in my case it did. Solution: Go to Properties of your CrystalReportViewer and set ReportSource=None
1,221,370
How can I disable Parameter Prompt in sub report at run time in Crystal Report XI? I used Ms VS 2005 and report also included. Other report features is the same Crystal Report features. Other report not show prompt at run time which are not included Sub report. Prompt appeared one is included sub report. so you may hv any suggestion. let me know pls. thanks.
2009/08/03
[ "https://Stackoverflow.com/questions/1221370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I solved it from this web site: <http://www.it-sideways.com/2011/10/how-to-disable-parameter-prompt-for.html>
Use following steps 1. Don't use CrystalReportViewer1.RefreshReport or CrystalReportViewer1.Refresh 2. Set Report source from properties to none 3. Report source must be assigned Dynamically 4. in your code have this sequence `REPORT1.Refresh() REPORT1.SetParameterValue(0, "some default value") 'assign some default value CrystalReportViewer1.ReportSource = REPORT1 'dynamically assigned report source`
3,120,927
I've read that javascript gets significant performance benefits from modifying off-dom. Earlier today, I was reading the clone documentation: > > "Note that when using the .clone() > method, we can modify the cloned > elements or their contents before > (re-)inserting them into the > document." > > > Is the implication then that if I have 1,000 LI's and I want to make a change across all of them, the most efficient method would be to clone it, modify the clone, destroy the original, and place the clone? How would you go about making this modification in the most efficient way?
2010/06/25
[ "https://Stackoverflow.com/questions/3120927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174621/" ]
Actually, the implication is that it would be more efficient to modify cloned elements before inserting them into the DOM than to insert the cloned elements into the document *and then modify them*. Whether or not clone-modify-replace is more efficient than simply modifying the elements in-place will likely depend a *lot* on what modifications you intend to make... As always, *profile your code* and then choose the option that best meets your needs based on real data. ...And while you're at it... You can "detach" a DOM element directly: just call [`removeChild()`](http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/Node.html#removeChild_org.w3c.dom.Node_) (or, since you're using jQuery, [`detach()`](https://stackoverflow.com/questions/3120927/jquery-clone-performance/3120978#3120978)) - the element will still exist as long as you retain a reference to it, and can be re-inserted after you're done making modifications. ...Oh, and regardless of which technique you end up using, you'll almost certainly see better results from removing the parent UL than from removing each of the 1K child LI elements, one at a time...
There's one more efficient method: [`.detach()`](http://api.jquery.com/detach/) them from the tree, modify, and then reinsert. However, if you only modify properties of the DOM objects, and not read them, you shouldn't trigger a reflow (which is the slow operation) anyway, at least not in firefox (from what I've read). Though detaching them, and then reattaching makes sure that there are at most two reflows.
3,120,927
I've read that javascript gets significant performance benefits from modifying off-dom. Earlier today, I was reading the clone documentation: > > "Note that when using the .clone() > method, we can modify the cloned > elements or their contents before > (re-)inserting them into the > document." > > > Is the implication then that if I have 1,000 LI's and I want to make a change across all of them, the most efficient method would be to clone it, modify the clone, destroy the original, and place the clone? How would you go about making this modification in the most efficient way?
2010/06/25
[ "https://Stackoverflow.com/questions/3120927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/174621/" ]
The detach() method is the method designed for exactly what you're trying to do: <http://api.jquery.com/detach/> Edit: It's worth a mention that everyone do their own profiling/tests, which is good, common sense advice. Plus it's fun to see the ridiculous performance gains you'll get. :) My rule of thumb is this: If you're doing manipulations on many elements that involves adding or removing or moving elements around, you should absolutely use .detach(), if you're doing something like addClass, don't use detach. If you're unsure about specific manipulations or how many qualifies as 'many', you should run a test. Here's a simple comparison I made in this question's debate: <http://jsbin.com/uwode3/5> vs <http://jsbin.com/uwode3/4>
There's one more efficient method: [`.detach()`](http://api.jquery.com/detach/) them from the tree, modify, and then reinsert. However, if you only modify properties of the DOM objects, and not read them, you shouldn't trigger a reflow (which is the slow operation) anyway, at least not in firefox (from what I've read). Though detaching them, and then reattaching makes sure that there are at most two reflows.
31,349,235
There are multiple worksheets in my workbook. One worksheet named 'Region 1' contains a formula in cell B17, =Sum(B3:B16). I'd like a formula to put in a different worksheet named 'Order Regions', cell B9, that displays the value of cell B17 in 'Region 1'. Thanks for your help.
2015/07/10
[ "https://Stackoverflow.com/questions/31349235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5104240/" ]
I solved it using an Error task and reading both output variables ResultErrors and ResultFailures. ``` <Error Condition="$(ResultErrors) > 0 Or $(ResultFailures) > 0" Text="Unit Tests didn't pass *****" /> ```
You don't mention what version of the MSBuildExtensionPack you're using, but looking at the source for [Trunk](https://github.com/mikefourie/MSBuildExtensionPack/blob/9da869d07012caa0b6e7315ac5be498b7eb2cacf/Solutions/Main/Framework/CodeQuality/NUnit.cs "Trunk") (Line 278) It looks like you need to specify The `FailOnFailures` Property in order to get their failure detection to work. Therefore ``` <Target Name="Tests"> <MSBuild.ExtensionPack.CodeQuality.NUnit Assemblies="$(DropsDir)\$(Configuration)\$(TestPrj)\$(TestPrj).dll" ToolPath="$(NUnitPath)" FailOnFailures="True" ContinueOnError="False"> <Output TaskParameter="Total" PropertyName="ResultTotal"/> <Output TaskParameter="NotRun" PropertyName="ResultNotRun"/> <Output TaskParameter="Failures" PropertyName="ResultFailures"/> <Output TaskParameter="Errors" PropertyName="ResultErrors"/> <Output TaskParameter="Inconclusive" PropertyName="ResultInconclusive"/> <Output TaskParameter="Ignored" PropertyName="ResultIgnored"/> <Output TaskParameter="Skipped" PropertyName="ResultSkipped"/> <Output TaskParameter="Invalid" PropertyName="ResultInvalid"/> </MSBuild.ExtensionPack.CodeQuality.NUnit> </Target> ```
61,479,247
I my app I am fetch some text data from the server and showing this text data in the TextView. Here is something works fine. I am add an little arrow ImageView right to the TextView and this TextView is expandable so when TextView is more then 2 lines and if anyone click this TextView it expand and again click to shrink and I am also add an little arrow image right to the TextView (so user understant that it is an expandable text), here is everything is fine all code are works perfectly but now I want to remove this litter arrow image when the TextView is under 2 lines and when TextView is more then 2 lines it show. I want to tell you one more thing that I am also add a rotation in the arrow image so when the user click the text the little arrow image rotate the 180 degree and also text is expand and when user click the text second time arrow image again rotate to his previous position and text is shrink in 2 lines. I want to remove this little arrow when the text is under 2 lies I do not want to remove the arrow image when text line more then 2, I'm guessing you understand. I am new to the Java Code and I am learning is language so now I want to learn how to do this implementation in my app, I have add my code below so that you can understand batter. ``` textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title()); my_title_layout_expand.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isTextViewClicked) { //This will shrink textview to 2 lines if it is expanded. textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title()); myTitleImageView.setRotation(imageView.getRotation() + 0); myTitleImageView.setVisibility(View.VISIBLE); textViewMyVideoTitle.setMaxLines(2); isTextViewClicked = false; } else { //This will expand the textview if it is of 2 lines textViewMyVideoTitle.setText(videoLists.get(0).getVideo_title()); myTitleImageView.setRotation(imageView.getRotation() - 180); myTitleImageView.setVisibility(View.VISIBLE); textViewMyVideoTitle.setMaxLines(Integer.MAX_VALUE); isTextViewClicked = true; } } }); ``` **So anybody can help me to achieve this code** [![enter image description here](https://i.stack.imgur.com/cuyEt.gif)](https://i.stack.imgur.com/cuyEt.gif) [![enter image description here](https://i.stack.imgur.com/s16q9.gif)](https://i.stack.imgur.com/s16q9.gif)
2020/04/28
[ "https://Stackoverflow.com/questions/61479247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8374883/" ]
When working with files across multiple agents, you should use pipeline's workflow steps like [`fileExists`](https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#fileexists-verify-if-file-exists-in-workspace), [`readFile`](https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#readfile-read-file-from-workspace), and [`writeFile`](https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#writefile-write-file-to-workspace). You can use a combination of these steps to create a new file with the desired name in the current workspace. ```groovy def sourceFile = "release-pipeline/project/dist/myFile.js" if (fileExists(file: sourceFile)) { def newFile = "release-pipeline/project/dist/myFile-1.0.js" writeFile(file: newFile, encoding: "UTF-8", text: readFile(file: sourceFile, encoding: "UTF-8")) } ```
This can be done with the [File Operations](https://plugins.jenkins.io/file-operations/) plugin: ``` pipeline { agent any stages { stage('Rename') { steps { cleanWs() fileOperations([fileCreateOperation(fileName: 'foo', fileContent: '')]) fileOperations([fileRenameOperation(destination: 'bar', source: 'foo')]) sh "ls -l" } } } } ``` The plugin has quite a list of supported [file operations](https://www.jenkins.io/doc/pipeline/steps/file-operations/).
149,947
My intention here is to combine these four spells to let me amass an essentially infinite number of Spells through infinite Simulacrum whilst maintaining RAW and RAI rules. Please note why my combination presented won’t work with citations from either whom or where you are getting your information. Everything below is assumed to have enough provisions (Food, Water, Beds, etc) to survive and the character level is of a level capable of casting all spells listed below. Step 1: Create and enter your own Demiplane full of your Provisions. Step 2: Wait 24 hours. Step 3: Cast Glyph of Warding at an 8th level, Cast Simulacrum into Glyph of Warding vía Wish Spell. Set it to trigger when I step on it and click my ruby red slippers 3 times. Step 4: Wait 24 Hours. Step 5: (Now with full spell Slots) Step on Glyph and click my ruby red slippers 3 times. Step 6: New Simulacrum is formed, Simulacrum uses 8th level Slot and 9th level spot to cast an 8th level spell, replicating step 3. Step 7: Simulacrum proceeds to waste all of it’s spell slots Creating Glyphs or casting spells for me without me having to do anything other than provide material components. Step 8: Simulacrum has used all spell slots, I Proceed to Glyph and (Per RAI) my old Simulacrum is destroyed and a New one of me with all of my spell slots is made. Step 9: Sit back and enjoy infinite spell slots essentially. Other than the caveat of having a 200GP cost for my Glyph of Warding every time, is what I said feasible albeit lengthy?
2019/06/14
[ "https://rpg.stackexchange.com/questions/149947", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/52992/" ]
This doesn't quite work the way you say --------------------------------------- Most of your technique tracks with the rules, but Step 3 does not. > > Cast Glyph of Warding at an 8th level, Cast Simulacrum into Glyph of Warding vía Wish Spell. > > > *Wish* is a 9th level spell, and *glyph of warding* specifies: > > If you create a *spell glyph*, you can store any spell of up to the same level as the slot you use for the *glyph of warding*. > > > So, you cannot store a 9th level spell like *wish* in an 8th level *glyph of warding*. **However**, you *could* simply store *simulacrum* (a 7th level spell) in an 8th or 9th level *glyph of warding*, and this plan works fine. It would just take 12 hours (casting *simulacrum*) and "powdered ruby worth 1,500 gp" in addition to the 200 gp cost of the *glyph of warding*.
It doesn't require nearly this much effort. Simulacrum is a touch spell. You can just have your first simulacrums wish-cast simulacrum on you directly. When you want more 9th level spells, you can have a bunch of your older simulacrums get around your latest simulacrum for 12 hours and cast the original version. You might have to make sure to stagger them right to handle the issue where your simulacrums are going up in puffs of snow from having their casters recast simulacrum, but once you've done that you're clear because nothing happens to the simulacrums cast by those who were dispersed. Admittedly, this does mean that you have to pay the 1500 gp cost for actual-casting simulacrum for each 9th level spell slot you want to generate via this method, but that's a bit beside the point. The point is that simulacrums casting simulacrum are broken, and the game doesn't account for them. That's true. You have spotted it. [This series of unofficial tweets](https://www.sageadvice.eu/2016/09/17/if-i-cast-simulacrum-my-duplicate-lack-of-7th-spell-slot-that-i-used-to-create-him/) has Chris Perkins (Senior Producer) saying, in essence, "Yes, Simulacrums can cast simulacrum. Wish abuse? What?" followed by running away. I think that's about as good as your going to get for a "It looks like these rules might just be broken" confirmation.
149,947
My intention here is to combine these four spells to let me amass an essentially infinite number of Spells through infinite Simulacrum whilst maintaining RAW and RAI rules. Please note why my combination presented won’t work with citations from either whom or where you are getting your information. Everything below is assumed to have enough provisions (Food, Water, Beds, etc) to survive and the character level is of a level capable of casting all spells listed below. Step 1: Create and enter your own Demiplane full of your Provisions. Step 2: Wait 24 hours. Step 3: Cast Glyph of Warding at an 8th level, Cast Simulacrum into Glyph of Warding vía Wish Spell. Set it to trigger when I step on it and click my ruby red slippers 3 times. Step 4: Wait 24 Hours. Step 5: (Now with full spell Slots) Step on Glyph and click my ruby red slippers 3 times. Step 6: New Simulacrum is formed, Simulacrum uses 8th level Slot and 9th level spot to cast an 8th level spell, replicating step 3. Step 7: Simulacrum proceeds to waste all of it’s spell slots Creating Glyphs or casting spells for me without me having to do anything other than provide material components. Step 8: Simulacrum has used all spell slots, I Proceed to Glyph and (Per RAI) my old Simulacrum is destroyed and a New one of me with all of my spell slots is made. Step 9: Sit back and enjoy infinite spell slots essentially. Other than the caveat of having a 200GP cost for my Glyph of Warding every time, is what I said feasible albeit lengthy?
2019/06/14
[ "https://rpg.stackexchange.com/questions/149947", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/52992/" ]
This doesn't quite work the way you say --------------------------------------- Most of your technique tracks with the rules, but Step 3 does not. > > Cast Glyph of Warding at an 8th level, Cast Simulacrum into Glyph of Warding vía Wish Spell. > > > *Wish* is a 9th level spell, and *glyph of warding* specifies: > > If you create a *spell glyph*, you can store any spell of up to the same level as the slot you use for the *glyph of warding*. > > > So, you cannot store a 9th level spell like *wish* in an 8th level *glyph of warding*. **However**, you *could* simply store *simulacrum* (a 7th level spell) in an 8th or 9th level *glyph of warding*, and this plan works fine. It would just take 12 hours (casting *simulacrum*) and "powdered ruby worth 1,500 gp" in addition to the 200 gp cost of the *glyph of warding*.
It's way easier than that. As a level 20 wizard, you have 2 level 7 spell slots. So, you have to cast *simulacrum*, creating one with just 1 level 7 spell slot, then wait 24 hours and order your first simulacrum to cast *simulacrum* on you. Now you have 1 simulacrum with no level 7 slots and 1 with all the slots. From this point on you just create tons of simulacra in few days. Note that it is the simulacra that cast *simulacrum* on you, not you casting it yourself. So they all can exist, obeying one another. But, you can solve the problem of command by just giving them some sort of Asimov's laws, like: 1. protect and fight for the original no matter any other order from now on 2. obey the original above all except rule 1 3. protect and fight for yourself, without violating rules 1 and 2.
12,573,663
I have a web app for a client built in C# .Net 3.5. The web app does lots of things and there is one part where I send some data via an asychronous web request to do some processing on the database. This can take anywhere from 5 to 60 minutes. I then created a SQL trigger that when the column in the database that uses the Database Mail to send mail (via msdb.dbo.sp\_send\_dbmail). This works fine, but our client forbids us to send mail from the database server. Anyone have an alternative to this?
2012/09/24
[ "https://Stackoverflow.com/questions/12573663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665557/" ]
You could create an Email table containing all of the fields you need for your emails. Add a record for each email you need to send given your processing. Next, write a Windows service that pings that database for new email records at a regular interval. If found, generate your emails and send them from your application tier. Don't forget to have a boolean or similar mechanism indicating that the email has been sent so that it doesn't get picked up more than once.
My coder sense smells something fishy going on, but what keeps you from updating another table that you check on a timed interval with your application server? And have the application server send the alert?
12,573,663
I have a web app for a client built in C# .Net 3.5. The web app does lots of things and there is one part where I send some data via an asychronous web request to do some processing on the database. This can take anywhere from 5 to 60 minutes. I then created a SQL trigger that when the column in the database that uses the Database Mail to send mail (via msdb.dbo.sp\_send\_dbmail). This works fine, but our client forbids us to send mail from the database server. Anyone have an alternative to this?
2012/09/24
[ "https://Stackoverflow.com/questions/12573663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665557/" ]
My coder sense smells something fishy going on, but what keeps you from updating another table that you check on a timed interval with your application server? And have the application server send the alert?
Even a column on the Email table for "SendStatus" that can be "ReadyForSend", "Sent", "Error" or something is better than the trigger plan. And then some sort of scheduled task that looks for items in the proper state to be sent. Keep in mind the poor guy who has to figure out how this all works in 6 months to a year when you may or may not be on the project any longer.
12,573,663
I have a web app for a client built in C# .Net 3.5. The web app does lots of things and there is one part where I send some data via an asychronous web request to do some processing on the database. This can take anywhere from 5 to 60 minutes. I then created a SQL trigger that when the column in the database that uses the Database Mail to send mail (via msdb.dbo.sp\_send\_dbmail). This works fine, but our client forbids us to send mail from the database server. Anyone have an alternative to this?
2012/09/24
[ "https://Stackoverflow.com/questions/12573663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/665557/" ]
You could create an Email table containing all of the fields you need for your emails. Add a record for each email you need to send given your processing. Next, write a Windows service that pings that database for new email records at a regular interval. If found, generate your emails and send them from your application tier. Don't forget to have a boolean or similar mechanism indicating that the email has been sent so that it doesn't get picked up more than once.
Even a column on the Email table for "SendStatus" that can be "ReadyForSend", "Sent", "Error" or something is better than the trigger plan. And then some sort of scheduled task that looks for items in the proper state to be sent. Keep in mind the poor guy who has to figure out how this all works in 6 months to a year when you may or may not be on the project any longer.
60,836,675
I am given a task to create the similar ec2 instance from existing ec2 instance from the infrastructure in AWS. Is there any way I can import all the setting from existing ec2 and create similar ec2 having the same attributes like vpc, security group, volume type, size and user data.
2020/03/24
[ "https://Stackoverflow.com/questions/60836675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12679768/" ]
You would use the `aws_instance` [data source](https://www.terraform.io/docs/providers/aws/d/instance.html) to get a reference to the existing instance in your Terraform, after which you could create a new one using the `aws_instance` [resource](https://www.terraform.io/docs/providers/aws/r/instance.html), passing all the values from the data source.
You can use this example code. Enter the instance id which you want to clone ``` variable "AWS_ACCESS_KEY" {} variable "AWS_SECRET_KEY" {} variable "AWS_REGION" {} variable "AWS_INSTANCE_ID" { description = "The instance id which you want to copy" } provider "aws" { access_key = "${var.AWS_ACCESS_KEY}" secret_key = "${var.AWS_SECRET_KEY}" region = "${var.AWS_REGION}" } data "aws_instance" "my_ec2" { instance_id = "${var.aws_instance_id}" } output "instance_id" { value = "${data.aws_instance.my_ec2.id}" } resource "aws_instance" "new_instance" { ami = "${data.aws_instance.my_ec2.ami}" instance_type = "${data.aws_instance.my_ec2.instance_type}" subnet_id = "${data.aws_instance.my_ec2.subnet_id}" security_groups = "${data.aws_instance.my_ec2.security_groups}" } ```
60,836,675
I am given a task to create the similar ec2 instance from existing ec2 instance from the infrastructure in AWS. Is there any way I can import all the setting from existing ec2 and create similar ec2 having the same attributes like vpc, security group, volume type, size and user data.
2020/03/24
[ "https://Stackoverflow.com/questions/60836675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12679768/" ]
You would use the `aws_instance` [data source](https://www.terraform.io/docs/providers/aws/d/instance.html) to get a reference to the existing instance in your Terraform, after which you could create a new one using the `aws_instance` [resource](https://www.terraform.io/docs/providers/aws/r/instance.html), passing all the values from the data source.
You can create ami from source ec2 and use that ami as source ami while creating second ec2. `resource "aws_ami_from_instance" "example" {` `name= "terraform-example"` `source_instance_id = "i-xxxxxxxx"` }
57,962,457
This may be a simple SQL query, if I have a table like this: ``` books( id int, title varchar (255), description mediumtext ) ``` Summary: I need to search the title and description for the input "term" but sort the results first by title matches which considered higher rank for me then results by the results found from description search. details: I need to search for the "terms" in the title column ordered by title and then search the description and sort their results by title, then join the results from searching on the title with the search on the description BUT keep the first search on title at the top. the query steps: ``` result 1 = search title for terms sorted by title result 2 = search description for terms sorted by title result 3 = merge result 1, result 2 (union) ```
2019/09/16
[ "https://Stackoverflow.com/questions/57962457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1405646/" ]
You need a `CASE` statement in the `ORDER BY` to order first the results from title and then the results from description and then sort each group by `title`: ``` select * from books where title like '%search%' or description like '%search%' order by case when title like '%search%' then 1 when description like '%search%' then 2 end, title ``` Since you tagged MySql only, you can write the same query simpler: ``` select * from books where title like '%search%' or description like '%search%' order by title like '%search%' desc, title ```
You can use expressions in `order by`. So: ``` order by (case when title like concat('%', @search_term, '%') then 1 else 2 end), (case when description like concat('%', @search_term, '%') then 1 else 2 end) ``` In MySQL, this can be simplified to: ``` order by (title like concat('%', @search_term, '%')) desc, (description like concat('%', @search_term, '%')) desc ```
8,817,431
I have an array of almost 5000 objects I am entering into a MySQL database. The array has an index 'crn', and the corresponding column in the MySQL table is the primary key. Is there any way I can tell mysql to skip an entry if it detects a duplicate primary key rather than stop execution of the script? I could check the table before insertion of each row, but since i'm only expecting 1 or 2 duplicates among the 5000 or so objects, it seems it would turn out to be very expensive.
2012/01/11
[ "https://Stackoverflow.com/questions/8817431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315828/" ]
Use `INSERT IGNORE` instead of just `INSERT`
As @KingCrunch stated, INSERT IGNORE can do that for you. If you however need to know about the duplicates, you might want to consider INSERT ... ON DUPLICATE KEY UPDATE See <http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html>
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
You can use ``` strtotime(“+5 days”) ``` to get the current date plus 5 days or ``` $targetDate = date($date, strtotime(’+5 days’)); ```
if the date is already exists, you can used this code : ``` $tartDate = date("m/d/Y", strtotime("+1 Day", strtotime($Date))); ```
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
Use [`strtotime`](http://php.net/strtotime): ``` $date = date('Y-m-d', strtotime('+5 days')); ```
if the date is already exists, you can used this code : ``` $tartDate = date("m/d/Y", strtotime("+1 Day", strtotime($Date))); ```
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
Object oriented Style: ``` <?php $date = new DateTime('now'); $date->add(new DateInterval('P5D')); echo $date->format('Y-m-d') . "\n"; ?> ``` Procedural Style: ``` <?php $date = date_create('2016-01-01'); date_add($date, date_interval_create_from_date_string('5 days')); echo date_format($date, 'Y-m-d'); ?> ```
Did not supposed to be like this? ``` $date_cur = date('Y-m-d', current_time('timestamp', 0)); echo $date_cur . ' <br>'; $date_cur_plus = date('Y-m-d', strtotime('+5 days', current_time('timestamp', 0) ) ); echo $date_cur_plus; ```
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
Object oriented Style: ``` <?php $date = new DateTime('now'); $date->add(new DateInterval('P5D')); echo $date->format('Y-m-d') . "\n"; ?> ``` Procedural Style: ``` <?php $date = date_create('2016-01-01'); date_add($date, date_interval_create_from_date_string('5 days')); echo date_format($date, 'Y-m-d'); ?> ```
`strtotime()` is very nice. It allows you to do the following: ``` $startDate = 'now'; // or choose a certain date you want/have $startDate = '2013-02-14'; $intervals = array( '', '+ 5 days', '+ 31 days', '+ 3 months', '+ 2 years + 2 days' ); foreach($intervals as $interval) { $combinedDate = $startDate . ' ' . $interval; var_dump($combinedDate . ' => ' date('Y-m-d', strtotime($combinedDate))); } ``` with a result: > > now => 1360334498 = 2013-02-08 > > > now + 5 days => 1360766498 = 2013-02-13 > > > now + 31 days => 1363012898 = 2013-03-11 > > > now + 3 months => 1368020498 = 2013-05-08 > > > now + 2 years + 2 days => 1423579298 = 2015-02-10 > > > or: > > 2013-02-14 => 1360792800 = 2013-02-14 > > > 2013-02-14 + 5 days => 1361224800 = 2013-02-19 > > > 2013-02-14 + 31 days => 1363471200 = 2013-03-17 > > > 2013-02-14 + 3 months => 1368478800 = 2013-05-14 > > > 2013-02-14 + 2 years + 2 days => 1424037600 = 2015-02-16 > > >
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
``` $dateplus5 = date('Y-m-d', strtotime('+5 days')); ```
I used this: ``` $date = strtotime("+1 day", strtotime("2007-02-28")); echo date("Y-m-d", $date); ``` It's working now.
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
``` $date = date('Y-m-d', strtotime('+5 days')); ```
if the date is already exists, you can used this code : ``` $tartDate = date("m/d/Y", strtotime("+1 Day", strtotime($Date))); ```
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
Object oriented Style: ``` <?php $date = new DateTime('now'); $date->add(new DateInterval('P5D')); echo $date->format('Y-m-d') . "\n"; ?> ``` Procedural Style: ``` <?php $date = date_create('2016-01-01'); date_add($date, date_interval_create_from_date_string('5 days')); echo date_format($date, 'Y-m-d'); ?> ```
For specific date: ``` $date = '2011-11-01'; $date_plus = date('Y-m-d', strtotime($date.'+5 days')); echo $date.'<br>'.$date_plus; ``` It will be give : ``` 2011-11-01 2011-11-06 ```
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
You could use `mktime()` using the timestamp. Something like: ``` $date = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') + 5, date('Y'))); ``` Using `strtotime()` is faster, but my method still works and is flexible in the event that you need to make lots of modifications. Plus, `strtotime()` can't handle ambiguous dates. **Edit** If you have to add 5 days to an already existing date string in the format `YYYY-MM-DD`, then you could split it into an array and use those parts with `mktime()`. ``` $parts = explode('-', $date); $datePlusFive = date( 'Y-m-d', mktime(0, 0, 0, $parts[1], $parts[2] + 5, $parts[0]) // ^ Month ^ Day + 5 ^ Year ); ```
Object oriented Style: ``` <?php $date = new DateTime('now'); $date->add(new DateInterval('P5D')); echo $date->format('Y-m-d') . "\n"; ?> ``` Procedural Style: ``` <?php $date = date_create('2016-01-01'); date_add($date, date_interval_create_from_date_string('5 days')); echo date_format($date, 'Y-m-d'); ?> ```
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
``` $date = date('Y-m-d', strtotime('+5 days')); ```
For specific date: ``` $date = '2011-11-01'; $date_plus = date('Y-m-d', strtotime($date.'+5 days')); echo $date.'<br>'.$date_plus; ``` It will be give : ``` 2011-11-01 2011-11-06 ```
8,307,968
I'm aware of the threading issues etc that this could cause and of its dangers but I need to know how to do this for a security project I am doing at school. I need to know how to call a function in a remote address space of a given calling convention with arguments - preferably recovering the data the remote function has returned though its really not required that I do. If I can get specifics from the remote function's function prototype at compile time, I will be able to make this method work. I need to know how big the arguments are and if the arguments are explicitly declared as pointers or not `(void*, char*, int*, etc...)` I.e if I define a function prototype like: ``` typedef void (__cdecl *testFunc_t)(int* pData); ``` I would need to, at compile time, get the size of arguments at least, and if I could, which ones are pointers or not. Here we are assuming the remote function is either an `stdcall` or `_cdecl` call. The IDE I am using is Microsoft Visual Studio 2007 in case the solution is specific to a particular product. Here is my plan: 1. Create a thread in the remote process using `CreateRemoteThread` at the origin of the function want to call, though I would do so in a suspended state. 2. I would setup the stack such that the return address was that of a stub of code allocated inside of the process that would call `ExitThread(eax)` - as this would exit the thread with the function's return value - I would then recover this by by using `GetExitCodeThread` 3. I would also copy the arguments for the function call from my local stack to that of the newly created thread - this is where I need to know if function arguments are pointers and the size of the arguments. 4. Resume the thread and wait for it to exit, at which point I will return to the caller with the threads exit code. I know that this should be doable at compile time but whether the compiler has some method I can use to do it, I'm not sure. I'm also aware all this data can be easily recovered from a PDB file created after compiling the code and that the size of arguments might change if the compiler performs optimizations. I don't need to be told how dangerous this is, as I am fully aware of it, but this is not a commercial product but a small project I must do for school. The question: If I have a function prototype such as typedef void (\_\_cdecl testFunc\_t)(int pData); Is there anyway I can get the size of this prototype's arguments at compile time(i.e in the above example, the arguments would sum to a total size of sizeof(int\*) If, for example, I have a function like: ``` template<typename T> unsigned long getPrototypeArgLength<T>() { //would return size of arguments described in the prototype T } //when called as getPrototypeArgLength<testFunc>() ```
2011/11/29
[ "https://Stackoverflow.com/questions/8307968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1070878/" ]
``` $dateplus5 = date('Y-m-d', strtotime('+5 days')); ```
Did not supposed to be like this? ``` $date_cur = date('Y-m-d', current_time('timestamp', 0)); echo $date_cur . ' <br>'; $date_cur_plus = date('Y-m-d', strtotime('+5 days', current_time('timestamp', 0) ) ); echo $date_cur_plus; ```
34,256,562
I am trying to swipe a row in my ListView, identify its text and perform certain actions. I am able to detect left/right swipes but how to I go about identifying the text for that swiped row? I am not able to identify its location unlike using onItemClickListener where I could use the position variable. MainActivity Class ``` ListView orderListView; ArrayList<String> orders; ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_order_stock); orderListView = (ListView)findViewById(R.id.orderListView); orders = new ArrayList<>(); orders.add("order 1"); orders.add("order 2"); orders.add("order 3"); adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, orders); orderListView.setAdapter(adapter); OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(this, orderListView); orderListView.setOnTouchListener(onSwipeTouchListener); } ``` OnSwipeTouchListener Class ``` public class OnSwipeTouchListener implements View.OnTouchListener { ListView list; private GestureDetector gestureDetector; private Context context; public OnSwipeTouchListener(Context ctx, ListView list) { gestureDetector = new GestureDetector(ctx, new GestureListener()); context = ctx; this.list = list; } public OnSwipeTouchListener() { super(); } @Override public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } public void onSwipeRight(int pos) { Log.i("zxR", "right"); } public void onSwipeLeft() { Log.i("zxL", "left"); } private final class GestureListener extends GestureDetector.SimpleOnGestureListener { private static final int SWIPE_THRESHOLD = 100; private static final int SWIPE_VELOCITY_THRESHOLD = 100; @Override public boolean onDown(MotionEvent e) { return true; } private int getPostion(MotionEvent e1) { return list.pointToPosition((int) e1.getX(), (int) e1.getY()); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { float distanceX = e2.getX() - e1.getX(); float distanceY = e2.getY() - e1.getY(); if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) { if (distanceX > 0) onSwipeRight(getPostion(e1)); else onSwipeLeft(); return true; } return false; } } } ```
2015/12/13
[ "https://Stackoverflow.com/questions/34256562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5460020/" ]
Try this, I think this might help: Include ArrayAdapter in the argument of the constructor of OnSwipeTouchListener and pass the adapter of the ListView from the main activity Then add this code to your onFling() ``` float distanceX = e2.getX() - e1.getX(); float distanceY = e2.getY() - e1.getY(); int id = list.pointToPosition((int) e1.getX(), (int) e1.getY()); String text=adapter.getItem(id); Toast.makeText(context,"Text:"+text,Toast.LENGTH_SHORT).show(); ```
Use the new RecyclerView instead of ListView as it have simple api for gestures and animations. The same question for RecyclerView: <https://stackoverflow.com/a/30601554/2627680>
63,104
> > **Possible Duplicate:** > > [Plural possessive with separate posessions](https://english.stackexchange.com/questions/57142/plural-possessive-with-separate-posessions) > > > Which of the following is more correct? Or is there another form I'm missing? > > We drove to the movies in one of my **buddy's car**. > > We drove to the theater in one of my **buddies' cars**. > > We drove to the theater in one of my **buddies' car**. > > > I suppose the fundamental question is: does this phrasing suggest "one of [the collection of cars owned by my buddies]" or "the car owned by [one of my buddies]"?
2012/04/03
[ "https://english.stackexchange.com/questions/63104", "https://english.stackexchange.com", "https://english.stackexchange.com/users/12210/" ]
If you mean "one of the cars belonging to one buddy": > > We drove to the movies in one of my **buddy's cars**. > > > If you mean "one of the cars belonging to one of my buddies" or "the one car owned by one of my buddies": > > We drove to the theater in one of my **buddies' cars**. > > >
I think that "We drove to the movies in one of my buddy's car." is *incorrect* because "one of" implies a plural, which is lacking. Both of the latter two forms are correct. The first means "one of the cars belonging to my buddies", and would be appropriate, for example, if you are talking about buddies who are car collectors. The last means "the car belonging to one of my buddies". My gut feeling is that in common usage, the last form "one of my buddies' car" would be the best usage, because we usually think of someone driving their car, or having a car, even when they have more than one. [I use "they" rather than "his" in the last sentence following post-modern usage.]
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
You should first create an array of questions for each category to randomly select from. ``` const art = arr.filter(question => question.category === 'Art and Literature'); const music = arr.filter(question => question.category === 'Music'); const history = arr.filter(question => question.category === 'History'); ``` Now, just choose items randomly four times for each category array. ``` const categoryArrays = [art, music, history]; const results = [] // to store the selected ids for (i = 0, i < 3, i++) { // To iterate over the three categories for (j = 0, j < 4, j++) { // To select four times results.push(categoryArrays[i][Math.floor(Math.random() * categoryArrays[i].length)]._id); } } ```
Use shuffle function to remdomize the array containing questions than just take first top 4 results by matching category. Here is pseudo code: ``` let arrayOfQuestions =[]; let shuffledQuestions = _.shuffle(arrayOfQuestions); // _ is Lodash let artAndLiteratureQuestions = _.find(shuffledQuestions, { category: 'Art and Literature' } ``` in the same way you can extract the others category questions.
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
There's a couple of steps to this. First you'll want to filter out a list of items for the specific category. ``` const categories = ["Art and Literature", "Music", "History"]; for (let c of categories) { const itemsOfCategory = items.filter(i => item.category === c); } ``` Then you'll want to pick 4 random items from the filtered list and return them. It seems nicest to put this in it's own function. ``` const getRandomItems = (items, categories, numberOfItems) => { const results = []; for (let c of categories) { const itemsOfCategory = items.filter(i => i.category === c); const pickedItems = []; for (let i = 0; i < numberOfItems; i += 1) { pickedItems.push(Math.trunc(Math.random()*itemsOfCategory.length)) } results.push(pickedItems) } return results; } ``` You then pass in your list of items, the categories you want and how many items you want. `const randomItems = getRandomItems(items, categories, 4);`
Use shuffle function to remdomize the array containing questions than just take first top 4 results by matching category. Here is pseudo code: ``` let arrayOfQuestions =[]; let shuffledQuestions = _.shuffle(arrayOfQuestions); // _ is Lodash let artAndLiteratureQuestions = _.find(shuffledQuestions, { category: 'Art and Literature' } ``` in the same way you can extract the others category questions.
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
You can use `map` on `categories` array and then inside the callback use `filter` to get an array of objects where category matches. On first iteration it will give an array where the category is `Art and Literature` and so on. Then run another loop to get generate 4 random numbers and using this random number get a random question from filtered array.Store that value in a temporary variable and return that ``` let ques = [{ _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }] let type = ["Art and Literature", "Music", "History"]; let randomQues = type.map(function(item) { let quesArrays = [] let k = ques.filter(elem) { return elem.category === item; }) for (let i = 0; i < 4; i++) { let rand = Math.floor(Math.random() * k.length); quesArrays.push(rand) } return quesArrays; }) ```
Use shuffle function to remdomize the array containing questions than just take first top 4 results by matching category. Here is pseudo code: ``` let arrayOfQuestions =[]; let shuffledQuestions = _.shuffle(arrayOfQuestions); // _ is Lodash let artAndLiteratureQuestions = _.find(shuffledQuestions, { category: 'Art and Literature' } ``` in the same way you can extract the others category questions.
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
You could group all question ids by categories using reduce(), and then pick N random items from these arrays: ```js const categories = ['cat1', 'cat2', 'cat3']; const questions = Array.from({ length: 10 }, (_, i) => ( { _id: i, question: `question ${i}`, answer: `answer ${i}`, category: categories[Math.floor(Math.random() * categories.length)]}) ); function randomQuestions(questions, categories, n) { // group the ids into arrays for each category asked const idsByCategories = questions.reduce((acc, x) => { if (categories.includes(x.category)) { acc[x.category] = [...(acc[x.category] || []), x._id]; } return acc; }, {}); // pick a number of random ids for each category return categories.map(cat => (idsByCategories[cat] || []).sort(() => 0.5 - Math.random()).slice(0, n)); } console.log(JSON.stringify(randomQuestions(questions, ['cat1', 'cat3'], 2))); console.log(questions); ``` The random array picking code was taken [from this answer](https://stackoverflow.com/a/38571132/9325419).
Use shuffle function to remdomize the array containing questions than just take first top 4 results by matching category. Here is pseudo code: ``` let arrayOfQuestions =[]; let shuffledQuestions = _.shuffle(arrayOfQuestions); // _ is Lodash let artAndLiteratureQuestions = _.find(shuffledQuestions, { category: 'Art and Literature' } ``` in the same way you can extract the others category questions.
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
``` const questions = [ { _id: "5ca3216579a592b0910f70d4", question: "Who wrote Twilight series of novels?", answer: "Stephenie Meyer", category: "Art and Literature", } ] const categories = ["Art and Literature", "Music", "History"]; const numberOfEachCategory = 2; const randSelected = categories.map((category) => { const filtered = questions.filter((obj) => obj.category === category).slice(); if(filtered.length > numberOfEachCategory) { const randomArray = []; for(let i = numberOfEachCategory; i > 0; i--) { randomArray.push(...filtered.splice(Math.floor(Math.random() * filtered.length), 1)); } return randomArray; } else { return filtered; } }) console.log(randSelected); ``` Result is Array of Arrays. each inside array for each category
Use shuffle function to remdomize the array containing questions than just take first top 4 results by matching category. Here is pseudo code: ``` let arrayOfQuestions =[]; let shuffledQuestions = _.shuffle(arrayOfQuestions); // _ is Lodash let artAndLiteratureQuestions = _.find(shuffledQuestions, { category: 'Art and Literature' } ``` in the same way you can extract the others category questions.
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
You should first create an array of questions for each category to randomly select from. ``` const art = arr.filter(question => question.category === 'Art and Literature'); const music = arr.filter(question => question.category === 'Music'); const history = arr.filter(question => question.category === 'History'); ``` Now, just choose items randomly four times for each category array. ``` const categoryArrays = [art, music, history]; const results = [] // to store the selected ids for (i = 0, i < 3, i++) { // To iterate over the three categories for (j = 0, j < 4, j++) { // To select four times results.push(categoryArrays[i][Math.floor(Math.random() * categoryArrays[i].length)]._id); } } ```
You may use this logic to **get all results** in one liner for **all categories** :) Just need to change filter check with your check. ```js let list = [1,1,1,1, 1, 1,1, 3, 2, 3, 4, 5, 6 ]; let options = [1, 3]; const result = options.map((val) => { return list.filter(f => val === f ).map((v, i, ref) => { if(i<=3) return ref[parseInt(Math.random()*ref.length-i)] }).slice(0, 3) }) console.log(result); ```
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
There's a couple of steps to this. First you'll want to filter out a list of items for the specific category. ``` const categories = ["Art and Literature", "Music", "History"]; for (let c of categories) { const itemsOfCategory = items.filter(i => item.category === c); } ``` Then you'll want to pick 4 random items from the filtered list and return them. It seems nicest to put this in it's own function. ``` const getRandomItems = (items, categories, numberOfItems) => { const results = []; for (let c of categories) { const itemsOfCategory = items.filter(i => i.category === c); const pickedItems = []; for (let i = 0; i < numberOfItems; i += 1) { pickedItems.push(Math.trunc(Math.random()*itemsOfCategory.length)) } results.push(pickedItems) } return results; } ``` You then pass in your list of items, the categories you want and how many items you want. `const randomItems = getRandomItems(items, categories, 4);`
You may use this logic to **get all results** in one liner for **all categories** :) Just need to change filter check with your check. ```js let list = [1,1,1,1, 1, 1,1, 3, 2, 3, 4, 5, 6 ]; let options = [1, 3]; const result = options.map((val) => { return list.filter(f => val === f ).map((v, i, ref) => { if(i<=3) return ref[parseInt(Math.random()*ref.length-i)] }).slice(0, 3) }) console.log(result); ```
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
You can use `map` on `categories` array and then inside the callback use `filter` to get an array of objects where category matches. On first iteration it will give an array where the category is `Art and Literature` and so on. Then run another loop to get generate 4 random numbers and using this random number get a random question from filtered array.Store that value in a temporary variable and return that ``` let ques = [{ _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }] let type = ["Art and Literature", "Music", "History"]; let randomQues = type.map(function(item) { let quesArrays = [] let k = ques.filter(elem) { return elem.category === item; }) for (let i = 0; i < 4; i++) { let rand = Math.floor(Math.random() * k.length); quesArrays.push(rand) } return quesArrays; }) ```
You may use this logic to **get all results** in one liner for **all categories** :) Just need to change filter check with your check. ```js let list = [1,1,1,1, 1, 1,1, 3, 2, 3, 4, 5, 6 ]; let options = [1, 3]; const result = options.map((val) => { return list.filter(f => val === f ).map((v, i, ref) => { if(i<=3) return ref[parseInt(Math.random()*ref.length-i)] }).slice(0, 3) }) console.log(result); ```
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
You could group all question ids by categories using reduce(), and then pick N random items from these arrays: ```js const categories = ['cat1', 'cat2', 'cat3']; const questions = Array.from({ length: 10 }, (_, i) => ( { _id: i, question: `question ${i}`, answer: `answer ${i}`, category: categories[Math.floor(Math.random() * categories.length)]}) ); function randomQuestions(questions, categories, n) { // group the ids into arrays for each category asked const idsByCategories = questions.reduce((acc, x) => { if (categories.includes(x.category)) { acc[x.category] = [...(acc[x.category] || []), x._id]; } return acc; }, {}); // pick a number of random ids for each category return categories.map(cat => (idsByCategories[cat] || []).sort(() => 0.5 - Math.random()).slice(0, n)); } console.log(JSON.stringify(randomQuestions(questions, ['cat1', 'cat3'], 2))); console.log(questions); ``` The random array picking code was taken [from this answer](https://stackoverflow.com/a/38571132/9325419).
You may use this logic to **get all results** in one liner for **all categories** :) Just need to change filter check with your check. ```js let list = [1,1,1,1, 1, 1,1, 3, 2, 3, 4, 5, 6 ]; let options = [1, 3]; const result = options.map((val) => { return list.filter(f => val === f ).map((v, i, ref) => { if(i<=3) return ref[parseInt(Math.random()*ref.length-i)] }).slice(0, 3) }) console.log(result); ```
55,512,355
I have an array of 700 question objects that look like this: ``` [ { _id: "5ca3216579a592b0910f70d4" question: "Who wrote Twilight series of novels?" answer: "Stephenie Meyer" category: "Art and Literature" }, ... ] ``` I also have an array of 3 selected question categories that look like this: ``` ["Art and Literature", "Music", "History"] ``` What I basically need is 4 random questions of each question category. So: * 4 random questions of Art and Literature * 4 random questions of Music * 4 random questions of History Ideally I think it would be nice to have the 12 random question id's set in a new array based on these 3 categories so I could send them to my database. How is this to be done?
2019/04/04
[ "https://Stackoverflow.com/questions/55512355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10685852/" ]
``` const questions = [ { _id: "5ca3216579a592b0910f70d4", question: "Who wrote Twilight series of novels?", answer: "Stephenie Meyer", category: "Art and Literature", } ] const categories = ["Art and Literature", "Music", "History"]; const numberOfEachCategory = 2; const randSelected = categories.map((category) => { const filtered = questions.filter((obj) => obj.category === category).slice(); if(filtered.length > numberOfEachCategory) { const randomArray = []; for(let i = numberOfEachCategory; i > 0; i--) { randomArray.push(...filtered.splice(Math.floor(Math.random() * filtered.length), 1)); } return randomArray; } else { return filtered; } }) console.log(randSelected); ``` Result is Array of Arrays. each inside array for each category
You may use this logic to **get all results** in one liner for **all categories** :) Just need to change filter check with your check. ```js let list = [1,1,1,1, 1, 1,1, 3, 2, 3, 4, 5, 6 ]; let options = [1, 3]; const result = options.map((val) => { return list.filter(f => val === f ).map((v, i, ref) => { if(i<=3) return ref[parseInt(Math.random()*ref.length-i)] }).slice(0, 3) }) console.log(result); ```
12,389,850
I have a registration form i would like to submit to a SQL 2008 database, I thought I had it right, but it doesn't seem to be working. i posted the code belowe to show what i have so far. Basically I would like to know if the code i have should work, if not could someone show me how to tweek what i have. ``` protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { SqlConnection NutRegistration = new SqlConnection("Data Source=server; Initial Catalog=DBname;Integrated Security=false;User ID=uname;Password=password"); NutRegistration.Open(); SqlCommand thisCommand = NutRegistration.CreateCommand(); thisCommand.CommandText = "INSERT INTO users (txtNickName, txtEmail, txtPassword) VALUES (nickname, email, password);"; NutRegistration.Close(); } ``` thanks in advance
2012/09/12
[ "https://Stackoverflow.com/questions/12389850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022395/" ]
Your formulae are using text instead of numbers eg `=IF(B6>=3.3,"1","0")` should perhaps be `=IF(B6>=3.3,1,0)` =A1 + B1 + C1 forces Excel to convert any numeric text to numeric type
You can encapsulate your calculated cells with VALUE() that needs to be summarized: A1: > > =**VALUE(** *IF(B6>=3.3,"1","0")* **)** > > > B1: > > =**VALUE(** *IF(C6<7,"0", IF(C6<9,"1",IF(C6>=9,"2")))* **)** > > > C1: > > =**VALUE(** *IF(D6>85,"1","0")* **)** > > > D1: > > =SUM(A1:C1) > > > This will force your formulae to output a number instead of text, and this can be summarized.
12,389,850
I have a registration form i would like to submit to a SQL 2008 database, I thought I had it right, but it doesn't seem to be working. i posted the code belowe to show what i have so far. Basically I would like to know if the code i have should work, if not could someone show me how to tweek what i have. ``` protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { SqlConnection NutRegistration = new SqlConnection("Data Source=server; Initial Catalog=DBname;Integrated Security=false;User ID=uname;Password=password"); NutRegistration.Open(); SqlCommand thisCommand = NutRegistration.CreateCommand(); thisCommand.CommandText = "INSERT INTO users (txtNickName, txtEmail, txtPassword) VALUES (nickname, email, password);"; NutRegistration.Close(); } ``` thanks in advance
2012/09/12
[ "https://Stackoverflow.com/questions/12389850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022395/" ]
Your formulae are using text instead of numbers eg `=IF(B6>=3.3,"1","0")` should perhaps be `=IF(B6>=3.3,1,0)` =A1 + B1 + C1 forces Excel to convert any numeric text to numeric type
Please note: The real issue is with the IF formulas. When returning a value, it should not be in quotes. The quotes make it text. For example, C1: should be If(D6>85,1,0). Then, Value is not necessary.
12,389,850
I have a registration form i would like to submit to a SQL 2008 database, I thought I had it right, but it doesn't seem to be working. i posted the code belowe to show what i have so far. Basically I would like to know if the code i have should work, if not could someone show me how to tweek what i have. ``` protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { SqlConnection NutRegistration = new SqlConnection("Data Source=server; Initial Catalog=DBname;Integrated Security=false;User ID=uname;Password=password"); NutRegistration.Open(); SqlCommand thisCommand = NutRegistration.CreateCommand(); thisCommand.CommandText = "INSERT INTO users (txtNickName, txtEmail, txtPassword) VALUES (nickname, email, password);"; NutRegistration.Close(); } ``` thanks in advance
2012/09/12
[ "https://Stackoverflow.com/questions/12389850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022395/" ]
Your formulae are using text instead of numbers eg `=IF(B6>=3.3,"1","0")` should perhaps be `=IF(B6>=3.3,1,0)` =A1 + B1 + C1 forces Excel to convert any numeric text to numeric type
You can also just encapsulate the item in the formula you want to be considered a number. In my case I did not want anything in the calculated cell if there is no result (IF = false) but encapsulating the whole formula resulted in a 0 result. If I make false = "" I get an error. So I just have =IF(test=X,Value(true),"") - X in my case is text but can be a number.
12,389,850
I have a registration form i would like to submit to a SQL 2008 database, I thought I had it right, but it doesn't seem to be working. i posted the code belowe to show what i have so far. Basically I would like to know if the code i have should work, if not could someone show me how to tweek what i have. ``` protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { SqlConnection NutRegistration = new SqlConnection("Data Source=server; Initial Catalog=DBname;Integrated Security=false;User ID=uname;Password=password"); NutRegistration.Open(); SqlCommand thisCommand = NutRegistration.CreateCommand(); thisCommand.CommandText = "INSERT INTO users (txtNickName, txtEmail, txtPassword) VALUES (nickname, email, password);"; NutRegistration.Close(); } ``` thanks in advance
2012/09/12
[ "https://Stackoverflow.com/questions/12389850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022395/" ]
Your formulae are using text instead of numbers eg `=IF(B6>=3.3,"1","0")` should perhaps be `=IF(B6>=3.3,1,0)` =A1 + B1 + C1 forces Excel to convert any numeric text to numeric type
May have happened that you wanted to sum a formula that previously uses iterative computation (*circular reference*). In that case, excel ocasionaly turns this feature **ON/OFF** without any notice. You would need to switch **ON** that function previously. To do that: `Excel -> Option > Formulas ...>`
12,389,850
I have a registration form i would like to submit to a SQL 2008 database, I thought I had it right, but it doesn't seem to be working. i posted the code belowe to show what i have so far. Basically I would like to know if the code i have should work, if not could someone show me how to tweek what i have. ``` protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { SqlConnection NutRegistration = new SqlConnection("Data Source=server; Initial Catalog=DBname;Integrated Security=false;User ID=uname;Password=password"); NutRegistration.Open(); SqlCommand thisCommand = NutRegistration.CreateCommand(); thisCommand.CommandText = "INSERT INTO users (txtNickName, txtEmail, txtPassword) VALUES (nickname, email, password);"; NutRegistration.Close(); } ``` thanks in advance
2012/09/12
[ "https://Stackoverflow.com/questions/12389850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022395/" ]
You can encapsulate your calculated cells with VALUE() that needs to be summarized: A1: > > =**VALUE(** *IF(B6>=3.3,"1","0")* **)** > > > B1: > > =**VALUE(** *IF(C6<7,"0", IF(C6<9,"1",IF(C6>=9,"2")))* **)** > > > C1: > > =**VALUE(** *IF(D6>85,"1","0")* **)** > > > D1: > > =SUM(A1:C1) > > > This will force your formulae to output a number instead of text, and this can be summarized.
Please note: The real issue is with the IF formulas. When returning a value, it should not be in quotes. The quotes make it text. For example, C1: should be If(D6>85,1,0). Then, Value is not necessary.
12,389,850
I have a registration form i would like to submit to a SQL 2008 database, I thought I had it right, but it doesn't seem to be working. i posted the code belowe to show what i have so far. Basically I would like to know if the code i have should work, if not could someone show me how to tweek what i have. ``` protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { SqlConnection NutRegistration = new SqlConnection("Data Source=server; Initial Catalog=DBname;Integrated Security=false;User ID=uname;Password=password"); NutRegistration.Open(); SqlCommand thisCommand = NutRegistration.CreateCommand(); thisCommand.CommandText = "INSERT INTO users (txtNickName, txtEmail, txtPassword) VALUES (nickname, email, password);"; NutRegistration.Close(); } ``` thanks in advance
2012/09/12
[ "https://Stackoverflow.com/questions/12389850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022395/" ]
You can encapsulate your calculated cells with VALUE() that needs to be summarized: A1: > > =**VALUE(** *IF(B6>=3.3,"1","0")* **)** > > > B1: > > =**VALUE(** *IF(C6<7,"0", IF(C6<9,"1",IF(C6>=9,"2")))* **)** > > > C1: > > =**VALUE(** *IF(D6>85,"1","0")* **)** > > > D1: > > =SUM(A1:C1) > > > This will force your formulae to output a number instead of text, and this can be summarized.
You can also just encapsulate the item in the formula you want to be considered a number. In my case I did not want anything in the calculated cell if there is no result (IF = false) but encapsulating the whole formula resulted in a 0 result. If I make false = "" I get an error. So I just have =IF(test=X,Value(true),"") - X in my case is text but can be a number.
12,389,850
I have a registration form i would like to submit to a SQL 2008 database, I thought I had it right, but it doesn't seem to be working. i posted the code belowe to show what i have so far. Basically I would like to know if the code i have should work, if not could someone show me how to tweek what i have. ``` protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { SqlConnection NutRegistration = new SqlConnection("Data Source=server; Initial Catalog=DBname;Integrated Security=false;User ID=uname;Password=password"); NutRegistration.Open(); SqlCommand thisCommand = NutRegistration.CreateCommand(); thisCommand.CommandText = "INSERT INTO users (txtNickName, txtEmail, txtPassword) VALUES (nickname, email, password);"; NutRegistration.Close(); } ``` thanks in advance
2012/09/12
[ "https://Stackoverflow.com/questions/12389850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022395/" ]
You can encapsulate your calculated cells with VALUE() that needs to be summarized: A1: > > =**VALUE(** *IF(B6>=3.3,"1","0")* **)** > > > B1: > > =**VALUE(** *IF(C6<7,"0", IF(C6<9,"1",IF(C6>=9,"2")))* **)** > > > C1: > > =**VALUE(** *IF(D6>85,"1","0")* **)** > > > D1: > > =SUM(A1:C1) > > > This will force your formulae to output a number instead of text, and this can be summarized.
May have happened that you wanted to sum a formula that previously uses iterative computation (*circular reference*). In that case, excel ocasionaly turns this feature **ON/OFF** without any notice. You would need to switch **ON** that function previously. To do that: `Excel -> Option > Formulas ...>`
16,230,435
I know this question has been asked before, but there was no answer provided. I also tried looking elsewhere, have traced the function calls and checked everything, but I cannot figure out the answer. I have a very simple Handler, which calls a Runnable variable every second. It is meant to keep a track of time spent on the activity. So the handler begins a call in onCreate, and in the Runnable there is a postDelayed(runnableVar, 1000) to continue running it every second. This is updating a text view in the activity. The text view is showing everything in doubles. I checked my log and found that the runnable is called twice. I don't know why this is happening. Here is my code: ``` //My runnable variable in the activity private Runnable mUpdateTimeTask = new Runnable(){ @Override public void run(){ if (gameTimer != null) { Log.d("UPDATERUNNABLE", "Inside runnable run"); gameTimer.setText(getTime()); } mHandler.postDelayed(this,1000); } }; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); Log.d(TRIALTAG,"Inside on create"); startMins = mPrefsMin; //This is set in onPause and retrieved onResume startSecs = mPrefsSecs; Log.d(TRIALTAG,"Start mins : " + startMins + " Start Secs : " + startSecs); mHandler.removeCallbacks(mUpdateTimeTask); mHandler.post(mUpdateTimeTask); } private String getTime() { String finalTime; Log.d("GETTIME", "Start secs is : " + startSecs); if(startSecs >= 60){ startSecs=0; startMins++; } if(startSecs<10){ finalTime = startMins+":0"+startSecs; }else{ finalTime = startMins+":"+startSecs; } startSecs++; return finalTime; } @Override protected void onPause(){ super.onPause(); Log.d(TRIALTAG,"On Pause CALLED"); mHandler.removeCallbacks(mUpdateTimeTask); SharedPreferences.Editor ed = mPrefs.edit(); ed.putInt("my_mins", startMins); ed.putInt("my_secs", startSecs); ed.commit(); } @Override protected void onResume(){ super.onResume(); Log.d(TRIALTAG,"On RESUME CALLED"); if(gameTimer != null){ mPrefs = getSharedPreferences("mPrefs", MODE_PRIVATE); mPrefsMin = mPrefs.getInt("my_mins", 0); mPrefsSecs = mPrefs.getInt("my_secs", 0); mHandler.post(mUpdateTimeTask); }else{ mPrefsMin = 0; mPrefsSecs = 0; } } ``` All this is within my activity class. What am I doing wrong??
2013/04/26
[ "https://Stackoverflow.com/questions/16230435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2010545/" ]
The problem is that you are posting your `Runnable` object twice - in `onCreate` and `onResume` methods. Try modifying your `onResume` method and removing the previous added `Runnable` ``` @Override protected void onResume(){ super.onResume(); Log.d(TRIALTAG,"On RESUME CALLED"); if(gameTimer != null){ mPrefs = getSharedPreferences("mPrefs", MODE_PRIVATE); mPrefsMin = mPrefs.getInt("my_mins", 0); mPrefsSecs = mPrefs.getInt("my_secs", 0); mHandler.removeCallbacks(mUpdateTimeTask); mHandler.post(mUpdateTimeTask); }else{ mPrefsMin = 0; mPrefsSecs = 0; } } ```
There is an another way also that you can use to update the UI on specific time interval. ``` new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while (true) { try { Thread.sleep(10000); mHandler.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub gameTimer.setText(getTime()); } }); } catch (Exception e) { // TODO: handle exception } } } }).start(); ```
16,230,435
I know this question has been asked before, but there was no answer provided. I also tried looking elsewhere, have traced the function calls and checked everything, but I cannot figure out the answer. I have a very simple Handler, which calls a Runnable variable every second. It is meant to keep a track of time spent on the activity. So the handler begins a call in onCreate, and in the Runnable there is a postDelayed(runnableVar, 1000) to continue running it every second. This is updating a text view in the activity. The text view is showing everything in doubles. I checked my log and found that the runnable is called twice. I don't know why this is happening. Here is my code: ``` //My runnable variable in the activity private Runnable mUpdateTimeTask = new Runnable(){ @Override public void run(){ if (gameTimer != null) { Log.d("UPDATERUNNABLE", "Inside runnable run"); gameTimer.setText(getTime()); } mHandler.postDelayed(this,1000); } }; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); Log.d(TRIALTAG,"Inside on create"); startMins = mPrefsMin; //This is set in onPause and retrieved onResume startSecs = mPrefsSecs; Log.d(TRIALTAG,"Start mins : " + startMins + " Start Secs : " + startSecs); mHandler.removeCallbacks(mUpdateTimeTask); mHandler.post(mUpdateTimeTask); } private String getTime() { String finalTime; Log.d("GETTIME", "Start secs is : " + startSecs); if(startSecs >= 60){ startSecs=0; startMins++; } if(startSecs<10){ finalTime = startMins+":0"+startSecs; }else{ finalTime = startMins+":"+startSecs; } startSecs++; return finalTime; } @Override protected void onPause(){ super.onPause(); Log.d(TRIALTAG,"On Pause CALLED"); mHandler.removeCallbacks(mUpdateTimeTask); SharedPreferences.Editor ed = mPrefs.edit(); ed.putInt("my_mins", startMins); ed.putInt("my_secs", startSecs); ed.commit(); } @Override protected void onResume(){ super.onResume(); Log.d(TRIALTAG,"On RESUME CALLED"); if(gameTimer != null){ mPrefs = getSharedPreferences("mPrefs", MODE_PRIVATE); mPrefsMin = mPrefs.getInt("my_mins", 0); mPrefsSecs = mPrefs.getInt("my_secs", 0); mHandler.post(mUpdateTimeTask); }else{ mPrefsMin = 0; mPrefsSecs = 0; } } ``` All this is within my activity class. What am I doing wrong??
2013/04/26
[ "https://Stackoverflow.com/questions/16230435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2010545/" ]
The problem is that you are posting your `Runnable` object twice - in `onCreate` and `onResume` methods. Try modifying your `onResume` method and removing the previous added `Runnable` ``` @Override protected void onResume(){ super.onResume(); Log.d(TRIALTAG,"On RESUME CALLED"); if(gameTimer != null){ mPrefs = getSharedPreferences("mPrefs", MODE_PRIVATE); mPrefsMin = mPrefs.getInt("my_mins", 0); mPrefsSecs = mPrefs.getInt("my_secs", 0); mHandler.removeCallbacks(mUpdateTimeTask); mHandler.post(mUpdateTimeTask); }else{ mPrefsMin = 0; mPrefsSecs = 0; } } ```
in onCreate remove ``` mHandler.removeCallbacks(mUpdateTimeTask); mHandler.post(mUpdateTimeTask); ```
14,759,465
There must be an easy way to replace an element of an array in Ruby. I don't want to use regular expressions. ``` while @word_array.include? c do idx = @word_array.index(c) @currently_found[idx] = c @word_array.index(idx) = " " end ``` I want to save the char *c* at the same index but in another array.
2013/02/07
[ "https://Stackoverflow.com/questions/14759465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2013672/" ]
> > I'd like to recreate a generic version of the excel function AVERAGEIF > > > Why don't you just use LINQ? ``` var average = collection.Where(x => x.Something) .Average(x => x.SomeProperty); ``` Note that this will throw an exception if there are no matching elements. If you don't want that, you could use: ``` var average = collection.Where(x => x.Something) .DefaultIfEmpty() .Average(x => x.SomeProperty); ``` It's not clear why you would want to create a separate method for this.
The following is the answer that works for me: ``` public double AVERAGEIF<T1,T2>(IEnumerable<T1> average_range, IEnumerable<T2> criteria_range, Func<T2, bool> criteria) { var t1andt2 = average_range.Zip(criteria_range, (l, r) => Tuple.Create<T1, T2>(l, r)); return t1andt2.Where(x => criteria(x.Item2)).Average(x => Convert.ToDouble(x.Item1)); } void Main() { var average_range = new List<string>() {"10.1", "10.1", "0", "0"} ; var criteria_range = new List<bool>() {true, true, false, false }; Func<bool, bool> criteria = c => c == true; AVERAGEIF(average_range, criteria_range, criteria).Dump(); } ```
31,429,391
I have a String which i am entering through console. ``` Scanner obj = new Scanner(System.in); System.out.println("Enter a string"); String s = obj.next(); ``` Now i want to delete specific character from that string and that character is also being entered from console. ``` System.out.println("Enter the character which you want to delete from your string"); String s1=obj.next(); ``` Please explain how we can do this??
2015/07/15
[ "https://Stackoverflow.com/questions/31429391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5093387/" ]
Read the character, replace it with nothing. ``` Scanner obj = new Scanner(System.in); System.out.println("Enter a string"); String s = obj.next(); System.out.println("Enter a character to delete"); char ch = (char)System.in.read(); s = s.replace(ch + "", ""); ```
I agree with @Uma Kanth but to make it more correct. You can't modify a string because it is immutable. You are generating a new object and your string variable references to it. But Uma Kanth ist right
31,429,391
I have a String which i am entering through console. ``` Scanner obj = new Scanner(System.in); System.out.println("Enter a string"); String s = obj.next(); ``` Now i want to delete specific character from that string and that character is also being entered from console. ``` System.out.println("Enter the character which you want to delete from your string"); String s1=obj.next(); ``` Please explain how we can do this??
2015/07/15
[ "https://Stackoverflow.com/questions/31429391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5093387/" ]
Read the character, replace it with nothing. ``` Scanner obj = new Scanner(System.in); System.out.println("Enter a string"); String s = obj.next(); System.out.println("Enter a character to delete"); char ch = (char)System.in.read(); s = s.replace(ch + "", ""); ```
So use `s.replaceAll(s1,"")`//to replace all occurrences of given string. use `s.replace(s1,"")`//replace only once ``` s=s.replaceAll(s1,""); System.out.println(s); ```
31,429,391
I have a String which i am entering through console. ``` Scanner obj = new Scanner(System.in); System.out.println("Enter a string"); String s = obj.next(); ``` Now i want to delete specific character from that string and that character is also being entered from console. ``` System.out.println("Enter the character which you want to delete from your string"); String s1=obj.next(); ``` Please explain how we can do this??
2015/07/15
[ "https://Stackoverflow.com/questions/31429391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5093387/" ]
``` Convert that string to char array String s = obj.next(); Char[] arrstr = s.toCharArray() ``` Create a string buffer ``` StringBuffer newstring= new StringBuffer(""); Scanner obj = new Scanner(System.in); System.out.println("Enter a string"); String chartoreplace = obj.next(); ``` iterate over that array and store characters that you dont want to replace in buffer ``` for(Char ch : arrstr){ if(!ch.equals(chartoreplace) { newstring.append(ch); } } ``` at the end return string stored in the buffer as ``` newstring.toString(); ``` Other way to replace ``` String s = obj.next(); System.out.println("Enter a string"); String chartoreplace = obj.next(); s.replace('chartoreplace ',''); ``` this will replace that character
I agree with @Uma Kanth but to make it more correct. You can't modify a string because it is immutable. You are generating a new object and your string variable references to it. But Uma Kanth ist right
31,429,391
I have a String which i am entering through console. ``` Scanner obj = new Scanner(System.in); System.out.println("Enter a string"); String s = obj.next(); ``` Now i want to delete specific character from that string and that character is also being entered from console. ``` System.out.println("Enter the character which you want to delete from your string"); String s1=obj.next(); ``` Please explain how we can do this??
2015/07/15
[ "https://Stackoverflow.com/questions/31429391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5093387/" ]
``` Convert that string to char array String s = obj.next(); Char[] arrstr = s.toCharArray() ``` Create a string buffer ``` StringBuffer newstring= new StringBuffer(""); Scanner obj = new Scanner(System.in); System.out.println("Enter a string"); String chartoreplace = obj.next(); ``` iterate over that array and store characters that you dont want to replace in buffer ``` for(Char ch : arrstr){ if(!ch.equals(chartoreplace) { newstring.append(ch); } } ``` at the end return string stored in the buffer as ``` newstring.toString(); ``` Other way to replace ``` String s = obj.next(); System.out.println("Enter a string"); String chartoreplace = obj.next(); s.replace('chartoreplace ',''); ``` this will replace that character
So use `s.replaceAll(s1,"")`//to replace all occurrences of given string. use `s.replace(s1,"")`//replace only once ``` s=s.replaceAll(s1,""); System.out.println(s); ```